ox-beamer: Remove strange indentation in default header
[org-mode.git] / lisp / org.el
blob4de2beb3dac3c5b70f35b0e7d760d87375767e11
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (org-babel-tangle-file file exported-file "emacs-lisp"))
202 (message "%s %s"
203 (if compile
204 (progn (byte-compile-file exported-file 'load)
205 "Compiled and loaded")
206 (progn (load-file exported-file) "Loaded"))
207 exported-file)))
209 (defcustom org-babel-load-languages '((emacs-lisp . t))
210 "Languages which can be evaluated in Org-mode buffers.
211 This list can be used to load support for any of the languages
212 below, note that each language will depend on a different set of
213 system executables and/or Emacs modes. When a language is
214 \"loaded\", then code blocks in that language can be evaluated
215 with `org-babel-execute-src-block' bound by default to C-c
216 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
217 be set to remove code block evaluation from the C-c C-c
218 keybinding. By default only Emacs Lisp (which has no
219 requirements) is loaded."
220 :group 'org-babel
221 :set 'org-babel-do-load-languages
222 :version "24.1"
223 :type '(alist :tag "Babel Languages"
224 :key-type
225 (choice
226 (const :tag "Awk" awk)
227 (const :tag "C" C)
228 (const :tag "R" R)
229 (const :tag "Asymptote" asymptote)
230 (const :tag "Calc" calc)
231 (const :tag "Clojure" clojure)
232 (const :tag "CSS" css)
233 (const :tag "Ditaa" ditaa)
234 (const :tag "Dot" dot)
235 (const :tag "Emacs Lisp" emacs-lisp)
236 (const :tag "Fortran" fortran)
237 (const :tag "Gnuplot" gnuplot)
238 (const :tag "Haskell" haskell)
239 (const :tag "IO" io)
240 (const :tag "Java" java)
241 (const :tag "Javascript" js)
242 (const :tag "LaTeX" latex)
243 (const :tag "Ledger" ledger)
244 (const :tag "Lilypond" lilypond)
245 (const :tag "Lisp" lisp)
246 (const :tag "Makefile" makefile)
247 (const :tag "Maxima" maxima)
248 (const :tag "Matlab" matlab)
249 (const :tag "Mscgen" mscgen)
250 (const :tag "Ocaml" ocaml)
251 (const :tag "Octave" octave)
252 (const :tag "Org" org)
253 (const :tag "Perl" perl)
254 (const :tag "Pico Lisp" picolisp)
255 (const :tag "PlantUML" plantuml)
256 (const :tag "Python" python)
257 (const :tag "Ruby" ruby)
258 (const :tag "Sass" sass)
259 (const :tag "Scala" scala)
260 (const :tag "Scheme" scheme)
261 (const :tag "Screen" screen)
262 (const :tag "Shell Script" sh)
263 (const :tag "Shen" shen)
264 (const :tag "Sql" sql)
265 (const :tag "Sqlite" sqlite))
266 :value-type (boolean :tag "Activate" :value t)))
268 ;;;; Customization variables
269 (defcustom org-clone-delete-id nil
270 "Remove ID property of clones of a subtree.
271 When non-nil, clones of a subtree don't inherit the ID property.
272 Otherwise they inherit the ID property with a new unique
273 identifier."
274 :type 'boolean
275 :version "24.1"
276 :group 'org-id)
278 ;;; Version
279 (org-check-version)
281 ;;;###autoload
282 (defun org-version (&optional here full message)
283 "Show the org-mode version in the echo area.
284 With prefix argument HERE, insert it at point.
285 When FULL is non-nil, use a verbose version string.
286 When MESSAGE is non-nil, display a message with the version."
287 (interactive "P")
288 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
289 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
290 (load-suffixes (list ".el"))
291 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
292 (org-trash (or
293 (and (fboundp 'org-release) (fboundp 'org-git-version))
294 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
295 (load-suffixes save-load-suffixes)
296 (org-version (org-release))
297 (git-version (org-git-version))
298 (version (format "Org-mode version %s (%s @ %s)"
299 org-version
300 git-version
301 (if org-install-dir
302 (if (string= org-dir org-install-dir)
303 org-install-dir
304 (concat "mixed installation! " org-install-dir " and " org-dir))
305 "org-loaddefs.el can not be found!")))
306 (_version (if full version org-version)))
307 (if (org-called-interactively-p 'interactive)
308 (if here
309 (insert version)
310 (message version))
311 (if message (message _version))
312 _version)))
314 (defconst org-version (org-version))
316 ;;; Compatibility constants
318 ;;; The custom variables
320 (defgroup org nil
321 "Outline-based notes management and organizer."
322 :tag "Org"
323 :group 'outlines
324 :group 'calendar)
326 (defcustom org-mode-hook nil
327 "Mode hook for Org-mode, run after the mode was turned on."
328 :group 'org
329 :type 'hook)
331 (defcustom org-load-hook nil
332 "Hook that is run after org.el has been loaded."
333 :group 'org
334 :type 'hook)
336 (defcustom org-log-buffer-setup-hook nil
337 "Hook that is run after an Org log buffer is created."
338 :group 'org
339 :version "24.1"
340 :type 'hook)
342 (defvar org-modules) ; defined below
343 (defvar org-modules-loaded nil
344 "Have the modules been loaded already?")
346 (defun org-load-modules-maybe (&optional force)
347 "Load all extensions listed in `org-modules'."
348 (when (or force (not org-modules-loaded))
349 (mapc (lambda (ext)
350 (condition-case nil (require ext)
351 (error (message "Problems while trying to load feature `%s'" ext))))
352 org-modules)
353 (setq org-modules-loaded t)))
355 (defun org-set-modules (var value)
356 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
357 (set var value)
358 (when (featurep 'org)
359 (org-load-modules-maybe 'force)))
361 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
362 "Modules that should always be loaded together with org.el.
364 If a description starts with <C>, the file is not part of Emacs
365 and loading it will require that you have downloaded and properly
366 installed the Org mode distribution.
368 You can also use this system to load external packages (i.e. neither Org
369 core modules, nor modules from the CONTRIB directory). Just add symbols
370 to the end of the list. If the package is called org-xyz.el, then you need
371 to add the symbol `xyz', and the package must have a call to:
373 \(provide 'org-xyz)
375 For export specific modules, see also `org-export-backends'."
376 :group 'org
377 :set 'org-set-modules
378 :version "24.4"
379 :package-version '(Org . "8.0")
380 :type
381 '(set :greedy t
382 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
383 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
384 (const :tag " crypt: Encryption of subtrees" org-crypt)
385 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
386 (const :tag " docview: Links to doc-view buffers" org-docview)
387 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
388 (const :tag " habit: Track your consistency with habits" org-habit)
389 (const :tag " id: Global IDs for identifying entries" org-id)
390 (const :tag " info: Links to Info nodes" org-info)
391 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
392 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
393 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
394 (const :tag " mouse: Additional mouse support" org-mouse)
395 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
396 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
397 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
399 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
400 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
401 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
402 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
403 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
404 (const :tag "C collector: Collect properties into tables" org-collector)
405 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
406 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
407 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
408 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
409 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
410 (const :tag "C eval: Include command output as text" org-eval)
411 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
412 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
413 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
414 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
415 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
416 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
417 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
418 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
419 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
420 (const :tag "C mac-message: Links to messages in Apple Mail" org-mac-message)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export-registered-backends) ; From ox.el
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (defcustom org-export-backends '(ascii html icalendar latex)
442 "List of export back-ends that should be always available.
444 If a description starts with <C>, the file is not part of Emacs
445 and loading it will require that you have downloaded and properly
446 installed the Org mode distribution.
448 Unlike to `org-modules', libraries in this list will not be
449 loaded along with Org, but only once the export framework is
450 needed.
452 This variable needs to be set before org.el is loaded. If you
453 need to make a change while Emacs is running, use the customize
454 interface or run the following code, where VALUE stands for the
455 new value of the variable, after updating it:
457 \(progn
458 \(setq org-export-registered-backends
459 \(org-remove-if-not
460 \(lambda (backend)
461 \(or (memq backend val)
462 \(catch 'parentp
463 \(mapc
464 \(lambda (b)
465 \(and (org-export-derived-backend-p b (car backend))
466 \(throw 'parentp t)))
467 val)
468 nil)))
469 org-export-registered-backends))
470 \(let ((new-list (mapcar 'car org-export-registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default var new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export-registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (or (memq backend val)
495 (catch 'parentp
496 (mapc
497 (lambda (b)
498 (and (org-export-derived-backend-p b (car backend))
499 (throw 'parentp t)))
500 val)
501 nil)))
502 org-export-registered-backends))
503 ;; Now build NEW-LIST of both new back-ends and required
504 ;; parents.
505 (let ((new-list (mapcar 'car org-export-registered-backends)))
506 (dolist (backend val)
507 (cond
508 ((not (load (format "ox-%s" backend) t t))
509 (message "Problems while trying to load export back-end `%s'"
510 backend))
511 ((not (memq backend new-list)) (push backend new-list))))
512 ;; Set VAR to that list with fixed dependencies.
513 (set-default var new-list))))
514 :type '(set :greedy t
515 (const :tag " ascii Export buffer to ASCII format" ascii)
516 (const :tag " beamer Export buffer to Beamer presentation" beamer)
517 (const :tag " html Export buffer to HTML format" html)
518 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
519 (const :tag " latex Export buffer to LaTeX format" latex)
520 (const :tag " man Export buffer to MAN format" man)
521 (const :tag " md Export buffer to Markdown format" md)
522 (const :tag " odt Export buffer to ODT format" odt)
523 (const :tag " org Export buffer to Org format" org)
524 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
525 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
526 (const :tag "C deck Export buffer to deck.js presentations" deck)
527 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
528 (const :tag "C groff Export buffer to Groff format" groff)
529 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
530 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
531 (const :tag "C s5 Export buffer to s5 presentations" s5)
532 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
534 (eval-after-load 'ox
535 '(mapc
536 (lambda (backend)
537 (condition-case nil (require (intern (format "ox-%s" backend)))
538 (error (message "Problems while trying to load export back-end `%s'"
539 backend))))
540 org-export-backends))
542 (defcustom org-support-shift-select nil
543 "Non-nil means make shift-cursor commands select text when possible.
545 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
546 start selecting a region, or enlarge regions started in this way.
547 In Org-mode, in special contexts, these same keys are used for
548 other purposes, important enough to compete with shift selection.
549 Org tries to balance these needs by supporting `shift-select-mode'
550 outside these special contexts, under control of this variable.
552 The default of this variable is nil, to avoid confusing behavior. Shifted
553 cursor keys will then execute Org commands in the following contexts:
554 - on a headline, changing TODO state (left/right) and priority (up/down)
555 - on a time stamp, changing the time
556 - in a plain list item, changing the bullet type
557 - in a property definition line, switching between allowed values
558 - in the BEGIN line of a clock table (changing the time block).
559 Outside these contexts, the commands will throw an error.
561 When this variable is t and the cursor is not in a special
562 context, Org-mode will support shift-selection for making and
563 enlarging regions. To make this more effective, the bullet
564 cycling will no longer happen anywhere in an item line, but only
565 if the cursor is exactly on the bullet.
567 If you set this variable to the symbol `always', then the keys
568 will not be special in headlines, property lines, and item lines,
569 to make shift selection work there as well. If this is what you
570 want, you can use the following alternative commands: `C-c C-t'
571 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
572 can be used to switch TODO sets, `C-c -' to cycle item bullet
573 types, and properties can be edited by hand or in column view.
575 However, when the cursor is on a timestamp, shift-cursor commands
576 will still edit the time stamp - this is just too good to give up.
578 XEmacs user should have this variable set to nil, because
579 `shift-select-mode' is in Emacs 23 or later only."
580 :group 'org
581 :type '(choice
582 (const :tag "Never" nil)
583 (const :tag "When outside special context" t)
584 (const :tag "Everywhere except timestamps" always)))
586 (defcustom org-loop-over-headlines-in-active-region nil
587 "Shall some commands act upon headlines in the active region?
589 When set to `t', some commands will be performed in all headlines
590 within the active region.
592 When set to `start-level', some commands will be performed in all
593 headlines within the active region, provided that these headlines
594 are of the same level than the first one.
596 When set to a string, those commands will be performed on the
597 matching headlines within the active region. Such string must be
598 a tags/property/todo match as it is used in the agenda tags view.
600 The list of commands is: `org-schedule', `org-deadline',
601 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
602 `org-archive-to-archive-sibling'. The archiving commands skip
603 already archived entries."
604 :type '(choice (const :tag "Don't loop" nil)
605 (const :tag "All headlines in active region" t)
606 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
607 (string :tag "Tags/Property/Todo matcher"))
608 :version "24.1"
609 :group 'org-todo
610 :group 'org-archive)
612 (defgroup org-startup nil
613 "Options concerning startup of Org-mode."
614 :tag "Org Startup"
615 :group 'org)
617 (defcustom org-startup-folded t
618 "Non-nil means entering Org-mode will switch to OVERVIEW.
619 This can also be configured on a per-file basis by adding one of
620 the following lines anywhere in the buffer:
622 #+STARTUP: fold (or `overview', this is equivalent)
623 #+STARTUP: nofold (or `showall', this is equivalent)
624 #+STARTUP: content
625 #+STARTUP: showeverything
627 By default, this option is ignored when Org opens agenda files
628 for the first time. If you want the agenda to honor the startup
629 option, set `org-agenda-inhibit-startup' to nil."
630 :group 'org-startup
631 :type '(choice
632 (const :tag "nofold: show all" nil)
633 (const :tag "fold: overview" t)
634 (const :tag "content: all headlines" content)
635 (const :tag "show everything, even drawers" showeverything)))
637 (defcustom org-startup-truncated t
638 "Non-nil means entering Org-mode will set `truncate-lines'.
639 This is useful since some lines containing links can be very long and
640 uninteresting. Also tables look terrible when wrapped."
641 :group 'org-startup
642 :type 'boolean)
644 (defcustom org-startup-indented nil
645 "Non-nil means turn on `org-indent-mode' on startup.
646 This can also be configured on a per-file basis by adding one of
647 the following lines anywhere in the buffer:
649 #+STARTUP: indent
650 #+STARTUP: noindent"
651 :group 'org-structure
652 :type '(choice
653 (const :tag "Not" nil)
654 (const :tag "Globally (slow on startup in large files)" t)))
656 (defcustom org-use-sub-superscripts t
657 "Non-nil means interpret \"_\" and \"^\" for display.
658 When this option is turned on, you can use TeX-like syntax for sub- and
659 superscripts. Several characters after \"_\" or \"^\" will be
660 considered as a single item - so grouping with {} is normally not
661 needed. For example, the following things will be parsed as single
662 sub- or superscripts.
664 10^24 or 10^tau several digits will be considered 1 item.
665 10^-12 or 10^-tau a leading sign with digits or a word
666 x^2-y^3 will be read as x^2 - y^3, because items are
667 terminated by almost any nonword/nondigit char.
668 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
670 Still, ambiguity is possible - so when in doubt use {} to enclose
671 the sub/superscript. If you set this variable to the symbol
672 `{}', the braces are *required* in order to trigger
673 interpretations as sub/superscript. This can be helpful in
674 documents that need \"_\" frequently in plain text."
675 :group 'org-startup
676 :version "24.1"
677 :type '(choice
678 (const :tag "Always interpret" t)
679 (const :tag "Only with braces" {})
680 (const :tag "Never interpret" nil)))
682 (defcustom org-startup-with-beamer-mode nil
683 "Non-nil means turn on `org-beamer-mode' on startup.
684 This can also be configured on a per-file basis by adding one of
685 the following lines anywhere in the buffer:
687 #+STARTUP: beamer"
688 :group 'org-startup
689 :version "24.1"
690 :type 'boolean)
692 (defcustom org-startup-align-all-tables nil
693 "Non-nil means align all tables when visiting a file.
694 This is useful when the column width in tables is forced with <N> cookies
695 in table fields. Such tables will look correct only after the first re-align.
696 This can also be configured on a per-file basis by adding one of
697 the following lines anywhere in the buffer:
698 #+STARTUP: align
699 #+STARTUP: noalign"
700 :group 'org-startup
701 :type 'boolean)
703 (defcustom org-startup-with-inline-images nil
704 "Non-nil means show inline images when loading a new Org file.
705 This can also be configured on a per-file basis by adding one of
706 the following lines anywhere in the buffer:
707 #+STARTUP: inlineimages
708 #+STARTUP: noinlineimages"
709 :group 'org-startup
710 :version "24.1"
711 :type 'boolean)
713 (defcustom org-startup-with-latex-preview nil
714 "Non-nil means preview LaTeX fragments when loading a new Org file.
716 This can also be configured on a per-file basis by adding one of
717 the followinglines anywhere in the buffer:
718 #+STARTUP: latexpreview
719 #+STARTUP: nolatexpreview"
720 :group 'org-startup
721 :version "24.4"
722 :package-version '(Org . "8.0")
723 :type 'boolean)
725 (defcustom org-insert-mode-line-in-empty-file nil
726 "Non-nil means insert the first line setting Org-mode in empty files.
727 When the function `org-mode' is called interactively in an empty file, this
728 normally means that the file name does not automatically trigger Org-mode.
729 To ensure that the file will always be in Org-mode in the future, a
730 line enforcing Org-mode will be inserted into the buffer, if this option
731 has been set."
732 :group 'org-startup
733 :type 'boolean)
735 (defcustom org-replace-disputed-keys nil
736 "Non-nil means use alternative key bindings for some keys.
737 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
738 These keys are also used by other packages like shift-selection-mode'
739 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
740 If you want to use Org-mode together with one of these other modes,
741 or more generally if you would like to move some Org-mode commands to
742 other keys, set this variable and configure the keys with the variable
743 `org-disputed-keys'.
745 This option is only relevant at load-time of Org-mode, and must be set
746 *before* org.el is loaded. Changing it requires a restart of Emacs to
747 become effective."
748 :group 'org-startup
749 :type 'boolean)
751 (defcustom org-use-extra-keys nil
752 "Non-nil means use extra key sequence definitions for certain commands.
753 This happens automatically if you run XEmacs or if `window-system'
754 is nil. This variable lets you do the same manually. You must
755 set it before loading org.
757 Example: on Carbon Emacs 22 running graphically, with an external
758 keyboard on a Powerbook, the default way of setting M-left might
759 not work for either Alt or ESC. Setting this variable will make
760 it work for ESC."
761 :group 'org-startup
762 :type 'boolean)
764 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
766 (defcustom org-disputed-keys
767 '(([(shift up)] . [(meta p)])
768 ([(shift down)] . [(meta n)])
769 ([(shift left)] . [(meta -)])
770 ([(shift right)] . [(meta +)])
771 ([(control shift right)] . [(meta shift +)])
772 ([(control shift left)] . [(meta shift -)]))
773 "Keys for which Org-mode and other modes compete.
774 This is an alist, cars are the default keys, second element specifies
775 the alternative to use when `org-replace-disputed-keys' is t.
777 Keys can be specified in any syntax supported by `define-key'.
778 The value of this option takes effect only at Org-mode's startup,
779 therefore you'll have to restart Emacs to apply it after changing."
780 :group 'org-startup
781 :type 'alist)
783 (defun org-key (key)
784 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
785 Or return the original if not disputed.
786 Also apply the translations defined in `org-xemacs-key-equivalents'."
787 (when org-replace-disputed-keys
788 (let* ((nkey (key-description key))
789 (x (org-find-if (lambda (x)
790 (equal (key-description (car x)) nkey))
791 org-disputed-keys)))
792 (setq key (if x (cdr x) key))))
793 (when (featurep 'xemacs)
794 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
795 key)
797 (defun org-find-if (predicate seq)
798 (catch 'exit
799 (while seq
800 (if (funcall predicate (car seq))
801 (throw 'exit (car seq))
802 (pop seq)))))
804 (defun org-defkey (keymap key def)
805 "Define a key, possibly translated, as returned by `org-key'."
806 (define-key keymap (org-key key) def))
808 (defcustom org-ellipsis nil
809 "The ellipsis to use in the Org-mode outline.
810 When nil, just use the standard three dots. When a string, use that instead,
811 When a face, use the standard 3 dots, but with the specified face.
812 The change affects only Org-mode (which will then use its own display table).
813 Changing this requires executing `M-x org-mode' in a buffer to become
814 effective."
815 :group 'org-startup
816 :type '(choice (const :tag "Default" nil)
817 (face :tag "Face" :value org-warning)
818 (string :tag "String" :value "...#")))
820 (defvar org-display-table nil
821 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
823 (defgroup org-keywords nil
824 "Keywords in Org-mode."
825 :tag "Org Keywords"
826 :group 'org)
828 (defcustom org-deadline-string "DEADLINE:"
829 "String to mark deadline entries.
830 A deadline is this string, followed by a time stamp. Should be a word,
831 terminated by a colon. You can insert a schedule keyword and
832 a timestamp with \\[org-deadline].
833 Changes become only effective after restarting Emacs."
834 :group 'org-keywords
835 :type 'string)
837 (defcustom org-scheduled-string "SCHEDULED:"
838 "String to mark scheduled TODO entries.
839 A schedule is this string, followed by a time stamp. Should be a word,
840 terminated by a colon. You can insert a schedule keyword and
841 a timestamp with \\[org-schedule].
842 Changes become only effective after restarting Emacs."
843 :group 'org-keywords
844 :type 'string)
846 (defcustom org-closed-string "CLOSED:"
847 "String used as the prefix for timestamps logging closing a TODO entry."
848 :group 'org-keywords
849 :type 'string)
851 (defcustom org-clock-string "CLOCK:"
852 "String used as prefix for timestamps clocking work hours on an item."
853 :group 'org-keywords
854 :type 'string)
856 (defcustom org-closed-keep-when-no-todo nil
857 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
858 :group 'org-todo
859 :group 'org-keywords
860 :version "24.4"
861 :package-version '(Org . "8.0")
862 :type 'boolean)
864 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
865 org-scheduled-string "\\|"
866 org-deadline-string "\\|"
867 org-closed-string "\\|"
868 org-clock-string "\\)")
869 "Matches a line with planning or clock info.")
871 (defcustom org-comment-string "COMMENT"
872 "Entries starting with this keyword will never be exported.
873 An entry can be toggled between COMMENT and normal with
874 \\[org-toggle-comment].
875 Changes become only effective after restarting Emacs."
876 :group 'org-keywords
877 :type 'string)
879 (defcustom org-quote-string "QUOTE"
880 "Entries starting with this keyword will be exported in fixed-width font.
881 Quoting applies only to the text in the entry following the headline, and does
882 not extend beyond the next headline, even if that is lower level.
883 An entry can be toggled between QUOTE and normal with
884 \\[org-toggle-fixed-width-section]."
885 :group 'org-keywords
886 :type 'string)
888 (defconst org-repeat-re
889 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
890 "Regular expression for specifying repeated events.
891 After a match, group 1 contains the repeat expression.")
893 (defgroup org-structure nil
894 "Options concerning the general structure of Org-mode files."
895 :tag "Org Structure"
896 :group 'org)
898 (defgroup org-reveal-location nil
899 "Options about how to make context of a location visible."
900 :tag "Org Reveal Location"
901 :group 'org-structure)
903 (defconst org-context-choice
904 '(choice
905 (const :tag "Always" t)
906 (const :tag "Never" nil)
907 (repeat :greedy t :tag "Individual contexts"
908 (cons
909 (choice :tag "Context"
910 (const agenda)
911 (const org-goto)
912 (const occur-tree)
913 (const tags-tree)
914 (const link-search)
915 (const mark-goto)
916 (const bookmark-jump)
917 (const isearch)
918 (const default))
919 (boolean))))
920 "Contexts for the reveal options.")
922 (defcustom org-show-hierarchy-above '((default . t))
923 "Non-nil means show full hierarchy when revealing a location.
924 Org-mode often shows locations in an org-mode file which might have
925 been invisible before. When this is set, the hierarchy of headings
926 above the exposed location is shown.
927 Turning this off for example for sparse trees makes them very compact.
928 Instead of t, this can also be an alist specifying this option for different
929 contexts. Valid contexts are
930 agenda when exposing an entry from the agenda
931 org-goto when using the command `org-goto' on key C-c C-j
932 occur-tree when using the command `org-occur' on key C-c /
933 tags-tree when constructing a sparse tree based on tags matches
934 link-search when exposing search matches associated with a link
935 mark-goto when exposing the jump goal of a mark
936 bookmark-jump when exposing a bookmark location
937 isearch when exiting from an incremental search
938 default default for all contexts not set explicitly"
939 :group 'org-reveal-location
940 :type org-context-choice)
942 (defcustom org-show-following-heading '((default . nil))
943 "Non-nil means show following heading when revealing a location.
944 Org-mode often shows locations in an org-mode file which might have
945 been invisible before. When this is set, the heading following the
946 match is shown.
947 Turning this off for example for sparse trees makes them very compact,
948 but makes it harder to edit the location of the match. In such a case,
949 use the command \\[org-reveal] to show more context.
950 Instead of t, this can also be an alist specifying this option for different
951 contexts. See `org-show-hierarchy-above' for valid contexts."
952 :group 'org-reveal-location
953 :type org-context-choice)
955 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
956 "Non-nil means show all sibling heading when revealing a location.
957 Org-mode often shows locations in an org-mode file which might have
958 been invisible before. When this is set, the sibling of the current entry
959 heading are all made visible. If `org-show-hierarchy-above' is t,
960 the same happens on each level of the hierarchy above the current entry.
962 By default this is on for the isearch context, off for all other contexts.
963 Turning this off for example for sparse trees makes them very compact,
964 but makes it harder to edit the location of the match. In such a case,
965 use the command \\[org-reveal] to show more context.
966 Instead of t, this can also be an alist specifying this option for different
967 contexts. See `org-show-hierarchy-above' for valid contexts."
968 :group 'org-reveal-location
969 :type org-context-choice
970 :version "24.4"
971 :package-version '(Org . "8.0"))
973 (defcustom org-show-entry-below '((default . nil))
974 "Non-nil means show the entry below a headline when revealing a location.
975 Org-mode often shows locations in an org-mode file which might have
976 been invisible before. When this is set, the text below the headline that is
977 exposed is also shown.
979 By default this is off for all contexts.
980 Instead of t, this can also be an alist specifying this option for different
981 contexts. See `org-show-hierarchy-above' for valid contexts."
982 :group 'org-reveal-location
983 :type org-context-choice)
985 (defcustom org-indirect-buffer-display 'other-window
986 "How should indirect tree buffers be displayed?
987 This applies to indirect buffers created with the commands
988 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
989 Valid values are:
990 current-window Display in the current window
991 other-window Just display in another window.
992 dedicated-frame Create one new frame, and re-use it each time.
993 new-frame Make a new frame each time. Note that in this case
994 previously-made indirect buffers are kept, and you need to
995 kill these buffers yourself."
996 :group 'org-structure
997 :group 'org-agenda-windows
998 :type '(choice
999 (const :tag "In current window" current-window)
1000 (const :tag "In current frame, other window" other-window)
1001 (const :tag "Each time a new frame" new-frame)
1002 (const :tag "One dedicated frame" dedicated-frame)))
1004 (defcustom org-use-speed-commands nil
1005 "Non-nil means activate single letter commands at beginning of a headline.
1006 This may also be a function to test for appropriate locations where speed
1007 commands should be active."
1008 :group 'org-structure
1009 :type '(choice
1010 (const :tag "Never" nil)
1011 (const :tag "At beginning of headline stars" t)
1012 (function)))
1014 (defcustom org-speed-commands-user nil
1015 "Alist of additional speed commands.
1016 This list will be checked before `org-speed-commands-default'
1017 when the variable `org-use-speed-commands' is non-nil
1018 and when the cursor is at the beginning of a headline.
1019 The car if each entry is a string with a single letter, which must
1020 be assigned to `self-insert-command' in the global map.
1021 The cdr is either a command to be called interactively, a function
1022 to be called, or a form to be evaluated.
1023 An entry that is just a list with a single string will be interpreted
1024 as a descriptive headline that will be added when listing the speed
1025 commands in the Help buffer using the `?' speed command."
1026 :group 'org-structure
1027 :type '(repeat :value ("k" . ignore)
1028 (choice :value ("k" . ignore)
1029 (list :tag "Descriptive Headline" (string :tag "Headline"))
1030 (cons :tag "Letter and Command"
1031 (string :tag "Command letter")
1032 (choice
1033 (function)
1034 (sexp))))))
1036 (defgroup org-cycle nil
1037 "Options concerning visibility cycling in Org-mode."
1038 :tag "Org Cycle"
1039 :group 'org-structure)
1041 (defcustom org-cycle-skip-children-state-if-no-children t
1042 "Non-nil means skip CHILDREN state in entries that don't have any."
1043 :group 'org-cycle
1044 :type 'boolean)
1046 (defcustom org-cycle-max-level nil
1047 "Maximum level which should still be subject to visibility cycling.
1048 Levels higher than this will, for cycling, be treated as text, not a headline.
1049 When `org-odd-levels-only' is set, a value of N in this variable actually
1050 means 2N-1 stars as the limiting headline.
1051 When nil, cycle all levels.
1052 Note that the limiting level of cycling is also influenced by
1053 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1054 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1055 than its value."
1056 :group 'org-cycle
1057 :type '(choice
1058 (const :tag "No limit" nil)
1059 (integer :tag "Maximum level")))
1061 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1062 "Names of drawers. Drawers are not opened by cycling on the headline above.
1063 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1064 this:
1065 :DRAWERNAME:
1066 .....
1067 :END:
1068 The drawer \"PROPERTIES\" is special for capturing properties through
1069 the property API.
1071 Drawers can be defined on the per-file basis with a line like:
1073 #+DRAWERS: HIDDEN STATE PROPERTIES"
1074 :group 'org-structure
1075 :group 'org-cycle
1076 :type '(repeat (string :tag "Drawer Name")))
1078 (defcustom org-hide-block-startup nil
1079 "Non-nil means entering Org-mode will fold all blocks.
1080 This can also be set in on a per-file basis with
1082 #+STARTUP: hideblocks
1083 #+STARTUP: showblocks"
1084 :group 'org-startup
1085 :group 'org-cycle
1086 :type 'boolean)
1088 (defcustom org-cycle-global-at-bob nil
1089 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1090 This makes it possible to do global cycling without having to use S-TAB or
1091 \\[universal-argument] TAB. For this special case to work, the first line
1092 of the buffer must not be a headline -- it may be empty or some other text.
1093 When used in this way, `org-cycle-hook' is disabled temporarily to make
1094 sure the cursor stays at the beginning of the buffer. When this option is
1095 nil, don't do anything special at the beginning of the buffer."
1096 :group 'org-cycle
1097 :type 'boolean)
1099 (defcustom org-cycle-level-after-item/entry-creation t
1100 "Non-nil means cycle entry level or item indentation in new empty entries.
1102 When the cursor is at the end of an empty headline, i.e., with only stars
1103 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1104 and then all possible ancestor states, before returning to the original state.
1105 This makes data entry extremely fast: M-RET to create a new headline,
1106 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1108 When the cursor is at the end of an empty plain list item, one TAB will
1109 make it a subitem, two or more tabs will back up to make this an item
1110 higher up in the item hierarchy."
1111 :group 'org-cycle
1112 :type 'boolean)
1114 (defcustom org-cycle-emulate-tab t
1115 "Where should `org-cycle' emulate TAB.
1116 nil Never
1117 white Only in completely white lines
1118 whitestart Only at the beginning of lines, before the first non-white char
1119 t Everywhere except in headlines
1120 exc-hl-bol Everywhere except at the start of a headline
1121 If TAB is used in a place where it does not emulate TAB, the current subtree
1122 visibility is cycled."
1123 :group 'org-cycle
1124 :type '(choice (const :tag "Never" nil)
1125 (const :tag "Only in completely white lines" white)
1126 (const :tag "Before first char in a line" whitestart)
1127 (const :tag "Everywhere except in headlines" t)
1128 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1130 (defcustom org-cycle-separator-lines 2
1131 "Number of empty lines needed to keep an empty line between collapsed trees.
1132 If you leave an empty line between the end of a subtree and the following
1133 headline, this empty line is hidden when the subtree is folded.
1134 Org-mode will leave (exactly) one empty line visible if the number of
1135 empty lines is equal or larger to the number given in this variable.
1136 So the default 2 means at least 2 empty lines after the end of a subtree
1137 are needed to produce free space between a collapsed subtree and the
1138 following headline.
1140 If the number is negative, and the number of empty lines is at least -N,
1141 all empty lines are shown.
1143 Special case: when 0, never leave empty lines in collapsed view."
1144 :group 'org-cycle
1145 :type 'integer)
1146 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1148 (defcustom org-pre-cycle-hook nil
1149 "Hook that is run before visibility cycling is happening.
1150 The function(s) in this hook must accept a single argument which indicates
1151 the new state that will be set right after running this hook. The
1152 argument is a symbol. Before a global state change, it can have the values
1153 `overview', `content', or `all'. Before a local state change, it can have
1154 the values `folded', `children', or `subtree'."
1155 :group 'org-cycle
1156 :type 'hook)
1158 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1159 org-cycle-hide-drawers
1160 org-cycle-hide-inline-tasks
1161 org-cycle-show-empty-lines
1162 org-optimize-window-after-visibility-change)
1163 "Hook that is run after `org-cycle' has changed the buffer visibility.
1164 The function(s) in this hook must accept a single argument which indicates
1165 the new state that was set by the most recent `org-cycle' command. The
1166 argument is a symbol. After a global state change, it can have the values
1167 `overview', `contents', or `all'. After a local state change, it can have
1168 the values `folded', `children', or `subtree'."
1169 :group 'org-cycle
1170 :type 'hook)
1172 (defgroup org-edit-structure nil
1173 "Options concerning structure editing in Org-mode."
1174 :tag "Org Edit Structure"
1175 :group 'org-structure)
1177 (defcustom org-odd-levels-only nil
1178 "Non-nil means skip even levels and only use odd levels for the outline.
1179 This has the effect that two stars are being added/taken away in
1180 promotion/demotion commands. It also influences how levels are
1181 handled by the exporters.
1182 Changing it requires restart of `font-lock-mode' to become effective
1183 for fontification also in regions already fontified.
1184 You may also set this on a per-file basis by adding one of the following
1185 lines to the buffer:
1187 #+STARTUP: odd
1188 #+STARTUP: oddeven"
1189 :group 'org-edit-structure
1190 :group 'org-appearance
1191 :type 'boolean)
1193 (defcustom org-adapt-indentation t
1194 "Non-nil means adapt indentation to outline node level.
1196 When this variable is set, Org assumes that you write outlines by
1197 indenting text in each node to align with the headline (after the stars).
1198 The following issues are influenced by this variable:
1200 - When this is set and the *entire* text in an entry is indented, the
1201 indentation is increased by one space in a demotion command, and
1202 decreased by one in a promotion command. If any line in the entry
1203 body starts with text at column 0, indentation is not changed at all.
1205 - Property drawers and planning information is inserted indented when
1206 this variable s set. When nil, they will not be indented.
1208 - TAB indents a line relative to context. The lines below a headline
1209 will be indented when this variable is set.
1211 Note that this is all about true indentation, by adding and removing
1212 space characters. See also `org-indent.el' which does level-dependent
1213 indentation in a virtual way, i.e. at display time in Emacs."
1214 :group 'org-edit-structure
1215 :type 'boolean)
1217 (defcustom org-special-ctrl-a/e nil
1218 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1220 When t, `C-a' will bring back the cursor to the beginning of the
1221 headline text, i.e. after the stars and after a possible TODO
1222 keyword. In an item, this will be the position after bullet and
1223 check-box, if any. When the cursor is already at that position,
1224 another `C-a' will bring it to the beginning of the line.
1226 `C-e' will jump to the end of the headline, ignoring the presence
1227 of tags in the headline. A second `C-e' will then jump to the
1228 true end of the line, after any tags. This also means that, when
1229 this variable is non-nil, `C-e' also will never jump beyond the
1230 end of the heading of a folded section, i.e. not after the
1231 ellipses.
1233 When set to the symbol `reversed', the first `C-a' or `C-e' works
1234 normally, going to the true line boundary first. Only a directly
1235 following, identical keypress will bring the cursor to the
1236 special positions.
1238 This may also be a cons cell where the behavior for `C-a' and
1239 `C-e' is set separately."
1240 :group 'org-edit-structure
1241 :type '(choice
1242 (const :tag "off" nil)
1243 (const :tag "on: after stars/bullet and before tags first" t)
1244 (const :tag "reversed: true line boundary first" reversed)
1245 (cons :tag "Set C-a and C-e separately"
1246 (choice :tag "Special C-a"
1247 (const :tag "off" nil)
1248 (const :tag "on: after stars/bullet first" t)
1249 (const :tag "reversed: before stars/bullet first" reversed))
1250 (choice :tag "Special C-e"
1251 (const :tag "off" nil)
1252 (const :tag "on: before tags first" t)
1253 (const :tag "reversed: after tags first" reversed)))))
1254 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1256 (defcustom org-special-ctrl-k nil
1257 "Non-nil means `C-k' will behave specially in headlines.
1258 When nil, `C-k' will call the default `kill-line' command.
1259 When t, the following will happen while the cursor is in the headline:
1261 - When the cursor is at the beginning of a headline, kill the entire
1262 line and possible the folded subtree below the line.
1263 - When in the middle of the headline text, kill the headline up to the tags.
1264 - When after the headline text, kill the tags."
1265 :group 'org-edit-structure
1266 :type 'boolean)
1268 (defcustom org-ctrl-k-protect-subtree nil
1269 "Non-nil means, do not delete a hidden subtree with C-k.
1270 When set to the symbol `error', simply throw an error when C-k is
1271 used to kill (part-of) a headline that has hidden text behind it.
1272 Any other non-nil value will result in a query to the user, if it is
1273 OK to kill that hidden subtree. When nil, kill without remorse."
1274 :group 'org-edit-structure
1275 :version "24.1"
1276 :type '(choice
1277 (const :tag "Do not protect hidden subtrees" nil)
1278 (const :tag "Protect hidden subtrees with a security query" t)
1279 (const :tag "Never kill a hidden subtree with C-k" error)))
1281 (defcustom org-catch-invisible-edits nil
1282 "Check if in invisible region before inserting or deleting a character.
1283 Valid values are:
1285 nil Do not check, so just do invisible edits.
1286 error Throw an error and do nothing.
1287 show Make point visible, and do the requested edit.
1288 show-and-error Make point visible, then throw an error and abort the edit.
1289 smart Make point visible, and do insertion/deletion if it is
1290 adjacent to visible text and the change feels predictable.
1291 Never delete a previously invisible character or add in the
1292 middle or right after an invisible region. Basically, this
1293 allows insertion and backward-delete right before ellipses.
1294 FIXME: maybe in this case we should not even show?"
1295 :group 'org-edit-structure
1296 :version "24.1"
1297 :type '(choice
1298 (const :tag "Do not check" nil)
1299 (const :tag "Throw error when trying to edit" error)
1300 (const :tag "Unhide, but do not do the edit" show-and-error)
1301 (const :tag "Show invisible part and do the edit" show)
1302 (const :tag "Be smart and do the right thing" smart)))
1304 (defcustom org-yank-folded-subtrees t
1305 "Non-nil means when yanking subtrees, fold them.
1306 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1307 it starts with a heading and all other headings in it are either children
1308 or siblings, then fold all the subtrees. However, do this only if no
1309 text after the yank would be swallowed into a folded tree by this action."
1310 :group 'org-edit-structure
1311 :type 'boolean)
1313 (defcustom org-yank-adjusted-subtrees nil
1314 "Non-nil means when yanking subtrees, adjust the level.
1315 With this setting, `org-paste-subtree' is used to insert the subtree, see
1316 this function for details."
1317 :group 'org-edit-structure
1318 :type 'boolean)
1320 (defcustom org-M-RET-may-split-line '((default . t))
1321 "Non-nil means M-RET will split the line at the cursor position.
1322 When nil, it will go to the end of the line before making a
1323 new line.
1324 You may also set this option in a different way for different
1325 contexts. Valid contexts are:
1327 headline when creating a new headline
1328 item when creating a new item
1329 table in a table field
1330 default the value to be used for all contexts not explicitly
1331 customized"
1332 :group 'org-structure
1333 :group 'org-table
1334 :type '(choice
1335 (const :tag "Always" t)
1336 (const :tag "Never" nil)
1337 (repeat :greedy t :tag "Individual contexts"
1338 (cons
1339 (choice :tag "Context"
1340 (const headline)
1341 (const item)
1342 (const table)
1343 (const default))
1344 (boolean)))))
1347 (defcustom org-insert-heading-respect-content nil
1348 "Non-nil means insert new headings after the current subtree.
1349 When nil, the new heading is created directly after the current line.
1350 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1351 this variable on for the duration of the command."
1352 :group 'org-structure
1353 :type 'boolean)
1355 (defcustom org-blank-before-new-entry '((heading . auto)
1356 (plain-list-item . auto))
1357 "Should `org-insert-heading' leave a blank line before new heading/item?
1358 The value is an alist, with `heading' and `plain-list-item' as CAR,
1359 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1360 which case Org will look at the surrounding headings/items and try to
1361 make an intelligent decision whether to insert a blank line or not.
1363 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1364 the setting here is ignored and no empty line is inserted to avoid breaking
1365 the list structure."
1366 :group 'org-edit-structure
1367 :type '(list
1368 (cons (const heading)
1369 (choice (const :tag "Never" nil)
1370 (const :tag "Always" t)
1371 (const :tag "Auto" auto)))
1372 (cons (const plain-list-item)
1373 (choice (const :tag "Never" nil)
1374 (const :tag "Always" t)
1375 (const :tag "Auto" auto)))))
1377 (defcustom org-insert-heading-hook nil
1378 "Hook being run after inserting a new heading."
1379 :group 'org-edit-structure
1380 :type 'hook)
1382 (defcustom org-enable-fixed-width-editor t
1383 "Non-nil means lines starting with \":\" are treated as fixed-width.
1384 This currently only means they are never auto-wrapped.
1385 When nil, such lines will be treated like ordinary lines.
1386 See also the QUOTE keyword."
1387 :group 'org-edit-structure
1388 :type 'boolean)
1390 (defcustom org-goto-auto-isearch t
1391 "Non-nil means typing characters in `org-goto' starts incremental search.
1392 When nil, you can use these keybindings to navigate the buffer:
1394 q Quit the org-goto interface
1395 n Go to the next visible heading
1396 p Go to the previous visible heading
1397 f Go one heading forward on same level
1398 b Go one heading backward on same level
1399 u Go one heading up"
1400 :group 'org-edit-structure
1401 :type 'boolean)
1403 (defgroup org-sparse-trees nil
1404 "Options concerning sparse trees in Org-mode."
1405 :tag "Org Sparse Trees"
1406 :group 'org-structure)
1408 (defcustom org-highlight-sparse-tree-matches t
1409 "Non-nil means highlight all matches that define a sparse tree.
1410 The highlights will automatically disappear the next time the buffer is
1411 changed by an edit command."
1412 :group 'org-sparse-trees
1413 :type 'boolean)
1415 (defcustom org-remove-highlights-with-change t
1416 "Non-nil means any change to the buffer will remove temporary highlights.
1417 Such highlights are created by `org-occur' and `org-clock-display'.
1418 When nil, `C-c C-c needs to be used to get rid of the highlights.
1419 The highlights created by `org-preview-latex-fragment' always need
1420 `C-c C-c' to be removed."
1421 :group 'org-sparse-trees
1422 :group 'org-time
1423 :type 'boolean)
1426 (defcustom org-occur-hook '(org-first-headline-recenter)
1427 "Hook that is run after `org-occur' has constructed a sparse tree.
1428 This can be used to recenter the window to show as much of the structure
1429 as possible."
1430 :group 'org-sparse-trees
1431 :type 'hook)
1433 (defgroup org-imenu-and-speedbar nil
1434 "Options concerning imenu and speedbar in Org-mode."
1435 :tag "Org Imenu and Speedbar"
1436 :group 'org-structure)
1438 (defcustom org-imenu-depth 2
1439 "The maximum level for Imenu access to Org-mode headlines.
1440 This also applied for speedbar access."
1441 :group 'org-imenu-and-speedbar
1442 :type 'integer)
1444 (defgroup org-table nil
1445 "Options concerning tables in Org-mode."
1446 :tag "Org Table"
1447 :group 'org)
1449 (defcustom org-enable-table-editor 'optimized
1450 "Non-nil means lines starting with \"|\" are handled by the table editor.
1451 When nil, such lines will be treated like ordinary lines.
1453 When equal to the symbol `optimized', the table editor will be optimized to
1454 do the following:
1455 - Automatic overwrite mode in front of whitespace in table fields.
1456 This makes the structure of the table stay in tact as long as the edited
1457 field does not exceed the column width.
1458 - Minimize the number of realigns. Normally, the table is aligned each time
1459 TAB or RET are pressed to move to another field. With optimization this
1460 happens only if changes to a field might have changed the column width.
1461 Optimization requires replacing the functions `self-insert-command',
1462 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1463 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1464 very good at guessing when a re-align will be necessary, but you can always
1465 force one with \\[org-ctrl-c-ctrl-c].
1467 If you would like to use the optimized version in Org-mode, but the
1468 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1470 This variable can be used to turn on and off the table editor during a session,
1471 but in order to toggle optimization, a restart is required.
1473 See also the variable `org-table-auto-blank-field'."
1474 :group 'org-table
1475 :type '(choice
1476 (const :tag "off" nil)
1477 (const :tag "on" t)
1478 (const :tag "on, optimized" optimized)))
1480 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1481 (version<= emacs-version "24.1"))
1482 "Non-nil means cluster self-insert commands for undo when possible.
1483 If this is set, then, like in the Emacs command loop, 20 consecutive
1484 characters will be undone together.
1485 This is configurable, because there is some impact on typing performance."
1486 :group 'org-table
1487 :type 'boolean)
1489 (defcustom org-table-tab-recognizes-table.el t
1490 "Non-nil means TAB will automatically notice a table.el table.
1491 When it sees such a table, it moves point into it and - if necessary -
1492 calls `table-recognize-table'."
1493 :group 'org-table-editing
1494 :type 'boolean)
1496 (defgroup org-link nil
1497 "Options concerning links in Org-mode."
1498 :tag "Org Link"
1499 :group 'org)
1501 (defvar org-link-abbrev-alist-local nil
1502 "Buffer-local version of `org-link-abbrev-alist', which see.
1503 The value of this is taken from the #+LINK lines.")
1504 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1506 (defcustom org-link-abbrev-alist nil
1507 "Alist of link abbreviations.
1508 The car of each element is a string, to be replaced at the start of a link.
1509 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1510 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1512 [[linkkey:tag][description]]
1514 The 'linkkey' must be a word word, starting with a letter, followed
1515 by letters, numbers, '-' or '_'.
1517 If REPLACE is a string, the tag will simply be appended to create the link.
1518 If the string contains \"%s\", the tag will be inserted there. If the string
1519 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1520 at that point (see the function `url-hexify-string'). If the string contains
1521 the specifier \"%(my-function)\", then the custom function `my-function' will
1522 be invoked: this function takes the tag as its only argument and must return
1523 a string.
1525 REPLACE may also be a function that will be called with the tag as the
1526 only argument to create the link, which should be returned as a string.
1528 See the manual for examples."
1529 :group 'org-link
1530 :type '(repeat
1531 (cons
1532 (string :tag "Protocol")
1533 (choice
1534 (string :tag "Format")
1535 (function)))))
1537 (defcustom org-descriptive-links t
1538 "Non-nil means Org will display descriptive links.
1539 E.g. [[http://orgmode.org][Org website]] will be displayed as
1540 \"Org Website\", hiding the link itself and just displaying its
1541 description. When set to `nil', Org will display the full links
1542 literally.
1544 You can interactively set the value of this variable by calling
1545 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1546 :group 'org-link
1547 :type 'boolean)
1549 (defcustom org-link-file-path-type 'adaptive
1550 "How the path name in file links should be stored.
1551 Valid values are:
1553 relative Relative to the current directory, i.e. the directory of the file
1554 into which the link is being inserted.
1555 absolute Absolute path, if possible with ~ for home directory.
1556 noabbrev Absolute path, no abbreviation of home directory.
1557 adaptive Use relative path for files in the current directory and sub-
1558 directories of it. For other files, use an absolute path."
1559 :group 'org-link
1560 :type '(choice
1561 (const relative)
1562 (const absolute)
1563 (const noabbrev)
1564 (const adaptive)))
1566 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1567 "Types of links that should be activated in Org-mode files.
1568 This is a list of symbols, each leading to the activation of a certain link
1569 type. In principle, it does not hurt to turn on most link types - there may
1570 be a small gain when turning off unused link types. The types are:
1572 bracket The recommended [[link][description]] or [[link]] links with hiding.
1573 angle Links in angular brackets that may contain whitespace like
1574 <bbdb:Carsten Dominik>.
1575 plain Plain links in normal text, no whitespace, like http://google.com.
1576 radio Text that is matched by a radio target, see manual for details.
1577 tag Tag settings in a headline (link to tag search).
1578 date Time stamps (link to calendar).
1579 footnote Footnote labels.
1581 Changing this variable requires a restart of Emacs to become effective."
1582 :group 'org-link
1583 :type '(set :greedy t
1584 (const :tag "Double bracket links" bracket)
1585 (const :tag "Angular bracket links" angle)
1586 (const :tag "Plain text links" plain)
1587 (const :tag "Radio target matches" radio)
1588 (const :tag "Tags" tag)
1589 (const :tag "Timestamps" date)
1590 (const :tag "Footnotes" footnote)))
1592 (defcustom org-make-link-description-function nil
1593 "Function to use for generating link descriptions from links.
1594 When nil, the link location will be used. This function must take
1595 two parameters: the first one is the link, the second one is the
1596 description generated by `org-insert-link'. The function should
1597 return the description to use."
1598 :group 'org-link
1599 :type 'function)
1601 (defgroup org-link-store nil
1602 "Options concerning storing links in Org-mode."
1603 :tag "Org Store Link"
1604 :group 'org-link)
1606 (defcustom org-url-hexify-p t
1607 "When non-nil, hexify URL when creating a link."
1608 :type 'boolean
1609 :version "24.3"
1610 :group 'org-link-store)
1612 (defcustom org-email-link-description-format "Email %c: %.30s"
1613 "Format of the description part of a link to an email or usenet message.
1614 The following %-escapes will be replaced by corresponding information:
1616 %F full \"From\" field
1617 %f name, taken from \"From\" field, address if no name
1618 %T full \"To\" field
1619 %t first name in \"To\" field, address if no name
1620 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1621 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1622 %s subject
1623 %d date
1624 %m message-id.
1626 You may use normal field width specification between the % and the letter.
1627 This is for example useful to limit the length of the subject.
1629 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1630 :group 'org-link-store
1631 :type 'string)
1633 (defcustom org-from-is-user-regexp
1634 (let (r1 r2)
1635 (when (and user-mail-address (not (string= user-mail-address "")))
1636 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1637 (when (and user-full-name (not (string= user-full-name "")))
1638 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1639 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1640 "Regexp matched against the \"From:\" header of an email or usenet message.
1641 It should match if the message is from the user him/herself."
1642 :group 'org-link-store
1643 :type 'regexp)
1645 (defcustom org-context-in-file-links t
1646 "Non-nil means file links from `org-store-link' contain context.
1647 A search string will be added to the file name with :: as separator and
1648 used to find the context when the link is activated by the command
1649 `org-open-at-point'. When this option is t, the entire active region
1650 will be placed in the search string of the file link. If set to a
1651 positive integer, only the first n lines of context will be stored.
1653 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1654 negates this setting for the duration of the command."
1655 :group 'org-link-store
1656 :type '(choice boolean integer))
1658 (defcustom org-keep-stored-link-after-insertion nil
1659 "Non-nil means keep link in list for entire session.
1661 The command `org-store-link' adds a link pointing to the current
1662 location to an internal list. These links accumulate during a session.
1663 The command `org-insert-link' can be used to insert links into any
1664 Org-mode file (offering completion for all stored links). When this
1665 option is nil, every link which has been inserted once using \\[org-insert-link]
1666 will be removed from the list, to make completing the unused links
1667 more efficient."
1668 :group 'org-link-store
1669 :type 'boolean)
1671 (defgroup org-link-follow nil
1672 "Options concerning following links in Org-mode."
1673 :tag "Org Follow Link"
1674 :group 'org-link)
1676 (defcustom org-link-translation-function nil
1677 "Function to translate links with different syntax to Org syntax.
1678 This can be used to translate links created for example by the Planner
1679 or emacs-wiki packages to Org syntax.
1680 The function must accept two parameters, a TYPE containing the link
1681 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1682 which is everything after the link protocol. It should return a cons
1683 with possibly modified values of type and path.
1684 Org contains a function for this, so if you set this variable to
1685 `org-translate-link-from-planner', you should be able follow many
1686 links created by planner."
1687 :group 'org-link-follow
1688 :type 'function)
1690 (defcustom org-follow-link-hook nil
1691 "Hook that is run after a link has been followed."
1692 :group 'org-link-follow
1693 :type 'hook)
1695 (defcustom org-tab-follows-link nil
1696 "Non-nil means on links TAB will follow the link.
1697 Needs to be set before org.el is loaded.
1698 This really should not be used, it does not make sense, and the
1699 implementation is bad."
1700 :group 'org-link-follow
1701 :type 'boolean)
1703 (defcustom org-return-follows-link nil
1704 "Non-nil means on links RET will follow the link.
1705 In tables, the special behavior of RET has precedence."
1706 :group 'org-link-follow
1707 :type 'boolean)
1709 (defcustom org-mouse-1-follows-link
1710 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1711 "Non-nil means mouse-1 on a link will follow the link.
1712 A longer mouse click will still set point. Does not work on XEmacs.
1713 Needs to be set before org.el is loaded."
1714 :group 'org-link-follow
1715 :type 'boolean)
1717 (defcustom org-mark-ring-length 4
1718 "Number of different positions to be recorded in the ring.
1719 Changing this requires a restart of Emacs to work correctly."
1720 :group 'org-link-follow
1721 :type 'integer)
1723 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1724 "Non-nil means internal links in Org files must exactly match a headline.
1725 When nil, the link search tries to match a phrase with all words
1726 in the search text."
1727 :group 'org-link-follow
1728 :version "24.1"
1729 :type '(choice
1730 (const :tag "Use fuzzy text search" nil)
1731 (const :tag "Match only exact headline" t)
1732 (const :tag "Match exact headline or query to create it"
1733 query-to-create)))
1735 (defcustom org-link-frame-setup
1736 '((vm . vm-visit-folder-other-frame)
1737 (vm-imap . vm-visit-imap-folder-other-frame)
1738 (gnus . org-gnus-no-new-news)
1739 (file . find-file-other-window)
1740 (wl . wl-other-frame))
1741 "Setup the frame configuration for following links.
1742 When following a link with Emacs, it may often be useful to display
1743 this link in another window or frame. This variable can be used to
1744 set this up for the different types of links.
1745 For VM, use any of
1746 `vm-visit-folder'
1747 `vm-visit-folder-other-window'
1748 `vm-visit-folder-other-frame'
1749 For Gnus, use any of
1750 `gnus'
1751 `gnus-other-frame'
1752 `org-gnus-no-new-news'
1753 For FILE, use any of
1754 `find-file'
1755 `find-file-other-window'
1756 `find-file-other-frame'
1757 For Wanderlust use any of
1758 `wl'
1759 `wl-other-frame'
1760 For the calendar, use the variable `calendar-setup'.
1761 For BBDB, it is currently only possible to display the matches in
1762 another window."
1763 :group 'org-link-follow
1764 :type '(list
1765 (cons (const vm)
1766 (choice
1767 (const vm-visit-folder)
1768 (const vm-visit-folder-other-window)
1769 (const vm-visit-folder-other-frame)))
1770 (cons (const gnus)
1771 (choice
1772 (const gnus)
1773 (const gnus-other-frame)
1774 (const org-gnus-no-new-news)))
1775 (cons (const file)
1776 (choice
1777 (const find-file)
1778 (const find-file-other-window)
1779 (const find-file-other-frame)))
1780 (cons (const wl)
1781 (choice
1782 (const wl)
1783 (const wl-other-frame)))))
1785 (defcustom org-display-internal-link-with-indirect-buffer nil
1786 "Non-nil means use indirect buffer to display infile links.
1787 Activating internal links (from one location in a file to another location
1788 in the same file) normally just jumps to the location. When the link is
1789 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1790 is displayed in
1791 another window. When this option is set, the other window actually displays
1792 an indirect buffer clone of the current buffer, to avoid any visibility
1793 changes to the current buffer."
1794 :group 'org-link-follow
1795 :type 'boolean)
1797 (defcustom org-open-non-existing-files nil
1798 "Non-nil means `org-open-file' will open non-existing files.
1799 When nil, an error will be generated.
1800 This variable applies only to external applications because they
1801 might choke on non-existing files. If the link is to a file that
1802 will be opened in Emacs, the variable is ignored."
1803 :group 'org-link-follow
1804 :type 'boolean)
1806 (defcustom org-open-directory-means-index-dot-org nil
1807 "Non-nil means a link to a directory really means to index.org.
1808 When nil, following a directory link will run dired or open a finder/explorer
1809 window on that directory."
1810 :group 'org-link-follow
1811 :type 'boolean)
1813 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1814 "Function and arguments to call for following mailto links.
1815 This is a list with the first element being a Lisp function, and the
1816 remaining elements being arguments to the function. In string arguments,
1817 %a will be replaced by the address, and %s will be replaced by the subject
1818 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1819 :group 'org-link-follow
1820 :type '(choice
1821 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1822 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1823 (const :tag "message-mail" (message-mail "%a" "%s"))
1824 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1826 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1827 "Non-nil means ask for confirmation before executing shell links.
1828 Shell links can be dangerous: just think about a link
1830 [[shell:rm -rf ~/*][Google Search]]
1832 This link would show up in your Org-mode document as \"Google Search\",
1833 but really it would remove your entire home directory.
1834 Therefore we advise against setting this variable to nil.
1835 Just change it to `y-or-n-p' if you want to confirm with a
1836 single keystroke rather than having to type \"yes\"."
1837 :group 'org-link-follow
1838 :type '(choice
1839 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1840 (const :tag "with y-or-n (faster)" y-or-n-p)
1841 (const :tag "no confirmation (dangerous)" nil)))
1842 (put 'org-confirm-shell-link-function
1843 'safe-local-variable
1844 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1846 (defcustom org-confirm-shell-link-not-regexp ""
1847 "A regexp to skip confirmation for shell links."
1848 :group 'org-link-follow
1849 :version "24.1"
1850 :type 'regexp)
1852 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1853 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1854 Elisp links can be dangerous: just think about a link
1856 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1858 This link would show up in your Org-mode document as \"Google Search\",
1859 but really it would remove your entire home directory.
1860 Therefore we advise against setting this variable to nil.
1861 Just change it to `y-or-n-p' if you want to confirm with a
1862 single keystroke rather than having to type \"yes\"."
1863 :group 'org-link-follow
1864 :type '(choice
1865 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1866 (const :tag "with y-or-n (faster)" y-or-n-p)
1867 (const :tag "no confirmation (dangerous)" nil)))
1868 (put 'org-confirm-shell-link-function
1869 'safe-local-variable
1870 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1872 (defcustom org-confirm-elisp-link-not-regexp ""
1873 "A regexp to skip confirmation for Elisp links."
1874 :group 'org-link-follow
1875 :version "24.1"
1876 :type 'regexp)
1878 (defconst org-file-apps-defaults-gnu
1879 '((remote . emacs)
1880 (system . mailcap)
1881 (t . mailcap))
1882 "Default file applications on a UNIX or GNU/Linux system.
1883 See `org-file-apps'.")
1885 (defconst org-file-apps-defaults-macosx
1886 '((remote . emacs)
1887 (t . "open %s")
1888 (system . "open %s")
1889 ("ps.gz" . "gv %s")
1890 ("eps.gz" . "gv %s")
1891 ("dvi" . "xdvi %s")
1892 ("fig" . "xfig %s"))
1893 "Default file applications on a MacOS X system.
1894 The system \"open\" is known as a default, but we use X11 applications
1895 for some files for which the OS does not have a good default.
1896 See `org-file-apps'.")
1898 (defconst org-file-apps-defaults-windowsnt
1899 (list
1900 '(remote . emacs)
1901 (cons t
1902 (list (if (featurep 'xemacs)
1903 'mswindows-shell-execute
1904 'w32-shell-execute)
1905 "open" 'file))
1906 (cons 'system
1907 (list (if (featurep 'xemacs)
1908 'mswindows-shell-execute
1909 'w32-shell-execute)
1910 "open" 'file)))
1911 "Default file applications on a Windows NT system.
1912 The system \"open\" is used for most files.
1913 See `org-file-apps'.")
1915 (defcustom org-file-apps
1916 '((auto-mode . emacs)
1917 ("\\.mm\\'" . default)
1918 ("\\.x?html?\\'" . default)
1919 ("\\.pdf\\'" . default))
1920 "External applications for opening `file:path' items in a document.
1921 Org-mode uses system defaults for different file types, but
1922 you can use this variable to set the application for a given file
1923 extension. The entries in this list are cons cells where the car identifies
1924 files and the cdr the corresponding command. Possible values for the
1925 file identifier are
1926 \"string\" A string as a file identifier can be interpreted in different
1927 ways, depending on its contents:
1929 - Alphanumeric characters only:
1930 Match links with this file extension.
1931 Example: (\"pdf\" . \"evince %s\")
1932 to open PDFs with evince.
1934 - Regular expression: Match links where the
1935 filename matches the regexp. If you want to
1936 use groups here, use shy groups.
1938 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1939 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1940 to open *.html and *.xhtml with firefox.
1942 - Regular expression which contains (non-shy) groups:
1943 Match links where the whole link, including \"::\", and
1944 anything after that, matches the regexp.
1945 In a custom command string, %1, %2, etc. are replaced with
1946 the parts of the link that were matched by the groups.
1947 For backwards compatibility, if a command string is given
1948 that does not use any of the group matches, this case is
1949 handled identically to the second one (i.e. match against
1950 file name only).
1951 In a custom lisp form, you can access the group matches with
1952 (match-string n link).
1954 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1955 to open [[file:document.pdf::5]] with evince at page 5.
1957 `directory' Matches a directory
1958 `remote' Matches a remote file, accessible through tramp or efs.
1959 Remote files most likely should be visited through Emacs
1960 because external applications cannot handle such paths.
1961 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1962 so all files Emacs knows how to handle. Using this with
1963 command `emacs' will open most files in Emacs. Beware that this
1964 will also open html files inside Emacs, unless you add
1965 (\"html\" . default) to the list as well.
1966 t Default for files not matched by any of the other options.
1967 `system' The system command to open files, like `open' on Windows
1968 and Mac OS X, and mailcap under GNU/Linux. This is the command
1969 that will be selected if you call `C-c C-o' with a double
1970 \\[universal-argument] \\[universal-argument] prefix.
1972 Possible values for the command are:
1973 `emacs' The file will be visited by the current Emacs process.
1974 `default' Use the default application for this file type, which is the
1975 association for t in the list, most likely in the system-specific
1976 part.
1977 This can be used to overrule an unwanted setting in the
1978 system-specific variable.
1979 `system' Use the system command for opening files, like \"open\".
1980 This command is specified by the entry whose car is `system'.
1981 Most likely, the system-specific version of this variable
1982 does define this command, but you can overrule/replace it
1983 here.
1984 string A command to be executed by a shell; %s will be replaced
1985 by the path to the file.
1986 sexp A Lisp form which will be evaluated. The file path will
1987 be available in the Lisp variable `file'.
1988 For more examples, see the system specific constants
1989 `org-file-apps-defaults-macosx'
1990 `org-file-apps-defaults-windowsnt'
1991 `org-file-apps-defaults-gnu'."
1992 :group 'org-link-follow
1993 :type '(repeat
1994 (cons (choice :value ""
1995 (string :tag "Extension")
1996 (const :tag "System command to open files" system)
1997 (const :tag "Default for unrecognized files" t)
1998 (const :tag "Remote file" remote)
1999 (const :tag "Links to a directory" directory)
2000 (const :tag "Any files that have Emacs modes"
2001 auto-mode))
2002 (choice :value ""
2003 (const :tag "Visit with Emacs" emacs)
2004 (const :tag "Use default" default)
2005 (const :tag "Use the system command" system)
2006 (string :tag "Command")
2007 (sexp :tag "Lisp form")))))
2009 (defcustom org-doi-server-url "http://dx.doi.org/"
2010 "The URL of the DOI server."
2011 :type 'string
2012 :version "24.3"
2013 :group 'org-link-follow)
2015 (defgroup org-refile nil
2016 "Options concerning refiling entries in Org-mode."
2017 :tag "Org Refile"
2018 :group 'org)
2020 (defcustom org-directory "~/org"
2021 "Directory with org files.
2022 This is just a default location to look for Org files. There is no need
2023 at all to put your files into this directory. It is only used in the
2024 following situations:
2026 1. When a capture template specifies a target file that is not an
2027 absolute path. The path will then be interpreted relative to
2028 `org-directory'
2029 2. When a capture note is filed away in an interactive way (when exiting the
2030 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2031 with `org-directory' as the default path."
2032 :group 'org-refile
2033 :group 'org-remember
2034 :group 'org-capture
2035 :type 'directory)
2037 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2038 "Default target for storing notes.
2039 Used as a fall back file for org-remember.el and org-capture.el, for
2040 templates that do not specify a target file."
2041 :group 'org-refile
2042 :group 'org-remember
2043 :group 'org-capture
2044 :type '(choice
2045 (const :tag "Default from remember-data-file" nil)
2046 file))
2048 (defcustom org-goto-interface 'outline
2049 "The default interface to be used for `org-goto'.
2050 Allowed values are:
2051 outline The interface shows an outline of the relevant file
2052 and the correct heading is found by moving through
2053 the outline or by searching with incremental search.
2054 outline-path-completion Headlines in the current buffer are offered via
2055 completion. This is the interface also used by
2056 the refile command."
2057 :group 'org-refile
2058 :type '(choice
2059 (const :tag "Outline" outline)
2060 (const :tag "Outline-path-completion" outline-path-completion)))
2062 (defcustom org-goto-max-level 5
2063 "Maximum target level when running `org-goto' with refile interface."
2064 :group 'org-refile
2065 :type 'integer)
2067 (defcustom org-reverse-note-order nil
2068 "Non-nil means store new notes at the beginning of a file or entry.
2069 When nil, new notes will be filed to the end of a file or entry.
2070 This can also be a list with cons cells of regular expressions that
2071 are matched against file names, and values."
2072 :group 'org-remember
2073 :group 'org-capture
2074 :group 'org-refile
2075 :type '(choice
2076 (const :tag "Reverse always" t)
2077 (const :tag "Reverse never" nil)
2078 (repeat :tag "By file name regexp"
2079 (cons regexp boolean))))
2081 (defcustom org-log-refile nil
2082 "Information to record when a task is refiled.
2084 Possible values are:
2086 nil Don't add anything
2087 time Add a time stamp to the task
2088 note Prompt for a note and add it with template `org-log-note-headings'
2090 This option can also be set with on a per-file-basis with
2092 #+STARTUP: nologrefile
2093 #+STARTUP: logrefile
2094 #+STARTUP: lognoterefile
2096 You can have local logging settings for a subtree by setting the LOGGING
2097 property to one or more of these keywords.
2099 When bulk-refiling from the agenda, the value `note' is forbidden and
2100 will temporarily be changed to `time'."
2101 :group 'org-refile
2102 :group 'org-progress
2103 :version "24.1"
2104 :type '(choice
2105 (const :tag "No logging" nil)
2106 (const :tag "Record timestamp" time)
2107 (const :tag "Record timestamp with note." note)))
2109 (defcustom org-refile-targets nil
2110 "Targets for refiling entries with \\[org-refile].
2111 This is a list of cons cells. Each cell contains:
2112 - a specification of the files to be considered, either a list of files,
2113 or a symbol whose function or variable value will be used to retrieve
2114 a file name or a list of file names. If you use `org-agenda-files' for
2115 that, all agenda files will be scanned for targets. Nil means consider
2116 headings in the current buffer.
2117 - A specification of how to find candidate refile targets. This may be
2118 any of:
2119 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2120 This tag has to be present in all target headlines, inheritance will
2121 not be considered.
2122 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2123 todo keyword.
2124 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2125 headlines that are refiling targets.
2126 - a cons cell (:level . N). Any headline of level N is considered a target.
2127 Note that, when `org-odd-levels-only' is set, level corresponds to
2128 order in hierarchy, not to the number of stars.
2129 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2130 Note that, when `org-odd-levels-only' is set, level corresponds to
2131 order in hierarchy, not to the number of stars.
2133 Each element of this list generates a set of possible targets.
2134 The union of these sets is presented (with completion) to
2135 the user by `org-refile'.
2137 You can set the variable `org-refile-target-verify-function' to a function
2138 to verify each headline found by the simple criteria above.
2140 When this variable is nil, all top-level headlines in the current buffer
2141 are used, equivalent to the value `((nil . (:level . 1))'."
2142 :group 'org-refile
2143 :type '(repeat
2144 (cons
2145 (choice :value org-agenda-files
2146 (const :tag "All agenda files" org-agenda-files)
2147 (const :tag "Current buffer" nil)
2148 (function) (variable) (file))
2149 (choice :tag "Identify target headline by"
2150 (cons :tag "Specific tag" (const :value :tag) (string))
2151 (cons :tag "TODO keyword" (const :value :todo) (string))
2152 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2153 (cons :tag "Level number" (const :value :level) (integer))
2154 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2156 (defcustom org-refile-target-verify-function nil
2157 "Function to verify if the headline at point should be a refile target.
2158 The function will be called without arguments, with point at the
2159 beginning of the headline. It should return t and leave point
2160 where it is if the headline is a valid target for refiling.
2162 If the target should not be selected, the function must return nil.
2163 In addition to this, it may move point to a place from where the search
2164 should be continued. For example, the function may decide that the entire
2165 subtree of the current entry should be excluded and move point to the end
2166 of the subtree."
2167 :group 'org-refile
2168 :type 'function)
2170 (defcustom org-refile-use-cache nil
2171 "Non-nil means cache refile targets to speed up the process.
2172 The cache for a particular file will be updated automatically when
2173 the buffer has been killed, or when any of the marker used for flagging
2174 refile targets no longer points at a live buffer.
2175 If you have added new entries to a buffer that might themselves be targets,
2176 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2177 find that easier, `C-u C-u C-u C-c C-w'."
2178 :group 'org-refile
2179 :version "24.1"
2180 :type 'boolean)
2182 (defcustom org-refile-use-outline-path nil
2183 "Non-nil means provide refile targets as paths.
2184 So a level 3 headline will be available as level1/level2/level3.
2186 When the value is `file', also include the file name (without directory)
2187 into the path. In this case, you can also stop the completion after
2188 the file name, to get entries inserted as top level in the file.
2190 When `full-file-path', include the full file path."
2191 :group 'org-refile
2192 :type '(choice
2193 (const :tag "Not" nil)
2194 (const :tag "Yes" t)
2195 (const :tag "Start with file name" file)
2196 (const :tag "Start with full file path" full-file-path)))
2198 (defcustom org-outline-path-complete-in-steps t
2199 "Non-nil means complete the outline path in hierarchical steps.
2200 When Org-mode uses the refile interface to select an outline path
2201 \(see variable `org-refile-use-outline-path'), the completion of
2202 the path can be done is a single go, or if can be done in steps down
2203 the headline hierarchy. Going in steps is probably the best if you
2204 do not use a special completion package like `ido' or `icicles'.
2205 However, when using these packages, going in one step can be very
2206 fast, while still showing the whole path to the entry."
2207 :group 'org-refile
2208 :type 'boolean)
2210 (defcustom org-refile-allow-creating-parent-nodes nil
2211 "Non-nil means allow to create new nodes as refile targets.
2212 New nodes are then created by adding \"/new node name\" to the completion
2213 of an existing node. When the value of this variable is `confirm',
2214 new node creation must be confirmed by the user (recommended)
2215 When nil, the completion must match an existing entry.
2217 Note that, if the new heading is not seen by the criteria
2218 listed in `org-refile-targets', multiple instances of the same
2219 heading would be created by trying again to file under the new
2220 heading."
2221 :group 'org-refile
2222 :type '(choice
2223 (const :tag "Never" nil)
2224 (const :tag "Always" t)
2225 (const :tag "Prompt for confirmation" confirm)))
2227 (defcustom org-refile-active-region-within-subtree nil
2228 "Non-nil means also refile active region within a subtree.
2230 By default `org-refile' doesn't allow refiling regions if they
2231 don't contain a set of subtrees, but it might be convenient to
2232 do so sometimes: in that case, the first line of the region is
2233 converted to a headline before refiling."
2234 :group 'org-refile
2235 :version "24.1"
2236 :type 'boolean)
2238 (defgroup org-todo nil
2239 "Options concerning TODO items in Org-mode."
2240 :tag "Org TODO"
2241 :group 'org)
2243 (defgroup org-progress nil
2244 "Options concerning Progress logging in Org-mode."
2245 :tag "Org Progress"
2246 :group 'org-time)
2248 (defvar org-todo-interpretation-widgets
2249 '((:tag "Sequence (cycling hits every state)" sequence)
2250 (:tag "Type (cycling directly to DONE)" type))
2251 "The available interpretation symbols for customizing `org-todo-keywords'.
2252 Interested libraries should add to this list.")
2254 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2255 "List of TODO entry keyword sequences and their interpretation.
2256 \\<org-mode-map>This is a list of sequences.
2258 Each sequence starts with a symbol, either `sequence' or `type',
2259 indicating if the keywords should be interpreted as a sequence of
2260 action steps, or as different types of TODO items. The first
2261 keywords are states requiring action - these states will select a headline
2262 for inclusion into the global TODO list Org-mode produces. If one of
2263 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2264 signify that no further action is necessary. If \"|\" is not found,
2265 the last keyword is treated as the only DONE state of the sequence.
2267 The command \\[org-todo] cycles an entry through these states, and one
2268 additional state where no keyword is present. For details about this
2269 cycling, see the manual.
2271 TODO keywords and interpretation can also be set on a per-file basis with
2272 the special #+SEQ_TODO and #+TYP_TODO lines.
2274 Each keyword can optionally specify a character for fast state selection
2275 \(in combination with the variable `org-use-fast-todo-selection')
2276 and specifiers for state change logging, using the same syntax that
2277 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2278 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2279 indicates to record a time stamp each time this state is selected.
2281 Each keyword may also specify if a timestamp or a note should be
2282 recorded when entering or leaving the state, by adding additional
2283 characters in the parenthesis after the keyword. This looks like this:
2284 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2285 record only the time of the state change. With X and Y being either
2286 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2287 Y when leaving the state if and only if the *target* state does not
2288 define X. You may omit any of the fast-selection key or X or /Y,
2289 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2291 For backward compatibility, this variable may also be just a list
2292 of keywords. In this case the interpretation (sequence or type) will be
2293 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2294 :group 'org-todo
2295 :group 'org-keywords
2296 :type '(choice
2297 (repeat :tag "Old syntax, just keywords"
2298 (string :tag "Keyword"))
2299 (repeat :tag "New syntax"
2300 (cons
2301 (choice
2302 :tag "Interpretation"
2303 ;;Quick and dirty way to see
2304 ;;`org-todo-interpretations'. This takes the
2305 ;;place of item arguments
2306 :convert-widget
2307 (lambda (widget)
2308 (widget-put widget
2309 :args (mapcar
2310 #'(lambda (x)
2311 (widget-convert
2312 (cons 'const x)))
2313 org-todo-interpretation-widgets))
2314 widget))
2315 (repeat
2316 (string :tag "Keyword"))))))
2318 (defvar org-todo-keywords-1 nil
2319 "All TODO and DONE keywords active in a buffer.")
2320 (make-variable-buffer-local 'org-todo-keywords-1)
2321 (defvar org-todo-keywords-for-agenda nil)
2322 (defvar org-done-keywords-for-agenda nil)
2323 (defvar org-drawers-for-agenda nil)
2324 (defvar org-todo-keyword-alist-for-agenda nil)
2325 (defvar org-tag-alist-for-agenda nil
2326 "Alist of all tags from all agenda files.")
2327 (defvar org-tag-groups-alist-for-agenda nil
2328 "Alist of all groups tags from all current agenda files.")
2329 (defvar org-tag-groups-alist nil)
2330 (make-variable-buffer-local 'org-tag-groups-alist)
2331 (defvar org-agenda-contributing-files nil)
2332 (defvar org-not-done-keywords nil)
2333 (make-variable-buffer-local 'org-not-done-keywords)
2334 (defvar org-done-keywords nil)
2335 (make-variable-buffer-local 'org-done-keywords)
2336 (defvar org-todo-heads nil)
2337 (make-variable-buffer-local 'org-todo-heads)
2338 (defvar org-todo-sets nil)
2339 (make-variable-buffer-local 'org-todo-sets)
2340 (defvar org-todo-log-states nil)
2341 (make-variable-buffer-local 'org-todo-log-states)
2342 (defvar org-todo-kwd-alist nil)
2343 (make-variable-buffer-local 'org-todo-kwd-alist)
2344 (defvar org-todo-key-alist nil)
2345 (make-variable-buffer-local 'org-todo-key-alist)
2346 (defvar org-todo-key-trigger nil)
2347 (make-variable-buffer-local 'org-todo-key-trigger)
2349 (defcustom org-todo-interpretation 'sequence
2350 "Controls how TODO keywords are interpreted.
2351 This variable is in principle obsolete and is only used for
2352 backward compatibility, if the interpretation of todo keywords is
2353 not given already in `org-todo-keywords'. See that variable for
2354 more information."
2355 :group 'org-todo
2356 :group 'org-keywords
2357 :type '(choice (const sequence)
2358 (const type)))
2360 (defcustom org-use-fast-todo-selection t
2361 "Non-nil means use the fast todo selection scheme with C-c C-t.
2362 This variable describes if and under what circumstances the cycling
2363 mechanism for TODO keywords will be replaced by a single-key, direct
2364 selection scheme.
2366 When nil, fast selection is never used.
2368 When the symbol `prefix', it will be used when `org-todo' is called
2369 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2370 `C-u t' in an agenda buffer.
2372 When t, fast selection is used by default. In this case, the prefix
2373 argument forces cycling instead.
2375 In all cases, the special interface is only used if access keys have
2376 actually been assigned by the user, i.e. if keywords in the configuration
2377 are followed by a letter in parenthesis, like TODO(t)."
2378 :group 'org-todo
2379 :type '(choice
2380 (const :tag "Never" nil)
2381 (const :tag "By default" t)
2382 (const :tag "Only with C-u C-c C-t" prefix)))
2384 (defcustom org-provide-todo-statistics t
2385 "Non-nil means update todo statistics after insert and toggle.
2386 ALL-HEADLINES means update todo statistics by including headlines
2387 with no TODO keyword as well, counting them as not done.
2388 A list of TODO keywords means the same, but skip keywords that are
2389 not in this list.
2391 When this is set, todo statistics is updated in the parent of the
2392 current entry each time a todo state is changed."
2393 :group 'org-todo
2394 :type '(choice
2395 (const :tag "Yes, only for TODO entries" t)
2396 (const :tag "Yes, including all entries" 'all-headlines)
2397 (repeat :tag "Yes, for TODOs in this list"
2398 (string :tag "TODO keyword"))
2399 (other :tag "No TODO statistics" nil)))
2401 (defcustom org-hierarchical-todo-statistics t
2402 "Non-nil means TODO statistics covers just direct children.
2403 When nil, all entries in the subtree are considered.
2404 This has only an effect if `org-provide-todo-statistics' is set.
2405 To set this to nil for only a single subtree, use a COOKIE_DATA
2406 property and include the word \"recursive\" into the value."
2407 :group 'org-todo
2408 :type 'boolean)
2410 (defcustom org-after-todo-state-change-hook nil
2411 "Hook which is run after the state of a TODO item was changed.
2412 The new state (a string with a TODO keyword, or nil) is available in the
2413 Lisp variable `org-state'."
2414 :group 'org-todo
2415 :type 'hook)
2417 (defvar org-blocker-hook nil
2418 "Hook for functions that are allowed to block a state change.
2420 Functions in this hook should not modify the buffer.
2421 Each function gets as its single argument a property list,
2422 see `org-trigger-hook' for more information about this list.
2424 If any of the functions in this hook returns nil, the state change
2425 is blocked.")
2427 (defvar org-trigger-hook nil
2428 "Hook for functions that are triggered by a state change.
2430 Each function gets as its single argument a property list with at
2431 least the following elements:
2433 (:type type-of-change :position pos-at-entry-start
2434 :from old-state :to new-state)
2436 Depending on the type, more properties may be present.
2438 This mechanism is currently implemented for:
2440 TODO state changes
2441 ------------------
2442 :type todo-state-change
2443 :from previous state (keyword as a string), or nil, or a symbol
2444 'todo' or 'done', to indicate the general type of state.
2445 :to new state, like in :from")
2447 (defcustom org-enforce-todo-dependencies nil
2448 "Non-nil means undone TODO entries will block switching the parent to DONE.
2449 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2450 be blocked if any prior sibling is not yet done.
2451 Finally, if the parent is blocked because of ordered siblings of its own,
2452 the child will also be blocked."
2453 :set (lambda (var val)
2454 (set var val)
2455 (if val
2456 (add-hook 'org-blocker-hook
2457 'org-block-todo-from-children-or-siblings-or-parent)
2458 (remove-hook 'org-blocker-hook
2459 'org-block-todo-from-children-or-siblings-or-parent)))
2460 :group 'org-todo
2461 :type 'boolean)
2463 (defcustom org-enforce-todo-checkbox-dependencies nil
2464 "Non-nil means unchecked boxes will block switching the parent to DONE.
2465 When this is nil, checkboxes have no influence on switching TODO states.
2466 When non-nil, you first need to check off all check boxes before the TODO
2467 entry can be switched to DONE.
2468 This variable needs to be set before org.el is loaded, and you need to
2469 restart Emacs after a change to make the change effective. The only way
2470 to change is while Emacs is running is through the customize interface."
2471 :set (lambda (var val)
2472 (set var val)
2473 (if val
2474 (add-hook 'org-blocker-hook
2475 'org-block-todo-from-checkboxes)
2476 (remove-hook 'org-blocker-hook
2477 'org-block-todo-from-checkboxes)))
2478 :group 'org-todo
2479 :type 'boolean)
2481 (defcustom org-treat-insert-todo-heading-as-state-change nil
2482 "Non-nil means inserting a TODO heading is treated as state change.
2483 So when the command \\[org-insert-todo-heading] is used, state change
2484 logging will apply if appropriate. When nil, the new TODO item will
2485 be inserted directly, and no logging will take place."
2486 :group 'org-todo
2487 :type 'boolean)
2489 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2490 "Non-nil means switching TODO states with S-cursor counts as state change.
2491 This is the default behavior. However, setting this to nil allows a
2492 convenient way to select a TODO state and bypass any logging associated
2493 with that."
2494 :group 'org-todo
2495 :type 'boolean)
2497 (defcustom org-todo-state-tags-triggers nil
2498 "Tag changes that should be triggered by TODO state changes.
2499 This is a list. Each entry is
2501 (state-change (tag . flag) .......)
2503 State-change can be a string with a state, and empty string to indicate the
2504 state that has no TODO keyword, or it can be one of the symbols `todo'
2505 or `done', meaning any not-done or done state, respectively."
2506 :group 'org-todo
2507 :group 'org-tags
2508 :type '(repeat
2509 (cons (choice :tag "When changing to"
2510 (const :tag "Not-done state" todo)
2511 (const :tag "Done state" done)
2512 (string :tag "State"))
2513 (repeat
2514 (cons :tag "Tag action"
2515 (string :tag "Tag")
2516 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2518 (defcustom org-log-done nil
2519 "Information to record when a task moves to the DONE state.
2521 Possible values are:
2523 nil Don't add anything, just change the keyword
2524 time Add a time stamp to the task
2525 note Prompt for a note and add it with template `org-log-note-headings'
2527 This option can also be set with on a per-file-basis with
2529 #+STARTUP: nologdone
2530 #+STARTUP: logdone
2531 #+STARTUP: lognotedone
2533 You can have local logging settings for a subtree by setting the LOGGING
2534 property to one or more of these keywords."
2535 :group 'org-todo
2536 :group 'org-progress
2537 :type '(choice
2538 (const :tag "No logging" nil)
2539 (const :tag "Record CLOSED timestamp" time)
2540 (const :tag "Record CLOSED timestamp with note." note)))
2542 ;; Normalize old uses of org-log-done.
2543 (cond
2544 ((eq org-log-done t) (setq org-log-done 'time))
2545 ((and (listp org-log-done) (memq 'done org-log-done))
2546 (setq org-log-done 'note)))
2548 (defcustom org-log-reschedule nil
2549 "Information to record when the scheduling date of a tasks is modified.
2551 Possible values are:
2553 nil Don't add anything, just change the date
2554 time Add a time stamp to the task
2555 note Prompt for a note and add it with template `org-log-note-headings'
2557 This option can also be set with on a per-file-basis with
2559 #+STARTUP: nologreschedule
2560 #+STARTUP: logreschedule
2561 #+STARTUP: lognotereschedule"
2562 :group 'org-todo
2563 :group 'org-progress
2564 :type '(choice
2565 (const :tag "No logging" nil)
2566 (const :tag "Record timestamp" time)
2567 (const :tag "Record timestamp with note." note)))
2569 (defcustom org-log-redeadline nil
2570 "Information to record when the deadline date of a tasks is modified.
2572 Possible values are:
2574 nil Don't add anything, just change the date
2575 time Add a time stamp to the task
2576 note Prompt for a note and add it with template `org-log-note-headings'
2578 This option can also be set with on a per-file-basis with
2580 #+STARTUP: nologredeadline
2581 #+STARTUP: logredeadline
2582 #+STARTUP: lognoteredeadline
2584 You can have local logging settings for a subtree by setting the LOGGING
2585 property to one or more of these keywords."
2586 :group 'org-todo
2587 :group 'org-progress
2588 :type '(choice
2589 (const :tag "No logging" nil)
2590 (const :tag "Record timestamp" time)
2591 (const :tag "Record timestamp with note." note)))
2593 (defcustom org-log-note-clock-out nil
2594 "Non-nil means record a note when clocking out of an item.
2595 This can also be configured on a per-file basis by adding one of
2596 the following lines anywhere in the buffer:
2598 #+STARTUP: lognoteclock-out
2599 #+STARTUP: nolognoteclock-out"
2600 :group 'org-todo
2601 :group 'org-progress
2602 :type 'boolean)
2604 (defcustom org-log-done-with-time t
2605 "Non-nil means the CLOSED time stamp will contain date and time.
2606 When nil, only the date will be recorded."
2607 :group 'org-progress
2608 :type 'boolean)
2610 (defcustom org-log-note-headings
2611 '((done . "CLOSING NOTE %t")
2612 (state . "State %-12s from %-12S %t")
2613 (note . "Note taken on %t")
2614 (reschedule . "Rescheduled from %S on %t")
2615 (delschedule . "Not scheduled, was %S on %t")
2616 (redeadline . "New deadline from %S on %t")
2617 (deldeadline . "Removed deadline, was %S on %t")
2618 (refile . "Refiled on %t")
2619 (clock-out . ""))
2620 "Headings for notes added to entries.
2621 The value is an alist, with the car being a symbol indicating the note
2622 context, and the cdr is the heading to be used. The heading may also be the
2623 empty string.
2624 %t in the heading will be replaced by a time stamp.
2625 %T will be an active time stamp instead the default inactive one
2626 %d will be replaced by a short-format time stamp.
2627 %D will be replaced by an active short-format time stamp.
2628 %s will be replaced by the new TODO state, in double quotes.
2629 %S will be replaced by the old TODO state, in double quotes.
2630 %u will be replaced by the user name.
2631 %U will be replaced by the full user name.
2633 In fact, it is not a good idea to change the `state' entry, because
2634 agenda log mode depends on the format of these entries."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(list :greedy t
2638 (cons (const :tag "Heading when closing an item" done) string)
2639 (cons (const :tag
2640 "Heading when changing todo state (todo sequence only)"
2641 state) string)
2642 (cons (const :tag "Heading when just taking a note" note) string)
2643 (cons (const :tag "Heading when clocking out" clock-out) string)
2644 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2645 (cons (const :tag "Heading when rescheduling" reschedule) string)
2646 (cons (const :tag "Heading when changing deadline" redeadline) string)
2647 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2648 (cons (const :tag "Heading when refiling" refile) string)))
2650 (unless (assq 'note org-log-note-headings)
2651 (push '(note . "%t") org-log-note-headings))
2653 (defcustom org-log-into-drawer nil
2654 "Non-nil means insert state change notes and time stamps into a drawer.
2655 When nil, state changes notes will be inserted after the headline and
2656 any scheduling and clock lines, but not inside a drawer.
2658 The value of this variable should be the name of the drawer to use.
2659 LOGBOOK is proposed as the default drawer for this purpose, you can
2660 also set this to a string to define the drawer of your choice.
2662 A value of t is also allowed, representing \"LOGBOOK\".
2664 A value of t or nil can also be set with on a per-file-basis with
2666 #+STARTUP: logdrawer
2667 #+STARTUP: nologdrawer
2669 If this variable is set, `org-log-state-notes-insert-after-drawers'
2670 will be ignored.
2672 You can set the property LOG_INTO_DRAWER to overrule this setting for
2673 a subtree."
2674 :group 'org-todo
2675 :group 'org-progress
2676 :type '(choice
2677 (const :tag "Not into a drawer" nil)
2678 (const :tag "LOGBOOK" t)
2679 (string :tag "Other")))
2681 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2683 (defun org-log-into-drawer ()
2684 "Return the value of `org-log-into-drawer', but let properties overrule.
2685 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2686 used instead of the default value."
2687 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2688 (cond
2689 ((not p) org-log-into-drawer)
2690 ((equal p "nil") nil)
2691 ((equal p "t") "LOGBOOK")
2692 (t p))))
2694 (defcustom org-log-state-notes-insert-after-drawers nil
2695 "Non-nil means insert state change notes after any drawers in entry.
2696 Only the drawers that *immediately* follow the headline and the
2697 deadline/scheduled line are skipped.
2698 When nil, insert notes right after the heading and perhaps the line
2699 with deadline/scheduling if present.
2701 This variable will have no effect if `org-log-into-drawer' is
2702 set."
2703 :group 'org-todo
2704 :group 'org-progress
2705 :type 'boolean)
2707 (defcustom org-log-states-order-reversed t
2708 "Non-nil means the latest state note will be directly after heading.
2709 When nil, the state change notes will be ordered according to time.
2711 This option can also be set with on a per-file-basis with
2713 #+STARTUP: logstatesreversed
2714 #+STARTUP: nologstatesreversed"
2715 :group 'org-todo
2716 :group 'org-progress
2717 :type 'boolean)
2719 (defcustom org-todo-repeat-to-state nil
2720 "The TODO state to which a repeater should return the repeating task.
2721 By default this is the first task in a TODO sequence, or the previous state
2722 in a TODO_TYP set. But you can specify another task here.
2723 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2724 :group 'org-todo
2725 :version "24.1"
2726 :type '(choice (const :tag "Head of sequence" nil)
2727 (string :tag "Specific state")))
2729 (defcustom org-log-repeat 'time
2730 "Non-nil means record moving through the DONE state when triggering repeat.
2731 An auto-repeating task is immediately switched back to TODO when
2732 marked DONE. If you are not logging state changes (by adding \"@\"
2733 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2734 record a closing note, there will be no record of the task moving
2735 through DONE. This variable forces taking a note anyway.
2737 nil Don't force a record
2738 time Record a time stamp
2739 note Prompt for a note and add it with template `org-log-note-headings'
2741 This option can also be set with on a per-file-basis with
2743 #+STARTUP: nologrepeat
2744 #+STARTUP: logrepeat
2745 #+STARTUP: lognoterepeat
2747 You can have local logging settings for a subtree by setting the LOGGING
2748 property to one or more of these keywords."
2749 :group 'org-todo
2750 :group 'org-progress
2751 :type '(choice
2752 (const :tag "Don't force a record" nil)
2753 (const :tag "Force recording the DONE state" time)
2754 (const :tag "Force recording a note with the DONE state" note)))
2757 (defgroup org-priorities nil
2758 "Priorities in Org-mode."
2759 :tag "Org Priorities"
2760 :group 'org-todo)
2762 (defcustom org-enable-priority-commands t
2763 "Non-nil means priority commands are active.
2764 When nil, these commands will be disabled, so that you never accidentally
2765 set a priority."
2766 :group 'org-priorities
2767 :type 'boolean)
2769 (defcustom org-highest-priority ?A
2770 "The highest priority of TODO items. A character like ?A, ?B etc.
2771 Must have a smaller ASCII number than `org-lowest-priority'."
2772 :group 'org-priorities
2773 :type 'character)
2775 (defcustom org-lowest-priority ?C
2776 "The lowest priority of TODO items. A character like ?A, ?B etc.
2777 Must have a larger ASCII number than `org-highest-priority'."
2778 :group 'org-priorities
2779 :type 'character)
2781 (defcustom org-default-priority ?B
2782 "The default priority of TODO items.
2783 This is the priority an item gets if no explicit priority is given.
2784 When starting to cycle on an empty priority the first step in the cycle
2785 depends on `org-priority-start-cycle-with-default'. The resulting first
2786 step priority must not exceed the range from `org-highest-priority' to
2787 `org-lowest-priority' which means that `org-default-priority' has to be
2788 in this range exclusive or inclusive the range boundaries. Else the
2789 first step refuses to set the default and the second will fall back
2790 to (depending on the command used) the highest or lowest priority."
2791 :group 'org-priorities
2792 :type 'character)
2794 (defcustom org-priority-start-cycle-with-default t
2795 "Non-nil means start with default priority when starting to cycle.
2796 When this is nil, the first step in the cycle will be (depending on the
2797 command used) one higher or lower than the default priority.
2798 See also `org-default-priority'."
2799 :group 'org-priorities
2800 :type 'boolean)
2802 (defcustom org-get-priority-function nil
2803 "Function to extract the priority from a string.
2804 The string is normally the headline. If this is nil Org computes the
2805 priority from the priority cookie like [#A] in the headline. It returns
2806 an integer, increasing by 1000 for each priority level.
2807 The user can set a different function here, which should take a string
2808 as an argument and return the numeric priority."
2809 :group 'org-priorities
2810 :version "24.1"
2811 :type 'function)
2813 (defgroup org-time nil
2814 "Options concerning time stamps and deadlines in Org-mode."
2815 :tag "Org Time"
2816 :group 'org)
2818 (defcustom org-insert-labeled-timestamps-at-point nil
2819 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2820 When nil, these labeled time stamps are forces into the second line of an
2821 entry, just after the headline. When scheduling from the global TODO list,
2822 the time stamp will always be forced into the second line."
2823 :group 'org-time
2824 :type 'boolean)
2826 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2827 "Formats for `format-time-string' which are used for time stamps.
2828 It is not recommended to change this constant.")
2830 (defcustom org-time-stamp-rounding-minutes '(0 5)
2831 "Number of minutes to round time stamps to.
2832 These are two values, the first applies when first creating a time stamp.
2833 The second applies when changing it with the commands `S-up' and `S-down'.
2834 When changing the time stamp, this means that it will change in steps
2835 of N minutes, as given by the second value.
2837 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2838 numbers should be factors of 60, so for example 5, 10, 15.
2840 When this is larger than 1, you can still force an exact time stamp by using
2841 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2842 and by using a prefix arg to `S-up/down' to specify the exact number
2843 of minutes to shift."
2844 :group 'org-time
2845 :get #'(lambda (var) ; Make sure both elements are there
2846 (if (integerp (default-value var))
2847 (list (default-value var) 5)
2848 (default-value var)))
2849 :type '(list
2850 (integer :tag "when inserting times")
2851 (integer :tag "when modifying times")))
2853 ;; Normalize old customizations of this variable.
2854 (when (integerp org-time-stamp-rounding-minutes)
2855 (setq org-time-stamp-rounding-minutes
2856 (list org-time-stamp-rounding-minutes
2857 org-time-stamp-rounding-minutes)))
2859 (defcustom org-display-custom-times nil
2860 "Non-nil means overlay custom formats over all time stamps.
2861 The formats are defined through the variable `org-time-stamp-custom-formats'.
2862 To turn this on on a per-file basis, insert anywhere in the file:
2863 #+STARTUP: customtime"
2864 :group 'org-time
2865 :set 'set-default
2866 :type 'sexp)
2867 (make-variable-buffer-local 'org-display-custom-times)
2869 (defcustom org-time-stamp-custom-formats
2870 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2871 "Custom formats for time stamps. See `format-time-string' for the syntax.
2872 These are overlaid over the default ISO format if the variable
2873 `org-display-custom-times' is set. Time like %H:%M should be at the
2874 end of the second format. The custom formats are also honored by export
2875 commands, if custom time display is turned on at the time of export."
2876 :group 'org-time
2877 :type 'sexp)
2879 (defun org-time-stamp-format (&optional long inactive)
2880 "Get the right format for a time string."
2881 (let ((f (if long (cdr org-time-stamp-formats)
2882 (car org-time-stamp-formats))))
2883 (if inactive
2884 (concat "[" (substring f 1 -1) "]")
2885 f)))
2887 (defcustom org-time-clocksum-format
2888 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2889 "The format string used when creating CLOCKSUM lines.
2890 This is also used when Org mode generates a time duration.
2892 The value can be a single format string containing two
2893 %-sequences, which will be filled with the number of hours and
2894 minutes in that order.
2896 Alternatively, the value can be a plist associating any of the
2897 keys :years, :months, :weeks, :days, :hours or :minutes with
2898 format strings. The time duration is formatted using only the
2899 time components that are needed and concatenating the results.
2900 If a time unit in absent, it falls back to the next smallest
2901 unit.
2903 The keys :require-years, :require-months, :require-days,
2904 :require-weeks, :require-hours, :require-minutes are also
2905 meaningful. A non-nil value for these keys indicates that the
2906 corresponding time component should always be included, even if
2907 its value is 0.
2910 For example,
2912 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2913 :require-minutes t)
2915 means durations longer than a day will be expressed in days,
2916 hours and minutes, and durations less than a day will always be
2917 expressed in hours and minutes (even for durations less than an
2918 hour).
2920 The value
2922 \(:days \"%dd\" :minutes \"%dm\")
2924 means durations longer than a day will be expressed in days and
2925 minutes, and durations less than a day will be expressed entirely
2926 in minutes (even for durations longer than an hour)."
2927 :group 'org-time
2928 :group 'org-clock
2929 :version "24.4"
2930 :package-version '(Org . "8.0")
2931 :type '(choice (string :tag "Format string")
2932 (set :tag "Plist"
2933 (group :inline t (const :tag "Years" :years)
2934 (string :tag "Format string"))
2935 (group :inline t
2936 (const :tag "Always show years" :require-years)
2937 (const t))
2938 (group :inline t (const :tag "Months" :months)
2939 (string :tag "Format string"))
2940 (group :inline t
2941 (const :tag "Always show months" :require-months)
2942 (const t))
2943 (group :inline t (const :tag "Weeks" :weeks)
2944 (string :tag "Format string"))
2945 (group :inline t
2946 (const :tag "Always show weeks" :require-weeks)
2947 (const t))
2948 (group :inline t (const :tag "Days" :days)
2949 (string :tag "Format string"))
2950 (group :inline t
2951 (const :tag "Always show days" :require-days)
2952 (const t))
2953 (group :inline t (const :tag "Hours" :hours)
2954 (string :tag "Format string"))
2955 (group :inline t
2956 (const :tag "Always show hours" :require-hours)
2957 (const t))
2958 (group :inline t (const :tag "Minutes" :minutes)
2959 (string :tag "Format string"))
2960 (group :inline t
2961 (const :tag "Always show minutes" :require-minutes)
2962 (const t)))))
2964 (defcustom org-time-clocksum-use-fractional nil
2965 "When non-nil, \\[org-clock-display] uses fractional times.
2966 See `org-time-clocksum-format' for more on time clock formats."
2967 :group 'org-time
2968 :group 'org-clock
2969 :version "24.3"
2970 :type 'boolean)
2972 (defcustom org-time-clocksum-use-effort-durations nil
2973 "When non-nil, \\[org-clock-display] uses effort durations.
2974 E.g. by default, one day is considered to be a 8 hours effort,
2975 so a task that has been clocked for 16 hours will be displayed
2976 as during 2 days in the clock display or in the clocktable.
2978 See `org-effort-durations' on how to set effort durations
2979 and `org-time-clocksum-format' for more on time clock formats."
2980 :group 'org-time
2981 :group 'org-clock
2982 :version "24.4"
2983 :package-version '(Org . "8.0")
2984 :type 'boolean)
2986 (defcustom org-time-clocksum-fractional-format "%.2f"
2987 "The format string used when creating CLOCKSUM lines,
2988 or when Org mode generates a time duration, if
2989 `org-time-clocksum-use-fractional' is enabled.
2991 The value can be a single format string containing one
2992 %-sequence, which will be filled with the number of hours as
2993 a float.
2995 Alternatively, the value can be a plist associating any of the
2996 keys :years, :months, :weeks, :days, :hours or :minutes with
2997 a format string. The time duration is formatted using the
2998 largest time unit which gives a non-zero integer part. If all
2999 specified formats have zero integer part, the smallest time unit
3000 is used."
3001 :group 'org-time
3002 :type '(choice (string :tag "Format string")
3003 (set (group :inline t (const :tag "Years" :years)
3004 (string :tag "Format string"))
3005 (group :inline t (const :tag "Months" :months)
3006 (string :tag "Format string"))
3007 (group :inline t (const :tag "Weeks" :weeks)
3008 (string :tag "Format string"))
3009 (group :inline t (const :tag "Days" :days)
3010 (string :tag "Format string"))
3011 (group :inline t (const :tag "Hours" :hours)
3012 (string :tag "Format string"))
3013 (group :inline t (const :tag "Minutes" :minutes)
3014 (string :tag "Format string")))))
3016 (defcustom org-deadline-warning-days 14
3017 "Number of days before expiration during which a deadline becomes active.
3018 This variable governs the display in sparse trees and in the agenda.
3019 When 0 or negative, it means use this number (the absolute value of it)
3020 even if a deadline has a different individual lead time specified.
3022 Custom commands can set this variable in the options section."
3023 :group 'org-time
3024 :group 'org-agenda-daily/weekly
3025 :type 'integer)
3027 (defcustom org-scheduled-delay-days 0
3028 "Number of days before a scheduled item becomes active.
3029 This variable governs the display in sparse trees and in the agenda.
3030 The default value (i.e. 0) means: don't delay scheduled item.
3031 When negative, it means use this number (the absolute value of it)
3032 even if a scheduled item has a different individual delay time
3033 specified.
3035 Custom commands can set this variable in the options section."
3036 :group 'org-time
3037 :group 'org-agenda-daily/weekly
3038 :version "24.4"
3039 :package-version '(Org . "8.0")
3040 :type 'integer)
3042 (defcustom org-read-date-prefer-future t
3043 "Non-nil means assume future for incomplete date input from user.
3044 This affects the following situations:
3045 1. The user gives a month but not a year.
3046 For example, if it is April and you enter \"feb 2\", this will be read
3047 as Feb 2, *next* year. \"May 5\", however, will be this year.
3048 2. The user gives a day, but no month.
3049 For example, if today is the 15th, and you enter \"3\", Org-mode will
3050 read this as the third of *next* month. However, if you enter \"17\",
3051 it will be considered as *this* month.
3053 If you set this variable to the symbol `time', then also the following
3054 will work:
3056 3. If the user gives a time.
3057 If the time is before now, it will be interpreted as tomorrow.
3059 Currently none of this works for ISO week specifications.
3061 When this option is nil, the current day, month and year will always be
3062 used as defaults.
3064 See also `org-agenda-jump-prefer-future'."
3065 :group 'org-time
3066 :type '(choice
3067 (const :tag "Never" nil)
3068 (const :tag "Check month and day" t)
3069 (const :tag "Check month, day, and time" time)))
3071 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3072 "Should the agenda jump command prefer the future for incomplete dates?
3073 The default is to do the same as configured in `org-read-date-prefer-future'.
3074 But you can also set a deviating value here.
3075 This may t or nil, or the symbol `org-read-date-prefer-future'."
3076 :group 'org-agenda
3077 :group 'org-time
3078 :version "24.1"
3079 :type '(choice
3080 (const :tag "Use org-read-date-prefer-future"
3081 org-read-date-prefer-future)
3082 (const :tag "Never" nil)
3083 (const :tag "Always" t)))
3085 (defcustom org-read-date-force-compatible-dates t
3086 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3088 Depending on the system Emacs is running on, certain dates cannot
3089 be represented with the type used internally to represent time.
3090 Dates between 1970-1-1 and 2038-1-1 can always be represented
3091 correctly. Some systems allow for earlier dates, some for later,
3092 some for both. One way to find out it to insert any date into an
3093 Org buffer, putting the cursor on the year and hitting S-up and
3094 S-down to test the range.
3096 When this variable is set to t, the date/time prompt will not let
3097 you specify dates outside the 1970-2037 range, so it is certain that
3098 these dates will work in whatever version of Emacs you are
3099 running, and also that you can move a file from one Emacs implementation
3100 to another. WHenever Org is forcing the year for you, it will display
3101 a message and beep.
3103 When this variable is nil, Org will check if the date is
3104 representable in the specific Emacs implementation you are using.
3105 If not, it will force a year, usually the current year, and beep
3106 to remind you. Currently this setting is not recommended because
3107 the likelihood that you will open your Org files in an Emacs that
3108 has limited date range is not negligible.
3110 A workaround for this problem is to use diary sexp dates for time
3111 stamps outside of this range."
3112 :group 'org-time
3113 :version "24.1"
3114 :type 'boolean)
3116 (defcustom org-read-date-display-live t
3117 "Non-nil means display current interpretation of date prompt live.
3118 This display will be in an overlay, in the minibuffer."
3119 :group 'org-time
3120 :type 'boolean)
3122 (defcustom org-read-date-popup-calendar t
3123 "Non-nil means pop up a calendar when prompting for a date.
3124 In the calendar, the date can be selected with mouse-1. However, the
3125 minibuffer will also be active, and you can simply enter the date as well.
3126 When nil, only the minibuffer will be available."
3127 :group 'org-time
3128 :type 'boolean)
3129 (org-defvaralias 'org-popup-calendar-for-date-prompt
3130 'org-read-date-popup-calendar)
3132 (make-obsolete-variable
3133 'org-read-date-minibuffer-setup-hook
3134 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3135 (defcustom org-read-date-minibuffer-setup-hook nil
3136 "Hook to be used to set up keys for the date/time interface.
3137 Add key definitions to `minibuffer-local-map', which will be a
3138 temporary copy.
3140 WARNING: This option is obsolete, you should use
3141 `org-read-date-minibuffer-local-map' to set up keys."
3142 :group 'org-time
3143 :type 'hook)
3145 (defcustom org-extend-today-until 0
3146 "The hour when your day really ends. Must be an integer.
3147 This has influence for the following applications:
3148 - When switching the agenda to \"today\". It it is still earlier than
3149 the time given here, the day recognized as TODAY is actually yesterday.
3150 - When a date is read from the user and it is still before the time given
3151 here, the current date and time will be assumed to be yesterday, 23:59.
3152 Also, timestamps inserted in capture templates follow this rule.
3154 IMPORTANT: This is a feature whose implementation is and likely will
3155 remain incomplete. Really, it is only here because past midnight seems to
3156 be the favorite working time of John Wiegley :-)"
3157 :group 'org-time
3158 :type 'integer)
3160 (defcustom org-use-effective-time nil
3161 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3162 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3163 \"effective time\" of any timestamps between midnight and 8am will be
3164 23:59 of the previous day."
3165 :group 'org-time
3166 :version "24.1"
3167 :type 'boolean)
3169 (defcustom org-use-last-clock-out-time-as-effective-time nil
3170 "When non-nil, use the last clock out time for `org-todo'.
3171 Note that this option has precedence over the combined use of
3172 `org-use-effective-time' and `org-extend-today-until'."
3173 :group 'org-time
3174 :version "24.4"
3175 :package-version '(Org . "8.0")
3176 :type 'boolean)
3178 (defcustom org-edit-timestamp-down-means-later nil
3179 "Non-nil means S-down will increase the time in a time stamp.
3180 When nil, S-up will increase."
3181 :group 'org-time
3182 :type 'boolean)
3184 (defcustom org-calendar-follow-timestamp-change t
3185 "Non-nil means make the calendar window follow timestamp changes.
3186 When a timestamp is modified and the calendar window is visible, it will be
3187 moved to the new date."
3188 :group 'org-time
3189 :type 'boolean)
3191 (defgroup org-tags nil
3192 "Options concerning tags in Org-mode."
3193 :tag "Org Tags"
3194 :group 'org)
3196 (defcustom org-tag-alist nil
3197 "List of tags allowed in Org-mode files.
3198 When this list is nil, Org-mode will base TAG input on what is already in the
3199 buffer.
3200 The value of this variable is an alist, the car of each entry must be a
3201 keyword as a string, the cdr may be a character that is used to select
3202 that tag through the fast-tag-selection interface.
3203 See the manual for details."
3204 :group 'org-tags
3205 :type '(repeat
3206 (choice
3207 (cons (string :tag "Tag name")
3208 (character :tag "Access char"))
3209 (list :tag "Start radio group"
3210 (const :startgroup)
3211 (option (string :tag "Group description")))
3212 (list :tag "Group tags delimiter"
3213 (const :grouptags))
3214 (list :tag "End radio group"
3215 (const :endgroup)
3216 (option (string :tag "Group description")))
3217 (const :tag "New line" (:newline)))))
3219 (defcustom org-tag-persistent-alist nil
3220 "List of tags that will always appear in all Org-mode files.
3221 This is in addition to any in buffer settings or customizations
3222 of `org-tag-alist'.
3223 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3224 The value of this variable is an alist, the car of each entry must be a
3225 keyword as a string, the cdr may be a character that is used to select
3226 that tag through the fast-tag-selection interface.
3227 See the manual for details.
3228 To disable these tags on a per-file basis, insert anywhere in the file:
3229 #+STARTUP: noptag"
3230 :group 'org-tags
3231 :type '(repeat
3232 (choice
3233 (cons (string :tag "Tag name")
3234 (character :tag "Access char"))
3235 (const :tag "Start radio group" (:startgroup))
3236 (const :tag "Group tags delimiter" (:grouptags))
3237 (const :tag "End radio group" (:endgroup))
3238 (const :tag "New line" (:newline)))))
3240 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3241 "If non-nil, always offer completion for all tags of all agenda files.
3242 Instead of customizing this variable directly, you might want to
3243 set it locally for capture buffers, because there no list of
3244 tags in that file can be created dynamically (there are none).
3246 (add-hook 'org-capture-mode-hook
3247 (lambda ()
3248 (set (make-local-variable
3249 'org-complete-tags-always-offer-all-agenda-tags)
3250 t)))"
3251 :group 'org-tags
3252 :version "24.1"
3253 :type 'boolean)
3255 (defvar org-file-tags nil
3256 "List of tags that can be inherited by all entries in the file.
3257 The tags will be inherited if the variable `org-use-tag-inheritance'
3258 says they should be.
3259 This variable is populated from #+FILETAGS lines.")
3261 (defcustom org-use-fast-tag-selection 'auto
3262 "Non-nil means use fast tag selection scheme.
3263 This is a special interface to select and deselect tags with single keys.
3264 When nil, fast selection is never used.
3265 When the symbol `auto', fast selection is used if and only if selection
3266 characters for tags have been configured, either through the variable
3267 `org-tag-alist' or through a #+TAGS line in the buffer.
3268 When t, fast selection is always used and selection keys are assigned
3269 automatically if necessary."
3270 :group 'org-tags
3271 :type '(choice
3272 (const :tag "Always" t)
3273 (const :tag "Never" nil)
3274 (const :tag "When selection characters are configured" 'auto)))
3276 (defcustom org-fast-tag-selection-single-key nil
3277 "Non-nil means fast tag selection exits after first change.
3278 When nil, you have to press RET to exit it.
3279 During fast tag selection, you can toggle this flag with `C-c'.
3280 This variable can also have the value `expert'. In this case, the window
3281 displaying the tags menu is not even shown, until you press C-c again."
3282 :group 'org-tags
3283 :type '(choice
3284 (const :tag "No" nil)
3285 (const :tag "Yes" t)
3286 (const :tag "Expert" expert)))
3288 (defvar org-fast-tag-selection-include-todo nil
3289 "Non-nil means fast tags selection interface will also offer TODO states.
3290 This is an undocumented feature, you should not rely on it.")
3292 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3293 "The column to which tags should be indented in a headline.
3294 If this number is positive, it specifies the column. If it is negative,
3295 it means that the tags should be flushright to that column. For example,
3296 -80 works well for a normal 80 character screen.
3297 When 0, place tags directly after headline text, with only one space in
3298 between."
3299 :group 'org-tags
3300 :type 'integer)
3302 (defcustom org-auto-align-tags t
3303 "Non-nil keeps tags aligned when modifying headlines.
3304 Some operations (i.e. demoting) change the length of a headline and
3305 therefore shift the tags around. With this option turned on, after
3306 each such operation the tags are again aligned to `org-tags-column'."
3307 :group 'org-tags
3308 :type 'boolean)
3310 (defcustom org-use-tag-inheritance t
3311 "Non-nil means tags in levels apply also for sublevels.
3312 When nil, only the tags directly given in a specific line apply there.
3313 This may also be a list of tags that should be inherited, or a regexp that
3314 matches tags that should be inherited. Additional control is possible
3315 with the variable `org-tags-exclude-from-inheritance' which gives an
3316 explicit list of tags to be excluded from inheritance, even if the value of
3317 `org-use-tag-inheritance' would select it for inheritance.
3319 If this option is t, a match early-on in a tree can lead to a large
3320 number of matches in the subtree when constructing the agenda or creating
3321 a sparse tree. If you only want to see the first match in a tree during
3322 a search, check out the variable `org-tags-match-list-sublevels'."
3323 :group 'org-tags
3324 :type '(choice
3325 (const :tag "Not" nil)
3326 (const :tag "Always" t)
3327 (repeat :tag "Specific tags" (string :tag "Tag"))
3328 (regexp :tag "Tags matched by regexp")))
3330 (defcustom org-tags-exclude-from-inheritance nil
3331 "List of tags that should never be inherited.
3332 This is a way to exclude a few tags from inheritance. For way to do
3333 the opposite, to actively allow inheritance for selected tags,
3334 see the variable `org-use-tag-inheritance'."
3335 :group 'org-tags
3336 :type '(repeat (string :tag "Tag")))
3338 (defun org-tag-inherit-p (tag)
3339 "Check if TAG is one that should be inherited."
3340 (cond
3341 ((member tag org-tags-exclude-from-inheritance) nil)
3342 ((eq org-use-tag-inheritance t) t)
3343 ((not org-use-tag-inheritance) nil)
3344 ((stringp org-use-tag-inheritance)
3345 (string-match org-use-tag-inheritance tag))
3346 ((listp org-use-tag-inheritance)
3347 (member tag org-use-tag-inheritance))
3348 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3350 (defcustom org-tags-match-list-sublevels t
3351 "Non-nil means list also sublevels of headlines matching a search.
3352 This variable applies to tags/property searches, and also to stuck
3353 projects because this search is based on a tags match as well.
3355 When set to the symbol `indented', sublevels are indented with
3356 leading dots.
3358 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3359 the sublevels of a headline matching a tag search often also match
3360 the same search. Listing all of them can create very long lists.
3361 Setting this variable to nil causes subtrees of a match to be skipped.
3363 This variable is semi-obsolete and probably should always be true. It
3364 is better to limit inheritance to certain tags using the variables
3365 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3366 :group 'org-tags
3367 :type '(choice
3368 (const :tag "No, don't list them" nil)
3369 (const :tag "Yes, do list them" t)
3370 (const :tag "List them, indented with leading dots" indented)))
3372 (defcustom org-tags-sort-function nil
3373 "When set, tags are sorted using this function as a comparator."
3374 :group 'org-tags
3375 :type '(choice
3376 (const :tag "No sorting" nil)
3377 (const :tag "Alphabetical" string<)
3378 (const :tag "Reverse alphabetical" string>)
3379 (function :tag "Custom function" nil)))
3381 (defvar org-tags-history nil
3382 "History of minibuffer reads for tags.")
3383 (defvar org-last-tags-completion-table nil
3384 "The last used completion table for tags.")
3385 (defvar org-after-tags-change-hook nil
3386 "Hook that is run after the tags in a line have changed.")
3388 (defgroup org-properties nil
3389 "Options concerning properties in Org-mode."
3390 :tag "Org Properties"
3391 :group 'org)
3393 (defcustom org-property-format "%-10s %s"
3394 "How property key/value pairs should be formatted by `indent-line'.
3395 When `indent-line' hits a property definition, it will format the line
3396 according to this format, mainly to make sure that the values are
3397 lined-up with respect to each other."
3398 :group 'org-properties
3399 :type 'string)
3401 (defcustom org-properties-postprocess-alist nil
3402 "Alist of properties and functions to adjust inserted values.
3403 Elements of this alist must be of the form
3405 ([string] [function])
3407 where [string] must be a property name and [function] must be a
3408 lambda expression: this lambda expression must take one argument,
3409 the value to adjust, and return the new value as a string.
3411 For example, this element will allow the property \"Remaining\"
3412 to be updated wrt the relation between the \"Effort\" property
3413 and the clock summary:
3415 ((\"Remaining\" (lambda(value)
3416 (let ((clocksum (org-clock-sum-current-item))
3417 (effort (org-duration-string-to-minutes
3418 (org-entry-get (point) \"Effort\"))))
3419 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3420 :group 'org-properties
3421 :version "24.1"
3422 :type '(alist :key-type (string :tag "Property")
3423 :value-type (function :tag "Function")))
3425 (defcustom org-use-property-inheritance nil
3426 "Non-nil means properties apply also for sublevels.
3428 This setting is chiefly used during property searches. Turning it on can
3429 cause significant overhead when doing a search, which is why it is not
3430 on by default.
3432 When nil, only the properties directly given in the current entry count.
3433 When t, every property is inherited. The value may also be a list of
3434 properties that should have inheritance, or a regular expression matching
3435 properties that should be inherited.
3437 However, note that some special properties use inheritance under special
3438 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3439 and the properties ending in \"_ALL\" when they are used as descriptor
3440 for valid values of a property.
3442 Note for programmers:
3443 When querying an entry with `org-entry-get', you can control if inheritance
3444 should be used. By default, `org-entry-get' looks only at the local
3445 properties. You can request inheritance by setting the inherit argument
3446 to t (to force inheritance) or to `selective' (to respect the setting
3447 in this variable)."
3448 :group 'org-properties
3449 :type '(choice
3450 (const :tag "Not" nil)
3451 (const :tag "Always" t)
3452 (repeat :tag "Specific properties" (string :tag "Property"))
3453 (regexp :tag "Properties matched by regexp")))
3455 (defun org-property-inherit-p (property)
3456 "Check if PROPERTY is one that should be inherited."
3457 (cond
3458 ((eq org-use-property-inheritance t) t)
3459 ((not org-use-property-inheritance) nil)
3460 ((stringp org-use-property-inheritance)
3461 (string-match org-use-property-inheritance property))
3462 ((listp org-use-property-inheritance)
3463 (member property org-use-property-inheritance))
3464 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3466 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3467 "The default column format, if no other format has been defined.
3468 This variable can be set on the per-file basis by inserting a line
3470 #+COLUMNS: %25ITEM ....."
3471 :group 'org-properties
3472 :type 'string)
3474 (defcustom org-columns-ellipses ".."
3475 "The ellipses to be used when a field in column view is truncated.
3476 When this is the empty string, as many characters as possible are shown,
3477 but then there will be no visual indication that the field has been truncated.
3478 When this is a string of length N, the last N characters of a truncated
3479 field are replaced by this string. If the column is narrower than the
3480 ellipses string, only part of the ellipses string will be shown."
3481 :group 'org-properties
3482 :type 'string)
3484 (defcustom org-columns-modify-value-for-display-function nil
3485 "Function that modifies values for display in column view.
3486 For example, it can be used to cut out a certain part from a time stamp.
3487 The function must take 2 arguments:
3489 column-title The title of the column (*not* the property name)
3490 value The value that should be modified.
3492 The function should return the value that should be displayed,
3493 or nil if the normal value should be used."
3494 :group 'org-properties
3495 :type 'function)
3497 (defcustom org-effort-property "Effort"
3498 "The property that is being used to keep track of effort estimates.
3499 Effort estimates given in this property need to have the format H:MM."
3500 :group 'org-properties
3501 :group 'org-progress
3502 :type '(string :tag "Property"))
3504 (defconst org-global-properties-fixed
3505 '(("VISIBILITY_ALL" . "folded children content all")
3506 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3507 "List of property/value pairs that can be inherited by any entry.
3509 These are fixed values, for the preset properties. The user variable
3510 that can be used to add to this list is `org-global-properties'.
3512 The entries in this list are cons cells where the car is a property
3513 name and cdr is a string with the value. If the value represents
3514 multiple items like an \"_ALL\" property, separate the items by
3515 spaces.")
3517 (defcustom org-global-properties nil
3518 "List of property/value pairs that can be inherited by any entry.
3520 This list will be combined with the constant `org-global-properties-fixed'.
3522 The entries in this list are cons cells where the car is a property
3523 name and cdr is a string with the value.
3525 You can set buffer-local values for the same purpose in the variable
3526 `org-file-properties' this by adding lines like
3528 #+PROPERTY: NAME VALUE"
3529 :group 'org-properties
3530 :type '(repeat
3531 (cons (string :tag "Property")
3532 (string :tag "Value"))))
3534 (defvar org-file-properties nil
3535 "List of property/value pairs that can be inherited by any entry.
3536 Valid for the current buffer.
3537 This variable is populated from #+PROPERTY lines.")
3538 (make-variable-buffer-local 'org-file-properties)
3540 (defgroup org-agenda nil
3541 "Options concerning agenda views in Org-mode."
3542 :tag "Org Agenda"
3543 :group 'org)
3545 (defvar org-category nil
3546 "Variable used by org files to set a category for agenda display.
3547 Such files should use a file variable to set it, for example
3549 # -*- mode: org; org-category: \"ELisp\"
3551 or contain a special line
3553 #+CATEGORY: ELisp
3555 If the file does not specify a category, then file's base name
3556 is used instead.")
3557 (make-variable-buffer-local 'org-category)
3558 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3560 (defcustom org-agenda-files nil
3561 "The files to be used for agenda display.
3562 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3563 \\[org-remove-file]. You can also use customize to edit the list.
3565 If an entry is a directory, all files in that directory that are matched by
3566 `org-agenda-file-regexp' will be part of the file list.
3568 If the value of the variable is not a list but a single file name, then
3569 the list of agenda files is actually stored and maintained in that file, one
3570 agenda file per line. In this file paths can be given relative to
3571 `org-directory'. Tilde expansion and environment variable substitution
3572 are also made."
3573 :group 'org-agenda
3574 :type '(choice
3575 (repeat :tag "List of files and directories" file)
3576 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3578 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3579 "Regular expression to match files for `org-agenda-files'.
3580 If any element in the list in that variable contains a directory instead
3581 of a normal file, all files in that directory that are matched by this
3582 regular expression will be included."
3583 :group 'org-agenda
3584 :type 'regexp)
3586 (defcustom org-agenda-text-search-extra-files nil
3587 "List of extra files to be searched by text search commands.
3588 These files will be searched in addition to the agenda files by the
3589 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3590 Note that these files will only be searched for text search commands,
3591 not for the other agenda views like todo lists, tag searches or the weekly
3592 agenda. This variable is intended to list notes and possibly archive files
3593 that should also be searched by these two commands.
3594 In fact, if the first element in the list is the symbol `agenda-archives',
3595 then all archive files of all agenda files will be added to the search
3596 scope."
3597 :group 'org-agenda
3598 :type '(set :greedy t
3599 (const :tag "Agenda Archives" agenda-archives)
3600 (repeat :inline t (file))))
3602 (org-defvaralias 'org-agenda-multi-occur-extra-files
3603 'org-agenda-text-search-extra-files)
3605 (defcustom org-agenda-skip-unavailable-files nil
3606 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3607 A nil value means to remove them, after a query, from the list."
3608 :group 'org-agenda
3609 :type 'boolean)
3611 (defcustom org-calendar-to-agenda-key [?c]
3612 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3613 The command `org-calendar-goto-agenda' will be bound to this key. The
3614 default is the character `c' because then `c' can be used to switch back and
3615 forth between agenda and calendar."
3616 :group 'org-agenda
3617 :type 'sexp)
3619 (defcustom org-calendar-insert-diary-entry-key [?i]
3620 "The key to be installed in `calendar-mode-map' for adding diary entries.
3621 This option is irrelevant until `org-agenda-diary-file' has been configured
3622 to point to an Org-mode file. When that is the case, the command
3623 `org-agenda-diary-entry' will be bound to the key given here, by default
3624 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3625 if you want to continue doing this, you need to change this to a different
3626 key."
3627 :group 'org-agenda
3628 :type 'sexp)
3630 (defcustom org-agenda-diary-file 'diary-file
3631 "File to which to add new entries with the `i' key in agenda and calendar.
3632 When this is the symbol `diary-file', the functionality in the Emacs
3633 calendar will be used to add entries to the `diary-file'. But when this
3634 points to a file, `org-agenda-diary-entry' will be used instead."
3635 :group 'org-agenda
3636 :type '(choice
3637 (const :tag "The standard Emacs diary file" diary-file)
3638 (file :tag "Special Org file diary entries")))
3640 (eval-after-load "calendar"
3641 '(progn
3642 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3643 'org-calendar-goto-agenda)
3644 (add-hook 'calendar-mode-hook
3645 (lambda ()
3646 (unless (eq org-agenda-diary-file 'diary-file)
3647 (define-key calendar-mode-map
3648 org-calendar-insert-diary-entry-key
3649 'org-agenda-diary-entry))))))
3651 (defgroup org-latex nil
3652 "Options for embedding LaTeX code into Org-mode."
3653 :tag "Org LaTeX"
3654 :group 'org)
3656 (defcustom org-format-latex-options
3657 '(:foreground default :background default :scale 1.0
3658 :html-foreground "Black" :html-background "Transparent"
3659 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3660 "Options for creating images from LaTeX fragments.
3661 This is a property list with the following properties:
3662 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3663 `default' means use the foreground of the default face.
3664 `auto' means use the foreground from the text face.
3665 :background the background color, or \"Transparent\".
3666 `default' means use the background of the default face.
3667 `auto' means use the background from the text face.
3668 :scale a scaling factor for the size of the images, to get more pixels
3669 :html-foreground, :html-background, :html-scale
3670 the same numbers for HTML export.
3671 :matchers a list indicating which matchers should be used to
3672 find LaTeX fragments. Valid members of this list are:
3673 \"begin\" find environments
3674 \"$1\" find single characters surrounded by $.$
3675 \"$\" find math expressions surrounded by $...$
3676 \"$$\" find math expressions surrounded by $$....$$
3677 \"\\(\" find math expressions surrounded by \\(...\\)
3678 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3679 :group 'org-latex
3680 :type 'plist)
3682 (defcustom org-format-latex-signal-error t
3683 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3684 When nil, just push out a message."
3685 :group 'org-latex
3686 :version "24.1"
3687 :type 'boolean)
3689 (defcustom org-latex-to-mathml-jar-file nil
3690 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3691 Use this to specify additional executable file say a jar file.
3693 When using MathToWeb as the converter, specify the full-path to
3694 your mathtoweb.jar file."
3695 :group 'org-latex
3696 :version "24.1"
3697 :type '(choice
3698 (const :tag "None" nil)
3699 (file :tag "JAR file" :must-match t)))
3701 (defcustom org-latex-to-mathml-convert-command nil
3702 "Command to convert LaTeX fragments to MathML.
3703 Replace format-specifiers in the command as noted below and use
3704 `shell-command' to convert LaTeX to MathML.
3705 %j: Executable file in fully expanded form as specified by
3706 `org-latex-to-mathml-jar-file'.
3707 %I: Input LaTeX file in fully expanded form
3708 %o: Output MathML file
3709 This command is used by `org-create-math-formula'.
3711 When using MathToWeb as the converter, set this to
3712 \"java -jar %j -unicode -force -df %o %I\"."
3713 :group 'org-latex
3714 :version "24.1"
3715 :type '(choice
3716 (const :tag "None" nil)
3717 (string :tag "\nShell command")))
3719 (defcustom org-latex-create-formula-image-program 'dvipng
3720 "Program to convert LaTeX fragments with.
3722 dvipng Process the LaTeX fragments to dvi file, then convert
3723 dvi files to png files using dvipng.
3724 This will also include processing of non-math environments.
3725 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3726 to convert pdf files to png files"
3727 :group 'org-latex
3728 :version "24.1"
3729 :type '(choice
3730 (const :tag "dvipng" dvipng)
3731 (const :tag "imagemagick" imagemagick)))
3733 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3734 "Path to store latex preview images.
3735 A relative path here creates many directories relative to the
3736 processed org files paths. An absolute path puts all preview
3737 images at the same place."
3738 :group 'org-latex
3739 :version "24.3"
3740 :type 'string)
3742 (defun org-format-latex-mathml-available-p ()
3743 "Return t if `org-latex-to-mathml-convert-command' is usable."
3744 (save-match-data
3745 (when (and (boundp 'org-latex-to-mathml-convert-command)
3746 org-latex-to-mathml-convert-command)
3747 (let ((executable (car (split-string
3748 org-latex-to-mathml-convert-command))))
3749 (when (executable-find executable)
3750 (if (string-match
3751 "%j" org-latex-to-mathml-convert-command)
3752 (file-readable-p org-latex-to-mathml-jar-file)
3753 t))))))
3755 (defcustom org-format-latex-header "\\documentclass{article}
3756 \\usepackage[usenames]{color}
3757 \\usepackage{amsmath}
3758 \\usepackage[mathscr]{eucal}
3759 \\pagestyle{empty} % do not remove
3760 \[PACKAGES]
3761 \[DEFAULT-PACKAGES]
3762 % The settings below are copied from fullpage.sty
3763 \\setlength{\\textwidth}{\\paperwidth}
3764 \\addtolength{\\textwidth}{-3cm}
3765 \\setlength{\\oddsidemargin}{1.5cm}
3766 \\addtolength{\\oddsidemargin}{-2.54cm}
3767 \\setlength{\\evensidemargin}{\\oddsidemargin}
3768 \\setlength{\\textheight}{\\paperheight}
3769 \\addtolength{\\textheight}{-\\headheight}
3770 \\addtolength{\\textheight}{-\\headsep}
3771 \\addtolength{\\textheight}{-\\footskip}
3772 \\addtolength{\\textheight}{-3cm}
3773 \\setlength{\\topmargin}{1.5cm}
3774 \\addtolength{\\topmargin}{-2.54cm}"
3775 "The document header used for processing LaTeX fragments.
3776 It is imperative that this header make sure that no page number
3777 appears on the page. The package defined in the variables
3778 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3779 will either replace the placeholder \"[PACKAGES]\" in this
3780 header, or they will be appended."
3781 :group 'org-latex
3782 :type 'string)
3784 (defun org-set-packages-alist (var val)
3785 "Set the packages alist and make sure it has 3 elements per entry."
3786 (set var (mapcar (lambda (x)
3787 (if (and (consp x) (= (length x) 2))
3788 (list (car x) (nth 1 x) t)
3790 val)))
3792 (defun org-get-packages-alist (var)
3793 "Get the packages alist and make sure it has 3 elements per entry."
3794 (mapcar (lambda (x)
3795 (if (and (consp x) (= (length x) 2))
3796 (list (car x) (nth 1 x) t)
3798 (default-value var)))
3800 (defcustom org-latex-default-packages-alist
3801 '(("AUTO" "inputenc" t)
3802 ("T1" "fontenc" t)
3803 ("" "fixltx2e" nil)
3804 ("" "graphicx" t)
3805 ("" "longtable" nil)
3806 ("" "float" nil)
3807 ("" "wrapfig" nil)
3808 ("normalem" "ulem" t)
3809 ("" "textcomp" t)
3810 ("" "marvosym" t)
3811 ("" "wasysym" t)
3812 ("" "latexsym" t)
3813 ("" "amssymb" t)
3814 ("" "amstext" nil)
3815 ("" "hyperref" nil)
3816 "\\tolerance=1000")
3817 "Alist of default packages to be inserted in the header.
3819 Change this only if one of the packages here causes an
3820 incompatibility with another package you are using.
3822 The packages in this list are needed by one part or another of
3823 Org mode to function properly:
3825 - inputenc, fontenc: for basic font and character selection
3826 - amstext: for subscript and superscript
3827 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3828 symbols used for interpreting the entities in `org-entities'.
3829 You can skip some of these packages if you don't use any of the
3830 symbols in it.
3831 - ulem: for underline and strike-through
3832 - graphicx: for including images
3833 - float, wrapfig: for figure placement
3834 - longtable: for long tables
3835 - hyperref: for cross references
3837 Therefore you should not modify this variable unless you know
3838 what you are doing. The one reason to change it anyway is that
3839 you might be loading some other package that conflicts with one
3840 of the default packages. Each cell is of the format
3841 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3842 the package also needs to be included when compiling LaTeX
3843 snippets into images for inclusion into non-LaTeX output."
3844 :group 'org-latex
3845 :group 'org-export-latex
3846 :set 'org-set-packages-alist
3847 :get 'org-get-packages-alist
3848 :version "24.1"
3849 :type '(repeat
3850 (choice
3851 (list :tag "options/package pair"
3852 (string :tag "options")
3853 (string :tag "package")
3854 (boolean :tag "Snippet"))
3855 (string :tag "A line of LaTeX"))))
3857 (defcustom org-latex-packages-alist nil
3858 "Alist of packages to be inserted in every LaTeX header.
3860 These will be inserted after `org-latex-default-packages-alist'.
3861 Each cell is of the format:
3863 \(\"options\" \"package\" snippet-flag)
3865 SNIPPET-FLAG, when t, indicates that this package is also needed
3866 when turning LaTeX snippets into images for inclusion into
3867 non-LaTeX output.
3869 Make sure that you only list packages here which:
3871 - you want in every file
3872 - do not conflict with the setup in `org-format-latex-header'.
3873 - do not conflict with the default packages in
3874 `org-latex-default-packages-alist'."
3875 :group 'org-latex
3876 :group 'org-export-latex
3877 :set 'org-set-packages-alist
3878 :get 'org-get-packages-alist
3879 :type '(repeat
3880 (choice
3881 (list :tag "options/package pair"
3882 (string :tag "options")
3883 (string :tag "package")
3884 (boolean :tag "Snippet"))
3885 (string :tag "A line of LaTeX"))))
3887 (defgroup org-appearance nil
3888 "Settings for Org-mode appearance."
3889 :tag "Org Appearance"
3890 :group 'org)
3892 (defcustom org-level-color-stars-only nil
3893 "Non-nil means fontify only the stars in each headline.
3894 When nil, the entire headline is fontified.
3895 Changing it requires restart of `font-lock-mode' to become effective
3896 also in regions already fontified."
3897 :group 'org-appearance
3898 :type 'boolean)
3900 (defcustom org-hide-leading-stars nil
3901 "Non-nil means hide the first N-1 stars in a headline.
3902 This works by using the face `org-hide' for these stars. This
3903 face is white for a light background, and black for a dark
3904 background. You may have to customize the face `org-hide' to
3905 make this work.
3906 Changing it requires restart of `font-lock-mode' to become effective
3907 also in regions already fontified.
3908 You may also set this on a per-file basis by adding one of the following
3909 lines to the buffer:
3911 #+STARTUP: hidestars
3912 #+STARTUP: showstars"
3913 :group 'org-appearance
3914 :type 'boolean)
3916 (defcustom org-hidden-keywords nil
3917 "List of symbols corresponding to keywords to be hidden the org buffer.
3918 For example, a value '(title) for this list will make the document's title
3919 appear in the buffer without the initial #+TITLE: keyword."
3920 :group 'org-appearance
3921 :version "24.1"
3922 :type '(set (const :tag "#+AUTHOR" author)
3923 (const :tag "#+DATE" date)
3924 (const :tag "#+EMAIL" email)
3925 (const :tag "#+TITLE" title)))
3927 (defcustom org-custom-properties nil
3928 "List of properties (as strings) with a special meaning.
3929 The default use of these custom properties is to let the user
3930 hide them with `org-toggle-custom-properties-visibility'."
3931 :group 'org-properties
3932 :group 'org-appearance
3933 :version "24.3"
3934 :type '(repeat (string :tag "Property Name")))
3936 (defcustom org-fontify-done-headline nil
3937 "Non-nil means change the face of a headline if it is marked DONE.
3938 Normally, only the TODO/DONE keyword indicates the state of a headline.
3939 When this is non-nil, the headline after the keyword is set to the
3940 `org-headline-done' as an additional indication."
3941 :group 'org-appearance
3942 :type 'boolean)
3944 (defcustom org-fontify-emphasized-text t
3945 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3946 Changing this variable requires a restart of Emacs to take effect."
3947 :group 'org-appearance
3948 :type 'boolean)
3950 (defcustom org-fontify-whole-heading-line nil
3951 "Non-nil means fontify the whole line for headings.
3952 This is useful when setting a background color for the
3953 org-level-* faces."
3954 :group 'org-appearance
3955 :type 'boolean)
3957 (defcustom org-highlight-latex-and-related nil
3958 "Non-nil means highlight LaTeX related syntax in the buffer.
3959 When non nil, the value should be a list containing any of the
3960 following symbols:
3961 `latex' Highlight LaTeX snippets and environments.
3962 `script' Highlight subscript and superscript.
3963 `entities' Highlight entities."
3964 :group 'org-appearance
3965 :version "24.4"
3966 :package-version '(Org . "8.0")
3967 :type '(choice
3968 (const :tag "No highlighting" nil)
3969 (set :greedy t :tag "Highlight"
3970 (const :tag "LaTeX snippets and environments" latex)
3971 (const :tag "Subscript and superscript" script)
3972 (const :tag "Entities" entities))))
3974 (defcustom org-hide-emphasis-markers nil
3975 "Non-nil mean font-lock should hide the emphasis marker characters."
3976 :group 'org-appearance
3977 :type 'boolean)
3979 (defcustom org-pretty-entities nil
3980 "Non-nil means show entities as UTF8 characters.
3981 When nil, the \\name form remains in the buffer."
3982 :group 'org-appearance
3983 :version "24.1"
3984 :type 'boolean)
3986 (defcustom org-pretty-entities-include-sub-superscripts t
3987 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3988 :group 'org-appearance
3989 :version "24.1"
3990 :type 'boolean)
3992 (defvar org-emph-re nil
3993 "Regular expression for matching emphasis.
3994 After a match, the match groups contain these elements:
3995 0 The match of the full regular expression, including the characters
3996 before and after the proper match
3997 1 The character before the proper match, or empty at beginning of line
3998 2 The proper match, including the leading and trailing markers
3999 3 The leading marker like * or /, indicating the type of highlighting
4000 4 The text between the emphasis markers, not including the markers
4001 5 The character after the match, empty at the end of a line")
4002 (defvar org-verbatim-re nil
4003 "Regular expression for matching verbatim text.")
4004 (defvar org-emphasis-regexp-components) ; defined just below
4005 (defvar org-emphasis-alist) ; defined just below
4006 (defun org-set-emph-re (var val)
4007 "Set variable and compute the emphasis regular expression."
4008 (set var val)
4009 (when (and (boundp 'org-emphasis-alist)
4010 (boundp 'org-emphasis-regexp-components)
4011 org-emphasis-alist org-emphasis-regexp-components)
4012 (let* ((e org-emphasis-regexp-components)
4013 (pre (car e))
4014 (post (nth 1 e))
4015 (border (nth 2 e))
4016 (body (nth 3 e))
4017 (nl (nth 4 e))
4018 (body1 (concat body "*?"))
4019 (markers (mapconcat 'car org-emphasis-alist ""))
4020 (vmarkers (mapconcat
4021 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4022 org-emphasis-alist "")))
4023 ;; make sure special characters appear at the right position in the class
4024 (if (string-match "\\^" markers)
4025 (setq markers (concat (replace-match "" t t markers) "^")))
4026 (if (string-match "-" markers)
4027 (setq markers (concat (replace-match "" t t markers) "-")))
4028 (if (string-match "\\^" vmarkers)
4029 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4030 (if (string-match "-" vmarkers)
4031 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4032 (if (> nl 0)
4033 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4034 (int-to-string nl) "\\}")))
4035 ;; Make the regexp
4036 (setq org-emph-re
4037 (concat "\\([" pre "]\\|^\\)"
4038 "\\("
4039 "\\([" markers "]\\)"
4040 "\\("
4041 "[^" border "]\\|"
4042 "[^" border "]"
4043 body1
4044 "[^" border "]"
4045 "\\)"
4046 "\\3\\)"
4047 "\\([" post "]\\|$\\)"))
4048 (setq org-verbatim-re
4049 (concat "\\([" pre "]\\|^\\)"
4050 "\\("
4051 "\\([" vmarkers "]\\)"
4052 "\\("
4053 "[^" border "]\\|"
4054 "[^" border "]"
4055 body1
4056 "[^" border "]"
4057 "\\)"
4058 "\\3\\)"
4059 "\\([" post "]\\|$\\)")))))
4061 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4062 ;; set this option proved cumbersome. See this message/thread:
4063 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4064 (defvar org-emphasis-regexp-components
4065 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4066 "Components used to build the regular expression for emphasis.
4067 This is a list with five entries. Terminology: In an emphasis string
4068 like \" *strong word* \", we call the initial space PREMATCH, the final
4069 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4070 and \"trong wor\" is the body. The different components in this variable
4071 specify what is allowed/forbidden in each part:
4073 pre Chars allowed as prematch. Beginning of line will be allowed too.
4074 post Chars allowed as postmatch. End of line will be allowed too.
4075 border The chars *forbidden* as border characters.
4076 body-regexp A regexp like \".\" to match a body character. Don't use
4077 non-shy groups here, and don't allow newline here.
4078 newline The maximum number of newlines allowed in an emphasis exp.
4080 You need to reload Org or to restart Emacs after customizing this.")
4082 (defcustom org-emphasis-alist
4083 `(("*" bold)
4084 ("/" italic)
4085 ("_" underline)
4086 ("=" org-code verbatim)
4087 ("~" org-verbatim verbatim)
4088 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4089 "Alist of characters and faces to emphasize text.
4090 Text starting and ending with a special character will be emphasized,
4091 for example *bold*, _underlined_ and /italic/. This variable sets the
4092 marker characters and the face to be used by font-lock for highlighting
4093 in Org-mode Emacs buffers.
4095 You need to reload Org or to restart Emacs after customizing this."
4096 :group 'org-appearance
4097 :set 'org-set-emph-re
4098 :version "24.4"
4099 :package-version '(Org . "8.0")
4100 :type '(repeat
4101 (list
4102 (string :tag "Marker character")
4103 (choice
4104 (face :tag "Font-lock-face")
4105 (plist :tag "Face property list"))
4106 (option (const verbatim)))))
4108 (defvar org-protecting-blocks
4109 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4110 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4111 This is needed for font-lock setup.")
4113 ;;; Miscellaneous options
4115 (defgroup org-completion nil
4116 "Completion in Org-mode."
4117 :tag "Org Completion"
4118 :group 'org)
4120 (defcustom org-completion-use-ido nil
4121 "Non-nil means use ido completion wherever possible.
4122 Note that `ido-mode' must be active for this variable to be relevant.
4123 If you decide to turn this variable on, you might well want to turn off
4124 `org-outline-path-complete-in-steps'.
4125 See also `org-completion-use-iswitchb'."
4126 :group 'org-completion
4127 :type 'boolean)
4129 (defcustom org-completion-use-iswitchb nil
4130 "Non-nil means use iswitchb completion wherever possible.
4131 Note that `iswitchb-mode' must be active for this variable to be relevant.
4132 If you decide to turn this variable on, you might well want to turn off
4133 `org-outline-path-complete-in-steps'.
4134 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4135 :group 'org-completion
4136 :type 'boolean)
4138 (defcustom org-completion-fallback-command 'hippie-expand
4139 "The expansion command called by \\[pcomplete] in normal context.
4140 Normal means, no org-mode-specific context."
4141 :group 'org-completion
4142 :type 'function)
4144 ;;; Functions and variables from their packages
4145 ;; Declared here to avoid compiler warnings
4147 ;; XEmacs only
4148 (defvar outline-mode-menu-heading)
4149 (defvar outline-mode-menu-show)
4150 (defvar outline-mode-menu-hide)
4151 (defvar zmacs-regions) ; XEmacs regions
4153 ;; Emacs only
4154 (defvar mark-active)
4156 ;; Various packages
4157 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4158 (declare-function calendar-forward-day "cal-move" (arg))
4159 (declare-function calendar-goto-date "cal-move" (date))
4160 (declare-function calendar-goto-today "cal-move" ())
4161 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4162 (defvar calc-embedded-close-formula)
4163 (defvar calc-embedded-open-formula)
4164 (declare-function cdlatex-tab "ext:cdlatex" ())
4165 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4166 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4167 (defvar font-lock-unfontify-region-function)
4168 (declare-function iswitchb-read-buffer "iswitchb"
4169 (prompt &optional default require-match start matches-set))
4170 (defvar iswitchb-temp-buflist)
4171 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4172 (defvar org-agenda-tags-todo-honor-ignore-options)
4173 (declare-function org-agenda-skip "org-agenda" ())
4174 (declare-function
4175 org-agenda-format-item "org-agenda"
4176 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4177 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4178 (declare-function org-agenda-change-all-lines "org-agenda"
4179 (newhead hdmarker &optional fixface just-this))
4180 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4181 (declare-function org-agenda-maybe-redo "org-agenda" ())
4182 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4183 (beg end))
4184 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4185 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4186 "org-agenda" (&optional end))
4187 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4188 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4189 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4190 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4191 (declare-function org-indent-mode "org-indent" (&optional arg))
4192 (declare-function parse-time-string "parse-time" (string))
4193 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4194 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4195 (defvar remember-data-file)
4196 (defvar texmathp-why)
4197 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4198 (declare-function table--at-cell-p "table" (position &optional object at-column))
4200 (defvar org-latex-regexps)
4202 ;;; Autoload and prepare some org modules
4204 ;; Some table stuff that needs to be defined here, because it is used
4205 ;; by the functions setting up org-mode or checking for table context.
4207 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4208 "Detect an org-type or table-type table.")
4209 (defconst org-table-line-regexp "^[ \t]*|"
4210 "Detect an org-type table line.")
4211 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4212 "Detect an org-type table line.")
4213 (defconst org-table-hline-regexp "^[ \t]*|-"
4214 "Detect an org-type table hline.")
4215 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4216 "Detect a table-type table hline.")
4217 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4218 "Detect the first line outside a table when searching from within it.
4219 This works for both table types.")
4221 ;; Autoload the functions in org-table.el that are needed by functions here.
4223 (eval-and-compile
4224 (org-autoload "org-table"
4225 '(org-table-begin org-table-blank-field org-table-end)))
4227 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4228 "Detect a #+TBLFM line.")
4230 ;;;###autoload
4231 (defun turn-on-orgtbl ()
4232 "Unconditionally turn on `orgtbl-mode'."
4233 (require 'org-table)
4234 (orgtbl-mode 1))
4236 (defun org-at-table-p (&optional table-type)
4237 "Return t if the cursor is inside an org-type table.
4238 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4239 (if org-enable-table-editor
4240 (save-excursion
4241 (beginning-of-line 1)
4242 (looking-at (if table-type org-table-any-line-regexp
4243 org-table-line-regexp)))
4244 nil))
4245 (defsubst org-table-p () (org-at-table-p))
4247 (defun org-at-table.el-p ()
4248 "Return t if and only if we are at a table.el table."
4249 (and (org-at-table-p 'any)
4250 (save-excursion
4251 (goto-char (org-table-begin 'any))
4252 (looking-at org-table1-hline-regexp))))
4254 (defun org-table-recognize-table.el ()
4255 "If there is a table.el table nearby, recognize it and move into it."
4256 (if org-table-tab-recognizes-table.el
4257 (if (org-at-table.el-p)
4258 (progn
4259 (beginning-of-line 1)
4260 (if (looking-at org-table-dataline-regexp)
4262 (if (looking-at org-table1-hline-regexp)
4263 (progn
4264 (beginning-of-line 2)
4265 (if (looking-at org-table-any-border-regexp)
4266 (beginning-of-line -1)))))
4267 (if (re-search-forward "|" (org-table-end t) t)
4268 (progn
4269 (require 'table)
4270 (if (table--at-cell-p (point))
4272 (message "recognizing table.el table...")
4273 (table-recognize-table)
4274 (message "recognizing table.el table...done")))
4275 (error "This should not happen"))
4277 nil)
4278 nil))
4280 (defun org-at-table-hline-p ()
4281 "Return t if the cursor is inside a hline in a table."
4282 (if org-enable-table-editor
4283 (save-excursion
4284 (beginning-of-line 1)
4285 (looking-at org-table-hline-regexp))
4286 nil))
4288 (defvar org-table-clean-did-remove-column nil)
4289 (defun org-table-map-tables (function &optional quietly)
4290 "Apply FUNCTION to the start of all tables in the buffer."
4291 (save-excursion
4292 (save-restriction
4293 (widen)
4294 (goto-char (point-min))
4295 (while (re-search-forward org-table-any-line-regexp nil t)
4296 (unless quietly
4297 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4298 (beginning-of-line 1)
4299 (when (and (looking-at org-table-line-regexp)
4300 ;; Exclude tables in src/example/verbatim/clocktable blocks
4301 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4302 (save-excursion (funcall function))
4303 (or (looking-at org-table-line-regexp)
4304 (forward-char 1)))
4305 (re-search-forward org-table-any-border-regexp nil 1))))
4306 (unless quietly (message "Mapping tables: done")))
4308 ;; Declare and autoload functions from ox.el and al.
4310 (declare-function org-export-get-environment "ox"
4311 (&optional backend subtreep ext-plist))
4312 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4314 ;; Declare and autoload functions from org-agenda.el
4316 (eval-and-compile
4317 (org-autoload "org-agenda"
4318 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4320 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4321 (declare-function org-clock-update-mode-line "org-clock" ())
4322 (declare-function org-resolve-clocks "org-clock"
4323 (&optional also-non-dangling-p prompt last-valid))
4325 (defun org-at-TBLFM-p (&optional pos)
4326 "Return t when point (or POS) is in #+TBLFM line."
4327 (save-excursion
4328 (let ((pos pos)))
4329 (goto-char (or pos (point)))
4330 (beginning-of-line 1)
4331 (looking-at org-TBLFM-regexp)))
4333 (defvar org-clock-start-time)
4334 (defvar org-clock-marker (make-marker)
4335 "Marker recording the last clock-in.")
4336 (defvar org-clock-hd-marker (make-marker)
4337 "Marker recording the last clock-in, but the headline position.")
4338 (defvar org-clock-heading ""
4339 "The heading of the current clock entry.")
4340 (defun org-clock-is-active ()
4341 "Return the buffer where the clock is currently running.
4342 Return nil if no clock is running."
4343 (marker-buffer org-clock-marker))
4345 (eval-and-compile
4346 (org-autoload "org-clock" '(org-clock-remove-overlays
4347 org-clock-update-time-maybe
4348 org-clocktable-shift)))
4350 (defun org-check-running-clock ()
4351 "Check if the current buffer contains the running clock.
4352 If yes, offer to stop it and to save the buffer with the changes."
4353 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4354 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4355 (buffer-name))))
4356 (org-clock-out)
4357 (when (y-or-n-p "Save changed buffer?")
4358 (save-buffer))))
4360 (defun org-clocktable-try-shift (dir n)
4361 "Check if this line starts a clock table, if yes, shift the time block."
4362 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4363 (org-clocktable-shift dir n)))
4365 ;;;###autoload
4366 (defun org-clock-persistence-insinuate ()
4367 "Set up hooks for clock persistence."
4368 (require 'org-clock)
4369 (add-hook 'org-mode-hook 'org-clock-load)
4370 (add-hook 'kill-emacs-hook 'org-clock-save))
4372 ;; Define the variable already here, to make sure we have it.
4373 (defvar org-indent-mode nil
4374 "Non-nil if Org-Indent mode is enabled.
4375 Use the command `org-indent-mode' to change this variable.")
4377 ;; Autoload archiving code
4378 ;; The stuff that is needed for cycling and tags has to be defined here.
4380 (defgroup org-archive nil
4381 "Options concerning archiving in Org-mode."
4382 :tag "Org Archive"
4383 :group 'org-structure)
4385 (defcustom org-archive-location "%s_archive::"
4386 "The location where subtrees should be archived.
4388 The value of this variable is a string, consisting of two parts,
4389 separated by a double-colon. The first part is a filename and
4390 the second part is a headline.
4392 When the filename is omitted, archiving happens in the same file.
4393 %s in the filename will be replaced by the current file
4394 name (without the directory part). Archiving to a different file
4395 is useful to keep archived entries from contributing to the
4396 Org-mode Agenda.
4398 The archived entries will be filed as subtrees of the specified
4399 headline. When the headline is omitted, the subtrees are simply
4400 filed away at the end of the file, as top-level entries. Also in
4401 the heading you can use %s to represent the file name, this can be
4402 useful when using the same archive for a number of different files.
4404 Here are a few examples:
4405 \"%s_archive::\"
4406 If the current file is Projects.org, archive in file
4407 Projects.org_archive, as top-level trees. This is the default.
4409 \"::* Archived Tasks\"
4410 Archive in the current file, under the top-level headline
4411 \"* Archived Tasks\".
4413 \"~/org/archive.org::\"
4414 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4416 \"~/org/archive.org::* From %s\"
4417 Archive in file ~/org/archive.org (absolute path), under headlines
4418 \"From FILENAME\" where file name is the current file name.
4420 \"~/org/datetree.org::datetree/* Finished Tasks\"
4421 The \"datetree/\" string is special, signifying to archive
4422 items to the datetree. Items are placed in either the CLOSED
4423 date of the item, or the current date if there is no CLOSED date.
4424 The heading will be a subentry to the current date. There doesn't
4425 need to be a heading, but there always needs to be a slash after
4426 datetree. For example, to store archived items directly in the
4427 datetree, use \"~/org/datetree.org::datetree/\".
4429 \"basement::** Finished Tasks\"
4430 Archive in file ./basement (relative path), as level 3 trees
4431 below the level 2 heading \"** Finished Tasks\".
4433 You may set this option on a per-file basis by adding to the buffer a
4434 line like
4436 #+ARCHIVE: basement::** Finished Tasks
4438 You may also define it locally for a subtree by setting an ARCHIVE property
4439 in the entry. If such a property is found in an entry, or anywhere up
4440 the hierarchy, it will be used."
4441 :group 'org-archive
4442 :type 'string)
4444 (defcustom org-archive-tag "ARCHIVE"
4445 "The tag that marks a subtree as archived.
4446 An archived subtree does not open during visibility cycling, and does
4447 not contribute to the agenda listings.
4448 After changing this, font-lock must be restarted in the relevant buffers to
4449 get the proper fontification."
4450 :group 'org-archive
4451 :group 'org-keywords
4452 :type 'string)
4454 (defcustom org-agenda-skip-archived-trees t
4455 "Non-nil means the agenda will skip any items located in archived trees.
4456 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4457 variable is no longer recommended, you should leave it at the value t.
4458 Instead, use the key `v' to cycle the archives-mode in the agenda."
4459 :group 'org-archive
4460 :group 'org-agenda-skip
4461 :type 'boolean)
4463 (defcustom org-columns-skip-archived-trees t
4464 "Non-nil means ignore archived trees when creating column view."
4465 :group 'org-archive
4466 :group 'org-properties
4467 :type 'boolean)
4469 (defcustom org-cycle-open-archived-trees nil
4470 "Non-nil means `org-cycle' will open archived trees.
4471 An archived tree is a tree marked with the tag ARCHIVE.
4472 When nil, archived trees will stay folded. You can still open them with
4473 normal outline commands like `show-all', but not with the cycling commands."
4474 :group 'org-archive
4475 :group 'org-cycle
4476 :type 'boolean)
4478 (defcustom org-sparse-tree-open-archived-trees nil
4479 "Non-nil means sparse tree construction shows matches in archived trees.
4480 When nil, matches in these trees are highlighted, but the trees are kept in
4481 collapsed state."
4482 :group 'org-archive
4483 :group 'org-sparse-trees
4484 :type 'boolean)
4486 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4487 "The default date type when building a sparse tree.
4488 When this is nil, a date is a scheduled or a deadline timestamp.
4489 Otherwise, these types are allowed:
4491 all: all timestamps
4492 active: only active timestamps (<...>)
4493 inactive: only inactive timestamps (<...)
4494 scheduled: only scheduled timestamps
4495 deadline: only deadline timestamps"
4496 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4497 (const :tag "All timestamps" all)
4498 (const :tag "Only active timestamps" active)
4499 (const :tag "Only inactive timestamps" inactive)
4500 (const :tag "Only scheduled timestamps" scheduled)
4501 (const :tag "Only deadline timestamps" deadline)
4502 (const :tag "Only closed timestamps" closed))
4503 :version "24.3"
4504 :group 'org-sparse-trees)
4506 (defun org-cycle-hide-archived-subtrees (state)
4507 "Re-hide all archived subtrees after a visibility state change."
4508 (when (and (not org-cycle-open-archived-trees)
4509 (not (memq state '(overview folded))))
4510 (save-excursion
4511 (let* ((globalp (memq state '(contents all)))
4512 (beg (if globalp (point-min) (point)))
4513 (end (if globalp (point-max) (org-end-of-subtree t))))
4514 (org-hide-archived-subtrees beg end)
4515 (goto-char beg)
4516 (if (looking-at (concat ".*:" org-archive-tag ":"))
4517 (message "%s" (substitute-command-keys
4518 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4520 (defun org-force-cycle-archived ()
4521 "Cycle subtree even if it is archived."
4522 (interactive)
4523 (setq this-command 'org-cycle)
4524 (let ((org-cycle-open-archived-trees t))
4525 (call-interactively 'org-cycle)))
4527 (defun org-hide-archived-subtrees (beg end)
4528 "Re-hide all archived subtrees after a visibility state change."
4529 (save-excursion
4530 (let* ((re (concat ":" org-archive-tag ":")))
4531 (goto-char beg)
4532 (while (re-search-forward re end t)
4533 (when (org-at-heading-p)
4534 (org-flag-subtree t)
4535 (org-end-of-subtree t))))))
4537 (declare-function outline-end-of-heading "outline" ())
4538 (declare-function outline-flag-region "outline" (from to flag))
4539 (defun org-flag-subtree (flag)
4540 (save-excursion
4541 (org-back-to-heading t)
4542 (outline-end-of-heading)
4543 (outline-flag-region (point)
4544 (progn (org-end-of-subtree t) (point))
4545 flag)))
4547 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4549 (eval-and-compile
4550 (org-autoload "org-archive"
4551 '(org-add-archive-files)))
4553 ;; Autoload Column View Code
4555 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4556 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4557 (declare-function org-columns-compute "org-colview" (property))
4559 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4560 '(org-columns-number-to-string
4561 org-columns-get-format-and-top-level
4562 org-columns-compute
4563 org-columns-remove-overlays))
4565 ;; Autoload ID code
4567 (declare-function org-id-store-link "org-id")
4568 (declare-function org-id-locations-load "org-id")
4569 (declare-function org-id-locations-save "org-id")
4570 (defvar org-id-track-globally)
4571 (org-autoload "org-id"
4572 '(org-id-new
4573 org-id-copy
4574 org-id-get-with-outline-path-completion
4575 org-id-get-with-outline-drilling))
4577 ;;; Variables for pre-computed regular expressions, all buffer local
4579 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4580 "Matches first line of a hidden block.")
4581 (make-variable-buffer-local 'org-drawer-regexp)
4582 (defvar org-todo-regexp nil
4583 "Matches any of the TODO state keywords.")
4584 (make-variable-buffer-local 'org-todo-regexp)
4585 (defvar org-not-done-regexp nil
4586 "Matches any of the TODO state keywords except the last one.")
4587 (make-variable-buffer-local 'org-not-done-regexp)
4588 (defvar org-not-done-heading-regexp nil
4589 "Matches a TODO headline that is not done.")
4590 (make-variable-buffer-local 'org-not-done-regexp)
4591 (defvar org-todo-line-regexp nil
4592 "Matches a headline and puts TODO state into group 2 if present.")
4593 (make-variable-buffer-local 'org-todo-line-regexp)
4594 (defvar org-complex-heading-regexp nil
4595 "Matches a headline and puts everything into groups:
4596 group 1: the stars
4597 group 2: The todo keyword, maybe
4598 group 3: Priority cookie
4599 group 4: True headline
4600 group 5: Tags")
4601 (make-variable-buffer-local 'org-complex-heading-regexp)
4602 (defvar org-complex-heading-regexp-format nil
4603 "Printf format to make regexp to match an exact headline.
4604 This regexp will match the headline of any node which has the
4605 exact headline text that is put into the format, but may have any
4606 TODO state, priority and tags.")
4607 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4608 (defvar org-todo-line-tags-regexp nil
4609 "Matches a headline and puts TODO state into group 2 if present.
4610 Also put tags into group 4 if tags are present.")
4611 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4612 (defvar org-ds-keyword-length 12
4613 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4614 (make-variable-buffer-local 'org-ds-keyword-length)
4615 (defvar org-deadline-regexp nil
4616 "Matches the DEADLINE keyword.")
4617 (make-variable-buffer-local 'org-deadline-regexp)
4618 (defvar org-deadline-time-regexp nil
4619 "Matches the DEADLINE keyword together with a time stamp.")
4620 (make-variable-buffer-local 'org-deadline-time-regexp)
4621 (defvar org-deadline-time-hour-regexp nil
4622 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4623 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4624 (defvar org-deadline-line-regexp nil
4625 "Matches the DEADLINE keyword and the rest of the line.")
4626 (make-variable-buffer-local 'org-deadline-line-regexp)
4627 (defvar org-scheduled-regexp nil
4628 "Matches the SCHEDULED keyword.")
4629 (make-variable-buffer-local 'org-scheduled-regexp)
4630 (defvar org-scheduled-time-regexp nil
4631 "Matches the SCHEDULED keyword together with a time stamp.")
4632 (make-variable-buffer-local 'org-scheduled-time-regexp)
4633 (defvar org-scheduled-time-hour-regexp nil
4634 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4635 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4636 (defvar org-closed-time-regexp nil
4637 "Matches the CLOSED keyword together with a time stamp.")
4638 (make-variable-buffer-local 'org-closed-time-regexp)
4640 (defvar org-keyword-time-regexp nil
4641 "Matches any of the 4 keywords, together with the time stamp.")
4642 (make-variable-buffer-local 'org-keyword-time-regexp)
4643 (defvar org-keyword-time-not-clock-regexp nil
4644 "Matches any of the 3 keywords, together with the time stamp.")
4645 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4646 (defvar org-maybe-keyword-time-regexp nil
4647 "Matches a timestamp, possibly preceded by a keyword.")
4648 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4649 (defvar org-all-time-keywords nil
4650 "List of time keywords.")
4651 (make-variable-buffer-local 'org-all-time-keywords)
4653 (defconst org-plain-time-of-day-regexp
4654 (concat
4655 "\\(\\<[012]?[0-9]"
4656 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4657 "\\(--?"
4658 "\\(\\<[012]?[0-9]"
4659 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4660 "\\)?")
4661 "Regular expression to match a plain time or time range.
4662 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4663 groups carry important information:
4664 0 the full match
4665 1 the first time, range or not
4666 8 the second time, if it is a range.")
4668 (defconst org-plain-time-extension-regexp
4669 (concat
4670 "\\(\\<[012]?[0-9]"
4671 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4672 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4673 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4674 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4675 groups carry important information:
4676 0 the full match
4677 7 hours of duration
4678 9 minutes of duration")
4680 (defconst org-stamp-time-of-day-regexp
4681 (concat
4682 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4683 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4684 "\\(--?"
4685 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4686 "Regular expression to match a timestamp time or time range.
4687 After a match, the following groups carry important information:
4688 0 the full match
4689 1 date plus weekday, for back referencing to make sure both times are on the same day
4690 2 the first time, range or not
4691 4 the second time, if it is a range.")
4693 (defconst org-startup-options
4694 '(("fold" org-startup-folded t)
4695 ("overview" org-startup-folded t)
4696 ("nofold" org-startup-folded nil)
4697 ("showall" org-startup-folded nil)
4698 ("showeverything" org-startup-folded showeverything)
4699 ("content" org-startup-folded content)
4700 ("indent" org-startup-indented t)
4701 ("noindent" org-startup-indented nil)
4702 ("hidestars" org-hide-leading-stars t)
4703 ("showstars" org-hide-leading-stars nil)
4704 ("odd" org-odd-levels-only t)
4705 ("oddeven" org-odd-levels-only nil)
4706 ("align" org-startup-align-all-tables t)
4707 ("noalign" org-startup-align-all-tables nil)
4708 ("inlineimages" org-startup-with-inline-images t)
4709 ("noinlineimages" org-startup-with-inline-images nil)
4710 ("latexpreview" org-startup-with-latex-preview t)
4711 ("nolatexpreview" org-startup-with-latex-preview nil)
4712 ("customtime" org-display-custom-times t)
4713 ("logdone" org-log-done time)
4714 ("lognotedone" org-log-done note)
4715 ("nologdone" org-log-done nil)
4716 ("lognoteclock-out" org-log-note-clock-out t)
4717 ("nolognoteclock-out" org-log-note-clock-out nil)
4718 ("logrepeat" org-log-repeat state)
4719 ("lognoterepeat" org-log-repeat note)
4720 ("logdrawer" org-log-into-drawer t)
4721 ("nologdrawer" org-log-into-drawer nil)
4722 ("logstatesreversed" org-log-states-order-reversed t)
4723 ("nologstatesreversed" org-log-states-order-reversed nil)
4724 ("nologrepeat" org-log-repeat nil)
4725 ("logreschedule" org-log-reschedule time)
4726 ("lognotereschedule" org-log-reschedule note)
4727 ("nologreschedule" org-log-reschedule nil)
4728 ("logredeadline" org-log-redeadline time)
4729 ("lognoteredeadline" org-log-redeadline note)
4730 ("nologredeadline" org-log-redeadline nil)
4731 ("logrefile" org-log-refile time)
4732 ("lognoterefile" org-log-refile note)
4733 ("nologrefile" org-log-refile nil)
4734 ("fninline" org-footnote-define-inline t)
4735 ("nofninline" org-footnote-define-inline nil)
4736 ("fnlocal" org-footnote-section nil)
4737 ("fnauto" org-footnote-auto-label t)
4738 ("fnprompt" org-footnote-auto-label nil)
4739 ("fnconfirm" org-footnote-auto-label confirm)
4740 ("fnplain" org-footnote-auto-label plain)
4741 ("fnadjust" org-footnote-auto-adjust t)
4742 ("nofnadjust" org-footnote-auto-adjust nil)
4743 ("constcgs" constants-unit-system cgs)
4744 ("constSI" constants-unit-system SI)
4745 ("noptag" org-tag-persistent-alist nil)
4746 ("hideblocks" org-hide-block-startup t)
4747 ("nohideblocks" org-hide-block-startup nil)
4748 ("beamer" org-startup-with-beamer-mode t)
4749 ("entitiespretty" org-pretty-entities t)
4750 ("entitiesplain" org-pretty-entities nil))
4751 "Variable associated with STARTUP options for org-mode.
4752 Each element is a list of three items: the startup options (as written
4753 in the #+STARTUP line), the corresponding variable, and the value to set
4754 this variable to if the option is found. An optional forth element PUSH
4755 means to push this value onto the list in the variable.")
4757 (defun org-update-property-plist (key val props)
4758 "Update PROPS with KEY and VAL."
4759 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4760 (key (if appending (substring key 0 (- (length key) 1)) key))
4761 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4762 (previous (cdr (assoc key props))))
4763 (if appending
4764 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4765 (cons (cons key val) remainder))))
4767 (defconst org-block-regexp
4768 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4769 "Regular expression for hiding blocks.")
4770 (defconst org-heading-keyword-regexp-format
4771 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4772 "Printf format for a regexp matching a headline with some keyword.
4773 This regexp will match the headline of any node which has the
4774 exact keyword that is put into the format. The keyword isn't in
4775 any group by default, but the stars and the body are.")
4776 (defconst org-heading-keyword-maybe-regexp-format
4777 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4778 "Printf format for a regexp matching a headline, possibly with some keyword.
4779 This regexp can match any headline with the specified keyword, or
4780 without a keyword. The keyword isn't in any group by default,
4781 but the stars and the body are.")
4783 (defcustom org-group-tags t
4784 "When non-nil (the default), use group tags.
4785 This can be turned on/off through `org-toggle-tags-groups'."
4786 :group 'org-tags
4787 :group 'org-startup
4788 :type 'boolean)
4790 (defun org-toggle-tags-groups ()
4791 "Toggle support for group tags.
4792 Support for group tags is controlled by the option
4793 `org-group-tags', which is non-nil by default."
4794 (interactive)
4795 (setq org-group-tags (not org-group-tags))
4796 (cond ((and (derived-mode-p 'org-agenda-mode)
4797 org-group-tags)
4798 (org-agenda-redo))
4799 ((derived-mode-p 'org-mode)
4800 (let ((org-inhibit-startup t)) (org-mode))))
4801 (message "Groups tags support has been turned %s"
4802 (if org-group-tags "on" "off")))
4804 (defun org-set-regexps-and-options-for-tags ()
4805 "Precompute variables used for tags."
4806 (when (derived-mode-p 'org-mode)
4807 (org-set-local 'org-file-tags nil)
4808 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4809 (splitre "[ \t]+")
4810 (start 0)
4811 tags ftags key value)
4812 (save-excursion
4813 (save-restriction
4814 (widen)
4815 (goto-char (point-min))
4816 (while (re-search-forward re nil t)
4817 (setq key (upcase (org-match-string-no-properties 1))
4818 value (org-match-string-no-properties 2))
4819 (if (stringp value) (setq value (org-trim value)))
4820 (cond
4821 ((equal key "TAGS")
4822 (setq tags (append tags (if tags '("\\n") nil)
4823 (org-split-string value splitre))))
4824 ((equal key "FILETAGS")
4825 (when (string-match "\\S-" value)
4826 (setq ftags
4827 (append
4828 ftags
4829 (apply 'append
4830 (mapcar (lambda (x) (org-split-string x ":"))
4831 (org-split-string value)))))))))))
4832 ;; Process the file tags.
4833 (and ftags (org-set-local 'org-file-tags
4834 (mapcar 'org-add-prop-inherited ftags)))
4835 (org-set-local 'org-tag-groups-alist nil)
4836 ;; Process the tags.
4837 (when (and (not tags) org-tag-alist)
4838 (setq tags
4839 (mapcar
4840 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4841 ((eq (car tg) :endgroup) "}")
4842 ((eq (car tg) :grouptags) ":")
4843 ((eq (car tg) :newline) "\n")
4844 (t (concat (car tg)
4845 (if (characterp (cdr tg))
4846 (format "(%s)" (char-to-string (cdr tg))) "")))))
4847 org-tag-alist)))
4848 (let (e tgs g)
4849 (while (setq e (pop tags))
4850 (cond
4851 ((equal e "{")
4852 (progn (push '(:startgroup) tgs)
4853 (when (equal (nth 1 tags) ":")
4854 (push (list (replace-regexp-in-string
4855 "(.+)$" "" (nth 0 tags)))
4856 org-tag-groups-alist)
4857 (setq g 0))))
4858 ((equal e ":") (push '(:grouptags) tgs))
4859 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4860 ((equal e "\\n") (push '(:newline) tgs))
4861 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4862 (push (cons (match-string 1 e)
4863 (string-to-char (match-string 2 e))) tgs)
4864 (if (and g (> g 0))
4865 (setcar org-tag-groups-alist
4866 (append (car org-tag-groups-alist)
4867 (list (match-string 1 e)))))
4868 (if g (setq g (1+ g))))
4869 (t (push (list e) tgs)
4870 (if (and g (> g 0))
4871 (setcar org-tag-groups-alist
4872 (append (car org-tag-groups-alist) (list e))))
4873 (if g (setq g (1+ g))))))
4874 (org-set-local 'org-tag-alist nil)
4875 (while (setq e (pop tgs))
4876 (or (and (stringp (car e))
4877 (assoc (car e) org-tag-alist))
4878 (push e org-tag-alist)))
4879 ;; Return a list with tag variables
4880 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4882 (defvar org-ota nil)
4883 (defun org-set-regexps-and-options ()
4884 "Precompute regular expressions used in the current buffer."
4885 (when (derived-mode-p 'org-mode)
4886 (org-set-local 'org-todo-kwd-alist nil)
4887 (org-set-local 'org-todo-key-alist nil)
4888 (org-set-local 'org-todo-key-trigger nil)
4889 (org-set-local 'org-todo-keywords-1 nil)
4890 (org-set-local 'org-done-keywords nil)
4891 (org-set-local 'org-todo-heads nil)
4892 (org-set-local 'org-todo-sets nil)
4893 (org-set-local 'org-todo-log-states nil)
4894 (org-set-local 'org-file-properties nil)
4895 (let ((re (org-make-options-regexp
4896 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4897 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4898 "SETUPFILE" "OPTIONS")
4899 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4900 (splitre "[ \t]+")
4901 (scripts org-use-sub-superscripts)
4902 kwds kws0 kwsa key log value cat arch const links hw dws
4903 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4904 (start 0))
4905 (save-excursion
4906 (save-restriction
4907 (widen)
4908 (goto-char (point-min))
4909 (while
4910 (or (and
4911 ext-setup-or-nil
4912 (not org-ota)
4913 (let (ret)
4914 (with-temp-buffer
4915 (insert ext-setup-or-nil)
4916 (let ((major-mode 'org-mode) org-ota)
4917 (setq ret (save-match-data
4918 (org-set-regexps-and-options-for-tags)))))
4919 ;; Append setupfile tags to existing tags
4920 (setq org-ota t)
4921 (setq org-file-tags
4922 (delq nil (append org-file-tags (nth 0 ret)))
4923 org-tag-alist
4924 (delq nil (append org-tag-alist (nth 1 ret)))
4925 org-tag-groups-alist
4926 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4927 (and ext-setup-or-nil
4928 (string-match re ext-setup-or-nil start)
4929 (setq start (match-end 0)))
4930 (and (setq ext-setup-or-nil nil start 0)
4931 (re-search-forward re nil t)))
4932 (setq key (upcase (match-string 1 ext-setup-or-nil))
4933 value (org-match-string-no-properties 2 ext-setup-or-nil))
4934 (if (stringp value) (setq value (org-trim value)))
4935 (cond
4936 ((equal key "CATEGORY")
4937 (setq cat value))
4938 ((member key '("SEQ_TODO" "TODO"))
4939 (push (cons 'sequence (org-split-string value splitre)) kwds))
4940 ((equal key "TYP_TODO")
4941 (push (cons 'type (org-split-string value splitre)) kwds))
4942 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4943 ;; general TODO-like setup
4944 (push (cons (intern (downcase (match-string 1 key)))
4945 (org-split-string value splitre)) kwds))
4946 ((equal key "COLUMNS")
4947 (org-set-local 'org-columns-default-format value))
4948 ((equal key "LINK")
4949 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4950 (push (cons (match-string 1 value)
4951 (org-trim (match-string 2 value)))
4952 links)))
4953 ((equal key "PRIORITIES")
4954 (setq prio (org-split-string value " +")))
4955 ((equal key "PROPERTY")
4956 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4957 (setq props (org-update-property-plist (match-string 1 value)
4958 (match-string 2 value)
4959 props))))
4960 ((equal key "DRAWERS")
4961 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4962 ((equal key "CONSTANTS")
4963 (org-table-set-constants))
4964 ((equal key "STARTUP")
4965 (let ((opts (org-split-string value splitre))
4966 l var val)
4967 (while (setq l (pop opts))
4968 (when (setq l (assoc l org-startup-options))
4969 (setq var (nth 1 l) val (nth 2 l))
4970 (if (not (nth 3 l))
4971 (set (make-local-variable var) val)
4972 (if (not (listp (symbol-value var)))
4973 (set (make-local-variable var) nil))
4974 (set (make-local-variable var) (symbol-value var))
4975 (add-to-list var val))))))
4976 ((equal key "ARCHIVE")
4977 (setq arch value)
4978 (remove-text-properties 0 (length arch)
4979 '(face t fontified t) arch))
4980 ((equal key "OPTIONS")
4981 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4982 (setq scripts (read (match-string 2 value)))))
4983 ((and (equal key "SETUPFILE")
4984 ;; Prevent checking in Gnus messages
4985 (not buffer-read-only))
4986 (setq setup-contents (org-file-contents
4987 (expand-file-name
4988 (org-remove-double-quotes value))
4989 'noerror))
4990 (if (not ext-setup-or-nil)
4991 (setq ext-setup-or-nil setup-contents start 0)
4992 (setq ext-setup-or-nil
4993 (concat (substring ext-setup-or-nil 0 start)
4994 "\n" setup-contents "\n"
4995 (substring ext-setup-or-nil start)))))))
4996 ;; search for property blocks
4997 (goto-char (point-min))
4998 (while (re-search-forward org-block-regexp nil t)
4999 (when (equal "PROPERTY" (upcase (match-string 1)))
5000 (setq value (replace-regexp-in-string
5001 "[\n\r]" " " (match-string 4)))
5002 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5003 (setq props (org-update-property-plist (match-string 1 value)
5004 (match-string 2 value)
5005 props)))))))
5006 (org-set-local 'org-use-sub-superscripts scripts)
5007 (when cat
5008 (org-set-local 'org-category (intern cat))
5009 (push (cons "CATEGORY" cat) props))
5010 (when prio
5011 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5012 (setq prio (mapcar 'string-to-char prio))
5013 (org-set-local 'org-highest-priority (nth 0 prio))
5014 (org-set-local 'org-lowest-priority (nth 1 prio))
5015 (org-set-local 'org-default-priority (nth 2 prio)))
5016 (and props (org-set-local 'org-file-properties (nreverse props)))
5017 (and drawers (org-set-local 'org-drawers drawers))
5018 (and arch (org-set-local 'org-archive-location arch))
5019 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5020 ;; Process the TODO keywords
5021 (unless kwds
5022 ;; Use the global values as if they had been given locally.
5023 (setq kwds (default-value 'org-todo-keywords))
5024 (if (stringp (car kwds))
5025 (setq kwds (list (cons org-todo-interpretation
5026 (default-value 'org-todo-keywords)))))
5027 (setq kwds (reverse kwds)))
5028 (setq kwds (nreverse kwds))
5029 (let (inter kws kw)
5030 (while (setq kws (pop kwds))
5031 (let ((kws (or
5032 (run-hook-with-args-until-success
5033 'org-todo-setup-filter-hook kws)
5034 kws)))
5035 (setq inter (pop kws) sep (member "|" kws)
5036 kws0 (delete "|" (copy-sequence kws))
5037 kwsa nil
5038 kws1 (mapcar
5039 (lambda (x)
5040 ;; 1 2
5041 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5042 (progn
5043 (setq kw (match-string 1 x)
5044 key (and (match-end 2) (match-string 2 x))
5045 log (org-extract-log-state-settings x))
5046 (push (cons kw (and key (string-to-char key))) kwsa)
5047 (and log (push log org-todo-log-states))
5049 (error "Invalid TODO keyword %s" x)))
5050 kws0)
5051 kwsa (if kwsa (append '((:startgroup))
5052 (nreverse kwsa)
5053 '((:endgroup))))
5054 hw (car kws1)
5055 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5056 tail (list inter hw (car dws) (org-last dws))))
5057 (add-to-list 'org-todo-heads hw 'append)
5058 (push kws1 org-todo-sets)
5059 (setq org-done-keywords (append org-done-keywords dws nil))
5060 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5061 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5062 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5063 (setq org-todo-sets (nreverse org-todo-sets)
5064 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5065 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5066 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5067 ;; Compute the regular expressions and other local variables.
5068 ;; Using `org-outline-regexp-bol' would complicate them much,
5069 ;; because of the fixed white space at the end of that string.
5070 (if (not org-done-keywords)
5071 (setq org-done-keywords (and org-todo-keywords-1
5072 (list (org-last org-todo-keywords-1)))))
5073 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5074 (length org-scheduled-string)
5075 (length org-clock-string)
5076 (length org-closed-string)))
5077 org-drawer-regexp
5078 (concat "^[ \t]*:\\("
5079 (mapconcat 'regexp-quote org-drawers "\\|")
5080 "\\):[ \t]*$")
5081 org-not-done-keywords
5082 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5083 org-todo-regexp
5084 (concat "\\("
5085 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5086 "\\)")
5087 org-not-done-regexp
5088 (concat "\\("
5089 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5090 "\\)")
5091 org-not-done-heading-regexp
5092 (format org-heading-keyword-regexp-format org-not-done-regexp)
5093 org-todo-line-regexp
5094 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5095 org-complex-heading-regexp
5096 (concat "^\\(\\*+\\)"
5097 "\\(?: +" org-todo-regexp "\\)?"
5098 "\\(?: +\\(\\[#.\\]\\)\\)?"
5099 "\\(?: +\\(.*?\\)\\)??"
5100 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5101 "[ \t]*$")
5102 org-complex-heading-regexp-format
5103 (concat "^\\(\\*+\\)"
5104 "\\(?: +" org-todo-regexp "\\)?"
5105 "\\(?: +\\(\\[#.\\]\\)\\)?"
5106 "\\(?: +"
5107 ;; Stats cookies can be stuck to body.
5108 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5109 "\\(%s\\)"
5110 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5111 "\\)"
5112 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5113 "[ \t]*$")
5114 org-todo-line-tags-regexp
5115 (concat "^\\(\\*+\\)"
5116 "\\(?: +" org-todo-regexp "\\)?"
5117 "\\(?: +\\(.*?\\)\\)??"
5118 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5119 "[ \t]*$")
5120 org-deadline-regexp (concat "\\<" org-deadline-string)
5121 org-deadline-time-regexp
5122 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5123 org-deadline-time-hour-regexp
5124 (concat "\\<" org-deadline-string
5125 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5126 org-deadline-line-regexp
5127 (concat "\\<\\(" org-deadline-string "\\).*")
5128 org-scheduled-regexp
5129 (concat "\\<" org-scheduled-string)
5130 org-scheduled-time-regexp
5131 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5132 org-scheduled-time-hour-regexp
5133 (concat "\\<" org-scheduled-string
5134 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5135 org-closed-time-regexp
5136 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5137 org-keyword-time-regexp
5138 (concat "\\<\\(" org-scheduled-string
5139 "\\|" org-deadline-string
5140 "\\|" org-closed-string
5141 "\\|" org-clock-string "\\)"
5142 " *[[<]\\([^]>]+\\)[]>]")
5143 org-keyword-time-not-clock-regexp
5144 (concat "\\<\\(" org-scheduled-string
5145 "\\|" org-deadline-string
5146 "\\|" org-closed-string
5147 "\\)"
5148 " *[[<]\\([^]>]+\\)[]>]")
5149 org-maybe-keyword-time-regexp
5150 (concat "\\(\\<\\(" org-scheduled-string
5151 "\\|" org-deadline-string
5152 "\\|" org-closed-string
5153 "\\|" org-clock-string "\\)\\)?"
5154 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5155 org-all-time-keywords
5156 (mapcar (lambda (w) (substring w 0 -1))
5157 (list org-scheduled-string org-deadline-string
5158 org-clock-string org-closed-string)))
5159 (setq org-ota nil)
5160 (org-compute-latex-and-related-regexp))))
5162 (defun org-file-contents (file &optional noerror)
5163 "Return the contents of FILE, as a string."
5164 (if (or (not file)
5165 (not (file-readable-p file)))
5166 (if noerror
5167 (message "Cannot read file \"%s\"" file)
5168 (error "Cannot read file \"%s\"" file))
5169 (with-temp-buffer
5170 (insert-file-contents file)
5171 (buffer-string))))
5173 (defun org-extract-log-state-settings (x)
5174 "Extract the log state setting from a TODO keyword string.
5175 This will extract info from a string like \"WAIT(w@/!)\"."
5176 (let (kw key log1 log2)
5177 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5178 (setq kw (match-string 1 x)
5179 key (and (match-end 2) (match-string 2 x))
5180 log1 (and (match-end 3) (match-string 3 x))
5181 log2 (and (match-end 4) (match-string 4 x)))
5182 (and (or log1 log2)
5183 (list kw
5184 (and log1 (if (equal log1 "!") 'time 'note))
5185 (and log2 (if (equal log2 "!") 'time 'note)))))))
5187 (defun org-remove-keyword-keys (list)
5188 "Remove a pair of parenthesis at the end of each string in LIST."
5189 (mapcar (lambda (x)
5190 (if (string-match "(.*)$" x)
5191 (substring x 0 (match-beginning 0))
5193 list))
5195 (defun org-assign-fast-keys (alist)
5196 "Assign fast keys to a keyword-key alist.
5197 Respect keys that are already there."
5198 (let (new e (alt ?0))
5199 (while (setq e (pop alist))
5200 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5201 (cdr e)) ;; Key already assigned.
5202 (push e new)
5203 (let ((clist (string-to-list (downcase (car e))))
5204 (used (append new alist)))
5205 (when (= (car clist) ?@)
5206 (pop clist))
5207 (while (and clist (rassoc (car clist) used))
5208 (pop clist))
5209 (unless clist
5210 (while (rassoc alt used)
5211 (incf alt)))
5212 (push (cons (car e) (or (car clist) alt)) new))))
5213 (nreverse new)))
5215 ;;; Some variables used in various places
5217 (defvar org-window-configuration nil
5218 "Used in various places to store a window configuration.")
5219 (defvar org-selected-window nil
5220 "Used in various places to store a window configuration.")
5221 (defvar org-finish-function nil
5222 "Function to be called when `C-c C-c' is used.
5223 This is for getting out of special buffers like capture.")
5226 ;; FIXME: Occasionally check by commenting these, to make sure
5227 ;; no other functions uses these, forgetting to let-bind them.
5228 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5229 (defvar org-last-state)
5230 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5232 ;; Defined somewhere in this file, but used before definition.
5233 (defvar org-entities) ;; defined in org-entities.el
5234 (defvar org-struct-menu)
5235 (defvar org-org-menu)
5236 (defvar org-tbl-menu)
5238 ;;;; Define the Org-mode
5240 ;; We use a before-change function to check if a table might need
5241 ;; an update.
5242 (defvar org-table-may-need-update t
5243 "Indicates that a table might need an update.
5244 This variable is set by `org-before-change-function'.
5245 `org-table-align' sets it back to nil.")
5246 (defun org-before-change-function (beg end)
5247 "Every change indicates that a table might need an update."
5248 (setq org-table-may-need-update t))
5249 (defvar org-mode-map)
5250 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5251 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5252 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5253 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5254 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5255 (defvar org-table-buffer-is-an nil)
5257 (defvar bidi-paragraph-direction)
5258 (defvar buffer-face-mode-face)
5260 (require 'outline)
5261 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5262 (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"))
5263 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5265 ;; Other stuff we need.
5266 (require 'time-date)
5267 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5268 (require 'easymenu)
5269 (require 'overlay)
5271 ;; (require 'org-macs) moved higher up in the file before it is first used
5272 (require 'org-entities)
5273 ;; (require 'org-compat) moved higher up in the file before it is first used
5274 (require 'org-faces)
5275 (require 'org-list)
5276 (require 'org-pcomplete)
5277 (require 'org-src)
5278 (require 'org-footnote)
5279 (require 'org-macro)
5281 ;; babel
5282 (require 'ob)
5284 ;;;###autoload
5285 (define-derived-mode org-mode outline-mode "Org"
5286 "Outline-based notes management and organizer, alias
5287 \"Carsten's outline-mode for keeping track of everything.\"
5289 Org-mode develops organizational tasks around a NOTES file which
5290 contains information about projects as plain text. Org-mode is
5291 implemented on top of outline-mode, which is ideal to keep the content
5292 of large files well structured. It supports ToDo items, deadlines and
5293 time stamps, which magically appear in the diary listing of the Emacs
5294 calendar. Tables are easily created with a built-in table editor.
5295 Plain text URL-like links connect to websites, emails (VM), Usenet
5296 messages (Gnus), BBDB entries, and any files related to the project.
5297 For printing and sharing of notes, an Org-mode file (or a part of it)
5298 can be exported as a structured ASCII or HTML file.
5300 The following commands are available:
5302 \\{org-mode-map}"
5304 ;; Get rid of Outline menus, they are not needed
5305 ;; Need to do this here because define-derived-mode sets up
5306 ;; the keymap so late. Still, it is a waste to call this each time
5307 ;; we switch another buffer into org-mode.
5308 (if (featurep 'xemacs)
5309 (when (boundp 'outline-mode-menu-heading)
5310 ;; Assume this is Greg's port, it uses easymenu
5311 (easy-menu-remove outline-mode-menu-heading)
5312 (easy-menu-remove outline-mode-menu-show)
5313 (easy-menu-remove outline-mode-menu-hide))
5314 (define-key org-mode-map [menu-bar headings] 'undefined)
5315 (define-key org-mode-map [menu-bar hide] 'undefined)
5316 (define-key org-mode-map [menu-bar show] 'undefined))
5318 (org-load-modules-maybe)
5319 (easy-menu-add org-org-menu)
5320 (easy-menu-add org-tbl-menu)
5321 (org-install-agenda-files-menu)
5322 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5323 (add-to-invisibility-spec '(org-cwidth))
5324 (add-to-invisibility-spec '(org-hide-block . t))
5325 (when (featurep 'xemacs)
5326 (org-set-local 'line-move-ignore-invisible t))
5327 (org-set-local 'outline-regexp org-outline-regexp)
5328 (org-set-local 'outline-level 'org-outline-level)
5329 (setq bidi-paragraph-direction 'left-to-right)
5330 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5331 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5332 (when (and org-ellipsis
5333 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5334 (fboundp 'make-glyph-code))
5335 (unless org-display-table
5336 (setq org-display-table (make-display-table)))
5337 (set-display-table-slot
5338 org-display-table 4
5339 (vconcat (mapcar
5340 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5341 org-ellipsis)))
5342 (if (stringp org-ellipsis) org-ellipsis "..."))))
5343 (setq buffer-display-table org-display-table))
5344 (org-set-regexps-and-options-for-tags)
5345 (org-set-regexps-and-options)
5346 (org-set-font-lock-defaults)
5347 (when (and org-tag-faces (not org-tags-special-faces-re))
5348 ;; tag faces set outside customize.... force initialization.
5349 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5350 ;; Calc embedded
5351 (org-set-local 'calc-embedded-open-mode "# ")
5352 ;; Modify a few syntax entries
5353 (modify-syntax-entry ?@ "w")
5354 (modify-syntax-entry ?\" "\"")
5355 (if org-startup-truncated (setq truncate-lines t))
5356 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5357 (org-set-local 'font-lock-unfontify-region-function
5358 'org-unfontify-region)
5359 ;; Activate before-change-function
5360 (org-set-local 'org-table-may-need-update t)
5361 (org-add-hook 'before-change-functions 'org-before-change-function nil
5362 'local)
5363 ;; Check for running clock before killing a buffer
5364 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5365 ;; Initialize macros templates.
5366 (org-macro-initialize-templates)
5367 ;; Initialize radio targets.
5368 (org-update-radio-target-regexp)
5369 ;; Indentation.
5370 (org-set-local 'indent-line-function 'org-indent-line)
5371 (org-set-local 'indent-region-function 'org-indent-region)
5372 ;; Filling and auto-filling.
5373 (org-setup-filling)
5374 ;; Comments.
5375 (org-setup-comments-handling)
5376 ;; Beginning/end of defun
5377 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5378 (org-set-local 'end-of-defun-function 'org-forward-element)
5379 ;; Next error for sparse trees
5380 (org-set-local 'next-error-function 'org-occur-next-match)
5381 ;; Make sure dependence stuff works reliably, even for users who set it
5382 ;; too late :-(
5383 (if org-enforce-todo-dependencies
5384 (add-hook 'org-blocker-hook
5385 'org-block-todo-from-children-or-siblings-or-parent)
5386 (remove-hook 'org-blocker-hook
5387 'org-block-todo-from-children-or-siblings-or-parent))
5388 (if org-enforce-todo-checkbox-dependencies
5389 (add-hook 'org-blocker-hook
5390 'org-block-todo-from-checkboxes)
5391 (remove-hook 'org-blocker-hook
5392 'org-block-todo-from-checkboxes))
5394 ;; Align options lines
5395 (org-set-local
5396 'align-mode-rules-list
5397 '((org-in-buffer-settings
5398 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5399 (modes . '(org-mode)))))
5401 ;; Imenu
5402 (org-set-local 'imenu-create-index-function
5403 'org-imenu-get-tree)
5405 ;; Make isearch reveal context
5406 (if (or (featurep 'xemacs)
5407 (not (boundp 'outline-isearch-open-invisible-function)))
5408 ;; Emacs 21 and XEmacs make use of the hook
5409 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5410 ;; Emacs 22 deals with this through a special variable
5411 (org-set-local 'outline-isearch-open-invisible-function
5412 (lambda (&rest ignore) (org-show-context 'isearch)))
5413 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5415 ;; Setup the pcomplete hooks
5416 (set (make-local-variable 'pcomplete-command-completion-function)
5417 'org-pcomplete-initial)
5418 (set (make-local-variable 'pcomplete-command-name-function)
5419 'org-command-at-point)
5420 (set (make-local-variable 'pcomplete-default-completion-function)
5421 'ignore)
5422 (set (make-local-variable 'pcomplete-parse-arguments-function)
5423 'org-parse-arguments)
5424 (set (make-local-variable 'pcomplete-termination-string) "")
5425 (when (>= emacs-major-version 23)
5426 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5428 ;; If empty file that did not turn on org-mode automatically, make it to.
5429 (if (and org-insert-mode-line-in-empty-file
5430 (org-called-interactively-p 'any)
5431 (= (point-min) (point-max)))
5432 (insert "# -*- mode: org -*-\n\n"))
5433 (unless org-inhibit-startup
5434 (org-unmodified
5435 (and org-startup-with-beamer-mode (org-beamer-mode))
5436 (when org-startup-align-all-tables
5437 (org-table-map-tables 'org-table-align 'quietly))
5438 (when org-startup-with-inline-images
5439 (org-display-inline-images))
5440 (when org-startup-with-latex-preview
5441 (org-preview-latex-fragment))
5442 (unless org-inhibit-startup-visibility-stuff
5443 (org-set-startup-visibility))))
5444 ;; Try to set org-hide correctly
5445 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5447 ;; Update `customize-package-emacs-version-alist'
5448 (add-to-list 'customize-package-emacs-version-alist
5449 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5450 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5451 ("8.0" . "24.4")))
5453 (defvar org-mode-transpose-word-syntax-table
5454 (let ((st (make-syntax-table)))
5455 (mapc (lambda(c) (modify-syntax-entry
5456 (string-to-char (car c)) "w p" st))
5457 org-emphasis-alist)
5458 st))
5460 (when (fboundp 'abbrev-table-put)
5461 (abbrev-table-put org-mode-abbrev-table
5462 :parents (list text-mode-abbrev-table)))
5464 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5466 (defsubst org-fix-ellipsis-at-bol ()
5467 (save-excursion (goto-char (window-start)) (recenter 0)))
5469 (defun org-find-invisible-foreground ()
5470 (let ((candidates (remove
5471 "unspecified-bg"
5472 (nconc
5473 (list (face-background 'default)
5474 (face-background 'org-default))
5475 (mapcar
5476 (lambda (alist)
5477 (when (boundp alist)
5478 (cdr (assoc 'background-color (symbol-value alist)))))
5479 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5480 (list (face-foreground 'org-hide))))))
5481 (car (remove nil candidates))))
5483 (defun org-current-time (&optional rounding-minutes past)
5484 "Current time, possibly rounded to ROUNDING-MINUTES.
5485 When ROUNDING-MINUTES is not an integer, fall back on the car of
5486 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5487 the rounding returns a past time."
5488 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5489 (car org-time-stamp-rounding-minutes)))
5490 (time (decode-time)) res)
5491 (if (< r 1)
5492 (current-time)
5493 (setq res
5494 (apply 'encode-time
5495 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5496 (nthcdr 2 time))))
5497 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5498 (seconds-to-time (- (org-float-time res) (* r 60)))
5499 res))))
5501 (defun org-today ()
5502 "Return today date, considering `org-extend-today-until'."
5503 (time-to-days
5504 (time-subtract (current-time)
5505 (list 0 (* 3600 org-extend-today-until) 0))))
5507 ;;;; Font-Lock stuff, including the activators
5509 (defvar org-mouse-map (make-sparse-keymap))
5510 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5511 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5512 (when org-mouse-1-follows-link
5513 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5514 (when org-tab-follows-link
5515 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5516 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5518 (require 'font-lock)
5520 (defconst org-non-link-chars "]\t\n\r<>")
5521 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5522 "shell" "elisp" "doi" "message"))
5523 (defvar org-link-types-re nil
5524 "Matches a link that has a url-like prefix like \"http:\"")
5525 (defvar org-link-re-with-space nil
5526 "Matches a link with spaces, optional angular brackets around it.")
5527 (defvar org-link-re-with-space2 nil
5528 "Matches a link with spaces, optional angular brackets around it.")
5529 (defvar org-link-re-with-space3 nil
5530 "Matches a link with spaces, only for internal part in bracket links.")
5531 (defvar org-angle-link-re nil
5532 "Matches link with angular brackets, spaces are allowed.")
5533 (defvar org-plain-link-re nil
5534 "Matches plain link, without spaces.")
5535 (defvar org-bracket-link-regexp nil
5536 "Matches a link in double brackets.")
5537 (defvar org-bracket-link-analytic-regexp nil
5538 "Regular expression used to analyze links.
5539 Here is what the match groups contain after a match:
5540 1: http:
5541 2: http
5542 3: path
5543 4: [desc]
5544 5: desc")
5545 (defvar org-bracket-link-analytic-regexp++ nil
5546 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5547 (defvar org-any-link-re nil
5548 "Regular expression matching any link.")
5550 (defconst org-match-sexp-depth 3
5551 "Number of stacked braces for sub/superscript matching.")
5553 (defun org-create-multibrace-regexp (left right n)
5554 "Create a regular expression which will match a balanced sexp.
5555 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5556 as single character strings.
5557 The regexp returned will match the entire expression including the
5558 delimiters. It will also define a single group which contains the
5559 match except for the outermost delimiters. The maximum depth of
5560 stacked delimiters is N. Escaping delimiters is not possible."
5561 (let* ((nothing (concat "[^" left right "]*?"))
5562 (or "\\|")
5563 (re nothing)
5564 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5565 (while (> n 1)
5566 (setq n (1- n)
5567 re (concat re or next)
5568 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5569 (concat left "\\(" re "\\)" right)))
5571 (defvar org-match-substring-regexp
5572 (concat
5573 "\\(\\S-\\)\\([_^]\\)\\("
5574 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5575 "\\|"
5576 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5577 "\\|"
5578 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5579 "The regular expression matching a sub- or superscript.")
5581 (defvar org-match-substring-with-braces-regexp
5582 (concat
5583 "\\(\\S-\\)\\([_^]\\)\\("
5584 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5585 "\\)")
5586 "The regular expression matching a sub- or superscript, forcing braces.")
5588 (defun org-make-link-regexps ()
5589 "Update the link regular expressions.
5590 This should be called after the variable `org-link-types' has changed."
5591 (setq org-link-types-re
5592 (concat
5593 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5594 org-link-re-with-space
5595 (concat
5596 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5597 "\\([^" org-non-link-chars " ]"
5598 "[^" org-non-link-chars "]*"
5599 "[^" org-non-link-chars " ]\\)>?")
5600 org-link-re-with-space2
5601 (concat
5602 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5603 "\\([^" org-non-link-chars " ]"
5604 "[^\t\n\r]*"
5605 "[^" org-non-link-chars " ]\\)>?")
5606 org-link-re-with-space3
5607 (concat
5608 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5609 "\\([^" org-non-link-chars " ]"
5610 "[^\t\n\r]*\\)")
5611 org-angle-link-re
5612 (concat
5613 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5614 "\\([^" org-non-link-chars " ]"
5615 "[^" org-non-link-chars "]*"
5616 "\\)>")
5617 org-plain-link-re
5618 (concat
5619 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5620 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5621 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5622 org-bracket-link-regexp
5623 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5624 org-bracket-link-analytic-regexp
5625 (concat
5626 "\\[\\["
5627 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5628 "\\([^]]+\\)"
5629 "\\]"
5630 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5631 "\\]")
5632 org-bracket-link-analytic-regexp++
5633 (concat
5634 "\\[\\["
5635 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5636 "\\([^]]+\\)"
5637 "\\]"
5638 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5639 "\\]")
5640 org-any-link-re
5641 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5642 org-angle-link-re "\\)\\|\\("
5643 org-plain-link-re "\\)")))
5645 (org-make-link-regexps)
5647 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5648 "Regular expression for fast time stamp matching.")
5649 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5650 "Regular expression for fast time stamp matching.")
5651 (defconst org-ts-regexp0
5652 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5653 "Regular expression matching time strings for analysis.
5654 This one does not require the space after the date, so it can be used
5655 on a string that terminates immediately after the date.")
5656 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5657 "Regular expression matching time strings for analysis.")
5658 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5659 "Regular expression matching time stamps, with groups.")
5660 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5661 "Regular expression matching time stamps (also [..]), with groups.")
5662 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5663 "Regular expression matching a time stamp range.")
5664 (defconst org-tr-regexp-both
5665 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5666 "Regular expression matching a time stamp range.")
5667 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5668 org-ts-regexp "\\)?")
5669 "Regular expression matching a time stamp or time stamp range.")
5670 (defconst org-tsr-regexp-both
5671 (concat org-ts-regexp-both "\\(--?-?"
5672 org-ts-regexp-both "\\)?")
5673 "Regular expression matching a time stamp or time stamp range.
5674 The time stamps may be either active or inactive.")
5676 (defvar org-emph-face nil)
5678 (defun org-do-emphasis-faces (limit)
5679 "Run through the buffer and add overlays to emphasized strings."
5680 (let (rtn a)
5681 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5682 (if (not (= (char-after (match-beginning 3))
5683 (char-after (match-beginning 4))))
5684 (progn
5685 (setq rtn t)
5686 (setq a (assoc (match-string 3) org-emphasis-alist))
5687 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5688 'face
5689 (nth 1 a))
5690 (and (nth 4 a)
5691 (org-remove-flyspell-overlays-in
5692 (match-beginning 0) (match-end 0)))
5693 (add-text-properties (match-beginning 2) (match-end 2)
5694 '(font-lock-multiline t org-emphasis t))
5695 (when org-hide-emphasis-markers
5696 (add-text-properties (match-end 4) (match-beginning 5)
5697 '(invisible org-link))
5698 (add-text-properties (match-beginning 3) (match-end 3)
5699 '(invisible org-link)))))
5700 (backward-char 1))
5701 rtn))
5703 (defun org-emphasize (&optional char)
5704 "Insert or change an emphasis, i.e. a font like bold or italic.
5705 If there is an active region, change that region to a new emphasis.
5706 If there is no region, just insert the marker characters and position
5707 the cursor between them.
5708 CHAR should be the marker character. If it is a space, it means to
5709 remove the emphasis of the selected region.
5710 If CHAR is not given (for example in an interactive call) it will be
5711 prompted for."
5712 (interactive)
5713 (let ((erc org-emphasis-regexp-components)
5714 (prompt "")
5715 (string "") beg end move c s)
5716 (if (org-region-active-p)
5717 (setq beg (region-beginning) end (region-end)
5718 string (buffer-substring beg end))
5719 (setq move t))
5721 (unless char
5722 (message "Emphasis marker or tag: [%s]"
5723 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5724 (setq char (read-char-exclusive)))
5725 (if (equal char ?\ )
5726 (setq s "" move nil)
5727 (unless (assoc (char-to-string char) org-emphasis-alist)
5728 (user-error "No such emphasis marker: \"%c\"" char))
5729 (setq s (char-to-string char)))
5730 (while (and (> (length string) 1)
5731 (equal (substring string 0 1) (substring string -1))
5732 (assoc (substring string 0 1) org-emphasis-alist))
5733 (setq string (substring string 1 -1)))
5734 (setq string (concat s string s))
5735 (if beg (delete-region beg end))
5736 (unless (or (bolp)
5737 (string-match (concat "[" (nth 0 erc) "\n]")
5738 (char-to-string (char-before (point)))))
5739 (insert " "))
5740 (unless (or (eobp)
5741 (string-match (concat "[" (nth 1 erc) "\n]")
5742 (char-to-string (char-after (point)))))
5743 (insert " ") (backward-char 1))
5744 (insert string)
5745 (and move (backward-char 1))))
5747 (defconst org-nonsticky-props
5748 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5750 (defsubst org-rear-nonsticky-at (pos)
5751 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5753 (defun org-activate-plain-links (limit)
5754 "Run through the buffer and add overlays to links."
5755 (let (f hl)
5756 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5757 (not (org-in-src-block-p)))
5758 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5759 (setq f (get-text-property (match-beginning 0) 'face))
5760 (setq hl (org-match-string-no-properties 0))
5761 (if (or (eq f 'org-tag)
5762 (and (listp f) (memq 'org-tag f)))
5764 (add-text-properties (match-beginning 0) (match-end 0)
5765 (list 'mouse-face 'highlight
5766 'face 'org-link
5767 'htmlize-link `(:uri ,hl)
5768 'keymap org-mouse-map))
5769 (org-rear-nonsticky-at (match-end 0)))
5770 t)))
5772 (defun org-activate-code (limit)
5773 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5774 (progn
5775 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5776 (remove-text-properties (match-beginning 0) (match-end 0)
5777 '(display t invisible t intangible t))
5778 t)))
5780 (defcustom org-src-fontify-natively nil
5781 "When non-nil, fontify code in code blocks."
5782 :type 'boolean
5783 :version "24.1"
5784 :group 'org-appearance
5785 :group 'org-babel)
5787 (defcustom org-allow-promoting-top-level-subtree nil
5788 "When non-nil, allow promoting a top level subtree.
5789 The leading star of the top level headline will be replaced
5790 by a #."
5791 :type 'boolean
5792 :version "24.1"
5793 :group 'org-appearance)
5795 (defun org-fontify-meta-lines-and-blocks (limit)
5796 (condition-case nil
5797 (org-fontify-meta-lines-and-blocks-1 limit)
5798 (error (message "org-mode fontification error"))))
5800 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5801 "Fontify #+ lines and blocks."
5802 (let ((case-fold-search t))
5803 (if (re-search-forward
5804 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5805 limit t)
5806 (let ((beg (match-beginning 0))
5807 (block-start (match-end 0))
5808 (block-end nil)
5809 (lang (match-string 7))
5810 (beg1 (line-beginning-position 2))
5811 (dc1 (downcase (match-string 2)))
5812 (dc3 (downcase (match-string 3)))
5813 end end1 quoting block-type ovl)
5814 (cond
5815 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5816 ;; a single line of backend-specific content
5817 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5818 (remove-text-properties (match-beginning 0) (match-end 0)
5819 '(display t invisible t intangible t))
5820 (add-text-properties (match-beginning 1) (match-end 3)
5821 '(font-lock-fontified t face org-meta-line))
5822 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5823 '(font-lock-fontified t face org-block))
5824 ; for backend-specific code
5826 ((and (match-end 4) (equal dc3 "+begin"))
5827 ;; Truly a block
5828 (setq block-type (downcase (match-string 5))
5829 quoting (member block-type org-protecting-blocks))
5830 (when (re-search-forward
5831 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5832 nil t) ;; on purpose, we look further than LIMIT
5833 (setq end (min (point-max) (match-end 0))
5834 end1 (min (point-max) (1- (match-beginning 0))))
5835 (setq block-end (match-beginning 0))
5836 (when quoting
5837 (remove-text-properties beg end
5838 '(display t invisible t intangible t)))
5839 (add-text-properties
5840 beg end
5841 '(font-lock-fontified t font-lock-multiline t))
5842 (add-text-properties beg beg1 '(face org-meta-line))
5843 (add-text-properties end1 (min (point-max) (1+ end))
5844 '(face org-meta-line)) ; for end_src
5845 (cond
5846 ((and lang (not (string= lang "")) org-src-fontify-natively)
5847 (org-src-font-lock-fontify-block lang block-start block-end)
5848 ;; remove old background overlays
5849 (mapc (lambda (ov)
5850 (if (eq (overlay-get ov 'face) 'org-block-background)
5851 (delete-overlay ov)))
5852 (overlays-at (/ (+ beg1 block-end) 2)))
5853 ;; add a background overlay
5854 (setq ovl (make-overlay beg1 block-end))
5855 (overlay-put ovl 'face 'org-block-background)
5856 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5857 (quoting
5858 (add-text-properties beg1 (min (point-max) (1+ end1))
5859 '(face org-block))) ; end of source block
5860 ((not org-fontify-quote-and-verse-blocks))
5861 ((string= block-type "quote")
5862 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5863 ((string= block-type "verse")
5864 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5865 (add-text-properties beg beg1 '(face org-block-begin-line))
5866 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5867 '(face org-block-end-line))
5869 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5870 (add-text-properties
5871 beg (match-end 3)
5872 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5873 '(font-lock-fontified t invisible t)
5874 '(font-lock-fontified t face org-document-info-keyword)))
5875 (add-text-properties
5876 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5877 (if (string-equal dc1 "+title:")
5878 '(font-lock-fontified t face org-document-title)
5879 '(font-lock-fontified t face org-document-info))))
5880 ((or (equal dc1 "+results")
5881 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5882 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5883 "+call:" "+header:" "+headers:" "+name:"))
5884 (and (match-end 4) (equal dc3 "+attr")))
5885 (add-text-properties
5886 beg (match-end 0)
5887 '(font-lock-fontified t face org-meta-line))
5889 ((member dc3 '(" " ""))
5890 (add-text-properties
5891 beg (match-end 0)
5892 '(font-lock-fontified t face font-lock-comment-face)))
5893 ((not (member (char-after beg) '(?\ ?\t)))
5894 ;; just any other in-buffer setting, but not indented
5895 (add-text-properties
5896 beg (match-end 0)
5897 '(font-lock-fontified t face org-meta-line))
5899 (t nil))))))
5901 (defun org-activate-angle-links (limit)
5902 "Run through the buffer and add overlays to links."
5903 (if (and (re-search-forward org-angle-link-re limit t)
5904 (not (org-in-src-block-p)))
5905 (progn
5906 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5907 (add-text-properties (match-beginning 0) (match-end 0)
5908 (list 'mouse-face 'highlight
5909 'keymap org-mouse-map))
5910 (org-rear-nonsticky-at (match-end 0))
5911 t)))
5913 (defun org-activate-footnote-links (limit)
5914 "Run through the buffer and add overlays to footnotes."
5915 (let ((fn (org-footnote-next-reference-or-definition limit)))
5916 (when fn
5917 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5918 (org-remove-flyspell-overlays-in beg end)
5919 (add-text-properties beg end
5920 (list 'mouse-face 'highlight
5921 'keymap org-mouse-map
5922 'help-echo
5923 (if (= (point-at-bol) beg)
5924 "Footnote definition"
5925 "Footnote reference")
5926 'font-lock-fontified t
5927 'font-lock-multiline t
5928 'face 'org-footnote))))))
5930 (defun org-activate-bracket-links (limit)
5931 "Run through the buffer and add overlays to bracketed links."
5932 (if (and (re-search-forward org-bracket-link-regexp limit t)
5933 (not (org-in-src-block-p)))
5934 (let* ((hl (org-match-string-no-properties 1))
5935 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5936 (ip (org-maybe-intangible
5937 (list 'invisible 'org-link
5938 'keymap org-mouse-map 'mouse-face 'highlight
5939 'font-lock-multiline t 'help-echo help
5940 'htmlize-link `(:uri ,hl))))
5941 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5942 'font-lock-multiline t 'help-echo help
5943 'htmlize-link `(:uri ,hl))))
5944 ;; We need to remove the invisible property here. Table narrowing
5945 ;; may have made some of this invisible.
5946 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5947 (remove-text-properties (match-beginning 0) (match-end 0)
5948 '(invisible nil))
5949 (if (match-end 3)
5950 (progn
5951 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5952 (org-rear-nonsticky-at (match-beginning 3))
5953 (add-text-properties (match-beginning 3) (match-end 3) vp)
5954 (org-rear-nonsticky-at (match-end 3))
5955 (add-text-properties (match-end 3) (match-end 0) ip)
5956 (org-rear-nonsticky-at (match-end 0)))
5957 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5958 (org-rear-nonsticky-at (match-beginning 1))
5959 (add-text-properties (match-beginning 1) (match-end 1) vp)
5960 (org-rear-nonsticky-at (match-end 1))
5961 (add-text-properties (match-end 1) (match-end 0) ip)
5962 (org-rear-nonsticky-at (match-end 0)))
5963 t)))
5965 (defun org-activate-dates (limit)
5966 "Run through the buffer and add overlays to dates."
5967 (if (and (re-search-forward org-tsr-regexp-both limit t)
5968 (not (equal (char-before (match-beginning 0)) 91)))
5969 (progn
5970 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5971 (add-text-properties (match-beginning 0) (match-end 0)
5972 (list 'mouse-face 'highlight
5973 'keymap org-mouse-map))
5974 (org-rear-nonsticky-at (match-end 0))
5975 (when org-display-custom-times
5976 (if (match-end 3)
5977 (org-display-custom-time (match-beginning 3) (match-end 3)))
5978 (org-display-custom-time (match-beginning 1) (match-end 1)))
5979 t)))
5981 (defvar org-target-link-regexp nil
5982 "Regular expression matching radio targets in plain text.")
5983 (make-variable-buffer-local 'org-target-link-regexp)
5984 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5985 "Regular expression matching a link target.")
5986 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5987 "Regular expression matching a radio target.")
5988 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5989 "Regular expression matching any target.")
5991 (defun org-activate-target-links (limit)
5992 "Run through the buffer and add overlays to target matches."
5993 (when org-target-link-regexp
5994 (let ((case-fold-search t))
5995 (if (re-search-forward org-target-link-regexp limit t)
5996 (progn
5997 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5998 (add-text-properties (match-beginning 0) (match-end 0)
5999 (list 'mouse-face 'highlight
6000 'keymap org-mouse-map
6001 'help-echo "Radio target link"
6002 'org-linked-text t))
6003 (org-rear-nonsticky-at (match-end 0))
6004 t)))))
6006 (defun org-update-radio-target-regexp ()
6007 "Find all radio targets in this file and update the regular expression."
6008 (interactive)
6009 (when (memq 'radio org-activate-links)
6010 (setq org-target-link-regexp
6011 (org-make-target-link-regexp (org-all-targets 'radio)))
6012 (org-restart-font-lock)))
6014 (defun org-hide-wide-columns (limit)
6015 (let (s e)
6016 (setq s (text-property-any (point) (or limit (point-max))
6017 'org-cwidth t))
6018 (when s
6019 (setq e (next-single-property-change s 'org-cwidth))
6020 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6021 (goto-char e)
6022 t)))
6024 (defvar org-latex-and-related-regexp nil
6025 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6026 (defvar org-match-substring-regexp)
6027 (defvar org-match-substring-with-braces-regexp)
6029 (defun org-compute-latex-and-related-regexp ()
6030 "Compute regular expression for LaTeX, entities and sub/superscript.
6031 Result depends on variable `org-highlight-latex-and-related'."
6032 (org-set-local
6033 'org-latex-and-related-regexp
6034 (let* ((re-sub
6035 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6036 ((eq org-use-sub-superscripts '{})
6037 (list org-match-substring-with-braces-regexp))
6038 (org-use-sub-superscripts (list org-match-substring-regexp))))
6039 (re-latex
6040 (when (memq 'latex org-highlight-latex-and-related)
6041 (let ((matchers (plist-get org-format-latex-options :matchers)))
6042 (delq nil
6043 (mapcar (lambda (x)
6044 (and (member (car x) matchers) (nth 1 x)))
6045 org-latex-regexps)))))
6046 (re-entities
6047 (when (memq 'entities org-highlight-latex-and-related)
6048 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6049 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6051 (defun org-do-latex-and-related (limit)
6052 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6053 LIMIT bounds the search for syntax to highlight. Stop at first
6054 highlighted object, if any. Return t if some highlighting was
6055 done, nil otherwise."
6056 (when (org-string-nw-p org-latex-and-related-regexp)
6057 (catch 'found
6058 (while (re-search-forward org-latex-and-related-regexp limit t)
6059 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6060 'face))
6061 '(org-code org-verbatim underline))
6062 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6063 '(?_ ?^))
6065 0)))
6066 (font-lock-prepend-text-property
6067 (+ offset (match-beginning 0)) (match-end 0)
6068 'face 'org-latex-and-related)
6069 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6070 '(font-lock-multiline t)))
6071 (throw 'found t)))
6072 nil)))
6074 (defun org-restart-font-lock ()
6075 "Restart `font-lock-mode', to force refontification."
6076 (when (and (boundp 'font-lock-mode) font-lock-mode)
6077 (font-lock-mode -1)
6078 (font-lock-mode 1)))
6080 (defun org-all-targets (&optional radio)
6081 "Return a list of all targets in this file.
6082 When optional argument RADIO is non-nil, only find radio
6083 targets."
6084 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6085 (save-excursion
6086 (goto-char (point-min))
6087 (while (re-search-forward re nil t)
6088 ;; Make sure point is really within the object.
6089 (backward-char)
6090 (let ((obj (org-element-context)))
6091 (when (memq (org-element-type obj) '(radio-target target))
6092 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6093 rtn)))
6095 (defun org-make-target-link-regexp (targets)
6096 "Make regular expression matching all strings in TARGETS.
6097 The regular expression finds the targets also if there is a line break
6098 between words."
6099 (and targets
6100 (concat
6101 "\\<\\("
6102 (mapconcat
6103 (lambda (x)
6104 (setq x (regexp-quote x))
6105 (while (string-match " +" x)
6106 (setq x (replace-match "\\s-+" t t x)))
6108 targets
6109 "\\|")
6110 "\\)\\>")))
6112 (defun org-activate-tags (limit)
6113 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6114 (progn
6115 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6116 (add-text-properties (match-beginning 1) (match-end 1)
6117 (list 'mouse-face 'highlight
6118 'keymap org-mouse-map))
6119 (org-rear-nonsticky-at (match-end 1))
6120 t)))
6122 (defun org-outline-level ()
6123 "Compute the outline level of the heading at point.
6124 If this is called at a normal headline, the level is the number of stars.
6125 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6126 (save-excursion
6127 (if (not (condition-case nil
6128 (org-back-to-heading t)
6129 (error nil)))
6131 (looking-at org-outline-regexp)
6132 (1- (- (match-end 0) (match-beginning 0))))))
6134 (defvar org-font-lock-keywords nil)
6136 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6137 "Regular expression matching a property line.")
6139 (defvar org-font-lock-hook nil
6140 "Functions to be called for special font lock stuff.")
6142 (defvar org-font-lock-set-keywords-hook nil
6143 "Functions that can manipulate `org-font-lock-extra-keywords'.
6144 This is called after `org-font-lock-extra-keywords' is defined, but before
6145 it is installed to be used by font lock. This can be useful if something
6146 needs to be inserted at a specific position in the font-lock sequence.")
6148 (defun org-font-lock-hook (limit)
6149 "Run `org-font-lock-hook' within LIMIT."
6150 (run-hook-with-args 'org-font-lock-hook limit))
6152 (defun org-set-font-lock-defaults ()
6153 "Set font lock defaults for the current buffer."
6154 (let* ((em org-fontify-emphasized-text)
6155 (lk org-activate-links)
6156 (org-font-lock-extra-keywords
6157 (list
6158 ;; Call the hook
6159 '(org-font-lock-hook)
6160 ;; Headlines
6161 `(,(if org-fontify-whole-heading-line
6162 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6163 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6164 (1 (org-get-level-face 1))
6165 (2 (org-get-level-face 2))
6166 (3 (org-get-level-face 3)))
6167 ;; Table lines
6168 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6169 (1 'org-table t))
6170 ;; Table internals
6171 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6172 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6173 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6174 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6175 ;; Drawers
6176 (list org-drawer-regexp '(0 'org-special-keyword t))
6177 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6178 ;; Properties
6179 (list org-property-re
6180 '(1 'org-special-keyword t)
6181 '(3 'org-property-value t))
6182 ;; Links
6183 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6184 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6185 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6186 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6187 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6188 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6189 (if (memq 'footnote lk) '(org-activate-footnote-links))
6190 ;; Targets.
6191 (list org-any-target-regexp '(0 'org-target t))
6192 ;; Diary sexps.
6193 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6194 ;; Macro
6195 '("{{{.+}}}" (0 'org-macro t))
6196 '(org-hide-wide-columns (0 nil append))
6197 ;; TODO keyword
6198 (list (format org-heading-keyword-regexp-format
6199 org-todo-regexp)
6200 '(2 (org-get-todo-face 2) t))
6201 ;; DONE
6202 (if org-fontify-done-headline
6203 (list (format org-heading-keyword-regexp-format
6204 (concat
6205 "\\(?:"
6206 (mapconcat 'regexp-quote org-done-keywords "\\|")
6207 "\\)"))
6208 '(2 'org-headline-done t))
6209 nil)
6210 ;; Priorities
6211 '(org-font-lock-add-priority-faces)
6212 ;; Tags
6213 '(org-font-lock-add-tag-faces)
6214 ;; Tags groups
6215 (if (and org-group-tags org-tag-groups-alist)
6216 (list (concat org-outline-regexp-bol ".+\\(:"
6217 (regexp-opt (mapcar 'car org-tag-groups-alist))
6218 ":\\).*$")
6219 '(1 'org-tag-group prepend)))
6220 ;; Special keywords
6221 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6222 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6223 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6224 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6225 ;; Emphasis
6226 (if em
6227 (if (featurep 'xemacs)
6228 '(org-do-emphasis-faces (0 nil append))
6229 '(org-do-emphasis-faces)))
6230 ;; Checkboxes
6231 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6232 1 'org-checkbox prepend)
6233 (if (cdr (assq 'checkbox org-list-automatic-rules))
6234 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6235 (0 (org-get-checkbox-statistics-face) t)))
6236 ;; Description list items
6237 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6238 1 'org-list-dt prepend)
6239 ;; ARCHIVEd headings
6240 (list (concat
6241 org-outline-regexp-bol
6242 "\\(.*:" org-archive-tag ":.*\\)")
6243 '(1 'org-archived prepend))
6244 ;; Specials
6245 '(org-do-latex-and-related)
6246 '(org-fontify-entities)
6247 '(org-raise-scripts)
6248 ;; Code
6249 '(org-activate-code (1 'org-code t))
6250 ;; COMMENT
6251 (list (format org-heading-keyword-regexp-format
6252 (concat "\\("
6253 org-comment-string "\\|" org-quote-string
6254 "\\)"))
6255 '(2 'org-special-keyword t))
6256 ;; Blocks and meta lines
6257 '(org-fontify-meta-lines-and-blocks))))
6258 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6259 (run-hooks 'org-font-lock-set-keywords-hook)
6260 ;; Now set the full font-lock-keywords
6261 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6262 (org-set-local 'font-lock-defaults
6263 '(org-font-lock-keywords t nil nil backward-paragraph))
6264 (kill-local-variable 'font-lock-keywords) nil))
6266 (defun org-toggle-pretty-entities ()
6267 "Toggle the composition display of entities as UTF8 characters."
6268 (interactive)
6269 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6270 (org-restart-font-lock)
6271 (if org-pretty-entities
6272 (message "Entities are now displayed as UTF8 characters")
6273 (save-restriction
6274 (widen)
6275 (org-decompose-region (point-min) (point-max))
6276 (message "Entities are now displayed as plain text"))))
6278 (defvar org-custom-properties-overlays nil
6279 "List of overlays used for custom properties.")
6280 (make-variable-buffer-local 'org-custom-properties-overlays)
6282 (defun org-toggle-custom-properties-visibility ()
6283 "Display or hide properties in `org-custom-properties'."
6284 (interactive)
6285 (if org-custom-properties-overlays
6286 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6287 (setq org-custom-properties-overlays nil))
6288 (unless (not org-custom-properties)
6289 (save-excursion
6290 (save-restriction
6291 (widen)
6292 (goto-char (point-min))
6293 (while (re-search-forward org-property-re nil t)
6294 (mapc (lambda(p)
6295 (when (equal p (substring (match-string 1) 1 -1))
6296 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6297 (overlay-put o 'invisible t)
6298 (overlay-put o 'org-custom-property t)
6299 (push o org-custom-properties-overlays))))
6300 org-custom-properties)))))))
6302 (defun org-fontify-entities (limit)
6303 "Find an entity to fontify."
6304 (let (ee)
6305 (when org-pretty-entities
6306 (catch 'match
6307 (while (re-search-forward
6308 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6309 limit t)
6310 (if (and (not (org-in-indented-comment-line))
6311 (setq ee (org-entity-get (match-string 1)))
6312 (= (length (nth 6 ee)) 1))
6313 (let*
6314 ((end (if (equal (match-string 2) "{}")
6315 (match-end 2)
6316 (match-end 1))))
6317 (add-text-properties
6318 (match-beginning 0) end
6319 (list 'font-lock-fontified t))
6320 (compose-region (match-beginning 0) end
6321 (nth 6 ee) nil)
6322 (backward-char 1)
6323 (throw 'match t))))
6324 nil))))
6326 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6327 "Fontify string S like in Org-mode."
6328 (with-temp-buffer
6329 (insert s)
6330 (let ((org-odd-levels-only odd-levels))
6331 (org-mode)
6332 (font-lock-fontify-buffer)
6333 (buffer-string))))
6335 (defvar org-m nil)
6336 (defvar org-l nil)
6337 (defvar org-f nil)
6338 (defun org-get-level-face (n)
6339 "Get the right face for match N in font-lock matching of headlines."
6340 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6341 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6342 (if org-cycle-level-faces
6343 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6344 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6345 (cond
6346 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6347 ((eq n 2) org-f)
6348 (t (if org-level-color-stars-only nil org-f))))
6351 (defun org-get-todo-face (kwd)
6352 "Get the right face for a TODO keyword KWD.
6353 If KWD is a number, get the corresponding match group."
6354 (if (numberp kwd) (setq kwd (match-string kwd)))
6355 (or (org-face-from-face-or-color
6356 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6357 (and (member kwd org-done-keywords) 'org-done)
6358 'org-todo))
6360 (defun org-face-from-face-or-color (context inherit face-or-color)
6361 "Create a face list that inherits INHERIT, but sets the foreground color.
6362 When FACE-OR-COLOR is not a string, just return it."
6363 (if (stringp face-or-color)
6364 (list :inherit inherit
6365 (cdr (assoc context org-faces-easy-properties))
6366 face-or-color)
6367 face-or-color))
6369 (defun org-font-lock-add-tag-faces (limit)
6370 "Add the special tag faces."
6371 (when (and org-tag-faces org-tags-special-faces-re)
6372 (while (re-search-forward org-tags-special-faces-re limit t)
6373 (add-text-properties (match-beginning 1) (match-end 1)
6374 (list 'face (org-get-tag-face 1)
6375 'font-lock-fontified t))
6376 (backward-char 1))))
6378 (defun org-font-lock-add-priority-faces (limit)
6379 "Add the special priority faces."
6380 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6381 (when (save-match-data (org-at-heading-p))
6382 (add-text-properties
6383 (match-beginning 0) (match-end 0)
6384 (list 'face (or (org-face-from-face-or-color
6385 'priority 'org-priority
6386 (cdr (assoc (char-after (match-beginning 1))
6387 org-priority-faces)))
6388 'org-priority)
6389 'font-lock-fontified t)))))
6391 (defun org-get-tag-face (kwd)
6392 "Get the right face for a TODO keyword KWD.
6393 If KWD is a number, get the corresponding match group."
6394 (if (numberp kwd) (setq kwd (match-string kwd)))
6395 (or (org-face-from-face-or-color
6396 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6397 'org-tag))
6399 (defun org-unfontify-region (beg end &optional maybe_loudly)
6400 "Remove fontification and activation overlays from links."
6401 (font-lock-default-unfontify-region beg end)
6402 (let* ((buffer-undo-list t)
6403 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6404 (inhibit-modification-hooks t)
6405 deactivate-mark buffer-file-name buffer-file-truename)
6406 (org-decompose-region beg end)
6407 (remove-text-properties beg end
6408 '(mouse-face t keymap t org-linked-text t
6409 invisible t intangible t
6410 org-no-flyspell t org-emphasis t))
6411 (org-remove-font-lock-display-properties beg end)))
6413 (defconst org-script-display '(((raise -0.3) (height 0.7))
6414 ((raise 0.3) (height 0.7))
6415 ((raise -0.5))
6416 ((raise 0.5)))
6417 "Display properties for showing superscripts and subscripts.")
6419 (defun org-remove-font-lock-display-properties (beg end)
6420 "Remove specific display properties that have been added by font lock.
6421 The will remove the raise properties that are used to show superscripts
6422 and subscripts."
6423 (let (next prop)
6424 (while (< beg end)
6425 (setq next (next-single-property-change beg 'display nil end)
6426 prop (get-text-property beg 'display))
6427 (if (member prop org-script-display)
6428 (put-text-property beg next 'display nil))
6429 (setq beg next))))
6431 (defun org-raise-scripts (limit)
6432 "Add raise properties to sub/superscripts."
6433 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6434 (if (re-search-forward
6435 (if (eq org-use-sub-superscripts t)
6436 org-match-substring-regexp
6437 org-match-substring-with-braces-regexp)
6438 limit t)
6439 (let* ((pos (point)) table-p comment-p
6440 (mpos (match-beginning 3))
6441 (emph-p (get-text-property mpos 'org-emphasis))
6442 (link-p (get-text-property mpos 'mouse-face))
6443 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6444 (goto-char (point-at-bol))
6445 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6446 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6447 (goto-char pos)
6448 ;; Handle a_b^c
6449 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6450 (if (or comment-p emph-p link-p keyw-p)
6452 (put-text-property (match-beginning 3) (match-end 0)
6453 'display
6454 (if (equal (char-after (match-beginning 2)) ?^)
6455 (nth (if table-p 3 1) org-script-display)
6456 (nth (if table-p 2 0) org-script-display)))
6457 (add-text-properties (match-beginning 2) (match-end 2)
6458 (list 'invisible t
6459 'org-dwidth t 'org-dwidth-n 1))
6460 (if (and (eq (char-after (match-beginning 3)) ?{)
6461 (eq (char-before (match-end 3)) ?}))
6462 (progn
6463 (add-text-properties
6464 (match-beginning 3) (1+ (match-beginning 3))
6465 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6466 (add-text-properties
6467 (1- (match-end 3)) (match-end 3)
6468 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6469 t)))))
6471 ;;;; Visibility cycling, including org-goto and indirect buffer
6473 ;;; Cycling
6475 (defvar org-cycle-global-status nil)
6476 (make-variable-buffer-local 'org-cycle-global-status)
6477 (put 'org-cycle-global-status 'org-state t)
6478 (defvar org-cycle-subtree-status nil)
6479 (make-variable-buffer-local 'org-cycle-subtree-status)
6480 (put 'org-cycle-subtree-status 'org-state t)
6482 (defvar org-inlinetask-min-level)
6484 ;;;###autoload
6485 (defun org-cycle (&optional arg)
6486 "TAB-action and visibility cycling for Org-mode.
6488 This is the command invoked in Org-mode by the TAB key. Its main purpose
6489 is outline visibility cycling, but it also invokes other actions
6490 in special contexts.
6492 - When this function is called with a prefix argument, rotate the entire
6493 buffer through 3 states (global cycling)
6494 1. OVERVIEW: Show only top-level headlines.
6495 2. CONTENTS: Show all headlines of all levels, but no body text.
6496 3. SHOW ALL: Show everything.
6497 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6498 determined by the variable `org-startup-folded', and by any VISIBILITY
6499 properties in the buffer.
6500 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6501 including any drawers.
6503 - When inside a table, re-align the table and move to the next field.
6505 - When point is at the beginning of a headline, rotate the subtree started
6506 by this line through 3 different states (local cycling)
6507 1. FOLDED: Only the main headline is shown.
6508 2. CHILDREN: The main headline and the direct children are shown.
6509 From this state, you can move to one of the children
6510 and zoom in further.
6511 3. SUBTREE: Show the entire subtree, including body text.
6512 If there is no subtree, switch directly from CHILDREN to FOLDED.
6514 - When point is at the beginning of an empty headline and the variable
6515 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6516 of the headline by demoting and promoting it to likely levels. This
6517 speeds up creation document structure by pressing TAB once or several
6518 times right after creating a new headline.
6520 - When there is a numeric prefix, go up to a heading with level ARG, do
6521 a `show-subtree' and return to the previous cursor position. If ARG
6522 is negative, go up that many levels.
6524 - When point is not at the beginning of a headline, execute the global
6525 binding for TAB, which is re-indenting the line. See the option
6526 `org-cycle-emulate-tab' for details.
6528 - Special case: if point is at the beginning of the buffer and there is
6529 no headline in line 1, this function will act as if called with prefix arg
6530 (C-u TAB, same as S-TAB) also when called without prefix arg.
6531 But only if also the variable `org-cycle-global-at-bob' is t."
6532 (interactive "P")
6533 (org-load-modules-maybe)
6534 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6535 (and org-cycle-level-after-item/entry-creation
6536 (or (org-cycle-level)
6537 (org-cycle-item-indentation))))
6538 (let* (message-log-max ; Don't populate the *Messages* buffer
6539 (limit-level
6540 (or org-cycle-max-level
6541 (and (boundp 'org-inlinetask-min-level)
6542 org-inlinetask-min-level
6543 (1- org-inlinetask-min-level))))
6544 (nstars (and limit-level
6545 (if org-odd-levels-only
6546 (and limit-level (1- (* limit-level 2)))
6547 limit-level)))
6548 (org-outline-regexp
6549 (if (not (derived-mode-p 'org-mode))
6550 outline-regexp
6551 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6552 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6553 (not (looking-at org-outline-regexp))))
6554 (org-cycle-hook
6555 (if bob-special
6556 (delq 'org-optimize-window-after-visibility-change
6557 (copy-sequence org-cycle-hook))
6558 org-cycle-hook))
6559 (pos (point)))
6561 (if (or bob-special (equal arg '(4)))
6562 ;; special case: use global cycling
6563 (setq arg t))
6565 (cond
6567 ((equal arg '(16))
6568 (setq last-command 'dummy)
6569 (org-set-startup-visibility)
6570 (message "Startup visibility, plus VISIBILITY properties"))
6572 ((equal arg '(64))
6573 (show-all)
6574 (message "Entire buffer visible, including drawers"))
6576 ;; Table: enter it or move to the next field.
6577 ((org-at-table-p 'any)
6578 (if (org-at-table.el-p)
6579 (message "Use C-c ' to edit table.el tables")
6580 (if arg (org-table-edit-field t)
6581 (org-table-justify-field-maybe)
6582 (call-interactively 'org-table-next-field))))
6584 ((run-hook-with-args-until-success
6585 'org-tab-after-check-for-table-hook))
6587 ;; Global cycling: delegate to `org-cycle-internal-global'.
6588 ((eq arg t) (org-cycle-internal-global))
6590 ;; Drawers: delegate to `org-flag-drawer'.
6591 ((and org-drawers org-drawer-regexp
6592 (save-excursion
6593 (beginning-of-line 1)
6594 (looking-at org-drawer-regexp)))
6595 (org-flag-drawer ; toggle block visibility
6596 (not (get-char-property (match-end 0) 'invisible))))
6598 ;; Show-subtree, ARG levels up from here.
6599 ((integerp arg)
6600 (save-excursion
6601 (org-back-to-heading)
6602 (outline-up-heading (if (< arg 0) (- arg)
6603 (- (funcall outline-level) arg)))
6604 (org-show-subtree)))
6606 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6607 ((and (featurep 'org-inlinetask)
6608 (org-inlinetask-at-task-p)
6609 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6610 (org-inlinetask-toggle-visibility))
6612 ((org-try-cdlatex-tab))
6614 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6615 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6616 (save-excursion (beginning-of-line 1)
6617 (looking-at org-outline-regexp)))
6618 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6619 (org-cycle-internal-local))
6621 ;; From there: TAB emulation and template completion.
6622 (buffer-read-only (org-back-to-heading))
6624 ((run-hook-with-args-until-success
6625 'org-tab-after-check-for-cycling-hook))
6627 ((org-try-structure-completion))
6629 ((run-hook-with-args-until-success
6630 'org-tab-before-tab-emulation-hook))
6632 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6633 (or (not (bolp))
6634 (not (looking-at org-outline-regexp))))
6635 (call-interactively (global-key-binding "\t")))
6637 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6638 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6639 (or (and (eq org-cycle-emulate-tab 'white)
6640 (= (match-end 0) (point-at-eol)))
6641 (and (eq org-cycle-emulate-tab 'whitestart)
6642 (>= (match-end 0) pos))))
6644 (eq org-cycle-emulate-tab t))
6645 (call-interactively (global-key-binding "\t")))
6647 (t (save-excursion
6648 (org-back-to-heading)
6649 (org-cycle)))))))
6651 (defun org-cycle-internal-global ()
6652 "Do the global cycling action."
6653 ;; Hack to avoid display of messages for .org attachments in Gnus
6654 (let (message-log-max ; Don't populate the *Messages* buffer
6655 (ga (string-match "\\*fontification" (buffer-name))))
6656 (cond
6657 ((and (eq last-command this-command)
6658 (eq org-cycle-global-status 'overview))
6659 ;; We just created the overview - now do table of contents
6660 ;; This can be slow in very large buffers, so indicate action
6661 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6662 (unless ga (message "CONTENTS..."))
6663 (org-content)
6664 (unless ga (message "CONTENTS...done"))
6665 (setq org-cycle-global-status 'contents)
6666 (run-hook-with-args 'org-cycle-hook 'contents))
6668 ((and (eq last-command this-command)
6669 (eq org-cycle-global-status 'contents))
6670 ;; We just showed the table of contents - now show everything
6671 (run-hook-with-args 'org-pre-cycle-hook 'all)
6672 (show-all)
6673 (unless ga (message "SHOW ALL"))
6674 (setq org-cycle-global-status 'all)
6675 (run-hook-with-args 'org-cycle-hook 'all))
6678 ;; Default action: go to overview
6679 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6680 (org-overview)
6681 (unless ga (message "OVERVIEW"))
6682 (setq org-cycle-global-status 'overview)
6683 (run-hook-with-args 'org-cycle-hook 'overview)))))
6685 (defun org-cycle-internal-local ()
6686 "Do the local cycling action."
6687 (let (message-log-max ; Don't populate the *Messages* buffer
6688 (goal-column 0) eoh eol eos has-children children-skipped struct)
6689 ;; First, determine end of headline (EOH), end of subtree or item
6690 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6691 (save-excursion
6692 (if (org-at-item-p)
6693 (progn
6694 (beginning-of-line)
6695 (setq struct (org-list-struct))
6696 (setq eoh (point-at-eol))
6697 (setq eos (org-list-get-item-end-before-blank (point) struct))
6698 (setq has-children (org-list-has-child-p (point) struct)))
6699 (org-back-to-heading)
6700 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6701 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6702 (setq has-children
6703 (or (save-excursion
6704 (let ((level (funcall outline-level)))
6705 (outline-next-heading)
6706 (and (org-at-heading-p t)
6707 (> (funcall outline-level) level))))
6708 (save-excursion
6709 (org-list-search-forward (org-item-beginning-re) eos t)))))
6710 ;; Determine end invisible part of buffer (EOL)
6711 (beginning-of-line 2)
6712 ;; XEmacs doesn't have `next-single-char-property-change'
6713 (if (featurep 'xemacs)
6714 (while (and (not (eobp)) ;; this is like `next-line'
6715 (get-char-property (1- (point)) 'invisible))
6716 (beginning-of-line 2))
6717 (while (and (not (eobp)) ;; this is like `next-line'
6718 (get-char-property (1- (point)) 'invisible))
6719 (goto-char (next-single-char-property-change (point) 'invisible))
6720 (and (eolp) (beginning-of-line 2))))
6721 (setq eol (point)))
6722 ;; Find out what to do next and set `this-command'
6723 (cond
6724 ((= eos eoh)
6725 ;; Nothing is hidden behind this heading
6726 (unless (org-before-first-heading-p)
6727 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6728 (message "EMPTY ENTRY")
6729 (setq org-cycle-subtree-status nil)
6730 (save-excursion
6731 (goto-char eos)
6732 (outline-next-heading)
6733 (if (outline-invisible-p) (org-flag-heading nil))))
6734 ((and (or (>= eol eos)
6735 (not (string-match "\\S-" (buffer-substring eol eos))))
6736 (or has-children
6737 (not (setq children-skipped
6738 org-cycle-skip-children-state-if-no-children))))
6739 ;; Entire subtree is hidden in one line: children view
6740 (unless (org-before-first-heading-p)
6741 (run-hook-with-args 'org-pre-cycle-hook 'children))
6742 (if (org-at-item-p)
6743 (org-list-set-item-visibility (point-at-bol) struct 'children)
6744 (org-show-entry)
6745 (org-with-limited-levels (show-children))
6746 ;; FIXME: This slows down the func way too much.
6747 ;; How keep drawers hidden in subtree anyway?
6748 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6749 ;; (org-cycle-hide-drawers 'subtree))
6751 ;; Fold every list in subtree to top-level items.
6752 (when (eq org-cycle-include-plain-lists 'integrate)
6753 (save-excursion
6754 (org-back-to-heading)
6755 (while (org-list-search-forward (org-item-beginning-re) eos t)
6756 (beginning-of-line 1)
6757 (let* ((struct (org-list-struct))
6758 (prevs (org-list-prevs-alist struct))
6759 (end (org-list-get-bottom-point struct)))
6760 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6761 (org-list-get-all-items (point) struct prevs))
6762 (goto-char (if (< end eos) end eos)))))))
6763 (message "CHILDREN")
6764 (save-excursion
6765 (goto-char eos)
6766 (outline-next-heading)
6767 (if (outline-invisible-p) (org-flag-heading nil)))
6768 (setq org-cycle-subtree-status 'children)
6769 (unless (org-before-first-heading-p)
6770 (run-hook-with-args 'org-cycle-hook 'children)))
6771 ((or children-skipped
6772 (and (eq last-command this-command)
6773 (eq org-cycle-subtree-status 'children)))
6774 ;; We just showed the children, or no children are there,
6775 ;; now show everything.
6776 (unless (org-before-first-heading-p)
6777 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6778 (outline-flag-region eoh eos nil)
6779 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6780 (setq org-cycle-subtree-status 'subtree)
6781 (unless (org-before-first-heading-p)
6782 (run-hook-with-args 'org-cycle-hook 'subtree)))
6784 ;; Default action: hide the subtree.
6785 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6786 (outline-flag-region eoh eos t)
6787 (message "FOLDED")
6788 (setq org-cycle-subtree-status 'folded)
6789 (unless (org-before-first-heading-p)
6790 (run-hook-with-args 'org-cycle-hook 'folded))))))
6792 ;;;###autoload
6793 (defun org-global-cycle (&optional arg)
6794 "Cycle the global visibility. For details see `org-cycle'.
6795 With \\[universal-argument] prefix arg, switch to startup visibility.
6796 With a numeric prefix, show all headlines up to that level."
6797 (interactive "P")
6798 (let ((org-cycle-include-plain-lists
6799 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6800 (cond
6801 ((integerp arg)
6802 (show-all)
6803 (hide-sublevels arg)
6804 (setq org-cycle-global-status 'contents))
6805 ((equal arg '(4))
6806 (org-set-startup-visibility)
6807 (message "Startup visibility, plus VISIBILITY properties."))
6809 (org-cycle '(4))))))
6811 (defun org-set-startup-visibility ()
6812 "Set the visibility required by startup options and properties."
6813 (cond
6814 ((eq org-startup-folded t)
6815 (org-cycle '(4)))
6816 ((eq org-startup-folded 'content)
6817 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6818 (org-cycle '(4)) (org-cycle '(4)))))
6819 (unless (eq org-startup-folded 'showeverything)
6820 (if org-hide-block-startup (org-hide-block-all))
6821 (org-set-visibility-according-to-property 'no-cleanup)
6822 (org-cycle-hide-archived-subtrees 'all)
6823 (org-cycle-hide-drawers 'all)
6824 (org-cycle-show-empty-lines t)))
6826 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6827 "Switch subtree visibilities according to :VISIBILITY: property."
6828 (interactive)
6829 (let (org-show-entry-below state)
6830 (save-excursion
6831 (goto-char (point-min))
6832 (while (re-search-forward
6833 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6834 nil t)
6835 (setq state (match-string 1))
6836 (save-excursion
6837 (org-back-to-heading t)
6838 (hide-subtree)
6839 (org-reveal)
6840 (cond
6841 ((equal state '("fold" "folded"))
6842 (hide-subtree))
6843 ((equal state "children")
6844 (org-show-hidden-entry)
6845 (show-children))
6846 ((equal state "content")
6847 (save-excursion
6848 (save-restriction
6849 (org-narrow-to-subtree)
6850 (org-content))))
6851 ((member state '("all" "showall"))
6852 (show-subtree)))))
6853 (unless no-cleanup
6854 (org-cycle-hide-archived-subtrees 'all)
6855 (org-cycle-hide-drawers 'all)
6856 (org-cycle-show-empty-lines 'all)))))
6858 ;; This function uses outline-regexp instead of the more fundamental
6859 ;; org-outline-regexp so that org-cycle-global works outside of Org
6860 ;; buffers, where outline-regexp is needed.
6861 (defun org-overview ()
6862 "Switch to overview mode, showing only top-level headlines.
6863 Really, this shows all headlines with level equal or greater than the level
6864 of the first headline in the buffer. This is important, because if the
6865 first headline is not level one, then (hide-sublevels 1) gives confusing
6866 results."
6867 (interactive)
6868 (let ((l (org-current-line))
6869 (level (save-excursion
6870 (goto-char (point-min))
6871 (if (re-search-forward (concat "^" outline-regexp) nil t)
6872 (progn
6873 (goto-char (match-beginning 0))
6874 (funcall outline-level))))))
6875 (and level (hide-sublevels level))
6876 (recenter '(4))
6877 (org-goto-line l)))
6879 (defun org-content (&optional arg)
6880 "Show all headlines in the buffer, like a table of contents.
6881 With numerical argument N, show content up to level N."
6882 (interactive "P")
6883 (save-excursion
6884 ;; Visit all headings and show their offspring
6885 (and (integerp arg) (org-overview))
6886 (goto-char (point-max))
6887 (catch 'exit
6888 (while (and (progn (condition-case nil
6889 (outline-previous-visible-heading 1)
6890 (error (goto-char (point-min))))
6892 (looking-at org-outline-regexp))
6893 (if (integerp arg)
6894 (show-children (1- arg))
6895 (show-branches))
6896 (if (bobp) (throw 'exit nil))))))
6899 (defun org-optimize-window-after-visibility-change (state)
6900 "Adjust the window after a change in outline visibility.
6901 This function is the default value of the hook `org-cycle-hook'."
6902 (when (get-buffer-window (current-buffer))
6903 (cond
6904 ((eq state 'content) nil)
6905 ((eq state 'all) nil)
6906 ((eq state 'folded) nil)
6907 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6908 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6910 (defun org-remove-empty-overlays-at (pos)
6911 "Remove outline overlays that do not contain non-white stuff."
6912 (mapc
6913 (lambda (o)
6914 (and (eq 'outline (overlay-get o 'invisible))
6915 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6916 (overlay-end o))))
6917 (delete-overlay o)))
6918 (overlays-at pos)))
6920 (defun org-clean-visibility-after-subtree-move ()
6921 "Fix visibility issues after moving a subtree."
6922 ;; First, find a reasonable region to look at:
6923 ;; Start two siblings above, end three below
6924 (let* ((beg (save-excursion
6925 (and (org-get-last-sibling)
6926 (org-get-last-sibling))
6927 (point)))
6928 (end (save-excursion
6929 (and (org-get-next-sibling)
6930 (org-get-next-sibling)
6931 (org-get-next-sibling))
6932 (if (org-at-heading-p)
6933 (point-at-eol)
6934 (point))))
6935 (level (looking-at "\\*+"))
6936 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6937 (save-excursion
6938 (save-restriction
6939 (narrow-to-region beg end)
6940 (when re
6941 ;; Properly fold already folded siblings
6942 (goto-char (point-min))
6943 (while (re-search-forward re nil t)
6944 (if (and (not (outline-invisible-p))
6945 (save-excursion
6946 (goto-char (point-at-eol)) (outline-invisible-p)))
6947 (hide-entry))))
6948 (org-cycle-show-empty-lines 'overview)
6949 (org-cycle-hide-drawers 'overview)))))
6951 (defun org-cycle-show-empty-lines (state)
6952 "Show empty lines above all visible headlines.
6953 The region to be covered depends on STATE when called through
6954 `org-cycle-hook'. Lisp program can use t for STATE to get the
6955 entire buffer covered. Note that an empty line is only shown if there
6956 are at least `org-cycle-separator-lines' empty lines before the headline."
6957 (when (not (= org-cycle-separator-lines 0))
6958 (save-excursion
6959 (let* ((n (abs org-cycle-separator-lines))
6960 (re (cond
6961 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6962 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6963 (t (let ((ns (number-to-string (- n 2))))
6964 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6965 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6966 beg end b e)
6967 (cond
6968 ((memq state '(overview contents t))
6969 (setq beg (point-min) end (point-max)))
6970 ((memq state '(children folded))
6971 (setq beg (point) end (progn (org-end-of-subtree t t)
6972 (beginning-of-line 2)
6973 (point)))))
6974 (when beg
6975 (goto-char beg)
6976 (while (re-search-forward re end t)
6977 (unless (get-char-property (match-end 1) 'invisible)
6978 (setq e (match-end 1))
6979 (if (< org-cycle-separator-lines 0)
6980 (setq b (save-excursion
6981 (goto-char (match-beginning 0))
6982 (org-back-over-empty-lines)
6983 (if (save-excursion
6984 (goto-char (max (point-min) (1- (point))))
6985 (org-at-heading-p))
6986 (1- (point))
6987 (point))))
6988 (setq b (match-beginning 1)))
6989 (outline-flag-region b e nil)))))))
6990 ;; Never hide empty lines at the end of the file.
6991 (save-excursion
6992 (goto-char (point-max))
6993 (outline-previous-heading)
6994 (outline-end-of-heading)
6995 (if (and (looking-at "[ \t\n]+")
6996 (= (match-end 0) (point-max)))
6997 (outline-flag-region (point) (match-end 0) nil))))
6999 (defun org-show-empty-lines-in-parent ()
7000 "Move to the parent and re-show empty lines before visible headlines."
7001 (save-excursion
7002 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7003 (org-cycle-show-empty-lines context))))
7005 (defun org-files-list ()
7006 "Return `org-agenda-files' list, plus all open org-mode files.
7007 This is useful for operations that need to scan all of a user's
7008 open and agenda-wise Org files."
7009 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7010 (dolist (buf (buffer-list))
7011 (with-current-buffer buf
7012 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7013 (let ((file (expand-file-name (buffer-file-name))))
7014 (unless (member file files)
7015 (push file files))))))
7016 files))
7018 (defsubst org-entry-beginning-position ()
7019 "Return the beginning position of the current entry."
7020 (save-excursion (outline-back-to-heading t) (point)))
7022 (defsubst org-entry-end-position ()
7023 "Return the end position of the current entry."
7024 (save-excursion (outline-next-heading) (point)))
7026 (defun org-cycle-hide-drawers (state)
7027 "Re-hide all drawers after a visibility state change."
7028 (when (and (derived-mode-p 'org-mode)
7029 (not (memq state '(overview folded contents))))
7030 (save-excursion
7031 (let* ((globalp (memq state '(contents all)))
7032 (beg (if globalp (point-min) (point)))
7033 (end (if globalp (point-max)
7034 (if (eq state 'children)
7035 (save-excursion (outline-next-heading) (point))
7036 (org-end-of-subtree t)))))
7037 (goto-char beg)
7038 (while (re-search-forward org-drawer-regexp end t)
7039 (org-flag-drawer t))))))
7041 (defun org-cycle-hide-inline-tasks (state)
7042 "Re-hide inline task when switching to 'contents visibility state."
7043 (when (and (eq state 'contents)
7044 (boundp 'org-inlinetask-min-level)
7045 org-inlinetask-min-level)
7046 (hide-sublevels (1- org-inlinetask-min-level))))
7048 (defun org-flag-drawer (flag)
7049 "When FLAG is non-nil, hide the drawer we are within.
7050 Otherwise make it visible."
7051 (save-excursion
7052 (beginning-of-line 1)
7053 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7054 (let ((b (match-end 0)))
7055 (if (re-search-forward
7056 "^[ \t]*:END:"
7057 (save-excursion (outline-next-heading) (point)) t)
7058 (outline-flag-region b (point-at-eol) flag)
7059 (user-error ":END: line missing at position %s" b))))))
7061 (defun org-subtree-end-visible-p ()
7062 "Is the end of the current subtree visible?"
7063 (pos-visible-in-window-p
7064 (save-excursion (org-end-of-subtree t) (point))))
7066 (defun org-first-headline-recenter (&optional N)
7067 "Move cursor to the first headline and recenter the headline.
7068 Optional argument N means put the headline into the Nth line of the window."
7069 (goto-char (point-min))
7070 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7071 (beginning-of-line)
7072 (recenter (prefix-numeric-value N))))
7074 ;;; Saving and restoring visibility
7076 (defun org-outline-overlay-data (&optional use-markers)
7077 "Return a list of the locations of all outline overlays.
7078 These are overlays with the `invisible' property value `outline'.
7079 The return value is a list of cons cells, with start and stop
7080 positions for each overlay.
7081 If USE-MARKERS is set, return the positions as markers."
7082 (let (beg end)
7083 (save-excursion
7084 (save-restriction
7085 (widen)
7086 (delq nil
7087 (mapcar (lambda (o)
7088 (when (eq (overlay-get o 'invisible) 'outline)
7089 (setq beg (overlay-start o)
7090 end (overlay-end o))
7091 (and beg end (> end beg)
7092 (if use-markers
7093 (cons (move-marker (make-marker) beg)
7094 (move-marker (make-marker) end))
7095 (cons beg end)))))
7096 (overlays-in (point-min) (point-max))))))))
7098 (defun org-set-outline-overlay-data (data)
7099 "Create visibility overlays for all positions in DATA.
7100 DATA should have been made by `org-outline-overlay-data'."
7101 (let (o)
7102 (save-excursion
7103 (save-restriction
7104 (widen)
7105 (show-all)
7106 (mapc (lambda (c)
7107 (outline-flag-region (car c) (cdr c) t))
7108 data)))))
7110 ;;; Folding of blocks
7112 (defvar org-hide-block-overlays nil
7113 "Overlays hiding blocks.")
7114 (make-variable-buffer-local 'org-hide-block-overlays)
7116 (defun org-block-map (function &optional start end)
7117 "Call FUNCTION at the head of all source blocks in the current buffer.
7118 Optional arguments START and END can be used to limit the range."
7119 (let ((start (or start (point-min)))
7120 (end (or end (point-max))))
7121 (save-excursion
7122 (goto-char start)
7123 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7124 (save-excursion
7125 (save-match-data
7126 (goto-char (match-beginning 0))
7127 (funcall function)))))))
7129 (defun org-hide-block-toggle-all ()
7130 "Toggle the visibility of all blocks in the current buffer."
7131 (org-block-map #'org-hide-block-toggle))
7133 (defun org-hide-block-all ()
7134 "Fold all blocks in the current buffer."
7135 (interactive)
7136 (org-show-block-all)
7137 (org-block-map #'org-hide-block-toggle-maybe))
7139 (defun org-show-block-all ()
7140 "Unfold all blocks in the current buffer."
7141 (interactive)
7142 (mapc 'delete-overlay org-hide-block-overlays)
7143 (setq org-hide-block-overlays nil))
7145 (defun org-hide-block-toggle-maybe ()
7146 "Toggle visibility of block at point."
7147 (interactive)
7148 (let ((case-fold-search t))
7149 (if (save-excursion
7150 (beginning-of-line 1)
7151 (looking-at org-block-regexp))
7152 (progn (org-hide-block-toggle)
7153 t) ;; to signal that we took action
7154 nil))) ;; to signal that we did not
7156 (defun org-hide-block-toggle (&optional force)
7157 "Toggle the visibility of the current block."
7158 (interactive)
7159 (save-excursion
7160 (beginning-of-line)
7161 (if (re-search-forward org-block-regexp nil t)
7162 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7163 (end (match-end 0)) ;; end of entire body
7165 (if (memq t (mapcar (lambda (overlay)
7166 (eq (overlay-get overlay 'invisible)
7167 'org-hide-block))
7168 (overlays-at start)))
7169 (if (or (not force) (eq force 'off))
7170 (mapc (lambda (ov)
7171 (when (member ov org-hide-block-overlays)
7172 (setq org-hide-block-overlays
7173 (delq ov org-hide-block-overlays)))
7174 (when (eq (overlay-get ov 'invisible)
7175 'org-hide-block)
7176 (delete-overlay ov)))
7177 (overlays-at start)))
7178 (setq ov (make-overlay start end))
7179 (overlay-put ov 'invisible 'org-hide-block)
7180 ;; make the block accessible to isearch
7181 (overlay-put
7182 ov 'isearch-open-invisible
7183 (lambda (ov)
7184 (when (member ov org-hide-block-overlays)
7185 (setq org-hide-block-overlays
7186 (delq ov org-hide-block-overlays)))
7187 (when (eq (overlay-get ov 'invisible)
7188 'org-hide-block)
7189 (delete-overlay ov))))
7190 (push ov org-hide-block-overlays)))
7191 (user-error "Not looking at a source block"))))
7193 ;; org-tab-after-check-for-cycling-hook
7194 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7195 ;; Remove overlays when changing major mode
7196 (add-hook 'org-mode-hook
7197 (lambda () (org-add-hook 'change-major-mode-hook
7198 'org-show-block-all 'append 'local)))
7200 ;;; Org-goto
7202 (defvar org-goto-window-configuration nil)
7203 (defvar org-goto-marker nil)
7204 (defvar org-goto-map)
7205 (defun org-goto-map ()
7206 "Set the keymap `org-goto'."
7207 (setq org-goto-map
7208 (let ((map (make-sparse-keymap)))
7209 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7210 mouse-drag-region universal-argument org-occur))
7211 cmd)
7212 (while (setq cmd (pop cmds))
7213 (substitute-key-definition cmd cmd map global-map)))
7214 (suppress-keymap map)
7215 (org-defkey map "\C-m" 'org-goto-ret)
7216 (org-defkey map [(return)] 'org-goto-ret)
7217 (org-defkey map [(left)] 'org-goto-left)
7218 (org-defkey map [(right)] 'org-goto-right)
7219 (org-defkey map [(control ?g)] 'org-goto-quit)
7220 (org-defkey map "\C-i" 'org-cycle)
7221 (org-defkey map [(tab)] 'org-cycle)
7222 (org-defkey map [(down)] 'outline-next-visible-heading)
7223 (org-defkey map [(up)] 'outline-previous-visible-heading)
7224 (if org-goto-auto-isearch
7225 (if (fboundp 'define-key-after)
7226 (define-key-after map [t] 'org-goto-local-auto-isearch)
7227 nil)
7228 (org-defkey map "q" 'org-goto-quit)
7229 (org-defkey map "n" 'outline-next-visible-heading)
7230 (org-defkey map "p" 'outline-previous-visible-heading)
7231 (org-defkey map "f" 'outline-forward-same-level)
7232 (org-defkey map "b" 'outline-backward-same-level)
7233 (org-defkey map "u" 'outline-up-heading))
7234 (org-defkey map "/" 'org-occur)
7235 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7236 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7237 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7238 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7239 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7240 map)))
7242 (defconst org-goto-help
7243 "Browse buffer copy, to find location or copy text.%s
7244 RET=jump to location C-g=quit and return to previous location
7245 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7247 (defvar org-goto-start-pos) ; dynamically scoped parameter
7249 (defun org-goto (&optional alternative-interface)
7250 "Look up a different location in the current file, keeping current visibility.
7252 When you want look-up or go to a different location in a
7253 document, the fastest way is often to fold the entire buffer and
7254 then dive into the tree. This method has the disadvantage, that
7255 the previous location will be folded, which may not be what you
7256 want.
7258 This command works around this by showing a copy of the current
7259 buffer in an indirect buffer, in overview mode. You can dive
7260 into the tree in that copy, use org-occur and incremental search
7261 to find a location. When pressing RET or `Q', the command
7262 returns to the original buffer in which the visibility is still
7263 unchanged. After RET it will also jump to the location selected
7264 in the indirect buffer and expose the headline hierarchy above.
7266 With a prefix argument, use the alternative interface: e.g. if
7267 `org-goto-interface' is 'outline use 'outline-path-completion."
7268 (interactive "P")
7269 (org-goto-map)
7270 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7271 (org-refile-use-outline-path t)
7272 (org-refile-target-verify-function nil)
7273 (interface
7274 (if (not alternative-interface)
7275 org-goto-interface
7276 (if (eq org-goto-interface 'outline)
7277 'outline-path-completion
7278 'outline)))
7279 (org-goto-start-pos (point))
7280 (selected-point
7281 (if (eq interface 'outline)
7282 (car (org-get-location (current-buffer) org-goto-help))
7283 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7284 (org-refile-check-position pa)
7285 (nth 3 pa)))))
7286 (if selected-point
7287 (progn
7288 (org-mark-ring-push org-goto-start-pos)
7289 (goto-char selected-point)
7290 (if (or (outline-invisible-p) (org-invisible-p2))
7291 (org-show-context 'org-goto)))
7292 (message "Quit"))))
7294 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7295 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7296 (defvar org-goto-local-auto-isearch-map) ; defined below
7298 (defun org-get-location (buf help)
7299 "Let the user select a location in the Org-mode buffer BUF.
7300 This function uses a recursive edit. It returns the selected position
7301 or nil."
7302 (org-no-popups
7303 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7304 (isearch-hide-immediately nil)
7305 (isearch-search-fun-function
7306 (lambda () 'org-goto-local-search-headings))
7307 (org-goto-selected-point org-goto-exit-command))
7308 (save-excursion
7309 (save-window-excursion
7310 (delete-other-windows)
7311 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7312 (org-pop-to-buffer-same-window
7313 (condition-case nil
7314 (make-indirect-buffer (current-buffer) "*org-goto*")
7315 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7316 (with-output-to-temp-buffer "*Org Help*"
7317 (princ (format help (if org-goto-auto-isearch
7318 " Just type for auto-isearch."
7319 " n/p/f/b/u to navigate, q to quit."))))
7320 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7321 (setq buffer-read-only nil)
7322 (let ((org-startup-truncated t)
7323 (org-startup-folded nil)
7324 (org-startup-align-all-tables nil))
7325 (org-mode)
7326 (org-overview))
7327 (setq buffer-read-only t)
7328 (if (and (boundp 'org-goto-start-pos)
7329 (integer-or-marker-p org-goto-start-pos))
7330 (let ((org-show-hierarchy-above t)
7331 (org-show-siblings t)
7332 (org-show-following-heading t))
7333 (goto-char org-goto-start-pos)
7334 (and (outline-invisible-p) (org-show-context)))
7335 (goto-char (point-min)))
7336 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7337 (message "Select location and press RET")
7338 (use-local-map org-goto-map)
7339 (recursive-edit)))
7340 (kill-buffer "*org-goto*")
7341 (cons org-goto-selected-point org-goto-exit-command))))
7343 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7344 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7345 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7346 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7348 (defun org-goto-local-search-headings (string bound noerror)
7349 "Search and make sure that any matches are in headlines."
7350 (catch 'return
7351 (while (if isearch-forward
7352 (search-forward string bound noerror)
7353 (search-backward string bound noerror))
7354 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7355 (and (member :headline context)
7356 (not (member :tags context))))
7357 (throw 'return (point))))))
7359 (defun org-goto-local-auto-isearch ()
7360 "Start isearch."
7361 (interactive)
7362 (goto-char (point-min))
7363 (let ((keys (this-command-keys)))
7364 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7365 (isearch-mode t)
7366 (isearch-process-search-char (string-to-char keys)))))
7368 (defun org-goto-ret (&optional arg)
7369 "Finish `org-goto' by going to the new location."
7370 (interactive "P")
7371 (setq org-goto-selected-point (point)
7372 org-goto-exit-command 'return)
7373 (throw 'exit nil))
7375 (defun org-goto-left ()
7376 "Finish `org-goto' by going to the new location."
7377 (interactive)
7378 (if (org-at-heading-p)
7379 (progn
7380 (beginning-of-line 1)
7381 (setq org-goto-selected-point (point)
7382 org-goto-exit-command 'left)
7383 (throw 'exit nil))
7384 (user-error "Not on a heading")))
7386 (defun org-goto-right ()
7387 "Finish `org-goto' by going to the new location."
7388 (interactive)
7389 (if (org-at-heading-p)
7390 (progn
7391 (setq org-goto-selected-point (point)
7392 org-goto-exit-command 'right)
7393 (throw 'exit nil))
7394 (user-error "Not on a heading")))
7396 (defun org-goto-quit ()
7397 "Finish `org-goto' without cursor motion."
7398 (interactive)
7399 (setq org-goto-selected-point nil)
7400 (setq org-goto-exit-command 'quit)
7401 (throw 'exit nil))
7403 ;;; Indirect buffer display of subtrees
7405 (defvar org-indirect-dedicated-frame nil
7406 "This is the frame being used for indirect tree display.")
7407 (defvar org-last-indirect-buffer nil)
7409 (defun org-tree-to-indirect-buffer (&optional arg)
7410 "Create indirect buffer and narrow it to current subtree.
7411 With a numerical prefix ARG, go up to this level and then take that tree.
7412 If ARG is negative, go up that many levels.
7414 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7415 indirect buffer previously made with this command, to avoid proliferation of
7416 indirect buffers. However, when you call the command with a \
7417 \\[universal-argument] prefix, or
7418 when `org-indirect-buffer-display' is `new-frame', the last buffer
7419 is kept so that you can work with several indirect buffers at the same time.
7420 If `org-indirect-buffer-display' is `dedicated-frame', the \
7421 \\[universal-argument] prefix also
7422 requests that a new frame be made for the new buffer, so that the dedicated
7423 frame is not changed."
7424 (interactive "P")
7425 (let ((cbuf (current-buffer))
7426 (cwin (selected-window))
7427 (pos (point))
7428 beg end level heading ibuf)
7429 (save-excursion
7430 (org-back-to-heading t)
7431 (when (numberp arg)
7432 (setq level (org-outline-level))
7433 (if (< arg 0) (setq arg (+ level arg)))
7434 (while (> (setq level (org-outline-level)) arg)
7435 (org-up-heading-safe)))
7436 (setq beg (point)
7437 heading (org-get-heading))
7438 (org-end-of-subtree t t)
7439 (if (org-at-heading-p) (backward-char 1))
7440 (setq end (point)))
7441 (if (and (buffer-live-p org-last-indirect-buffer)
7442 (not (eq org-indirect-buffer-display 'new-frame))
7443 (not arg))
7444 (kill-buffer org-last-indirect-buffer))
7445 (setq ibuf (org-get-indirect-buffer cbuf)
7446 org-last-indirect-buffer ibuf)
7447 (cond
7448 ((or (eq org-indirect-buffer-display 'new-frame)
7449 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7450 (select-frame (make-frame))
7451 (delete-other-windows)
7452 (org-pop-to-buffer-same-window ibuf)
7453 (org-set-frame-title heading))
7454 ((eq org-indirect-buffer-display 'dedicated-frame)
7455 (raise-frame
7456 (select-frame (or (and org-indirect-dedicated-frame
7457 (frame-live-p org-indirect-dedicated-frame)
7458 org-indirect-dedicated-frame)
7459 (setq org-indirect-dedicated-frame (make-frame)))))
7460 (delete-other-windows)
7461 (org-pop-to-buffer-same-window ibuf)
7462 (org-set-frame-title (concat "Indirect: " heading)))
7463 ((eq org-indirect-buffer-display 'current-window)
7464 (org-pop-to-buffer-same-window ibuf))
7465 ((eq org-indirect-buffer-display 'other-window)
7466 (pop-to-buffer ibuf))
7467 (t (error "Invalid value")))
7468 (if (featurep 'xemacs)
7469 (save-excursion (org-mode) (turn-on-font-lock)))
7470 (narrow-to-region beg end)
7471 (show-all)
7472 (goto-char pos)
7473 (run-hook-with-args 'org-cycle-hook 'all)
7474 (and (window-live-p cwin) (select-window cwin))))
7476 (defun org-get-indirect-buffer (&optional buffer)
7477 (setq buffer (or buffer (current-buffer)))
7478 (let ((n 1) (base (buffer-name buffer)) bname)
7479 (while (buffer-live-p
7480 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7481 (setq n (1+ n)))
7482 (condition-case nil
7483 (make-indirect-buffer buffer bname 'clone)
7484 (error (make-indirect-buffer buffer bname)))))
7486 (defun org-set-frame-title (title)
7487 "Set the title of the current frame to the string TITLE."
7488 ;; FIXME: how to name a single frame in XEmacs???
7489 (unless (featurep 'xemacs)
7490 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7492 ;;;; Structure editing
7494 ;;; Inserting headlines
7496 (defun org-previous-line-empty-p (&optional next)
7497 "Is the previous line a blank line?
7498 When NEXT is non-nil, check the next line instead."
7499 (save-excursion
7500 (and (not (bobp))
7501 (or (beginning-of-line (if next 2 0)) t)
7502 (save-match-data
7503 (looking-at "[ \t]*$")))))
7505 (defun org-insert-heading (&optional arg invisible-ok)
7506 "Insert a new heading or item with same depth at point.
7507 If point is in a plain list and ARG is nil, create a new list item.
7508 With one universal prefix argument, insert a heading even in lists.
7509 With two universal prefix arguments, insert the heading at the end
7510 of the parent subtree.
7512 If point is at the beginning of a headline, insert a sibling before
7513 the current headline. If point is not at the beginning, split the line
7514 and create a new headline with the text in the current line after point
7515 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7517 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7518 This is important for non-interactive uses of the command."
7519 (interactive "P")
7520 (if (org-called-interactively-p 'any) (org-reveal))
7521 (cond
7522 ((or (= (buffer-size) 0)
7523 (and (not (save-excursion
7524 (and (ignore-errors (org-back-to-heading invisible-ok))
7525 (org-at-heading-p))))
7526 (or arg (not (org-in-item-p)))))
7527 (insert
7528 (if (org-previous-line-empty-p) "" "\n")
7529 (if (org-in-src-block-p) ",* " "* "))
7530 (run-hooks 'org-insert-heading-hook))
7531 ((or arg
7532 (and (not (org-in-item-p)) org-insert-heading-respect-content)
7533 (not (org-insert-item
7534 (save-excursion
7535 (beginning-of-line)
7536 (looking-at org-list-full-item-re)
7537 (match-string 3)))))
7538 (let (begn endn)
7539 (when (org-buffer-narrowed-p)
7540 (setq begn (point-min) endn (point-max))
7541 (widen))
7542 (let* ((empty-line-p nil)
7543 (eops (equal arg '(16))) ; insert at end of parent subtree
7544 (org-insert-heading-respect-content
7545 (or (not (null arg)) org-insert-heading-respect-content))
7546 (level nil)
7547 (on-heading (org-at-heading-p))
7548 ;; Get a level to fall back on
7549 (fix-level
7550 (save-excursion
7551 (org-back-to-heading t)
7552 (looking-at org-outline-regexp)
7553 (make-string (1- (length (match-string 0))) ?*)))
7554 (on-empty-line
7555 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7556 (head (save-excursion
7557 (condition-case nil
7558 (progn
7559 (org-back-to-heading invisible-ok)
7560 (when (and (not on-heading)
7561 (featurep 'org-inlinetask)
7562 (integerp org-inlinetask-min-level)
7563 (>= (length (match-string 0))
7564 org-inlinetask-min-level))
7565 ;; Find a heading level before the inline task
7566 (while (and (setq level (org-up-heading-safe))
7567 (>= level org-inlinetask-min-level)))
7568 (if (org-at-heading-p)
7569 (org-back-to-heading invisible-ok)
7570 (error "This should not happen")))
7571 (unless (and (save-excursion
7572 (save-match-data
7573 (org-backward-heading-same-level 1 invisible-ok))
7574 (= (point) (match-beginning 0)))
7575 (not (org-previous-line-empty-p t)))
7576 (setq empty-line-p (org-previous-line-empty-p)))
7577 (match-string 0))
7578 (error (or fix-level "* ")))))
7579 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7580 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7581 pos hide-previous previous-pos)
7582 (if ;; At the beginning of a heading, open a new line for insertion
7583 (and (bolp) (org-at-heading-p)
7584 (not eops)
7585 (or (bobp)
7586 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7587 (open-line (if blank 2 1))
7588 (save-excursion
7589 (setq previous-pos (point-at-bol))
7590 (end-of-line)
7591 (setq hide-previous (outline-invisible-p)))
7592 (and org-insert-heading-respect-content
7593 (save-excursion
7594 (while (outline-invisible-p)
7595 (org-show-subtree)
7596 (org-up-heading-safe))))
7597 (let ((split
7598 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7599 (save-excursion
7600 (let ((p (point)))
7601 (goto-char (point-at-bol))
7602 (and (looking-at org-complex-heading-regexp)
7603 (match-beginning 4)
7604 (> p (match-beginning 4)))))))
7605 tags pos)
7606 (cond
7607 ;; Insert a new line, possibly at end of parent subtree
7608 ((and (not arg) (not on-heading) (not on-empty-line)
7609 (not (save-excursion
7610 (beginning-of-line 1)
7611 (or (looking-at org-list-full-item-re)
7612 ;; Don't convert :end: lines to headline
7613 (looking-at "^\\s-*:end:")
7614 (looking-at "^\\s-*#\\+end_?")))))
7615 (beginning-of-line 1))
7616 (org-insert-heading-respect-content
7617 (if (not eops)
7618 (progn
7619 (org-end-of-subtree nil t)
7620 (and (looking-at "^\\*") (backward-char 1))
7621 (while (and (not (bobp))
7622 ;; Don't delete spaces in empty headlines
7623 (not (looking-back org-outline-regexp))
7624 (member (char-before) '(?\ ?\t ?\n)))
7625 (backward-delete-char 1)))
7626 (let ((p (point)))
7627 (org-up-heading-safe)
7628 (if (= p (point))
7629 (goto-char (point-max))
7630 (org-end-of-subtree nil t))))
7631 (when (featurep 'org-inlinetask)
7632 (while (and (not (eobp))
7633 (looking-at "\\(\\*+\\)[ \t]+")
7634 (>= (length (match-string 1))
7635 org-inlinetask-min-level))
7636 (org-end-of-subtree nil t)))
7637 (or (bolp) (newline))
7638 (or (org-previous-line-empty-p)
7639 (and blank (newline)))
7640 (if (or empty-line-p eops) (open-line 1)))
7641 ;; Insert a headling containing text after point
7642 ((org-at-heading-p)
7643 (when hide-previous
7644 (show-children)
7645 (org-show-entry))
7646 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7647 (setq tags (and (match-end 2) (match-string 2)))
7648 (and (match-end 1)
7649 (delete-region (match-beginning 1) (match-end 1)))
7650 (setq pos (point-at-bol))
7651 (or split (end-of-line 1))
7652 (delete-horizontal-space)
7653 (if (string-match "\\`\\*+\\'"
7654 (buffer-substring (point-at-bol) (point)))
7655 (insert " "))
7656 (newline (if blank 2 1))
7657 (when tags
7658 (save-excursion
7659 (goto-char pos)
7660 (end-of-line 1)
7661 (insert " " tags)
7662 (org-set-tags nil 'align))))
7664 (or split (end-of-line 1))
7665 (newline (cond ((and blank (not on-empty-line)) 2)
7666 (blank 1)
7667 (on-empty-line 0) (t 1)))))))
7668 (insert head) (just-one-space)
7669 (setq pos (point))
7670 (end-of-line 1)
7671 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7672 (when (and org-insert-heading-respect-content hide-previous)
7673 (save-excursion
7674 (goto-char previous-pos)
7675 (hide-subtree)))
7676 (when (and begn endn)
7677 (narrow-to-region (min (point) begn) (max (point) endn)))
7678 (run-hooks 'org-insert-heading-hook))))))
7680 (defun org-get-heading (&optional no-tags no-todo)
7681 "Return the heading of the current entry, without the stars.
7682 When NO-TAGS is non-nil, don't include tags.
7683 When NO-TODO is non-nil, don't include TODO keywords."
7684 (save-excursion
7685 (org-back-to-heading t)
7686 (cond
7687 ((and no-tags no-todo)
7688 (looking-at org-complex-heading-regexp)
7689 (match-string 4))
7690 (no-tags
7691 (looking-at (concat org-outline-regexp
7692 "\\(.*?\\)"
7693 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7694 (match-string 1))
7695 (no-todo
7696 (looking-at org-todo-line-regexp)
7697 (match-string 3))
7698 (t (looking-at org-heading-regexp)
7699 (match-string 2)))))
7701 (defvar orgstruct-mode) ; defined below
7703 (defun org-heading-components ()
7704 "Return the components of the current heading.
7705 This is a list with the following elements:
7706 - the level as an integer
7707 - the reduced level, different if `org-odd-levels-only' is set.
7708 - the TODO keyword, or nil
7709 - the priority character, like ?A, or nil if no priority is given
7710 - the headline text itself, or the tags string if no headline text
7711 - the tags string, or nil."
7712 (save-excursion
7713 (org-back-to-heading t)
7714 (if (let (case-fold-search)
7715 (looking-at
7716 (if orgstruct-mode
7717 org-heading-regexp
7718 org-complex-heading-regexp)))
7719 (if orgstruct-mode
7720 (list (length (match-string 1))
7721 (org-reduced-level (length (match-string 1)))
7724 (match-string 2)
7725 nil)
7726 (list (length (match-string 1))
7727 (org-reduced-level (length (match-string 1)))
7728 (org-match-string-no-properties 2)
7729 (and (match-end 3) (aref (match-string 3) 2))
7730 (org-match-string-no-properties 4)
7731 (org-match-string-no-properties 5))))))
7733 (defun org-get-entry ()
7734 "Get the entry text, after heading, entire subtree."
7735 (save-excursion
7736 (org-back-to-heading t)
7737 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7739 (defun org-insert-heading-after-current ()
7740 "Insert a new heading with same level as current, after current subtree."
7741 (interactive)
7742 (org-back-to-heading)
7743 (org-insert-heading)
7744 (org-move-subtree-down)
7745 (end-of-line 1))
7747 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7748 "Insert heading with `org-insert-heading-respect-content' set to t."
7749 (interactive "P")
7750 (let ((org-insert-heading-respect-content t))
7751 (org-insert-heading arg invisible-ok)))
7753 (defun org-insert-todo-heading-respect-content (&optional force-state)
7754 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7755 (interactive "P")
7756 (let ((org-insert-heading-respect-content t))
7757 (org-insert-todo-heading force-state t)))
7759 (defun org-insert-todo-heading (arg &optional force-heading)
7760 "Insert a new heading with the same level and TODO state as current heading.
7761 If the heading has no TODO state, or if the state is DONE, use the first
7762 state (TODO by default). Also one prefix arg, force first state. With two
7763 prefix args, force inserting at the end of the parent subtree."
7764 (interactive "P")
7765 (when (or force-heading (not (org-insert-item 'checkbox)))
7766 (org-insert-heading (or (and (equal arg '(16)) '(16))
7767 force-heading))
7768 (save-excursion
7769 (org-back-to-heading)
7770 (outline-previous-heading)
7771 (looking-at org-todo-line-regexp))
7772 (let*
7773 ((new-mark-x
7774 (if (or arg
7775 (not (match-beginning 2))
7776 (member (match-string 2) org-done-keywords))
7777 (car org-todo-keywords-1)
7778 (match-string 2)))
7779 (new-mark
7781 (run-hook-with-args-until-success
7782 'org-todo-get-default-hook new-mark-x nil)
7783 new-mark-x)))
7784 (beginning-of-line 1)
7785 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7786 (if org-treat-insert-todo-heading-as-state-change
7787 (org-todo new-mark)
7788 (insert new-mark " "))))
7789 (when org-provide-todo-statistics
7790 (org-update-parent-todo-statistics))))
7792 (defun org-insert-subheading (arg)
7793 "Insert a new subheading and demote it.
7794 Works for outline headings and for plain lists alike."
7795 (interactive "P")
7796 (org-insert-heading arg)
7797 (cond
7798 ((org-at-heading-p) (org-do-demote))
7799 ((org-at-item-p) (org-indent-item))))
7801 (defun org-insert-todo-subheading (arg)
7802 "Insert a new subheading with TODO keyword or checkbox and demote it.
7803 Works for outline headings and for plain lists alike."
7804 (interactive "P")
7805 (org-insert-todo-heading arg)
7806 (cond
7807 ((org-at-heading-p) (org-do-demote))
7808 ((org-at-item-p) (org-indent-item))))
7810 ;;; Promotion and Demotion
7812 (defvar org-after-demote-entry-hook nil
7813 "Hook run after an entry has been demoted.
7814 The cursor will be at the beginning of the entry.
7815 When a subtree is being demoted, the hook will be called for each node.")
7817 (defvar org-after-promote-entry-hook nil
7818 "Hook run after an entry has been promoted.
7819 The cursor will be at the beginning of the entry.
7820 When a subtree is being promoted, the hook will be called for each node.")
7822 (defun org-promote-subtree ()
7823 "Promote the entire subtree.
7824 See also `org-promote'."
7825 (interactive)
7826 (save-excursion
7827 (org-with-limited-levels (org-map-tree 'org-promote)))
7828 (org-fix-position-after-promote))
7830 (defun org-demote-subtree ()
7831 "Demote the entire subtree. See `org-demote'.
7832 See also `org-promote'."
7833 (interactive)
7834 (save-excursion
7835 (org-with-limited-levels (org-map-tree 'org-demote)))
7836 (org-fix-position-after-promote))
7839 (defun org-do-promote ()
7840 "Promote the current heading higher up the tree.
7841 If the region is active in `transient-mark-mode', promote all headings
7842 in the region."
7843 (interactive)
7844 (save-excursion
7845 (if (org-region-active-p)
7846 (org-map-region 'org-promote (region-beginning) (region-end))
7847 (org-promote)))
7848 (org-fix-position-after-promote))
7850 (defun org-do-demote ()
7851 "Demote the current heading lower down the tree.
7852 If the region is active in `transient-mark-mode', demote all headings
7853 in the region."
7854 (interactive)
7855 (save-excursion
7856 (if (org-region-active-p)
7857 (org-map-region 'org-demote (region-beginning) (region-end))
7858 (org-demote)))
7859 (org-fix-position-after-promote))
7861 (defun org-fix-position-after-promote ()
7862 "Make sure that after pro/demotion cursor position is right."
7863 (let ((pos (point)))
7864 (when (save-excursion
7865 (beginning-of-line 1)
7866 (looking-at org-todo-line-regexp)
7867 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7868 (cond ((eobp) (insert " "))
7869 ((eolp) (insert " "))
7870 ((equal (char-after) ?\ ) (forward-char 1))))))
7872 (defun org-current-level ()
7873 "Return the level of the current entry, or nil if before the first headline.
7874 The level is the number of stars at the beginning of the headline."
7875 (save-excursion
7876 (org-with-limited-levels
7877 (if (ignore-errors (org-back-to-heading t))
7878 (funcall outline-level)))))
7880 (defun org-get-previous-line-level ()
7881 "Return the outline depth of the last headline before the current line.
7882 Returns 0 for the first headline in the buffer, and nil if before the
7883 first headline."
7884 (let ((current-level (org-current-level))
7885 (prev-level (when (> (line-number-at-pos) 1)
7886 (save-excursion
7887 (beginning-of-line 0)
7888 (org-current-level)))))
7889 (cond ((null current-level) nil) ; Before first headline
7890 ((null prev-level) 0) ; At first headline
7891 (prev-level))))
7893 (defun org-reduced-level (l)
7894 "Compute the effective level of a heading.
7895 This takes into account the setting of `org-odd-levels-only'."
7896 (cond
7897 ((zerop l) 0)
7898 (org-odd-levels-only (1+ (floor (/ l 2))))
7899 (t l)))
7901 (defun org-level-increment ()
7902 "Return the number of stars that will be added or removed at a
7903 time to headlines when structure editing, based on the value of
7904 `org-odd-levels-only'."
7905 (if org-odd-levels-only 2 1))
7907 (defun org-get-valid-level (level &optional change)
7908 "Rectify a level change under the influence of `org-odd-levels-only'
7909 LEVEL is a current level, CHANGE is by how much the level should be
7910 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7911 even level numbers will become the next higher odd number."
7912 (if org-odd-levels-only
7913 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7914 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7915 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7916 (max 1 (+ level (or change 0)))))
7918 (if (boundp 'define-obsolete-function-alias)
7919 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7920 (define-obsolete-function-alias 'org-get-legal-level
7921 'org-get-valid-level)
7922 (define-obsolete-function-alias 'org-get-legal-level
7923 'org-get-valid-level "23.1")))
7925 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7926 ;; ̀org-with-limited-levels'
7927 (defun org-promote ()
7928 "Promote the current heading higher up the tree.
7929 If the region is active in `transient-mark-mode', promote all headings
7930 in the region."
7931 (org-back-to-heading t)
7932 (let* ((level (save-match-data (funcall outline-level)))
7933 (after-change-functions (remove 'flyspell-after-change-function
7934 after-change-functions))
7935 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7936 (diff (abs (- level (length up-head) -1))))
7937 (cond ((and (= level 1) org-called-with-limited-levels
7938 org-allow-promoting-top-level-subtree)
7939 (replace-match "# " nil t))
7940 ((= level 1)
7941 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7942 (t (replace-match up-head nil t)))
7943 ;; Fixup tag positioning
7944 (unless (= level 1)
7945 (and org-auto-align-tags (org-set-tags nil t))
7946 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7947 (run-hooks 'org-after-promote-entry-hook)))
7949 (defun org-demote ()
7950 "Demote the current heading lower down the tree.
7951 If the region is active in `transient-mark-mode', demote all headings
7952 in the region."
7953 (org-back-to-heading t)
7954 (let* ((level (save-match-data (funcall outline-level)))
7955 (after-change-functions (remove 'flyspell-after-change-function
7956 after-change-functions))
7957 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7958 (diff (abs (- level (length down-head) -1))))
7959 (replace-match down-head nil t)
7960 ;; Fixup tag positioning
7961 (and org-auto-align-tags (org-set-tags nil t))
7962 (if org-adapt-indentation (org-fixup-indentation diff))
7963 (run-hooks 'org-after-demote-entry-hook)))
7965 (defun org-cycle-level ()
7966 "Cycle the level of an empty headline through possible states.
7967 This goes first to child, then to parent, level, then up the hierarchy.
7968 After top level, it switches back to sibling level."
7969 (interactive)
7970 (let ((org-adapt-indentation nil))
7971 (when (org-point-at-end-of-empty-headline)
7972 (setq this-command 'org-cycle-level) ; Only needed for caching
7973 (let ((cur-level (org-current-level))
7974 (prev-level (org-get-previous-line-level)))
7975 (cond
7976 ;; If first headline in file, promote to top-level.
7977 ((= prev-level 0)
7978 (loop repeat (/ (- cur-level 1) (org-level-increment))
7979 do (org-do-promote)))
7980 ;; If same level as prev, demote one.
7981 ((= prev-level cur-level)
7982 (org-do-demote))
7983 ;; If parent is top-level, promote to top level if not already.
7984 ((= prev-level 1)
7985 (loop repeat (/ (- cur-level 1) (org-level-increment))
7986 do (org-do-promote)))
7987 ;; If top-level, return to prev-level.
7988 ((= cur-level 1)
7989 (loop repeat (/ (- prev-level 1) (org-level-increment))
7990 do (org-do-demote)))
7991 ;; If less than prev-level, promote one.
7992 ((< cur-level prev-level)
7993 (org-do-promote))
7994 ;; If deeper than prev-level, promote until higher than
7995 ;; prev-level.
7996 ((> cur-level prev-level)
7997 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7998 do (org-do-promote))))
7999 t))))
8001 (defun org-map-tree (fun)
8002 "Call FUN for every heading underneath the current one."
8003 (org-back-to-heading)
8004 (let ((level (funcall outline-level)))
8005 (save-excursion
8006 (funcall fun)
8007 (while (and (progn
8008 (outline-next-heading)
8009 (> (funcall outline-level) level))
8010 (not (eobp)))
8011 (funcall fun)))))
8013 (defun org-map-region (fun beg end)
8014 "Call FUN for every heading between BEG and END."
8015 (let ((org-ignore-region t))
8016 (save-excursion
8017 (setq end (copy-marker end))
8018 (goto-char beg)
8019 (if (and (re-search-forward org-outline-regexp-bol nil t)
8020 (< (point) end))
8021 (funcall fun))
8022 (while (and (progn
8023 (outline-next-heading)
8024 (< (point) end))
8025 (not (eobp)))
8026 (funcall fun)))))
8028 (defvar org-property-end-re) ; silence byte-compiler
8029 (defun org-fixup-indentation (diff)
8030 "Change the indentation in the current entry by DIFF.
8031 However, if any line in the current entry has no indentation, or if it
8032 would end up with no indentation after the change, nothing at all is done."
8033 (save-excursion
8034 (let ((end (save-excursion (outline-next-heading)
8035 (point-marker)))
8036 (prohibit (if (> diff 0)
8037 "^\\S-"
8038 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8039 col)
8040 (unless (save-excursion (end-of-line 1)
8041 (re-search-forward prohibit end t))
8042 (while (and (< (point) end)
8043 (re-search-forward "^[ \t]+" end t))
8044 (goto-char (match-end 0))
8045 (setq col (current-column))
8046 (if (< diff 0) (replace-match ""))
8047 (org-indent-to-column (+ diff col))))
8048 (move-marker end nil))))
8050 (defun org-convert-to-odd-levels ()
8051 "Convert an org-mode file with all levels allowed to one with odd levels.
8052 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8053 level 5 etc."
8054 (interactive)
8055 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8056 (let ((outline-level 'org-outline-level)
8057 (org-odd-levels-only nil) n)
8058 (save-excursion
8059 (goto-char (point-min))
8060 (while (re-search-forward "^\\*\\*+ " nil t)
8061 (setq n (- (length (match-string 0)) 2))
8062 (while (>= (setq n (1- n)) 0)
8063 (org-demote))
8064 (end-of-line 1))))))
8066 (defun org-convert-to-oddeven-levels ()
8067 "Convert an org-mode file with only odd levels to one with odd/even levels.
8068 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8069 file contains a section with an even level, conversion would
8070 destroy the structure of the file. An error is signaled in this
8071 case."
8072 (interactive)
8073 (goto-char (point-min))
8074 ;; First check if there are no even levels
8075 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8076 (org-show-context t)
8077 (error "Not all levels are odd in this file. Conversion not possible"))
8078 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8079 (let ((outline-regexp org-outline-regexp)
8080 (outline-level 'org-outline-level)
8081 (org-odd-levels-only nil) n)
8082 (save-excursion
8083 (goto-char (point-min))
8084 (while (re-search-forward "^\\*\\*+ " nil t)
8085 (setq n (/ (1- (length (match-string 0))) 2))
8086 (while (>= (setq n (1- n)) 0)
8087 (org-promote))
8088 (end-of-line 1))))))
8090 (defun org-tr-level (n)
8091 "Make N odd if required."
8092 (if org-odd-levels-only (1+ (/ n 2)) n))
8094 ;;; Vertical tree motion, cutting and pasting of subtrees
8096 (defun org-move-subtree-up (&optional arg)
8097 "Move the current subtree up past ARG headlines of the same level."
8098 (interactive "p")
8099 (org-move-subtree-down (- (prefix-numeric-value arg))))
8101 (defun org-move-subtree-down (&optional arg)
8102 "Move the current subtree down past ARG headlines of the same level."
8103 (interactive "p")
8104 (setq arg (prefix-numeric-value arg))
8105 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8106 'org-get-last-sibling))
8107 (ins-point (make-marker))
8108 (cnt (abs arg))
8109 (col (current-column))
8110 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8111 ;; Select the tree
8112 (org-back-to-heading)
8113 (setq beg0 (point))
8114 (save-excursion
8115 (setq ne-beg (org-back-over-empty-lines))
8116 (setq beg (point)))
8117 (save-match-data
8118 (save-excursion (outline-end-of-heading)
8119 (setq folded (outline-invisible-p)))
8120 (outline-end-of-subtree))
8121 (outline-next-heading)
8122 (setq ne-end (org-back-over-empty-lines))
8123 (setq end (point))
8124 (goto-char beg0)
8125 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8126 ;; include less whitespace
8127 (save-excursion
8128 (goto-char beg)
8129 (forward-line (- ne-beg ne-end))
8130 (setq beg (point))))
8131 ;; Find insertion point, with error handling
8132 (while (> cnt 0)
8133 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8134 (progn (goto-char beg0)
8135 (user-error "Cannot move past superior level or buffer limit")))
8136 (setq cnt (1- cnt)))
8137 (if (> arg 0)
8138 ;; Moving forward - still need to move over subtree
8139 (progn (org-end-of-subtree t t)
8140 (save-excursion
8141 (org-back-over-empty-lines)
8142 (or (bolp) (newline)))))
8143 (setq ne-ins (org-back-over-empty-lines))
8144 (move-marker ins-point (point))
8145 (setq txt (buffer-substring beg end))
8146 (org-save-markers-in-region beg end)
8147 (delete-region beg end)
8148 (org-remove-empty-overlays-at beg)
8149 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8150 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8151 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8152 (let ((bbb (point)))
8153 (insert-before-markers txt)
8154 (org-reinstall-markers-in-region bbb)
8155 (move-marker ins-point bbb))
8156 (or (bolp) (insert "\n"))
8157 (setq ins-end (point))
8158 (goto-char ins-point)
8159 (org-skip-whitespace)
8160 (when (and (< arg 0)
8161 (org-first-sibling-p)
8162 (> ne-ins ne-beg))
8163 ;; Move whitespace back to beginning
8164 (save-excursion
8165 (goto-char ins-end)
8166 (let ((kill-whole-line t))
8167 (kill-line (- ne-ins ne-beg)) (point)))
8168 (insert (make-string (- ne-ins ne-beg) ?\n)))
8169 (move-marker ins-point nil)
8170 (if folded
8171 (hide-subtree)
8172 (org-show-entry)
8173 (show-children)
8174 (org-cycle-hide-drawers 'children))
8175 (org-clean-visibility-after-subtree-move)
8176 ;; move back to the initial column we were at
8177 (move-to-column col)))
8179 (defvar org-subtree-clip ""
8180 "Clipboard for cut and paste of subtrees.
8181 This is actually only a copy of the kill, because we use the normal kill
8182 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8184 (defvar org-subtree-clip-folded nil
8185 "Was the last copied subtree folded?
8186 This is used to fold the tree back after pasting.")
8188 (defun org-cut-subtree (&optional n)
8189 "Cut the current subtree into the clipboard.
8190 With prefix arg N, cut this many sequential subtrees.
8191 This is a short-hand for marking the subtree and then cutting it."
8192 (interactive "p")
8193 (org-copy-subtree n 'cut))
8195 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8196 "Copy the current subtree it in the clipboard.
8197 With prefix arg N, copy this many sequential subtrees.
8198 This is a short-hand for marking the subtree and then copying it.
8199 If CUT is non-nil, actually cut the subtree.
8200 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8201 of some markers in the region, even if CUT is non-nil. This is
8202 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8203 (interactive "p")
8204 (let (beg end folded (beg0 (point)))
8205 (if (org-called-interactively-p 'any)
8206 (org-back-to-heading nil) ; take what looks like a subtree
8207 (org-back-to-heading t)) ; take what is really there
8208 (setq beg (point))
8209 (skip-chars-forward " \t\r\n")
8210 (save-match-data
8211 (if nosubtrees
8212 (outline-next-heading)
8213 (save-excursion (outline-end-of-heading)
8214 (setq folded (outline-invisible-p)))
8215 (condition-case nil
8216 (org-forward-heading-same-level (1- n) t)
8217 (error nil))
8218 (org-end-of-subtree t t)))
8219 (setq end (point))
8220 (goto-char beg0)
8221 (when (> end beg)
8222 (setq org-subtree-clip-folded folded)
8223 (when (or cut force-store-markers)
8224 (org-save-markers-in-region beg end))
8225 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8226 (setq org-subtree-clip (current-kill 0))
8227 (message "%s: Subtree(s) with %d characters"
8228 (if cut "Cut" "Copied")
8229 (length org-subtree-clip)))))
8231 (defun org-paste-subtree (&optional level tree for-yank)
8232 "Paste the clipboard as a subtree, with modification of headline level.
8233 The entire subtree is promoted or demoted in order to match a new headline
8234 level.
8236 If the cursor is at the beginning of a headline, the same level as
8237 that headline is used to paste the tree.
8239 If not, the new level is derived from the *visible* headings
8240 before and after the insertion point, and taken to be the inferior headline
8241 level of the two. So if the previous visible heading is level 3 and the
8242 next is level 4 (or vice versa), level 4 will be used for insertion.
8243 This makes sure that the subtree remains an independent subtree and does
8244 not swallow low level entries.
8246 You can also force a different level, either by using a numeric prefix
8247 argument, or by inserting the heading marker by hand. For example, if the
8248 cursor is after \"*****\", then the tree will be shifted to level 5.
8250 If optional TREE is given, use this text instead of the kill ring.
8252 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8253 move back over whitespace before inserting, and move point to the end of
8254 the inserted text when done."
8255 (interactive "P")
8256 (setq tree (or tree (and kill-ring (current-kill 0))))
8257 (unless (org-kill-is-subtree-p tree)
8258 (user-error "%s"
8259 (substitute-command-keys
8260 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8261 (org-with-limited-levels
8262 (let* ((visp (not (outline-invisible-p)))
8263 (txt tree)
8264 (^re_ "\\(\\*+\\)[ \t]*")
8265 (old-level (if (string-match org-outline-regexp-bol txt)
8266 (- (match-end 0) (match-beginning 0) 1)
8267 -1))
8268 (force-level (cond (level (prefix-numeric-value level))
8269 ((and (looking-at "[ \t]*$")
8270 (string-match
8271 "^\\*+$" (buffer-substring
8272 (point-at-bol) (point))))
8273 (- (match-end 1) (match-beginning 1)))
8274 ((and (bolp)
8275 (looking-at org-outline-regexp))
8276 (- (match-end 0) (point) 1))))
8277 (previous-level (save-excursion
8278 (condition-case nil
8279 (progn
8280 (outline-previous-visible-heading 1)
8281 (if (looking-at ^re_)
8282 (- (match-end 0) (match-beginning 0) 1)
8284 (error 1))))
8285 (next-level (save-excursion
8286 (condition-case nil
8287 (progn
8288 (or (looking-at org-outline-regexp)
8289 (outline-next-visible-heading 1))
8290 (if (looking-at ^re_)
8291 (- (match-end 0) (match-beginning 0) 1)
8293 (error 1))))
8294 (new-level (or force-level (max previous-level next-level)))
8295 (shift (if (or (= old-level -1)
8296 (= new-level -1)
8297 (= old-level new-level))
8299 (- new-level old-level)))
8300 (delta (if (> shift 0) -1 1))
8301 (func (if (> shift 0) 'org-demote 'org-promote))
8302 (org-odd-levels-only nil)
8303 beg end newend)
8304 ;; Remove the forced level indicator
8305 (if force-level
8306 (delete-region (point-at-bol) (point)))
8307 ;; Paste
8308 (beginning-of-line (if (bolp) 1 2))
8309 (setq beg (point))
8310 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8311 (insert-before-markers txt)
8312 (unless (string-match "\n\\'" txt) (insert "\n"))
8313 (setq newend (point))
8314 (org-reinstall-markers-in-region beg)
8315 (setq end (point))
8316 (goto-char beg)
8317 (skip-chars-forward " \t\n\r")
8318 (setq beg (point))
8319 (if (and (outline-invisible-p) visp)
8320 (save-excursion (outline-show-heading)))
8321 ;; Shift if necessary
8322 (unless (= shift 0)
8323 (save-restriction
8324 (narrow-to-region beg end)
8325 (while (not (= shift 0))
8326 (org-map-region func (point-min) (point-max))
8327 (setq shift (+ delta shift)))
8328 (goto-char (point-min))
8329 (setq newend (point-max))))
8330 (when (or (org-called-interactively-p 'interactive) for-yank)
8331 (message "Clipboard pasted as level %d subtree" new-level))
8332 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8333 kill-ring
8334 (eq org-subtree-clip (current-kill 0))
8335 org-subtree-clip-folded)
8336 ;; The tree was folded before it was killed/copied
8337 (hide-subtree))
8338 (and for-yank (goto-char newend)))))
8340 (defun org-kill-is-subtree-p (&optional txt)
8341 "Check if the current kill is an outline subtree, or a set of trees.
8342 Returns nil if kill does not start with a headline, or if the first
8343 headline level is not the largest headline level in the tree.
8344 So this will actually accept several entries of equal levels as well,
8345 which is OK for `org-paste-subtree'.
8346 If optional TXT is given, check this string instead of the current kill."
8347 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8348 (re (org-get-limited-outline-regexp))
8349 (^re (concat "^" re))
8350 (start-level (and kill
8351 (string-match
8352 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8353 kill)
8354 (- (match-end 2) (match-beginning 2) 1)))
8355 (start (1+ (or (match-beginning 2) -1))))
8356 (if (not start-level)
8357 (progn
8358 nil) ;; does not even start with a heading
8359 (catch 'exit
8360 (while (setq start (string-match ^re kill (1+ start)))
8361 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8362 (throw 'exit nil)))
8363 t))))
8365 (defvar org-markers-to-move nil
8366 "Markers that should be moved with a cut-and-paste operation.
8367 Those markers are stored together with their positions relative to
8368 the start of the region.")
8370 (defun org-save-markers-in-region (beg end)
8371 "Check markers in region.
8372 If these markers are between BEG and END, record their position relative
8373 to BEG, so that after moving the block of text, we can put the markers back
8374 into place.
8375 This function gets called just before an entry or tree gets cut from the
8376 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8377 called immediately, to move the markers with the entries."
8378 (setq org-markers-to-move nil)
8379 (when (featurep 'org-clock)
8380 (org-clock-save-markers-for-cut-and-paste beg end))
8381 (when (featurep 'org-agenda)
8382 (org-agenda-save-markers-for-cut-and-paste beg end)))
8384 (defun org-check-and-save-marker (marker beg end)
8385 "Check if MARKER is between BEG and END.
8386 If yes, remember the marker and the distance to BEG."
8387 (when (and (marker-buffer marker)
8388 (equal (marker-buffer marker) (current-buffer)))
8389 (if (and (>= marker beg) (< marker end))
8390 (push (cons marker (- marker beg)) org-markers-to-move))))
8392 (defun org-reinstall-markers-in-region (beg)
8393 "Move all remembered markers to their position relative to BEG."
8394 (mapc (lambda (x)
8395 (move-marker (car x) (+ beg (cdr x))))
8396 org-markers-to-move)
8397 (setq org-markers-to-move nil))
8399 (defun org-narrow-to-subtree ()
8400 "Narrow buffer to the current subtree."
8401 (interactive)
8402 (save-excursion
8403 (save-match-data
8404 (org-with-limited-levels
8405 (narrow-to-region
8406 (progn (org-back-to-heading t) (point))
8407 (progn (org-end-of-subtree t t)
8408 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8409 (point)))))))
8411 (defun org-narrow-to-block ()
8412 "Narrow buffer to the current block."
8413 (interactive)
8414 (let* ((case-fold-search t)
8415 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8416 "^[ \t]*#\\+end_.*")))
8417 (if blockp
8418 (narrow-to-region (car blockp) (cdr blockp))
8419 (user-error "Not in a block"))))
8421 (eval-when-compile
8422 (defvar org-property-drawer-re))
8424 (defvar org-property-start-re) ;; defined below
8425 (defun org-clone-subtree-with-time-shift (n &optional shift)
8426 "Clone the task (subtree) at point N times.
8427 The clones will be inserted as siblings.
8429 In interactive use, the user will be prompted for the number of
8430 clones to be produced. If the entry has a timestamp, the user
8431 will also be prompted for a time shift, which may be a repeater
8432 as used in time stamps, for example `+3d'. To disable this,
8433 you can call the function with a universal prefix argument.
8435 When a valid repeater is given and the entry contains any time
8436 stamps, the clones will become a sequence in time, with time
8437 stamps in the subtree shifted for each clone produced. If SHIFT
8438 is nil or the empty string, time stamps will be left alone. The
8439 ID property of the original subtree is removed.
8441 If the original subtree did contain time stamps with a repeater,
8442 the following will happen:
8443 - the repeater will be removed in each clone
8444 - an additional clone will be produced, with the current, unshifted
8445 date(s) in the entry.
8446 - the original entry will be placed *after* all the clones, with
8447 repeater intact.
8448 - the start days in the repeater in the original entry will be shifted
8449 to past the last clone.
8450 In this way you can spell out a number of instances of a repeating task,
8451 and still retain the repeater to cover future instances of the task."
8452 (interactive "nNumber of clones to produce: ")
8453 (let ((shift
8454 (or shift
8455 (if (and (not (equal current-prefix-arg '(4)))
8456 (save-excursion
8457 (re-search-forward org-ts-regexp-both
8458 (save-excursion
8459 (org-end-of-subtree t)
8460 (point)) t)))
8461 (read-from-minibuffer
8462 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8463 ""))) ;; No time shift
8464 (n-no-remove -1)
8465 (drawer-re org-drawer-regexp)
8466 beg end template task idprop
8467 shift-n shift-what doshift nmin nmax)
8468 (if (not (and (integerp n) (> n 0)))
8469 (error "Invalid number of replications %s" n))
8470 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8471 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8472 shift)))
8473 (error "Invalid shift specification %s" shift))
8474 (when doshift
8475 (setq shift-n (string-to-number (match-string 1 shift))
8476 shift-what (cdr (assoc (match-string 2 shift)
8477 '(("d" . day) ("w" . week)
8478 ("m" . month) ("y" . year))))))
8479 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8480 (setq nmin 1 nmax n)
8481 (org-back-to-heading t)
8482 (setq beg (point))
8483 (setq idprop (org-entry-get nil "ID"))
8484 (org-end-of-subtree t t)
8485 (or (bolp) (insert "\n"))
8486 (setq end (point))
8487 (setq template (buffer-substring beg end))
8488 (when (and doshift
8489 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8490 (delete-region beg end)
8491 (setq end beg)
8492 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8493 (goto-char end)
8494 (loop for n from nmin to nmax do
8495 ;; prepare clone
8496 (with-temp-buffer
8497 (insert template)
8498 (org-mode)
8499 (goto-char (point-min))
8500 (org-show-subtree)
8501 (and idprop (if org-clone-delete-id
8502 (org-entry-delete nil "ID")
8503 (org-id-get-create t)))
8504 (unless (= n 0)
8505 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8506 (kill-whole-line))
8507 (goto-char (point-min))
8508 (while (re-search-forward drawer-re nil t)
8509 (mapc (lambda (d)
8510 (org-remove-empty-drawer-at d (point))) org-drawers)))
8511 (goto-char (point-min))
8512 (when doshift
8513 (while (re-search-forward org-ts-regexp-both nil t)
8514 (org-timestamp-change (* n shift-n) shift-what))
8515 (unless (= n n-no-remove)
8516 (goto-char (point-min))
8517 (while (re-search-forward org-ts-regexp nil t)
8518 (save-excursion
8519 (goto-char (match-beginning 0))
8520 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8521 (delete-region (match-beginning 1) (match-end 1)))))))
8522 (setq task (buffer-string)))
8523 (insert task))
8524 (goto-char beg)))
8526 ;;; Outline Sorting
8528 (defun org-sort (with-case)
8529 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8530 Optional argument WITH-CASE means sort case-sensitively."
8531 (interactive "P")
8532 (cond
8533 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8534 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8536 (org-call-with-arg 'org-sort-entries with-case))))
8538 (defun org-sort-remove-invisible (s)
8539 "Remove invisible links from string S."
8540 (remove-text-properties 0 (length s) org-rm-props s)
8541 (while (string-match org-bracket-link-regexp s)
8542 (setq s (replace-match (if (match-end 2)
8543 (match-string 3 s)
8544 (match-string 1 s)) t t s)))
8545 (let ((st (format " %s " s)))
8546 (while (string-match org-emph-re st)
8547 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8548 (setq s (substring st 1 -1)))
8551 (defvar org-priority-regexp) ; defined later in the file
8553 (defvar org-after-sorting-entries-or-items-hook nil
8554 "Hook that is run after a bunch of entries or items have been sorted.
8555 When children are sorted, the cursor is in the parent line when this
8556 hook gets called. When a region or a plain list is sorted, the cursor
8557 will be in the first entry of the sorted region/list.")
8559 (defun org-sort-entries
8560 (&optional with-case sorting-type getkey-func compare-func property)
8561 "Sort entries on a certain level of an outline tree.
8562 If there is an active region, the entries in the region are sorted.
8563 Else, if the cursor is before the first entry, sort the top-level items.
8564 Else, the children of the entry at point are sorted.
8566 Sorting can be alphabetically, numerically, by date/time as given by
8567 a time stamp, by a property, by priority order, or by a custom function.
8569 The command prompts for the sorting type unless it has been given to the
8570 function through the SORTING-TYPE argument, which needs to be a character,
8571 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8572 precise meaning of each character:
8574 n Numerically, by converting the beginning of the entry/item to a number.
8575 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8576 o By order of TODO keywords.
8577 t By date/time, either the first active time stamp in the entry, or, if
8578 none exist, by the first inactive one.
8579 s By the scheduled date/time.
8580 d By deadline date/time.
8581 c By creation time, which is assumed to be the first inactive time stamp
8582 at the beginning of a line.
8583 p By priority according to the cookie.
8584 r By the value of a property.
8586 Capital letters will reverse the sort order.
8588 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8589 called with point at the beginning of the record. It must return either
8590 a string or a number that should serve as the sorting key for that record.
8592 Comparing entries ignores case by default. However, with an optional argument
8593 WITH-CASE, the sorting considers case as well.
8595 Sorting is done against the visible part of the headlines, it ignores hidden
8596 links."
8597 (interactive "P")
8598 (let ((case-func (if with-case 'identity 'downcase))
8599 (cmstr
8600 ;; The clock marker is lost when using `sort-subr', let's
8601 ;; store the clocking string.
8602 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8603 (save-excursion
8604 (goto-char org-clock-marker)
8605 (looking-back "^.*") (match-string-no-properties 0))))
8606 start beg end stars re re2
8607 txt what tmp)
8608 ;; Find beginning and end of region to sort
8609 (cond
8610 ((org-region-active-p)
8611 ;; we will sort the region
8612 (setq end (region-end)
8613 what "region")
8614 (goto-char (region-beginning))
8615 (if (not (org-at-heading-p)) (outline-next-heading))
8616 (setq start (point)))
8617 ((or (org-at-heading-p)
8618 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8619 ;; we will sort the children of the current headline
8620 (org-back-to-heading)
8621 (setq start (point)
8622 end (progn (org-end-of-subtree t t)
8623 (or (bolp) (insert "\n"))
8624 (org-back-over-empty-lines)
8625 (point))
8626 what "children")
8627 (goto-char start)
8628 (show-subtree)
8629 (outline-next-heading))
8631 ;; we will sort the top-level entries in this file
8632 (goto-char (point-min))
8633 (or (org-at-heading-p) (outline-next-heading))
8634 (setq start (point))
8635 (goto-char (point-max))
8636 (beginning-of-line 1)
8637 (when (looking-at ".*?\\S-")
8638 ;; File ends in a non-white line
8639 (end-of-line 1)
8640 (insert "\n"))
8641 (setq end (point-max))
8642 (setq what "top-level")
8643 (goto-char start)
8644 (show-all)))
8646 (setq beg (point))
8647 (if (>= beg end) (user-error "Nothing to sort"))
8649 (looking-at "\\(\\*+\\)")
8650 (setq stars (match-string 1)
8651 re (concat "^" (regexp-quote stars) " +")
8652 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8653 txt (buffer-substring beg end))
8654 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8655 (if (and (not (equal stars "*")) (string-match re2 txt))
8656 (user-error "Region to sort contains a level above the first entry"))
8658 (unless sorting-type
8659 (message
8660 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8661 [t]ime [s]cheduled [d]eadline [c]reated
8662 A/N/P/R/O/F/T/S/D/C means reversed:"
8663 what)
8664 (setq sorting-type (read-char-exclusive))
8666 (unless getkey-func
8667 (and (= (downcase sorting-type) ?f)
8668 (setq getkey-func
8669 (org-icompleting-read "Sort using function: "
8670 obarray 'fboundp t nil nil))
8671 (setq getkey-func (intern getkey-func))))
8673 (and (= (downcase sorting-type) ?r)
8674 (not property)
8675 (setq property
8676 (org-icompleting-read "Property: "
8677 (mapcar 'list (org-buffer-property-keys t))
8678 nil t))))
8680 (message "Sorting entries...")
8682 (save-restriction
8683 (narrow-to-region start end)
8684 (let ((dcst (downcase sorting-type))
8685 (case-fold-search nil)
8686 (now (current-time)))
8687 (sort-subr
8688 (/= dcst sorting-type)
8689 ;; This function moves to the beginning character of the "record" to
8690 ;; be sorted.
8691 (lambda nil
8692 (if (re-search-forward re nil t)
8693 (goto-char (match-beginning 0))
8694 (goto-char (point-max))))
8695 ;; This function moves to the last character of the "record" being
8696 ;; sorted.
8697 (lambda nil
8698 (save-match-data
8699 (condition-case nil
8700 (outline-forward-same-level 1)
8701 (error
8702 (goto-char (point-max))))))
8703 ;; This function returns the value that gets sorted against.
8704 (lambda nil
8705 (cond
8706 ((= dcst ?n)
8707 (if (looking-at org-complex-heading-regexp)
8708 (string-to-number (org-sort-remove-invisible (match-string 4)))
8709 nil))
8710 ((= dcst ?a)
8711 (if (looking-at org-complex-heading-regexp)
8712 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8713 nil))
8714 ((= dcst ?t)
8715 (let ((end (save-excursion (outline-next-heading) (point))))
8716 (if (or (re-search-forward org-ts-regexp end t)
8717 (re-search-forward org-ts-regexp-both end t))
8718 (org-time-string-to-seconds (match-string 0))
8719 (org-float-time now))))
8720 ((= dcst ?c)
8721 (let ((end (save-excursion (outline-next-heading) (point))))
8722 (if (re-search-forward
8723 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8724 end t)
8725 (org-time-string-to-seconds (match-string 0))
8726 (org-float-time now))))
8727 ((= dcst ?s)
8728 (let ((end (save-excursion (outline-next-heading) (point))))
8729 (if (re-search-forward org-scheduled-time-regexp end t)
8730 (org-time-string-to-seconds (match-string 1))
8731 (org-float-time now))))
8732 ((= dcst ?d)
8733 (let ((end (save-excursion (outline-next-heading) (point))))
8734 (if (re-search-forward org-deadline-time-regexp end t)
8735 (org-time-string-to-seconds (match-string 1))
8736 (org-float-time now))))
8737 ((= dcst ?p)
8738 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8739 (string-to-char (match-string 2))
8740 org-default-priority))
8741 ((= dcst ?r)
8742 (or (org-entry-get nil property) ""))
8743 ((= dcst ?o)
8744 (if (looking-at org-complex-heading-regexp)
8745 (- 9999 (length (member (match-string 2)
8746 org-todo-keywords-1)))))
8747 ((= dcst ?f)
8748 (if getkey-func
8749 (progn
8750 (setq tmp (funcall getkey-func))
8751 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8752 tmp)
8753 (error "Invalid key function `%s'" getkey-func)))
8754 (t (error "Invalid sorting type `%c'" sorting-type))))
8756 (cond
8757 ((= dcst ?a) 'string<)
8758 ((= dcst ?f) compare-func)
8759 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8760 (run-hooks 'org-after-sorting-entries-or-items-hook)
8761 ;; Reset the clock marker if needed
8762 (when cmstr
8763 (save-excursion
8764 (goto-char start)
8765 (search-forward cmstr nil t)
8766 (move-marker org-clock-marker (point))))
8767 (message "Sorting entries...done")))
8769 (defun org-do-sort (table what &optional with-case sorting-type)
8770 "Sort TABLE of WHAT according to SORTING-TYPE.
8771 The user will be prompted for the SORTING-TYPE if the call to this
8772 function does not specify it. WHAT is only for the prompt, to indicate
8773 what is being sorted. The sorting key will be extracted from
8774 the car of the elements of the table.
8775 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8776 (unless sorting-type
8777 (message
8778 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8779 what)
8780 (setq sorting-type (read-char-exclusive)))
8781 (let ((dcst (downcase sorting-type))
8782 extractfun comparefun)
8783 ;; Define the appropriate functions
8784 (cond
8785 ((= dcst ?n)
8786 (setq extractfun 'string-to-number
8787 comparefun (if (= dcst sorting-type) '< '>)))
8788 ((= dcst ?a)
8789 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8790 (lambda(x) (downcase (org-sort-remove-invisible x))))
8791 comparefun (if (= dcst sorting-type)
8792 'string<
8793 (lambda (a b) (and (not (string< a b))
8794 (not (string= a b)))))))
8795 ((= dcst ?t)
8796 (setq extractfun
8797 (lambda (x)
8798 (if (or (string-match org-ts-regexp x)
8799 (string-match org-ts-regexp-both x))
8800 (org-float-time
8801 (org-time-string-to-time (match-string 0 x)))
8803 comparefun (if (= dcst sorting-type) '< '>)))
8804 (t (error "Invalid sorting type `%c'" sorting-type)))
8806 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8807 table)
8808 (lambda (a b) (funcall comparefun (car a) (car b))))))
8811 ;;; The orgstruct minor mode
8813 ;; Define a minor mode which can be used in other modes in order to
8814 ;; integrate the org-mode structure editing commands.
8816 ;; This is really a hack, because the org-mode structure commands use
8817 ;; keys which normally belong to the major mode. Here is how it
8818 ;; works: The minor mode defines all the keys necessary to operate the
8819 ;; structure commands, but wraps the commands into a function which
8820 ;; tests if the cursor is currently at a headline or a plain list
8821 ;; item. If that is the case, the structure command is used,
8822 ;; temporarily setting many Org-mode variables like regular
8823 ;; expressions for filling etc. However, when any of those keys is
8824 ;; used at a different location, function uses `key-binding' to look
8825 ;; up if the key has an associated command in another currently active
8826 ;; keymap (minor modes, major mode, global), and executes that
8827 ;; command. There might be problems if any of the keys is otherwise
8828 ;; used as a prefix key.
8830 (defcustom orgstruct-heading-prefix-regexp nil
8831 "Regexp that matches the custom prefix of Org headlines in
8832 orgstruct(++)-mode."
8833 :group 'org
8834 :version "24.4"
8835 :package-version '(Org . "8.0")
8836 :type 'string)
8837 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8839 (defcustom orgstruct-setup-hook nil
8840 "Hook run after orgstruct-mode-map is filled."
8841 :group 'org
8842 :version "24.4"
8843 :package-version '(Org . "8.0")
8844 :type 'hook)
8846 (defvar orgstruct-initialized nil)
8848 (defvar org-local-vars nil
8849 "List of local variables, for use by `orgstruct-mode'.")
8851 ;;;###autoload
8852 (define-minor-mode orgstruct-mode
8853 "Toggle the minor mode `orgstruct-mode'.
8854 This mode is for using Org-mode structure commands in other
8855 modes. The following keys behave as if Org-mode were active, if
8856 the cursor is on a headline, or on a plain list item (both as
8857 defined by Org-mode)."
8858 nil " OrgStruct" (make-sparse-keymap)
8859 (funcall (if orgstruct-mode
8860 'add-to-invisibility-spec
8861 'remove-from-invisibility-spec)
8862 '(outline . t))
8863 (when orgstruct-mode
8864 (org-load-modules-maybe)
8865 (unless orgstruct-initialized
8866 (orgstruct-setup)
8867 (setq orgstruct-initialized t))))
8869 ;;;###autoload
8870 (defun turn-on-orgstruct ()
8871 "Unconditionally turn on `orgstruct-mode'."
8872 (orgstruct-mode 1))
8874 (defvar org-fb-vars nil)
8875 (make-variable-buffer-local 'org-fb-vars)
8876 (defun orgstruct++-mode (&optional arg)
8877 "Toggle `orgstruct-mode', the enhanced version of it.
8878 In addition to setting orgstruct-mode, this also exports all
8879 indentation and autofilling variables from org-mode into the
8880 buffer. It will also recognize item context in multiline items."
8881 (interactive "P")
8882 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8883 (if (< arg 1)
8884 (progn (orgstruct-mode -1)
8885 (mapc (lambda(v)
8886 (org-set-local (car v)
8887 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8888 org-fb-vars))
8889 (orgstruct-mode 1)
8890 (setq org-fb-vars nil)
8891 (let (var val)
8892 (mapc
8893 (lambda (x)
8894 (when (string-match
8895 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8896 (symbol-name (car x)))
8897 (setq var (car x) val (nth 1 x))
8898 (push (list var `(quote ,(eval var))) org-fb-vars)
8899 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8900 org-local-vars)
8901 (org-set-local 'orgstruct-is-++ t))))
8903 (defvar orgstruct-is-++ nil
8904 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8905 (make-variable-buffer-local 'orgstruct-is-++)
8907 ;;;###autoload
8908 (defun turn-on-orgstruct++ ()
8909 "Unconditionally turn on `orgstruct++-mode'."
8910 (orgstruct++-mode 1))
8912 (defun orgstruct-error ()
8913 "Error when there is no default binding for a structure key."
8914 (interactive)
8915 (funcall (if (fboundp 'user-error)
8916 'user-error
8917 'error)
8918 "This key has no function outside structure elements"))
8920 (defun orgstruct-setup ()
8921 "Setup orgstruct keymap."
8922 (dolist (cell '((org-demote . t)
8923 (org-metaleft . t)
8924 (org-metaright . t)
8925 (org-promote . t)
8926 (org-shiftmetaleft . t)
8927 (org-shiftmetaright . t)
8928 org-backward-element
8929 org-backward-heading-same-level
8930 org-ctrl-c-ret
8931 org-ctrl-c-minus
8932 org-ctrl-c-star
8933 org-cycle
8934 org-forward-heading-same-level
8935 org-insert-heading
8936 org-insert-heading-respect-content
8937 org-kill-note-or-show-branches
8938 org-mark-subtree
8939 org-meta-return
8940 org-metadown
8941 org-metaup
8942 org-narrow-to-subtree
8943 org-promote-subtree
8944 org-reveal
8945 org-shiftdown
8946 org-shiftleft
8947 org-shiftmetadown
8948 org-shiftmetaup
8949 org-shiftright
8950 org-shifttab
8951 org-shifttab
8952 org-shiftup
8953 org-show-subtree
8954 org-sort
8955 org-up-element
8956 outline-demote
8957 outline-next-visible-heading
8958 outline-previous-visible-heading
8959 outline-promote
8960 outline-up-heading
8961 show-children))
8962 (let ((f (or (car-safe cell) cell))
8963 (disable-when-heading-prefix (cdr-safe cell)))
8964 (when (fboundp f)
8965 (dolist (binding (nconc (where-is-internal f org-mode-map)
8966 (where-is-internal f outline-mode-map)))
8967 ;; TODO use local-function-key-map
8968 (dolist (rep '(("<tab>" . "TAB")
8969 ("<return>" . "RET")
8970 ("<escape>" . "ESC")
8971 ("<delete>" . "DEL")))
8972 (setq binding (read-kbd-macro
8973 (let ((case-fold-search))
8974 (replace-regexp-in-string
8975 (regexp-quote (cdr rep))
8976 (car rep)
8977 (key-description binding))))))
8978 (let ((key (lookup-key orgstruct-mode-map binding)))
8979 (when (or (not key) (numberp key))
8980 (condition-case nil
8981 (org-defkey orgstruct-mode-map
8982 binding
8983 (orgstruct-make-binding f binding disable-when-heading-prefix))
8984 (error nil))))))))
8985 (run-hooks 'orgstruct-setup-hook))
8987 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8988 "Create a function for binding in the structure minor mode.
8989 FUN is the command to call inside a table. KEY is the key that
8990 should be checked in for a command to execute outside of tables.
8991 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8992 if `orgstruct-heading-prefix-regexp' is non-nil."
8993 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8994 (let ((nname name)
8995 (i 0))
8996 (while (fboundp (intern nname))
8997 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8998 (setq name (intern nname)))
8999 (eval
9000 (let ((bindings '((org-heading-regexp
9001 (concat "^"
9002 orgstruct-heading-prefix-regexp
9003 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9004 (org-outline-regexp
9005 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9006 (org-outline-regexp-bol
9007 (concat "^" org-outline-regexp))
9008 (outline-regexp org-outline-regexp)
9009 (outline-heading-end-regexp "\n")
9010 (outline-level 'org-outline-level)
9011 (outline-heading-alist))))
9012 `(defun ,name (arg)
9013 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9014 "Outside of structure, run the binding of `"
9015 (key-description key) "'."
9016 (when disable-when-heading-prefix
9017 (concat
9018 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9019 "back to the default binding due to limitations of Org's implementation of\n"
9020 "`" (symbol-name fun) "'.")))
9021 (interactive "p")
9022 (let* ((disable
9023 ,(when disable-when-heading-prefix
9024 '(and orgstruct-heading-prefix-regexp
9025 (not (string= orgstruct-heading-prefix-regexp "")))))
9026 (fallback
9027 (or disable
9028 (not
9029 (let* ,bindings
9030 (org-context-p 'headline 'item
9031 ,(when (memq fun '(org-insert-heading))
9032 '(when orgstruct-is-++
9033 'item-body))))))))
9034 (if fallback
9035 (let* ((orgstruct-mode)
9036 (binding
9037 (loop with key = ,key
9038 for rep in
9039 '(nil
9040 ("<\\([^>]*\\)tab>" . "\\1TAB")
9041 ("<\\([^>]*\\)return>" . "\\1RET")
9042 ("<\\([^>]*\\)escape>" . "\\1ESC")
9043 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9045 (when rep
9046 (setq key (read-kbd-macro
9047 (let ((case-fold-search))
9048 (replace-regexp-in-string
9049 (car rep)
9050 (cdr rep)
9051 (key-description key))))))
9052 thereis (key-binding key))))
9053 (if (keymapp binding)
9054 (set-temporary-overlay-map binding)
9055 (let ((func (or binding
9056 (unless disable
9057 'orgstruct-error))))
9058 (when func
9059 (call-interactively func)))))
9060 (org-run-like-in-org-mode
9061 (lambda ()
9062 (interactive)
9063 (let* ,bindings
9064 (call-interactively ',fun)))))))))
9065 name))
9067 (defun org-contextualize-keys (alist contexts)
9068 "Return valid elements in ALIST depending on CONTEXTS.
9070 `org-agenda-custom-commands' or `org-capture-templates' are the
9071 values used for ALIST, and `org-agenda-custom-commands-contexts'
9072 or `org-capture-templates-contexts' are the associated contexts
9073 definitions."
9074 (let ((contexts
9075 ;; normalize contexts
9076 (mapcar
9077 (lambda(c) (cond ((listp (cadr c))
9078 (list (car c) (car c) (cadr c)))
9079 ((string= "" (cadr c))
9080 (list (car c) (car c) (caddr c)))
9081 (t c))) contexts))
9082 (a alist) c r s)
9083 ;; loop over all commands or templates
9084 (while (setq c (pop a))
9085 (let (vrules repl)
9086 (cond
9087 ((not (assoc (car c) contexts))
9088 (push c r))
9089 ((and (assoc (car c) contexts)
9090 (setq vrules (org-contextualize-validate-key
9091 (car c) contexts)))
9092 (mapc (lambda (vr)
9093 (when (not (equal (car vr) (cadr vr)))
9094 (setq repl vr))) vrules)
9095 (if (not repl) (push c r)
9096 (push (cadr repl) s)
9097 (push
9098 (cons (car c)
9099 (cdr (or (assoc (cadr repl) alist)
9100 (error "Undefined key `%s' as contextual replacement for `%s'"
9101 (cadr repl) (car c)))))
9102 r))))))
9103 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9104 (delq
9106 (delete-dups
9107 (mapcar (lambda (x)
9108 (let ((tpl (car x)))
9109 (when (not (delq
9111 (mapcar (lambda(y)
9112 (equal y tpl)) s))) x)))
9113 (reverse r))))))
9115 (defun org-contextualize-validate-key (key contexts)
9116 "Check CONTEXTS for agenda or capture KEY."
9117 (let (r rr res)
9118 (while (setq r (pop contexts))
9119 (mapc
9120 (lambda (rr)
9121 (when
9122 (and (equal key (car r))
9123 (if (functionp rr) (funcall rr)
9124 (or (and (eq (car rr) 'in-file)
9125 (buffer-file-name)
9126 (string-match (cdr rr) (buffer-file-name)))
9127 (and (eq (car rr) 'in-mode)
9128 (string-match (cdr rr) (symbol-name major-mode)))
9129 (and (eq (car rr) 'in-buffer)
9130 (string-match (cdr rr) (buffer-name)))
9131 (when (and (eq (car rr) 'not-in-file)
9132 (buffer-file-name))
9133 (not (string-match (cdr rr) (buffer-file-name))))
9134 (when (eq (car rr) 'not-in-mode)
9135 (not (string-match (cdr rr) (symbol-name major-mode))))
9136 (when (eq (car rr) 'not-in-buffer)
9137 (not (string-match (cdr rr) (buffer-name)))))))
9138 (push r res)))
9139 (car (last r))))
9140 (delete-dups (delq nil res))))
9142 (defun org-context-p (&rest contexts)
9143 "Check if local context is any of CONTEXTS.
9144 Possible values in the list of contexts are `table', `headline', and `item'."
9145 (let ((pos (point)))
9146 (goto-char (point-at-bol))
9147 (prog1 (or (and (memq 'table contexts)
9148 (looking-at "[ \t]*|"))
9149 (and (memq 'headline contexts)
9150 (looking-at org-outline-regexp))
9151 (and (memq 'item contexts)
9152 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9153 (and (memq 'item-body contexts)
9154 (org-in-item-p)))
9155 (goto-char pos))))
9157 (defun org-get-local-variables ()
9158 "Return a list of all local variables in an Org mode buffer."
9159 (let (varlist)
9160 (with-current-buffer (get-buffer-create "*Org tmp*")
9161 (erase-buffer)
9162 (org-mode)
9163 (setq varlist (buffer-local-variables)))
9164 (kill-buffer "*Org tmp*")
9165 (delq nil
9166 (mapcar
9167 (lambda (x)
9168 (setq x
9169 (if (symbolp x)
9170 (list x)
9171 (list (car x) (cdr x))))
9172 (if (and (not (get (car x) 'org-state))
9173 (string-match
9174 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9175 (symbol-name (car x))))
9176 x nil))
9177 varlist))))
9179 (defun org-clone-local-variables (from-buffer &optional regexp)
9180 "Clone local variables from FROM-BUFFER.
9181 Optional argument REGEXP selects variables to clone."
9182 (mapc
9183 (lambda (pair)
9184 (and (symbolp (car pair))
9185 (or (null regexp)
9186 (string-match regexp (symbol-name (car pair))))
9187 (set (make-local-variable (car pair))
9188 (cdr pair))))
9189 (buffer-local-variables from-buffer)))
9191 ;;;###autoload
9192 (defun org-run-like-in-org-mode (cmd)
9193 "Run a command, pretending that the current buffer is in Org-mode.
9194 This will temporarily bind local variables that are typically bound in
9195 Org-mode to the values they have in Org-mode, and then interactively
9196 call CMD."
9197 (org-load-modules-maybe)
9198 (unless org-local-vars
9199 (setq org-local-vars (org-get-local-variables)))
9200 (let (binds)
9201 (dolist (var org-local-vars)
9202 (when (or (not (boundp (car var)))
9203 (eq (symbol-value (car var))
9204 (default-value (car var))))
9205 (push (list (car var) `(quote ,(cadr var))) binds)))
9206 (eval `(let ,binds
9207 (call-interactively (quote ,cmd))))))
9209 ;;;; Archiving
9211 (defun org-get-category (&optional pos force-refresh)
9212 "Get the category applying to position POS."
9213 (save-match-data
9214 (if force-refresh (org-refresh-category-properties))
9215 (let ((pos (or pos (point))))
9216 (or (get-text-property pos 'org-category)
9217 (progn (org-refresh-category-properties)
9218 (get-text-property pos 'org-category))))))
9220 (defun org-refresh-category-properties ()
9221 "Refresh category text properties in the buffer."
9222 (let ((case-fold-search t)
9223 (inhibit-read-only t)
9224 (def-cat (cond
9225 ((null org-category)
9226 (if buffer-file-name
9227 (file-name-sans-extension
9228 (file-name-nondirectory buffer-file-name))
9229 "???"))
9230 ((symbolp org-category) (symbol-name org-category))
9231 (t org-category)))
9232 beg end cat pos optionp)
9233 (org-with-silent-modifications
9234 (save-excursion
9235 (save-restriction
9236 (widen)
9237 (goto-char (point-min))
9238 (put-text-property (point) (point-max) 'org-category def-cat)
9239 (while (re-search-forward
9240 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9241 (setq pos (match-end 0)
9242 optionp (equal (char-after (match-beginning 0)) ?#)
9243 cat (org-trim (match-string 2)))
9244 (if optionp
9245 (setq beg (point-at-bol) end (point-max))
9246 (org-back-to-heading t)
9247 (setq beg (point) end (org-end-of-subtree t t)))
9248 (put-text-property beg end 'org-category cat)
9249 (put-text-property beg end 'org-category-position beg)
9250 (goto-char pos)))))))
9252 (defun org-refresh-properties (dprop tprop)
9253 "Refresh buffer text properties.
9254 DPROP is the drawer property and TPROP is the corresponding text
9255 property to set."
9256 (let ((case-fold-search t)
9257 (inhibit-read-only t) p)
9258 (org-with-silent-modifications
9259 (save-excursion
9260 (save-restriction
9261 (widen)
9262 (goto-char (point-min))
9263 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9264 (setq p (org-match-string-no-properties 1))
9265 (save-excursion
9266 (org-back-to-heading t)
9267 (put-text-property
9268 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9271 ;;;; Link Stuff
9273 ;;; Link abbreviations
9275 (defun org-link-expand-abbrev (link)
9276 "Apply replacements as defined in `org-link-abbrev-alist'."
9277 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9278 (let* ((key (match-string 1 link))
9279 (as (or (assoc key org-link-abbrev-alist-local)
9280 (assoc key org-link-abbrev-alist)))
9281 (tag (and (match-end 2) (match-string 3 link)))
9282 rpl)
9283 (if (not as)
9284 link
9285 (setq rpl (cdr as))
9286 (cond
9287 ((symbolp rpl) (funcall rpl tag))
9288 ((string-match "%(\\([^)]+\\))" rpl)
9289 (replace-match
9290 (save-match-data
9291 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9292 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9293 ((string-match "%h" rpl)
9294 (replace-match (url-hexify-string (or tag "")) t t rpl))
9295 (t (concat rpl tag)))))
9296 link))
9298 ;;; Storing and inserting links
9300 (defvar org-insert-link-history nil
9301 "Minibuffer history for links inserted with `org-insert-link'.")
9303 (defvar org-stored-links nil
9304 "Contains the links stored with `org-store-link'.")
9306 (defvar org-store-link-plist nil
9307 "Plist with info about the most recently link created with `org-store-link'.")
9309 (defvar org-link-protocols nil
9310 "Link protocols added to Org-mode using `org-add-link-type'.")
9312 (defvar org-store-link-functions nil
9313 "List of functions that are called to create and store a link.
9314 Each function will be called in turn until one returns a non-nil
9315 value. Each function should check if it is responsible for creating
9316 this link (for example by looking at the major mode).
9317 If not, it must exit and return nil.
9318 If yes, it should return a non-nil value after a calling
9319 `org-store-link-props' with a list of properties and values.
9320 Special properties are:
9322 :type The link prefix, like \"http\". This must be given.
9323 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9324 This is obligatory as well.
9325 :description Optional default description for the second pair
9326 of brackets in an Org-mode link. The user can still change
9327 this when inserting this link into an Org-mode buffer.
9329 In addition to these, any additional properties can be specified
9330 and then used in capture templates.")
9332 (defun org-add-link-type (type &optional follow export)
9333 "Add TYPE to the list of `org-link-types'.
9334 Re-compute all regular expressions depending on `org-link-types'
9336 FOLLOW and EXPORT are two functions.
9338 FOLLOW should take the link path as the single argument and do whatever
9339 is necessary to follow the link, for example find a file or display
9340 a mail message.
9342 EXPORT should format the link path for export to one of the export formats.
9343 It should be a function accepting three arguments:
9345 path the path of the link, the text after the prefix (like \"http:\")
9346 desc the description of the link, if any, or a description added by
9347 org-export-normalize-links if there is none
9348 format the export format, a symbol like `html' or `latex' or `ascii'..
9350 The function may use the FORMAT information to return different values
9351 depending on the format. The return value will be put literally into
9352 the exported file. If the return value is nil, this means Org should
9353 do what it normally does with links which do not have EXPORT defined.
9355 Org-mode has a built-in default for exporting links. If you are happy with
9356 this default, there is no need to define an export function for the link
9357 type. For a simple example of an export function, see `org-bbdb.el'."
9358 (add-to-list 'org-link-types type t)
9359 (org-make-link-regexps)
9360 (if (assoc type org-link-protocols)
9361 (setcdr (assoc type org-link-protocols) (list follow export))
9362 (push (list type follow export) org-link-protocols)))
9364 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9365 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9367 ;;;###autoload
9368 (defun org-store-link (arg)
9369 "\\<org-mode-map>Store an org-link to the current location.
9370 This link is added to `org-stored-links' and can later be inserted
9371 into an org-buffer with \\[org-insert-link].
9373 For some link types, a prefix arg is interpreted.
9374 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9375 For file links, arg negates `org-context-in-file-links'.
9377 A double prefix arg force skipping storing functions that are not
9378 part of Org's core.
9380 A triple prefix arg force storing a link for each line in the
9381 active region."
9382 (interactive "P")
9383 (org-load-modules-maybe)
9384 (if (and (equal arg '(64)) (org-region-active-p))
9385 (save-excursion
9386 (let ((end (region-end)))
9387 (goto-char (region-beginning))
9388 (set-mark (point))
9389 (while (< (point-at-eol) end)
9390 (move-end-of-line 1) (activate-mark)
9391 (let (current-prefix-arg)
9392 (call-interactively 'org-store-link))
9393 (move-beginning-of-line 2)
9394 (set-mark (point)))))
9395 (org-with-limited-levels
9396 (setq org-store-link-plist nil)
9397 (let (link cpltxt desc description search
9398 txt custom-id agenda-link sfuns sfunsn)
9399 (cond
9401 ;; Store a link using an external link type
9402 ((and (not (equal arg '(16)))
9403 (setq sfuns
9404 (delq
9405 nil (mapcar (lambda (f)
9406 (let (fs) (if (funcall f) (push f fs))))
9407 org-store-link-functions))
9408 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9409 (or (and (cdr sfuns)
9410 (funcall (intern
9411 (completing-read
9412 "Which function for creating the link? "
9413 sfunsn t (car sfunsn)))))
9414 (funcall (caar sfuns)))
9415 (setq link (plist-get org-store-link-plist :link)
9416 desc (or (plist-get org-store-link-plist
9417 :description) link))))
9419 ;; Store a link from a source code buffer
9420 ((org-src-edit-buffer-p)
9421 (let (label gc)
9422 (while (or (not label)
9423 (save-excursion
9424 (save-restriction
9425 (widen)
9426 (goto-char (point-min))
9427 (re-search-forward
9428 (regexp-quote (format org-coderef-label-format label))
9429 nil t))))
9430 (when label (message "Label exists already") (sit-for 2))
9431 (setq label (read-string "Code line label: " label)))
9432 (end-of-line 1)
9433 (setq link (format org-coderef-label-format label))
9434 (setq gc (- 79 (length link)))
9435 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9436 (insert link)
9437 (setq link (concat "(" label ")") desc nil)))
9439 ;; We are in the agenda, link to referenced location
9440 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9441 (let ((m (or (get-text-property (point) 'org-hd-marker)
9442 (get-text-property (point) 'org-marker))))
9443 (when m
9444 (org-with-point-at m
9445 (setq agenda-link
9446 (if (org-called-interactively-p 'any)
9447 (call-interactively 'org-store-link)
9448 (org-store-link nil)))))))
9450 ((eq major-mode 'calendar-mode)
9451 (let ((cd (calendar-cursor-to-date)))
9452 (setq link
9453 (format-time-string
9454 (car org-time-stamp-formats)
9455 (apply 'encode-time
9456 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9457 nil nil nil))))
9458 (org-store-link-props :type "calendar" :date cd)))
9460 ((eq major-mode 'help-mode)
9461 (setq link (concat "help:" (save-excursion
9462 (goto-char (point-min))
9463 (looking-at "^[^ ]+")
9464 (match-string 0))))
9465 (org-store-link-props :type "help"))
9467 ((eq major-mode 'w3-mode)
9468 (setq cpltxt (if (and (buffer-name)
9469 (not (string-match "Untitled" (buffer-name))))
9470 (buffer-name)
9471 (url-view-url t))
9472 link (url-view-url t))
9473 (org-store-link-props :type "w3" :url (url-view-url t)))
9475 ((eq major-mode 'image-mode)
9476 (setq cpltxt (concat "file:"
9477 (abbreviate-file-name buffer-file-name))
9478 link cpltxt)
9479 (org-store-link-props :type "image" :file buffer-file-name))
9481 ;; In dired, store a link to the file of the current line
9482 ((eq major-mode 'dired-mode)
9483 (let ((file (dired-get-filename nil t)))
9484 (setq file (if file
9485 (abbreviate-file-name
9486 (expand-file-name (dired-get-filename nil t)))
9487 ;; otherwise, no file so use current directory.
9488 default-directory))
9489 (setq cpltxt (concat "file:" file)
9490 link cpltxt)))
9492 ((setq search (run-hook-with-args-until-success
9493 'org-create-file-search-functions))
9494 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9495 "::" search))
9496 (setq cpltxt (or description link)))
9498 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9499 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9500 (cond
9501 ;; Store a link using the target at point
9502 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9503 (setq cpltxt
9504 (concat "file:"
9505 (abbreviate-file-name
9506 (buffer-file-name (buffer-base-buffer)))
9507 "::" (match-string 1))
9508 link cpltxt))
9509 ((and (featurep 'org-id)
9510 (or (eq org-id-link-to-org-use-id t)
9511 (and (org-called-interactively-p 'any)
9512 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9513 (and (eq org-id-link-to-org-use-id
9514 'create-if-interactive-and-no-custom-id)
9515 (not custom-id))))
9516 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9517 ;; Store a link using the ID at point
9518 (setq link (condition-case nil
9519 (prog1 (org-id-store-link)
9520 (setq desc (plist-get org-store-link-plist
9521 :description)))
9522 (error
9523 ;; Probably before first headline, link only to file
9524 (concat "file:"
9525 (abbreviate-file-name
9526 (buffer-file-name (buffer-base-buffer))))))))
9528 ;; Just link to current headline
9529 (setq cpltxt (concat "file:"
9530 (abbreviate-file-name
9531 (buffer-file-name (buffer-base-buffer)))))
9532 ;; Add a context search string
9533 (when (org-xor org-context-in-file-links arg)
9534 (let* ((ee (org-element-at-point))
9535 (et (org-element-type ee))
9536 (ev (plist-get (cadr ee) :value))
9537 (ek (plist-get (cadr ee) :key))
9538 (eok (and (stringp ek) (string-match "name" ek))))
9539 (setq txt (cond
9540 ((org-at-heading-p) nil)
9541 ((and (eq et 'keyword) eok) ev)
9542 ((org-region-active-p)
9543 (buffer-substring (region-beginning) (region-end)))))
9544 (when (or (null txt) (string-match "\\S-" txt))
9545 (setq cpltxt
9546 (concat cpltxt "::"
9547 (condition-case nil
9548 (org-make-org-heading-search-string txt)
9549 (error "")))
9550 desc (or (and (eq et 'keyword) eok ev)
9551 (nth 4 (ignore-errors (org-heading-components)))
9552 "NONE")))))
9553 (if (string-match "::\\'" cpltxt)
9554 (setq cpltxt (substring cpltxt 0 -2)))
9555 (setq link cpltxt))))
9557 ((buffer-file-name (buffer-base-buffer))
9558 ;; Just link to this file here.
9559 (setq cpltxt (concat "file:"
9560 (abbreviate-file-name
9561 (buffer-file-name (buffer-base-buffer)))))
9562 ;; Add a context string.
9563 (when (org-xor org-context-in-file-links arg)
9564 (setq txt (if (org-region-active-p)
9565 (buffer-substring (region-beginning) (region-end))
9566 (buffer-substring (point-at-bol) (point-at-eol))))
9567 ;; Only use search option if there is some text.
9568 (when (string-match "\\S-" txt)
9569 (setq cpltxt
9570 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9571 desc "NONE")))
9572 (setq link cpltxt))
9574 ((org-called-interactively-p 'interactive)
9575 (user-error "No method for storing a link from this buffer"))
9577 (t (setq link nil)))
9579 ;; We're done setting link and desc, clean up
9580 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9581 (setq link (or link cpltxt)
9582 desc (or desc cpltxt))
9583 (cond ((equal desc "NONE") (setq desc nil))
9584 ((string-match org-bracket-link-analytic-regexp desc)
9585 (let ((d0 (match-string 3 desc))
9586 (p0 (match-string 5 desc)))
9587 (setq desc
9588 (replace-regexp-in-string
9589 org-bracket-link-regexp
9590 (concat (or p0 d0)
9591 (if (equal (length (match-string 0 desc))
9592 (length desc)) "*" "")) desc)))))
9594 ;; Return the link
9595 (if (not (and (or (org-called-interactively-p 'any)
9596 executing-kbd-macro) link))
9597 (or agenda-link (and link (org-make-link-string link desc)))
9598 (push (list link desc) org-stored-links)
9599 (message "Stored: %s" (or desc link))
9600 (when custom-id
9601 (setq link (concat "file:" (abbreviate-file-name
9602 (buffer-file-name)) "::#" custom-id))
9603 (push (list link desc) org-stored-links)))))))
9605 (defun org-store-link-props (&rest plist)
9606 "Store link properties, extract names and addresses."
9607 (let (x adr)
9608 (when (setq x (plist-get plist :from))
9609 (setq adr (mail-extract-address-components x))
9610 (setq plist (plist-put plist :fromname (car adr)))
9611 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9612 (when (setq x (plist-get plist :to))
9613 (setq adr (mail-extract-address-components x))
9614 (setq plist (plist-put plist :toname (car adr)))
9615 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9616 (let ((from (plist-get plist :from))
9617 (to (plist-get plist :to)))
9618 (when (and from to org-from-is-user-regexp)
9619 (setq plist
9620 (plist-put plist :fromto
9621 (if (string-match org-from-is-user-regexp from)
9622 (concat "to %t")
9623 (concat "from %f"))))))
9624 (setq org-store-link-plist plist))
9626 (defun org-add-link-props (&rest plist)
9627 "Add these properties to the link property list."
9628 (let (key value)
9629 (while plist
9630 (setq key (pop plist) value (pop plist))
9631 (setq org-store-link-plist
9632 (plist-put org-store-link-plist key value)))))
9634 (defun org-email-link-description (&optional fmt)
9635 "Return the description part of an email link.
9636 This takes information from `org-store-link-plist' and formats it
9637 according to FMT (default from `org-email-link-description-format')."
9638 (setq fmt (or fmt org-email-link-description-format))
9639 (let* ((p org-store-link-plist)
9640 (to (plist-get p :toaddress))
9641 (from (plist-get p :fromaddress))
9642 (table
9643 (list
9644 (cons "%c" (plist-get p :fromto))
9645 (cons "%F" (plist-get p :from))
9646 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9647 (cons "%T" (plist-get p :to))
9648 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9649 (cons "%s" (plist-get p :subject))
9650 (cons "%d" (plist-get p :date))
9651 (cons "%m" (plist-get p :message-id)))))
9652 (when (string-match "%c" fmt)
9653 ;; Check if the user wrote this message
9654 (if (and org-from-is-user-regexp from to
9655 (save-match-data (string-match org-from-is-user-regexp from)))
9656 (setq fmt (replace-match "to %t" t t fmt))
9657 (setq fmt (replace-match "from %f" t t fmt))))
9658 (org-replace-escapes fmt table)))
9660 (defun org-make-org-heading-search-string (&optional string)
9661 "Make search string for the current headline or STRING."
9662 (let ((s (or string
9663 (and (derived-mode-p 'org-mode)
9664 (save-excursion
9665 (org-back-to-heading t)
9666 (org-element-property :raw-value (org-element-at-point))))))
9667 (lines org-context-in-file-links))
9668 (or string (setq s (concat "*" s))) ; Add * for headlines
9669 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9670 (when (and string (integerp lines) (> lines 0))
9671 (let ((slines (org-split-string s "\n")))
9672 (when (< lines (length slines))
9673 (setq s (mapconcat
9674 'identity
9675 (reverse (nthcdr (- (length slines) lines)
9676 (reverse slines))) "\n")))))
9677 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9679 (defun org-make-link-string (link &optional description)
9680 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9681 (unless (string-match "\\S-" link)
9682 (error "Empty link"))
9683 (when (and description
9684 (stringp description)
9685 (not (string-match "\\S-" description)))
9686 (setq description nil))
9687 (when (stringp description)
9688 ;; Remove brackets from the description, they are fatal.
9689 (while (string-match "\\[" description)
9690 (setq description (replace-match "{" t t description)))
9691 (while (string-match "\\]" description)
9692 (setq description (replace-match "}" t t description))))
9693 (when (equal link description)
9694 ;; No description needed, it is identical
9695 (setq description nil))
9696 (when (and (not description)
9697 (not (string-match (org-image-file-name-regexp) link))
9698 (not (equal link (org-link-escape link))))
9699 (setq description (org-extract-attributes link)))
9700 (setq link
9701 (cond ((string-match (org-image-file-name-regexp) link) link)
9702 ((string-match org-link-types-re link)
9703 (concat (match-string 1 link)
9704 (org-link-escape (substring link (match-end 1)))))
9705 (t (org-link-escape link))))
9706 (concat "[[" link "]"
9707 (if description (concat "[" description "]") "")
9708 "]"))
9710 (defconst org-link-escape-chars
9711 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9712 "List of characters that should be escaped in link.
9713 This is the list that is used for internal purposes.")
9715 (defconst org-link-escape-chars-browser
9716 '(?\ )
9717 "List of escapes for characters that are problematic in links.
9718 This is the list that is used before handing over to the browser.")
9720 (defun org-link-escape (text &optional table merge)
9721 "Return percent escaped representation of TEXT.
9722 TEXT is a string with the text to escape.
9723 Optional argument TABLE is a list with characters that should be
9724 escaped. When nil, `org-link-escape-chars' is used.
9725 If optional argument MERGE is set, merge TABLE into
9726 `org-link-escape-chars'."
9727 (cond
9728 ((and table merge)
9729 (mapc (lambda (defchr)
9730 (unless (member defchr table)
9731 (setq table (cons defchr table)))) org-link-escape-chars))
9732 ((null table)
9733 (setq table org-link-escape-chars)))
9734 (mapconcat
9735 (lambda (char)
9736 (if (or (member char table)
9737 (and (or (< char 32) (= char 37) (> char 126))
9738 org-url-hexify-p))
9739 (mapconcat (lambda (sequence-element)
9740 (format "%%%.2X" sequence-element))
9741 (or (encode-coding-char char 'utf-8)
9742 (error "Unable to percent escape character: %s"
9743 (char-to-string char))) "")
9744 (char-to-string char))) text ""))
9746 (defun org-link-unescape (str)
9747 "Unhex hexified Unicode strings as returned from the JavaScript function
9748 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9749 (unless (and (null str) (string= "" str))
9750 (let ((pos 0) (case-fold-search t) unhexed)
9751 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9752 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9753 (setq str (replace-match unhexed t t str))
9754 (setq pos (+ pos (length unhexed))))))
9755 str)
9757 (defun org-link-unescape-compound (hex)
9758 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9759 Note: this function also decodes single byte encodings like
9760 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9761 (save-match-data
9762 (let* ((bytes (cdr (split-string hex "%")))
9763 (ret "")
9764 (eat 0)
9765 (sum 0))
9766 (while bytes
9767 (let* ((val (string-to-number (pop bytes) 16))
9768 (shift-xor
9769 (if (= 0 eat)
9770 (cond
9771 ((>= val 252) (cons 6 252))
9772 ((>= val 248) (cons 5 248))
9773 ((>= val 240) (cons 4 240))
9774 ((>= val 224) (cons 3 224))
9775 ((>= val 192) (cons 2 192))
9776 (t (cons 0 0)))
9777 (cons 6 128))))
9778 (if (>= val 192) (setq eat (car shift-xor)))
9779 (setq val (logxor val (cdr shift-xor)))
9780 (setq sum (+ (lsh sum (car shift-xor)) val))
9781 (if (> eat 0) (setq eat (- eat 1)))
9782 (cond
9783 ((= 0 eat) ;multi byte
9784 (setq ret (concat ret (org-char-to-string sum)))
9785 (setq sum 0))
9786 ((not bytes) ; single byte(s)
9787 (setq ret (org-link-unescape-single-byte-sequence hex))))
9788 )) ;; end (while bytes
9789 ret )))
9791 (defun org-link-unescape-single-byte-sequence (hex)
9792 "Unhexify hex-encoded single byte character sequences."
9793 (mapconcat (lambda (byte)
9794 (char-to-string (string-to-number byte 16)))
9795 (cdr (split-string hex "%")) ""))
9797 (defun org-xor (a b)
9798 "Exclusive or."
9799 (if a (not b) b))
9801 (defun org-fixup-message-id-for-http (s)
9802 "Replace special characters in a message id, so it can be used in an http query."
9803 (when (string-match "%" s)
9804 (setq s (mapconcat (lambda (c)
9805 (if (eq c ?%)
9806 "%25"
9807 (char-to-string c)))
9808 s "")))
9809 (while (string-match "<" s)
9810 (setq s (replace-match "%3C" t t s)))
9811 (while (string-match ">" s)
9812 (setq s (replace-match "%3E" t t s)))
9813 (while (string-match "@" s)
9814 (setq s (replace-match "%40" t t s)))
9817 (defun org-link-prettify (link)
9818 "Return a human-readable representation of LINK.
9819 The car of LINK must be a raw link the cdr of LINK must be either
9820 a link description or nil."
9821 (let ((desc (or (cadr link) "<no description>")))
9822 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9823 "<" (car link) ">")))
9825 ;;;###autoload
9826 (defun org-insert-link-global ()
9827 "Insert a link like Org-mode does.
9828 This command can be called in any mode to insert a link in Org-mode syntax."
9829 (interactive)
9830 (org-load-modules-maybe)
9831 (org-run-like-in-org-mode 'org-insert-link))
9833 (defun org-insert-all-links (&optional keep)
9834 "Insert all links in `org-stored-links'."
9835 (interactive "P")
9836 (let ((links (copy-sequence org-stored-links)) l)
9837 (while (setq l (if keep (pop links) (pop org-stored-links)))
9838 (insert "- ")
9839 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9840 (insert "\n"))))
9842 (defun org-link-fontify-links-to-this-file ()
9843 "Fontify links to the current file in `org-stored-links'."
9844 (let ((f (buffer-file-name)) a b)
9845 (setq a (mapcar (lambda(l)
9846 (let ((ll (car l)))
9847 (when (and (string-match "^file:\\(.+\\)::" ll)
9848 (equal f (expand-file-name (match-string 1 ll))))
9849 ll)))
9850 org-stored-links))
9851 (when (featurep 'org-id)
9852 (setq b (mapcar (lambda(l)
9853 (let ((ll (car l)))
9854 (when (and (string-match "^id:\\(.+\\)$" ll)
9855 (equal f (expand-file-name
9856 (or (org-id-find-id-file
9857 (match-string 1 ll)) ""))))
9858 ll)))
9859 org-stored-links)))
9860 (mapcar (lambda(l)
9861 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9862 (delq nil (append a b)))))
9864 (defvar org-link-links-in-this-file nil)
9865 (defun org-insert-link (&optional complete-file link-location default-description)
9866 "Insert a link. At the prompt, enter the link.
9868 Completion can be used to insert any of the link protocol prefixes like
9869 http or ftp in use.
9871 The history can be used to select a link previously stored with
9872 `org-store-link'. When the empty string is entered (i.e. if you just
9873 press RET at the prompt), the link defaults to the most recently
9874 stored link. As SPC triggers completion in the minibuffer, you need to
9875 use M-SPC or C-q SPC to force the insertion of a space character.
9877 You will also be prompted for a description, and if one is given, it will
9878 be displayed in the buffer instead of the link.
9880 If there is already a link at point, this command will allow you to edit link
9881 and description parts.
9883 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9884 be selected using completion. The path to the file will be relative to the
9885 current directory if the file is in the current directory or a subdirectory.
9886 Otherwise, the link will be the absolute path as completed in the minibuffer
9887 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9888 option `org-link-file-path-type'.
9890 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9891 the current directory or below.
9893 With three \\[universal-argument] prefixes, negate the meaning of
9894 `org-keep-stored-link-after-insertion'.
9896 If `org-make-link-description-function' is non-nil, this function will be
9897 called with the link target, and the result will be the default
9898 link description.
9900 If the LINK-LOCATION parameter is non-nil, this value will be
9901 used as the link location instead of reading one interactively.
9903 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9904 be used as the default description."
9905 (interactive "P")
9906 (let* ((wcf (current-window-configuration))
9907 (origbuf (current-buffer))
9908 (region (if (org-region-active-p)
9909 (buffer-substring (region-beginning) (region-end))))
9910 (remove (and region (list (region-beginning) (region-end))))
9911 (desc region)
9912 tmphist ; byte-compile incorrectly complains about this
9913 (link link-location)
9914 (abbrevs org-link-abbrev-alist-local)
9915 entry file all-prefixes auto-desc)
9916 (cond
9917 (link-location) ; specified by arg, just use it.
9918 ((org-in-regexp org-bracket-link-regexp 1)
9919 ;; We do have a link at point, and we are going to edit it.
9920 (setq remove (list (match-beginning 0) (match-end 0)))
9921 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9922 (setq link (read-string "Link: "
9923 (org-link-unescape
9924 (org-match-string-no-properties 1)))))
9925 ((or (org-in-regexp org-angle-link-re)
9926 (org-in-regexp org-plain-link-re))
9927 ;; Convert to bracket link
9928 (setq remove (list (match-beginning 0) (match-end 0))
9929 link (read-string "Link: "
9930 (org-remove-angle-brackets (match-string 0)))))
9931 ((member complete-file '((4) (16)))
9932 ;; Completing read for file names.
9933 (setq link (org-file-complete-link complete-file)))
9935 ;; Read link, with completion for stored links.
9936 (org-link-fontify-links-to-this-file)
9937 (org-switch-to-buffer-other-window "*Org Links*")
9938 (with-current-buffer "*Org Links*"
9939 (erase-buffer)
9940 (insert "Insert a link.
9941 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9942 (when org-stored-links
9943 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9944 (insert (mapconcat 'org-link-prettify
9945 (reverse org-stored-links) "\n")))
9946 (goto-char (point-min)))
9947 (let ((cw (selected-window)))
9948 (select-window (get-buffer-window "*Org Links*" 'visible))
9949 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9950 (unless (pos-visible-in-window-p (point-max))
9951 (org-fit-window-to-buffer))
9952 (and (window-live-p cw) (select-window cw)))
9953 ;; Fake a link history, containing the stored links.
9954 (setq tmphist (append (mapcar 'car org-stored-links)
9955 org-insert-link-history))
9956 (setq all-prefixes (append (mapcar 'car abbrevs)
9957 (mapcar 'car org-link-abbrev-alist)
9958 org-link-types))
9959 (unwind-protect
9960 (progn
9961 (setq link
9962 (org-completing-read
9963 "Link: "
9964 (append
9965 (mapcar (lambda (x) (concat x ":"))
9966 all-prefixes)
9967 (mapcar 'car org-stored-links))
9968 nil nil nil
9969 'tmphist
9970 (caar org-stored-links)))
9971 (if (not (string-match "\\S-" link))
9972 (user-error "No link selected"))
9973 (mapc (lambda(l)
9974 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9975 org-stored-links)
9976 (if (or (member link all-prefixes)
9977 (and (equal ":" (substring link -1))
9978 (member (substring link 0 -1) all-prefixes)
9979 (setq link (substring link 0 -1))))
9980 (setq link (with-current-buffer origbuf
9981 (org-link-try-special-completion link)))))
9982 (set-window-configuration wcf)
9983 (kill-buffer "*Org Links*"))
9984 (setq entry (assoc link org-stored-links))
9985 (or entry (push link org-insert-link-history))
9986 (setq desc (or desc (nth 1 entry)))))
9988 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9989 (not org-keep-stored-link-after-insertion))
9990 (setq org-stored-links (delq (assoc link org-stored-links)
9991 org-stored-links)))
9993 (if (string-match org-plain-link-re link)
9994 ;; URL-like link, normalize the use of angular brackets.
9995 (setq link (org-remove-angle-brackets link)))
9997 ;; Check if we are linking to the current file with a search
9998 ;; option If yes, simplify the link by using only the search
9999 ;; option.
10000 (when (and buffer-file-name
10001 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10002 (let* ((path (match-string 1 link))
10003 (case-fold-search nil)
10004 (search (match-string 2 link)))
10005 (save-match-data
10006 (if (equal (file-truename buffer-file-name) (file-truename path))
10007 ;; We are linking to this same file, with a search option
10008 (setq link search)))))
10010 ;; Check if we can/should use a relative path. If yes, simplify the link
10011 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10012 (let* ((type (match-string 1 link))
10013 (path (match-string 2 link))
10014 (origpath path)
10015 (case-fold-search nil))
10016 (cond
10017 ((or (eq org-link-file-path-type 'absolute)
10018 (equal complete-file '(16)))
10019 (setq path (abbreviate-file-name (expand-file-name path))))
10020 ((eq org-link-file-path-type 'noabbrev)
10021 (setq path (expand-file-name path)))
10022 ((eq org-link-file-path-type 'relative)
10023 (setq path (file-relative-name path)))
10025 (save-match-data
10026 (if (string-match (concat "^" (regexp-quote
10027 (expand-file-name
10028 (file-name-as-directory
10029 default-directory))))
10030 (expand-file-name path))
10031 ;; We are linking a file with relative path name.
10032 (setq path (substring (expand-file-name path)
10033 (match-end 0)))
10034 (setq path (abbreviate-file-name (expand-file-name path)))))))
10035 (setq link (concat type path))
10036 (if (equal desc origpath)
10037 (setq desc path))))
10039 (if org-make-link-description-function
10040 (setq desc
10041 (or (condition-case nil
10042 (funcall org-make-link-description-function link desc)
10043 (error (progn (message "Can't get link description from `%s'"
10044 (symbol-name org-make-link-description-function))
10045 (sit-for 2) nil)))
10046 (read-string "Description: " default-description)))
10047 (if default-description (setq desc default-description)
10048 (setq desc (or (and auto-desc desc)
10049 (read-string "Description: " desc)))))
10051 (unless (string-match "\\S-" desc) (setq desc nil))
10052 (if remove (apply 'delete-region remove))
10053 (insert (org-make-link-string link desc))))
10055 (defun org-link-try-special-completion (type)
10056 "If there is completion support for link type TYPE, offer it."
10057 (let ((fun (intern (concat "org-" type "-complete-link"))))
10058 (if (functionp fun)
10059 (funcall fun)
10060 (read-string "Link (no completion support): " (concat type ":")))))
10062 (defun org-file-complete-link (&optional arg)
10063 "Create a file link using completion."
10064 (let (file link)
10065 (setq file (org-iread-file-name "File: "))
10066 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10067 (pwd1 (file-name-as-directory (abbreviate-file-name
10068 (expand-file-name ".")))))
10069 (cond
10070 ((equal arg '(16))
10071 (setq link (concat
10072 "file:"
10073 (abbreviate-file-name (expand-file-name file)))))
10074 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10075 (setq link (concat "file:" (match-string 1 file))))
10076 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10077 (expand-file-name file))
10078 (setq link (concat
10079 "file:" (match-string 1 (expand-file-name file)))))
10080 (t (setq link (concat "file:" file)))))
10081 link))
10083 (defun org-iread-file-name (&rest args)
10084 "Read-file-name using `ido-mode' speedup if available.
10085 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10086 See `read-file-name' for a description of parameters."
10087 (org-without-partial-completion
10088 (if (and org-completion-use-ido
10089 (fboundp 'ido-read-file-name)
10090 (boundp 'ido-mode) ido-mode
10091 (listp (second args)))
10092 (let ((ido-enter-matching-directory nil))
10093 (apply 'ido-read-file-name args))
10094 (apply 'read-file-name args))))
10096 (defun org-completing-read (&rest args)
10097 "Completing-read with SPACE being a normal character."
10098 (let ((enable-recursive-minibuffers t)
10099 (minibuffer-local-completion-map
10100 (copy-keymap minibuffer-local-completion-map)))
10101 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10102 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10103 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10104 (apply 'org-icompleting-read args)))
10106 (defun org-completing-read-no-i (&rest args)
10107 (let (org-completion-use-ido org-completion-use-iswitchb)
10108 (apply 'org-completing-read args)))
10110 (defun org-iswitchb-completing-read (prompt choices &rest args)
10111 "Use iswitch as a completing-read replacement to choose from choices.
10112 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10113 from."
10114 (let* ((iswitchb-use-virtual-buffers nil)
10115 (iswitchb-make-buflist-hook
10116 (lambda ()
10117 (setq iswitchb-temp-buflist choices))))
10118 (iswitchb-read-buffer prompt)))
10120 (defun org-icompleting-read (&rest args)
10121 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10122 (org-without-partial-completion
10123 (if (and org-completion-use-ido
10124 (fboundp 'ido-completing-read)
10125 (boundp 'ido-mode) ido-mode
10126 (listp (second args)))
10127 (let ((ido-enter-matching-directory nil))
10128 (apply 'ido-completing-read (concat (car args))
10129 (if (consp (car (nth 1 args)))
10130 (mapcar 'car (nth 1 args))
10131 (nth 1 args))
10132 (cddr args)))
10133 (if (and org-completion-use-iswitchb
10134 (boundp 'iswitchb-mode) iswitchb-mode
10135 (listp (second args)))
10136 (apply 'org-iswitchb-completing-read (concat (car args))
10137 (if (consp (car (nth 1 args)))
10138 (mapcar 'car (nth 1 args))
10139 (nth 1 args))
10140 (cddr args))
10141 (apply 'completing-read args)))))
10143 (defun org-extract-attributes (s)
10144 "Extract the attributes cookie from a string and set as text property."
10145 (let (a attr (start 0) key value)
10146 (save-match-data
10147 (when (string-match "{{\\([^}]+\\)}}$" s)
10148 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10149 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10150 (setq key (match-string 1 a) value (match-string 2 a)
10151 start (match-end 0)
10152 attr (plist-put attr (intern key) value))))
10153 (org-add-props s nil 'org-attr attr))
10156 ;;; Opening/following a link
10158 (defvar org-link-search-failed nil)
10160 (defvar org-open-link-functions nil
10161 "Hook for functions finding a plain text link.
10162 These functions must take a single argument, the link content.
10163 They will be called for links that look like [[link text][description]]
10164 when LINK TEXT does not have a protocol like \"http:\" and does not look
10165 like a filename (e.g. \"./blue.png\").
10167 These functions will be called *before* Org attempts to resolve the
10168 link by doing text searches in the current buffer - so if you want a
10169 link \"[[target]]\" to still find \"<<target>>\", your function should
10170 handle this as a special case.
10172 When the function does handle the link, it must return a non-nil value.
10173 If it decides that it is not responsible for this link, it must return
10174 nil to indicate that that Org-mode can continue with other options
10175 like exact and fuzzy text search.")
10177 (defun org-next-link (&optional search-backward)
10178 "Move forward to the next link.
10179 If the link is in hidden text, expose it."
10180 (interactive "P")
10181 (when (and org-link-search-failed (eq this-command last-command))
10182 (goto-char (point-min))
10183 (message "Link search wrapped back to beginning of buffer"))
10184 (setq org-link-search-failed nil)
10185 (let* ((pos (point))
10186 (ct (org-context))
10187 (a (assoc :link ct))
10188 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10189 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10190 ((looking-at org-any-link-re)
10191 ;; Don't stay stuck at link without an org-link face
10192 (forward-char (if search-backward -1 1))))
10193 (if (funcall srch-fun org-any-link-re nil t)
10194 (progn
10195 (goto-char (match-beginning 0))
10196 (if (outline-invisible-p) (org-show-context)))
10197 (goto-char pos)
10198 (setq org-link-search-failed t)
10199 (message "No further link found"))))
10201 (defun org-previous-link ()
10202 "Move backward to the previous link.
10203 If the link is in hidden text, expose it."
10204 (interactive)
10205 (funcall 'org-next-link t))
10207 (defun org-translate-link (s)
10208 "Translate a link string if a translation function has been defined."
10209 (if (and org-link-translation-function
10210 (fboundp org-link-translation-function)
10211 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10212 (progn
10213 (setq s (funcall org-link-translation-function
10214 (match-string 1 s) (match-string 2 s)))
10215 (concat (car s) ":" (cdr s)))
10218 (defun org-translate-link-from-planner (type path)
10219 "Translate a link from Emacs Planner syntax so that Org can follow it.
10220 This is still an experimental function, your mileage may vary."
10221 (cond
10222 ((member type '("http" "https" "news" "ftp"))
10223 ;; standard Internet links are the same.
10224 nil)
10225 ((and (equal type "irc") (string-match "^//" path))
10226 ;; Planner has two / at the beginning of an irc link, we have 1.
10227 ;; We should have zero, actually....
10228 (setq path (substring path 1)))
10229 ((and (equal type "lisp") (string-match "^/" path))
10230 ;; Planner has a slash, we do not.
10231 (setq type "elisp" path (substring path 1)))
10232 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10233 ;; A typical message link. Planner has the id after the final slash,
10234 ;; we separate it with a hash mark
10235 (setq path (concat (match-string 1 path) "#"
10236 (org-remove-angle-brackets (match-string 2 path))))))
10237 (cons type path))
10239 (defun org-find-file-at-mouse (ev)
10240 "Open file link or URL at mouse."
10241 (interactive "e")
10242 (mouse-set-point ev)
10243 (org-open-at-point 'in-emacs))
10245 (defun org-open-at-mouse (ev)
10246 "Open file link or URL at mouse.
10247 See the docstring of `org-open-file' for details."
10248 (interactive "e")
10249 (mouse-set-point ev)
10250 (if (eq major-mode 'org-agenda-mode)
10251 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10252 (org-open-at-point))
10254 (defvar org-window-config-before-follow-link nil
10255 "The window configuration before following a link.
10256 This is saved in case the need arises to restore it.")
10258 (defvar org-open-link-marker (make-marker)
10259 "Marker pointing to the location where `org-open-at-point; was called.")
10261 ;;;###autoload
10262 (defun org-open-at-point-global ()
10263 "Follow a link like Org-mode does.
10264 This command can be called in any mode to follow a link that has
10265 Org-mode syntax."
10266 (interactive)
10267 (org-run-like-in-org-mode 'org-open-at-point))
10269 ;;;###autoload
10270 (defun org-open-link-from-string (s &optional arg reference-buffer)
10271 "Open a link in the string S, as if it was in Org-mode."
10272 (interactive "sLink: \nP")
10273 (let ((reference-buffer (or reference-buffer (current-buffer))))
10274 (with-temp-buffer
10275 (let ((org-inhibit-startup (not reference-buffer)))
10276 (org-mode)
10277 (insert s)
10278 (goto-char (point-min))
10279 (when reference-buffer
10280 (setq org-link-abbrev-alist-local
10281 (with-current-buffer reference-buffer
10282 org-link-abbrev-alist-local)))
10283 (org-open-at-point arg reference-buffer)))))
10285 (defvar org-open-at-point-functions nil
10286 "Hook that is run when following a link at point.
10288 Functions in this hook must return t if they identify and follow
10289 a link at point. If they don't find anything interesting at point,
10290 they must return nil.")
10292 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10293 (defun org-open-at-point (&optional arg reference-buffer)
10294 "Open link at or after point.
10295 If there is no link at point, this function will search forward up to
10296 the end of the current line.
10297 Normally, files will be opened by an appropriate application. If the
10298 optional prefix argument ARG is non-nil, Emacs will visit the file.
10299 With a double prefix argument, try to open outside of Emacs, in the
10300 application the system uses for this file type."
10301 (interactive "P")
10302 ;; if in a code block, then open the block's results
10303 (unless (call-interactively #'org-babel-open-src-block-result)
10304 (org-load-modules-maybe)
10305 (move-marker org-open-link-marker (point))
10306 (setq org-window-config-before-follow-link (current-window-configuration))
10307 (org-remove-occur-highlights nil nil t)
10308 (cond
10309 ((and (org-at-heading-p)
10310 (not (org-at-timestamp-p t))
10311 (not (org-in-regexp
10312 (concat org-plain-link-re "\\|"
10313 org-bracket-link-regexp "\\|"
10314 org-angle-link-re "\\|"
10315 "[ \t]:[^ \t\n]+:[ \t]*$")))
10316 (not (get-text-property (point) 'org-linked-text)))
10317 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10318 (lk0 (car lkall))
10319 (lk (if (stringp lk0) (list lk0) lk0))
10320 (lkend (cdr lkall)))
10321 (mapcar (lambda(l)
10322 (search-forward l nil lkend)
10323 (goto-char (match-beginning 0))
10324 (org-open-at-point))
10325 lk))
10326 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10327 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10328 ((and (org-at-timestamp-p t)
10329 (not (org-in-regexp org-bracket-link-regexp)))
10330 (org-follow-timestamp-link))
10331 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10332 (not (org-in-regexp org-any-link-re)))
10333 (org-footnote-action))
10335 (let (type path link line search (pos (point)))
10336 (catch 'match
10337 (save-excursion
10338 (skip-chars-forward "^]\n\r")
10339 (when (org-in-regexp org-bracket-link-regexp 1)
10340 (setq link (org-extract-attributes
10341 (org-link-unescape (org-match-string-no-properties 1))))
10342 (while (string-match " *\n *" link)
10343 (setq link (replace-match " " t t link)))
10344 (setq link (org-link-expand-abbrev link))
10345 (cond
10346 ((or (file-name-absolute-p link)
10347 (string-match "^\\.\\.?/" link))
10348 (setq type "file" path link))
10349 ((string-match org-link-re-with-space3 link)
10350 (setq type (match-string 1 link) path (match-string 2 link)))
10351 ((string-match "^help:+\\(.+\\)" link)
10352 (setq type "help" path (match-string 1 link)))
10353 (t (setq type "thisfile" path link)))
10354 (throw 'match t)))
10356 (when (get-text-property (point) 'org-linked-text)
10357 (setq type "thisfile"
10358 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10359 (1+ (point)) (point))
10360 path (buffer-substring
10361 (or (previous-single-property-change pos 'org-linked-text)
10362 (point-min))
10363 (or (next-single-property-change pos 'org-linked-text)
10364 (point-max)))
10365 ;; Ensure we will search for a <<<radio>>> link, not
10366 ;; a simple reference like <<ref>>
10367 path (concat "<" path))
10368 (throw 'match t))
10370 (save-excursion
10371 (when (or (org-in-regexp org-angle-link-re)
10372 (let ((match (org-in-regexp org-plain-link-re)))
10373 ;; Check a plain link is not within a bracket link
10374 (and match
10375 (save-excursion
10376 (progn
10377 (goto-char (car match))
10378 (not (org-in-regexp org-bracket-link-regexp))))))
10379 (let ((line_ending (save-excursion (end-of-line) (point))))
10380 ;; We are in a line before a plain or bracket link
10381 (or (re-search-forward org-plain-link-re line_ending t)
10382 (re-search-forward org-bracket-link-regexp line_ending t))))
10383 (setq type (match-string 1)
10384 path (org-link-unescape (match-string 2)))
10385 (throw 'match t)))
10386 (save-excursion
10387 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10388 (setq type "tags"
10389 path (match-string 1))
10390 (while (string-match ":" path)
10391 (setq path (replace-match "+" t t path)))
10392 (throw 'match t)))
10393 (when (org-in-regexp "<\\([^><\n]+\\)>")
10394 (setq type "tree-match"
10395 path (match-string 1))
10396 (throw 'match t)))
10397 (unless path
10398 (user-error "No link found"))
10400 ;; switch back to reference buffer
10401 ;; needed when if called in a temporary buffer through
10402 ;; org-open-link-from-string
10403 (with-current-buffer (or reference-buffer (current-buffer))
10405 ;; Remove any trailing spaces in path
10406 (if (string-match " +\\'" path)
10407 (setq path (replace-match "" t t path)))
10408 (if (and org-link-translation-function
10409 (fboundp org-link-translation-function))
10410 ;; Check if we need to translate the link
10411 (let ((tmp (funcall org-link-translation-function type path)))
10412 (setq type (car tmp) path (cdr tmp))))
10414 (cond
10416 ((assoc type org-link-protocols)
10417 (funcall (nth 1 (assoc type org-link-protocols)) path))
10419 ((equal type "help")
10420 (let ((f-or-v (intern path)))
10421 (cond ((fboundp f-or-v)
10422 (describe-function f-or-v))
10423 ((boundp f-or-v)
10424 (describe-variable f-or-v))
10425 (t (error "Not a known function or variable")))))
10427 ((equal type "mailto")
10428 (let ((cmd (car org-link-mailto-program))
10429 (args (cdr org-link-mailto-program)) args1
10430 (address path) (subject "") a)
10431 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10432 (setq address (match-string 1 path)
10433 subject (org-link-escape (match-string 2 path))))
10434 (while args
10435 (cond
10436 ((not (stringp (car args))) (push (pop args) args1))
10437 (t (setq a (pop args))
10438 (if (string-match "%a" a)
10439 (setq a (replace-match address t t a)))
10440 (if (string-match "%s" a)
10441 (setq a (replace-match subject t t a)))
10442 (push a args1))))
10443 (apply cmd (nreverse args1))))
10445 ((member type '("http" "https" "ftp" "news"))
10446 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10447 (org-link-escape
10448 path org-link-escape-chars-browser)
10449 path))))
10451 ((string= type "doi")
10452 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10453 (org-link-escape
10454 path org-link-escape-chars-browser)
10455 path))))
10457 ((member type '("message"))
10458 (browse-url (concat type ":" path)))
10460 ((string= type "tags")
10461 (org-tags-view arg path))
10463 ((string= type "tree-match")
10464 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10466 ((string= type "file")
10467 (if (string-match "::\\([0-9]+\\)\\'" path)
10468 (setq line (string-to-number (match-string 1 path))
10469 path (substring path 0 (match-beginning 0)))
10470 (if (string-match "::\\(.+\\)\\'" path)
10471 (setq search (match-string 1 path)
10472 path (substring path 0 (match-beginning 0)))))
10473 (if (string-match "[*?{]" (file-name-nondirectory path))
10474 (dired path)
10475 (org-open-file path arg line search)))
10477 ((string= type "shell")
10478 (let ((buf (generate-new-buffer "*Org Shell Output"))
10479 (cmd path))
10480 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10481 (string-match org-confirm-shell-link-not-regexp cmd))
10482 (not org-confirm-shell-link-function)
10483 (funcall org-confirm-shell-link-function
10484 (format "Execute \"%s\" in shell? "
10485 (org-add-props cmd nil
10486 'face 'org-warning))))
10487 (progn
10488 (message "Executing %s" cmd)
10489 (shell-command cmd buf)
10490 (if (featurep 'midnight)
10491 (setq clean-buffer-list-kill-buffer-names
10492 (cons buf clean-buffer-list-kill-buffer-names))))
10493 (error "Abort"))))
10495 ((string= type "elisp")
10496 (let ((cmd path))
10497 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10498 (string-match org-confirm-elisp-link-not-regexp cmd))
10499 (not org-confirm-elisp-link-function)
10500 (funcall org-confirm-elisp-link-function
10501 (format "Execute \"%s\" as elisp? "
10502 (org-add-props cmd nil
10503 'face 'org-warning))))
10504 (message "%s => %s" cmd
10505 (if (equal (string-to-char cmd) ?\()
10506 (eval (read cmd))
10507 (call-interactively (read cmd))))
10508 (error "Abort"))))
10510 ((and (string= type "thisfile")
10511 (run-hook-with-args-until-success
10512 'org-open-link-functions path)))
10514 ((string= type "thisfile")
10515 (if arg
10516 (switch-to-buffer-other-window
10517 (org-get-buffer-for-internal-link (current-buffer)))
10518 (org-mark-ring-push))
10519 (let ((cmd `(org-link-search
10520 ,path
10521 ,(cond ((equal arg '(4)) ''occur)
10522 ((equal arg '(16)) ''org-occur))
10523 ,pos)))
10524 (condition-case nil (let ((org-link-search-inhibit-query t))
10525 (eval cmd))
10526 (error (progn (widen) (eval cmd))))))
10528 (t (browse-url-at-point)))))))
10529 (move-marker org-open-link-marker nil)
10530 (run-hook-with-args 'org-follow-link-hook)))
10532 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10533 "Offer links in the current entry and return the selected link.
10534 If there is only one link, return it.
10535 If NTH is an integer, return the NTH link found.
10536 If ZERO is a string, check also this string for a link, and if
10537 there is one, return it."
10538 (with-current-buffer buffer
10539 (save-excursion
10540 (save-restriction
10541 (widen)
10542 (goto-char marker)
10543 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10544 "\\(" org-angle-link-re "\\)\\|"
10545 "\\(" org-plain-link-re "\\)"))
10546 (cnt ?0)
10547 (in-emacs (if (integerp nth) nil nth))
10548 have-zero end links link c)
10549 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10550 (push (match-string 0 zero) links)
10551 (setq cnt (1- cnt) have-zero t))
10552 (save-excursion
10553 (org-back-to-heading t)
10554 (setq end (save-excursion (outline-next-heading) (point)))
10555 (while (re-search-forward re end t)
10556 (push (match-string 0) links))
10557 (setq links (org-uniquify (reverse links))))
10558 (cond
10559 ((null links)
10560 (message "No links"))
10561 ((equal (length links) 1)
10562 (setq link (car links)))
10563 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10564 (setq link (nth (if have-zero nth (1- nth)) links)))
10565 (t ; we have to select a link
10566 (save-excursion
10567 (save-window-excursion
10568 (delete-other-windows)
10569 (with-output-to-temp-buffer "*Select Link*"
10570 (mapc (lambda (l)
10571 (if (not (string-match org-bracket-link-regexp l))
10572 (princ (format "[%c] %s\n" (incf cnt)
10573 (org-remove-angle-brackets l)))
10574 (if (match-end 3)
10575 (princ (format "[%c] %s (%s)\n" (incf cnt)
10576 (match-string 3 l) (match-string 1 l)))
10577 (princ (format "[%c] %s\n" (incf cnt)
10578 (match-string 1 l))))))
10579 links))
10580 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10581 (message "Select link to open, RET to open all:")
10582 (setq c (read-char-exclusive))
10583 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10584 (when (equal c ?q) (error "Abort"))
10585 (if (equal c ?\C-m)
10586 (setq link links)
10587 (setq nth (- c ?0))
10588 (if have-zero (setq nth (1+ nth)))
10589 (unless (and (integerp nth) (>= (length links) nth))
10590 (user-error "Invalid link selection"))
10591 (setq link (nth (1- nth) links)))))
10592 (cons link end))))))
10594 ;; Add special file links that specify the way of opening
10596 (org-add-link-type "file+sys" 'org-open-file-with-system)
10597 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10598 (defun org-open-file-with-system (path)
10599 "Open file at PATH using the system way of opening it."
10600 (org-open-file path 'system))
10601 (defun org-open-file-with-emacs (path)
10602 "Open file at PATH in Emacs."
10603 (org-open-file path 'emacs))
10606 ;;; File search
10608 (defvar org-create-file-search-functions nil
10609 "List of functions to construct the right search string for a file link.
10610 These functions are called in turn with point at the location to
10611 which the link should point.
10613 A function in the hook should first test if it would like to
10614 handle this file type, for example by checking the `major-mode'
10615 or the file extension. If it decides not to handle this file, it
10616 should just return nil to give other functions a chance. If it
10617 does handle the file, it must return the search string to be used
10618 when following the link. The search string will be part of the
10619 file link, given after a double colon, and `org-open-at-point'
10620 will automatically search for it. If special measures must be
10621 taken to make the search successful, another function should be
10622 added to the companion hook `org-execute-file-search-functions',
10623 which see.
10625 A function in this hook may also use `setq' to set the variable
10626 `description' to provide a suggestion for the descriptive text to
10627 be used for this link when it gets inserted into an Org-mode
10628 buffer with \\[org-insert-link].")
10630 (defvar org-execute-file-search-functions nil
10631 "List of functions to execute a file search triggered by a link.
10633 Functions added to this hook must accept a single argument, the
10634 search string that was part of the file link, the part after the
10635 double colon. The function must first check if it would like to
10636 handle this search, for example by checking the `major-mode' or
10637 the file extension. If it decides not to handle this search, it
10638 should just return nil to give other functions a chance. If it
10639 does handle the search, it must return a non-nil value to keep
10640 other functions from trying.
10642 Each function can access the current prefix argument through the
10643 variable `current-prefix-arg'. Note that a single prefix is used
10644 to force opening a link in Emacs, so it may be good to only use a
10645 numeric or double prefix to guide the search function.
10647 In case this is needed, a function in this hook can also restore
10648 the window configuration before `org-open-at-point' was called using:
10650 (set-window-configuration org-window-config-before-follow-link)")
10652 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10653 (defun org-link-search (s &optional type avoid-pos stealth)
10654 "Search for a link search option.
10655 If S is surrounded by forward slashes, it is interpreted as a
10656 regular expression. In org-mode files, this will create an `org-occur'
10657 sparse tree. In ordinary files, `occur' will be used to list matches.
10658 If the current buffer is in `dired-mode', grep will be used to search
10659 in all files. If AVOID-POS is given, ignore matches near that position.
10661 When optional argument STEALTH is non-nil, do not modify
10662 visibility around point, thus ignoring
10663 `org-show-hierarchy-above', `org-show-following-heading' and
10664 `org-show-siblings' variables."
10665 (let ((case-fold-search t)
10666 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10667 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10668 (append '(("") (" ") ("\t") ("\n"))
10669 org-emphasis-alist)
10670 "\\|") "\\)"))
10671 (pos (point))
10672 (pre nil) (post nil)
10673 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10674 (cond
10675 ;; First check if there are any special search functions
10676 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10677 ;; Now try the builtin stuff
10678 ((and (equal (string-to-char s0) ?#)
10679 (> (length s0) 1)
10680 (save-excursion
10681 (goto-char (point-min))
10682 (and
10683 (re-search-forward
10684 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10685 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10686 (setq type 'dedicated
10687 pos (match-beginning 0))))
10688 ;; There is an exact target for this
10689 (goto-char pos)
10690 (org-back-to-heading t)))
10691 ((save-excursion
10692 (goto-char (point-min))
10693 (and
10694 (re-search-forward
10695 (concat "<<" (regexp-quote s0) ">>") nil t)
10696 (setq type 'dedicated
10697 pos (match-beginning 0))))
10698 ;; There is an exact target for this
10699 (goto-char pos))
10700 ((save-excursion
10701 (goto-char (point-min))
10702 (and
10703 (re-search-forward
10704 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10705 (setq type 'dedicated pos (match-beginning 0))))
10706 ;; Found an element with a matching #+name affiliated keyword.
10707 (goto-char pos))
10708 ((and (string-match "^(\\(.*\\))$" s0)
10709 (save-excursion
10710 (goto-char (point-min))
10711 (and
10712 (re-search-forward
10713 (concat "[^[]" (regexp-quote
10714 (format org-coderef-label-format
10715 (match-string 1 s0))))
10716 nil t)
10717 (setq type 'dedicated
10718 pos (1+ (match-beginning 0))))))
10719 ;; There is a coderef target for this
10720 (goto-char pos))
10721 ((string-match "^/\\(.*\\)/$" s)
10722 ;; A regular expression
10723 (cond
10724 ((derived-mode-p 'org-mode)
10725 (org-occur (match-string 1 s)))
10726 (t (org-do-occur (match-string 1 s)))))
10727 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10728 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10729 (goto-char (point-min))
10730 (cond
10731 ((let (case-fold-search)
10732 (re-search-forward (format org-complex-heading-regexp-format
10733 (regexp-quote s))
10734 nil t))
10735 ;; OK, found a match
10736 (setq type 'dedicated)
10737 (goto-char (match-beginning 0)))
10738 ((and (not org-link-search-inhibit-query)
10739 (eq org-link-search-must-match-exact-headline 'query-to-create)
10740 (y-or-n-p "No match - create this as a new heading? "))
10741 (goto-char (point-max))
10742 (or (bolp) (newline))
10743 (insert "* " s "\n")
10744 (beginning-of-line 0))
10746 (goto-char pos)
10747 (error "No match"))))
10749 ;; A normal search string
10750 (when (equal (string-to-char s) ?*)
10751 ;; Anchor on headlines, post may include tags.
10752 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10753 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10754 s (substring s 1)))
10755 (remove-text-properties
10756 0 (length s)
10757 '(face nil mouse-face nil keymap nil fontified nil) s)
10758 ;; Make a series of regular expressions to find a match
10759 (setq words (org-split-string s "[ \n\r\t]+")
10761 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10762 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10763 "\\)" markers)
10764 re2a_ (concat "\\(" (mapconcat 'downcase words
10765 "[ \t\r\n]+") "\\)[ \t\r\n]")
10766 re2a (concat "[ \t\r\n]" re2a_)
10767 re4_ (concat "\\(" (mapconcat 'downcase words
10768 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10769 re4 (concat "[^a-zA-Z_]" re4_)
10771 re1 (concat pre re2 post)
10772 re3 (concat pre (if pre re4_ re4) post)
10773 re5 (concat pre ".*" re4)
10774 re2 (concat pre re2)
10775 re2a (concat pre (if pre re2a_ re2a))
10776 re4 (concat pre (if pre re4_ re4))
10777 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10778 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10779 re5 "\\)"))
10780 (cond
10781 ((eq type 'org-occur) (org-occur reall))
10782 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10783 (t (goto-char (point-min))
10784 (setq type 'fuzzy)
10785 (if (or (and (org-search-not-self 1 re0 nil t)
10786 (setq type 'dedicated))
10787 (org-search-not-self 1 re1 nil t)
10788 (org-search-not-self 1 re2 nil t)
10789 (org-search-not-self 1 re2a nil t)
10790 (org-search-not-self 1 re3 nil t)
10791 (org-search-not-self 1 re4 nil t)
10792 (org-search-not-self 1 re5 nil t))
10793 (goto-char (match-beginning 1))
10794 (goto-char pos)
10795 (error "No match"))))))
10796 (and (derived-mode-p 'org-mode)
10797 (not stealth)
10798 (org-show-context 'link-search))
10799 type))
10801 (defun org-search-not-self (group &rest args)
10802 "Execute `re-search-forward', but only accept matches that do not
10803 enclose the position of `org-open-link-marker'."
10804 (let ((m org-open-link-marker))
10805 (catch 'exit
10806 (while (apply 're-search-forward args)
10807 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10808 (goto-char (match-end group))
10809 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10810 (> (match-beginning 0) (marker-position m))
10811 (< (match-end 0) (marker-position m)))
10812 (save-match-data
10813 (or (not (org-in-regexp
10814 org-bracket-link-analytic-regexp 1))
10815 (not (match-end 4)) ; no description
10816 (and (<= (match-beginning 4) (point))
10817 (>= (match-end 4) (point))))))
10818 (throw 'exit (point))))))))
10820 (defun org-get-buffer-for-internal-link (buffer)
10821 "Return a buffer to be used for displaying the link target of internal links."
10822 (cond
10823 ((not org-display-internal-link-with-indirect-buffer)
10824 buffer)
10825 ((string-match "(Clone)$" (buffer-name buffer))
10826 (message "Buffer is already a clone, not making another one")
10827 ;; we also do not modify visibility in this case
10828 buffer)
10829 (t ; make a new indirect buffer for displaying the link
10830 (let* ((bn (buffer-name buffer))
10831 (ibn (concat bn "(Clone)"))
10832 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10833 (with-current-buffer ib (org-overview))
10834 ib))))
10836 (defun org-do-occur (regexp &optional cleanup)
10837 "Call the Emacs command `occur'.
10838 If CLEANUP is non-nil, remove the printout of the regular expression
10839 in the *Occur* buffer. This is useful if the regex is long and not useful
10840 to read."
10841 (occur regexp)
10842 (when cleanup
10843 (let ((cwin (selected-window)) win beg end)
10844 (when (setq win (get-buffer-window "*Occur*"))
10845 (select-window win))
10846 (goto-char (point-min))
10847 (when (re-search-forward "match[a-z]+" nil t)
10848 (setq beg (match-end 0))
10849 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10850 (setq end (1- (match-beginning 0)))))
10851 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10852 (goto-char (point-min))
10853 (select-window cwin))))
10855 ;;; The mark ring for links jumps
10857 (defvar org-mark-ring nil
10858 "Mark ring for positions before jumps in Org-mode.")
10859 (defvar org-mark-ring-last-goto nil
10860 "Last position in the mark ring used to go back.")
10861 ;; Fill and close the ring
10862 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10863 (loop for i from 1 to org-mark-ring-length do
10864 (push (make-marker) org-mark-ring))
10865 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10866 org-mark-ring)
10868 (defun org-mark-ring-push (&optional pos buffer)
10869 "Put the current position or POS into the mark ring and rotate it."
10870 (interactive)
10871 (setq pos (or pos (point)))
10872 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10873 (move-marker (car org-mark-ring)
10874 (or pos (point))
10875 (or buffer (current-buffer)))
10876 (message "%s"
10877 (substitute-command-keys
10878 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10880 (defun org-mark-ring-goto (&optional n)
10881 "Jump to the previous position in the mark ring.
10882 With prefix arg N, jump back that many stored positions. When
10883 called several times in succession, walk through the entire ring.
10884 Org-mode commands jumping to a different position in the current file,
10885 or to another Org-mode file, automatically push the old position
10886 onto the ring."
10887 (interactive "p")
10888 (let (p m)
10889 (if (eq last-command this-command)
10890 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10891 (setq p org-mark-ring))
10892 (setq org-mark-ring-last-goto p)
10893 (setq m (car p))
10894 (org-pop-to-buffer-same-window (marker-buffer m))
10895 (goto-char m)
10896 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10898 (defun org-remove-angle-brackets (s)
10899 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10900 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10902 (defun org-add-angle-brackets (s)
10903 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10904 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10906 (defun org-remove-double-quotes (s)
10907 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10908 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10911 ;;; Following specific links
10913 (defun org-follow-timestamp-link ()
10914 "Open an agenda view for the time-stamp date/range at point."
10915 (cond
10916 ((org-at-date-range-p t)
10917 (let ((org-agenda-start-on-weekday)
10918 (t1 (match-string 1))
10919 (t2 (match-string 2)) tt1 tt2)
10920 (setq tt1 (time-to-days (org-time-string-to-time t1))
10921 tt2 (time-to-days (org-time-string-to-time t2)))
10922 (let ((org-agenda-buffer-tmp-name
10923 (format "*Org Agenda(a:%s)"
10924 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10925 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10926 ((org-at-timestamp-p t)
10927 (let ((org-agenda-buffer-tmp-name
10928 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10929 (org-agenda-list nil (time-to-days (org-time-string-to-time
10930 (substring (match-string 1) 0 10)))
10931 1)))
10932 (t (error "This should not happen"))))
10935 ;;; Following file links
10936 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10937 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10938 (declare-function mailcap-mime-info
10939 "mailcap" (string &optional request no-decode))
10940 (defvar org-wait nil)
10941 (defun org-open-file (path &optional in-emacs line search)
10942 "Open the file at PATH.
10943 First, this expands any special file name abbreviations. Then the
10944 configuration variable `org-file-apps' is checked if it contains an
10945 entry for this file type, and if yes, the corresponding command is launched.
10947 If no application is found, Emacs simply visits the file.
10949 With optional prefix argument IN-EMACS, Emacs will visit the file.
10950 With a double \\[universal-argument] \\[universal-argument] \
10951 prefix arg, Org tries to avoid opening in Emacs
10952 and to use an external application to visit the file.
10954 Optional LINE specifies a line to go to, optional SEARCH a string
10955 to search for. If LINE or SEARCH is given, the file will be
10956 opened in Emacs, unless an entry from org-file-apps that makes
10957 use of groups in a regexp matches.
10959 If you want to change the way frames are used when following a
10960 link, please customize `org-link-frame-setup'.
10962 If the file does not exist, an error is thrown."
10963 (let* ((file (if (equal path "")
10964 buffer-file-name
10965 (substitute-in-file-name (expand-file-name path))))
10966 (file-apps (append org-file-apps (org-default-apps)))
10967 (apps (org-remove-if
10968 'org-file-apps-entry-match-against-dlink-p file-apps))
10969 (apps-dlink (org-remove-if-not
10970 'org-file-apps-entry-match-against-dlink-p file-apps))
10971 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10972 (dirp (if remp nil (file-directory-p file)))
10973 (file (if (and dirp org-open-directory-means-index-dot-org)
10974 (concat (file-name-as-directory file) "index.org")
10975 file))
10976 (a-m-a-p (assq 'auto-mode apps))
10977 (dfile (downcase file))
10978 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10979 (link (cond ((and (eq line nil)
10980 (eq search nil))
10981 file)
10982 (line
10983 (concat file "::" (number-to-string line)))
10984 (search
10985 (concat file "::" search))))
10986 (dlink (downcase link))
10987 (old-buffer (current-buffer))
10988 (old-pos (point))
10989 (old-mode major-mode)
10990 ext cmd link-match-data)
10991 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10992 (setq ext (match-string 1 dfile))
10993 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10994 (setq ext (match-string 1 dfile))))
10995 (cond
10996 ((member in-emacs '((16) system))
10997 (setq cmd (cdr (assoc 'system apps))))
10998 (in-emacs (setq cmd 'emacs))
11000 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11001 (and dirp (cdr (assoc 'directory apps)))
11002 ; first, try matching against apps-dlink
11003 ; if we get a match here, store the match data for later
11004 (let ((match (assoc-default dlink apps-dlink
11005 'string-match)))
11006 (if match
11007 (progn (setq link-match-data (match-data))
11008 match)
11009 (progn (setq in-emacs (or in-emacs line search))
11010 nil))) ; if we have no match in apps-dlink,
11011 ; always open the file in emacs if line or search
11012 ; is given (for backwards compatibility)
11013 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11014 'string-match)
11015 (cdr (assoc ext apps))
11016 (cdr (assoc t apps))))))
11017 (when (eq cmd 'system)
11018 (setq cmd (cdr (assoc 'system apps))))
11019 (when (eq cmd 'default)
11020 (setq cmd (cdr (assoc t apps))))
11021 (when (eq cmd 'mailcap)
11022 (require 'mailcap)
11023 (mailcap-parse-mailcaps)
11024 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11025 (command (mailcap-mime-info mime-type)))
11026 (if (stringp command)
11027 (setq cmd command)
11028 (setq cmd 'emacs))))
11029 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11030 (not (file-exists-p file))
11031 (not org-open-non-existing-files))
11032 (user-error "No such file: %s" file))
11033 (cond
11034 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11035 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11036 (while (string-match "['\"]%s['\"]" cmd)
11037 (setq cmd (replace-match "%s" t t cmd)))
11038 (while (string-match "%s" cmd)
11039 (setq cmd (replace-match
11040 (save-match-data
11041 (shell-quote-argument
11042 (convert-standard-filename file)))
11043 t t cmd)))
11045 ;; Replace "%1", "%2" etc. in command with group matches from regex
11046 (save-match-data
11047 (let ((match-index 1)
11048 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11049 (set-match-data link-match-data)
11050 (while (<= match-index number-of-groups)
11051 (let ((regex (concat "%" (number-to-string match-index)))
11052 (replace-with (match-string match-index dlink)))
11053 (while (string-match regex cmd)
11054 (setq cmd (replace-match replace-with t t cmd))))
11055 (setq match-index (+ match-index 1)))))
11057 (save-window-excursion
11058 (message "Running %s...done" cmd)
11059 (start-process-shell-command cmd nil cmd)
11060 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11061 ((or (stringp cmd)
11062 (eq cmd 'emacs))
11063 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11064 (widen)
11065 (if line (org-goto-line line)
11066 (if search (org-link-search search))))
11067 ((consp cmd)
11068 (let ((file (convert-standard-filename file)))
11069 (save-match-data
11070 (set-match-data link-match-data)
11071 (eval cmd))))
11072 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11073 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11074 (or (not (equal old-buffer (current-buffer)))
11075 (not (equal old-pos (point))))
11076 (org-mark-ring-push old-pos old-buffer))))
11078 (defun org-file-apps-entry-match-against-dlink-p (entry)
11079 "This function returns non-nil if `entry' uses a regular
11080 expression which should be matched against the whole link by
11081 org-open-file.
11083 It assumes that is the case when the entry uses a regular
11084 expression which has at least one grouping construct and the
11085 action is either a lisp form or a command string containing
11086 '%1', i.e. using at least one subexpression match as a
11087 parameter."
11088 (let ((selector (car entry))
11089 (action (cdr entry)))
11090 (if (stringp selector)
11091 (and (> (regexp-opt-depth selector) 0)
11092 (or (and (stringp action)
11093 (string-match "%[0-9]" action))
11094 (consp action)))
11095 nil)))
11097 (defun org-default-apps ()
11098 "Return the default applications for this operating system."
11099 (cond
11100 ((eq system-type 'darwin)
11101 org-file-apps-defaults-macosx)
11102 ((eq system-type 'windows-nt)
11103 org-file-apps-defaults-windowsnt)
11104 (t org-file-apps-defaults-gnu)))
11106 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11107 "Convert extensions to regular expressions in the cars of LIST.
11108 Also, weed out any non-string entries, because the return value is used
11109 only for regexp matching.
11110 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11111 point to the symbol `emacs', indicating that the file should
11112 be opened in Emacs."
11113 (append
11114 (delq nil
11115 (mapcar (lambda (x)
11116 (if (not (stringp (car x)))
11118 (if (string-match "\\W" (car x))
11120 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11121 list))
11122 (if add-auto-mode
11123 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11125 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11126 (defun org-file-remote-p (file)
11127 "Test whether FILE specifies a location on a remote system.
11128 Return non-nil if the location is indeed remote.
11130 For example, the filename \"/user@host:/foo\" specifies a location
11131 on the system \"/user@host:\"."
11132 (cond ((fboundp 'file-remote-p)
11133 (file-remote-p file))
11134 ((fboundp 'tramp-handle-file-remote-p)
11135 (tramp-handle-file-remote-p file))
11136 ((and (boundp 'ange-ftp-name-format)
11137 (string-match (car ange-ftp-name-format) file))
11138 t)))
11141 ;;;; Refiling
11143 (defun org-get-org-file ()
11144 "Read a filename, with default directory `org-directory'."
11145 (let ((default (or org-default-notes-file remember-data-file)))
11146 (read-file-name (format "File name [%s]: " default)
11147 (file-name-as-directory org-directory)
11148 default)))
11150 (defun org-notes-order-reversed-p ()
11151 "Check if the current file should receive notes in reversed order."
11152 (cond
11153 ((not org-reverse-note-order) nil)
11154 ((eq t org-reverse-note-order) t)
11155 ((not (listp org-reverse-note-order)) nil)
11156 (t (catch 'exit
11157 (let ((all org-reverse-note-order)
11158 entry)
11159 (while (setq entry (pop all))
11160 (if (string-match (car entry) buffer-file-name)
11161 (throw 'exit (cdr entry))))
11162 nil)))))
11164 (defvar org-refile-target-table nil
11165 "The list of refile targets, created by `org-refile'.")
11167 (defvar org-agenda-new-buffers nil
11168 "Buffers created to visit agenda files.")
11170 (defvar org-refile-cache nil
11171 "Cache for refile targets.")
11173 (defvar org-refile-markers nil
11174 "All the markers used for caching refile locations.")
11176 (defun org-refile-marker (pos)
11177 "Get a new refile marker, but only if caching is in use."
11178 (if (not org-refile-use-cache)
11180 (let ((m (make-marker)))
11181 (move-marker m pos)
11182 (push m org-refile-markers)
11183 m)))
11185 (defun org-refile-cache-clear ()
11186 "Clear the refile cache and disable all the markers."
11187 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11188 (setq org-refile-markers nil)
11189 (setq org-refile-cache nil)
11190 (message "Refile cache has been cleared"))
11192 (defun org-refile-cache-check-set (set)
11193 "Check if all the markers in the cache still have live buffers."
11194 (let (marker)
11195 (catch 'exit
11196 (while (and set (setq marker (nth 3 (pop set))))
11197 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11198 (when (and marker (null (marker-buffer marker)))
11199 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11200 (sit-for 3)
11201 (throw 'exit nil)))
11202 t)))
11204 (defun org-refile-cache-put (set &rest identifiers)
11205 "Push the refile targets SET into the cache, under IDENTIFIERS."
11206 (let* ((key (sha1 (prin1-to-string identifiers)))
11207 (entry (assoc key org-refile-cache)))
11208 (if entry
11209 (setcdr entry set)
11210 (push (cons key set) org-refile-cache))))
11212 (defun org-refile-cache-get (&rest identifiers)
11213 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11214 (cond
11215 ((not org-refile-cache) nil)
11216 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11218 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11219 org-refile-cache))))
11220 (and set (org-refile-cache-check-set set) set)))))
11222 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11223 "Produce a table with refile targets."
11224 (let ((case-fold-search nil)
11225 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11226 (entries (or org-refile-targets '((nil . (:level . 1)))))
11227 targets tgs txt re files f desc descre fast-path-p level pos0)
11228 (message "Getting targets...")
11229 (with-current-buffer (or default-buffer (current-buffer))
11230 (while (setq entry (pop entries))
11231 (setq files (car entry) desc (cdr entry))
11232 (setq fast-path-p nil)
11233 (cond
11234 ((null files) (setq files (list (current-buffer))))
11235 ((eq files 'org-agenda-files)
11236 (setq files (org-agenda-files 'unrestricted)))
11237 ((and (symbolp files) (fboundp files))
11238 (setq files (funcall files)))
11239 ((and (symbolp files) (boundp files))
11240 (setq files (symbol-value files))))
11241 (if (stringp files) (setq files (list files)))
11242 (cond
11243 ((eq (car desc) :tag)
11244 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11245 ((eq (car desc) :todo)
11246 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11247 ((eq (car desc) :regexp)
11248 (setq descre (cdr desc)))
11249 ((eq (car desc) :level)
11250 (setq descre (concat "^\\*\\{" (number-to-string
11251 (if org-odd-levels-only
11252 (1- (* 2 (cdr desc)))
11253 (cdr desc)))
11254 "\\}[ \t]")))
11255 ((eq (car desc) :maxlevel)
11256 (setq fast-path-p t)
11257 (setq descre (concat "^\\*\\{1," (number-to-string
11258 (if org-odd-levels-only
11259 (1- (* 2 (cdr desc)))
11260 (cdr desc)))
11261 "\\}[ \t]")))
11262 (t (error "Bad refiling target description %s" desc)))
11263 (while (setq f (pop files))
11264 (with-current-buffer
11265 (if (bufferp f) f (org-get-agenda-file-buffer f))
11267 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11268 (progn
11269 (if (bufferp f) (setq f (buffer-file-name
11270 (buffer-base-buffer f))))
11271 (setq f (and f (expand-file-name f)))
11272 (if (eq org-refile-use-outline-path 'file)
11273 (push (list (file-name-nondirectory f) f nil nil) tgs))
11274 (save-excursion
11275 (save-restriction
11276 (widen)
11277 (goto-char (point-min))
11278 (while (re-search-forward descre nil t)
11279 (goto-char (setq pos0 (point-at-bol)))
11280 (catch 'next
11281 (when org-refile-target-verify-function
11282 (save-match-data
11283 (or (funcall org-refile-target-verify-function)
11284 (throw 'next t))))
11285 (when (and (looking-at org-complex-heading-regexp)
11286 (not (member (match-string 4) excluded-entries))
11287 (match-string 4))
11288 (setq level (org-reduced-level
11289 (- (match-end 1) (match-beginning 1)))
11290 txt (org-link-display-format (match-string 4))
11291 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11292 re (format org-complex-heading-regexp-format
11293 (regexp-quote (match-string 4))))
11294 (when org-refile-use-outline-path
11295 (setq txt (mapconcat
11296 'org-protect-slash
11297 (append
11298 (if (eq org-refile-use-outline-path
11299 'file)
11300 (list (file-name-nondirectory
11301 (buffer-file-name
11302 (buffer-base-buffer))))
11303 (if (eq org-refile-use-outline-path
11304 'full-file-path)
11305 (list (buffer-file-name
11306 (buffer-base-buffer)))))
11307 (org-get-outline-path fast-path-p
11308 level txt)
11309 (list txt))
11310 "/")))
11311 (push (list txt f re (org-refile-marker (point)))
11312 tgs)))
11313 (when (= (point) pos0)
11314 ;; verification function has not moved point
11315 (goto-char (point-at-eol))))))))
11316 (when org-refile-use-cache
11317 (org-refile-cache-put tgs (buffer-file-name) descre))
11318 (setq targets (append tgs targets))))))
11319 (message "Getting targets...done")
11320 (nreverse targets)))
11322 (defun org-protect-slash (s)
11323 (while (string-match "/" s)
11324 (setq s (replace-match "\\" t t s)))
11327 (defvar org-olpa (make-vector 20 nil))
11329 (defun org-get-outline-path (&optional fastp level heading)
11330 "Return the outline path to the current entry, as a list.
11332 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11333 routine which makes outline path derivations for an entire file,
11334 avoiding backtracing. Refile target collection makes use of that."
11335 (if fastp
11336 (progn
11337 (if (> level 19)
11338 (error "Outline path failure, more than 19 levels"))
11339 (loop for i from level upto 19 do
11340 (aset org-olpa i nil))
11341 (prog1
11342 (delq nil (append org-olpa nil))
11343 (aset org-olpa level heading)))
11344 (let (rtn case-fold-search)
11345 (save-excursion
11346 (save-restriction
11347 (widen)
11348 (while (org-up-heading-safe)
11349 (when (looking-at org-complex-heading-regexp)
11350 (push (org-trim
11351 (replace-regexp-in-string
11352 ;; Remove statistical/checkboxes cookies
11353 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11354 (org-match-string-no-properties 4)))
11355 rtn)))
11356 rtn)))))
11358 (defun org-format-outline-path (path &optional width prefix separator)
11359 "Format the outline path PATH for display.
11360 WIDTH is the maximum number of characters that is available.
11361 PREFIX is a prefix to be included in the returned string,
11362 such as the file name.
11363 SEPARATOR is inserted between the different parts of the path,
11364 the default is \"/\"."
11365 (setq width (or width 79))
11366 (if prefix (setq width (- width (length prefix))))
11367 (if (not path)
11368 (or prefix "")
11369 (let* ((nsteps (length path))
11370 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11371 (maxwidth (if (<= total-width width)
11372 10000 ;; everything fits
11373 ;; we need to shorten the level headings
11374 (/ (- width nsteps) nsteps)))
11375 (org-odd-levels-only nil)
11376 (n 0)
11377 (total (1+ (length prefix))))
11378 (setq maxwidth (max maxwidth 10))
11379 (concat prefix
11380 (if prefix (or separator "/"))
11381 (mapconcat
11382 (lambda (h)
11383 (setq n (1+ n))
11384 (if (and (= n nsteps) (< maxwidth 10000))
11385 (setq maxwidth (- total-width total)))
11386 (if (< (length h) maxwidth)
11387 (progn (setq total (+ total (length h) 1)) h)
11388 (setq h (substring h 0 (- maxwidth 2))
11389 total (+ total maxwidth 1))
11390 (if (string-match "[ \t]+\\'" h)
11391 (setq h (substring h 0 (match-beginning 0))))
11392 (setq h (concat h "..")))
11393 (org-add-props h nil 'face
11394 (nth (% (1- n) org-n-level-faces)
11395 org-level-faces))
11397 path (or separator "/"))))))
11399 (defun org-display-outline-path (&optional file current separator just-return-string)
11400 "Display the current outline path in the echo area.
11402 If FILE is non-nil, prepend the output with the file name.
11403 If CURRENT is non-nil, append the current heading to the output.
11404 SEPARATOR is passed through to `org-format-outline-path'. It separates
11405 the different parts of the path and defaults to \"/\".
11406 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11407 (interactive "P")
11408 (let* (case-fold-search
11409 message-log-max ; Don't populate the *Messages* buffer
11410 (bfn (buffer-file-name (buffer-base-buffer)))
11411 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11412 res)
11413 (if current (setq path (append path
11414 (save-excursion
11415 (org-back-to-heading t)
11416 (if (looking-at org-complex-heading-regexp)
11417 (list (match-string 4)))))))
11418 (setq res
11419 (org-format-outline-path
11420 path
11421 (1- (frame-width))
11422 (and file bfn (concat (file-name-nondirectory bfn) separator))
11423 separator))
11424 (if just-return-string
11425 (org-no-properties res)
11426 (message "%s" res))))
11428 (defvar org-refile-history nil
11429 "History for refiling operations.")
11431 (defvar org-after-refile-insert-hook nil
11432 "Hook run after `org-refile' has inserted its stuff at the new location.
11433 Note that this is still *before* the stuff will be removed from
11434 the *old* location.")
11436 (defvar org-capture-last-stored-marker)
11437 (defvar org-refile-keep nil
11438 "Non-nil means `org-refile' will copy instead of refile.")
11440 (defun org-copy ()
11441 "Like `org-refile', but copy."
11442 (interactive)
11443 (let ((org-refile-keep t))
11444 (funcall 'org-refile nil nil nil "Copy")))
11446 (defun org-refile (&optional goto default-buffer rfloc msg)
11447 "Move the entry or entries at point to another heading.
11448 The list of target headings is compiled using the information in
11449 `org-refile-targets', which see.
11451 At the target location, the entry is filed as a subitem of the target
11452 heading. Depending on `org-reverse-note-order', the new subitem will
11453 either be the first or the last subitem.
11455 If there is an active region, all entries in that region will be moved.
11456 However, the region must fulfill the requirement that the first heading
11457 is the first one sets the top-level of the moved text - at most siblings
11458 below it are allowed.
11460 With prefix arg GOTO, the command will only visit the target location
11461 and not actually move anything.
11463 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11464 go to the location where the last refiling operation has put the subtree.
11465 With a prefix argument of `2', refile to the running clock.
11467 RFLOC can be a refile location obtained in a different way.
11469 MSG is a string to replace \"Refile\" in the default prompt with
11470 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11472 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11474 If you are using target caching (see `org-refile-use-cache'),
11475 you have to clear the target cache in order to find new targets.
11476 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11477 prefix argument (`C-u C-u C-u C-c C-w')."
11479 (interactive "P")
11480 (if (member goto '(0 (64)))
11481 (org-refile-cache-clear)
11482 (let* ((actionmsg (or msg "Refile"))
11483 (cbuf (current-buffer))
11484 (regionp (org-region-active-p))
11485 (region-start (and regionp (region-beginning)))
11486 (region-end (and regionp (region-end)))
11487 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11488 pos it nbuf file re level reversed)
11489 (setq last-command nil)
11490 (when regionp
11491 (goto-char region-start)
11492 (or (bolp) (goto-char (point-at-bol)))
11493 (setq region-start (point))
11494 (unless (or (org-kill-is-subtree-p
11495 (buffer-substring region-start region-end))
11496 (prog1 org-refile-active-region-within-subtree
11497 (let ((s (point-at-eol)))
11498 (org-toggle-heading)
11499 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11500 (user-error "The region is not a (sequence of) subtree(s)")))
11501 (if (equal goto '(16))
11502 (org-refile-goto-last-stored)
11503 (when (or
11504 (and (equal goto 2)
11505 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11506 (prog1
11507 (setq it (list (or org-clock-heading "running clock")
11508 (buffer-file-name
11509 (marker-buffer org-clock-hd-marker))
11511 (marker-position org-clock-hd-marker)))
11512 (setq goto nil)))
11513 (setq it (or rfloc
11514 (let (heading-text)
11515 (save-excursion
11516 (unless goto
11517 (org-back-to-heading t)
11518 (setq heading-text
11519 (nth 4 (org-heading-components))))
11521 (org-refile-get-location
11522 (cond (goto "Goto")
11523 (regionp (concat actionmsg " region to"))
11524 (t (concat actionmsg " subtree \""
11525 heading-text "\" to")))
11526 default-buffer
11527 (and (not (equal '(4) goto))
11528 org-refile-allow-creating-parent-nodes)
11529 goto))))))
11530 (setq file (nth 1 it)
11531 re (nth 2 it)
11532 pos (nth 3 it))
11533 (if (and (not goto)
11535 (equal (buffer-file-name) file)
11536 (if regionp
11537 (and (>= pos region-start)
11538 (<= pos region-end))
11539 (and (>= pos (point))
11540 (< pos (save-excursion
11541 (org-end-of-subtree t t))))))
11542 (error "Cannot refile to position inside the tree or region"))
11544 (setq nbuf (or (find-buffer-visiting file)
11545 (find-file-noselect file)))
11546 (if goto
11547 (progn
11548 (org-pop-to-buffer-same-window nbuf)
11549 (goto-char pos)
11550 (org-show-context 'org-goto))
11551 (if regionp
11552 (progn
11553 (org-kill-new (buffer-substring region-start region-end))
11554 (org-save-markers-in-region region-start region-end))
11555 (org-copy-subtree 1 nil t))
11556 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11557 (find-file-noselect file)))
11558 (setq reversed (org-notes-order-reversed-p))
11559 (save-excursion
11560 (save-restriction
11561 (widen)
11562 (if pos
11563 (progn
11564 (goto-char pos)
11565 (looking-at org-outline-regexp)
11566 (setq level (org-get-valid-level (funcall outline-level) 1))
11567 (goto-char
11568 (if reversed
11569 (or (outline-next-heading) (point-max))
11570 (or (save-excursion (org-get-next-sibling))
11571 (org-end-of-subtree t t)
11572 (point-max)))))
11573 (setq level 1)
11574 (if (not reversed)
11575 (goto-char (point-max))
11576 (goto-char (point-min))
11577 (or (outline-next-heading) (goto-char (point-max)))))
11578 (if (not (bolp)) (newline))
11579 (org-paste-subtree level)
11580 (when org-log-refile
11581 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11582 (unless (eq org-log-refile 'note)
11583 (save-excursion (org-add-log-note))))
11584 (and org-auto-align-tags
11585 (let ((org-loop-over-headlines-in-active-region nil))
11586 (org-set-tags nil t)))
11587 (with-demoted-errors
11588 (bookmark-set "org-refile-last-stored"))
11589 ;; If we are refiling for capture, make sure that the
11590 ;; last-capture pointers point here
11591 (when (org-bound-and-true-p org-refile-for-capture)
11592 (with-demoted-errors
11593 (bookmark-set "org-capture-last-stored-marker"))
11594 (move-marker org-capture-last-stored-marker (point)))
11595 (if (fboundp 'deactivate-mark) (deactivate-mark))
11596 (run-hooks 'org-after-refile-insert-hook))))
11597 (unless org-refile-keep
11598 (if regionp
11599 (delete-region (point) (+ (point) (- region-end region-start)))
11600 (delete-region
11601 (and (org-back-to-heading t) (point))
11602 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11603 (when (featurep 'org-inlinetask)
11604 (org-inlinetask-remove-END-maybe))
11605 (setq org-markers-to-move nil)
11606 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11608 (defun org-refile-goto-last-stored ()
11609 "Go to the location where the last refile was stored."
11610 (interactive)
11611 (bookmark-jump "org-refile-last-stored")
11612 (message "This is the location of the last refile"))
11614 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11615 no-exclude)
11616 "Prompt the user for a refile location, using PROMPT.
11617 PROMPT should not be suffixed with a colon and a space, because
11618 this function appends the default value from
11619 `org-refile-history' automatically, if that is not empty.
11620 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11621 this is used for the GOTO interface."
11622 (let ((org-refile-targets org-refile-targets)
11623 (org-refile-use-outline-path org-refile-use-outline-path)
11624 excluded-entries)
11625 (when (and (derived-mode-p 'org-mode)
11626 (not org-refile-use-cache)
11627 (not no-exclude))
11628 (org-map-tree
11629 (lambda()
11630 (setq excluded-entries
11631 (append excluded-entries (list (org-get-heading t t)))))))
11632 (setq org-refile-target-table
11633 (org-refile-get-targets default-buffer excluded-entries)))
11634 (unless org-refile-target-table
11635 (user-error "No refile targets"))
11636 (let* ((cbuf (current-buffer))
11637 (partial-completion-mode nil)
11638 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11639 (cfunc (if (and org-refile-use-outline-path
11640 org-outline-path-complete-in-steps)
11641 'org-olpath-completing-read
11642 'org-icompleting-read))
11643 (extra (if org-refile-use-outline-path "/" ""))
11644 (cbnex (concat (buffer-name) extra))
11645 (filename (and cfn (expand-file-name cfn)))
11646 (tbl (mapcar
11647 (lambda (x)
11648 (if (and (not (member org-refile-use-outline-path
11649 '(file full-file-path)))
11650 (not (equal filename (nth 1 x))))
11651 (cons (concat (car x) extra " ("
11652 (file-name-nondirectory (nth 1 x)) ")")
11653 (cdr x))
11654 (cons (concat (car x) extra) (cdr x))))
11655 org-refile-target-table))
11656 (completion-ignore-case t)
11657 cdef
11658 (prompt (concat prompt
11659 (or (and (car org-refile-history)
11660 (concat " (default " (car org-refile-history) ")"))
11661 (and (assoc cbnex tbl) (setq cdef cbnex)
11662 (concat " (default " cbnex ")"))) ": "))
11663 pa answ parent-target child parent old-hist)
11664 (setq old-hist org-refile-history)
11665 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11666 nil 'org-refile-history (or cdef (car org-refile-history))))
11667 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11668 (org-refile-check-position pa)
11669 (if pa
11670 (progn
11671 (when (or (not org-refile-history)
11672 (not (eq old-hist org-refile-history))
11673 (not (equal (car pa) (car org-refile-history))))
11674 (setq org-refile-history
11675 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11676 org-refile-history
11677 (cdr org-refile-history))))
11678 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11679 (pop org-refile-history)))
11681 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11682 (progn
11683 (setq parent (match-string 1 answ)
11684 child (match-string 2 answ))
11685 (setq parent-target (or (assoc parent tbl)
11686 (assoc (concat parent "/") tbl)))
11687 (when (and parent-target
11688 (or (eq new-nodes t)
11689 (and (eq new-nodes 'confirm)
11690 (y-or-n-p (format "Create new node \"%s\"? "
11691 child)))))
11692 (org-refile-new-child parent-target child)))
11693 (user-error "Invalid target location")))))
11695 (declare-function org-string-nw-p "org-macs" (s))
11696 (defun org-refile-check-position (refile-pointer)
11697 "Check if the refile pointer matches the headline to which it points."
11698 (let* ((file (nth 1 refile-pointer))
11699 (re (nth 2 refile-pointer))
11700 (pos (nth 3 refile-pointer))
11701 buffer)
11702 (if (and (not (markerp pos)) (not file))
11703 (user-error "Please save the buffer to a file before refiling")
11704 (when (org-string-nw-p re)
11705 (setq buffer (if (markerp pos)
11706 (marker-buffer pos)
11707 (or (find-buffer-visiting file)
11708 (find-file-noselect file))))
11709 (with-current-buffer buffer
11710 (save-excursion
11711 (save-restriction
11712 (widen)
11713 (goto-char pos)
11714 (beginning-of-line 1)
11715 (unless (org-looking-at-p re)
11716 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11718 (defun org-refile-new-child (parent-target child)
11719 "Use refile target PARENT-TARGET to add new CHILD below it."
11720 (unless parent-target
11721 (error "Cannot find parent for new node"))
11722 (let ((file (nth 1 parent-target))
11723 (pos (nth 3 parent-target))
11724 level)
11725 (with-current-buffer (or (find-buffer-visiting file)
11726 (find-file-noselect file))
11727 (save-excursion
11728 (save-restriction
11729 (widen)
11730 (if pos
11731 (goto-char pos)
11732 (goto-char (point-max))
11733 (if (not (bolp)) (newline)))
11734 (when (looking-at org-outline-regexp)
11735 (setq level (funcall outline-level))
11736 (org-end-of-subtree t t))
11737 (org-back-over-empty-lines)
11738 (insert "\n" (make-string
11739 (if pos (org-get-valid-level level 1) 1) ?*)
11740 " " child "\n")
11741 (beginning-of-line 0)
11742 (list (concat (car parent-target) "/" child) file "" (point)))))))
11744 (defun org-olpath-completing-read (prompt collection &rest args)
11745 "Read an outline path like a file name."
11746 (let ((thetable collection)
11747 (org-completion-use-ido nil) ; does not work with ido.
11748 (org-completion-use-iswitchb nil)) ; or iswitchb
11749 (apply
11750 'org-icompleting-read prompt
11751 (lambda (string predicate &optional flag)
11752 (let (rtn r f (l (length string)))
11753 (cond
11754 ((eq flag nil)
11755 ;; try completion
11756 (try-completion string thetable))
11757 ((eq flag t)
11758 ;; all-completions
11759 (setq rtn (all-completions string thetable predicate))
11760 (mapcar
11761 (lambda (x)
11762 (setq r (substring x l))
11763 (if (string-match " ([^)]*)$" x)
11764 (setq f (match-string 0 x))
11765 (setq f ""))
11766 (if (string-match "/" r)
11767 (concat string (substring r 0 (match-end 0)) f)
11769 rtn))
11770 ((eq flag 'lambda)
11771 ;; exact match?
11772 (assoc string thetable)))))
11773 args)))
11775 ;;;; Dynamic blocks
11777 (defun org-find-dblock (name)
11778 "Find the first dynamic block with name NAME in the buffer.
11779 If not found, stay at current position and return nil."
11780 (let ((case-fold-search t) pos)
11781 (save-excursion
11782 (goto-char (point-min))
11783 (setq pos (and (re-search-forward
11784 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11785 (match-beginning 0))))
11786 (if pos (goto-char pos))
11787 pos))
11789 (defconst org-dblock-start-re
11790 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11791 "Matches the start line of a dynamic block, with parameters.")
11793 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11794 "Matches the end of a dynamic block.")
11796 (defun org-create-dblock (plist)
11797 "Create a dynamic block section, with parameters taken from PLIST.
11798 PLIST must contain a :name entry which is used as name of the block."
11799 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11800 (end-of-line 1)
11801 (newline))
11802 (let ((col (current-column))
11803 (name (plist-get plist :name)))
11804 (insert "#+BEGIN: " name)
11805 (while plist
11806 (if (eq (car plist) :name)
11807 (setq plist (cddr plist))
11808 (insert " " (prin1-to-string (pop plist)))))
11809 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11810 (beginning-of-line -2)))
11812 (defun org-prepare-dblock ()
11813 "Prepare dynamic block for refresh.
11814 This empties the block, puts the cursor at the insert position and returns
11815 the property list including an extra property :name with the block name."
11816 (unless (looking-at org-dblock-start-re)
11817 (user-error "Not at a dynamic block"))
11818 (let* ((begdel (1+ (match-end 0)))
11819 (name (org-no-properties (match-string 1)))
11820 (params (append (list :name name)
11821 (read (concat "(" (match-string 3) ")")))))
11822 (save-excursion
11823 (beginning-of-line 1)
11824 (skip-chars-forward " \t")
11825 (setq params (plist-put params :indentation-column (current-column))))
11826 (unless (re-search-forward org-dblock-end-re nil t)
11827 (error "Dynamic block not terminated"))
11828 (setq params
11829 (append params
11830 (list :content (buffer-substring
11831 begdel (match-beginning 0)))))
11832 (delete-region begdel (match-beginning 0))
11833 (goto-char begdel)
11834 (open-line 1)
11835 params))
11837 (defun org-map-dblocks (&optional command)
11838 "Apply COMMAND to all dynamic blocks in the current buffer.
11839 If COMMAND is not given, use `org-update-dblock'."
11840 (let ((cmd (or command 'org-update-dblock)))
11841 (save-excursion
11842 (goto-char (point-min))
11843 (while (re-search-forward org-dblock-start-re nil t)
11844 (goto-char (match-beginning 0))
11845 (save-excursion
11846 (condition-case nil
11847 (funcall cmd)
11848 (error (message "Error during update of dynamic block"))))
11849 (unless (re-search-forward org-dblock-end-re nil t)
11850 (error "Dynamic block not terminated"))))))
11852 (defun org-dblock-update (&optional arg)
11853 "User command for updating dynamic blocks.
11854 Update the dynamic block at point. With prefix ARG, update all dynamic
11855 blocks in the buffer."
11856 (interactive "P")
11857 (if arg
11858 (org-update-all-dblocks)
11859 (or (looking-at org-dblock-start-re)
11860 (org-beginning-of-dblock))
11861 (org-update-dblock)))
11863 (defun org-update-dblock ()
11864 "Update the dynamic block at point.
11865 This means to empty the block, parse for parameters and then call
11866 the correct writing function."
11867 (interactive)
11868 (save-window-excursion
11869 (let* ((pos (point))
11870 (line (org-current-line))
11871 (params (org-prepare-dblock))
11872 (name (plist-get params :name))
11873 (indent (plist-get params :indentation-column))
11874 (cmd (intern (concat "org-dblock-write:" name))))
11875 (message "Updating dynamic block `%s' at line %d..." name line)
11876 (funcall cmd params)
11877 (message "Updating dynamic block `%s' at line %d...done" name line)
11878 (goto-char pos)
11879 (when (and indent (> indent 0))
11880 (setq indent (make-string indent ?\ ))
11881 (save-excursion
11882 (org-beginning-of-dblock)
11883 (forward-line 1)
11884 (while (not (looking-at org-dblock-end-re))
11885 (insert indent)
11886 (beginning-of-line 2))
11887 (when (looking-at org-dblock-end-re)
11888 (and (looking-at "[ \t]+")
11889 (replace-match ""))
11890 (insert indent)))))))
11892 (defun org-beginning-of-dblock ()
11893 "Find the beginning of the dynamic block at point.
11894 Error if there is no such block at point."
11895 (let ((pos (point))
11896 beg)
11897 (end-of-line 1)
11898 (if (and (re-search-backward org-dblock-start-re nil t)
11899 (setq beg (match-beginning 0))
11900 (re-search-forward org-dblock-end-re nil t)
11901 (> (match-end 0) pos))
11902 (goto-char beg)
11903 (goto-char pos)
11904 (error "Not in a dynamic block"))))
11906 (defun org-update-all-dblocks ()
11907 "Update all dynamic blocks in the buffer.
11908 This function can be used in a hook."
11909 (interactive)
11910 (when (derived-mode-p 'org-mode)
11911 (org-map-dblocks 'org-update-dblock)))
11914 ;;;; Completion
11916 (defun org-get-export-keywords ()
11917 "Return a list of all currently understood export keywords.
11918 Export keywords include options, block names, attributes and
11919 keywords relative to each registered export back-end."
11920 (delq nil
11921 (let (keywords)
11922 (mapc
11923 (lambda (back-end)
11924 (let ((props (cdr back-end)))
11925 ;; Back-end name (for keywords, like #+LATEX:)
11926 (push (upcase (symbol-name (car back-end))) keywords)
11927 ;; Back-end options.
11928 (mapc (lambda (option) (push (cadr option) keywords))
11929 (plist-get (cdr back-end) :options-alist))))
11930 (org-bound-and-true-p org-export-registered-backends))
11931 keywords)))
11933 (defconst org-options-keywords
11934 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11935 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11936 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11937 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11938 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11940 (defcustom org-structure-template-alist
11941 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11942 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11943 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11944 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11945 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11946 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11947 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11948 "<literal style=\"latex\">\n?\n</literal>")
11949 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11950 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11951 "<literal style=\"html\">\n?\n</literal>")
11952 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11953 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11954 ("A" "#+ASCII: " "")
11955 ("i" "#+INDEX: ?" "#+INDEX: ?")
11956 ("I" "#+INCLUDE: %file ?"
11957 "<include file=%file markup=\"?\">"))
11958 "Structure completion elements.
11959 This is a list of abbreviation keys and values. The value gets inserted
11960 if you type `<' followed by the key and then press the completion key,
11961 usually `M-TAB'. %file will be replaced by a file name after prompting
11962 for the file using completion. The cursor will be placed at the position
11963 of the `?` in the template.
11964 There are two templates for each key, the first uses the original Org syntax,
11965 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11966 the default when the /org-mtags.el/ module has been loaded. See also the
11967 variable `org-mtags-prefer-muse-templates'."
11968 :group 'org-completion
11969 :type '(repeat
11970 (list
11971 (string :tag "Key")
11972 (string :tag "Template")
11973 (string :tag "Muse Template"))))
11975 (defun org-try-structure-completion ()
11976 "Try to complete a structure template before point.
11977 This looks for strings like \"<e\" on an otherwise empty line and
11978 expands them."
11979 (let ((l (buffer-substring (point-at-bol) (point)))
11981 (when (and (looking-at "[ \t]*$")
11982 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11983 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11984 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11985 (match-beginning 1)) a)
11986 t)))
11988 (defun org-complete-expand-structure-template (start cell)
11989 "Expand a structure template."
11990 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11991 (rpl (nth (if musep 2 1) cell))
11992 (ind ""))
11993 (delete-region start (point))
11994 (when (string-match "\\`#\\+" rpl)
11995 (cond
11996 ((bolp))
11997 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11998 (setq ind (buffer-substring (point-at-bol) (point))))
11999 (t (newline))))
12000 (setq start (point))
12001 (if (string-match "%file" rpl)
12002 (setq rpl (replace-match
12003 (concat
12004 "\""
12005 (save-match-data
12006 (abbreviate-file-name (read-file-name "Include file: ")))
12007 "\"")
12008 t t rpl)))
12009 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12010 (concat "\n" ind)))
12011 (insert rpl)
12012 (if (re-search-backward "\\?" start t) (delete-char 1))))
12014 ;;;; TODO, DEADLINE, Comments
12016 (defun org-toggle-comment ()
12017 "Change the COMMENT state of an entry."
12018 (interactive)
12019 (save-excursion
12020 (org-back-to-heading)
12021 (let (case-fold-search)
12022 (cond
12023 ((looking-at (format org-heading-keyword-regexp-format
12024 org-comment-string))
12025 (goto-char (match-end 1))
12026 (looking-at (concat " +" org-comment-string))
12027 (replace-match "" t t)
12028 (when (eolp) (insert " ")))
12029 ((looking-at org-outline-regexp)
12030 (goto-char (match-end 0))
12031 (insert org-comment-string " "))))))
12033 (defvar org-last-todo-state-is-todo nil
12034 "This is non-nil when the last TODO state change led to a TODO state.
12035 If the last change removed the TODO tag or switched to DONE, then
12036 this is nil.")
12038 (defvar org-setting-tags nil) ; dynamically skipped
12040 (defvar org-todo-setup-filter-hook nil
12041 "Hook for functions that pre-filter todo specs.
12042 Each function takes a todo spec and returns either nil or the spec
12043 transformed into canonical form." )
12045 (defvar org-todo-get-default-hook nil
12046 "Hook for functions that get a default item for todo.
12047 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12048 nil or a string to be used for the todo mark." )
12050 (defvar org-agenda-headline-snapshot-before-repeat)
12052 (defun org-current-effective-time ()
12053 "Return current time adjusted for `org-extend-today-until' variable."
12054 (let* ((ct (org-current-time))
12055 (dct (decode-time ct))
12056 (ct1
12057 (cond
12058 (org-use-last-clock-out-time-as-effective-time
12059 (or (org-clock-get-last-clock-out-time) ct))
12060 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12061 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12062 (t ct))))
12063 ct1))
12065 (defun org-todo-yesterday (&optional arg)
12066 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12067 (interactive "P")
12068 (if (eq major-mode 'org-agenda-mode)
12069 (apply 'org-agenda-todo-yesterday arg)
12070 (let* ((hour (third (decode-time
12071 (org-current-time))))
12072 (org-extend-today-until (1+ hour)))
12073 (org-todo arg))))
12075 (defvar org-block-entry-blocking ""
12076 "First entry preventing the TODO state change.")
12078 (defun org-todo (&optional arg)
12079 "Change the TODO state of an item.
12080 The state of an item is given by a keyword at the start of the heading,
12081 like
12082 *** TODO Write paper
12083 *** DONE Call mom
12085 The different keywords are specified in the variable `org-todo-keywords'.
12086 By default the available states are \"TODO\" and \"DONE\".
12087 So for this example: when the item starts with TODO, it is changed to DONE.
12088 When it starts with DONE, the DONE is removed. And when neither TODO nor
12089 DONE are present, add TODO at the beginning of the heading.
12091 With \\[universal-argument] prefix arg, use completion to determine the new \
12092 state.
12093 With numeric prefix arg, switch to that state.
12094 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12095 keywords (nextset).
12096 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12097 With a numeric prefix arg of 0, inhibit note taking for the change.
12099 For calling through lisp, arg is also interpreted in the following way:
12100 'none -> empty state
12101 \"\"(empty string) -> switch to empty state
12102 'done -> switch to DONE
12103 'nextset -> switch to the next set of keywords
12104 'previousset -> switch to the previous set of keywords
12105 \"WAITING\" -> switch to the specified keyword, but only if it
12106 really is a member of `org-todo-keywords'."
12107 (interactive "P")
12108 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12109 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12110 'region-start-level 'region))
12111 org-loop-over-headlines-in-active-region)
12112 (org-map-entries
12113 `(org-todo ,arg)
12114 org-loop-over-headlines-in-active-region
12115 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12116 (if (equal arg '(16)) (setq arg 'nextset))
12117 (let ((org-blocker-hook org-blocker-hook)
12118 commentp
12119 case-fold-search)
12120 (when (equal arg '(64))
12121 (setq arg nil org-blocker-hook nil))
12122 (when (and org-blocker-hook
12123 (or org-inhibit-blocking
12124 (org-entry-get nil "NOBLOCKING")))
12125 (setq org-blocker-hook nil))
12126 (save-excursion
12127 (catch 'exit
12128 (org-back-to-heading t)
12129 (when (looking-at (concat "^\\*+ " org-comment-string))
12130 (org-toggle-comment)
12131 (setq commentp t))
12132 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12133 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12134 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12135 (let* ((match-data (match-data))
12136 (startpos (point-at-bol))
12137 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12138 (org-log-done org-log-done)
12139 (org-log-repeat org-log-repeat)
12140 (org-todo-log-states org-todo-log-states)
12141 (org-inhibit-logging
12142 (if (equal arg 0)
12143 (progn (setq arg nil) 'note) org-inhibit-logging))
12144 (this (match-string 1))
12145 (hl-pos (match-beginning 0))
12146 (head (org-get-todo-sequence-head this))
12147 (ass (assoc head org-todo-kwd-alist))
12148 (interpret (nth 1 ass))
12149 (done-word (nth 3 ass))
12150 (final-done-word (nth 4 ass))
12151 (org-last-state (or this ""))
12152 (completion-ignore-case t)
12153 (member (member this org-todo-keywords-1))
12154 (tail (cdr member))
12155 (org-state (cond
12156 ((and org-todo-key-trigger
12157 (or (and (equal arg '(4))
12158 (eq org-use-fast-todo-selection 'prefix))
12159 (and (not arg) org-use-fast-todo-selection
12160 (not (eq org-use-fast-todo-selection
12161 'prefix)))))
12162 ;; Use fast selection
12163 (org-fast-todo-selection))
12164 ((and (equal arg '(4))
12165 (or (not org-use-fast-todo-selection)
12166 (not org-todo-key-trigger)))
12167 ;; Read a state with completion
12168 (org-icompleting-read
12169 "State: " (mapcar 'list org-todo-keywords-1)
12170 nil t))
12171 ((eq arg 'right)
12172 (if this
12173 (if tail (car tail) nil)
12174 (car org-todo-keywords-1)))
12175 ((eq arg 'left)
12176 (if (equal member org-todo-keywords-1)
12178 (if this
12179 (nth (- (length org-todo-keywords-1)
12180 (length tail) 2)
12181 org-todo-keywords-1)
12182 (org-last org-todo-keywords-1))))
12183 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12184 (setq arg nil))) ; hack to fall back to cycling
12185 (arg
12186 ;; user or caller requests a specific state
12187 (cond
12188 ((equal arg "") nil)
12189 ((eq arg 'none) nil)
12190 ((eq arg 'done) (or done-word (car org-done-keywords)))
12191 ((eq arg 'nextset)
12192 (or (car (cdr (member head org-todo-heads)))
12193 (car org-todo-heads)))
12194 ((eq arg 'previousset)
12195 (let ((org-todo-heads (reverse org-todo-heads)))
12196 (or (car (cdr (member head org-todo-heads)))
12197 (car org-todo-heads))))
12198 ((car (member arg org-todo-keywords-1)))
12199 ((stringp arg)
12200 (user-error "State `%s' not valid in this file" arg))
12201 ((nth (1- (prefix-numeric-value arg))
12202 org-todo-keywords-1))))
12203 ((null member) (or head (car org-todo-keywords-1)))
12204 ((equal this final-done-word) nil) ;; -> make empty
12205 ((null tail) nil) ;; -> first entry
12206 ((memq interpret '(type priority))
12207 (if (eq this-command last-command)
12208 (car tail)
12209 (if (> (length tail) 0)
12210 (or done-word (car org-done-keywords))
12211 nil)))
12213 (car tail))))
12214 (org-state (or
12215 (run-hook-with-args-until-success
12216 'org-todo-get-default-hook org-state org-last-state)
12217 org-state))
12218 (next (if org-state (concat " " org-state " ") " "))
12219 (change-plist (list :type 'todo-state-change :from this :to org-state
12220 :position startpos))
12221 dolog now-done-p)
12222 (when org-blocker-hook
12223 (setq org-last-todo-state-is-todo
12224 (not (member this org-done-keywords)))
12225 (unless (save-excursion
12226 (save-match-data
12227 (org-with-wide-buffer
12228 (run-hook-with-args-until-failure
12229 'org-blocker-hook change-plist))))
12230 (if (org-called-interactively-p 'interactive)
12231 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12232 this org-state org-block-entry-blocking)
12233 ;; fail silently
12234 (message "TODO state change from %s to %s blocked (by \"%s\")"
12235 this org-state org-block-entry-blocking)
12236 (throw 'exit nil))))
12237 (store-match-data match-data)
12238 (replace-match next t t)
12239 (unless (pos-visible-in-window-p hl-pos)
12240 (message "TODO state changed to %s" (org-trim next)))
12241 (unless head
12242 (setq head (org-get-todo-sequence-head org-state)
12243 ass (assoc head org-todo-kwd-alist)
12244 interpret (nth 1 ass)
12245 done-word (nth 3 ass)
12246 final-done-word (nth 4 ass)))
12247 (when (memq arg '(nextset previousset))
12248 (message "Keyword-Set %d/%d: %s"
12249 (- (length org-todo-sets) -1
12250 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12251 (length org-todo-sets)
12252 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12253 (setq org-last-todo-state-is-todo
12254 (not (member org-state org-done-keywords)))
12255 (setq now-done-p (and (member org-state org-done-keywords)
12256 (not (member this org-done-keywords))))
12257 (and logging (org-local-logging logging))
12258 (when (and (or org-todo-log-states org-log-done)
12259 (not (eq org-inhibit-logging t))
12260 (not (memq arg '(nextset previousset))))
12261 ;; we need to look at recording a time and note
12262 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12263 (nth 2 (assoc this org-todo-log-states))))
12264 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12265 (setq dolog 'time))
12266 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12267 (and org-state
12268 (member org-state org-not-done-keywords)
12269 (not (member this org-not-done-keywords))))
12270 ;; This is now a todo state and was not one before
12271 ;; If there was a CLOSED time stamp, get rid of it.
12272 (org-add-planning-info nil nil 'closed))
12273 (when (and now-done-p org-log-done)
12274 ;; It is now done, and it was not done before
12275 (org-add-planning-info 'closed (org-current-effective-time))
12276 (if (and (not dolog) (eq 'note org-log-done))
12277 (org-add-log-setup 'done org-state this 'findpos 'note)))
12278 (when (and org-state dolog)
12279 ;; This is a non-nil state, and we need to log it
12280 (org-add-log-setup 'state org-state this 'findpos dolog)))
12281 ;; Fixup tag positioning
12282 (org-todo-trigger-tag-changes org-state)
12283 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12284 (when org-provide-todo-statistics
12285 (org-update-parent-todo-statistics))
12286 (run-hooks 'org-after-todo-state-change-hook)
12287 (if (and arg (not (member org-state org-done-keywords)))
12288 (setq head (org-get-todo-sequence-head org-state)))
12289 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12290 ;; Do we need to trigger a repeat?
12291 (when now-done-p
12292 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12293 ;; This is for the agenda, take a snapshot of the headline.
12294 (save-match-data
12295 (setq org-agenda-headline-snapshot-before-repeat
12296 (org-get-heading))))
12297 (org-auto-repeat-maybe org-state))
12298 ;; Fixup cursor location if close to the keyword
12299 (if (and (outline-on-heading-p)
12300 (not (bolp))
12301 (save-excursion (beginning-of-line 1)
12302 (looking-at org-todo-line-regexp))
12303 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12304 (progn
12305 (goto-char (or (match-end 2) (match-end 1)))
12306 (and (looking-at " ") (just-one-space))))
12307 (when org-trigger-hook
12308 (save-excursion
12309 (run-hook-with-args 'org-trigger-hook change-plist)))
12310 (when commentp (org-toggle-comment))))))))
12312 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12313 "Block turning an entry into a TODO, using the hierarchy.
12314 This checks whether the current task should be blocked from state
12315 changes. Such blocking occurs when:
12317 1. The task has children which are not all in a completed state.
12319 2. A task has a parent with the property :ORDERED:, and there
12320 are siblings prior to the current task with incomplete
12321 status.
12323 3. The parent of the task is blocked because it has siblings that should
12324 be done first, or is child of a block grandparent TODO entry."
12326 (if (not org-enforce-todo-dependencies)
12327 t ; if locally turned off don't block
12328 (catch 'dont-block
12329 ;; If this is not a todo state change, or if this entry is already DONE,
12330 ;; do not block
12331 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12332 (member (plist-get change-plist :from)
12333 (cons 'done org-done-keywords))
12334 (member (plist-get change-plist :to)
12335 (cons 'todo org-not-done-keywords))
12336 (not (plist-get change-plist :to)))
12337 (throw 'dont-block t))
12338 ;; If this task has children, and any are undone, it's blocked
12339 (save-excursion
12340 (org-back-to-heading t)
12341 (let ((this-level (funcall outline-level)))
12342 (outline-next-heading)
12343 (let ((child-level (funcall outline-level)))
12344 (while (and (not (eobp))
12345 (> child-level this-level))
12346 ;; this todo has children, check whether they are all
12347 ;; completed
12348 (if (and (not (org-entry-is-done-p))
12349 (org-entry-is-todo-p))
12350 (progn (setq org-block-entry-blocking (org-get-heading))
12351 (throw 'dont-block nil)))
12352 (outline-next-heading)
12353 (setq child-level (funcall outline-level))))))
12354 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12355 ;; any previous siblings are undone, it's blocked
12356 (save-excursion
12357 (org-back-to-heading t)
12358 (let* ((pos (point))
12359 (parent-pos (and (org-up-heading-safe) (point))))
12360 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12361 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12362 (forward-line 1)
12363 (re-search-forward org-not-done-heading-regexp pos t))
12364 (setq org-block-entry-blocking (match-string 0))
12365 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12366 ;; Search further up the hierarchy, to see if an ancestor is blocked
12367 (while t
12368 (goto-char parent-pos)
12369 (if (not (looking-at org-not-done-heading-regexp))
12370 (throw 'dont-block t)) ; do not block, parent is not a TODO
12371 (setq pos (point))
12372 (setq parent-pos (and (org-up-heading-safe) (point)))
12373 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12374 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12375 (forward-line 1)
12376 (re-search-forward org-not-done-heading-regexp pos t)
12377 (setq org-block-entry-blocking (org-get-heading)))
12378 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12380 (defcustom org-track-ordered-property-with-tag nil
12381 "Should the ORDERED property also be shown as a tag?
12382 The ORDERED property decides if an entry should require subtasks to be
12383 completed in sequence. Since a property is not very visible, setting
12384 this option means that toggling the ORDERED property with the command
12385 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12386 not relevant for the behavior, but it makes things more visible.
12388 Note that toggling the tag with tags commands will not change the property
12389 and therefore not influence behavior!
12391 This can be t, meaning the tag ORDERED should be used, It can also be a
12392 string to select a different tag for this task."
12393 :group 'org-todo
12394 :type '(choice
12395 (const :tag "No tracking" nil)
12396 (const :tag "Track with ORDERED tag" t)
12397 (string :tag "Use other tag")))
12399 (defun org-toggle-ordered-property ()
12400 "Toggle the ORDERED property of the current entry.
12401 For better visibility, you can track the value of this property with a tag.
12402 See variable `org-track-ordered-property-with-tag'."
12403 (interactive)
12404 (let* ((t1 org-track-ordered-property-with-tag)
12405 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12406 (save-excursion
12407 (org-back-to-heading)
12408 (if (org-entry-get nil "ORDERED")
12409 (progn
12410 (org-delete-property "ORDERED" "PROPERTIES")
12411 (and tag (org-toggle-tag tag 'off))
12412 (message "Subtasks can be completed in arbitrary order"))
12413 (org-entry-put nil "ORDERED" "t")
12414 (and tag (org-toggle-tag tag 'on))
12415 (message "Subtasks must be completed in sequence")))))
12417 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12418 (defun org-block-todo-from-checkboxes (change-plist)
12419 "Block turning an entry into a TODO, using checkboxes.
12420 This checks whether the current task should be blocked from state
12421 changes because there are unchecked boxes in this entry."
12422 (if (not org-enforce-todo-checkbox-dependencies)
12423 t ; if locally turned off don't block
12424 (catch 'dont-block
12425 ;; If this is not a todo state change, or if this entry is already DONE,
12426 ;; do not block
12427 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12428 (member (plist-get change-plist :from)
12429 (cons 'done org-done-keywords))
12430 (member (plist-get change-plist :to)
12431 (cons 'todo org-not-done-keywords))
12432 (not (plist-get change-plist :to)))
12433 (throw 'dont-block t))
12434 ;; If this task has checkboxes that are not checked, it's blocked
12435 (save-excursion
12436 (org-back-to-heading t)
12437 (let ((beg (point)) end)
12438 (outline-next-heading)
12439 (setq end (point))
12440 (goto-char beg)
12441 (if (org-list-search-forward
12442 (concat (org-item-beginning-re)
12443 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12444 "\\[[- ]\\]")
12445 end t)
12446 (progn
12447 (if (boundp 'org-blocked-by-checkboxes)
12448 (setq org-blocked-by-checkboxes t))
12449 (throw 'dont-block nil)))))
12450 t))) ; do not block
12452 (defun org-entry-blocked-p ()
12453 "Is the current entry blocked?"
12454 (org-with-silent-modifications
12455 (if (org-entry-get nil "NOBLOCKING")
12456 nil ;; Never block this entry
12457 (not (run-hook-with-args-until-failure
12458 'org-blocker-hook
12459 (list :type 'todo-state-change
12460 :position (point)
12461 :from 'todo
12462 :to 'done))))))
12464 (defun org-update-statistics-cookies (all)
12465 "Update the statistics cookie, either from TODO or from checkboxes.
12466 This should be called with the cursor in a line with a statistics cookie."
12467 (interactive "P")
12468 (if all
12469 (progn
12470 (org-update-checkbox-count 'all)
12471 (org-map-entries 'org-update-parent-todo-statistics))
12472 (if (not (org-at-heading-p))
12473 (org-update-checkbox-count)
12474 (let ((pos (point-marker))
12475 end l1 l2)
12476 (ignore-errors (org-back-to-heading t))
12477 (if (not (org-at-heading-p))
12478 (org-update-checkbox-count)
12479 (setq l1 (org-outline-level))
12480 (setq end (save-excursion
12481 (outline-next-heading)
12482 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12483 (point)))
12484 (if (and (save-excursion
12485 (re-search-forward
12486 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12487 (not (save-excursion (re-search-forward
12488 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12489 (org-update-checkbox-count)
12490 (if (and l2 (> l2 l1))
12491 (progn
12492 (goto-char end)
12493 (org-update-parent-todo-statistics))
12494 (goto-char pos)
12495 (beginning-of-line 1)
12496 (while (re-search-forward
12497 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12498 (point-at-eol) t)
12499 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12500 (goto-char pos)
12501 (move-marker pos nil)))))
12503 (defvar org-entry-property-inherited-from) ;; defined below
12504 (defun org-update-parent-todo-statistics ()
12505 "Update any statistics cookie in the parent of the current headline.
12506 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12507 the entire subtree and this will travel up the hierarchy and update
12508 statistics everywhere."
12509 (let* ((prop (save-excursion (org-up-heading-safe)
12510 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12511 (recursive (or (not org-hierarchical-todo-statistics)
12512 (and prop (string-match "\\<recursive\\>" prop))))
12513 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12515 (first t)
12516 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12517 level ltoggle l1 new ndel
12518 (cnt-all 0) (cnt-done 0) is-percent kwd
12519 checkbox-beg ov ovs ove cookie-present)
12520 (catch 'exit
12521 (save-excursion
12522 (beginning-of-line 1)
12523 (setq ltoggle (funcall outline-level))
12524 ;; Three situations are to consider:
12526 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12527 ;; to the top-level ancestor on the headline;
12529 ;; 2. If parent has "recursive" property, repeat up to the
12530 ;; headline setting that property, taking inheritance into
12531 ;; account;
12533 ;; 3. Else, move up to direct parent and proceed only once.
12534 (while (and (setq level (org-up-heading-safe))
12535 (or recursive first)
12536 (>= (point) lim))
12537 (setq first nil cookie-present nil)
12538 (unless (and level
12539 (not (string-match
12540 "\\<checkbox\\>"
12541 (downcase (or (org-entry-get nil "COOKIE_DATA")
12542 "")))))
12543 (throw 'exit nil))
12544 (while (re-search-forward box-re (point-at-eol) t)
12545 (setq cnt-all 0 cnt-done 0 cookie-present t)
12546 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12547 (save-match-data
12548 (unless (outline-next-heading) (throw 'exit nil))
12549 (while (and (looking-at org-complex-heading-regexp)
12550 (> (setq l1 (length (match-string 1))) level))
12551 (setq kwd (and (or recursive (= l1 ltoggle))
12552 (match-string 2)))
12553 (if (or (eq org-provide-todo-statistics 'all-headlines)
12554 (and (listp org-provide-todo-statistics)
12555 (or (member kwd org-provide-todo-statistics)
12556 (member kwd org-done-keywords))))
12557 (setq cnt-all (1+ cnt-all))
12558 (if (eq org-provide-todo-statistics t)
12559 (and kwd (setq cnt-all (1+ cnt-all)))))
12560 (and (member kwd org-done-keywords)
12561 (setq cnt-done (1+ cnt-done)))
12562 (outline-next-heading)))
12563 (setq new
12564 (if is-percent
12565 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12566 (format "[%d/%d]" cnt-done cnt-all))
12567 ndel (- (match-end 0) checkbox-beg))
12568 ;; handle overlays when updating cookie from column view
12569 (when (setq ov (car (overlays-at checkbox-beg)))
12570 (setq ovs (overlay-start ov) ove (overlay-end ov))
12571 (delete-overlay ov))
12572 (goto-char checkbox-beg)
12573 (insert new)
12574 (delete-region (point) (+ (point) ndel))
12575 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12576 (when ov (move-overlay ov ovs ove)))
12577 (when cookie-present
12578 (run-hook-with-args 'org-after-todo-statistics-hook
12579 cnt-done (- cnt-all cnt-done))))))
12580 (run-hooks 'org-todo-statistics-hook)))
12582 (defvar org-after-todo-statistics-hook nil
12583 "Hook that is called after a TODO statistics cookie has been updated.
12584 Each function is called with two arguments: the number of not-done entries
12585 and the number of done entries.
12587 For example, the following function, when added to this hook, will switch
12588 an entry to DONE when all children are done, and back to TODO when new
12589 entries are set to a TODO status. Note that this hook is only called
12590 when there is a statistics cookie in the headline!
12592 (defun org-summary-todo (n-done n-not-done)
12593 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12594 (let (org-log-done org-log-states) ; turn off logging
12595 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12598 (defvar org-todo-statistics-hook nil
12599 "Hook that is run whenever Org thinks TODO statistics should be updated.
12600 This hook runs even if there is no statistics cookie present, in which case
12601 `org-after-todo-statistics-hook' would not run.")
12603 (defun org-todo-trigger-tag-changes (state)
12604 "Apply the changes defined in `org-todo-state-tags-triggers'."
12605 (let ((l org-todo-state-tags-triggers)
12606 changes)
12607 (when (or (not state) (equal state ""))
12608 (setq changes (append changes (cdr (assoc "" l)))))
12609 (when (and (stringp state) (> (length state) 0))
12610 (setq changes (append changes (cdr (assoc state l)))))
12611 (when (member state org-not-done-keywords)
12612 (setq changes (append changes (cdr (assoc 'todo l)))))
12613 (when (member state org-done-keywords)
12614 (setq changes (append changes (cdr (assoc 'done l)))))
12615 (dolist (c changes)
12616 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12618 (defun org-local-logging (value)
12619 "Get logging settings from a property VALUE."
12620 (let* (words w a)
12621 ;; directly set the variables, they are already local.
12622 (setq org-log-done nil
12623 org-log-repeat nil
12624 org-todo-log-states nil)
12625 (setq words (org-split-string value))
12626 (while (setq w (pop words))
12627 (cond
12628 ((setq a (assoc w org-startup-options))
12629 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12630 (set (nth 1 a) (nth 2 a))))
12631 ((setq a (org-extract-log-state-settings w))
12632 (and (member (car a) org-todo-keywords-1)
12633 (push a org-todo-log-states)))))))
12635 (defun org-get-todo-sequence-head (kwd)
12636 "Return the head of the TODO sequence to which KWD belongs.
12637 If KWD is not set, check if there is a text property remembering the
12638 right sequence."
12639 (let (p)
12640 (cond
12641 ((not kwd)
12642 (or (get-text-property (point-at-bol) 'org-todo-head)
12643 (progn
12644 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12645 nil (point-at-eol)))
12646 (get-text-property p 'org-todo-head))))
12647 ((not (member kwd org-todo-keywords-1))
12648 (car org-todo-keywords-1))
12649 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12651 (defun org-fast-todo-selection ()
12652 "Fast TODO keyword selection with single keys.
12653 Returns the new TODO keyword, or nil if no state change should occur."
12654 (let* ((fulltable org-todo-key-alist)
12655 (done-keywords org-done-keywords) ;; needed for the faces.
12656 (maxlen (apply 'max (mapcar
12657 (lambda (x)
12658 (if (stringp (car x)) (string-width (car x)) 0))
12659 fulltable)))
12660 (expert nil)
12661 (fwidth (+ maxlen 3 1 3))
12662 (ncol (/ (- (window-width) 4) fwidth))
12663 tg cnt e c tbl
12664 groups ingroup)
12665 (save-excursion
12666 (save-window-excursion
12667 (if expert
12668 (set-buffer (get-buffer-create " *Org todo*"))
12669 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12670 (erase-buffer)
12671 (org-set-local 'org-done-keywords done-keywords)
12672 (setq tbl fulltable cnt 0)
12673 (while (setq e (pop tbl))
12674 (cond
12675 ((equal e '(:startgroup))
12676 (push '() groups) (setq ingroup t)
12677 (when (not (= cnt 0))
12678 (setq cnt 0)
12679 (insert "\n"))
12680 (insert "{ "))
12681 ((equal e '(:endgroup))
12682 (setq ingroup nil cnt 0)
12683 (insert "}\n"))
12684 ((equal e '(:newline))
12685 (when (not (= cnt 0))
12686 (setq cnt 0)
12687 (insert "\n")
12688 (setq e (car tbl))
12689 (while (equal (car tbl) '(:newline))
12690 (insert "\n")
12691 (setq tbl (cdr tbl)))))
12693 (setq tg (car e) c (cdr e))
12694 (if ingroup (push tg (car groups)))
12695 (setq tg (org-add-props tg nil 'face
12696 (org-get-todo-face tg)))
12697 (if (and (= cnt 0) (not ingroup)) (insert " "))
12698 (insert "[" c "] " tg (make-string
12699 (- fwidth 4 (length tg)) ?\ ))
12700 (when (= (setq cnt (1+ cnt)) ncol)
12701 (insert "\n")
12702 (if ingroup (insert " "))
12703 (setq cnt 0)))))
12704 (insert "\n")
12705 (goto-char (point-min))
12706 (if (not expert) (org-fit-window-to-buffer))
12707 (message "[a-z..]:Set [SPC]:clear")
12708 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12709 (cond
12710 ((or (= c ?\C-g)
12711 (and (= c ?q) (not (rassoc c fulltable))))
12712 (setq quit-flag t))
12713 ((= c ?\ ) nil)
12714 ((setq e (rassoc c fulltable) tg (car e))
12716 (t (setq quit-flag t)))))))
12718 (defun org-entry-is-todo-p ()
12719 (member (org-get-todo-state) org-not-done-keywords))
12721 (defun org-entry-is-done-p ()
12722 (member (org-get-todo-state) org-done-keywords))
12724 (defun org-get-todo-state ()
12725 "Return the TODO keyword of the current subtree."
12726 (save-excursion
12727 (org-back-to-heading t)
12728 (and (looking-at org-todo-line-regexp)
12729 (match-end 2)
12730 (match-string 2))))
12732 (defun org-at-date-range-p (&optional inactive-ok)
12733 "Is the cursor inside a date range?"
12734 (interactive)
12735 (save-excursion
12736 (catch 'exit
12737 (let ((pos (point)))
12738 (skip-chars-backward "^[<\r\n")
12739 (skip-chars-backward "<[")
12740 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12741 (>= (match-end 0) pos)
12742 (throw 'exit t))
12743 (skip-chars-backward "^<[\r\n")
12744 (skip-chars-backward "<[")
12745 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12746 (>= (match-end 0) pos)
12747 (throw 'exit t)))
12748 nil)))
12750 (defun org-get-repeat (&optional tagline)
12751 "Check if there is a deadline/schedule with repeater in this entry."
12752 (save-match-data
12753 (save-excursion
12754 (org-back-to-heading t)
12755 (and (re-search-forward (if tagline
12756 (concat tagline "\\s-*" org-repeat-re)
12757 org-repeat-re)
12758 (org-entry-end-position) t)
12759 (match-string-no-properties 1)))))
12761 (defvar org-last-changed-timestamp)
12762 (defvar org-last-inserted-timestamp)
12763 (defvar org-log-post-message)
12764 (defvar org-log-note-purpose)
12765 (defvar org-log-note-how)
12766 (defvar org-log-note-extra)
12767 (defun org-auto-repeat-maybe (done-word)
12768 "Check if the current headline contains a repeated deadline/schedule.
12769 If yes, set TODO state back to what it was and change the base date
12770 of repeating deadline/scheduled time stamps to new date.
12771 This function is run automatically after each state change to a DONE state."
12772 ;; last-state is dynamically scoped into this function
12773 (let* ((repeat (org-get-repeat))
12774 (aa (assoc org-last-state org-todo-kwd-alist))
12775 (interpret (nth 1 aa))
12776 (head (nth 2 aa))
12777 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12778 (msg "Entry repeats: ")
12779 (org-log-done nil)
12780 (org-todo-log-states nil)
12781 re type n what ts time to-state)
12782 (when repeat
12783 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12784 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12785 org-todo-repeat-to-state))
12786 (unless (and to-state (member to-state org-todo-keywords-1))
12787 (setq to-state (if (eq interpret 'type) org-last-state head)))
12788 (org-todo to-state)
12789 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12790 (org-entry-put nil "LAST_REPEAT" (format-time-string
12791 (org-time-stamp-format t t))))
12792 (when org-log-repeat
12793 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12794 (memq 'org-add-log-note post-command-hook))
12795 ;; OK, we are already setup for some record
12796 (if (eq org-log-repeat 'note)
12797 ;; make sure we take a note, not only a time stamp
12798 (setq org-log-note-how 'note))
12799 ;; Set up for taking a record
12800 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12801 org-last-state
12802 'findpos org-log-repeat)))
12803 (org-back-to-heading t)
12804 (org-add-planning-info nil nil 'closed)
12805 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12806 org-deadline-time-regexp "\\)\\|\\("
12807 org-ts-regexp "\\)"))
12808 (while (re-search-forward
12809 re (save-excursion (outline-next-heading) (point)) t)
12810 (setq type (if (match-end 1) org-scheduled-string
12811 (if (match-end 3) org-deadline-string "Plain:"))
12812 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12813 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12814 (setq n (string-to-number (match-string 2 ts))
12815 what (match-string 3 ts))
12816 (if (equal what "w") (setq n (* n 7) what "d"))
12817 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12818 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12819 ;; Preparation, see if we need to modify the start date for the change
12820 (when (match-end 1)
12821 (setq time (save-match-data (org-time-string-to-time ts)))
12822 (cond
12823 ((equal (match-string 1 ts) ".")
12824 ;; Shift starting date to today
12825 (org-timestamp-change
12826 (- (org-today) (time-to-days time))
12827 'day))
12828 ((equal (match-string 1 ts) "+")
12829 (let ((nshiftmax 10) (nshift 0))
12830 (while (or (= nshift 0)
12831 (<= (time-to-days time)
12832 (time-to-days (current-time))))
12833 (when (= (incf nshift) nshiftmax)
12834 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12835 (error "Abort")))
12836 (org-timestamp-change n (cdr (assoc what whata)))
12837 (org-at-timestamp-p t)
12838 (setq ts (match-string 1))
12839 (setq time (save-match-data (org-time-string-to-time ts)))))
12840 (org-timestamp-change (- n) (cdr (assoc what whata)))
12841 ;; rematch, so that we have everything in place for the real shift
12842 (org-at-timestamp-p t)
12843 (setq ts (match-string 1))
12844 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12845 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12846 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12847 (setq org-log-post-message msg)
12848 (message "%s" msg))))
12850 (defun org-show-todo-tree (arg)
12851 "Make a compact tree which shows all headlines marked with TODO.
12852 The tree will show the lines where the regexp matches, and all higher
12853 headlines above the match.
12854 With a \\[universal-argument] prefix, prompt for a regexp to match.
12855 With a numeric prefix N, construct a sparse tree for the Nth element
12856 of `org-todo-keywords-1'."
12857 (interactive "P")
12858 (let ((case-fold-search nil)
12859 (kwd-re
12860 (cond ((null arg) org-not-done-regexp)
12861 ((equal arg '(4))
12862 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12863 (mapcar 'list org-todo-keywords-1))))
12864 (concat "\\("
12865 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12866 "\\)\\>")))
12867 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12868 (regexp-quote (nth (1- (prefix-numeric-value arg))
12869 org-todo-keywords-1)))
12870 (t (user-error "Invalid prefix argument: %s" arg)))))
12871 (message "%d TODO entries found"
12872 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12874 (defun org-deadline (arg &optional time)
12875 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12876 With one universal prefix argument, remove any deadline from the item.
12877 With two universal prefix arguments, prompt for a warning delay.
12878 With argument TIME, set the deadline at the corresponding date. TIME
12879 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12880 (interactive "P")
12881 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12882 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12883 'region-start-level 'region))
12884 org-loop-over-headlines-in-active-region)
12885 (org-map-entries
12886 `(org-deadline ',arg ,time)
12887 org-loop-over-headlines-in-active-region
12888 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12889 (let* ((old-date (org-entry-get nil "DEADLINE"))
12890 (old-date-time (if old-date (org-time-string-to-time old-date)))
12891 (repeater (and old-date
12892 (string-match
12893 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12894 old-date)
12895 (match-string 1 old-date))))
12896 (cond
12897 ((equal arg '(4))
12898 (when (and old-date org-log-redeadline)
12899 (org-add-log-setup 'deldeadline nil old-date 'findpos
12900 org-log-redeadline))
12901 (org-remove-timestamp-with-keyword org-deadline-string)
12902 (message "Item no longer has a deadline."))
12903 ((equal arg '(16))
12904 (save-excursion
12905 (if (re-search-forward
12906 org-deadline-time-regexp
12907 (save-excursion (outline-next-heading) (point)) t)
12908 (let* ((rpl0 (match-string 1))
12909 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12910 (replace-match
12911 (concat org-deadline-string
12912 " <" rpl
12913 (format " -%dd"
12914 (abs
12915 (- (time-to-days
12916 (save-match-data
12917 (org-read-date nil t nil "Warn starting from" old-date-time)))
12918 (time-to-days old-date-time))))
12919 ">") t t))
12920 (user-error "No deadline information to update"))))
12922 (org-add-planning-info 'deadline time 'closed)
12923 (when (and old-date org-log-redeadline
12924 (not (equal old-date
12925 (substring org-last-inserted-timestamp 1 -1))))
12926 (org-add-log-setup 'redeadline nil old-date 'findpos
12927 org-log-redeadline))
12928 (when repeater
12929 (save-excursion
12930 (org-back-to-heading t)
12931 (when (re-search-forward (concat org-deadline-string " "
12932 org-last-inserted-timestamp)
12933 (save-excursion
12934 (outline-next-heading) (point)) t)
12935 (goto-char (1- (match-end 0)))
12936 (insert " " repeater)
12937 (setq org-last-inserted-timestamp
12938 (concat (substring org-last-inserted-timestamp 0 -1)
12939 " " repeater
12940 (substring org-last-inserted-timestamp -1))))))
12941 (message "Deadline on %s" org-last-inserted-timestamp))))))
12943 (defun org-schedule (arg &optional time)
12944 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12945 With one universal prefix argument, remove any scheduling date from the item.
12946 With two universal prefix arguments, prompt for a delay cookie.
12947 With argument TIME, scheduled at the corresponding date. TIME can
12948 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12949 (interactive "P")
12950 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12951 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12952 'region-start-level 'region))
12953 org-loop-over-headlines-in-active-region)
12954 (org-map-entries
12955 `(org-schedule ',arg ,time)
12956 org-loop-over-headlines-in-active-region
12957 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12958 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12959 (old-date-time (if old-date (org-time-string-to-time old-date)))
12960 (repeater (and old-date
12961 (string-match
12962 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12963 old-date)
12964 (match-string 1 old-date))))
12965 (cond
12966 ((equal arg '(4))
12967 (progn
12968 (when (and old-date org-log-reschedule)
12969 (org-add-log-setup 'delschedule nil old-date 'findpos
12970 org-log-reschedule))
12971 (org-remove-timestamp-with-keyword org-scheduled-string)
12972 (message "Item is no longer scheduled.")))
12973 ((equal arg '(16))
12974 (save-excursion
12975 (if (re-search-forward
12976 org-scheduled-time-regexp
12977 (save-excursion (outline-next-heading) (point)) t)
12978 (let* ((rpl0 (match-string 1))
12979 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12980 (replace-match
12981 (concat org-scheduled-string
12982 " <" rpl
12983 (format " -%dd"
12984 (abs
12985 (- (time-to-days
12986 (save-match-data
12987 (org-read-date nil t nil "Delay until" old-date-time)))
12988 (time-to-days old-date-time))))
12989 ">") t t))
12990 (user-error "No scheduled information to update"))))
12992 (org-add-planning-info 'scheduled time 'closed)
12993 (when (and old-date org-log-reschedule
12994 (not (equal old-date
12995 (substring org-last-inserted-timestamp 1 -1))))
12996 (org-add-log-setup 'reschedule nil old-date 'findpos
12997 org-log-reschedule))
12998 (when repeater
12999 (save-excursion
13000 (org-back-to-heading t)
13001 (when (re-search-forward (concat org-scheduled-string " "
13002 org-last-inserted-timestamp)
13003 (save-excursion
13004 (outline-next-heading) (point)) t)
13005 (goto-char (1- (match-end 0)))
13006 (insert " " repeater)
13007 (setq org-last-inserted-timestamp
13008 (concat (substring org-last-inserted-timestamp 0 -1)
13009 " " repeater
13010 (substring org-last-inserted-timestamp -1))))))
13011 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13013 (defun org-get-scheduled-time (pom &optional inherit)
13014 "Get the scheduled time as a time tuple, of a format suitable
13015 for calling org-schedule with, or if there is no scheduling,
13016 returns nil."
13017 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13018 (when time
13019 (apply 'encode-time (org-parse-time-string time)))))
13021 (defun org-get-deadline-time (pom &optional inherit)
13022 "Get the deadline as a time tuple, of a format suitable for
13023 calling org-deadline with, or if there is no scheduling, returns
13024 nil."
13025 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13026 (when time
13027 (apply 'encode-time (org-parse-time-string time)))))
13029 (defun org-remove-timestamp-with-keyword (keyword)
13030 "Remove all time stamps with KEYWORD in the current entry."
13031 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13032 beg)
13033 (save-excursion
13034 (org-back-to-heading t)
13035 (setq beg (point))
13036 (outline-next-heading)
13037 (while (re-search-backward re beg t)
13038 (replace-match "")
13039 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13040 (equal (char-before) ?\ ))
13041 (backward-delete-char 1)
13042 (if (string-match "^[ \t]*$" (buffer-substring
13043 (point-at-bol) (point-at-eol)))
13044 (delete-region (point-at-bol)
13045 (min (point-max) (1+ (point-at-eol))))))))))
13047 (defun org-add-planning-info (what &optional time &rest remove)
13048 "Insert new timestamp with keyword in the line directly after the headline.
13049 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13050 If non is given, the user is prompted for a date.
13051 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13052 be removed."
13053 (interactive)
13054 (let (org-time-was-given org-end-time-was-given ts
13055 end default-time default-input)
13057 (catch 'exit
13058 (when (and (memq what '(scheduled deadline))
13059 (or (not time)
13060 (and (stringp time)
13061 (string-match "^[-+]+[0-9]" time))))
13062 ;; Try to get a default date/time from existing timestamp
13063 (save-excursion
13064 (org-back-to-heading t)
13065 (setq end (save-excursion (outline-next-heading) (point)))
13066 (when (re-search-forward (if (eq what 'scheduled)
13067 org-scheduled-time-regexp
13068 org-deadline-time-regexp)
13069 end t)
13070 (setq ts (match-string 1)
13071 default-time
13072 (apply 'encode-time (org-parse-time-string ts))
13073 default-input (and ts (org-get-compact-tod ts))))))
13074 (when what
13075 (setq time
13076 (if (stringp time)
13077 ;; This is a string (relative or absolute), set proper date
13078 (apply 'encode-time
13079 (org-read-date-analyze
13080 time default-time (decode-time default-time)))
13081 ;; If necessary, get the time from the user
13082 (or time (org-read-date nil 'to-time nil nil
13083 default-time default-input)))))
13085 (when (and org-insert-labeled-timestamps-at-point
13086 (member what '(scheduled deadline)))
13087 (insert
13088 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13089 (org-insert-time-stamp time org-time-was-given
13090 nil nil nil (list org-end-time-was-given))
13091 (setq what nil))
13092 (save-excursion
13093 (save-restriction
13094 (let (col list elt ts buffer-invisibility-spec)
13095 (org-back-to-heading t)
13096 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13097 (goto-char (match-end 1))
13098 (setq col (current-column))
13099 (goto-char (match-end 0))
13100 (if (eobp) (insert "\n") (forward-char 1))
13101 (when (and (not what)
13102 (not (looking-at
13103 (concat "[ \t]*"
13104 org-keyword-time-not-clock-regexp))))
13105 ;; Nothing to add, nothing to remove...... :-)
13106 (throw 'exit nil))
13107 (if (and (not (looking-at org-outline-regexp))
13108 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13109 "[^\r\n]*"))
13110 (not (equal (match-string 1) org-clock-string)))
13111 (narrow-to-region (match-beginning 0) (match-end 0))
13112 (insert-before-markers "\n")
13113 (backward-char 1)
13114 (narrow-to-region (point) (point))
13115 (and org-adapt-indentation (org-indent-to-column col)))
13116 ;; Check if we have to remove something.
13117 (setq list (cons what remove))
13118 (while list
13119 (setq elt (pop list))
13120 (when (or (and (eq elt 'scheduled)
13121 (re-search-forward org-scheduled-time-regexp nil t))
13122 (and (eq elt 'deadline)
13123 (re-search-forward org-deadline-time-regexp nil t))
13124 (and (eq elt 'closed)
13125 (re-search-forward org-closed-time-regexp nil t)))
13126 (replace-match "")
13127 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13128 (and (looking-at "[ \t]+") (replace-match ""))
13129 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13130 (when what
13131 (insert
13132 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13133 (cond ((eq what 'scheduled) org-scheduled-string)
13134 ((eq what 'deadline) org-deadline-string)
13135 ((eq what 'closed) org-closed-string))
13136 " ")
13137 (setq ts (org-insert-time-stamp
13138 time
13139 (or org-time-was-given
13140 (and (eq what 'closed) org-log-done-with-time))
13141 (eq what 'closed)
13142 nil nil (list org-end-time-was-given)))
13143 (insert
13144 (if (not (or (bolp) (eq (char-before) ?\ )
13145 (memq (char-after) '(32 10))
13146 (eobp))) " " ""))
13147 (end-of-line 1))
13148 (goto-char (point-min))
13149 (widen)
13150 (if (and (looking-at "[ \t]*\n")
13151 (equal (char-before) ?\n))
13152 (delete-region (1- (point)) (point-at-eol)))
13153 ts))))))
13155 (defvar org-log-note-marker (make-marker))
13156 (defvar org-log-note-purpose nil)
13157 (defvar org-log-note-state nil)
13158 (defvar org-log-note-previous-state nil)
13159 (defvar org-log-note-how nil)
13160 (defvar org-log-note-extra nil)
13161 (defvar org-log-note-window-configuration nil)
13162 (defvar org-log-note-return-to (make-marker))
13163 (defvar org-log-note-effective-time nil
13164 "Remembered current time so that dynamically scoped
13165 `org-extend-today-until' affects tha timestamps in state change
13166 log")
13168 (defvar org-log-post-message nil
13169 "Message to be displayed after a log note has been stored.
13170 The auto-repeater uses this.")
13172 (defun org-add-note ()
13173 "Add a note to the current entry.
13174 This is done in the same way as adding a state change note."
13175 (interactive)
13176 (org-add-log-setup 'note nil nil 'findpos nil))
13178 (defvar org-property-end-re)
13179 (defun org-add-log-setup (&optional purpose state prev-state
13180 findpos how extra)
13181 "Set up the post command hook to take a note.
13182 If this is about to TODO state change, the new state is expected in STATE.
13183 When FINDPOS is non-nil, find the correct position for the note in
13184 the current entry. If not, assume that it can be inserted at point.
13185 HOW is an indicator what kind of note should be created.
13186 EXTRA is additional text that will be inserted into the notes buffer."
13187 (let* ((org-log-into-drawer (org-log-into-drawer))
13188 (drawer (cond ((stringp org-log-into-drawer)
13189 org-log-into-drawer)
13190 (org-log-into-drawer "LOGBOOK"))))
13191 (save-restriction
13192 (save-excursion
13193 (when findpos
13194 (org-back-to-heading t)
13195 (narrow-to-region (point) (save-excursion
13196 (outline-next-heading) (point)))
13197 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13198 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13199 "[^\r\n]*\\)?"))
13200 (goto-char (match-end 0))
13201 (cond
13202 (drawer
13203 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13204 nil t)
13205 (progn
13206 (goto-char (match-end 0))
13207 (or org-log-states-order-reversed
13208 (and (re-search-forward org-property-end-re nil t)
13209 (goto-char (1- (match-beginning 0))))))
13210 (insert "\n:" drawer ":\n:END:")
13211 (beginning-of-line 0)
13212 (org-indent-line)
13213 (beginning-of-line 2)
13214 (org-indent-line)
13215 (end-of-line 0)))
13216 ((and org-log-state-notes-insert-after-drawers
13217 (save-excursion
13218 (forward-line) (looking-at org-drawer-regexp)))
13219 (forward-line)
13220 (while (looking-at org-drawer-regexp)
13221 (goto-char (match-end 0))
13222 (re-search-forward org-property-end-re (point-max) t)
13223 (forward-line))
13224 (forward-line -1)))
13225 (unless org-log-states-order-reversed
13226 (and (= (char-after) ?\n) (forward-char 1))
13227 (org-skip-over-state-notes)
13228 (skip-chars-backward " \t\n\r")))
13229 (move-marker org-log-note-marker (point))
13230 (setq org-log-note-purpose purpose
13231 org-log-note-state state
13232 org-log-note-previous-state prev-state
13233 org-log-note-how how
13234 org-log-note-extra extra
13235 org-log-note-effective-time (org-current-effective-time))
13236 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13238 (defun org-skip-over-state-notes ()
13239 "Skip past the list of State notes in an entry."
13240 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13241 (when (ignore-errors (goto-char (org-in-item-p)))
13242 (let* ((struct (org-list-struct))
13243 (prevs (org-list-prevs-alist struct)))
13244 (while (looking-at "[ \t]*- State")
13245 (goto-char (or (org-list-get-next-item (point) struct prevs)
13246 (org-list-get-item-end (point) struct)))))))
13248 (defun org-add-log-note (&optional purpose)
13249 "Pop up a window for taking a note, and add this note later at point."
13250 (remove-hook 'post-command-hook 'org-add-log-note)
13251 (setq org-log-note-window-configuration (current-window-configuration))
13252 (delete-other-windows)
13253 (move-marker org-log-note-return-to (point))
13254 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13255 (goto-char org-log-note-marker)
13256 (org-switch-to-buffer-other-window "*Org Note*")
13257 (erase-buffer)
13258 (if (memq org-log-note-how '(time state))
13259 (let (current-prefix-arg) (org-store-log-note))
13260 (let ((org-inhibit-startup t)) (org-mode))
13261 (insert (format "# Insert note for %s.
13262 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13263 (cond
13264 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13265 ((eq org-log-note-purpose 'done) "closed todo item")
13266 ((eq org-log-note-purpose 'state)
13267 (format "state change from \"%s\" to \"%s\""
13268 (or org-log-note-previous-state "")
13269 (or org-log-note-state "")))
13270 ((eq org-log-note-purpose 'reschedule)
13271 "rescheduling")
13272 ((eq org-log-note-purpose 'delschedule)
13273 "no longer scheduled")
13274 ((eq org-log-note-purpose 'redeadline)
13275 "changing deadline")
13276 ((eq org-log-note-purpose 'deldeadline)
13277 "removing deadline")
13278 ((eq org-log-note-purpose 'refile)
13279 "refiling")
13280 ((eq org-log-note-purpose 'note)
13281 "this entry")
13282 (t (error "This should not happen")))))
13283 (if org-log-note-extra (insert org-log-note-extra))
13284 (org-set-local 'org-finish-function 'org-store-log-note)
13285 (run-hooks 'org-log-buffer-setup-hook)))
13287 (defvar org-note-abort nil) ; dynamically scoped
13288 (defun org-store-log-note ()
13289 "Finish taking a log note, and insert it to where it belongs."
13290 (let ((txt (buffer-string)))
13291 (kill-buffer (current-buffer))
13292 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13293 lines ind bul)
13294 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13295 (setq txt (replace-match "" t t txt)))
13296 (if (string-match "\\s-+\\'" txt)
13297 (setq txt (replace-match "" t t txt)))
13298 (setq lines (org-split-string txt "\n"))
13299 (when (and note (string-match "\\S-" note))
13300 (setq note
13301 (org-replace-escapes
13302 note
13303 (list (cons "%u" (user-login-name))
13304 (cons "%U" user-full-name)
13305 (cons "%t" (format-time-string
13306 (org-time-stamp-format 'long 'inactive)
13307 org-log-note-effective-time))
13308 (cons "%T" (format-time-string
13309 (org-time-stamp-format 'long nil)
13310 org-log-note-effective-time))
13311 (cons "%d" (format-time-string
13312 (org-time-stamp-format nil 'inactive)
13313 org-log-note-effective-time))
13314 (cons "%D" (format-time-string
13315 (org-time-stamp-format nil nil)
13316 org-log-note-effective-time))
13317 (cons "%s" (if org-log-note-state
13318 (concat "\"" org-log-note-state "\"")
13319 ""))
13320 (cons "%S" (if org-log-note-previous-state
13321 (concat "\"" org-log-note-previous-state "\"")
13322 "\"\"")))))
13323 (if lines (setq note (concat note " \\\\")))
13324 (push note lines))
13325 (when (or current-prefix-arg org-note-abort)
13326 (when org-log-into-drawer
13327 (org-remove-empty-drawer-at
13328 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13329 org-log-note-marker))
13330 (setq lines nil))
13331 (when lines
13332 (with-current-buffer (marker-buffer org-log-note-marker)
13333 (save-excursion
13334 (goto-char org-log-note-marker)
13335 (move-marker org-log-note-marker nil)
13336 (end-of-line 1)
13337 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13338 (setq ind (save-excursion
13339 (if (ignore-errors (goto-char (org-in-item-p)))
13340 (let ((struct (org-list-struct)))
13341 (org-list-get-ind
13342 (org-list-get-top-point struct) struct))
13343 (skip-chars-backward " \r\t\n")
13344 (cond
13345 ((and (org-at-heading-p)
13346 org-adapt-indentation)
13347 (1+ (org-current-level)))
13348 ((org-at-heading-p) 0)
13349 (t (org-get-indentation))))))
13350 (setq bul (org-list-bullet-string "-"))
13351 (org-indent-line-to ind)
13352 (insert bul (pop lines))
13353 (let ((ind-body (+ (length bul) ind)))
13354 (while lines
13355 (insert "\n")
13356 (org-indent-line-to ind-body)
13357 (insert (pop lines))))
13358 (message "Note stored")
13359 (org-back-to-heading t)
13360 (org-cycle-hide-drawers 'children))
13361 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13362 ;; from within `org-add-log-note' because `buffer-undo-list'
13363 ;; is then modified outside of `org-with-remote-undo'.
13364 (when (eq this-command 'org-agenda-todo)
13365 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13366 ;; Don't add undo information when called from `org-agenda-todo'
13367 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13368 (set-window-configuration org-log-note-window-configuration)
13369 (with-current-buffer (marker-buffer org-log-note-return-to)
13370 (goto-char org-log-note-return-to))
13371 (move-marker org-log-note-return-to nil)
13372 (and org-log-post-message (message "%s" org-log-post-message))))
13374 (defun org-remove-empty-drawer-at (drawer pos)
13375 "Remove an empty drawer DRAWER at position POS.
13376 POS may also be a marker."
13377 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13378 (save-excursion
13379 (save-restriction
13380 (widen)
13381 (goto-char pos)
13382 (if (org-in-regexp
13383 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13384 (replace-match ""))))))
13386 (defvar org-ts-type nil)
13387 (defun org-sparse-tree (&optional arg type)
13388 "Create a sparse tree, prompt for the details.
13389 This command can create sparse trees. You first need to select the type
13390 of match used to create the tree:
13392 t Show all TODO entries.
13393 T Show entries with a specific TODO keyword.
13394 m Show entries selected by a tags/property match.
13395 p Enter a property name and its value (both with completion on existing
13396 names/values) and show entries with that property.
13397 r Show entries matching a regular expression (`/' can be used as well).
13398 b Show deadlines and scheduled items before a date.
13399 a Show deadlines and scheduled items after a date.
13400 d Show deadlines due within `org-deadline-warning-days'.
13401 D Show deadlines and scheduled items between a date range."
13402 (interactive "P")
13403 (let (ans kwd value ts-type)
13404 (setq type (or type org-sparse-tree-default-date-type))
13405 (setq org-ts-type type)
13406 (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"
13407 (cond ((eq type 'all) "all timestamps")
13408 ((eq type 'scheduled) "only scheduled")
13409 ((eq type 'deadline) "only deadline")
13410 ((eq type 'active) "only active timestamps")
13411 ((eq type 'inactive) "only inactive timestamps")
13412 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13413 ((eq type 'closed) "with a closed time-stamp")
13414 (t "scheduled/deadline")))
13415 (setq ans (read-char-exclusive))
13416 (cond
13417 ((equal ans ?c)
13418 (org-sparse-tree
13419 arg (cadr (member type '(scheduled-or-deadline
13420 all scheduled deadline active inactive closed)))))
13421 ((equal ans ?d)
13422 (call-interactively 'org-check-deadlines))
13423 ((equal ans ?b)
13424 (call-interactively 'org-check-before-date))
13425 ((equal ans ?a)
13426 (call-interactively 'org-check-after-date))
13427 ((equal ans ?D)
13428 (call-interactively 'org-check-dates-range))
13429 ((equal ans ?t)
13430 (call-interactively 'org-show-todo-tree))
13431 ((equal ans ?T)
13432 (org-show-todo-tree '(4)))
13433 ((member ans '(?T ?m))
13434 (call-interactively 'org-match-sparse-tree))
13435 ((member ans '(?p ?P))
13436 (setq kwd (org-icompleting-read "Property: "
13437 (mapcar 'list (org-buffer-property-keys))))
13438 (setq value (org-icompleting-read "Value: "
13439 (mapcar 'list (org-property-values kwd))))
13440 (unless (string-match "\\`{.*}\\'" value)
13441 (setq value (concat "\"" value "\"")))
13442 (org-match-sparse-tree arg (concat kwd "=" value)))
13443 ((member ans '(?r ?R ?/))
13444 (call-interactively 'org-occur))
13445 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13447 (defvar org-occur-highlights nil
13448 "List of overlays used for occur matches.")
13449 (make-variable-buffer-local 'org-occur-highlights)
13450 (defvar org-occur-parameters nil
13451 "Parameters of the active org-occur calls.
13452 This is a list, each call to org-occur pushes as cons cell,
13453 containing the regular expression and the callback, onto the list.
13454 The list can contain several entries if `org-occur' has been called
13455 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13456 will only contain one set of parameters. When the highlights are
13457 removed (for example with `C-c C-c', or with the next edit (depending
13458 on `org-remove-highlights-with-change'), this variable is emptied
13459 as well.")
13460 (make-variable-buffer-local 'org-occur-parameters)
13462 (defun org-occur (regexp &optional keep-previous callback)
13463 "Make a compact tree which shows all matches of REGEXP.
13464 The tree will show the lines where the regexp matches, and all higher
13465 headlines above the match. It will also show the heading after the match,
13466 to make sure editing the matching entry is easy.
13467 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13468 call to `org-occur' will be kept, to allow stacking of calls to this
13469 command.
13470 If CALLBACK is non-nil, it is a function which is called to confirm
13471 that the match should indeed be shown."
13472 (interactive "sRegexp: \nP")
13473 (when (equal regexp "")
13474 (user-error "Regexp cannot be empty"))
13475 (unless keep-previous
13476 (org-remove-occur-highlights nil nil t))
13477 (push (cons regexp callback) org-occur-parameters)
13478 (let ((cnt 0))
13479 (save-excursion
13480 (goto-char (point-min))
13481 (if (or (not keep-previous) ; do not want to keep
13482 (not org-occur-highlights)) ; no previous matches
13483 ;; hide everything
13484 (org-overview))
13485 (while (re-search-forward regexp nil t)
13486 (when (or (not callback)
13487 (save-match-data (funcall callback)))
13488 (setq cnt (1+ cnt))
13489 (when org-highlight-sparse-tree-matches
13490 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13491 (org-show-context 'occur-tree))))
13492 (when org-remove-highlights-with-change
13493 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13494 nil 'local))
13495 (unless org-sparse-tree-open-archived-trees
13496 (org-hide-archived-subtrees (point-min) (point-max)))
13497 (run-hooks 'org-occur-hook)
13498 (if (org-called-interactively-p 'interactive)
13499 (message "%d match(es) for regexp %s" cnt regexp))
13500 cnt))
13502 (defun org-occur-next-match (&optional n reset)
13503 "Function for `next-error-function' to find sparse tree matches.
13504 N is the number of matches to move, when negative move backwards.
13505 RESET is entirely ignored - this function always goes back to the
13506 starting point when no match is found."
13507 (let* ((limit (if (< n 0) (point-min) (point-max)))
13508 (search-func (if (< n 0)
13509 'previous-single-char-property-change
13510 'next-single-char-property-change))
13511 (n (abs n))
13512 (pos (point))
13514 (catch 'exit
13515 (while (setq p1 (funcall search-func (point) 'org-type))
13516 (when (equal p1 limit)
13517 (goto-char pos)
13518 (error "No more matches"))
13519 (when (equal (get-char-property p1 'org-type) 'org-occur)
13520 (setq n (1- n))
13521 (when (= n 0)
13522 (goto-char p1)
13523 (throw 'exit (point))))
13524 (goto-char p1))
13525 (goto-char p1)
13526 (error "No more matches"))))
13528 (defun org-show-context (&optional key)
13529 "Make sure point and context are visible.
13530 How much context is shown depends upon the variables
13531 `org-show-hierarchy-above', `org-show-following-heading',
13532 `org-show-entry-below' and `org-show-siblings'."
13533 (let ((heading-p (org-at-heading-p t))
13534 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13535 (following-p (org-get-alist-option org-show-following-heading key))
13536 (entry-p (org-get-alist-option org-show-entry-below key))
13537 (siblings-p (org-get-alist-option org-show-siblings key)))
13538 ;; Show heading or entry text
13539 (if (and heading-p (not entry-p))
13540 (org-flag-heading nil) ; only show the heading
13541 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13542 (org-show-hidden-entry))) ; show entire entry
13543 (when following-p
13544 ;; Show next sibling, or heading below text
13545 (save-excursion
13546 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13547 (org-flag-heading nil))))
13548 (when siblings-p (org-show-siblings))
13549 (when hierarchy-p
13550 ;; show all higher headings, possibly with siblings
13551 (save-excursion
13552 (while (and (condition-case nil
13553 (progn (org-up-heading-all 1) t)
13554 (error nil))
13555 (not (bobp)))
13556 (org-flag-heading nil)
13557 (when siblings-p (org-show-siblings)))))
13558 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13560 (defvar org-reveal-start-hook nil
13561 "Hook run before revealing a location.")
13563 (defun org-reveal (&optional siblings)
13564 "Show current entry, hierarchy above it, and the following headline.
13565 This can be used to show a consistent set of context around locations
13566 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13567 not t for the search context.
13569 With optional argument SIBLINGS, on each level of the hierarchy all
13570 siblings are shown. This repairs the tree structure to what it would
13571 look like when opened with hierarchical calls to `org-cycle'.
13572 With double optional argument \\[universal-argument] \\[universal-argument], \
13573 go to the parent and show the
13574 entire tree."
13575 (interactive "P")
13576 (run-hooks 'org-reveal-start-hook)
13577 (let ((org-show-hierarchy-above t)
13578 (org-show-following-heading t)
13579 (org-show-siblings (if siblings t org-show-siblings)))
13580 (org-show-context nil))
13581 (when (equal siblings '(16))
13582 (save-excursion
13583 (when (org-up-heading-safe)
13584 (org-show-subtree)
13585 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13587 (defun org-highlight-new-match (beg end)
13588 "Highlight from BEG to END and mark the highlight is an occur headline."
13589 (let ((ov (make-overlay beg end)))
13590 (overlay-put ov 'face 'secondary-selection)
13591 (overlay-put ov 'org-type 'org-occur)
13592 (push ov org-occur-highlights)))
13594 (defun org-remove-occur-highlights (&optional beg end noremove)
13595 "Remove the occur highlights from the buffer.
13596 BEG and END are ignored. If NOREMOVE is nil, remove this function
13597 from the `before-change-functions' in the current buffer."
13598 (interactive)
13599 (unless org-inhibit-highlight-removal
13600 (mapc 'delete-overlay org-occur-highlights)
13601 (setq org-occur-highlights nil)
13602 (setq org-occur-parameters nil)
13603 (unless noremove
13604 (remove-hook 'before-change-functions
13605 'org-remove-occur-highlights 'local))))
13607 ;;;; Priorities
13609 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13610 "Regular expression matching the priority indicator.")
13612 (defvar org-remove-priority-next-time nil)
13614 (defun org-priority-up ()
13615 "Increase the priority of the current item."
13616 (interactive)
13617 (org-priority 'up))
13619 (defun org-priority-down ()
13620 "Decrease the priority of the current item."
13621 (interactive)
13622 (org-priority 'down))
13624 (defun org-priority (&optional action show)
13625 "Change the priority of an item.
13626 ACTION can be `set', `up', `down', or a character."
13627 (interactive "P")
13628 (if (equal action '(4))
13629 (org-show-priority)
13630 (unless org-enable-priority-commands
13631 (user-error "Priority commands are disabled"))
13632 (setq action (or action 'set))
13633 (let (current new news have remove)
13634 (save-excursion
13635 (org-back-to-heading t)
13636 (if (looking-at org-priority-regexp)
13637 (setq current (string-to-char (match-string 2))
13638 have t))
13639 (cond
13640 ((eq action 'remove)
13641 (setq remove t new ?\ ))
13642 ((or (eq action 'set)
13643 (if (featurep 'xemacs) (characterp action) (integerp action)))
13644 (if (not (eq action 'set))
13645 (setq new action)
13646 (message "Priority %c-%c, SPC to remove: "
13647 org-highest-priority org-lowest-priority)
13648 (save-match-data
13649 (setq new (read-char-exclusive))))
13650 (if (and (= (upcase org-highest-priority) org-highest-priority)
13651 (= (upcase org-lowest-priority) org-lowest-priority))
13652 (setq new (upcase new)))
13653 (cond ((equal new ?\ ) (setq remove t))
13654 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13655 (user-error "Priority must be between `%c' and `%c'"
13656 org-highest-priority org-lowest-priority))))
13657 ((eq action 'up)
13658 (setq new (if have
13659 (1- current) ; normal cycling
13660 ;; last priority was empty
13661 (if (eq last-command this-command)
13662 org-lowest-priority ; wrap around empty to lowest
13663 ;; default
13664 (if org-priority-start-cycle-with-default
13665 org-default-priority
13666 (1- org-default-priority))))))
13667 ((eq action 'down)
13668 (setq new (if have
13669 (1+ current) ; normal cycling
13670 ;; last priority was empty
13671 (if (eq last-command this-command)
13672 org-highest-priority ; wrap around empty to highest
13673 ;; default
13674 (if org-priority-start-cycle-with-default
13675 org-default-priority
13676 (1+ org-default-priority))))))
13677 (t (user-error "Invalid action")))
13678 (if (or (< (upcase new) org-highest-priority)
13679 (> (upcase new) org-lowest-priority))
13680 (if (and (memq action '(up down))
13681 (not have) (not (eq last-command this-command)))
13682 ;; `new' is from default priority
13683 (error
13684 "The default can not be set, see `org-default-priority' why")
13685 ;; normal cycling: `new' is beyond highest/lowest priority
13686 ;; and is wrapped around to the empty priority
13687 (setq remove t)))
13688 (setq news (format "%c" new))
13689 (if have
13690 (if remove
13691 (replace-match "" t t nil 1)
13692 (replace-match news t t nil 2))
13693 (if remove
13694 (user-error "No priority cookie found in line")
13695 (let ((case-fold-search nil))
13696 (looking-at org-todo-line-regexp))
13697 (if (match-end 2)
13698 (progn
13699 (goto-char (match-end 2))
13700 (insert " [#" news "]"))
13701 (goto-char (match-beginning 3))
13702 (insert "[#" news "] "))))
13703 (org-preserve-lc (org-set-tags nil 'align)))
13704 (if remove
13705 (message "Priority removed")
13706 (message "Priority of current item set to %s" news)))))
13708 (defun org-show-priority ()
13709 "Show the priority of the current item.
13710 This priority is composed of the main priority given with the [#A] cookies,
13711 and by additional input from the age of a schedules or deadline entry."
13712 (interactive)
13713 (let ((pri (if (eq major-mode 'org-agenda-mode)
13714 (org-get-at-bol 'priority)
13715 (save-excursion
13716 (save-match-data
13717 (beginning-of-line)
13718 (and (looking-at org-heading-regexp)
13719 (org-get-priority (match-string 0))))))))
13720 (message "Priority is %d" (if pri pri -1000))))
13722 (defun org-get-priority (s)
13723 "Find priority cookie and return priority."
13724 (save-match-data
13725 (if (functionp org-get-priority-function)
13726 (funcall org-get-priority-function)
13727 (if (not (string-match org-priority-regexp s))
13728 (* 1000 (- org-lowest-priority org-default-priority))
13729 (* 1000 (- org-lowest-priority
13730 (string-to-char (match-string 2 s))))))))
13732 ;;;; Tags
13734 (defvar org-agenda-archives-mode)
13735 (defvar org-map-continue-from nil
13736 "Position from where mapping should continue.
13737 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13739 (defvar org-scanner-tags nil
13740 "The current tag list while the tags scanner is running.")
13741 (defvar org-trust-scanner-tags nil
13742 "Should `org-get-tags-at' use the tags for the scanner.
13743 This is for internal dynamical scoping only.
13744 When this is non-nil, the function `org-get-tags-at' will return the value
13745 of `org-scanner-tags' instead of building the list by itself. This
13746 can lead to large speed-ups when the tags scanner is used in a file with
13747 many entries, and when the list of tags is retrieved, for example to
13748 obtain a list of properties. Building the tags list for each entry in such
13749 a file becomes an N^2 operation - but with this variable set, it scales
13750 as N.")
13752 (defun org-scan-tags (action matcher todo-only &optional start-level)
13753 "Sca headline tags with inheritance and produce output ACTION.
13755 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13756 or `agenda' to produce an entry list for an agenda view. It can also be
13757 a Lisp form or a function that should be called at each matched headline, in
13758 this case the return value is a list of all return values from these calls.
13760 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13761 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13762 only lines with a not-done TODO keyword are included in the output.
13763 This should be the same variable that was scoped into
13764 and set by `org-make-tags-matcher' when it constructed MATCHER.
13766 START-LEVEL can be a string with asterisks, reducing the scope to
13767 headlines matching this string."
13768 (require 'org-agenda)
13769 (let* ((re (concat "^"
13770 (if start-level
13771 ;; Get the correct level to match
13772 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13773 org-outline-regexp)
13774 " *\\(\\<\\("
13775 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13776 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13777 (props (list 'face 'default
13778 'done-face 'org-agenda-done
13779 'undone-face 'default
13780 'mouse-face 'highlight
13781 'org-not-done-regexp org-not-done-regexp
13782 'org-todo-regexp org-todo-regexp
13783 'org-complex-heading-regexp org-complex-heading-regexp
13784 'help-echo
13785 (format "mouse-2 or RET jump to org file %s"
13786 (abbreviate-file-name
13787 (or (buffer-file-name (buffer-base-buffer))
13788 (buffer-name (buffer-base-buffer)))))))
13789 (org-map-continue-from nil)
13790 lspos tags tags-list
13791 (tags-alist (list (cons 0 org-file-tags)))
13792 (llast 0) rtn rtn1 level category i txt
13793 todo marker entry priority)
13794 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13795 (setq action (list 'lambda nil action)))
13796 (save-excursion
13797 (goto-char (point-min))
13798 (when (eq action 'sparse-tree)
13799 (org-overview)
13800 (org-remove-occur-highlights))
13801 (while (let (case-fold-search)
13802 (re-search-forward re nil t))
13803 (setq org-map-continue-from nil)
13804 (catch :skip
13805 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13806 tags (if (match-end 4) (org-match-string-no-properties 4)))
13807 (goto-char (setq lspos (match-beginning 0)))
13808 (setq level (org-reduced-level (org-outline-level))
13809 category (org-get-category))
13810 (setq i llast llast level)
13811 ;; remove tag lists from same and sublevels
13812 (while (>= i level)
13813 (when (setq entry (assoc i tags-alist))
13814 (setq tags-alist (delete entry tags-alist)))
13815 (setq i (1- i)))
13816 ;; add the next tags
13817 (when tags
13818 (setq tags (org-split-string tags ":")
13819 tags-alist
13820 (cons (cons level tags) tags-alist)))
13821 ;; compile tags for current headline
13822 (setq tags-list
13823 (if org-use-tag-inheritance
13824 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13825 tags)
13826 org-scanner-tags tags-list)
13827 (when org-use-tag-inheritance
13828 (setcdr (car tags-alist)
13829 (mapcar (lambda (x)
13830 (setq x (copy-sequence x))
13831 (org-add-prop-inherited x))
13832 (cdar tags-alist))))
13833 (when (and tags org-use-tag-inheritance
13834 (or (not (eq t org-use-tag-inheritance))
13835 org-tags-exclude-from-inheritance))
13836 ;; selective inheritance, remove uninherited ones
13837 (setcdr (car tags-alist)
13838 (org-remove-uninherited-tags (cdar tags-alist))))
13839 (when (and
13841 ;; eval matcher only when the todo condition is OK
13842 (and (or (not todo-only) (member todo org-not-done-keywords))
13843 (let ((case-fold-search t) (org-trust-scanner-tags t))
13844 (eval matcher)))
13846 ;; Call the skipper, but return t if it does not skip,
13847 ;; so that the `and' form continues evaluating
13848 (progn
13849 (unless (eq action 'sparse-tree) (org-agenda-skip))
13852 ;; Check if timestamps are deselecting this entry
13853 (or (not todo-only)
13854 (and (member todo org-not-done-keywords)
13855 (or (not org-agenda-tags-todo-honor-ignore-options)
13856 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13858 ;; select this headline
13859 (cond
13860 ((eq action 'sparse-tree)
13861 (and org-highlight-sparse-tree-matches
13862 (org-get-heading) (match-end 0)
13863 (org-highlight-new-match
13864 (match-beginning 1) (match-end 1)))
13865 (org-show-context 'tags-tree))
13866 ((eq action 'agenda)
13867 (setq txt (org-agenda-format-item
13869 (concat
13870 (if (eq org-tags-match-list-sublevels 'indented)
13871 (make-string (1- level) ?.) "")
13872 (org-get-heading))
13873 level category
13874 tags-list)
13875 priority (org-get-priority txt))
13876 (goto-char lspos)
13877 (setq marker (org-agenda-new-marker))
13878 (org-add-props txt props
13879 'org-marker marker 'org-hd-marker marker 'org-category category
13880 'todo-state todo
13881 'priority priority 'type "tagsmatch")
13882 (push txt rtn))
13883 ((functionp action)
13884 (setq org-map-continue-from nil)
13885 (save-excursion
13886 (setq rtn1 (funcall action))
13887 (push rtn1 rtn)))
13888 (t (user-error "Invalid action")))
13890 ;; if we are to skip sublevels, jump to end of subtree
13891 (unless org-tags-match-list-sublevels
13892 (org-end-of-subtree t)
13893 (backward-char 1))))
13894 ;; Get the correct position from where to continue
13895 (if org-map-continue-from
13896 (goto-char org-map-continue-from)
13897 (and (= (point) lspos) (end-of-line 1)))))
13898 (when (and (eq action 'sparse-tree)
13899 (not org-sparse-tree-open-archived-trees))
13900 (org-hide-archived-subtrees (point-min) (point-max)))
13901 (nreverse rtn)))
13903 (defun org-remove-uninherited-tags (tags)
13904 "Remove all tags that are not inherited from the list TAGS."
13905 (cond
13906 ((eq org-use-tag-inheritance t)
13907 (if org-tags-exclude-from-inheritance
13908 (org-delete-all org-tags-exclude-from-inheritance tags)
13909 tags))
13910 ((not org-use-tag-inheritance) nil)
13911 ((stringp org-use-tag-inheritance)
13912 (delq nil (mapcar
13913 (lambda (x)
13914 (if (and (string-match org-use-tag-inheritance x)
13915 (not (member x org-tags-exclude-from-inheritance)))
13916 x nil))
13917 tags)))
13918 ((listp org-use-tag-inheritance)
13919 (delq nil (mapcar
13920 (lambda (x)
13921 (if (member x org-use-tag-inheritance) x nil))
13922 tags)))))
13924 (defun org-match-sparse-tree (&optional todo-only match)
13925 "Create a sparse tree according to tags string MATCH.
13926 MATCH can contain positive and negative selection of tags, like
13927 \"+WORK+URGENT-WITHBOSS\".
13928 If optional argument TODO-ONLY is non-nil, only select lines that are
13929 also TODO lines."
13930 (interactive "P")
13931 (org-agenda-prepare-buffers (list (current-buffer)))
13932 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13934 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13936 (defvar org-cached-props nil)
13937 (defun org-cached-entry-get (pom property)
13938 (if (or (eq t org-use-property-inheritance)
13939 (and (stringp org-use-property-inheritance)
13940 (string-match org-use-property-inheritance property))
13941 (and (listp org-use-property-inheritance)
13942 (member property org-use-property-inheritance)))
13943 ;; Caching is not possible, check it directly
13944 (org-entry-get pom property 'inherit)
13945 ;; Get all properties, so that we can do complicated checks easily
13946 (cdr (assoc property (or org-cached-props
13947 (setq org-cached-props
13948 (org-entry-properties pom)))))))
13950 (defun org-global-tags-completion-table (&optional files)
13951 "Return the list of all tags in all agenda buffer/files.
13952 Optional FILES argument is a list of files which can be used
13953 instead of the agenda files."
13954 (save-excursion
13955 (org-uniquify
13956 (delq nil
13957 (apply 'append
13958 (mapcar
13959 (lambda (file)
13960 (set-buffer (find-file-noselect file))
13961 (append (org-get-buffer-tags)
13962 (mapcar (lambda (x) (if (stringp (car-safe x))
13963 (list (car-safe x)) nil))
13964 org-tag-alist)))
13965 (if (and files (car files))
13966 files
13967 (org-agenda-files))))))))
13969 (defun org-make-tags-matcher (match)
13970 "Create the TAGS/TODO matcher form for the selection string MATCH.
13972 The variable `todo-only' is scoped dynamically into this function.
13973 It will be set to t if the matcher restricts matching to TODO entries,
13974 otherwise will not be touched.
13976 Returns a cons of the selection string MATCH and the constructed
13977 lisp form implementing the matcher. The matcher is to be evaluated
13978 at an Org entry, with point on the headline, and returns t if the
13979 entry matches the selection string MATCH. The returned lisp form
13980 references two variables with information about the entry, which
13981 must be bound around the form's evaluation: todo, the TODO keyword
13982 at the entry (or nil of none); and tags-list, the list of all tags
13983 at the entry including inherited ones. Additionally, the category
13984 of the entry (if any) must be specified as the text property
13985 'org-category on the headline.
13987 See also `org-scan-tags'.
13989 (declare (special todo-only))
13990 (unless (boundp 'todo-only)
13991 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13992 (unless match
13993 ;; Get a new match request, with completion against the global
13994 ;; tags table and the local tags in current buffer
13995 (let ((org-last-tags-completion-table
13996 (org-uniquify
13997 (delq nil (append (org-get-buffer-tags)
13998 (org-global-tags-completion-table))))))
13999 (setq match (org-completing-read-no-i
14000 "Match: " 'org-tags-completion-function nil nil nil
14001 'org-tags-history))))
14003 ;; Parse the string and create a lisp form
14004 (let ((match0 match)
14005 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14006 minus tag mm
14007 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14008 orterms term orlist re-p str-p level-p level-op time-p
14009 prop-p pn pv po gv rest)
14010 ;; Expand group tags
14011 (setq match (org-tags-expand match))
14012 (if (string-match "/+" match)
14013 ;; match contains also a todo-matching request
14014 (progn
14015 (setq tagsmatch (substring match 0 (match-beginning 0))
14016 todomatch (substring match (match-end 0)))
14017 (if (string-match "^!" todomatch)
14018 (setq todo-only t todomatch (substring todomatch 1)))
14019 (if (string-match "^\\s-*$" todomatch)
14020 (setq todomatch nil)))
14021 ;; only matching tags
14022 (setq tagsmatch match todomatch nil))
14024 ;; Make the tags matcher
14025 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14026 (setq tagsmatcher t)
14027 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14028 (while (setq term (pop orterms))
14029 (while (and (equal (substring term -1) "\\") orterms)
14030 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14031 (while (string-match re term)
14032 (setq rest (substring term (match-end 0))
14033 minus (and (match-end 1)
14034 (equal (match-string 1 term) "-"))
14035 tag (save-match-data (replace-regexp-in-string
14036 "\\\\-" "-"
14037 (match-string 2 term)))
14038 re-p (equal (string-to-char tag) ?{)
14039 level-p (match-end 4)
14040 prop-p (match-end 5)
14041 mm (cond
14042 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14043 (level-p
14044 (setq level-op (org-op-to-function (match-string 3 term)))
14045 `(,level-op level ,(string-to-number
14046 (match-string 4 term))))
14047 (prop-p
14048 (setq pn (match-string 5 term)
14049 po (match-string 6 term)
14050 pv (match-string 7 term)
14051 re-p (equal (string-to-char pv) ?{)
14052 str-p (equal (string-to-char pv) ?\")
14053 time-p (save-match-data
14054 (string-match "^\"[[<].*[]>]\"$" pv))
14055 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14056 (if time-p (setq pv (org-matcher-time pv)))
14057 (setq po (org-op-to-function po (if time-p 'time str-p)))
14058 (cond
14059 ((equal pn "CATEGORY")
14060 (setq gv '(get-text-property (point) 'org-category)))
14061 ((equal pn "TODO")
14062 (setq gv 'todo))
14064 (setq gv `(org-cached-entry-get nil ,pn))))
14065 (if re-p
14066 (if (eq po 'org<>)
14067 `(not (string-match ,pv (or ,gv "")))
14068 `(string-match ,pv (or ,gv "")))
14069 (if str-p
14070 `(,po (or ,gv "") ,pv)
14071 `(,po (string-to-number (or ,gv ""))
14072 ,(string-to-number pv) ))))
14073 (t `(member ,tag tags-list)))
14074 mm (if minus (list 'not mm) mm)
14075 term rest)
14076 (push mm tagsmatcher))
14077 (push (if (> (length tagsmatcher) 1)
14078 (cons 'and tagsmatcher)
14079 (car tagsmatcher))
14080 orlist)
14081 (setq tagsmatcher nil))
14082 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14083 (setq tagsmatcher
14084 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14085 ;; Make the todo matcher
14086 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14087 (setq todomatcher t)
14088 (setq orterms (org-split-string todomatch "|") orlist nil)
14089 (while (setq term (pop orterms))
14090 (while (string-match re term)
14091 (setq minus (and (match-end 1)
14092 (equal (match-string 1 term) "-"))
14093 kwd (match-string 2 term)
14094 re-p (equal (string-to-char kwd) ?{)
14095 term (substring term (match-end 0))
14096 mm (if re-p
14097 `(string-match ,(substring kwd 1 -1) todo)
14098 (list 'equal 'todo kwd))
14099 mm (if minus (list 'not mm) mm))
14100 (push mm todomatcher))
14101 (push (if (> (length todomatcher) 1)
14102 (cons 'and todomatcher)
14103 (car todomatcher))
14104 orlist)
14105 (setq todomatcher nil))
14106 (setq todomatcher (if (> (length orlist) 1)
14107 (cons 'or orlist) (car orlist))))
14109 ;; Return the string and lisp forms of the matcher
14110 (setq matcher (if todomatcher
14111 (list 'and tagsmatcher todomatcher)
14112 tagsmatcher))
14113 (when todo-only
14114 (setq matcher (list 'and '(member todo org-not-done-keywords)
14115 matcher)))
14116 (cons match0 matcher)))
14118 (defun org-tags-expand (match &optional single-as-list downcased)
14119 "Expand group tags in MATCH.
14121 This replaces every group tag in MATCH with a regexp tag search.
14122 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14123 will be replaced like this:
14125 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14126 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14127 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14129 Replacing by a regexp preserves the structure of the match.
14130 E.g., this expansion
14132 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14134 will match anything tagged with \"Lab\" and \"Home\", or tagged
14135 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14137 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14138 assumed to be a single group tag, and the function will return
14139 the list of tags in this group.
14141 When DOWNCASE is non-nil, expand downcased TAGS."
14142 (if org-group-tags
14143 (let* ((case-fold-search t)
14144 (stable org-mode-syntax-table)
14145 (tal (or org-tag-groups-alist-for-agenda
14146 org-tag-groups-alist))
14147 (tal (if downcased
14148 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14149 (tml (mapcar 'car tal))
14150 (rtnmatch match) rpl)
14151 ;; @ and _ are allowed as word-components in tags
14152 (modify-syntax-entry ?@ "w" stable)
14153 (modify-syntax-entry ?_ "w" stable)
14154 (while (and tml
14155 (with-syntax-table stable
14156 (string-match
14157 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14158 (regexp-opt tml) "\\>\\)") rtnmatch)))
14159 (let* ((dir (match-string 1 rtnmatch))
14160 (tag (match-string 2 rtnmatch))
14161 (tag (if downcased (downcase tag) tag)))
14162 (setq tml (delete tag tml))
14163 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14164 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14165 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14166 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14167 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14168 (if single-as-list
14169 (or (reverse rpl) (list rtnmatch))
14170 rtnmatch))
14171 (if single-as-list (list (if downcased (downcase match) match))
14172 match)))
14174 (defun org-op-to-function (op &optional stringp)
14175 "Turn an operator into the appropriate function."
14176 (setq op
14177 (cond
14178 ((equal op "<" ) '(< string< org-time<))
14179 ((equal op ">" ) '(> org-string> org-time>))
14180 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14181 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14182 ((member op '("=" "==")) '(= string= org-time=))
14183 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14184 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14186 (defun org<> (a b) (not (= a b)))
14187 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14188 (defun org-string>= (a b) (not (string< a b)))
14189 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14190 (defun org-string<> (a b) (not (string= a b)))
14191 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14192 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14193 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14194 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14195 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14196 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14197 (defun org-2ft (s)
14198 "Convert S to a floating point time.
14199 If S is already a number, just return it. If it is a string, parse
14200 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14201 (cond
14202 ((numberp s) s)
14203 ((stringp s)
14204 (condition-case nil
14205 (float-time (apply 'encode-time (org-parse-time-string s)))
14206 (error 0.)))
14207 (t 0.)))
14209 (defun org-time-today ()
14210 "Time in seconds today at 0:00.
14211 Returns the float number of seconds since the beginning of the
14212 epoch to the beginning of today (00:00)."
14213 (float-time (apply 'encode-time
14214 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14216 (defun org-matcher-time (s)
14217 "Interpret a time comparison value."
14218 (save-match-data
14219 (cond
14220 ((string= s "<now>") (float-time))
14221 ((string= s "<today>") (org-time-today))
14222 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14223 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14224 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14225 (+ (org-time-today)
14226 (* (string-to-number (match-string 1 s))
14227 (cdr (assoc (match-string 2 s)
14228 '(("d" . 86400.0) ("w" . 604800.0)
14229 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14230 (t (org-2ft s)))))
14232 (defun org-match-any-p (re list)
14233 "Does re match any element of list?"
14234 (setq list (mapcar (lambda (x) (string-match re x)) list))
14235 (delq nil list))
14237 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14238 (defvar org-tags-overlay (make-overlay 1 1))
14239 (org-detach-overlay org-tags-overlay)
14241 (defun org-get-local-tags-at (&optional pos)
14242 "Get a list of tags defined in the current headline."
14243 (org-get-tags-at pos 'local))
14245 (defun org-get-local-tags ()
14246 "Get a list of tags defined in the current headline."
14247 (org-get-tags-at nil 'local))
14249 (defun org-get-tags-at (&optional pos local)
14250 "Get a list of all headline tags applicable at POS.
14251 POS defaults to point. If tags are inherited, the list contains
14252 the targets in the same sequence as the headlines appear, i.e.
14253 the tags of the current headline come last.
14254 When LOCAL is non-nil, only return tags from the current headline,
14255 ignore inherited ones."
14256 (interactive)
14257 (if (and org-trust-scanner-tags
14258 (or (not pos) (equal pos (point)))
14259 (not local))
14260 org-scanner-tags
14261 (let (tags ltags lastpos parent)
14262 (save-excursion
14263 (save-restriction
14264 (widen)
14265 (goto-char (or pos (point)))
14266 (save-match-data
14267 (catch 'done
14268 (condition-case nil
14269 (progn
14270 (org-back-to-heading t)
14271 (while (not (equal lastpos (point)))
14272 (setq lastpos (point))
14273 (when (looking-at
14274 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14275 (setq ltags (org-split-string
14276 (org-match-string-no-properties 1) ":"))
14277 (when parent
14278 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14279 (setq tags (append
14280 (if parent
14281 (org-remove-uninherited-tags ltags)
14282 ltags)
14283 tags)))
14284 (or org-use-tag-inheritance (throw 'done t))
14285 (if local (throw 'done t))
14286 (or (org-up-heading-safe) (error nil))
14287 (setq parent t)))
14288 (error nil)))))
14289 (if local
14290 tags
14291 (reverse (delete-dups
14292 (reverse (append
14293 (org-remove-uninherited-tags
14294 org-file-tags) tags)))))))))
14296 (defun org-add-prop-inherited (s)
14297 (add-text-properties 0 (length s) '(inherited t) s)
14300 (defun org-toggle-tag (tag &optional onoff)
14301 "Toggle the tag TAG for the current line.
14302 If ONOFF is `on' or `off', don't toggle but set to this state."
14303 (let (res current)
14304 (save-excursion
14305 (org-back-to-heading t)
14306 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14307 (point-at-eol) t)
14308 (progn
14309 (setq current (match-string 1))
14310 (replace-match ""))
14311 (setq current ""))
14312 (setq current (nreverse (org-split-string current ":")))
14313 (cond
14314 ((eq onoff 'on)
14315 (setq res t)
14316 (or (member tag current) (push tag current)))
14317 ((eq onoff 'off)
14318 (or (not (member tag current)) (setq current (delete tag current))))
14319 (t (if (member tag current)
14320 (setq current (delete tag current))
14321 (setq res t)
14322 (push tag current))))
14323 (end-of-line 1)
14324 (if current
14325 (progn
14326 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14327 (org-set-tags nil t))
14328 (delete-horizontal-space))
14329 (run-hooks 'org-after-tags-change-hook))
14330 res))
14332 (defun org-align-tags-here (to-col)
14333 ;; Assumes that this is a headline
14334 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14335 (beginning-of-line 1)
14336 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14337 (< pos (match-beginning 2)))
14338 (progn
14339 (setq tags-l (- (match-end 2) (match-beginning 2)))
14340 (goto-char (match-beginning 1))
14341 (insert " ")
14342 (delete-region (point) (1+ (match-beginning 2)))
14343 (setq ncol (max (current-column)
14344 (1+ col)
14345 (if (> to-col 0)
14346 to-col
14347 (- (abs to-col) tags-l))))
14348 (setq p (point))
14349 (insert (make-string (- ncol (current-column)) ?\ ))
14350 (setq ncol (current-column))
14351 (when indent-tabs-mode (tabify p (point-at-eol)))
14352 (org-move-to-column (min ncol col) t))
14353 (goto-char pos))))
14355 (defun org-set-tags-command (&optional arg just-align)
14356 "Call the set-tags command for the current entry."
14357 (interactive "P")
14358 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14359 (org-set-tags arg just-align)
14360 (save-excursion
14361 (unless (and (org-region-active-p)
14362 org-loop-over-headlines-in-active-region)
14363 (org-back-to-heading t))
14364 (org-set-tags arg just-align))))
14366 (defun org-set-tags-to (data)
14367 "Set the tags of the current entry to DATA, replacing the current tags.
14368 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14369 If DATA is nil or the empty string, any tags will be removed."
14370 (interactive "sTags: ")
14371 (setq data
14372 (cond
14373 ((eq data nil) "")
14374 ((equal data "") "")
14375 ((stringp data)
14376 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14377 ":"))
14378 ((listp data)
14379 (concat ":" (mapconcat 'identity data ":") ":"))))
14380 (when data
14381 (save-excursion
14382 (org-back-to-heading t)
14383 (when (looking-at org-complex-heading-regexp)
14384 (if (match-end 5)
14385 (progn
14386 (goto-char (match-beginning 5))
14387 (insert data)
14388 (delete-region (point) (point-at-eol))
14389 (org-set-tags nil 'align))
14390 (goto-char (point-at-eol))
14391 (insert " " data)
14392 (org-set-tags nil 'align)))
14393 (beginning-of-line 1)
14394 (if (looking-at ".*?\\([ \t]+\\)$")
14395 (delete-region (match-beginning 1) (match-end 1))))))
14397 (defun org-align-all-tags ()
14398 "Align the tags i all headings."
14399 (interactive)
14400 (save-excursion
14401 (or (ignore-errors (org-back-to-heading t))
14402 (outline-next-heading))
14403 (if (org-at-heading-p)
14404 (org-set-tags t)
14405 (message "No headings"))))
14407 (defvar org-indent-indentation-per-level)
14408 (defun org-set-tags (&optional arg just-align)
14409 "Set the tags for the current headline.
14410 With prefix ARG, realign all tags in headings in the current buffer."
14411 (interactive "P")
14412 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14413 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14414 'region-start-level 'region))
14415 org-loop-over-headlines-in-active-region)
14416 (org-map-entries
14417 ;; We don't use ARG and JUST-ALIGN here these args are not
14418 ;; useful when looping over headlines
14419 `(org-set-tags)
14420 org-loop-over-headlines-in-active-region
14421 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14422 (let* ((re org-outline-regexp-bol)
14423 (current (unless arg (org-get-tags-string)))
14424 (col (current-column))
14425 (org-setting-tags t)
14426 table current-tags inherited-tags ; computed below when needed
14427 tags p0 c0 c1 rpl di tc level)
14428 (if arg
14429 (save-excursion
14430 (goto-char (point-min))
14431 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14432 (while (re-search-forward re nil t)
14433 (org-set-tags nil t)
14434 (end-of-line 1)))
14435 (message "All tags realigned to column %d" org-tags-column))
14436 (if just-align
14437 (setq tags current)
14438 ;; Get a new set of tags from the user
14439 (save-excursion
14440 (setq table (append org-tag-persistent-alist
14441 (or org-tag-alist (org-get-buffer-tags))
14442 (and
14443 org-complete-tags-always-offer-all-agenda-tags
14444 (org-global-tags-completion-table
14445 (org-agenda-files))))
14446 org-last-tags-completion-table table
14447 current-tags (org-split-string current ":")
14448 inherited-tags (nreverse
14449 (nthcdr (length current-tags)
14450 (nreverse (org-get-tags-at))))
14451 tags
14452 (if (or (eq t org-use-fast-tag-selection)
14453 (and org-use-fast-tag-selection
14454 (delq nil (mapcar 'cdr table))))
14455 (org-fast-tag-selection
14456 current-tags inherited-tags table
14457 (if org-fast-tag-selection-include-todo
14458 org-todo-key-alist))
14459 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14460 (org-trim
14461 (org-icompleting-read "Tags: "
14462 'org-tags-completion-function
14463 nil nil current 'org-tags-history))))))
14464 (while (string-match "[-+&]+" tags)
14465 ;; No boolean logic, just a list
14466 (setq tags (replace-match ":" t t tags))))
14468 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14470 (if org-tags-sort-function
14471 (setq tags (mapconcat 'identity
14472 (sort (org-split-string
14473 tags (org-re "[^[:alnum:]_@#%]+"))
14474 org-tags-sort-function) ":")))
14476 (if (string-match "\\`[\t ]*\\'" tags)
14477 (setq tags "")
14478 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14479 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14481 ;; Insert new tags at the correct column
14482 (beginning-of-line 1)
14483 (setq level (or (and (looking-at org-outline-regexp)
14484 (- (match-end 0) (point) 1))
14486 (cond
14487 ((and (equal current "") (equal tags "")))
14488 ((re-search-forward
14489 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14490 (point-at-eol) t)
14491 (if (equal tags "")
14492 (setq rpl "")
14493 (goto-char (match-beginning 0))
14494 (setq c0 (current-column)
14495 ;; compute offset for the case of org-indent-mode active
14496 di (if org-indent-mode
14497 (* (1- org-indent-indentation-per-level) (1- level))
14499 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14500 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14501 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14502 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14503 (replace-match rpl t t)
14504 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14505 tags)
14506 (t (error "Tags alignment failed")))
14507 (org-move-to-column col)
14508 (unless just-align
14509 (run-hooks 'org-after-tags-change-hook))))))
14511 (defun org-change-tag-in-region (beg end tag off)
14512 "Add or remove TAG for each entry in the region.
14513 This works in the agenda, and also in an org-mode buffer."
14514 (interactive
14515 (list (region-beginning) (region-end)
14516 (let ((org-last-tags-completion-table
14517 (if (derived-mode-p 'org-mode)
14518 (org-uniquify
14519 (delq nil (append (org-get-buffer-tags)
14520 (org-global-tags-completion-table))))
14521 (org-global-tags-completion-table))))
14522 (org-icompleting-read
14523 "Tag: " 'org-tags-completion-function nil nil nil
14524 'org-tags-history))
14525 (progn
14526 (message "[s]et or [r]emove? ")
14527 (equal (read-char-exclusive) ?r))))
14528 (if (fboundp 'deactivate-mark) (deactivate-mark))
14529 (let ((agendap (equal major-mode 'org-agenda-mode))
14530 l1 l2 m buf pos newhead (cnt 0))
14531 (goto-char end)
14532 (setq l2 (1- (org-current-line)))
14533 (goto-char beg)
14534 (setq l1 (org-current-line))
14535 (loop for l from l1 to l2 do
14536 (org-goto-line l)
14537 (setq m (get-text-property (point) 'org-hd-marker))
14538 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14539 (and agendap m))
14540 (setq buf (if agendap (marker-buffer m) (current-buffer))
14541 pos (if agendap m (point)))
14542 (with-current-buffer buf
14543 (save-excursion
14544 (save-restriction
14545 (goto-char pos)
14546 (setq cnt (1+ cnt))
14547 (org-toggle-tag tag (if off 'off 'on))
14548 (setq newhead (org-get-heading)))))
14549 (and agendap (org-agenda-change-all-lines newhead m))))
14550 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14552 (defun org-tags-completion-function (string predicate &optional flag)
14553 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14554 (confirm (lambda (x) (stringp (car x)))))
14555 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14556 (setq s1 (match-string 1 string)
14557 s2 (match-string 2 string))
14558 (setq s1 "" s2 string))
14559 (cond
14560 ((eq flag nil)
14561 ;; try completion
14562 (setq rtn (try-completion s2 ctable confirm))
14563 (if (stringp rtn)
14564 (setq rtn
14565 (concat s1 s2 (substring rtn (length s2))
14566 (if (and org-add-colon-after-tag-completion
14567 (assoc rtn ctable))
14568 ":" ""))))
14569 rtn)
14570 ((eq flag t)
14571 ;; all-completions
14572 (all-completions s2 ctable confirm))
14573 ((eq flag 'lambda)
14574 ;; exact match?
14575 (assoc s2 ctable)))))
14577 (defun org-fast-tag-insert (kwd tags face &optional end)
14578 "Insert KDW, and the TAGS, the latter with face FACE.
14579 Also insert END."
14580 (insert (format "%-12s" (concat kwd ":"))
14581 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14582 (or end "")))
14584 (defun org-fast-tag-show-exit (flag)
14585 (save-excursion
14586 (org-goto-line 3)
14587 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14588 (replace-match ""))
14589 (when flag
14590 (end-of-line 1)
14591 (org-move-to-column (- (window-width) 19) t)
14592 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14594 (defun org-set-current-tags-overlay (current prefix)
14595 "Add an overlay to CURRENT tag with PREFIX."
14596 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14597 (if (featurep 'xemacs)
14598 (org-overlay-display org-tags-overlay (concat prefix s)
14599 'secondary-selection)
14600 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14601 (org-overlay-display org-tags-overlay (concat prefix s)))))
14603 (defvar org-last-tag-selection-key nil)
14604 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14605 "Fast tag selection with single keys.
14606 CURRENT is the current list of tags in the headline, INHERITED is the
14607 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14608 possibly with grouping information. TODO-TABLE is a similar table with
14609 TODO keywords, should these have keys assigned to them.
14610 If the keys are nil, a-z are automatically assigned.
14611 Returns the new tags string, or nil to not change the current settings."
14612 (let* ((fulltable (append table todo-table))
14613 (maxlen (apply 'max (mapcar
14614 (lambda (x)
14615 (if (stringp (car x)) (string-width (car x)) 0))
14616 fulltable)))
14617 (buf (current-buffer))
14618 (expert (eq org-fast-tag-selection-single-key 'expert))
14619 (buffer-tags nil)
14620 (fwidth (+ maxlen 3 1 3))
14621 (ncol (/ (- (window-width) 4) fwidth))
14622 (i-face 'org-done)
14623 (c-face 'org-todo)
14624 tg cnt e c char c1 c2 ntable tbl rtn
14625 ov-start ov-end ov-prefix
14626 (exit-after-next org-fast-tag-selection-single-key)
14627 (done-keywords org-done-keywords)
14628 groups ingroup)
14629 (save-excursion
14630 (beginning-of-line 1)
14631 (if (looking-at
14632 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14633 (setq ov-start (match-beginning 1)
14634 ov-end (match-end 1)
14635 ov-prefix "")
14636 (setq ov-start (1- (point-at-eol))
14637 ov-end (1+ ov-start))
14638 (skip-chars-forward "^\n\r")
14639 (setq ov-prefix
14640 (concat
14641 (buffer-substring (1- (point)) (point))
14642 (if (> (current-column) org-tags-column)
14644 (make-string (- org-tags-column (current-column)) ?\ ))))))
14645 (move-overlay org-tags-overlay ov-start ov-end)
14646 (save-window-excursion
14647 (if expert
14648 (set-buffer (get-buffer-create " *Org tags*"))
14649 (delete-other-windows)
14650 (split-window-vertically)
14651 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14652 (erase-buffer)
14653 (org-set-local 'org-done-keywords done-keywords)
14654 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14655 (org-fast-tag-insert "Current" current c-face "\n\n")
14656 (org-fast-tag-show-exit exit-after-next)
14657 (org-set-current-tags-overlay current ov-prefix)
14658 (setq tbl fulltable char ?a cnt 0)
14659 (while (setq e (pop tbl))
14660 (cond
14661 ((equal (car e) :startgroup)
14662 (push '() groups) (setq ingroup t)
14663 (when (not (= cnt 0))
14664 (setq cnt 0)
14665 (insert "\n"))
14666 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14667 ((equal (car e) :endgroup)
14668 (setq ingroup nil cnt 0)
14669 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14670 ((equal e '(:newline))
14671 (when (not (= cnt 0))
14672 (setq cnt 0)
14673 (insert "\n")
14674 (setq e (car tbl))
14675 (while (equal (car tbl) '(:newline))
14676 (insert "\n")
14677 (setq tbl (cdr tbl)))))
14678 ((equal e '(:grouptags)) nil)
14680 (setq tg (copy-sequence (car e)) c2 nil)
14681 (if (cdr e)
14682 (setq c (cdr e))
14683 ;; automatically assign a character.
14684 (setq c1 (string-to-char
14685 (downcase (substring
14686 tg (if (= (string-to-char tg) ?@) 1 0)))))
14687 (if (or (rassoc c1 ntable) (rassoc c1 table))
14688 (while (or (rassoc char ntable) (rassoc char table))
14689 (setq char (1+ char)))
14690 (setq c2 c1))
14691 (setq c (or c2 char)))
14692 (if ingroup (push tg (car groups)))
14693 (setq tg (org-add-props tg nil 'face
14694 (cond
14695 ((not (assoc tg table))
14696 (org-get-todo-face tg))
14697 ((member tg current) c-face)
14698 ((member tg inherited) i-face))))
14699 (if (equal (caar tbl) :grouptags)
14700 (org-add-props tg nil 'face 'org-tag-group))
14701 (if (and (= cnt 0) (not ingroup)) (insert " "))
14702 (insert "[" c "] " tg (make-string
14703 (- fwidth 4 (length tg)) ?\ ))
14704 (push (cons tg c) ntable)
14705 (when (= (setq cnt (1+ cnt)) ncol)
14706 (insert "\n")
14707 (if ingroup (insert " "))
14708 (setq cnt 0)))))
14709 (setq ntable (nreverse ntable))
14710 (insert "\n")
14711 (goto-char (point-min))
14712 (if (not expert) (org-fit-window-to-buffer))
14713 (setq rtn
14714 (catch 'exit
14715 (while t
14716 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14717 (if (not groups) "no " "")
14718 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14719 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14720 (setq org-last-tag-selection-key c)
14721 (cond
14722 ((= c ?\r) (throw 'exit t))
14723 ((= c ?!)
14724 (setq groups (not groups))
14725 (goto-char (point-min))
14726 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14727 ((= c ?\C-c)
14728 (if (not expert)
14729 (org-fast-tag-show-exit
14730 (setq exit-after-next (not exit-after-next)))
14731 (setq expert nil)
14732 (delete-other-windows)
14733 (set-window-buffer (split-window-vertically) " *Org tags*")
14734 (org-switch-to-buffer-other-window " *Org tags*")
14735 (org-fit-window-to-buffer)))
14736 ((or (= c ?\C-g)
14737 (and (= c ?q) (not (rassoc c ntable))))
14738 (org-detach-overlay org-tags-overlay)
14739 (setq quit-flag t))
14740 ((= c ?\ )
14741 (setq current nil)
14742 (if exit-after-next (setq exit-after-next 'now)))
14743 ((= c ?\t)
14744 (condition-case nil
14745 (setq tg (org-icompleting-read
14746 "Tag: "
14747 (or buffer-tags
14748 (with-current-buffer buf
14749 (org-get-buffer-tags)))))
14750 (quit (setq tg "")))
14751 (when (string-match "\\S-" tg)
14752 (add-to-list 'buffer-tags (list tg))
14753 (if (member tg current)
14754 (setq current (delete tg current))
14755 (push tg current)))
14756 (if exit-after-next (setq exit-after-next 'now)))
14757 ((setq e (rassoc c todo-table) tg (car e))
14758 (with-current-buffer buf
14759 (save-excursion (org-todo tg)))
14760 (if exit-after-next (setq exit-after-next 'now)))
14761 ((setq e (rassoc c ntable) tg (car e))
14762 (if (member tg current)
14763 (setq current (delete tg current))
14764 (loop for g in groups do
14765 (if (member tg g)
14766 (mapc (lambda (x)
14767 (setq current (delete x current)))
14768 g)))
14769 (push tg current))
14770 (if exit-after-next (setq exit-after-next 'now))))
14772 ;; Create a sorted list
14773 (setq current
14774 (sort current
14775 (lambda (a b)
14776 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14777 (if (eq exit-after-next 'now) (throw 'exit t))
14778 (goto-char (point-min))
14779 (beginning-of-line 2)
14780 (delete-region (point) (point-at-eol))
14781 (org-fast-tag-insert "Current" current c-face)
14782 (org-set-current-tags-overlay current ov-prefix)
14783 (while (re-search-forward
14784 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14785 (setq tg (match-string 1))
14786 (add-text-properties
14787 (match-beginning 1) (match-end 1)
14788 (list 'face
14789 (cond
14790 ((member tg current) c-face)
14791 ((member tg inherited) i-face)
14792 (t (get-text-property (match-beginning 1) 'face))))))
14793 (goto-char (point-min)))))
14794 (org-detach-overlay org-tags-overlay)
14795 (if rtn
14796 (mapconcat 'identity current ":")
14797 nil))))
14799 (defun org-get-tags-string ()
14800 "Get the TAGS string in the current headline."
14801 (unless (org-at-heading-p t)
14802 (user-error "Not on a heading"))
14803 (save-excursion
14804 (beginning-of-line 1)
14805 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14806 (org-match-string-no-properties 1)
14807 "")))
14809 (defun org-get-tags ()
14810 "Get the list of tags specified in the current headline."
14811 (org-split-string (org-get-tags-string) ":"))
14813 (defun org-get-buffer-tags ()
14814 "Get a table of all tags used in the buffer, for completion."
14815 (let (tags)
14816 (save-excursion
14817 (goto-char (point-min))
14818 (while (re-search-forward
14819 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14820 (when (equal (char-after (point-at-bol 0)) ?*)
14821 (mapc (lambda (x) (add-to-list 'tags x))
14822 (org-split-string (org-match-string-no-properties 1) ":")))))
14823 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14824 (mapcar 'list tags)))
14826 ;;;; The mapping API
14828 (defun org-map-entries (func &optional match scope &rest skip)
14829 "Call FUNC at each headline selected by MATCH in SCOPE.
14831 FUNC is a function or a lisp form. The function will be called without
14832 arguments, with the cursor positioned at the beginning of the headline.
14833 The return values of all calls to the function will be collected and
14834 returned as a list.
14836 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14837 does not need to preserve point. After evaluation, the cursor will be
14838 moved to the end of the line (presumably of the headline of the
14839 processed entry) and search continues from there. Under some
14840 circumstances, this may not produce the wanted results. For example,
14841 if you have removed (e.g. archived) the current (sub)tree it could
14842 mean that the next entry will be skipped entirely. In such cases, you
14843 can specify the position from where search should continue by making
14844 FUNC set the variable `org-map-continue-from' to the desired buffer
14845 position.
14847 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14848 Only headlines that are matched by this query will be considered during
14849 the iteration. When MATCH is nil or t, all headlines will be
14850 visited by the iteration.
14852 SCOPE determines the scope of this command. It can be any of:
14854 nil The current buffer, respecting the restriction if any
14855 tree The subtree started with the entry at point
14856 region The entries within the active region, if any
14857 region-start-level
14858 The entries within the active region, but only those at
14859 the same level than the first one.
14860 file The current buffer, without restriction
14861 file-with-archives
14862 The current buffer, and any archives associated with it
14863 agenda All agenda files
14864 agenda-with-archives
14865 All agenda files with any archive files associated with them
14866 \(file1 file2 ...)
14867 If this is a list, all files in the list will be scanned
14869 The remaining args are treated as settings for the skipping facilities of
14870 the scanner. The following items can be given here:
14872 archive skip trees with the archive tag
14873 comment skip trees with the COMMENT keyword
14874 function or Emacs Lisp form:
14875 will be used as value for `org-agenda-skip-function', so
14876 whenever the function returns a position, FUNC will not be
14877 called for that entry and search will continue from the
14878 position returned
14880 If your function needs to retrieve the tags including inherited tags
14881 at the *current* entry, you can use the value of the variable
14882 `org-scanner-tags' which will be much faster than getting the value
14883 with `org-get-tags-at'. If your function gets properties with
14884 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14885 to t around the call to `org-entry-properties' to get the same speedup.
14886 Note that if your function moves around to retrieve tags and properties at
14887 a *different* entry, you cannot use these techniques."
14888 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14889 (not (org-region-active-p)))
14890 (let* ((org-agenda-archives-mode nil) ; just to make sure
14891 (org-agenda-skip-archived-trees (memq 'archive skip))
14892 (org-agenda-skip-comment-trees (memq 'comment skip))
14893 (org-agenda-skip-function
14894 (car (org-delete-all '(comment archive) skip)))
14895 (org-tags-match-list-sublevels t)
14896 (start-level (eq scope 'region-start-level))
14897 matcher file res
14898 org-todo-keywords-for-agenda
14899 org-done-keywords-for-agenda
14900 org-todo-keyword-alist-for-agenda
14901 org-drawers-for-agenda
14902 org-tag-alist-for-agenda
14903 todo-only)
14905 (cond
14906 ((eq match t) (setq matcher t))
14907 ((eq match nil) (setq matcher t))
14908 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14910 (save-window-excursion
14911 (save-restriction
14912 (cond ((eq scope 'tree)
14913 (org-back-to-heading t)
14914 (org-narrow-to-subtree)
14915 (setq scope nil))
14916 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14917 (org-region-active-p))
14918 ;; If needed, set start-level to a string like "2"
14919 (when start-level
14920 (save-excursion
14921 (goto-char (region-beginning))
14922 (unless (org-at-heading-p) (outline-next-heading))
14923 (setq start-level (org-current-level))))
14924 (narrow-to-region (region-beginning)
14925 (save-excursion
14926 (goto-char (region-end))
14927 (unless (and (bolp) (org-at-heading-p))
14928 (outline-next-heading))
14929 (point)))
14930 (setq scope nil)))
14932 (if (not scope)
14933 (progn
14934 (org-agenda-prepare-buffers
14935 (list (buffer-file-name (current-buffer))))
14936 (setq res (org-scan-tags func matcher todo-only start-level)))
14937 ;; Get the right scope
14938 (cond
14939 ((and scope (listp scope) (symbolp (car scope)))
14940 (setq scope (eval scope)))
14941 ((eq scope 'agenda)
14942 (setq scope (org-agenda-files t)))
14943 ((eq scope 'agenda-with-archives)
14944 (setq scope (org-agenda-files t))
14945 (setq scope (org-add-archive-files scope)))
14946 ((eq scope 'file)
14947 (setq scope (list (buffer-file-name))))
14948 ((eq scope 'file-with-archives)
14949 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14950 (org-agenda-prepare-buffers scope)
14951 (while (setq file (pop scope))
14952 (with-current-buffer (org-find-base-buffer-visiting file)
14953 (save-excursion
14954 (save-restriction
14955 (widen)
14956 (goto-char (point-min))
14957 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14958 res)))
14960 ;;;; Properties
14962 ;;; Setting and retrieving properties
14964 (defconst org-special-properties
14965 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14966 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14967 "The special properties valid in Org-mode.
14969 These are properties that are not defined in the property drawer,
14970 but in some other way.")
14972 (defconst org-default-properties
14973 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14974 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14975 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14976 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14977 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14978 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14979 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14980 "Some properties that are used by Org-mode for various purposes.
14981 Being in this list makes sure that they are offered for completion.")
14983 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14984 "Regular expression matching the first line of a property drawer.")
14986 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14987 "Regular expression matching the last line of a property drawer.")
14989 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14990 "Regular expression matching the first line of a property drawer.")
14992 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14993 "Regular expression matching the first line of a property drawer.")
14995 (defconst org-property-drawer-re
14996 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14997 org-property-end-re "\\)\n?")
14998 "Matches an entire property drawer.")
15000 (defconst org-clock-drawer-re
15001 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15002 org-property-end-re "\\)\n?")
15003 "Matches an entire clock drawer.")
15005 (defsubst org-re-property (property)
15006 "Return a regexp matching a PROPERTY line.
15007 Match group 1 will be set to the value."
15008 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
15010 (defsubst org-re-property-keyword (property)
15011 "Return a regexp matching a PROPERTY line, possibly with no
15012 value for the property."
15013 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
15015 (defun org-property-action ()
15016 "Do an action on properties."
15017 (interactive)
15018 (let (c)
15019 (org-at-property-p)
15020 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15021 (setq c (read-char-exclusive))
15022 (cond
15023 ((equal c ?s)
15024 (call-interactively 'org-set-property))
15025 ((equal c ?d)
15026 (call-interactively 'org-delete-property))
15027 ((equal c ?D)
15028 (call-interactively 'org-delete-property-globally))
15029 ((equal c ?c)
15030 (call-interactively 'org-compute-property-at-point))
15031 (t (user-error "No such property action %c" c)))))
15033 (defun org-inc-effort ()
15034 "Increment the value of the effort property in the current entry."
15035 (interactive)
15036 (org-set-effort nil t))
15038 (defvar org-clock-effort) ;; Defined in org-clock.el
15039 (defvar org-clock-current-task) ;; Defined in org-clock.el
15040 (defun org-set-effort (&optional value increment)
15041 "Set the effort property of the current entry.
15042 With numerical prefix arg, use the nth allowed value, 0 stands for the
15043 10th allowed value.
15045 When INCREMENT is non-nil, set the property to the next allowed value."
15046 (interactive "P")
15047 (if (equal value 0) (setq value 10))
15048 (let* ((completion-ignore-case t)
15049 (prop org-effort-property)
15050 (cur (org-entry-get nil prop))
15051 (allowed (org-property-get-allowed-values nil prop 'table))
15052 (existing (mapcar 'list (org-property-values prop)))
15053 (heading (nth 4 (org-heading-components)))
15055 (val (cond
15056 ((stringp value) value)
15057 ((and allowed (integerp value))
15058 (or (car (nth (1- value) allowed))
15059 (car (org-last allowed))))
15060 ((and allowed increment)
15061 (or (caadr (member (list cur) allowed))
15062 (user-error "Allowed effort values are not set")))
15063 (allowed
15064 (message "Select 1-9,0, [RET%s]: %s"
15065 (if cur (concat "=" cur) "")
15066 (mapconcat 'car allowed " "))
15067 (setq rpl (read-char-exclusive))
15068 (if (equal rpl ?\r)
15070 (setq rpl (- rpl ?0))
15071 (if (equal rpl 0) (setq rpl 10))
15072 (if (and (> rpl 0) (<= rpl (length allowed)))
15073 (car (nth (1- rpl) allowed))
15074 (org-completing-read "Effort: " allowed nil))))
15076 (let (org-completion-use-ido org-completion-use-iswitchb)
15077 (org-completing-read
15078 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15079 (concat "[" cur "]") "")
15080 ": ")
15081 existing nil nil "" nil cur))))))
15082 (unless (equal (org-entry-get nil prop) val)
15083 (org-entry-put nil prop val))
15084 (save-excursion
15085 (org-back-to-heading t)
15086 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15087 (when (string= heading org-clock-current-task)
15088 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15089 (org-clock-update-mode-line))
15090 (message "%s is now %s" prop val)))
15092 (defun org-at-property-p ()
15093 "Is cursor inside a property drawer?"
15094 (save-excursion
15095 (beginning-of-line 1)
15096 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15097 (save-match-data ;; Used by calling procedures
15098 (let ((p (point))
15099 (range (unless (org-before-first-heading-p)
15100 (org-get-property-block))))
15101 (and range (<= (car range) p) (< p (cdr range))))))))
15103 (defun org-get-property-block (&optional beg end force)
15104 "Return the (beg . end) range of the body of the property drawer.
15105 BEG and END are the beginning and end of the current subtree, or of
15106 the part before the first headline. If they are not given, they will
15107 be found. If the drawer does not exist and FORCE is non-nil, create
15108 the drawer."
15109 (catch 'exit
15110 (save-excursion
15111 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15112 (progn (org-back-to-heading t) (point))))
15113 (end (or end (and (not (outline-next-heading)) (point-max))
15114 (point))))
15115 (goto-char beg)
15116 (if (re-search-forward org-property-start-re end t)
15117 (setq beg (1+ (match-end 0)))
15118 (if force
15119 (save-excursion
15120 (org-insert-property-drawer)
15121 (setq end (progn (outline-next-heading) (point))))
15122 (throw 'exit nil))
15123 (goto-char beg)
15124 (if (re-search-forward org-property-start-re end t)
15125 (setq beg (1+ (match-end 0)))))
15126 (if (re-search-forward org-property-end-re end t)
15127 (setq end (match-beginning 0))
15128 (or force (throw 'exit nil))
15129 (goto-char beg)
15130 (setq end beg)
15131 (org-indent-line)
15132 (insert ":END:\n"))
15133 (cons beg end)))))
15135 (defun org-entry-properties (&optional pom which specific)
15136 "Get all properties of the entry at point-or-marker POM.
15137 This includes the TODO keyword, the tags, time strings for deadline,
15138 scheduled, and clocking, and any additional properties defined in the
15139 entry. The return value is an alist, keys may occur multiple times
15140 if the property key was used several times.
15141 POM may also be nil, in which case the current entry is used.
15142 If WHICH is nil or `all', get all properties. If WHICH is
15143 `special' or `standard', only get that subclass. If WHICH
15144 is a string only get exactly this property. SPECIFIC can be a string, the
15145 specific property we are interested in. Specifying it can speed
15146 things up because then unnecessary parsing is avoided."
15147 (setq which (or which 'all))
15148 (org-with-point-at pom
15149 (let ((clockstr (substring org-clock-string 0 -1))
15150 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15151 (case-fold-search nil)
15152 beg end range props sum-props key key1 value string clocksum clocksumt)
15153 (save-excursion
15154 (when (condition-case nil
15155 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15156 (error nil))
15157 (setq beg (point))
15158 (setq sum-props (get-text-property (point) 'org-summaries))
15159 (setq clocksum (get-text-property (point) :org-clock-minutes)
15160 clocksumt (get-text-property (point) :org-clock-minutes-today))
15161 (outline-next-heading)
15162 (setq end (point))
15163 (when (memq which '(all special))
15164 ;; Get the special properties, like TODO and tags
15165 (goto-char beg)
15166 (when (and (or (not specific) (string= specific "TODO"))
15167 (looking-at org-todo-line-regexp) (match-end 2))
15168 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15169 (when (and (or (not specific) (string= specific "PRIORITY"))
15170 (looking-at org-priority-regexp))
15171 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15172 (when (or (not specific) (string= specific "FILE"))
15173 (push (cons "FILE" buffer-file-name) props))
15174 (when (and (or (not specific) (string= specific "TAGS"))
15175 (setq value (org-get-tags-string))
15176 (string-match "\\S-" value))
15177 (push (cons "TAGS" value) props))
15178 (when (and (or (not specific) (string= specific "ALLTAGS"))
15179 (setq value (org-get-tags-at)))
15180 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15181 ":"))
15182 props))
15183 (when (or (not specific) (string= specific "BLOCKED"))
15184 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15185 (when (or (not specific)
15186 (member specific
15187 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15188 "TIMESTAMP" "TIMESTAMP_IA")))
15189 (catch 'match
15190 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15191 (setq key (if (match-end 1)
15192 (substring (org-match-string-no-properties 1)
15193 0 -1))
15194 string (if (equal key clockstr)
15195 (org-trim
15196 (buffer-substring-no-properties
15197 (match-beginning 3) (goto-char
15198 (point-at-eol))))
15199 (substring (org-match-string-no-properties 3)
15200 1 -1)))
15201 ;; Get the correct property name from the key. This is
15202 ;; necessary if the user has configured time keywords.
15203 (setq key1 (concat key ":"))
15204 (cond
15205 ((not key)
15206 (setq key
15207 (if (= (char-after (match-beginning 3)) ?\[)
15208 "TIMESTAMP_IA" "TIMESTAMP")))
15209 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15210 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15211 ((equal key1 org-closed-string) (setq key "CLOSED"))
15212 ((equal key1 org-clock-string) (setq key "CLOCK")))
15213 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15214 (progn
15215 (push (cons key string) props)
15216 ;; no need to search further if match is found
15217 (throw 'match t))
15218 (when (or (equal key "CLOCK") (not (assoc key props)))
15219 (push (cons key string) props)))))))
15221 (when (memq which '(all standard))
15222 ;; Get the standard properties, like :PROP: ...
15223 (setq range (org-get-property-block beg end))
15224 (when range
15225 (goto-char (car range))
15226 (while (re-search-forward
15227 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15228 (cdr range) t)
15229 (setq key (org-match-string-no-properties 1)
15230 value (org-trim (or (org-match-string-no-properties 2) "")))
15231 (unless (member key excluded)
15232 (push (cons key (or value "")) props)))))
15233 (if clocksum
15234 (push (cons "CLOCKSUM"
15235 (org-columns-number-to-string (/ (float clocksum) 60.)
15236 'add_times))
15237 props))
15238 (if clocksumt
15239 (push (cons "CLOCKSUM_T"
15240 (org-columns-number-to-string (/ (float clocksumt) 60.)
15241 'add_times))
15242 props))
15243 (unless (assoc "CATEGORY" props)
15244 (push (cons "CATEGORY" (org-get-category)) props))
15245 (append sum-props (nreverse props)))))))
15247 (defun org-entry-get (pom property &optional inherit literal-nil)
15248 "Get value of PROPERTY for entry or content at point-or-marker POM.
15249 If INHERIT is non-nil and the entry does not have the property,
15250 then also check higher levels of the hierarchy.
15251 If INHERIT is the symbol `selective', use inheritance only if the setting
15252 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15253 If the property is present but empty, the return value is the empty string.
15254 If the property is not present at all, nil is returned.
15256 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15257 do not interpret it as the list atom nil. This is used for inheritance
15258 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15259 (org-with-point-at pom
15260 (if (and inherit (if (eq inherit 'selective)
15261 (org-property-inherit-p property)
15263 (org-entry-get-with-inheritance property literal-nil)
15264 (if (member property org-special-properties)
15265 ;; We need a special property. Use `org-entry-properties' to
15266 ;; retrieve it, but specify the wanted property
15267 (cdr (assoc property (org-entry-properties nil 'special property)))
15268 (let ((range (org-get-property-block)))
15269 (when (and range (not (eq (car range) (cdr range))))
15270 (let* ((props (list (or (assoc property org-file-properties)
15271 (assoc property org-global-properties)
15272 (assoc property org-global-properties-fixed))))
15273 (ap (lambda (key)
15274 (when (re-search-forward
15275 (org-re-property key) (cdr range) t)
15276 (setq props
15277 (org-update-property-plist
15279 (if (match-end 1)
15280 (org-match-string-no-properties 1) "")
15281 props)))))
15282 val)
15283 (goto-char (car range))
15284 (funcall ap property)
15285 (goto-char (car range))
15286 (while (funcall ap (concat property "+")))
15287 (setq val (cdr (assoc property props)))
15288 (when val (if literal-nil val (org-not-nil val))))))))))
15290 (defun org-property-or-variable-value (var &optional inherit)
15291 "Check if there is a property fixing the value of VAR.
15292 If yes, return this value. If not, return the current value of the variable."
15293 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15294 (if (and prop (stringp prop) (string-match "\\S-" prop))
15295 (read prop)
15296 (symbol-value var))))
15298 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15299 "Delete the property PROPERTY from entry at point-or-marker POM.
15300 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15301 an empty drawer to delete."
15302 (org-with-point-at pom
15303 (if (member property org-special-properties)
15304 nil ; cannot delete these properties.
15305 (let ((range (org-get-property-block)))
15306 (if (and range
15307 (goto-char (car range))
15308 (re-search-forward
15309 (org-re-property property)
15310 (cdr range) t))
15311 (progn
15312 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15313 (and delete-empty-drawer
15314 (org-remove-empty-drawer-at
15315 delete-empty-drawer (car range)))
15317 nil)))))
15319 ;; Multi-values properties are properties that contain multiple values
15320 ;; These values are assumed to be single words, separated by whitespace.
15321 (defun org-entry-add-to-multivalued-property (pom property value)
15322 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15323 (let* ((old (org-entry-get pom property))
15324 (values (and old (org-split-string old "[ \t]"))))
15325 (setq value (org-entry-protect-space value))
15326 (unless (member value values)
15327 (setq values (append values (list value)))
15328 (org-entry-put pom property
15329 (mapconcat 'identity values " ")))))
15331 (defun org-entry-remove-from-multivalued-property (pom property value)
15332 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15333 (let* ((old (org-entry-get pom property))
15334 (values (and old (org-split-string old "[ \t]"))))
15335 (setq value (org-entry-protect-space value))
15336 (when (member value values)
15337 (setq values (delete value values))
15338 (org-entry-put pom property
15339 (mapconcat 'identity values " ")))))
15341 (defun org-entry-member-in-multivalued-property (pom property value)
15342 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15343 (let* ((old (org-entry-get pom property))
15344 (values (and old (org-split-string old "[ \t]"))))
15345 (setq value (org-entry-protect-space value))
15346 (member value values)))
15348 (defun org-entry-get-multivalued-property (pom property)
15349 "Return a list of values in a multivalued property."
15350 (let* ((value (org-entry-get pom property))
15351 (values (and value (org-split-string value "[ \t]"))))
15352 (mapcar 'org-entry-restore-space values)))
15354 (defun org-entry-put-multivalued-property (pom property &rest values)
15355 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15356 VALUES should be a list of strings. Spaces will be protected."
15357 (org-entry-put pom property
15358 (mapconcat 'org-entry-protect-space values " "))
15359 (let* ((value (org-entry-get pom property))
15360 (values (and value (org-split-string value "[ \t]"))))
15361 (mapcar 'org-entry-restore-space values)))
15363 (defun org-entry-protect-space (s)
15364 "Protect spaces and newline in string S."
15365 (while (string-match " " s)
15366 (setq s (replace-match "%20" t t s)))
15367 (while (string-match "\n" s)
15368 (setq s (replace-match "%0A" t t s)))
15371 (defun org-entry-restore-space (s)
15372 "Restore spaces and newline in string S."
15373 (while (string-match "%20" s)
15374 (setq s (replace-match " " t t s)))
15375 (while (string-match "%0A" s)
15376 (setq s (replace-match "\n" t t s)))
15379 (defvar org-entry-property-inherited-from (make-marker)
15380 "Marker pointing to the entry from where a property was inherited.
15381 Each call to `org-entry-get-with-inheritance' will set this marker to the
15382 location of the entry where the inheritance search matched. If there was
15383 no match, the marker will point nowhere.
15384 Note that also `org-entry-get' calls this function, if the INHERIT flag
15385 is set.")
15387 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15388 "Get PROPERTY of entry or content at point, search higher levels if needed.
15389 The search will stop at the first ancestor which has the property defined.
15390 If the value found is \"nil\", return nil to show that the property
15391 should be considered as undefined (this is the meaning of nil here).
15392 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15393 (move-marker org-entry-property-inherited-from nil)
15394 (let (tmp)
15395 (save-excursion
15396 (save-restriction
15397 (widen)
15398 (catch 'ex
15399 (while t
15400 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15401 (or (ignore-errors (org-back-to-heading t))
15402 (goto-char (point-min)))
15403 (move-marker org-entry-property-inherited-from (point))
15404 (throw 'ex tmp))
15405 (or (ignore-errors (org-up-heading-safe))
15406 (throw 'ex nil))))))
15407 (setq tmp (or tmp
15408 (cdr (assoc property org-file-properties))
15409 (cdr (assoc property org-global-properties))
15410 (cdr (assoc property org-global-properties-fixed))))
15411 (if literal-nil tmp (org-not-nil tmp))))
15413 (defvar org-property-changed-functions nil
15414 "Hook called when the value of a property has changed.
15415 Each hook function should accept two arguments, the name of the property
15416 and the new value.")
15418 (defun org-entry-put (pom property value)
15419 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15420 (org-with-point-at pom
15421 (org-back-to-heading t)
15422 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15423 range)
15424 (cond
15425 ((equal property "TODO")
15426 (when (and (stringp value) (string-match "\\S-" value)
15427 (not (member value org-todo-keywords-1)))
15428 (user-error "\"%s\" is not a valid TODO state" value))
15429 (if (or (not value)
15430 (not (string-match "\\S-" value)))
15431 (setq value 'none))
15432 (org-todo value)
15433 (org-set-tags nil 'align))
15434 ((equal property "PRIORITY")
15435 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15436 (string-to-char value) ?\ ))
15437 (org-set-tags nil 'align))
15438 ((equal property "CLOCKSUM")
15439 (if (not (re-search-forward
15440 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15441 (error "Cannot find a clock log")
15442 (goto-char (- (match-end 1) 2))
15443 (cond
15444 ((eq value 'earlier) (org-timestamp-down))
15445 ((eq value 'later) (org-timestamp-up)))
15446 (org-clock-sum-current-item)))
15447 ((equal property "SCHEDULED")
15448 (if (re-search-forward org-scheduled-time-regexp end t)
15449 (cond
15450 ((eq value 'earlier) (org-timestamp-change -1 'day))
15451 ((eq value 'later) (org-timestamp-change 1 'day))
15452 (t (call-interactively 'org-schedule)))
15453 (call-interactively 'org-schedule)))
15454 ((equal property "DEADLINE")
15455 (if (re-search-forward org-deadline-time-regexp end t)
15456 (cond
15457 ((eq value 'earlier) (org-timestamp-change -1 'day))
15458 ((eq value 'later) (org-timestamp-change 1 'day))
15459 (t (call-interactively 'org-deadline)))
15460 (call-interactively 'org-deadline)))
15461 ((member property org-special-properties)
15462 (error "The %s property can not yet be set with `org-entry-put'"
15463 property))
15464 (t ; a non-special property
15465 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15466 (setq range (org-get-property-block beg end 'force))
15467 (goto-char (car range))
15468 (if (re-search-forward
15469 (org-re-property-keyword property) (cdr range) t)
15470 (progn
15471 (delete-region (match-beginning 0) (match-end 0))
15472 (goto-char (match-beginning 0)))
15473 (goto-char (cdr range))
15474 (insert "\n")
15475 (backward-char 1)
15476 (org-indent-line))
15477 (insert ":" property ":")
15478 (and value (insert " " value))
15479 (org-indent-line)))))
15480 (run-hook-with-args 'org-property-changed-functions property value)))
15482 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15483 "Get all property keys in the current buffer.
15484 With INCLUDE-SPECIALS, also list the special properties that reflect things
15485 like tags and TODO state.
15486 With INCLUDE-DEFAULTS, also include properties that has special meaning
15487 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15488 and others.
15489 With INCLUDE-COLUMNS, also include property names given in COLUMN
15490 formats in the current buffer."
15491 (let (rtn range cfmt s p)
15492 (save-excursion
15493 (save-restriction
15494 (widen)
15495 (goto-char (point-min))
15496 (while (re-search-forward org-property-start-re nil t)
15497 (setq range (org-get-property-block))
15498 (goto-char (car range))
15499 (while (re-search-forward
15500 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15501 (cdr range) t)
15502 (add-to-list 'rtn (org-match-string-no-properties 1)))
15503 (outline-next-heading))))
15505 (when include-specials
15506 (setq rtn (append org-special-properties rtn)))
15508 (when include-defaults
15509 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15510 (add-to-list 'rtn org-effort-property))
15512 (when include-columns
15513 (save-excursion
15514 (save-restriction
15515 (widen)
15516 (goto-char (point-min))
15517 (while (re-search-forward
15518 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15519 nil t)
15520 (setq cfmt (match-string 2) s 0)
15521 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15522 cfmt s)
15523 (setq s (match-end 0)
15524 p (match-string 1 cfmt))
15525 (unless (or (equal p "ITEM")
15526 (member p org-special-properties))
15527 (add-to-list 'rtn (match-string 1 cfmt))))))))
15529 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15531 (defun org-property-values (key)
15532 "Return a list of all values of property KEY in the current buffer."
15533 (save-excursion
15534 (save-restriction
15535 (widen)
15536 (goto-char (point-min))
15537 (let ((re (org-re-property key))
15538 values)
15539 (while (re-search-forward re nil t)
15540 (add-to-list 'values (org-trim (match-string 1))))
15541 (delete "" values)))))
15543 (defun org-insert-property-drawer ()
15544 "Insert a property drawer into the current entry."
15545 (org-back-to-heading t)
15546 (looking-at org-outline-regexp)
15547 (let ((indent (if org-adapt-indentation
15548 (- (match-end 0) (match-beginning 0))
15550 (beg (point))
15551 (re (concat "^[ \t]*" org-keyword-time-regexp))
15552 end hiddenp)
15553 (outline-next-heading)
15554 (setq end (point))
15555 (goto-char beg)
15556 (while (re-search-forward re end t))
15557 (setq hiddenp (outline-invisible-p))
15558 (end-of-line 1)
15559 (and (equal (char-after) ?\n) (forward-char 1))
15560 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15561 (if (member (match-string 1) '("CLOCK:" ":END:"))
15562 ;; just skip this line
15563 (beginning-of-line 2)
15564 ;; Drawer start, find the end
15565 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15566 (beginning-of-line 1)))
15567 (org-skip-over-state-notes)
15568 (skip-chars-backward " \t\n\r")
15569 (if (eq (char-before) ?*) (forward-char 1))
15570 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15571 (beginning-of-line 0)
15572 (org-indent-to-column indent)
15573 (beginning-of-line 2)
15574 (org-indent-to-column indent)
15575 (beginning-of-line 0)
15576 (if hiddenp
15577 (save-excursion
15578 (org-back-to-heading t)
15579 (hide-entry))
15580 (org-flag-drawer t))))
15582 (defun org-insert-drawer (&optional arg drawer)
15583 "Insert a drawer at point.
15585 Optional argument DRAWER, when non-nil, is a string representing
15586 drawer's name. Otherwise, the user is prompted for a name.
15588 If a region is active, insert the drawer around that region
15589 instead.
15591 Point is left between drawer's boundaries."
15592 (interactive "P")
15593 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15594 "LOGBOOK"))
15595 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15596 ;; internally by Org. They are meant to be inserted
15597 ;; automatically.
15598 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15599 ;; Remove system drawers from list. Note: For some reason,
15600 ;; `org-completing-read' ignores the predicate while
15601 ;; `completing-read' handles it fine.
15602 (drawer (if arg "PROPERTIES"
15603 (or drawer
15604 (completing-read
15605 "Drawer: " org-drawers
15606 (lambda (d) (not (member d system-drawers))))))))
15607 (cond
15608 ;; With C-u, fall back on `org-insert-property-drawer'
15609 (arg (org-insert-property-drawer))
15610 ;; With an active region, insert a drawer at point.
15611 ((not (org-region-active-p))
15612 (progn
15613 (unless (bolp) (insert "\n"))
15614 (insert (format ":%s:\n\n:END:\n" drawer))
15615 (forward-line -2)))
15616 ;; Otherwise, insert the drawer at point
15618 (let ((rbeg (region-beginning))
15619 (rend (copy-marker (region-end))))
15620 (unwind-protect
15621 (progn
15622 (goto-char rbeg)
15623 (beginning-of-line)
15624 (when (save-excursion
15625 (re-search-forward org-outline-regexp-bol rend t))
15626 (user-error "Drawers cannot contain headlines"))
15627 ;; Position point at the beginning of the first
15628 ;; non-blank line in region. Insert drawer's opening
15629 ;; there, then indent it.
15630 (org-skip-whitespace)
15631 (beginning-of-line)
15632 (insert ":" drawer ":\n")
15633 (forward-line -1)
15634 (indent-for-tab-command)
15635 ;; Move point to the beginning of the first blank line
15636 ;; after the last non-blank line in region. Insert
15637 ;; drawer's closing, then indent it.
15638 (goto-char rend)
15639 (skip-chars-backward " \r\t\n")
15640 (insert "\n:END:")
15641 (deactivate-mark t)
15642 (indent-for-tab-command)
15643 (unless (eolp) (insert "\n")))
15644 ;; Clear marker, whatever the outcome of insertion is.
15645 (set-marker rend nil)))))))
15647 (defvar org-property-set-functions-alist nil
15648 "Property set function alist.
15649 Each entry should have the following format:
15651 (PROPERTY . READ-FUNCTION)
15653 The read function will be called with the same argument as
15654 `org-completing-read'.")
15656 (defun org-set-property-function (property)
15657 "Get the function that should be used to set PROPERTY.
15658 This is computed according to `org-property-set-functions-alist'."
15659 (or (cdr (assoc property org-property-set-functions-alist))
15660 'org-completing-read))
15662 (defun org-read-property-value (property)
15663 "Read PROPERTY value from user."
15664 (let* ((completion-ignore-case t)
15665 (allowed (org-property-get-allowed-values nil property 'table))
15666 (cur (org-entry-get nil property))
15667 (prompt (concat property " value"
15668 (if (and cur (string-match "\\S-" cur))
15669 (concat " [" cur "]") "") ": "))
15670 (set-function (org-set-property-function property))
15671 (val (if allowed
15672 (funcall set-function prompt allowed nil
15673 (not (get-text-property 0 'org-unrestricted
15674 (caar allowed))))
15675 (let (org-completion-use-ido org-completion-use-iswitchb)
15676 (funcall set-function prompt
15677 (mapcar 'list (org-property-values property))
15678 nil nil "" nil cur)))))
15679 (if (equal val "")
15681 val)))
15683 (defvar org-last-set-property nil)
15684 (defvar org-last-set-property-value nil)
15685 (defun org-read-property-name ()
15686 "Read a property name."
15687 (let* ((completion-ignore-case t)
15688 (keys (org-buffer-property-keys nil t t))
15689 (default-prop (or (save-excursion
15690 (save-match-data
15691 (beginning-of-line)
15692 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15693 (null (string= (match-string 1) "END"))
15694 (match-string 1))))
15695 org-last-set-property))
15696 (property (org-icompleting-read
15697 (concat "Property"
15698 (if default-prop (concat " [" default-prop "]") "")
15699 ": ")
15700 (mapcar 'list keys)
15701 nil nil nil nil
15702 default-prop)))
15703 (if (member property keys)
15704 property
15705 (or (cdr (assoc (downcase property)
15706 (mapcar (lambda (x) (cons (downcase x) x))
15707 keys)))
15708 property))))
15710 (defun org-set-property-and-value (use-last)
15711 "Allow to set [PROPERTY]: [value] direction from prompt.
15712 When use-default, don't even ask, just use the last
15713 \"[PROPERTY]: [value]\" string from the history."
15714 (interactive "P")
15715 (let* ((completion-ignore-case t)
15716 (pv (or (and use-last org-last-set-property-value)
15717 (org-completing-read
15718 "Enter a \"[Property]: [value]\" pair: "
15719 nil nil nil nil nil
15720 org-last-set-property-value)))
15721 prop val)
15722 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15723 (setq prop (match-string 1 pv)
15724 val (match-string 2 pv))
15725 (org-set-property prop val))))
15727 (defun org-set-property (property value)
15728 "In the current entry, set PROPERTY to VALUE.
15729 When called interactively, this will prompt for a property name, offering
15730 completion on existing and default properties. And then it will prompt
15731 for a value, offering completion either on allowed values (via an inherited
15732 xxx_ALL property) or on existing values in other instances of this property
15733 in the current file."
15734 (interactive (list nil nil))
15735 (let* ((property (or property (org-read-property-name)))
15736 (value (or value (org-read-property-value property)))
15737 (fn (cdr (assoc property org-properties-postprocess-alist))))
15738 (setq org-last-set-property property)
15739 (setq org-last-set-property-value (concat property ": " value))
15740 ;; Possibly postprocess the inserted value:
15741 (when fn (setq value (funcall fn value)))
15742 (unless (equal (org-entry-get nil property) value)
15743 (org-entry-put nil property value))))
15745 (defun org-delete-property (property &optional delete-empty-drawer)
15746 "In the current entry, delete PROPERTY.
15747 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15748 an empty drawer to delete."
15749 (interactive
15750 (let* ((completion-ignore-case t)
15751 (prop (org-icompleting-read "Property: "
15752 (org-entry-properties nil 'standard))))
15753 (list prop)))
15754 (message "Property %s %s" property
15755 (if (org-entry-delete nil property delete-empty-drawer)
15756 "deleted"
15757 "was not present in the entry")))
15759 (defun org-delete-property-globally (property)
15760 "Remove PROPERTY globally, from all entries."
15761 (interactive
15762 (let* ((completion-ignore-case t)
15763 (prop (org-icompleting-read
15764 "Globally remove property: "
15765 (mapcar 'list (org-buffer-property-keys)))))
15766 (list prop)))
15767 (save-excursion
15768 (save-restriction
15769 (widen)
15770 (goto-char (point-min))
15771 (let ((cnt 0))
15772 (while (re-search-forward
15773 (org-re-property property)
15774 nil t)
15775 (setq cnt (1+ cnt))
15776 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15777 (message "Property \"%s\" removed from %d entries" property cnt)))))
15779 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15781 (defun org-compute-property-at-point ()
15782 "Compute the property at point.
15783 This looks for an enclosing column format, extracts the operator and
15784 then applies it to the property in the column format's scope."
15785 (interactive)
15786 (unless (org-at-property-p)
15787 (user-error "Not at a property"))
15788 (let ((prop (org-match-string-no-properties 2)))
15789 (org-columns-get-format-and-top-level)
15790 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15791 (user-error "No operator defined for property %s" prop))
15792 (org-columns-compute prop)))
15794 (defvar org-property-allowed-value-functions nil
15795 "Hook for functions supplying allowed values for a specific property.
15796 The functions must take a single argument, the name of the property, and
15797 return a flat list of allowed values. If \":ETC\" is one of
15798 the values, this means that these values are intended as defaults for
15799 completion, but that other values should be allowed too.
15800 The functions must return nil if they are not responsible for this
15801 property.")
15803 (defun org-property-get-allowed-values (pom property &optional table)
15804 "Get allowed values for the property PROPERTY.
15805 When TABLE is non-nil, return an alist that can directly be used for
15806 completion."
15807 (let (vals)
15808 (cond
15809 ((equal property "TODO")
15810 (setq vals (org-with-point-at pom
15811 (append org-todo-keywords-1 '("")))))
15812 ((equal property "PRIORITY")
15813 (let ((n org-lowest-priority))
15814 (while (>= n org-highest-priority)
15815 (push (char-to-string n) vals)
15816 (setq n (1- n)))))
15817 ((member property org-special-properties))
15818 ((setq vals (run-hook-with-args-until-success
15819 'org-property-allowed-value-functions property)))
15821 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15822 (when (and vals (string-match "\\S-" vals))
15823 (setq vals (car (read-from-string (concat "(" vals ")"))))
15824 (setq vals (mapcar (lambda (x)
15825 (cond ((stringp x) x)
15826 ((numberp x) (number-to-string x))
15827 ((symbolp x) (symbol-name x))
15828 (t "???")))
15829 vals)))))
15830 (when (member ":ETC" vals)
15831 (setq vals (remove ":ETC" vals))
15832 (org-add-props (car vals) '(org-unrestricted t)))
15833 (if table (mapcar 'list vals) vals)))
15835 (defun org-property-previous-allowed-value (&optional previous)
15836 "Switch to the next allowed value for this property."
15837 (interactive)
15838 (org-property-next-allowed-value t))
15840 (defun org-property-next-allowed-value (&optional previous)
15841 "Switch to the next allowed value for this property."
15842 (interactive)
15843 (unless (org-at-property-p)
15844 (user-error "Not at a property"))
15845 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15846 (key (match-string 2))
15847 (value (match-string 3))
15848 (allowed (or (org-property-get-allowed-values (point) key)
15849 (and (member value '("[ ]" "[-]" "[X]"))
15850 '("[ ]" "[X]"))))
15851 (heading (save-match-data (nth 4 (org-heading-components))))
15852 nval)
15853 (unless allowed
15854 (user-error "Allowed values for this property have not been defined"))
15855 (if previous (setq allowed (reverse allowed)))
15856 (if (member value allowed)
15857 (setq nval (car (cdr (member value allowed)))))
15858 (setq nval (or nval (car allowed)))
15859 (if (equal nval value)
15860 (user-error "Only one allowed value for this property"))
15861 (org-at-property-p)
15862 (replace-match (concat " :" key ": " nval) t t)
15863 (org-indent-line)
15864 (beginning-of-line 1)
15865 (skip-chars-forward " \t")
15866 (when (equal prop org-effort-property)
15867 (save-excursion
15868 (org-back-to-heading t)
15869 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15870 (when (string= org-clock-current-task heading)
15871 (setq org-clock-effort nval)
15872 (org-clock-update-mode-line)))
15873 (run-hook-with-args 'org-property-changed-functions key nval)))
15875 (defun org-find-olp (path &optional this-buffer)
15876 "Return a marker pointing to the entry at outline path OLP.
15877 If anything goes wrong, throw an error.
15878 You can wrap this call to catch the error like this:
15880 (condition-case msg
15881 (org-mobile-locate-entry (match-string 4))
15882 (error (nth 1 msg)))
15884 The return value will then be either a string with the error message,
15885 or a marker if everything is OK.
15887 If THIS-BUFFER is set, the outline path does not contain a file,
15888 only headings."
15889 (let* ((file (if this-buffer buffer-file-name (pop path)))
15890 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15891 (level 1)
15892 (lmin 1)
15893 (lmax 1)
15894 limit re end found pos heading cnt flevel)
15895 (unless buffer (error "File not found :%s" file))
15896 (with-current-buffer buffer
15897 (save-excursion
15898 (save-restriction
15899 (widen)
15900 (setq limit (point-max))
15901 (goto-char (point-min))
15902 (while (setq heading (pop path))
15903 (setq re (format org-complex-heading-regexp-format
15904 (regexp-quote heading)))
15905 (setq cnt 0 pos (point))
15906 (while (re-search-forward re end t)
15907 (setq level (- (match-end 1) (match-beginning 1)))
15908 (if (and (>= level lmin) (<= level lmax))
15909 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15910 (when (= cnt 0) (error "Heading not found on level %d: %s"
15911 lmax heading))
15912 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15913 lmax heading))
15914 (goto-char found)
15915 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15916 (setq end (save-excursion (org-end-of-subtree t t))))
15917 (when (org-at-heading-p)
15918 (point-marker)))))))
15920 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15921 "Find node HEADING in BUFFER.
15922 Return a marker to the heading if it was found, or nil if not.
15923 If POS-ONLY is set, return just the position instead of a marker.
15925 The heading text must match exact, but it may have a TODO keyword,
15926 a priority cookie and tags in the standard locations."
15927 (with-current-buffer (or buffer (current-buffer))
15928 (save-excursion
15929 (save-restriction
15930 (widen)
15931 (goto-char (point-min))
15932 (let (case-fold-search)
15933 (if (re-search-forward
15934 (format org-complex-heading-regexp-format
15935 (regexp-quote heading)) nil t)
15936 (if pos-only
15937 (match-beginning 0)
15938 (move-marker (make-marker) (match-beginning 0)))))))))
15940 (defun org-find-exact-heading-in-directory (heading &optional dir)
15941 "Find Org node headline HEADING in all .org files in directory DIR.
15942 When the target headline is found, return a marker to this location."
15943 (let ((files (directory-files (or dir default-directory)
15944 nil "\\`[^.#].*\\.org\\'"))
15945 file visiting m buffer)
15946 (catch 'found
15947 (while (setq file (pop files))
15948 (message "trying %s" file)
15949 (setq visiting (org-find-base-buffer-visiting file))
15950 (setq buffer (or visiting (find-file-noselect file)))
15951 (setq m (org-find-exact-headline-in-buffer
15952 heading buffer))
15953 (when (and (not m) (not visiting)) (kill-buffer buffer))
15954 (and m (throw 'found m))))))
15956 (defun org-find-entry-with-id (ident)
15957 "Locate the entry that contains the ID property with exact value IDENT.
15958 IDENT can be a string, a symbol or a number, this function will search for
15959 the string representation of it.
15960 Return the position where this entry starts, or nil if there is no such entry."
15961 (interactive "sID: ")
15962 (let ((id (cond
15963 ((stringp ident) ident)
15964 ((symbol-name ident) (symbol-name ident))
15965 ((numberp ident) (number-to-string ident))
15966 (t (error "IDENT %s must be a string, symbol or number" ident))))
15967 (case-fold-search nil))
15968 (save-excursion
15969 (save-restriction
15970 (widen)
15971 (goto-char (point-min))
15972 (when (re-search-forward
15973 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15974 nil t)
15975 (org-back-to-heading t)
15976 (point))))))
15978 ;;;; Timestamps
15980 (defvar org-last-changed-timestamp nil)
15981 (defvar org-last-inserted-timestamp nil
15982 "The last time stamp inserted with `org-insert-time-stamp'.")
15983 (defvar org-time-was-given) ; dynamically scoped parameter
15984 (defvar org-end-time-was-given) ; dynamically scoped parameter
15985 (defvar org-ts-what) ; dynamically scoped parameter
15987 (defun org-time-stamp (arg &optional inactive)
15988 "Prompt for a date/time and insert a time stamp.
15989 If the user specifies a time like HH:MM or if this command is
15990 called with at least one prefix argument, the time stamp contains
15991 the date and the time. Otherwise, only the date is be included.
15993 All parts of a date not specified by the user is filled in from
15994 the current date/time. So if you just press return without
15995 typing anything, the time stamp will represent the current
15996 date/time.
15998 If there is already a timestamp at the cursor, it will be
15999 modified.
16001 With two universal prefix arguments, insert an active timestamp
16002 with the current time without prompting the user."
16003 (interactive "P")
16004 (let* ((ts nil)
16005 (default-time
16006 ;; Default time is either today, or, when entering a range,
16007 ;; the range start.
16008 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16009 (save-excursion
16010 (re-search-backward
16011 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16012 (- (point) 20) t)))
16013 (apply 'encode-time (org-parse-time-string (match-string 1)))
16014 (current-time)))
16015 (default-input (and ts (org-get-compact-tod ts)))
16016 (repeater (save-excursion
16017 (save-match-data
16018 (beginning-of-line)
16019 (when (re-search-forward
16020 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16021 (save-excursion (progn (end-of-line) (point))) t)
16022 (match-string 0)))))
16023 org-time-was-given org-end-time-was-given time)
16024 (cond
16025 ((and (org-at-timestamp-p t)
16026 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16027 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16028 (insert "--")
16029 (setq time (let ((this-command this-command))
16030 (org-read-date arg 'totime nil nil
16031 default-time default-input inactive)))
16032 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16033 ((org-at-timestamp-p t)
16034 (setq time (let ((this-command this-command))
16035 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16036 (when (org-at-timestamp-p t) ; just to get the match data
16037 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16038 (replace-match "")
16039 (setq org-last-changed-timestamp
16040 (org-insert-time-stamp
16041 time (or org-time-was-given arg)
16042 inactive nil nil (list org-end-time-was-given)))
16043 (when repeater (goto-char (1- (point))) (insert " " repeater)
16044 (setq org-last-changed-timestamp
16045 (concat (substring org-last-inserted-timestamp 0 -1)
16046 " " repeater ">"))))
16047 (message "Timestamp updated"))
16048 ((equal arg '(16))
16049 (org-insert-time-stamp (current-time) t))
16051 (setq time (let ((this-command this-command))
16052 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16053 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16054 nil nil (list org-end-time-was-given))))))
16056 ;; FIXME: can we use this for something else, like computing time differences?
16057 (defun org-get-compact-tod (s)
16058 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16059 (let* ((t1 (match-string 1 s))
16060 (h1 (string-to-number (match-string 2 s)))
16061 (m1 (string-to-number (match-string 3 s)))
16062 (t2 (and (match-end 4) (match-string 5 s)))
16063 (h2 (and t2 (string-to-number (match-string 6 s))))
16064 (m2 (and t2 (string-to-number (match-string 7 s))))
16065 dh dm)
16066 (if (not t2)
16068 (setq dh (- h2 h1) dm (- m2 m1))
16069 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16070 (concat t1 "+" (number-to-string dh)
16071 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16073 (defun org-time-stamp-inactive (&optional arg)
16074 "Insert an inactive time stamp.
16075 An inactive time stamp is enclosed in square brackets instead of angle
16076 brackets. It is inactive in the sense that it does not trigger agenda entries,
16077 does not link to the calendar and cannot be changed with the S-cursor keys.
16078 So these are more for recording a certain time/date."
16079 (interactive "P")
16080 (org-time-stamp arg 'inactive))
16082 (defvar org-date-ovl (make-overlay 1 1))
16083 (overlay-put org-date-ovl 'face 'org-date-selected)
16084 (org-detach-overlay org-date-ovl)
16086 (defvar org-ans1) ; dynamically scoped parameter
16087 (defvar org-ans2) ; dynamically scoped parameter
16089 (defvar org-plain-time-of-day-regexp) ; defined below
16091 (defvar org-overriding-default-time nil) ; dynamically scoped
16092 (defvar org-read-date-overlay nil)
16093 (defvar org-dcst nil) ; dynamically scoped
16094 (defvar org-read-date-history nil)
16095 (defvar org-read-date-final-answer nil)
16096 (defvar org-read-date-analyze-futurep nil)
16097 (defvar org-read-date-analyze-forced-year nil)
16098 (defvar org-read-date-inactive)
16100 (defvar org-read-date-minibuffer-local-map
16101 (let ((map (make-sparse-keymap)))
16102 (set-keymap-parent map minibuffer-local-map)
16103 (org-defkey map (kbd ".")
16104 (lambda () (interactive)
16105 ;; Are we at the beginning of the prompt?
16106 (if (looking-back "^[^:]+: ")
16107 (org-eval-in-calendar '(calendar-goto-today))
16108 (insert "."))))
16109 (org-defkey map (kbd "C-.")
16110 (lambda () (interactive)
16111 (org-eval-in-calendar '(calendar-goto-today))))
16112 (org-defkey map [(meta shift left)]
16113 (lambda () (interactive)
16114 (org-eval-in-calendar '(calendar-backward-month 1))))
16115 (org-defkey map [(meta shift right)]
16116 (lambda () (interactive)
16117 (org-eval-in-calendar '(calendar-forward-month 1))))
16118 (org-defkey map [(meta shift up)]
16119 (lambda () (interactive)
16120 (org-eval-in-calendar '(calendar-backward-year 1))))
16121 (org-defkey map [(meta shift down)]
16122 (lambda () (interactive)
16123 (org-eval-in-calendar '(calendar-forward-year 1))))
16124 (org-defkey map [?\e (shift left)]
16125 (lambda () (interactive)
16126 (org-eval-in-calendar '(calendar-backward-month 1))))
16127 (org-defkey map [?\e (shift right)]
16128 (lambda () (interactive)
16129 (org-eval-in-calendar '(calendar-forward-month 1))))
16130 (org-defkey map [?\e (shift up)]
16131 (lambda () (interactive)
16132 (org-eval-in-calendar '(calendar-backward-year 1))))
16133 (org-defkey map [?\e (shift down)]
16134 (lambda () (interactive)
16135 (org-eval-in-calendar '(calendar-forward-year 1))))
16136 (org-defkey map [(shift up)]
16137 (lambda () (interactive)
16138 (org-eval-in-calendar '(calendar-backward-week 1))))
16139 (org-defkey map [(shift down)]
16140 (lambda () (interactive)
16141 (org-eval-in-calendar '(calendar-forward-week 1))))
16142 (org-defkey map [(shift left)]
16143 (lambda () (interactive)
16144 (org-eval-in-calendar '(calendar-backward-day 1))))
16145 (org-defkey map [(shift right)]
16146 (lambda () (interactive)
16147 (org-eval-in-calendar '(calendar-forward-day 1))))
16148 (org-defkey map "!"
16149 (lambda () (interactive)
16150 (org-eval-in-calendar '(diary-view-entries))
16151 (message "")))
16152 (org-defkey map ">"
16153 (lambda () (interactive)
16154 (org-eval-in-calendar '(scroll-calendar-left 1))))
16155 (org-defkey map "<"
16156 (lambda () (interactive)
16157 (org-eval-in-calendar '(scroll-calendar-right 1))))
16158 (org-defkey map "\C-v"
16159 (lambda () (interactive)
16160 (org-eval-in-calendar
16161 '(calendar-scroll-left-three-months 1))))
16162 (org-defkey map "\M-v"
16163 (lambda () (interactive)
16164 (org-eval-in-calendar
16165 '(calendar-scroll-right-three-months 1))))
16166 map)
16167 "Keymap for minibuffer commands when using `org-read-date'.")
16169 (defun org-read-date (&optional org-with-time to-time from-string prompt
16170 default-time default-input inactive)
16171 "Read a date, possibly a time, and make things smooth for the user.
16172 The prompt will suggest to enter an ISO date, but you can also enter anything
16173 which will at least partially be understood by `parse-time-string'.
16174 Unrecognized parts of the date will default to the current day, month, year,
16175 hour and minute. If this command is called to replace a timestamp at point,
16176 or to enter the second timestamp of a range, the default time is taken
16177 from the existing stamp. Furthermore, the command prefers the future,
16178 so if you are giving a date where the year is not given, and the day-month
16179 combination is already past in the current year, it will assume you
16180 mean next year. For details, see the manual. A few examples:
16182 3-2-5 --> 2003-02-05
16183 feb 15 --> currentyear-02-15
16184 2/15 --> currentyear-02-15
16185 sep 12 9 --> 2009-09-12
16186 12:45 --> today 12:45
16187 22 sept 0:34 --> currentyear-09-22 0:34
16188 12 --> currentyear-currentmonth-12
16189 Fri --> nearest Friday after today
16190 -Tue --> last Tuesday
16191 etc.
16193 Furthermore you can specify a relative date by giving, as the *first* thing
16194 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16195 change in days weeks, months, years.
16196 With a single plus or minus, the date is relative to today. With a double
16197 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16198 +4d --> four days from today
16199 +4 --> same as above
16200 +2w --> two weeks from today
16201 ++5 --> five days from default date
16203 The function understands only English month and weekday abbreviations.
16205 While prompting, a calendar is popped up - you can also select the
16206 date with the mouse (button 1). The calendar shows a period of three
16207 months. To scroll it to other months, use the keys `>' and `<'.
16208 If you don't like the calendar, turn it off with
16209 \(setq org-read-date-popup-calendar nil)
16211 With optional argument TO-TIME, the date will immediately be converted
16212 to an internal time.
16213 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16214 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16215 still enter a time, and this function will inform the calling routine
16216 about this change. The calling routine may then choose to change the
16217 format used to insert the time stamp into the buffer to include the time.
16218 With optional argument FROM-STRING, read from this string instead from
16219 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16220 the time/date that is used for everything that is not specified by the
16221 user."
16222 (require 'parse-time)
16223 (let* ((org-time-stamp-rounding-minutes
16224 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16225 (org-dcst org-display-custom-times)
16226 (ct (org-current-time))
16227 (org-def (or org-overriding-default-time default-time ct))
16228 (org-defdecode (decode-time org-def))
16229 (dummy (progn
16230 (when (< (nth 2 org-defdecode) org-extend-today-until)
16231 (setcar (nthcdr 2 org-defdecode) -1)
16232 (setcar (nthcdr 1 org-defdecode) 59)
16233 (setq org-def (apply 'encode-time org-defdecode)
16234 org-defdecode (decode-time org-def)))))
16235 (mouse-autoselect-window nil) ; Don't let the mouse jump
16236 (calendar-frame-setup nil)
16237 (calendar-setup nil)
16238 (calendar-move-hook nil)
16239 (calendar-view-diary-initially-flag nil)
16240 (calendar-view-holidays-initially-flag nil)
16241 (timestr (format-time-string
16242 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16243 (prompt (concat (if prompt (concat prompt " ") "")
16244 (format "Date+time [%s]: " timestr)))
16245 ans (org-ans0 "") org-ans1 org-ans2 final)
16247 (cond
16248 (from-string (setq ans from-string))
16249 (org-read-date-popup-calendar
16250 (save-excursion
16251 (save-window-excursion
16252 (calendar)
16253 (org-eval-in-calendar '(setq cursor-type nil) t)
16254 (unwind-protect
16255 (progn
16256 (calendar-forward-day (- (time-to-days org-def)
16257 (calendar-absolute-from-gregorian
16258 (calendar-current-date))))
16259 (org-eval-in-calendar nil t)
16260 (let* ((old-map (current-local-map))
16261 (map (copy-keymap calendar-mode-map))
16262 (minibuffer-local-map
16263 (copy-keymap org-read-date-minibuffer-local-map)))
16264 (org-defkey map (kbd "RET") 'org-calendar-select)
16265 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16266 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16267 (unwind-protect
16268 (progn
16269 (use-local-map map)
16270 (setq org-read-date-inactive inactive)
16271 (add-hook 'post-command-hook 'org-read-date-display)
16272 (setq org-ans0 (read-string prompt default-input
16273 'org-read-date-history nil))
16274 ;; org-ans0: from prompt
16275 ;; org-ans1: from mouse click
16276 ;; org-ans2: from calendar motion
16277 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16278 (remove-hook 'post-command-hook 'org-read-date-display)
16279 (use-local-map old-map)
16280 (when org-read-date-overlay
16281 (delete-overlay org-read-date-overlay)
16282 (setq org-read-date-overlay nil)))))
16283 (bury-buffer "*Calendar*")))))
16285 (t ; Naked prompt only
16286 (unwind-protect
16287 (setq ans (read-string prompt default-input
16288 'org-read-date-history timestr))
16289 (when org-read-date-overlay
16290 (delete-overlay org-read-date-overlay)
16291 (setq org-read-date-overlay nil)))))
16293 (setq final (org-read-date-analyze ans org-def org-defdecode))
16295 (when org-read-date-analyze-forced-year
16296 (message "Year was forced into %s"
16297 (if org-read-date-force-compatible-dates
16298 "compatible range (1970-2037)"
16299 "range representable on this machine"))
16300 (ding))
16302 ;; One round trip to get rid of 34th of August and stuff like that....
16303 (setq final (decode-time (apply 'encode-time final)))
16305 (setq org-read-date-final-answer ans)
16307 (if to-time
16308 (apply 'encode-time final)
16309 (if (and (boundp 'org-time-was-given) org-time-was-given)
16310 (format "%04d-%02d-%02d %02d:%02d"
16311 (nth 5 final) (nth 4 final) (nth 3 final)
16312 (nth 2 final) (nth 1 final))
16313 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16315 (defvar org-def)
16316 (defvar org-defdecode)
16317 (defvar org-with-time)
16318 (defun org-read-date-display ()
16319 "Display the current date prompt interpretation in the minibuffer."
16320 (when org-read-date-display-live
16321 (when org-read-date-overlay
16322 (delete-overlay org-read-date-overlay))
16323 (when (minibufferp (current-buffer))
16324 (save-excursion
16325 (end-of-line 1)
16326 (while (not (equal (buffer-substring
16327 (max (point-min) (- (point) 4)) (point))
16328 " "))
16329 (insert " ")))
16330 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16331 " " (or org-ans1 org-ans2)))
16332 (org-end-time-was-given nil)
16333 (f (org-read-date-analyze ans org-def org-defdecode))
16334 (fmts (if org-dcst
16335 org-time-stamp-custom-formats
16336 org-time-stamp-formats))
16337 (fmt (if (or org-with-time
16338 (and (boundp 'org-time-was-given) org-time-was-given))
16339 (cdr fmts)
16340 (car fmts)))
16341 (txt (format-time-string fmt (apply 'encode-time f)))
16342 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16343 (txt (concat "=> " txt)))
16344 (when (and org-end-time-was-given
16345 (string-match org-plain-time-of-day-regexp txt))
16346 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16347 org-end-time-was-given
16348 (substring txt (match-end 0)))))
16349 (when org-read-date-analyze-futurep
16350 (setq txt (concat txt " (=>F)")))
16351 (setq org-read-date-overlay
16352 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16353 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16355 (defun org-read-date-analyze (ans org-def org-defdecode)
16356 "Analyze the combined answer of the date prompt."
16357 ;; FIXME: cleanup and comment
16358 (let ((nowdecode (decode-time (current-time)))
16359 delta deltan deltaw deltadef year month day
16360 hour minute second wday pm h2 m2 tl wday1
16361 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16362 (setq org-read-date-analyze-futurep nil
16363 org-read-date-analyze-forced-year nil)
16364 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16365 (setq ans "+0"))
16367 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16368 (setq ans (replace-match "" t t ans)
16369 deltan (car delta)
16370 deltaw (nth 1 delta)
16371 deltadef (nth 2 delta)))
16373 ;; Check if there is an iso week date in there. If yes, store the
16374 ;; info and postpone interpreting it until the rest of the parsing
16375 ;; is done.
16376 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16377 (setq iso-year (if (match-end 1)
16378 (org-small-year-to-year
16379 (string-to-number (match-string 1 ans))))
16380 iso-weekday (if (match-end 3)
16381 (string-to-number (match-string 3 ans)))
16382 iso-week (string-to-number (match-string 2 ans)))
16383 (setq ans (replace-match "" t t ans)))
16385 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16386 (when (string-match
16387 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16388 (setq year (if (match-end 2)
16389 (string-to-number (match-string 2 ans))
16390 (progn (setq kill-year t)
16391 (string-to-number (format-time-string "%Y"))))
16392 month (string-to-number (match-string 3 ans))
16393 day (string-to-number (match-string 4 ans)))
16394 (if (< year 100) (setq year (+ 2000 year)))
16395 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16396 t nil ans)))
16398 ;; Help matching dotted european dates
16399 (when (string-match
16400 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16401 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16402 (setq kill-year t)
16403 (string-to-number (format-time-string "%Y")))
16404 day (string-to-number (match-string 1 ans))
16405 month (string-to-number (match-string 2 ans))
16406 ans (replace-match (format "%04d-%02d-%02d" year month day)
16407 t nil ans)))
16409 ;; Help matching american dates, like 5/30 or 5/30/7
16410 (when (string-match
16411 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16412 (setq year (if (match-end 4)
16413 (string-to-number (match-string 4 ans))
16414 (progn (setq kill-year t)
16415 (string-to-number (format-time-string "%Y"))))
16416 month (string-to-number (match-string 1 ans))
16417 day (string-to-number (match-string 2 ans)))
16418 (if (< year 100) (setq year (+ 2000 year)))
16419 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16420 t nil ans)))
16421 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16422 ;; If there is a time with am/pm, and *no* time without it, we convert
16423 ;; so that matching will be successful.
16424 (loop for i from 1 to 2 do ; twice, for end time as well
16425 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16426 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16427 (setq hour (string-to-number (match-string 1 ans))
16428 minute (if (match-end 3)
16429 (string-to-number (match-string 3 ans))
16431 pm (equal ?p
16432 (string-to-char (downcase (match-string 4 ans)))))
16433 (if (and (= hour 12) (not pm))
16434 (setq hour 0)
16435 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16436 (setq ans (replace-match (format "%02d:%02d" hour minute)
16437 t t ans))))
16439 ;; Check if a time range is given as a duration
16440 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16441 (setq hour (string-to-number (match-string 1 ans))
16442 h2 (+ hour (string-to-number (match-string 3 ans)))
16443 minute (string-to-number (match-string 2 ans))
16444 m2 (+ minute (if (match-end 5) (string-to-number
16445 (match-string 5 ans))0)))
16446 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16447 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16448 t t ans)))
16450 ;; Check if there is a time range
16451 (when (boundp 'org-end-time-was-given)
16452 (setq org-time-was-given nil)
16453 (when (and (string-match org-plain-time-of-day-regexp ans)
16454 (match-end 8))
16455 (setq org-end-time-was-given (match-string 8 ans))
16456 (setq ans (concat (substring ans 0 (match-beginning 7))
16457 (substring ans (match-end 7))))))
16459 (setq tl (parse-time-string ans)
16460 day (or (nth 3 tl) (nth 3 org-defdecode))
16461 month (or (nth 4 tl)
16462 (if (and org-read-date-prefer-future
16463 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16464 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16465 (nth 4 org-defdecode)))
16466 year (or (and (not kill-year) (nth 5 tl))
16467 (if (and org-read-date-prefer-future
16468 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16469 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16470 (nth 5 org-defdecode)))
16471 hour (or (nth 2 tl) (nth 2 org-defdecode))
16472 minute (or (nth 1 tl) (nth 1 org-defdecode))
16473 second (or (nth 0 tl) 0)
16474 wday (nth 6 tl))
16476 (when (and (eq org-read-date-prefer-future 'time)
16477 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16478 (equal day (nth 3 nowdecode))
16479 (equal month (nth 4 nowdecode))
16480 (equal year (nth 5 nowdecode))
16481 (nth 2 tl)
16482 (or (< (nth 2 tl) (nth 2 nowdecode))
16483 (and (= (nth 2 tl) (nth 2 nowdecode))
16484 (nth 1 tl)
16485 (< (nth 1 tl) (nth 1 nowdecode)))))
16486 (setq day (1+ day)
16487 futurep t))
16489 ;; Special date definitions below
16490 (cond
16491 (iso-week
16492 ;; There was an iso week
16493 (require 'cal-iso)
16494 (setq futurep nil)
16495 (setq year (or iso-year year)
16496 day (or iso-weekday wday 1)
16497 wday nil ; to make sure that the trigger below does not match
16498 iso-date (calendar-gregorian-from-absolute
16499 (calendar-absolute-from-iso
16500 (list iso-week day year))))
16501 ; FIXME: Should we also push ISO weeks into the future?
16502 ; (when (and org-read-date-prefer-future
16503 ; (not iso-year)
16504 ; (< (calendar-absolute-from-gregorian iso-date)
16505 ; (time-to-days (current-time))))
16506 ; (setq year (1+ year)
16507 ; iso-date (calendar-gregorian-from-absolute
16508 ; (calendar-absolute-from-iso
16509 ; (list iso-week day year)))))
16510 (setq month (car iso-date)
16511 year (nth 2 iso-date)
16512 day (nth 1 iso-date)))
16513 (deltan
16514 (setq futurep nil)
16515 (unless deltadef
16516 (let ((now (decode-time (current-time))))
16517 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16518 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16519 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16520 ((equal deltaw "m") (setq month (+ month deltan)))
16521 ((equal deltaw "y") (setq year (+ year deltan)))))
16522 ((and wday (not (nth 3 tl)))
16523 ;; Weekday was given, but no day, so pick that day in the week
16524 ;; on or after the derived date.
16525 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16526 (unless (equal wday wday1)
16527 (setq day (+ day (% (- wday wday1 -7) 7))))))
16528 (if (and (boundp 'org-time-was-given)
16529 (nth 2 tl))
16530 (setq org-time-was-given t))
16531 (if (< year 100) (setq year (+ 2000 year)))
16532 ;; Check of the date is representable
16533 (if org-read-date-force-compatible-dates
16534 (progn
16535 (if (< year 1970)
16536 (setq year 1970 org-read-date-analyze-forced-year t))
16537 (if (> year 2037)
16538 (setq year 2037 org-read-date-analyze-forced-year t)))
16539 (condition-case nil
16540 (ignore (encode-time second minute hour day month year))
16541 (error
16542 (setq year (nth 5 org-defdecode))
16543 (setq org-read-date-analyze-forced-year t))))
16544 (setq org-read-date-analyze-futurep futurep)
16545 (list second minute hour day month year)))
16547 (defvar parse-time-weekdays)
16548 (defun org-read-date-get-relative (s today default)
16549 "Check string S for special relative date string.
16550 TODAY and DEFAULT are internal times, for today and for a default.
16551 Return shift list (N what def-flag)
16552 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16553 N is the number of WHATs to shift.
16554 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16555 the DEFAULT date rather than TODAY."
16556 (require 'parse-time)
16557 (when (and
16558 (string-match
16559 (concat
16560 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16561 "\\([0-9]+\\)?"
16562 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16563 "\\([ \t]\\|$\\)") s)
16564 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16565 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16566 (string-to-char (substring (match-string 1 s) -1))
16567 ?+))
16568 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16569 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16570 (what (if (match-end 3) (match-string 3 s) "d"))
16571 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16572 (date (if rel default today))
16573 (wday (nth 6 (decode-time date)))
16574 delta)
16575 (if wday1
16576 (progn
16577 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16578 (if (= delta 0) (setq delta 7))
16579 (if (= dir ?-)
16580 (progn
16581 (setq delta (- delta 7))
16582 (if (= delta 0) (setq delta -7))))
16583 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16584 (list delta "d" rel))
16585 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16587 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16588 "Turn a user-specified date into the internal representation.
16589 The internal representation needed by the calendar is (month day year).
16590 This is a wrapper to handle the brain-dead convention in calendar that
16591 user function argument order change dependent on argument order."
16592 (if (boundp 'calendar-date-style)
16593 (cond
16594 ((eq calendar-date-style 'american)
16595 (list arg1 arg2 arg3))
16596 ((eq calendar-date-style 'european)
16597 (list arg2 arg1 arg3))
16598 ((eq calendar-date-style 'iso)
16599 (list arg2 arg3 arg1)))
16600 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16601 (if (org-bound-and-true-p european-calendar-style)
16602 (list arg2 arg1 arg3)
16603 (list arg1 arg2 arg3)))))
16605 (defun org-eval-in-calendar (form &optional keepdate)
16606 "Eval FORM in the calendar window and return to current window.
16607 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16608 otherwise stick to the current value of `org-ans2'."
16609 (let ((sf (selected-frame))
16610 (sw (selected-window)))
16611 (select-window (get-buffer-window "*Calendar*" t))
16612 (eval form)
16613 (when (and (not keepdate) (calendar-cursor-to-date))
16614 (let* ((date (calendar-cursor-to-date))
16615 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16616 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16617 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16618 (select-window sw)
16619 (org-select-frame-set-input-focus sf)))
16621 (defun org-calendar-select ()
16622 "Return to `org-read-date' with the date currently selected.
16623 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16624 (interactive)
16625 (when (calendar-cursor-to-date)
16626 (let* ((date (calendar-cursor-to-date))
16627 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16628 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16629 (if (active-minibuffer-window) (exit-minibuffer))))
16631 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16632 "Insert a date stamp for the date given by the internal TIME.
16633 WITH-HM means use the stamp format that includes the time of the day.
16634 INACTIVE means use square brackets instead of angular ones, so that the
16635 stamp will not contribute to the agenda.
16636 PRE and POST are optional strings to be inserted before and after the
16637 stamp.
16638 The command returns the inserted time stamp."
16639 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16640 stamp)
16641 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16642 (insert-before-markers (or pre ""))
16643 (when (listp extra)
16644 (setq extra (car extra))
16645 (if (and (stringp extra)
16646 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16647 (setq extra (format "-%02d:%02d"
16648 (string-to-number (match-string 1 extra))
16649 (string-to-number (match-string 2 extra))))
16650 (setq extra nil)))
16651 (when extra
16652 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16653 (insert-before-markers (setq stamp (format-time-string fmt time)))
16654 (insert-before-markers (or post ""))
16655 (setq org-last-inserted-timestamp stamp)))
16657 (defun org-toggle-time-stamp-overlays ()
16658 "Toggle the use of custom time stamp formats."
16659 (interactive)
16660 (setq org-display-custom-times (not org-display-custom-times))
16661 (unless org-display-custom-times
16662 (let ((p (point-min)) (bmp (buffer-modified-p)))
16663 (while (setq p (next-single-property-change p 'display))
16664 (if (and (get-text-property p 'display)
16665 (eq (get-text-property p 'face) 'org-date))
16666 (remove-text-properties
16667 p (setq p (next-single-property-change p 'display))
16668 '(display t))))
16669 (set-buffer-modified-p bmp)))
16670 (if (featurep 'xemacs)
16671 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16672 (org-restart-font-lock)
16673 (setq org-table-may-need-update t)
16674 (if org-display-custom-times
16675 (message "Time stamps are overlaid with custom format")
16676 (message "Time stamp overlays removed")))
16678 (defun org-display-custom-time (beg end)
16679 "Overlay modified time stamp format over timestamp between BEG and END."
16680 (let* ((ts (buffer-substring beg end))
16681 t1 w1 with-hm tf time str w2 (off 0))
16682 (save-match-data
16683 (setq t1 (org-parse-time-string ts t))
16684 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16685 (setq off (- (match-end 0) (match-beginning 0)))))
16686 (setq end (- end off))
16687 (setq w1 (- end beg)
16688 with-hm (and (nth 1 t1) (nth 2 t1))
16689 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16690 time (org-fix-decoded-time t1)
16691 str (org-add-props
16692 (format-time-string
16693 (substring tf 1 -1) (apply 'encode-time time))
16694 nil 'mouse-face 'highlight)
16695 w2 (length str))
16696 (if (not (= w2 w1))
16697 (add-text-properties (1+ beg) (+ 2 beg)
16698 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16699 (if (featurep 'xemacs)
16700 (progn
16701 (put-text-property beg end 'invisible t)
16702 (put-text-property beg end 'end-glyph (make-glyph str)))
16703 (put-text-property beg end 'display str))))
16705 (defun org-translate-time (string)
16706 "Translate all timestamps in STRING to custom format.
16707 But do this only if the variable `org-display-custom-times' is set."
16708 (when org-display-custom-times
16709 (save-match-data
16710 (let* ((start 0)
16711 (re org-ts-regexp-both)
16712 t1 with-hm inactive tf time str beg end)
16713 (while (setq start (string-match re string start))
16714 (setq beg (match-beginning 0)
16715 end (match-end 0)
16716 t1 (save-match-data
16717 (org-parse-time-string (substring string beg end) t))
16718 with-hm (and (nth 1 t1) (nth 2 t1))
16719 inactive (equal (substring string beg (1+ beg)) "[")
16720 tf (funcall (if with-hm 'cdr 'car)
16721 org-time-stamp-custom-formats)
16722 time (org-fix-decoded-time t1)
16723 str (format-time-string
16724 (concat
16725 (if inactive "[" "<") (substring tf 1 -1)
16726 (if inactive "]" ">"))
16727 (apply 'encode-time time))
16728 string (replace-match str t t string)
16729 start (+ start (length str)))))))
16730 string)
16732 (defun org-fix-decoded-time (time)
16733 "Set 0 instead of nil for the first 6 elements of time.
16734 Don't touch the rest."
16735 (let ((n 0))
16736 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16738 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16740 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16741 "Difference between TIMESTAMP-STRING and now in days.
16742 If SECONDS is non-nil, return the difference in seconds."
16743 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16744 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16745 (funcall fdiff (current-time)))))
16747 (defun org-deadline-close (timestamp-string &optional ndays)
16748 "Is the time in TIMESTAMP-STRING close to the current date?"
16749 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16750 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16751 (not (org-entry-is-done-p))))
16753 (defun org-get-wdays (ts &optional delay zero-delay)
16754 "Get the deadline lead time appropriate for timestring TS.
16755 When DELAY is non-nil, get the delay time for scheduled items
16756 instead of the deadline lead time. When ZERO-DELAY is non-nil
16757 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16758 don't try to find the delay cookie in the scheduled timestamp."
16759 (let ((tv (if delay org-scheduled-delay-days
16760 org-deadline-warning-days)))
16761 (cond
16762 ((or (and delay (< tv 0))
16763 (and delay zero-delay (<= tv 0))
16764 (and (not delay) (<= tv 0)))
16765 ;; Enforce this value no matter what
16766 (- tv))
16767 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16768 ;; lead time is specified.
16769 (floor (* (string-to-number (match-string 1 ts))
16770 (cdr (assoc (match-string 2 ts)
16771 '(("d" . 1) ("w" . 7)
16772 ("m" . 30.4) ("y" . 365.25)
16773 ("h" . 0.041667)))))))
16774 ;; go for the default.
16775 (t tv))))
16777 (defun org-calendar-select-mouse (ev)
16778 "Return to `org-read-date' with the date currently selected.
16779 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16780 (interactive "e")
16781 (mouse-set-point ev)
16782 (when (calendar-cursor-to-date)
16783 (let* ((date (calendar-cursor-to-date))
16784 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16785 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16786 (if (active-minibuffer-window) (exit-minibuffer))))
16788 (defun org-check-deadlines (ndays)
16789 "Check if there are any deadlines due or past due.
16790 A deadline is considered due if it happens within `org-deadline-warning-days'
16791 days from today's date. If the deadline appears in an entry marked DONE,
16792 it is not shown. The prefix arg NDAYS can be used to test that many
16793 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16794 (interactive "P")
16795 (let* ((org-warn-days
16796 (cond
16797 ((equal ndays '(4)) 100000)
16798 (ndays (prefix-numeric-value ndays))
16799 (t (abs org-deadline-warning-days))))
16800 (case-fold-search nil)
16801 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16802 (callback
16803 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16805 (message "%d deadlines past-due or due within %d days"
16806 (org-occur regexp nil callback)
16807 org-warn-days)))
16809 (defsubst org-re-timestamp (type)
16810 "Return a regexp for timestamp TYPE.
16811 Allowed values for TYPE are:
16813 all: all timestamps
16814 active: only active timestamps (<...>)
16815 inactive: only inactive timestamps ([...])
16816 scheduled: only scheduled timestamps
16817 deadline: only deadline timestamps
16818 closed: only closed time-stamps
16820 When TYPE is nil, fall back on returning a regexp that matches
16821 both scheduled and deadline timestamps."
16822 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16823 ((eq type 'active) org-ts-regexp)
16824 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16825 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16826 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16827 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16828 ((eq type 'scheduled-or-deadline)
16829 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16831 (defun org-check-before-date (date)
16832 "Check if there are deadlines or scheduled entries before DATE."
16833 (interactive (list (org-read-date)))
16834 (let ((case-fold-search nil)
16835 (regexp (org-re-timestamp org-ts-type))
16836 (callback
16837 (lambda () (time-less-p
16838 (org-time-string-to-time (match-string 1))
16839 (org-time-string-to-time date)))))
16840 (message "%d entries before %s"
16841 (org-occur regexp nil callback) date)))
16843 (defun org-check-after-date (date)
16844 "Check if there are deadlines or scheduled entries after DATE."
16845 (interactive (list (org-read-date)))
16846 (let ((case-fold-search nil)
16847 (regexp (org-re-timestamp org-ts-type))
16848 (callback
16849 (lambda () (not
16850 (time-less-p
16851 (org-time-string-to-time (match-string 1))
16852 (org-time-string-to-time date))))))
16853 (message "%d entries after %s"
16854 (org-occur regexp nil callback) date)))
16856 (defun org-check-dates-range (start-date end-date)
16857 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16858 (interactive (list (org-read-date nil nil nil "Range starts")
16859 (org-read-date nil nil nil "Range end")))
16860 (let ((case-fold-search nil)
16861 (regexp (org-re-timestamp org-ts-type))
16862 (callback
16863 (lambda ()
16864 (let ((match (match-string 1)))
16865 (and
16866 (not (time-less-p
16867 (org-time-string-to-time match)
16868 (org-time-string-to-time start-date)))
16869 (time-less-p
16870 (org-time-string-to-time match)
16871 (org-time-string-to-time end-date)))))))
16872 (message "%d entries between %s and %s"
16873 (org-occur regexp nil callback) start-date end-date)))
16875 (defun org-evaluate-time-range (&optional to-buffer)
16876 "Evaluate a time range by computing the difference between start and end.
16877 Normally the result is just printed in the echo area, but with prefix arg
16878 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16879 If the time range is actually in a table, the result is inserted into the
16880 next column.
16881 For time difference computation, a year is assumed to be exactly 365
16882 days in order to avoid rounding problems."
16883 (interactive "P")
16885 (org-clock-update-time-maybe)
16886 (save-excursion
16887 (unless (org-at-date-range-p t)
16888 (goto-char (point-at-bol))
16889 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16890 (if (not (org-at-date-range-p t))
16891 (user-error "Not at a time-stamp range, and none found in current line")))
16892 (let* ((ts1 (match-string 1))
16893 (ts2 (match-string 2))
16894 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16895 (match-end (match-end 0))
16896 (time1 (org-time-string-to-time ts1))
16897 (time2 (org-time-string-to-time ts2))
16898 (t1 (org-float-time time1))
16899 (t2 (org-float-time time2))
16900 (diff (abs (- t2 t1)))
16901 (negative (< (- t2 t1) 0))
16902 ;; (ys (floor (* 365 24 60 60)))
16903 (ds (* 24 60 60))
16904 (hs (* 60 60))
16905 (fy "%dy %dd %02d:%02d")
16906 (fy1 "%dy %dd")
16907 (fd "%dd %02d:%02d")
16908 (fd1 "%dd")
16909 (fh "%02d:%02d")
16910 y d h m align)
16911 (if havetime
16912 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16914 d (floor (/ diff ds)) diff (mod diff ds)
16915 h (floor (/ diff hs)) diff (mod diff hs)
16916 m (floor (/ diff 60)))
16917 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16919 d (floor (+ (/ diff ds) 0.5))
16920 h 0 m 0))
16921 (if (not to-buffer)
16922 (message "%s" (org-make-tdiff-string y d h m))
16923 (if (org-at-table-p)
16924 (progn
16925 (goto-char match-end)
16926 (setq align t)
16927 (and (looking-at " *|") (goto-char (match-end 0))))
16928 (goto-char match-end))
16929 (if (looking-at
16930 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16931 (replace-match ""))
16932 (if negative (insert " -"))
16933 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16934 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16935 (insert " " (format fh h m))))
16936 (if align (org-table-align))
16937 (message "Time difference inserted")))))
16939 (defun org-make-tdiff-string (y d h m)
16940 (let ((fmt "")
16941 (l nil))
16942 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16943 l (push y l)))
16944 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16945 l (push d l)))
16946 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16947 l (push h l)))
16948 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16949 l (push m l)))
16950 (apply 'format fmt (nreverse l))))
16952 (defun org-time-string-to-time (s &optional buffer pos)
16953 "Convert a timestamp string into internal time."
16954 (condition-case errdata
16955 (apply 'encode-time (org-parse-time-string s))
16956 (error (error "Bad timestamp `%s'%s\nError was: %s"
16957 s (if (not (and buffer pos))
16959 (format " at %d in buffer `%s'" pos buffer))
16960 (cdr errdata)))))
16962 (defun org-time-string-to-seconds (s)
16963 "Convert a timestamp string to a number of seconds."
16964 (org-float-time (org-time-string-to-time s)))
16966 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16967 "Convert a time stamp to an absolute day number.
16968 If there is a specifier for a cyclic time stamp, get the closest
16969 date to DAYNR.
16970 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16971 The variable `date' is bound by the calendar when this is called."
16972 (cond
16973 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16974 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16975 daynr
16976 (+ daynr 1000)))
16977 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16978 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16979 (time-to-days (current-time))) (match-string 0 s)
16980 prefer show-all))
16981 (t (time-to-days
16982 (condition-case errdata
16983 (apply 'encode-time (org-parse-time-string s))
16984 (error (error "Bad timestamp `%s'%s\nError was: %s"
16985 s (if (not (and buffer pos))
16987 (format " at %d in buffer `%s'" pos buffer))
16988 (cdr errdata))))))))
16990 (defun org-days-to-iso-week (days)
16991 "Return the iso week number."
16992 (require 'cal-iso)
16993 (car (calendar-iso-from-absolute days)))
16995 (defun org-small-year-to-year (year)
16996 "Convert 2-digit years into 4-digit years.
16997 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
16998 The year 2000 cannot be abbreviated. Any year larger than 99
16999 is returned unchanged."
17000 (if (< year 38)
17001 (setq year (+ 2000 year))
17002 (if (< year 100)
17003 (setq year (+ 1900 year))))
17004 year)
17006 (defun org-time-from-absolute (d)
17007 "Return the time corresponding to date D.
17008 D may be an absolute day number, or a calendar-type list (month day year)."
17009 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17010 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17012 (defun org-calendar-holiday ()
17013 "List of holidays, for Diary display in Org-mode."
17014 (require 'holidays)
17015 (let ((hl (funcall
17016 (if (fboundp 'calendar-check-holidays)
17017 'calendar-check-holidays 'check-calendar-holidays) date)))
17018 (if hl (mapconcat 'identity hl "; "))))
17020 (defun org-diary-sexp-entry (sexp entry date)
17021 "Process a SEXP diary ENTRY for DATE."
17022 (require 'diary-lib)
17023 (let ((result (if calendar-debug-sexp
17024 (let ((stack-trace-on-error t))
17025 (eval (car (read-from-string sexp))))
17026 (condition-case nil
17027 (eval (car (read-from-string sexp)))
17028 (error
17029 (beep)
17030 (message "Bad sexp at line %d in %s: %s"
17031 (org-current-line)
17032 (buffer-file-name) sexp)
17033 (sleep-for 2))))))
17034 (cond ((stringp result) (split-string result "; "))
17035 ((and (consp result)
17036 (not (consp (cdr result)))
17037 (stringp (cdr result))) (cdr result))
17038 ((and (consp result)
17039 (stringp (car result))) result)
17040 (result entry))))
17042 (defun org-diary-to-ical-string (frombuf)
17043 "Get iCalendar entries from diary entries in buffer FROMBUF.
17044 This uses the icalendar.el library."
17045 (let* ((tmpdir (if (featurep 'xemacs)
17046 (temp-directory)
17047 temporary-file-directory))
17048 (tmpfile (make-temp-name
17049 (expand-file-name "orgics" tmpdir)))
17050 buf rtn b e)
17051 (with-current-buffer frombuf
17052 (icalendar-export-region (point-min) (point-max) tmpfile)
17053 (setq buf (find-buffer-visiting tmpfile))
17054 (set-buffer buf)
17055 (goto-char (point-min))
17056 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17057 (setq b (match-beginning 0)))
17058 (goto-char (point-max))
17059 (if (re-search-backward "^END:VEVENT" nil t)
17060 (setq e (match-end 0)))
17061 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17062 (kill-buffer buf)
17063 (delete-file tmpfile)
17064 rtn))
17066 (defun org-closest-date (start current change prefer show-all)
17067 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17068 When PREFER is `past', return a date that is either CURRENT or past.
17069 When PREFER is `future', return a date that is either CURRENT or future.
17070 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17071 ;; Make the proper lists from the dates
17072 (catch 'exit
17073 (let ((a1 '(("h" . hour)
17074 ("d" . day)
17075 ("w" . week)
17076 ("m" . month)
17077 ("y" . year)))
17078 (shour (nth 2 (org-parse-time-string start)))
17079 dn dw sday cday n1 n2 n0
17080 d m y y1 y2 date1 date2 nmonths nm ny m2)
17082 (setq start (org-date-to-gregorian start)
17083 current (org-date-to-gregorian
17084 (if show-all
17085 current
17086 (time-to-days (current-time))))
17087 sday (calendar-absolute-from-gregorian start)
17088 cday (calendar-absolute-from-gregorian current))
17090 (if (<= cday sday) (throw 'exit sday))
17092 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17093 (setq dn (string-to-number (match-string 1 change))
17094 dw (cdr (assoc (match-string 2 change) a1)))
17095 (user-error "Invalid change specifier: %s" change))
17096 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17097 (cond
17098 ((eq dw 'hour)
17099 (let ((missing-hours
17100 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17101 dn)))
17102 (setq n1 (if (zerop missing-hours) cday
17103 (- cday (1+ (floor (/ missing-hours 24)))))
17104 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17105 ((eq dw 'day)
17106 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17107 n2 (+ n1 dn)))
17108 ((eq dw 'year)
17109 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17110 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17111 (setq date1 (list m d y1)
17112 n1 (calendar-absolute-from-gregorian date1)
17113 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17114 n2 (calendar-absolute-from-gregorian date2)))
17115 ((eq dw 'month)
17116 ;; approx number of month between the two dates
17117 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17118 ;; How often does dn fit in there?
17119 (setq d (nth 1 start) m (car start) y (nth 2 start)
17120 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17121 m (+ m nm)
17122 ny (floor (/ m 12))
17123 y (+ y ny)
17124 m (- m (* ny 12)))
17125 (while (> m 12) (setq m (- m 12) y (1+ y)))
17126 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17127 (setq m2 (+ m dn) y2 y)
17128 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17129 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17130 (while (<= n2 cday)
17131 (setq n1 n2 m m2 y y2)
17132 (setq m2 (+ m dn) y2 y)
17133 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17134 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17135 ;; Make sure n1 is the earlier date
17136 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17137 (if show-all
17138 (cond
17139 ((eq prefer 'past) (if (= cday n2) n2 n1))
17140 ((eq prefer 'future) (if (= cday n1) n1 n2))
17141 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17142 (cond
17143 ((eq prefer 'past) (if (= cday n2) n2 n1))
17144 ((eq prefer 'future) (if (= cday n1) n1 n2))
17145 (t (if (= cday n1) n1 n2)))))))
17147 (defun org-date-to-gregorian (date)
17148 "Turn any specification of DATE into a Gregorian date for the calendar."
17149 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17150 ((and (listp date) (= (length date) 3)) date)
17151 ((stringp date)
17152 (setq date (org-parse-time-string date))
17153 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17154 ((listp date)
17155 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17157 (defun org-parse-time-string (s &optional nodefault)
17158 "Parse the standard Org-mode time string.
17159 This should be a lot faster than the normal `parse-time-string'.
17160 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17161 hour and minute fields will be nil if not given."
17162 (cond ((string-match org-ts-regexp0 s)
17163 (list 0
17164 (if (or (match-beginning 8) (not nodefault))
17165 (string-to-number (or (match-string 8 s) "0")))
17166 (if (or (match-beginning 7) (not nodefault))
17167 (string-to-number (or (match-string 7 s) "0")))
17168 (string-to-number (match-string 4 s))
17169 (string-to-number (match-string 3 s))
17170 (string-to-number (match-string 2 s))
17171 nil nil nil))
17172 ((string-match "^<[^>]+>$" s)
17173 (decode-time (seconds-to-time (org-matcher-time s))))
17174 (t (error "Not a standard Org-mode time string: %s" s))))
17176 (defun org-timestamp-up (&optional arg)
17177 "Increase the date item at the cursor by one.
17178 If the cursor is on the year, change the year. If it is on the month,
17179 the day or the time, change that.
17180 With prefix ARG, change by that many units."
17181 (interactive "p")
17182 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17184 (defun org-timestamp-down (&optional arg)
17185 "Decrease the date item at the cursor by one.
17186 If the cursor is on the year, change the year. If it is on the month,
17187 the day or the time, change that.
17188 With prefix ARG, change by that many units."
17189 (interactive "p")
17190 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17192 (defun org-timestamp-up-day (&optional arg)
17193 "Increase the date in the time stamp by one day.
17194 With prefix ARG, change that many days."
17195 (interactive "p")
17196 (if (and (not (org-at-timestamp-p t))
17197 (org-at-heading-p))
17198 (org-todo 'up)
17199 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17201 (defun org-timestamp-down-day (&optional arg)
17202 "Decrease the date in the time stamp by one day.
17203 With prefix ARG, change that many days."
17204 (interactive "p")
17205 (if (and (not (org-at-timestamp-p t))
17206 (org-at-heading-p))
17207 (org-todo 'down)
17208 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17210 (defun org-at-timestamp-p (&optional inactive-ok)
17211 "Determine if the cursor is in or at a timestamp."
17212 (interactive)
17213 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17214 (pos (point))
17215 (ans (or (looking-at tsr)
17216 (save-excursion
17217 (skip-chars-backward "^[<\n\r\t")
17218 (if (> (point) (point-min)) (backward-char 1))
17219 (and (looking-at tsr)
17220 (> (- (match-end 0) pos) -1))))))
17221 (and ans
17222 (boundp 'org-ts-what)
17223 (setq org-ts-what
17224 (cond
17225 ((= pos (match-beginning 0)) 'bracket)
17226 ;; Point is considered to be "on the bracket" whether
17227 ;; it's really on it or right after it.
17228 ((= pos (1- (match-end 0))) 'bracket)
17229 ((= pos (match-end 0)) 'after)
17230 ((org-pos-in-match-range pos 2) 'year)
17231 ((org-pos-in-match-range pos 3) 'month)
17232 ((org-pos-in-match-range pos 7) 'hour)
17233 ((org-pos-in-match-range pos 8) 'minute)
17234 ((or (org-pos-in-match-range pos 4)
17235 (org-pos-in-match-range pos 5)) 'day)
17236 ((and (> pos (or (match-end 8) (match-end 5)))
17237 (< pos (match-end 0)))
17238 (- pos (or (match-end 8) (match-end 5))))
17239 (t 'day))))
17240 ans))
17242 (defun org-toggle-timestamp-type ()
17243 "Toggle the type (<active> or [inactive]) of a time stamp."
17244 (interactive)
17245 (when (org-at-timestamp-p t)
17246 (let ((beg (match-beginning 0)) (end (match-end 0))
17247 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17248 (save-excursion
17249 (goto-char beg)
17250 (while (re-search-forward "[][<>]" end t)
17251 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17252 t t)))
17253 (message "Timestamp is now %sactive"
17254 (if (equal (char-after beg) ?<) "" "in")))))
17256 (defun org-at-clock-log-p nil
17257 "Is the cursor on the clock log line?"
17258 (save-excursion
17259 (move-beginning-of-line 1)
17260 (looking-at "^[ \t]*CLOCK:")))
17262 (defvar org-clock-history) ; defined in org-clock.el
17263 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17264 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17265 "Change the date in the time stamp at point.
17266 The date will be changed by N times WHAT. WHAT can be `day', `month',
17267 `year', `minute', `second'. If WHAT is not given, the cursor position
17268 in the timestamp determines what will be changed.
17269 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17270 (let ((origin (point)) origin-cat
17271 with-hm inactive
17272 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17273 org-ts-what
17274 extra rem
17275 ts time time0 fixnext clrgx)
17276 (if (not (org-at-timestamp-p t))
17277 (user-error "Not at a timestamp"))
17278 (if (and (not what) (eq org-ts-what 'bracket))
17279 (org-toggle-timestamp-type)
17280 ;; Point isn't on brackets. Remember the part of the time-stamp
17281 ;; the point was in. Indeed, size of time-stamps may change,
17282 ;; but point must be kept in the same category nonetheless.
17283 (setq origin-cat org-ts-what)
17284 (if (and (not what) (not (eq org-ts-what 'day))
17285 org-display-custom-times
17286 (get-text-property (point) 'display)
17287 (not (get-text-property (1- (point)) 'display)))
17288 (setq org-ts-what 'day))
17289 (setq org-ts-what (or what org-ts-what)
17290 inactive (= (char-after (match-beginning 0)) ?\[)
17291 ts (match-string 0))
17292 (replace-match "")
17293 (when (string-match
17294 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17296 (setq extra (match-string 1 ts))
17297 (if suppress-tmp-delay
17298 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17299 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17300 (setq with-hm t))
17301 (setq time0 (org-parse-time-string ts))
17302 (when (and updown
17303 (eq org-ts-what 'minute)
17304 (not current-prefix-arg))
17305 ;; This looks like s-up and s-down. Change by one rounding step.
17306 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17307 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17308 (setcar (cdr time0) (+ (nth 1 time0)
17309 (if (> n 0) (- rem) (- dm rem))))))
17310 (setq time
17311 (encode-time (or (car time0) 0)
17312 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17313 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17314 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17315 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17316 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17317 (nthcdr 6 time0)))
17318 (when (and (member org-ts-what '(hour minute))
17319 extra
17320 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17321 (setq extra (org-modify-ts-extra
17322 extra
17323 (if (eq org-ts-what 'hour) 2 5)
17324 n dm)))
17325 (when (integerp org-ts-what)
17326 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17327 (if (eq what 'calendar)
17328 (let ((cal-date (org-get-date-from-calendar)))
17329 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17330 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17331 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17332 (setcar time0 (or (car time0) 0))
17333 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17334 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17335 (setq time (apply 'encode-time time0))))
17336 ;; Insert the new time-stamp, and ensure point stays in the same
17337 ;; category as before (i.e. not after the last position in that
17338 ;; category).
17339 (let ((pos (point)))
17340 ;; Stay before inserted string. `save-excursion' is of no use.
17341 (setq org-last-changed-timestamp
17342 (org-insert-time-stamp time with-hm inactive nil nil extra))
17343 (goto-char pos))
17344 (save-match-data
17345 (looking-at org-ts-regexp3)
17346 (goto-char (cond
17347 ;; `day' category ends before `hour' if any, or at
17348 ;; the end of the day name.
17349 ((eq origin-cat 'day)
17350 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17351 ((eq origin-cat 'hour) (min (match-end 7) origin))
17352 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17353 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17354 ;; `year' and `month' have both fixed size: point
17355 ;; couldn't have moved into another part.
17356 (t origin))))
17357 ;; Update clock if on a CLOCK line.
17358 (org-clock-update-time-maybe)
17359 ;; Maybe adjust the closest clock in `org-clock-history'
17360 (when org-clock-adjust-closest
17361 (if (not (and (org-at-clock-log-p)
17362 (< 1 (length (delq nil (mapcar 'marker-position
17363 org-clock-history))))))
17364 (message "No clock to adjust")
17365 (cond ((save-excursion ; fix previous clock?
17366 (re-search-backward org-ts-regexp0 nil t)
17367 (org-looking-back (concat org-clock-string " \\[")))
17368 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17369 ((save-excursion ; fix next clock?
17370 (re-search-backward org-ts-regexp0 nil t)
17371 (looking-at (concat org-ts-regexp0 "\\] =>")))
17372 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17373 (save-window-excursion
17374 ;; Find closest clock to point, adjust the previous/next one in history
17375 (let* ((p (save-excursion (org-back-to-heading t)))
17376 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17377 (clfixnth
17378 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17379 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17380 (if (not clfixpos)
17381 (message "No clock to adjust")
17382 (save-excursion
17383 (org-goto-marker-or-bmk clfixpos)
17384 (org-show-subtree)
17385 (when (re-search-forward clrgx nil t)
17386 (goto-char (match-beginning 1))
17387 (let (org-clock-adjust-closest)
17388 (org-timestamp-change n org-ts-what updown))
17389 (message "Clock adjusted in %s for heading: %s"
17390 (file-name-nondirectory (buffer-file-name))
17391 (org-get-heading t t)))))))))
17392 ;; Try to recenter the calendar window, if any.
17393 (if (and org-calendar-follow-timestamp-change
17394 (get-buffer-window "*Calendar*" t)
17395 (memq org-ts-what '(day month year)))
17396 (org-recenter-calendar (time-to-days time))))))
17398 (defun org-modify-ts-extra (s pos n dm)
17399 "Change the different parts of the lead-time and repeat fields in timestamp."
17400 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17401 ng h m new rem)
17402 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17403 (cond
17404 ((or (org-pos-in-match-range pos 2)
17405 (org-pos-in-match-range pos 3))
17406 (setq m (string-to-number (match-string 3 s))
17407 h (string-to-number (match-string 2 s)))
17408 (if (org-pos-in-match-range pos 2)
17409 (setq h (+ h n))
17410 (setq n (* dm (org-no-warnings (signum n))))
17411 (when (not (= 0 (setq rem (% m dm))))
17412 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17413 (setq m (+ m n)))
17414 (if (< m 0) (setq m (+ m 60) h (1- h)))
17415 (if (> m 59) (setq m (- m 60) h (1+ h)))
17416 (setq h (min 24 (max 0 h)))
17417 (setq ng 1 new (format "-%02d:%02d" h m)))
17418 ((org-pos-in-match-range pos 6)
17419 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17420 ((org-pos-in-match-range pos 5)
17421 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17423 ((org-pos-in-match-range pos 9)
17424 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17425 ((org-pos-in-match-range pos 8)
17426 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17428 (when ng
17429 (setq s (concat
17430 (substring s 0 (match-beginning ng))
17432 (substring s (match-end ng))))))
17435 (defun org-recenter-calendar (date)
17436 "If the calendar is visible, recenter it to DATE."
17437 (let ((cwin (get-buffer-window "*Calendar*" t)))
17438 (when cwin
17439 (let ((calendar-move-hook nil))
17440 (with-selected-window cwin
17441 (calendar-goto-date (if (listp date) date
17442 (calendar-gregorian-from-absolute date))))))))
17444 (defun org-goto-calendar (&optional arg)
17445 "Go to the Emacs calendar at the current date.
17446 If there is a time stamp in the current line, go to that date.
17447 A prefix ARG can be used to force the current date."
17448 (interactive "P")
17449 (let ((tsr org-ts-regexp) diff
17450 (calendar-move-hook nil)
17451 (calendar-view-holidays-initially-flag nil)
17452 (calendar-view-diary-initially-flag nil))
17453 (if (or (org-at-timestamp-p)
17454 (save-excursion
17455 (beginning-of-line 1)
17456 (looking-at (concat ".*" tsr))))
17457 (let ((d1 (time-to-days (current-time)))
17458 (d2 (time-to-days
17459 (org-time-string-to-time (match-string 1)))))
17460 (setq diff (- d2 d1))))
17461 (calendar)
17462 (calendar-goto-today)
17463 (if (and diff (not arg)) (calendar-forward-day diff))))
17465 (defun org-get-date-from-calendar ()
17466 "Return a list (month day year) of date at point in calendar."
17467 (with-current-buffer "*Calendar*"
17468 (save-match-data
17469 (calendar-cursor-to-date))))
17471 (defun org-date-from-calendar ()
17472 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17473 If there is already a time stamp at the cursor position, update it."
17474 (interactive)
17475 (if (org-at-timestamp-p t)
17476 (org-timestamp-change 0 'calendar)
17477 (let ((cal-date (org-get-date-from-calendar)))
17478 (org-insert-time-stamp
17479 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17481 (defcustom org-effort-durations
17482 `(("h" . 60)
17483 ("d" . ,(* 60 8))
17484 ("w" . ,(* 60 8 5))
17485 ("m" . ,(* 60 8 5 4))
17486 ("y" . ,(* 60 8 5 40)))
17487 "Conversion factor to minutes for an effort modifier.
17489 Each entry has the form (MODIFIER . MINUTES).
17491 In an effort string, a number followed by MODIFIER is multiplied
17492 by the specified number of MINUTES to obtain an effort in
17493 minutes.
17495 For example, if the value of this variable is ((\"hours\" . 60)), then an
17496 effort string \"2hours\" is equivalent to 120 minutes."
17497 :group 'org-agenda
17498 :version "24.1"
17499 :type '(alist :key-type (string :tag "Modifier")
17500 :value-type (number :tag "Minutes")))
17502 (defun org-minutes-to-clocksum-string (m)
17503 "Format number of minutes as a clocksum string.
17504 The format is determined by `org-time-clocksum-format',
17505 `org-time-clocksum-use-fractional' and
17506 `org-time-clocksum-fractional-format' and
17507 `org-time-clocksum-use-effort-durations'."
17508 (let ((clocksum "")
17509 (m (round m)) ; Don't allow fractions of minutes
17510 h d w mo y fmt n)
17511 (setq h (if org-time-clocksum-use-effort-durations
17512 (cdr (assoc "h" org-effort-durations)) 60)
17513 d (if org-time-clocksum-use-effort-durations
17514 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17515 w (if org-time-clocksum-use-effort-durations
17516 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17517 mo (if org-time-clocksum-use-effort-durations
17518 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17519 y (if org-time-clocksum-use-effort-durations
17520 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17521 ;; fractional format
17522 (if org-time-clocksum-use-fractional
17523 (cond
17524 ;; single format string
17525 ((stringp org-time-clocksum-fractional-format)
17526 (format org-time-clocksum-fractional-format (/ m (float h))))
17527 ;; choice of fractional formats for different time units
17528 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17529 (> (/ (truncate m) (* y d h)) 0))
17530 (format fmt (/ m (* y d (float h)))))
17531 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17532 (> (/ (truncate m) (* mo d h)) 0))
17533 (format fmt (/ m (* mo d (float h)))))
17534 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17535 (> (/ (truncate m) (* w d h)) 0))
17536 (format fmt (/ m (* w d (float h)))))
17537 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17538 (> (/ (truncate m) (* d h)) 0))
17539 (format fmt (/ m (* d (float h)))))
17540 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17541 (> (/ (truncate m) h) 0))
17542 (format fmt (/ m (float h))))
17543 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17544 (format fmt m))
17545 ;; fall back to smallest time unit with a format
17546 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17547 (format fmt (/ m (float h))))
17548 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17549 (format fmt (/ m (* d (float h)))))
17550 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17551 (format fmt (/ m (* w d (float h)))))
17552 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17553 (format fmt (/ m (* mo d (float h)))))
17554 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17555 (format fmt (/ m (* y d (float h))))))
17556 ;; standard (non-fractional) format, with single format string
17557 (if (stringp org-time-clocksum-format)
17558 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17559 ;; separate formats components
17560 (and (setq fmt (plist-get org-time-clocksum-format :years))
17561 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17562 (plist-get org-time-clocksum-format :require-years))
17563 (setq clocksum (concat clocksum (format fmt n))
17564 m (- m (* n y d h))))
17565 (and (setq fmt (plist-get org-time-clocksum-format :months))
17566 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17567 (plist-get org-time-clocksum-format :require-months))
17568 (setq clocksum (concat clocksum (format fmt n))
17569 m (- m (* n mo d h))))
17570 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17571 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17572 (plist-get org-time-clocksum-format :require-weeks))
17573 (setq clocksum (concat clocksum (format fmt n))
17574 m (- m (* n w d h))))
17575 (and (setq fmt (plist-get org-time-clocksum-format :days))
17576 (or (> (setq n (/ (truncate m) (* d h))) 0)
17577 (plist-get org-time-clocksum-format :require-days))
17578 (setq clocksum (concat clocksum (format fmt n))
17579 m (- m (* n d h))))
17580 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17581 (or (> (setq n (/ (truncate m) h)) 0)
17582 (plist-get org-time-clocksum-format :require-hours))
17583 (setq clocksum (concat clocksum (format fmt n))
17584 m (- m (* n h))))
17585 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17586 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17587 (setq clocksum (concat clocksum (format fmt m))))
17588 ;; return formatted time duration
17589 clocksum))))
17591 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17592 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17593 "Org mode version 8.0")
17595 (defun org-hours-to-clocksum-string (n)
17596 (org-minutes-to-clocksum-string (* n 60)))
17598 (defun org-hh:mm-string-to-minutes (s)
17599 "Convert a string H:MM to a number of minutes.
17600 If the string is just a number, interpret it as minutes.
17601 In fact, the first hh:mm or number in the string will be taken,
17602 there can be extra stuff in the string.
17603 If no number is found, the return value is 0."
17604 (cond
17605 ((integerp s) s)
17606 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17607 (+ (* (string-to-number (match-string 1 s)) 60)
17608 (string-to-number (match-string 2 s))))
17609 ((string-match "\\([0-9]+\\)" s)
17610 (string-to-number (match-string 1 s)))
17611 (t 0)))
17613 (defcustom org-image-actual-width t
17614 "Should we use the actual width of images when inlining them?
17616 When set to `t', always use the image width.
17618 When set to a number, use imagemagick (when available) to set
17619 the image's width to this value.
17621 When set to a number in a list, try to get the width from any
17622 #+ATTR.* keyword if it matches a width specification like
17624 #+ATTR_HTML: :width 300px
17626 and fall back on that number if none is found.
17628 When set to nil, try to get the width from an #+ATTR.* keyword
17629 and fall back on the original width if none is found.
17631 This requires Emacs >= 24.1, build with imagemagick support."
17632 :group 'org-appearance
17633 :version "24.4"
17634 :package-version '(Org . "8.0")
17635 :type '(choice
17636 (const :tag "Use the image width" t)
17637 (integer :tag "Use a number of pixels")
17638 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17639 (const :tag "Use #+ATTR* or don't resize" nil)))
17641 (defcustom org-agenda-inhibit-startup nil
17642 "Inhibit startup when preparing agenda buffers.
17643 When this variable is `t' (the default), the initialization of
17644 the Org agenda buffers is inhibited: e.g. the visibility state
17645 is not set, the tables are not re-aligned, etc."
17646 :type 'boolean
17647 :version "24.3"
17648 :group 'org-agenda)
17650 (defun org-duration-string-to-minutes (s &optional output-to-string)
17651 "Convert a duration string S to minutes.
17653 A bare number is interpreted as minutes, modifiers can be set by
17654 customizing `org-effort-durations' (which see).
17656 Entries containing a colon are interpreted as H:MM by
17657 `org-hh:mm-string-to-minutes'."
17658 (let ((result 0)
17659 (re (concat "\\([0-9.]+\\) *\\("
17660 (regexp-opt (mapcar 'car org-effort-durations))
17661 "\\)")))
17662 (while (string-match re s)
17663 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17664 (string-to-number (match-string 1 s))))
17665 (setq s (replace-match "" nil t s)))
17666 (setq result (floor result))
17667 (incf result (org-hh:mm-string-to-minutes s))
17668 (if output-to-string (number-to-string result) result)))
17670 ;;;; Files
17672 (defun org-save-all-org-buffers ()
17673 "Save all Org-mode buffers without user confirmation."
17674 (interactive)
17675 (message "Saving all Org-mode buffers...")
17676 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17677 (when (featurep 'org-id) (org-id-locations-save))
17678 (message "Saving all Org-mode buffers... done"))
17680 (defun org-revert-all-org-buffers ()
17681 "Revert all Org-mode buffers.
17682 Prompt for confirmation when there are unsaved changes.
17683 Be sure you know what you are doing before letting this function
17684 overwrite your changes.
17686 This function is useful in a setup where one tracks org files
17687 with a version control system, to revert on one machine after pulling
17688 changes from another. I believe the procedure must be like this:
17690 1. M-x org-save-all-org-buffers
17691 2. Pull changes from the other machine, resolve conflicts
17692 3. M-x org-revert-all-org-buffers"
17693 (interactive)
17694 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17695 (user-error "Abort"))
17696 (save-excursion
17697 (save-window-excursion
17698 (mapc
17699 (lambda (b)
17700 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17701 (with-current-buffer b buffer-file-name))
17702 (org-pop-to-buffer-same-window b)
17703 (revert-buffer t 'no-confirm)))
17704 (buffer-list))
17705 (when (and (featurep 'org-id) org-id-track-globally)
17706 (org-id-locations-load)))))
17708 ;;;; Agenda files
17710 ;;;###autoload
17711 (defun org-switchb (&optional arg)
17712 "Switch between Org buffers.
17713 With one prefix argument, restrict available buffers to files.
17714 With two prefix arguments, restrict available buffers to agenda files.
17716 Defaults to `iswitchb' for buffer name completion.
17717 Set `org-completion-use-ido' to make it use ido instead."
17718 (interactive "P")
17719 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17720 ((equal arg '(16)) (org-buffer-list 'agenda))
17721 (t (org-buffer-list))))
17722 (org-completion-use-iswitchb org-completion-use-iswitchb)
17723 (org-completion-use-ido org-completion-use-ido))
17724 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17725 (setq org-completion-use-iswitchb t))
17726 (org-pop-to-buffer-same-window
17727 (org-icompleting-read "Org buffer: "
17728 (mapcar 'list (mapcar 'buffer-name blist))
17729 nil t))))
17731 ;;; Define some older names previously used for this functionality
17732 ;;;###autoload
17733 (defalias 'org-ido-switchb 'org-switchb)
17734 ;;;###autoload
17735 (defalias 'org-iswitchb 'org-switchb)
17737 (defun org-buffer-list (&optional predicate exclude-tmp)
17738 "Return a list of Org buffers.
17739 PREDICATE can be `export', `files' or `agenda'.
17741 export restrict the list to Export buffers.
17742 files restrict the list to buffers visiting Org files.
17743 agenda restrict the list to buffers visiting agenda files.
17745 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17746 (let* ((bfn nil)
17747 (agenda-files (and (eq predicate 'agenda)
17748 (mapcar 'file-truename (org-agenda-files t))))
17749 (filter
17750 (cond
17751 ((eq predicate 'files)
17752 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17753 ((eq predicate 'export)
17754 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17755 ((eq predicate 'agenda)
17756 (lambda (b)
17757 (with-current-buffer b
17758 (and (derived-mode-p 'org-mode)
17759 (setq bfn (buffer-file-name b))
17760 (member (file-truename bfn) agenda-files)))))
17761 (t (lambda (b) (with-current-buffer b
17762 (or (derived-mode-p 'org-mode)
17763 (string-match "\*Org .*Export"
17764 (buffer-name b)))))))))
17765 (delq nil
17766 (mapcar
17767 (lambda(b)
17768 (if (and (funcall filter b)
17769 (or (not exclude-tmp)
17770 (not (string-match "tmp" (buffer-name b)))))
17772 nil))
17773 (buffer-list)))))
17775 (defun org-agenda-files (&optional unrestricted archives)
17776 "Get the list of agenda files.
17777 Optional UNRESTRICTED means return the full list even if a restriction
17778 is currently in place.
17779 When ARCHIVES is t, include all archive files that are really being
17780 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17781 `org-agenda-archives-mode' is t."
17782 (let ((files
17783 (cond
17784 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17785 ((stringp org-agenda-files) (org-read-agenda-file-list))
17786 ((listp org-agenda-files) org-agenda-files)
17787 (t (error "Invalid value of `org-agenda-files'")))))
17788 (setq files (apply 'append
17789 (mapcar (lambda (f)
17790 (if (file-directory-p f)
17791 (directory-files
17792 f t org-agenda-file-regexp)
17793 (list f)))
17794 files)))
17795 (when org-agenda-skip-unavailable-files
17796 (setq files (delq nil
17797 (mapcar (function
17798 (lambda (file)
17799 (and (file-readable-p file) file)))
17800 files))))
17801 (when (or (eq archives t)
17802 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17803 (setq files (org-add-archive-files files)))
17804 files))
17806 (defun org-agenda-file-p (&optional file)
17807 "Return non-nil, if FILE is an agenda file.
17808 If FILE is omitted, use the file associated with the current
17809 buffer."
17810 (member (or file (buffer-file-name))
17811 (org-agenda-files t)))
17813 (defun org-edit-agenda-file-list ()
17814 "Edit the list of agenda files.
17815 Depending on setup, this either uses customize to edit the variable
17816 `org-agenda-files', or it visits the file that is holding the list. In the
17817 latter case, the buffer is set up in a way that saving it automatically kills
17818 the buffer and restores the previous window configuration."
17819 (interactive)
17820 (if (stringp org-agenda-files)
17821 (let ((cw (current-window-configuration)))
17822 (find-file org-agenda-files)
17823 (org-set-local 'org-window-configuration cw)
17824 (org-add-hook 'after-save-hook
17825 (lambda ()
17826 (set-window-configuration
17827 (prog1 org-window-configuration
17828 (kill-buffer (current-buffer))))
17829 (org-install-agenda-files-menu)
17830 (message "New agenda file list installed"))
17831 nil 'local)
17832 (message "%s" (substitute-command-keys
17833 "Edit list and finish with \\[save-buffer]")))
17834 (customize-variable 'org-agenda-files)))
17836 (defun org-store-new-agenda-file-list (list)
17837 "Set new value for the agenda file list and save it correctly."
17838 (if (stringp org-agenda-files)
17839 (let ((fe (org-read-agenda-file-list t)) b u)
17840 (while (setq b (find-buffer-visiting org-agenda-files))
17841 (kill-buffer b))
17842 (with-temp-file org-agenda-files
17843 (insert
17844 (mapconcat
17845 (lambda (f) ;; Keep un-expanded entries.
17846 (if (setq u (assoc f fe))
17847 (cdr u)
17849 list "\n")
17850 "\n")))
17851 (let ((org-mode-hook nil) (org-inhibit-startup t)
17852 (org-insert-mode-line-in-empty-file nil))
17853 (setq org-agenda-files list)
17854 (customize-save-variable 'org-agenda-files org-agenda-files))))
17856 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17857 "Read the list of agenda files from a file.
17858 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17859 filenames, used by `org-store-new-agenda-file-list' to write back
17860 un-expanded file names."
17861 (when (file-directory-p org-agenda-files)
17862 (error "`org-agenda-files' cannot be a single directory"))
17863 (when (stringp org-agenda-files)
17864 (with-temp-buffer
17865 (insert-file-contents org-agenda-files)
17866 (mapcar
17867 (lambda (f)
17868 (let ((e (expand-file-name (substitute-in-file-name f)
17869 org-directory)))
17870 (if pair-with-expansion
17871 (cons e f)
17872 e)))
17873 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17875 ;;;###autoload
17876 (defun org-cycle-agenda-files ()
17877 "Cycle through the files in `org-agenda-files'.
17878 If the current buffer visits an agenda file, find the next one in the list.
17879 If the current buffer does not, find the first agenda file."
17880 (interactive)
17881 (let* ((fs (org-agenda-files t))
17882 (files (append fs (list (car fs))))
17883 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17884 file)
17885 (unless files (user-error "No agenda files"))
17886 (catch 'exit
17887 (while (setq file (pop files))
17888 (if (equal (file-truename file) tcf)
17889 (when (car files)
17890 (find-file (car files))
17891 (throw 'exit t))))
17892 (find-file (car fs)))
17893 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17895 (defun org-agenda-file-to-front (&optional to-end)
17896 "Move/add the current file to the top of the agenda file list.
17897 If the file is not present in the list, it is added to the front. If it is
17898 present, it is moved there. With optional argument TO-END, add/move to the
17899 end of the list."
17900 (interactive "P")
17901 (let ((org-agenda-skip-unavailable-files nil)
17902 (file-alist (mapcar (lambda (x)
17903 (cons (file-truename x) x))
17904 (org-agenda-files t)))
17905 (ctf (file-truename
17906 (or buffer-file-name
17907 (user-error "Please save the current buffer to a file"))))
17908 x had)
17909 (setq x (assoc ctf file-alist) had x)
17911 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17912 (if to-end
17913 (setq file-alist (append (delq x file-alist) (list x)))
17914 (setq file-alist (cons x (delq x file-alist))))
17915 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17916 (org-install-agenda-files-menu)
17917 (message "File %s to %s of agenda file list"
17918 (if had "moved" "added") (if to-end "end" "front"))))
17920 (defun org-remove-file (&optional file)
17921 "Remove current file from the list of files in variable `org-agenda-files'.
17922 These are the files which are being checked for agenda entries.
17923 Optional argument FILE means use this file instead of the current."
17924 (interactive)
17925 (let* ((org-agenda-skip-unavailable-files nil)
17926 (file (or file buffer-file-name
17927 (user-error "Current buffer does not visit a file")))
17928 (true-file (file-truename file))
17929 (afile (abbreviate-file-name file))
17930 (files (delq nil (mapcar
17931 (lambda (x)
17932 (if (equal true-file
17933 (file-truename x))
17934 nil x))
17935 (org-agenda-files t)))))
17936 (if (not (= (length files) (length (org-agenda-files t))))
17937 (progn
17938 (org-store-new-agenda-file-list files)
17939 (org-install-agenda-files-menu)
17940 (message "Removed file: %s" afile))
17941 (message "File was not in list: %s (not removed)" afile))))
17943 (defun org-file-menu-entry (file)
17944 (vector file (list 'find-file file) t))
17946 (defun org-check-agenda-file (file)
17947 "Make sure FILE exists. If not, ask user what to do."
17948 (when (not (file-exists-p file))
17949 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17950 (abbreviate-file-name file))
17951 (let ((r (downcase (read-char-exclusive))))
17952 (cond
17953 ((equal r ?r)
17954 (org-remove-file file)
17955 (throw 'nextfile t))
17956 (t (error "Abort"))))))
17958 (defun org-get-agenda-file-buffer (file)
17959 "Get a buffer visiting FILE. If the buffer needs to be created, add
17960 it to the list of buffers which might be released later."
17961 (let ((buf (org-find-base-buffer-visiting file)))
17962 (if buf
17963 buf ; just return it
17964 ;; Make a new buffer and remember it
17965 (setq buf (find-file-noselect file))
17966 (if buf (push buf org-agenda-new-buffers))
17967 buf)))
17969 (defun org-release-buffers (blist)
17970 "Release all buffers in list, asking the user for confirmation when needed.
17971 When a buffer is unmodified, it is just killed. When modified, it is saved
17972 \(if the user agrees) and then killed."
17973 (let (buf file)
17974 (while (setq buf (pop blist))
17975 (setq file (buffer-file-name buf))
17976 (when (and (buffer-modified-p buf)
17977 file
17978 (y-or-n-p (format "Save file %s? " file)))
17979 (with-current-buffer buf (save-buffer)))
17980 (kill-buffer buf))))
17982 (defun org-agenda-prepare-buffers (files)
17983 "Create buffers for all agenda files, protect archived trees and comments."
17984 (interactive)
17985 (let ((pa '(:org-archived t))
17986 (pc '(:org-comment t))
17987 (pall '(:org-archived t :org-comment t))
17988 (inhibit-read-only t)
17989 (org-inhibit-startup org-agenda-inhibit-startup)
17990 (rea (concat ":" org-archive-tag ":"))
17991 file re)
17992 (setq org-tag-alist-for-agenda nil
17993 org-tag-groups-alist-for-agenda nil)
17994 (save-excursion
17995 (save-restriction
17996 (while (setq file (pop files))
17997 (catch 'nextfile
17998 (if (bufferp file)
17999 (set-buffer file)
18000 (org-check-agenda-file file)
18001 (set-buffer (org-get-agenda-file-buffer file)))
18002 (widen)
18003 (org-set-regexps-and-options-for-tags)
18004 (goto-char (point-min))
18005 (let ((case-fold-search t))
18006 (when (search-forward "#+setupfile" nil t)
18007 ;; Don't set all regexps and options systematically as
18008 ;; this is only run for setting agenda tags from setup
18009 ;; file
18010 (org-set-regexps-and-options)))
18011 (org-refresh-category-properties)
18012 (org-refresh-properties org-effort-property 'org-effort)
18013 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18014 (setq org-todo-keywords-for-agenda
18015 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18016 (setq org-done-keywords-for-agenda
18017 (append org-done-keywords-for-agenda org-done-keywords))
18018 (setq org-todo-keyword-alist-for-agenda
18019 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18020 (setq org-drawers-for-agenda
18021 (append org-drawers-for-agenda org-drawers))
18022 (setq org-tag-alist-for-agenda
18023 (org-uniquify
18024 (append org-tag-alist-for-agenda
18025 org-tag-alist
18026 org-tag-persistent-alist)))
18027 (if org-group-tags
18028 (setq org-tag-groups-alist-for-agenda
18029 (org-uniquify-alist
18030 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18031 (org-with-silent-modifications
18032 (save-excursion
18033 (remove-text-properties (point-min) (point-max) pall)
18034 (when org-agenda-skip-archived-trees
18035 (goto-char (point-min))
18036 (while (re-search-forward rea nil t)
18037 (if (org-at-heading-p t)
18038 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18039 (goto-char (point-min))
18040 (setq re (format org-heading-keyword-regexp-format
18041 org-comment-string))
18042 (while (re-search-forward re nil t)
18043 (add-text-properties
18044 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18045 (setq org-todo-keywords-for-agenda
18046 (org-uniquify org-todo-keywords-for-agenda))
18047 (setq org-todo-keyword-alist-for-agenda
18048 (org-uniquify org-todo-keyword-alist-for-agenda))))
18051 ;;;; CDLaTeX minor mode
18053 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18054 "Keymap for the minor `org-cdlatex-mode'.")
18056 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18057 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18058 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18059 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18060 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18062 (defvar org-cdlatex-texmathp-advice-is-done nil
18063 "Flag remembering if we have applied the advice to texmathp already.")
18065 (define-minor-mode org-cdlatex-mode
18066 "Toggle the minor `org-cdlatex-mode'.
18067 This mode supports entering LaTeX environment and math in LaTeX fragments
18068 in Org-mode.
18069 \\{org-cdlatex-mode-map}"
18070 nil " OCDL" nil
18071 (when org-cdlatex-mode
18072 (require 'cdlatex)
18073 (run-hooks 'cdlatex-mode-hook)
18074 (cdlatex-compute-tables))
18075 (unless org-cdlatex-texmathp-advice-is-done
18076 (setq org-cdlatex-texmathp-advice-is-done t)
18077 (defadvice texmathp (around org-math-always-on activate)
18078 "Always return t in org-mode buffers.
18079 This is because we want to insert math symbols without dollars even outside
18080 the LaTeX math segments. If Orgmode thinks that point is actually inside
18081 an embedded LaTeX fragment, let texmathp do its job.
18082 \\[org-cdlatex-mode-map]"
18083 (interactive)
18084 (let (p)
18085 (cond
18086 ((not (derived-mode-p 'org-mode)) ad-do-it)
18087 ((eq this-command 'cdlatex-math-symbol)
18088 (setq ad-return-value t
18089 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18091 (let ((p (org-inside-LaTeX-fragment-p)))
18092 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18093 (setq ad-return-value t
18094 texmathp-why '("Org-mode embedded math" . 0))
18095 (if p ad-do-it)))))))))
18097 (defun turn-on-org-cdlatex ()
18098 "Unconditionally turn on `org-cdlatex-mode'."
18099 (org-cdlatex-mode 1))
18101 (defun org-try-cdlatex-tab ()
18102 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18103 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18104 - inside a LaTeX fragment, or
18105 - after the first word in a line, where an abbreviation expansion could
18106 insert a LaTeX environment."
18107 (when org-cdlatex-mode
18108 (cond
18109 ;; Before any word on the line: No expansion possible.
18110 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18111 ;; Just after first word on the line: Expand it. Make sure it
18112 ;; cannot happen on headlines, though.
18113 ((save-excursion
18114 (skip-chars-backward "a-zA-Z0-9*")
18115 (skip-chars-backward " \t")
18116 (and (bolp) (not (org-at-heading-p))))
18117 (cdlatex-tab) t)
18118 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18120 (defun org-cdlatex-underscore-caret (&optional arg)
18121 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18122 Revert to the normal definition outside of these fragments."
18123 (interactive "P")
18124 (if (org-inside-LaTeX-fragment-p)
18125 (call-interactively 'cdlatex-sub-superscript)
18126 (let (org-cdlatex-mode)
18127 (call-interactively (key-binding (vector last-input-event))))))
18129 (defun org-cdlatex-math-modify (&optional arg)
18130 "Execute `cdlatex-math-modify' in LaTeX fragments.
18131 Revert to the normal definition outside of these fragments."
18132 (interactive "P")
18133 (if (org-inside-LaTeX-fragment-p)
18134 (call-interactively 'cdlatex-math-modify)
18135 (let (org-cdlatex-mode)
18136 (call-interactively (key-binding (vector last-input-event))))))
18140 ;;;; LaTeX fragments
18142 (defvar org-latex-regexps
18143 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18144 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18145 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18146 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18147 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18148 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18149 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18150 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18151 "Regular expressions for matching embedded LaTeX.")
18153 (defun org-inside-LaTeX-fragment-p ()
18154 "Test if point is inside a LaTeX fragment.
18155 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18156 sequence appearing also before point.
18157 Even though the matchers for math are configurable, this function assumes
18158 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18159 delimiters are skipped when they have been removed by customization.
18160 The return value is nil, or a cons cell with the delimiter and the
18161 position of this delimiter.
18163 This function does a reasonably good job, but can locally be fooled by
18164 for example currency specifications. For example it will assume being in
18165 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18166 fragments that are properly closed, but during editing, we have to live
18167 with the uncertainty caused by missing closing delimiters. This function
18168 looks only before point, not after."
18169 (catch 'exit
18170 (let ((pos (point))
18171 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18172 (lim (progn
18173 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18174 (point)))
18175 dd-on str (start 0) m re)
18176 (goto-char pos)
18177 (when dodollar
18178 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18179 re (nth 1 (assoc "$" org-latex-regexps)))
18180 (while (string-match re str start)
18181 (cond
18182 ((= (match-end 0) (length str))
18183 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18184 ((= (match-end 0) (- (length str) 5))
18185 (throw 'exit nil))
18186 (t (setq start (match-end 0))))))
18187 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18188 (goto-char pos)
18189 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18190 (and (match-beginning 2) (throw 'exit nil))
18191 ;; count $$
18192 (while (re-search-backward "\\$\\$" lim t)
18193 (setq dd-on (not dd-on)))
18194 (goto-char pos)
18195 (if dd-on (cons "$$" m))))))
18197 (defun org-inside-latex-macro-p ()
18198 "Is point inside a LaTeX macro or its arguments?"
18199 (save-match-data
18200 (org-in-regexp
18201 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18203 (defvar org-latex-fragment-image-overlays nil
18204 "List of overlays carrying the images of latex fragments.")
18205 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18207 (defun org-remove-latex-fragment-image-overlays ()
18208 "Remove all overlays with LaTeX fragment images in current buffer."
18209 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18210 (setq org-latex-fragment-image-overlays nil))
18212 (defun org-preview-latex-fragment (&optional subtree)
18213 "Preview the LaTeX fragment at point, or all locally or globally.
18214 If the cursor is in a LaTeX fragment, create the image and overlay
18215 it over the source code. If there is no fragment at point, display
18216 all fragments in the current text, from one headline to the next. With
18217 prefix SUBTREE, display all fragments in the current subtree. With a
18218 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18219 the cursor is before the first headline,
18220 display all fragments in the buffer.
18221 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18222 (interactive "P")
18223 (unless buffer-file-name
18224 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18225 (org-remove-latex-fragment-image-overlays)
18226 (save-excursion
18227 (save-restriction
18228 (let (beg end at msg)
18229 (cond
18230 ((or (equal subtree '(16))
18231 (not (save-excursion
18232 (re-search-backward org-outline-regexp-bol nil t))))
18233 (setq beg (point-min) end (point-max)
18234 msg "Creating images for buffer...%s"))
18235 ((equal subtree '(4))
18236 (org-back-to-heading)
18237 (setq beg (point) end (org-end-of-subtree t)
18238 msg "Creating images for subtree...%s"))
18240 (if (setq at (org-inside-LaTeX-fragment-p))
18241 (goto-char (max (point-min) (- (cdr at) 2)))
18242 (org-back-to-heading))
18243 (setq beg (point) end (progn (outline-next-heading) (point))
18244 msg (if at "Creating image...%s"
18245 "Creating images for entry...%s"))))
18246 (message msg "")
18247 (narrow-to-region beg end)
18248 (goto-char beg)
18249 (org-format-latex
18250 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18251 (file-name-nondirectory
18252 buffer-file-name)))
18253 default-directory 'overlays msg at 'forbuffer
18254 org-latex-create-formula-image-program)
18255 (message msg "done. Use `C-c C-c' to remove images.")))))
18257 (defun org-format-latex (prefix &optional dir overlays msg at
18258 forbuffer processing-type)
18259 "Replace LaTeX fragments with links to an image, and produce images.
18260 Some of the options can be changed using the variable
18261 `org-format-latex-options'."
18262 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18263 (let* ((prefixnodir (file-name-nondirectory prefix))
18264 (absprefix (expand-file-name prefix dir))
18265 (todir (file-name-directory absprefix))
18266 (opt org-format-latex-options)
18267 (optnew org-format-latex-options)
18268 (matchers (plist-get opt :matchers))
18269 (re-list org-latex-regexps)
18270 (cnt 0) txt hash link beg end re e checkdir
18271 string
18272 m n block-type block linkfile movefile ov)
18273 ;; Check the different regular expressions
18274 (while (setq e (pop re-list))
18275 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18276 block (if block-type "\n\n" ""))
18277 (when (member m matchers)
18278 (goto-char (point-min))
18279 (while (re-search-forward re nil t)
18280 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18281 (or (not overlays)
18282 (not (eq (get-char-property (match-beginning n)
18283 'org-overlay-type)
18284 'org-latex-overlay))))
18285 (cond
18286 ((eq processing-type 'verbatim))
18287 ((eq processing-type 'mathjax)
18288 ;; Prepare for MathJax processing.
18289 (setq string (match-string n))
18290 (when (member m '("$" "$1"))
18291 (save-excursion
18292 (delete-region (match-beginning n) (match-end n))
18293 (goto-char (match-beginning n))
18294 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18295 ((or (eq processing-type 'dvipng)
18296 (eq processing-type 'imagemagick))
18297 ;; Process to an image.
18298 (setq txt (match-string n)
18299 beg (match-beginning n) end (match-end n)
18300 cnt (1+ cnt))
18301 (let ((face (face-at-point))
18302 (fg (plist-get opt :foreground))
18303 (bg (plist-get opt :background))
18304 ;; Ensure full list is printed.
18305 print-length print-level)
18306 (when forbuffer
18307 ;; Get the colors from the face at point.
18308 (goto-char beg)
18309 (when (eq fg 'auto)
18310 (setq fg (face-attribute face :foreground nil 'default)))
18311 (when (eq bg 'auto)
18312 (setq bg (face-attribute face :background nil 'default)))
18313 (setq optnew (copy-sequence opt))
18314 (plist-put optnew :foreground fg)
18315 (plist-put optnew :background bg))
18316 (setq hash (sha1 (prin1-to-string
18317 (list org-format-latex-header
18318 org-latex-default-packages-alist
18319 org-latex-packages-alist
18320 org-format-latex-options
18321 forbuffer txt fg bg)))
18322 linkfile (format "%s_%s.png" prefix hash)
18323 movefile (format "%s_%s.png" absprefix hash)))
18324 (setq link (concat block "[[file:" linkfile "]]" block))
18325 (if msg (message msg cnt))
18326 (goto-char beg)
18327 (unless checkdir ; Ensure the directory exists.
18328 (setq checkdir t)
18329 (or (file-directory-p todir) (make-directory todir t)))
18330 (unless (file-exists-p movefile)
18331 (org-create-formula-image
18332 txt movefile optnew forbuffer processing-type))
18333 (if overlays
18334 (progn
18335 (mapc (lambda (o)
18336 (if (eq (overlay-get o 'org-overlay-type)
18337 'org-latex-overlay)
18338 (delete-overlay o)))
18339 (overlays-in beg end))
18340 (setq ov (make-overlay beg end))
18341 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18342 (if (featurep 'xemacs)
18343 (progn
18344 (overlay-put ov 'invisible t)
18345 (overlay-put
18346 ov 'end-glyph
18347 (make-glyph (vector 'png :file movefile))))
18348 (overlay-put
18349 ov 'display
18350 (list 'image :type 'png :file movefile :ascent 'center)))
18351 (push ov org-latex-fragment-image-overlays)
18352 (goto-char end))
18353 (delete-region beg end)
18354 (insert (org-add-props link
18355 (list 'org-latex-src
18356 (replace-regexp-in-string
18357 "\"" "" txt)
18358 'org-latex-src-embed-type
18359 (if block-type 'paragraph 'character))))))
18360 ((eq processing-type 'mathml)
18361 ;; Process to MathML
18362 (unless (save-match-data (org-format-latex-mathml-available-p))
18363 (user-error "LaTeX to MathML converter not configured"))
18364 (setq txt (match-string n)
18365 beg (match-beginning n) end (match-end n)
18366 cnt (1+ cnt))
18367 (if msg (message msg cnt))
18368 (goto-char beg)
18369 (delete-region beg end)
18370 (insert (org-format-latex-as-mathml
18371 txt block-type prefix dir)))
18373 (error "Unknown conversion type %s for LaTeX fragments"
18374 processing-type)))))))))
18376 (defun org-create-math-formula (latex-frag &optional mathml-file)
18377 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18378 Use `org-latex-to-mathml-convert-command'. If the conversion is
18379 sucessful, return the portion between \"<math...> </math>\"
18380 elements otherwise return nil. When MATHML-FILE is specified,
18381 write the results in to that file. When invoked as an
18382 interactive command, prompt for LATEX-FRAG, with initial value
18383 set to the current active region and echo the results for user
18384 inspection."
18385 (interactive (list (let ((frag (when (org-region-active-p)
18386 (buffer-substring-no-properties
18387 (region-beginning) (region-end)))))
18388 (read-string "LaTeX Fragment: " frag nil frag))))
18389 (unless latex-frag (error "Invalid LaTeX fragment"))
18390 (let* ((tmp-in-file (file-relative-name
18391 (make-temp-name (expand-file-name "ltxmathml-in"))))
18392 (ignore (write-region latex-frag nil tmp-in-file))
18393 (tmp-out-file (file-relative-name
18394 (make-temp-name (expand-file-name "ltxmathml-out"))))
18395 (cmd (format-spec
18396 org-latex-to-mathml-convert-command
18397 `((?j . ,(shell-quote-argument
18398 (expand-file-name org-latex-to-mathml-jar-file)))
18399 (?I . ,(shell-quote-argument tmp-in-file))
18400 (?o . ,(shell-quote-argument tmp-out-file)))))
18401 mathml shell-command-output)
18402 (when (org-called-interactively-p 'any)
18403 (unless (org-format-latex-mathml-available-p)
18404 (user-error "LaTeX to MathML converter not configured")))
18405 (message "Running %s" cmd)
18406 (setq shell-command-output (shell-command-to-string cmd))
18407 (setq mathml
18408 (when (file-readable-p tmp-out-file)
18409 (with-current-buffer (find-file-noselect tmp-out-file t)
18410 (goto-char (point-min))
18411 (when (re-search-forward
18412 (concat
18413 (regexp-quote
18414 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18415 "\\(.\\|\n\\)*"
18416 (regexp-quote "</math>")) nil t)
18417 (prog1 (match-string 0) (kill-buffer))))))
18418 (cond
18419 (mathml
18420 (setq mathml
18421 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18422 (when mathml-file
18423 (write-region mathml nil mathml-file))
18424 (when (org-called-interactively-p 'any)
18425 (message mathml)))
18426 ((message "LaTeX to MathML conversion failed")
18427 (message shell-command-output)))
18428 (delete-file tmp-in-file)
18429 (when (file-exists-p tmp-out-file)
18430 (delete-file tmp-out-file))
18431 mathml))
18433 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18434 prefix &optional dir)
18435 "Use `org-create-math-formula' but check local cache first."
18436 (let* ((absprefix (expand-file-name prefix dir))
18437 (print-length nil) (print-level nil)
18438 (formula-id (concat
18439 "formula-"
18440 (sha1
18441 (prin1-to-string
18442 (list latex-frag
18443 org-latex-to-mathml-convert-command)))))
18444 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18445 (formula-cache-dir (file-name-directory formula-cache)))
18447 (unless (file-directory-p formula-cache-dir)
18448 (make-directory formula-cache-dir t))
18450 (unless (file-exists-p formula-cache)
18451 (org-create-math-formula latex-frag formula-cache))
18453 (if (file-exists-p formula-cache)
18454 ;; Successful conversion. Return the link to MathML file.
18455 (org-add-props
18456 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18457 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18458 'org-latex-src-embed-type (if latex-frag-type
18459 'paragraph 'character)))
18460 ;; Failed conversion. Return the LaTeX fragment verbatim
18461 latex-frag)))
18463 (defun org-create-formula-image (string tofile options buffer &optional type)
18464 "Create an image from LaTeX source using dvipng or convert.
18465 This function calls either `org-create-formula-image-with-dvipng'
18466 or `org-create-formula-image-with-imagemagick' depending on the
18467 value of `org-latex-create-formula-image-program' or on the value
18468 of the optional TYPE variable.
18470 Note: ultimately these two function should be combined as they
18471 share a good deal of logic."
18472 (org-check-external-command
18473 "latex" "needed to convert LaTeX fragments to images")
18474 (funcall
18475 (case (or type org-latex-create-formula-image-program)
18476 ('dvipng
18477 (org-check-external-command
18478 "dvipng" "needed to convert LaTeX fragments to images")
18479 #'org-create-formula-image-with-dvipng)
18480 ('imagemagick
18481 (org-check-external-command
18482 "convert" "you need to install imagemagick")
18483 #'org-create-formula-image-with-imagemagick)
18484 (t (error
18485 "Invalid value of `org-latex-create-formula-image-program'")))
18486 string tofile options buffer))
18488 (declare-function org-export--get-global-options "ox" (&optional backend))
18489 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18490 (defun org-create-formula--latex-header ()
18491 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18492 (org-latex-guess-inputenc
18493 (org-splice-latex-header
18494 org-format-latex-header
18495 org-latex-default-packages-alist
18496 org-latex-packages-alist t
18497 (plist-get
18498 (org-combine-plists
18499 (org-export--get-global-options 'latex)
18500 (org-export--get-inbuffer-options 'latex))
18501 :latex-header))))
18503 ;; This function borrows from Ganesh Swami's latex2png.el
18504 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18505 "This calls dvipng."
18506 (require 'ox-latex)
18507 (let* ((tmpdir (if (featurep 'xemacs)
18508 (temp-directory)
18509 temporary-file-directory))
18510 (texfilebase (make-temp-name
18511 (expand-file-name "orgtex" tmpdir)))
18512 (texfile (concat texfilebase ".tex"))
18513 (dvifile (concat texfilebase ".dvi"))
18514 (pngfile (concat texfilebase ".png"))
18515 (fnh (if (featurep 'xemacs)
18516 (font-height (face-font 'default))
18517 (face-attribute 'default :height nil)))
18518 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18519 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18520 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18521 "Black"))
18522 (bg (or (plist-get options (if buffer :background :html-background))
18523 "Transparent")))
18524 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18525 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18526 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18527 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18528 (let ((latex-header (org-create-formula--latex-header)))
18529 (with-temp-file texfile
18530 (insert latex-header)
18531 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18532 (let ((dir default-directory))
18533 (condition-case nil
18534 (progn
18535 (cd tmpdir)
18536 (call-process "latex" nil nil nil texfile))
18537 (error nil))
18538 (cd dir))
18539 (if (not (file-exists-p dvifile))
18540 (progn (message "Failed to create dvi file from %s" texfile) nil)
18541 (condition-case nil
18542 (if (featurep 'xemacs)
18543 (call-process "dvipng" nil nil nil
18544 "-fg" fg "-bg" bg
18545 "-T" "tight"
18546 "-o" pngfile
18547 dvifile)
18548 (call-process "dvipng" nil nil nil
18549 "-fg" fg "-bg" bg
18550 "-D" dpi
18551 ;;"-x" scale "-y" scale
18552 "-T" "tight"
18553 "-o" pngfile
18554 dvifile))
18555 (error nil))
18556 (if (not (file-exists-p pngfile))
18557 (if org-format-latex-signal-error
18558 (error "Failed to create png file from %s" texfile)
18559 (message "Failed to create png file from %s" texfile)
18560 nil)
18561 ;; Use the requested file name and clean up
18562 (copy-file pngfile tofile 'replace)
18563 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18564 (if (file-exists-p (concat texfilebase e))
18565 (delete-file (concat texfilebase e))))
18566 pngfile))))
18568 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18569 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18570 "This calls convert, which is included into imagemagick."
18571 (require 'ox-latex)
18572 (let* ((tmpdir (if (featurep 'xemacs)
18573 (temp-directory)
18574 temporary-file-directory))
18575 (texfilebase (make-temp-name
18576 (expand-file-name "orgtex" tmpdir)))
18577 (texfile (concat texfilebase ".tex"))
18578 (pdffile (concat texfilebase ".pdf"))
18579 (pngfile (concat texfilebase ".png"))
18580 (fnh (if (featurep 'xemacs)
18581 (font-height (face-font 'default))
18582 (face-attribute 'default :height nil)))
18583 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18584 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18585 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18586 "black"))
18587 (bg (or (plist-get options (if buffer :background :html-background))
18588 "white")))
18589 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18590 (setq fg (org-latex-color-format fg)))
18591 (if (eq bg 'default) (setq bg (org-latex-color :background))
18592 (setq bg (org-latex-color-format
18593 (if (string= bg "Transparent") "white" bg))))
18594 (let ((latex-header (org-create-formula--latex-header)))
18595 (with-temp-file texfile
18596 (insert latex-header)
18597 (insert "\n\\begin{document}\n"
18598 "\\definecolor{fg}{rgb}{" fg "}\n"
18599 "\\definecolor{bg}{rgb}{" bg "}\n"
18600 "\n\\pagecolor{bg}\n"
18601 "\n{\\color{fg}\n"
18602 string
18603 "\n}\n"
18604 "\n\\end{document}\n")))
18605 (org-latex-compile texfile t)
18606 (if (not (file-exists-p pdffile))
18607 (progn (message "Failed to create pdf file from %s" texfile) nil)
18608 (condition-case nil
18609 (if (featurep 'xemacs)
18610 (call-process "convert" nil nil nil
18611 "-density" "96"
18612 "-trim"
18613 "-antialias"
18614 pdffile
18615 "-quality" "100"
18616 ;; "-sharpen" "0x1.0"
18617 pngfile)
18618 (call-process "convert" nil nil nil
18619 "-density" dpi
18620 "-trim"
18621 "-antialias"
18622 pdffile
18623 "-quality" "100"
18624 ;; "-sharpen" "0x1.0"
18625 pngfile))
18626 (error nil))
18627 (if (not (file-exists-p pngfile))
18628 (if org-format-latex-signal-error
18629 (error "Failed to create png file from %s" texfile)
18630 (message "Failed to create png file from %s" texfile)
18631 nil)
18632 ;; Use the requested file name and clean up
18633 (copy-file pngfile tofile 'replace)
18634 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18635 (if (file-exists-p (concat texfilebase e))
18636 (delete-file (concat texfilebase e))))
18637 pngfile))))
18639 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18640 "Fill a LaTeX header template TPL.
18641 In the template, the following place holders will be recognized:
18643 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18644 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18645 [PACKAGES] \\usepackage statements for PKG
18646 [NO-PACKAGES] do not include PKG
18647 [EXTRA] the string EXTRA
18648 [NO-EXTRA] do not include EXTRA
18650 For backward compatibility, if both the positive and the negative place
18651 holder is missing, the positive one (without the \"NO-\") will be
18652 assumed to be present at the end of the template.
18653 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18654 EXTRA is a string.
18655 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18656 (let (rpl (end ""))
18657 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18658 (setq rpl (if (or (match-end 1) (not def-pkg))
18659 "" (org-latex-packages-to-string def-pkg snippets-p t))
18660 tpl (replace-match rpl t t tpl))
18661 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18663 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18664 (setq rpl (if (or (match-end 1) (not pkg))
18665 "" (org-latex-packages-to-string pkg snippets-p t))
18666 tpl (replace-match rpl t t tpl))
18667 (if pkg (setq end
18668 (concat end "\n"
18669 (org-latex-packages-to-string pkg snippets-p)))))
18671 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18672 (setq rpl (if (or (match-end 1) (not extra))
18673 "" (concat extra "\n"))
18674 tpl (replace-match rpl t t tpl))
18675 (if (and extra (string-match "\\S-" extra))
18676 (setq end (concat end "\n" extra))))
18678 (if (string-match "\\S-" end)
18679 (concat tpl "\n" end)
18680 tpl)))
18682 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18683 "Turn an alist of packages into a string with the \\usepackage macros."
18684 (setq pkg (mapconcat (lambda(p)
18685 (cond
18686 ((stringp p) p)
18687 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18688 (format "%% Package %s omitted" (cadr p)))
18689 ((equal "" (car p))
18690 (format "\\usepackage{%s}" (cadr p)))
18692 (format "\\usepackage[%s]{%s}"
18693 (car p) (cadr p)))))
18695 "\n"))
18696 (if newline (concat pkg "\n") pkg))
18698 (defun org-dvipng-color (attr)
18699 "Return a RGB color specification for dvipng."
18700 (apply 'format "rgb %s %s %s"
18701 (mapcar 'org-normalize-color
18702 (if (featurep 'xemacs)
18703 (color-rgb-components
18704 (face-property 'default
18705 (cond ((eq attr :foreground) 'foreground)
18706 ((eq attr :background) 'background))))
18707 (color-values (face-attribute 'default attr nil))))))
18709 (defun org-dvipng-color-format (color-name)
18710 "Convert COLOR-NAME to a RGB color value for dvipng."
18711 (apply 'format "rgb %s %s %s"
18712 (mapcar 'org-normalize-color
18713 (color-values color-name))))
18715 (defun org-latex-color (attr)
18716 "Return a RGB color for the LaTeX color package."
18717 (apply 'format "%s,%s,%s"
18718 (mapcar 'org-normalize-color
18719 (if (featurep 'xemacs)
18720 (color-rgb-components
18721 (face-property 'default
18722 (cond ((eq attr :foreground) 'foreground)
18723 ((eq attr :background) 'background))))
18724 (color-values (face-attribute 'default attr nil))))))
18726 (defun org-latex-color-format (color-name)
18727 "Convert COLOR-NAME to a RGB color value."
18728 (apply 'format "%s,%s,%s"
18729 (mapcar 'org-normalize-color
18730 (color-values color-name))))
18732 (defun org-normalize-color (value)
18733 "Return string to be used as color value for an RGB component."
18734 (format "%g" (/ value 65535.0)))
18738 ;; Image display
18740 (defvar org-inline-image-overlays nil)
18741 (make-variable-buffer-local 'org-inline-image-overlays)
18743 (defun org-toggle-inline-images (&optional include-linked)
18744 "Toggle the display of inline images.
18745 INCLUDE-LINKED is passed to `org-display-inline-images'."
18746 (interactive "P")
18747 (if org-inline-image-overlays
18748 (progn
18749 (org-remove-inline-images)
18750 (message "Inline image display turned off"))
18751 (org-display-inline-images include-linked)
18752 (if (and (org-called-interactively-p)
18753 org-inline-image-overlays)
18754 (message "%d images displayed inline"
18755 (length org-inline-image-overlays))
18756 (message "No images to display inline"))))
18758 (defun org-redisplay-inline-images ()
18759 "Refresh the display of inline images."
18760 (interactive)
18761 (if (not org-inline-image-overlays)
18762 (org-toggle-inline-images)
18763 (org-toggle-inline-images)
18764 (org-toggle-inline-images)))
18766 (defun org-display-inline-images (&optional include-linked refresh beg end)
18767 "Display inline images.
18768 Normally only links without a description part are inlined, because this
18769 is how it will work for export. When INCLUDE-LINKED is set, also links
18770 with a description part will be inlined. This can be nice for a quick
18771 look at those images, but it does not reflect what exported files will look
18772 like.
18773 When REFRESH is set, refresh existing images between BEG and END.
18774 This will create new image displays only if necessary.
18775 BEG and END default to the buffer boundaries."
18776 (interactive "P")
18777 (unless refresh
18778 (org-remove-inline-images)
18779 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18780 (save-excursion
18781 (save-restriction
18782 (widen)
18783 (setq beg (or beg (point-min)) end (or end (point-max)))
18784 (goto-char beg)
18785 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18786 (substring (org-image-file-name-regexp) 0 -2)
18787 "\\)\\]" (if include-linked "" "\\]")))
18788 (case-fold-search t)
18789 old file ov img type attrwidth width)
18790 (while (re-search-forward re end t)
18791 (setq old (get-char-property-and-overlay (match-beginning 1)
18792 'org-image-overlay)
18793 file (expand-file-name
18794 (concat (or (match-string 3) "") (match-string 4))))
18795 (when (image-type-available-p 'imagemagick)
18796 (setq attrwidth (if (or (listp org-image-actual-width)
18797 (null org-image-actual-width))
18798 (save-excursion
18799 (save-match-data
18800 (when (re-search-backward
18801 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18802 (save-excursion
18803 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18804 (string-to-number (match-string 1))))))
18805 width (cond ((eq org-image-actual-width t) nil)
18806 ((null org-image-actual-width) attrwidth)
18807 ((numberp org-image-actual-width)
18808 org-image-actual-width)
18809 ((listp org-image-actual-width)
18810 (or attrwidth (car org-image-actual-width))))
18811 type (if width 'imagemagick)))
18812 (when (file-exists-p file)
18813 (if (and (car-safe old) refresh)
18814 (image-refresh (overlay-get (cdr old) 'display))
18815 (setq img (save-match-data (create-image file type nil :width width)))
18816 (when img
18817 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18818 (overlay-put ov 'display img)
18819 (overlay-put ov 'face 'default)
18820 (overlay-put ov 'org-image-overlay t)
18821 (overlay-put ov 'modification-hooks
18822 (list 'org-display-inline-remove-overlay))
18823 (push ov org-inline-image-overlays)))))))))
18825 (define-obsolete-function-alias
18826 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18828 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18829 "Remove inline-display overlay if a corresponding region is modified."
18830 (let ((inhibit-modification-hooks t))
18831 (when (and ov after)
18832 (delete ov org-inline-image-overlays)
18833 (delete-overlay ov))))
18835 (defun org-remove-inline-images ()
18836 "Remove inline display of images."
18837 (interactive)
18838 (mapc 'delete-overlay org-inline-image-overlays)
18839 (setq org-inline-image-overlays nil))
18841 ;;;; Key bindings
18843 ;; Outline functions from `outline-mode-prefix-map'
18844 ;; that can be remapped in Org:
18845 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18846 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18847 (define-key org-mode-map [remap outline-forward-same-level]
18848 'org-forward-heading-same-level)
18849 (define-key org-mode-map [remap outline-backward-same-level]
18850 'org-backward-heading-same-level)
18851 (define-key org-mode-map [remap show-branches]
18852 'org-kill-note-or-show-branches)
18853 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18854 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18855 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18857 ;; Outline functions from `outline-mode-prefix-map' that can not
18858 ;; be remapped in Org:
18860 ;; - the column "key binding" shows whether the Outline function is still
18861 ;; available in Org mode on the same key that it has been bound to in
18862 ;; Outline mode:
18863 ;; - "overridden": key used for a different functionality in Org mode
18864 ;; - else: key still bound to the same Outline function in Org mode
18866 ;; | Outline function | key binding | Org replacement |
18867 ;; |------------------------------------+-------------+-----------------------|
18868 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18869 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18870 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18871 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18872 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18873 ;; | `show-entry' | overridden | no replacement |
18874 ;; | `show-children' | `C-c C-i' | visibility cycling |
18875 ;; | `show-branches' | `C-c C-k' | still same function |
18876 ;; | `show-subtree' | overridden | visibility cycling |
18877 ;; | `show-all' | overridden | no replacement |
18878 ;; | `hide-subtree' | overridden | visibility cycling |
18879 ;; | `hide-body' | overridden | no replacement |
18880 ;; | `hide-entry' | overridden | visibility cycling |
18881 ;; | `hide-leaves' | overridden | no replacement |
18882 ;; | `hide-sublevels' | overridden | no replacement |
18883 ;; | `hide-other' | overridden | no replacement |
18885 ;; Make `C-c C-x' a prefix key
18886 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18888 ;; TAB key with modifiers
18889 (org-defkey org-mode-map "\C-i" 'org-cycle)
18890 (org-defkey org-mode-map [(tab)] 'org-cycle)
18891 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18892 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18893 ;; The following line is necessary under Suse GNU/Linux
18894 (unless (featurep 'xemacs)
18895 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18896 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18897 (define-key org-mode-map [backtab] 'org-shifttab)
18899 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18900 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18901 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18903 ;; Cursor keys with modifiers
18904 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18905 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18906 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18907 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18909 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18910 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18911 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18912 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18914 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18915 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18916 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18917 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18919 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18920 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18921 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18922 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18924 ;; Babel keys
18925 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18926 (mapc (lambda (pair)
18927 (define-key org-babel-map (car pair) (cdr pair)))
18928 org-babel-key-bindings)
18930 ;;; Extra keys for tty access.
18931 ;; We only set them when really needed because otherwise the
18932 ;; menus don't show the simple keys
18934 (when (or org-use-extra-keys
18935 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18936 (not window-system))
18937 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18938 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18939 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18940 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18941 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18942 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18943 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18944 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18945 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18946 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18947 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18948 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18949 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18950 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18951 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18952 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18953 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18954 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18955 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18956 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18957 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18958 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18959 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18960 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18961 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18962 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18963 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18964 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18966 ;; All the other keys
18968 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18969 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18970 (if (boundp 'narrow-map)
18971 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18972 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18973 (if (boundp 'narrow-map)
18974 (org-defkey narrow-map "b" 'org-narrow-to-block)
18975 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18976 (if (boundp 'narrow-map)
18977 (org-defkey narrow-map "e" 'org-narrow-to-element)
18978 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18979 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18980 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18981 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18982 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18983 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18984 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18985 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18986 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18987 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18988 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18989 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18990 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18991 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18992 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18993 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18994 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18995 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18996 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18997 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18998 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18999 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19000 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19001 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19002 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19003 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19004 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19005 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19006 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19007 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19008 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19009 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19010 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19011 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19012 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19013 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19014 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19015 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19016 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19017 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19018 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19019 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19020 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19021 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19022 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19023 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19024 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19025 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19026 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19027 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19028 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19029 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19030 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19031 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19032 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19033 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19034 (org-defkey org-mode-map "\C-c^" 'org-sort)
19035 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19036 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19037 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19038 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19039 (org-defkey org-mode-map "\C-m" 'org-return)
19040 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19041 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19042 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19043 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19044 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19045 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19046 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19047 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19048 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19049 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19050 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19051 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19052 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19053 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19054 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19055 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19056 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19057 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19058 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19059 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19060 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19061 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19062 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19064 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19065 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19066 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19068 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19069 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19070 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19071 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19072 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19073 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19074 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19075 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19076 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19077 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19078 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19079 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19080 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19081 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19082 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19083 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19084 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19085 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19086 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19087 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19088 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19089 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19090 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19092 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19093 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19094 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19095 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19096 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19098 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19100 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19102 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19103 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19105 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19108 (when (featurep 'xemacs)
19109 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19112 (defconst org-speed-commands-default
19114 ("Outline Navigation")
19115 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19116 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19117 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19118 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19119 ("F" . org-next-block)
19120 ("B" . org-previous-block)
19121 ("u" . (org-speed-move-safe 'outline-up-heading))
19122 ("j" . org-goto)
19123 ("g" . (org-refile t))
19124 ("Outline Visibility")
19125 ("c" . org-cycle)
19126 ("C" . org-shifttab)
19127 (" " . org-display-outline-path)
19128 ("s" . org-narrow-to-subtree)
19129 ("=" . org-columns)
19130 ("Outline Structure Editing")
19131 ("U" . org-shiftmetaup)
19132 ("D" . org-shiftmetadown)
19133 ("r" . org-metaright)
19134 ("l" . org-metaleft)
19135 ("R" . org-shiftmetaright)
19136 ("L" . org-shiftmetaleft)
19137 ("i" . (progn (forward-char 1) (call-interactively
19138 'org-insert-heading-respect-content)))
19139 ("^" . org-sort)
19140 ("w" . org-refile)
19141 ("a" . org-archive-subtree-default-with-confirmation)
19142 ("@" . org-mark-subtree)
19143 ("#" . org-toggle-comment)
19144 ("Clock Commands")
19145 ("I" . org-clock-in)
19146 ("O" . org-clock-out)
19147 ("Meta Data Editing")
19148 ("t" . org-todo)
19149 ("," . (org-priority))
19150 ("0" . (org-priority ?\ ))
19151 ("1" . (org-priority ?A))
19152 ("2" . (org-priority ?B))
19153 ("3" . (org-priority ?C))
19154 (":" . org-set-tags-command)
19155 ("e" . org-set-effort)
19156 ("E" . org-inc-effort)
19157 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19158 (org-entry-put (point) "APPT_WARNTIME" m)))
19159 ("Agenda Views etc")
19160 ("v" . org-agenda)
19161 ("/" . org-sparse-tree)
19162 ("Misc")
19163 ("o" . org-open-at-point)
19164 ("?" . org-speed-command-help)
19165 ("<" . (org-agenda-set-restriction-lock 'subtree))
19166 (">" . (org-agenda-remove-restriction-lock))
19168 "The default speed commands.")
19170 (defun org-print-speed-command (e)
19171 (if (> (length (car e)) 1)
19172 (progn
19173 (princ "\n")
19174 (princ (car e))
19175 (princ "\n")
19176 (princ (make-string (length (car e)) ?-))
19177 (princ "\n"))
19178 (princ (car e))
19179 (princ " ")
19180 (if (symbolp (cdr e))
19181 (princ (symbol-name (cdr e)))
19182 (prin1 (cdr e)))
19183 (princ "\n")))
19185 (defun org-speed-command-help ()
19186 "Show the available speed commands."
19187 (interactive)
19188 (if (not org-use-speed-commands)
19189 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19190 (with-output-to-temp-buffer "*Help*"
19191 (princ "User-defined Speed commands\n===========================\n")
19192 (mapc 'org-print-speed-command org-speed-commands-user)
19193 (princ "\n")
19194 (princ "Built-in Speed commands\n=======================\n")
19195 (mapc 'org-print-speed-command org-speed-commands-default))
19196 (with-current-buffer "*Help*"
19197 (setq truncate-lines t))))
19199 (defun org-speed-move-safe (cmd)
19200 "Execute CMD, but make sure that the cursor always ends up in a headline.
19201 If not, return to the original position and throw an error."
19202 (interactive)
19203 (let ((pos (point)))
19204 (call-interactively cmd)
19205 (unless (and (bolp) (org-at-heading-p))
19206 (goto-char pos)
19207 (error "Boundary reached while executing %s" cmd))))
19209 (defvar org-self-insert-command-undo-counter 0)
19211 (defvar org-table-auto-blank-field) ; defined in org-table.el
19212 (defvar org-speed-command nil)
19214 (define-obsolete-function-alias
19215 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19217 (defun org-speed-command-activate (keys)
19218 "Hook for activating single-letter speed commands.
19219 `org-speed-commands-default' specifies a minimal command set.
19220 Use `org-speed-commands-user' for further customization."
19221 (when (or (and (bolp) (looking-at org-outline-regexp))
19222 (and (functionp org-use-speed-commands)
19223 (funcall org-use-speed-commands)))
19224 (cdr (assoc keys (append org-speed-commands-user
19225 org-speed-commands-default)))))
19227 (define-obsolete-function-alias
19228 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19230 (defun org-babel-speed-command-activate (keys)
19231 "Hook for activating single-letter code block commands."
19232 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19233 (cdr (assoc keys org-babel-key-bindings))))
19235 (defcustom org-speed-command-hook
19236 '(org-speed-command-default-hook org-babel-speed-command-hook)
19237 "Hook for activating speed commands at strategic locations.
19238 Hook functions are called in sequence until a valid handler is
19239 found.
19241 Each hook takes a single argument, a user-pressed command key
19242 which is also a `self-insert-command' from the global map.
19244 Within the hook, examine the cursor position and the command key
19245 and return nil or a valid handler as appropriate. Handler could
19246 be one of an interactive command, a function, or a form.
19248 Set `org-use-speed-commands' to non-nil value to enable this
19249 hook. The default setting is `org-speed-command-activate'."
19250 :group 'org-structure
19251 :version "24.1"
19252 :type 'hook)
19254 (defun org-self-insert-command (N)
19255 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19256 If the cursor is in a table looking at whitespace, the whitespace is
19257 overwritten, and the table is not marked as requiring realignment."
19258 (interactive "p")
19259 (org-check-before-invisible-edit 'insert)
19260 (cond
19261 ((and org-use-speed-commands
19262 (setq org-speed-command
19263 (run-hook-with-args-until-success
19264 'org-speed-command-hook (this-command-keys))))
19265 (cond
19266 ((commandp org-speed-command)
19267 (setq this-command org-speed-command)
19268 (call-interactively org-speed-command))
19269 ((functionp org-speed-command)
19270 (funcall org-speed-command))
19271 ((and org-speed-command (listp org-speed-command))
19272 (eval org-speed-command))
19273 (t (let (org-use-speed-commands)
19274 (call-interactively 'org-self-insert-command)))))
19275 ((and
19276 (org-table-p)
19277 (progn
19278 ;; check if we blank the field, and if that triggers align
19279 (and (featurep 'org-table) org-table-auto-blank-field
19280 (member last-command
19281 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19282 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19283 ;; got extra space, this field does not determine column width
19284 (let (org-table-may-need-update) (org-table-blank-field))
19285 ;; no extra space, this field may determine column width
19286 (org-table-blank-field)))
19288 (eq N 1)
19289 (looking-at "[^|\n]* |"))
19290 (let (org-table-may-need-update)
19291 (goto-char (1- (match-end 0)))
19292 (backward-delete-char 1)
19293 (goto-char (match-beginning 0))
19294 (self-insert-command N)))
19296 (setq org-table-may-need-update t)
19297 (self-insert-command N)
19298 (org-fix-tags-on-the-fly)
19299 (if org-self-insert-cluster-for-undo
19300 (if (not (eq last-command 'org-self-insert-command))
19301 (setq org-self-insert-command-undo-counter 1)
19302 (if (>= org-self-insert-command-undo-counter 20)
19303 (setq org-self-insert-command-undo-counter 1)
19304 (and (> org-self-insert-command-undo-counter 0)
19305 buffer-undo-list (listp buffer-undo-list)
19306 (not (cadr buffer-undo-list)) ; remove nil entry
19307 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19308 (setq org-self-insert-command-undo-counter
19309 (1+ org-self-insert-command-undo-counter))))))))
19311 (defun org-check-before-invisible-edit (kind)
19312 "Check is editing if kind KIND would be dangerous with invisible text around.
19313 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19314 ;; First, try to get out of here as quickly as possible, to reduce overhead
19315 (if (and org-catch-invisible-edits
19316 (or (not (boundp 'visible-mode)) (not visible-mode))
19317 (or (get-char-property (point) 'invisible)
19318 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19319 ;; OK, we need to take a closer look
19320 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19321 (invisible-before-point (if (bobp) nil (get-char-property
19322 (1- (point)) 'invisible)))
19323 (border-and-ok-direction
19325 ;; Check if we are acting predictably before invisible text
19326 (and invisible-at-point (not invisible-before-point)
19327 (memq kind '(insert delete-backward)))
19328 ;; Check if we are acting predictably after invisible text
19329 ;; This works not well, and I have turned it off. It seems
19330 ;; better to always show and stop after invisible text.
19331 ;; (and (not invisible-at-point) invisible-before-point
19332 ;; (memq kind '(insert delete)))
19334 (when (or (memq invisible-at-point '(outline org-hide-block t))
19335 (memq invisible-before-point '(outline org-hide-block t)))
19336 (if (eq org-catch-invisible-edits 'error)
19337 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19338 (if (and org-custom-properties-overlays
19339 (y-or-n-p "Display invisible properties in this buffer? "))
19340 (org-toggle-custom-properties-visibility)
19341 ;; Make the area visible
19342 (save-excursion
19343 (if invisible-before-point
19344 (goto-char (previous-single-char-property-change
19345 (point) 'invisible)))
19346 (org-cycle))
19347 (cond
19348 ((eq org-catch-invisible-edits 'show)
19349 ;; That's it, we do the edit after showing
19350 (message
19351 "Unfolding invisible region around point before editing")
19352 (sit-for 1))
19353 ((and (eq org-catch-invisible-edits 'smart)
19354 border-and-ok-direction)
19355 (message "Unfolding invisible region around point before editing"))
19357 ;; Don't do the edit, make the user repeat it in full visibility
19358 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19360 (defun org-fix-tags-on-the-fly ()
19361 (when (and (equal (char-after (point-at-bol)) ?*)
19362 (org-at-heading-p))
19363 (org-align-tags-here org-tags-column)))
19365 (defun org-delete-backward-char (N)
19366 "Like `delete-backward-char', insert whitespace at field end in tables.
19367 When deleting backwards, in tables this function will insert whitespace in
19368 front of the next \"|\" separator, to keep the table aligned. The table will
19369 still be marked for re-alignment if the field did fill the entire column,
19370 because, in this case the deletion might narrow the column."
19371 (interactive "p")
19372 (save-match-data
19373 (org-check-before-invisible-edit 'delete-backward)
19374 (if (and (org-table-p)
19375 (eq N 1)
19376 (string-match "|" (buffer-substring (point-at-bol) (point)))
19377 (looking-at ".*?|"))
19378 (let ((pos (point))
19379 (noalign (looking-at "[^|\n\r]* |"))
19380 (c org-table-may-need-update))
19381 (backward-delete-char N)
19382 (if (not overwrite-mode)
19383 (progn
19384 (skip-chars-forward "^|")
19385 (insert " ")
19386 (goto-char (1- pos))))
19387 ;; noalign: if there were two spaces at the end, this field
19388 ;; does not determine the width of the column.
19389 (if noalign (setq org-table-may-need-update c)))
19390 (backward-delete-char N)
19391 (org-fix-tags-on-the-fly))))
19393 (defun org-delete-char (N)
19394 "Like `delete-char', but insert whitespace at field end in tables.
19395 When deleting characters, in tables this function will insert whitespace in
19396 front of the next \"|\" separator, to keep the table aligned. The table will
19397 still be marked for re-alignment if the field did fill the entire column,
19398 because, in this case the deletion might narrow the column."
19399 (interactive "p")
19400 (save-match-data
19401 (org-check-before-invisible-edit 'delete)
19402 (if (and (org-table-p)
19403 (not (bolp))
19404 (not (= (char-after) ?|))
19405 (eq N 1))
19406 (if (looking-at ".*?|")
19407 (let ((pos (point))
19408 (noalign (looking-at "[^|\n\r]* |"))
19409 (c org-table-may-need-update))
19410 (replace-match
19411 (concat (substring (match-string 0) 1 -1) " |") nil t)
19412 (goto-char pos)
19413 ;; noalign: if there were two spaces at the end, this field
19414 ;; does not determine the width of the column.
19415 (if noalign (setq org-table-may-need-update c)))
19416 (delete-char N))
19417 (delete-char N)
19418 (org-fix-tags-on-the-fly))))
19420 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19421 (put 'org-self-insert-command 'delete-selection t)
19422 (put 'orgtbl-self-insert-command 'delete-selection t)
19423 (put 'org-delete-char 'delete-selection 'supersede)
19424 (put 'org-delete-backward-char 'delete-selection 'supersede)
19425 (put 'org-yank 'delete-selection 'yank)
19427 ;; Make `flyspell-mode' delay after some commands
19428 (put 'org-self-insert-command 'flyspell-delayed t)
19429 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19430 (put 'org-delete-char 'flyspell-delayed t)
19431 (put 'org-delete-backward-char 'flyspell-delayed t)
19433 ;; Make pabbrev-mode expand after org-mode commands
19434 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19435 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19437 ;; How to do this: Measure non-white length of current string
19438 ;; If equal to column width, we should realign.
19440 (defun org-remap (map &rest commands)
19441 "In MAP, remap the functions given in COMMANDS.
19442 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19443 (let (new old)
19444 (while commands
19445 (setq old (pop commands) new (pop commands))
19446 (if (fboundp 'command-remapping)
19447 (org-defkey map (vector 'remap old) new)
19448 (substitute-key-definition old new map global-map)))))
19450 (defun org-transpose-words ()
19451 "Transpose words for Org.
19452 This uses the `org-mode-transpose-word-syntax-table' syntax
19453 table, which interprets characters in `org-emphasis-alist' as
19454 word constituants."
19455 (interactive)
19456 (with-syntax-table org-mode-transpose-word-syntax-table
19457 (call-interactively 'transpose-words)))
19458 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19460 (when (eq org-enable-table-editor 'optimized)
19461 ;; If the user wants maximum table support, we need to hijack
19462 ;; some standard editing functions
19463 (org-remap org-mode-map
19464 'self-insert-command 'org-self-insert-command
19465 'delete-char 'org-delete-char
19466 'delete-backward-char 'org-delete-backward-char)
19467 (org-defkey org-mode-map "|" 'org-force-self-insert))
19469 (defvar org-ctrl-c-ctrl-c-hook nil
19470 "Hook for functions attaching themselves to `C-c C-c'.
19472 This can be used to add additional functionality to the C-c C-c
19473 key which executes context-dependent commands. This hook is run
19474 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19475 run after the last test.
19477 Each function will be called with no arguments. The function
19478 must check if the context is appropriate for it to act. If yes,
19479 it should do its thing and then return a non-nil value. If the
19480 context is wrong, just do nothing and return nil.")
19482 (defvar org-ctrl-c-ctrl-c-final-hook nil
19483 "Hook for functions attaching themselves to `C-c C-c'.
19485 This can be used to add additional functionality to the C-c C-c
19486 key which executes context-dependent commands. This hook is run
19487 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19488 before the first test.
19490 Each function will be called with no arguments. The function
19491 must check if the context is appropriate for it to act. If yes,
19492 it should do its thing and then return a non-nil value. If the
19493 context is wrong, just do nothing and return nil.")
19495 (defvar org-tab-first-hook nil
19496 "Hook for functions to attach themselves to TAB.
19497 See `org-ctrl-c-ctrl-c-hook' for more information.
19498 This hook runs as the first action when TAB is pressed, even before
19499 `org-cycle' messes around with the `outline-regexp' to cater for
19500 inline tasks and plain list item folding.
19501 If any function in this hook returns t, any other actions that
19502 would have been caused by TAB (such as table field motion or visibility
19503 cycling) will not occur.")
19505 (defvar org-tab-after-check-for-table-hook nil
19506 "Hook for functions to attach themselves to TAB.
19507 See `org-ctrl-c-ctrl-c-hook' for more information.
19508 This hook runs after it has been established that the cursor is not in a
19509 table, but before checking if the cursor is in a headline or if global cycling
19510 should be done.
19511 If any function in this hook returns t, not other actions like visibility
19512 cycling will be done.")
19514 (defvar org-tab-after-check-for-cycling-hook nil
19515 "Hook for functions to attach themselves to TAB.
19516 See `org-ctrl-c-ctrl-c-hook' for more information.
19517 This hook runs after it has been established that not table field motion and
19518 not visibility should be done because of current context. This is probably
19519 the place where a package like yasnippets can hook in.")
19521 (defvar org-tab-before-tab-emulation-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 every other options for TAB have been exhausted, but
19525 before indentation and \t insertion takes place.")
19527 (defvar org-metaleft-hook nil
19528 "Hook for functions attaching themselves to `M-left'.
19529 See `org-ctrl-c-ctrl-c-hook' for more information.")
19530 (defvar org-metaright-hook nil
19531 "Hook for functions attaching themselves to `M-right'.
19532 See `org-ctrl-c-ctrl-c-hook' for more information.")
19533 (defvar org-metaup-hook nil
19534 "Hook for functions attaching themselves to `M-up'.
19535 See `org-ctrl-c-ctrl-c-hook' for more information.")
19536 (defvar org-metadown-hook nil
19537 "Hook for functions attaching themselves to `M-down'.
19538 See `org-ctrl-c-ctrl-c-hook' for more information.")
19539 (defvar org-shiftmetaleft-hook nil
19540 "Hook for functions attaching themselves to `M-S-left'.
19541 See `org-ctrl-c-ctrl-c-hook' for more information.")
19542 (defvar org-shiftmetaright-hook nil
19543 "Hook for functions attaching themselves to `M-S-right'.
19544 See `org-ctrl-c-ctrl-c-hook' for more information.")
19545 (defvar org-shiftmetaup-hook nil
19546 "Hook for functions attaching themselves to `M-S-up'.
19547 See `org-ctrl-c-ctrl-c-hook' for more information.")
19548 (defvar org-shiftmetadown-hook nil
19549 "Hook for functions attaching themselves to `M-S-down'.
19550 See `org-ctrl-c-ctrl-c-hook' for more information.")
19551 (defvar org-metareturn-hook nil
19552 "Hook for functions attaching themselves to `M-RET'.
19553 See `org-ctrl-c-ctrl-c-hook' for more information.")
19554 (defvar org-shiftup-hook nil
19555 "Hook for functions attaching themselves to `S-up'.
19556 See `org-ctrl-c-ctrl-c-hook' for more information.")
19557 (defvar org-shiftup-final-hook nil
19558 "Hook for functions attaching themselves to `S-up'.
19559 This one runs after all other options except shift-select have been excluded.
19560 See `org-ctrl-c-ctrl-c-hook' for more information.")
19561 (defvar org-shiftdown-hook nil
19562 "Hook for functions attaching themselves to `S-down'.
19563 See `org-ctrl-c-ctrl-c-hook' for more information.")
19564 (defvar org-shiftdown-final-hook nil
19565 "Hook for functions attaching themselves to `S-down'.
19566 This one runs after all other options except shift-select have been excluded.
19567 See `org-ctrl-c-ctrl-c-hook' for more information.")
19568 (defvar org-shiftleft-hook nil
19569 "Hook for functions attaching themselves to `S-left'.
19570 See `org-ctrl-c-ctrl-c-hook' for more information.")
19571 (defvar org-shiftleft-final-hook nil
19572 "Hook for functions attaching themselves to `S-left'.
19573 This one runs after all other options except shift-select have been excluded.
19574 See `org-ctrl-c-ctrl-c-hook' for more information.")
19575 (defvar org-shiftright-hook nil
19576 "Hook for functions attaching themselves to `S-right'.
19577 See `org-ctrl-c-ctrl-c-hook' for more information.")
19578 (defvar org-shiftright-final-hook nil
19579 "Hook for functions attaching themselves to `S-right'.
19580 This one runs after all other options except shift-select have been excluded.
19581 See `org-ctrl-c-ctrl-c-hook' for more information.")
19583 (defun org-modifier-cursor-error ()
19584 "Throw an error, a modified cursor command was applied in wrong context."
19585 (user-error "This command is active in special context like tables, headlines or items"))
19587 (defun org-shiftselect-error ()
19588 "Throw an error because Shift-Cursor command was applied in wrong context."
19589 (if (and (boundp 'shift-select-mode) shift-select-mode)
19590 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19591 (user-error "This command works only in special context like headlines or timestamps")))
19593 (defun org-call-for-shift-select (cmd)
19594 (let ((this-command-keys-shift-translated t))
19595 (call-interactively cmd)))
19597 (defun org-shifttab (&optional arg)
19598 "Global visibility cycling or move to previous table field.
19599 Call `org-table-previous-field' within a table.
19600 When ARG is nil, cycle globally through visibility states.
19601 When ARG is a numeric prefix, show contents of this level."
19602 (interactive "P")
19603 (cond
19604 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19605 ((integerp arg)
19606 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19607 (message "Content view to level: %d" arg)
19608 (org-content (prefix-numeric-value arg2))
19609 (org-cycle-show-empty-lines t)
19610 (setq org-cycle-global-status 'overview)))
19611 (t (call-interactively 'org-global-cycle))))
19613 (defun org-shiftmetaleft ()
19614 "Promote subtree or delete table column.
19615 Calls `org-promote-subtree', `org-outdent-item-tree', or
19616 `org-table-delete-column', depending on context. See the
19617 individual commands for more information."
19618 (interactive)
19619 (cond
19620 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19621 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19622 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19623 ((if (not (org-region-active-p)) (org-at-item-p)
19624 (save-excursion (goto-char (region-beginning))
19625 (org-at-item-p)))
19626 (call-interactively 'org-outdent-item-tree))
19627 (t (org-modifier-cursor-error))))
19629 (defun org-shiftmetaright ()
19630 "Demote subtree or insert table column.
19631 Calls `org-demote-subtree', `org-indent-item-tree', or
19632 `org-table-insert-column', depending on context. See the
19633 individual commands for more information."
19634 (interactive)
19635 (cond
19636 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19637 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19638 ((org-at-heading-p) (call-interactively 'org-demote-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-indent-item-tree))
19643 (t (org-modifier-cursor-error))))
19645 (defun org-shiftmetaup (&optional arg)
19646 "Move subtree up or kill table row.
19647 Calls `org-move-subtree-up' or `org-table-kill-row' or
19648 `org-move-item-up' or `org-timestamp-up', depending on context.
19649 See the individual commands for more information."
19650 (interactive "P")
19651 (cond
19652 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19653 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19654 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19655 ((org-at-item-p) (call-interactively 'org-move-item-up))
19656 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19657 (call-interactively 'org-timestamp-up)))
19658 (t (call-interactively 'org-drag-line-backward))))
19660 (defun org-shiftmetadown (&optional arg)
19661 "Move subtree down or insert table row.
19662 Calls `org-move-subtree-down' or `org-table-insert-row' or
19663 `org-move-item-down' or `org-timestamp-up', depending on context.
19664 See the individual commands for more information."
19665 (interactive "P")
19666 (cond
19667 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19668 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19669 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19670 ((org-at-item-p) (call-interactively 'org-move-item-down))
19671 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19672 (call-interactively 'org-timestamp-down)))
19673 (t (call-interactively 'org-drag-line-forward))))
19675 (defsubst org-hidden-tree-error ()
19676 (user-error
19677 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19679 (defun org-metaleft (&optional arg)
19680 "Promote heading or move table column to left.
19681 Calls `org-do-promote' or `org-table-move-column', depending on context.
19682 With no specific context, calls the Emacs default `backward-word'.
19683 See the individual commands for more information."
19684 (interactive "P")
19685 (cond
19686 ((run-hook-with-args-until-success 'org-metaleft-hook))
19687 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19688 ((org-with-limited-levels
19689 (or (org-at-heading-p)
19690 (and (org-region-active-p)
19691 (save-excursion
19692 (goto-char (region-beginning))
19693 (org-at-heading-p)))))
19694 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19695 (call-interactively 'org-do-promote))
19696 ;; At an inline task.
19697 ((org-at-heading-p)
19698 (call-interactively 'org-inlinetask-promote))
19699 ((or (org-at-item-p)
19700 (and (org-region-active-p)
19701 (save-excursion
19702 (goto-char (region-beginning))
19703 (org-at-item-p))))
19704 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19705 (call-interactively 'org-outdent-item))
19706 (t (call-interactively 'backward-word))))
19708 (defun org-metaright (&optional arg)
19709 "Demote a subtree, a list item or move table column to right.
19710 In front of a drawer or a block keyword, indent it correctly.
19711 With no specific context, calls the Emacs default `forward-word'.
19712 See the individual commands for more information."
19713 (interactive "P")
19714 (cond
19715 ((run-hook-with-args-until-success 'org-metaright-hook))
19716 ((org-at-table-p) (call-interactively 'org-table-move-column))
19717 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19718 ((org-at-block-p) (call-interactively 'org-indent-block))
19719 ((org-with-limited-levels
19720 (or (org-at-heading-p)
19721 (and (org-region-active-p)
19722 (save-excursion
19723 (goto-char (region-beginning))
19724 (org-at-heading-p)))))
19725 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19726 (call-interactively 'org-do-demote))
19727 ;; At an inline task.
19728 ((org-at-heading-p)
19729 (call-interactively 'org-inlinetask-demote))
19730 ((or (org-at-item-p)
19731 (and (org-region-active-p)
19732 (save-excursion
19733 (goto-char (region-beginning))
19734 (org-at-item-p))))
19735 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19736 (call-interactively 'org-indent-item))
19737 (t (call-interactively 'forward-word))))
19739 (defun org-check-for-hidden (what)
19740 "Check if there are hidden headlines/items in the current visual line.
19741 WHAT can be either `headlines' or `items'. If the current line is
19742 an outline or item heading and it has a folded subtree below it,
19743 this function returns t, nil otherwise."
19744 (let ((re (cond
19745 ((eq what 'headlines) org-outline-regexp-bol)
19746 ((eq what 'items) (org-item-beginning-re))
19747 (t (error "This should not happen"))))
19748 beg end)
19749 (save-excursion
19750 (catch 'exit
19751 (unless (org-region-active-p)
19752 (setq beg (point-at-bol))
19753 (beginning-of-line 2)
19754 (while (and (not (eobp)) ;; this is like `next-line'
19755 (get-char-property (1- (point)) 'invisible))
19756 (beginning-of-line 2))
19757 (setq end (point))
19758 (goto-char beg)
19759 (goto-char (point-at-eol))
19760 (setq end (max end (point)))
19761 (while (re-search-forward re end t)
19762 (if (get-char-property (match-beginning 0) 'invisible)
19763 (throw 'exit t))))
19764 nil))))
19766 (defun org-metaup (&optional arg)
19767 "Move subtree up or move table row up.
19768 Calls `org-move-subtree-up' or `org-table-move-row' or
19769 `org-move-item-up', depending on context. See the individual commands
19770 for more information."
19771 (interactive "P")
19772 (cond
19773 ((run-hook-with-args-until-success 'org-metaup-hook))
19774 ((org-region-active-p)
19775 (let* ((a (min (region-beginning) (region-end)))
19776 (b (1- (max (region-beginning) (region-end))))
19777 (c (save-excursion (goto-char a)
19778 (move-beginning-of-line 0)))
19779 (d (save-excursion (goto-char a)
19780 (move-end-of-line 0) (point))))
19781 (transpose-regions a b c d)
19782 (goto-char c)))
19783 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19784 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19785 ((org-at-item-p) (call-interactively 'org-move-item-up))
19786 (t (org-drag-element-backward))))
19788 (defun org-metadown (&optional arg)
19789 "Move subtree down or move table row down.
19790 Calls `org-move-subtree-down' or `org-table-move-row' or
19791 `org-move-item-down', depending on context. See the individual
19792 commands for more information."
19793 (interactive "P")
19794 (cond
19795 ((run-hook-with-args-until-success 'org-metadown-hook))
19796 ((org-region-active-p)
19797 (let* ((a (min (region-beginning) (region-end)))
19798 (b (max (region-beginning) (region-end)))
19799 (c (save-excursion (goto-char b)
19800 (move-beginning-of-line 1)))
19801 (d (save-excursion (goto-char b)
19802 (move-end-of-line 1) (1+ (point)))))
19803 (transpose-regions a b c d)
19804 (goto-char d)))
19805 ((org-at-table-p) (call-interactively 'org-table-move-row))
19806 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19807 ((org-at-item-p) (call-interactively 'org-move-item-down))
19808 (t (org-drag-element-forward))))
19810 (defun org-shiftup (&optional arg)
19811 "Increase item in timestamp or increase priority of current headline.
19812 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19813 depending on context. See the individual commands for more information."
19814 (interactive "P")
19815 (cond
19816 ((run-hook-with-args-until-success 'org-shiftup-hook))
19817 ((and org-support-shift-select (org-region-active-p))
19818 (org-call-for-shift-select 'previous-line))
19819 ((org-at-timestamp-p t)
19820 (call-interactively (if org-edit-timestamp-down-means-later
19821 'org-timestamp-down 'org-timestamp-up)))
19822 ((and (not (eq org-support-shift-select 'always))
19823 org-enable-priority-commands
19824 (org-at-heading-p))
19825 (call-interactively 'org-priority-up))
19826 ((and (not org-support-shift-select) (org-at-item-p))
19827 (call-interactively 'org-previous-item))
19828 ((org-clocktable-try-shift 'up arg))
19829 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19830 (org-support-shift-select
19831 (org-call-for-shift-select 'previous-line))
19832 (t (org-shiftselect-error))))
19834 (defun org-shiftdown (&optional arg)
19835 "Decrease item in timestamp or decrease priority of current headline.
19836 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19837 depending on context. See the individual commands for more information."
19838 (interactive "P")
19839 (cond
19840 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19841 ((and org-support-shift-select (org-region-active-p))
19842 (org-call-for-shift-select 'next-line))
19843 ((org-at-timestamp-p t)
19844 (call-interactively (if org-edit-timestamp-down-means-later
19845 'org-timestamp-up 'org-timestamp-down)))
19846 ((and (not (eq org-support-shift-select 'always))
19847 org-enable-priority-commands
19848 (org-at-heading-p))
19849 (call-interactively 'org-priority-down))
19850 ((and (not org-support-shift-select) (org-at-item-p))
19851 (call-interactively 'org-next-item))
19852 ((org-clocktable-try-shift 'down arg))
19853 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19854 (org-support-shift-select
19855 (org-call-for-shift-select 'next-line))
19856 (t (org-shiftselect-error))))
19858 (defun org-shiftright (&optional arg)
19859 "Cycle the thing at point or in the current line, depending on context.
19860 Depending on context, this does one of the following:
19862 - switch a timestamp at point one day into the future
19863 - on a headline, switch to the next TODO keyword.
19864 - on an item, switch entire list to the next bullet type
19865 - on a property line, switch to the next allowed value
19866 - on a clocktable definition line, move time block into the future"
19867 (interactive "P")
19868 (cond
19869 ((run-hook-with-args-until-success 'org-shiftright-hook))
19870 ((and org-support-shift-select (org-region-active-p))
19871 (org-call-for-shift-select 'forward-char))
19872 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19873 ((and (not (eq org-support-shift-select 'always))
19874 (org-at-heading-p))
19875 (let ((org-inhibit-logging
19876 (not org-treat-S-cursor-todo-selection-as-state-change))
19877 (org-inhibit-blocking
19878 (not org-treat-S-cursor-todo-selection-as-state-change)))
19879 (org-call-with-arg 'org-todo 'right)))
19880 ((or (and org-support-shift-select
19881 (not (eq org-support-shift-select 'always))
19882 (org-at-item-bullet-p))
19883 (and (not org-support-shift-select) (org-at-item-p)))
19884 (org-call-with-arg 'org-cycle-list-bullet nil))
19885 ((and (not (eq org-support-shift-select 'always))
19886 (org-at-property-p))
19887 (call-interactively 'org-property-next-allowed-value))
19888 ((org-clocktable-try-shift 'right arg))
19889 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19890 (org-support-shift-select
19891 (org-call-for-shift-select 'forward-char))
19892 (t (org-shiftselect-error))))
19894 (defun org-shiftleft (&optional arg)
19895 "Cycle the thing at point or in the current line, depending on context.
19896 Depending on context, this does one of the following:
19898 - switch a timestamp at point one day into the past
19899 - on a headline, switch to the previous TODO keyword.
19900 - on an item, switch entire list to the previous bullet type
19901 - on a property line, switch to the previous allowed value
19902 - on a clocktable definition line, move time block into the past"
19903 (interactive "P")
19904 (cond
19905 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19906 ((and org-support-shift-select (org-region-active-p))
19907 (org-call-for-shift-select 'backward-char))
19908 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19909 ((and (not (eq org-support-shift-select 'always))
19910 (org-at-heading-p))
19911 (let ((org-inhibit-logging
19912 (not org-treat-S-cursor-todo-selection-as-state-change))
19913 (org-inhibit-blocking
19914 (not org-treat-S-cursor-todo-selection-as-state-change)))
19915 (org-call-with-arg 'org-todo 'left)))
19916 ((or (and org-support-shift-select
19917 (not (eq org-support-shift-select 'always))
19918 (org-at-item-bullet-p))
19919 (and (not org-support-shift-select) (org-at-item-p)))
19920 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19921 ((and (not (eq org-support-shift-select 'always))
19922 (org-at-property-p))
19923 (call-interactively 'org-property-previous-allowed-value))
19924 ((org-clocktable-try-shift 'left arg))
19925 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19926 (org-support-shift-select
19927 (org-call-for-shift-select 'backward-char))
19928 (t (org-shiftselect-error))))
19930 (defun org-shiftcontrolright ()
19931 "Switch to next TODO set."
19932 (interactive)
19933 (cond
19934 ((and org-support-shift-select (org-region-active-p))
19935 (org-call-for-shift-select 'forward-word))
19936 ((and (not (eq org-support-shift-select 'always))
19937 (org-at-heading-p))
19938 (org-call-with-arg 'org-todo 'nextset))
19939 (org-support-shift-select
19940 (org-call-for-shift-select 'forward-word))
19941 (t (org-shiftselect-error))))
19943 (defun org-shiftcontrolleft ()
19944 "Switch to previous TODO set."
19945 (interactive)
19946 (cond
19947 ((and org-support-shift-select (org-region-active-p))
19948 (org-call-for-shift-select 'backward-word))
19949 ((and (not (eq org-support-shift-select 'always))
19950 (org-at-heading-p))
19951 (org-call-with-arg 'org-todo 'previousset))
19952 (org-support-shift-select
19953 (org-call-for-shift-select 'backward-word))
19954 (t (org-shiftselect-error))))
19956 (defun org-shiftcontrolup (&optional n)
19957 "Change timestamps synchronously up in CLOCK log lines.
19958 Optional argument N tells to change by that many units."
19959 (interactive "P")
19960 (cond ((and (not org-support-shift-select)
19961 (org-at-clock-log-p)
19962 (org-at-timestamp-p t))
19963 (org-clock-timestamps-up n))
19964 (t (org-shiftselect-error))))
19966 (defun org-shiftcontroldown (&optional n)
19967 "Change timestamps synchronously down in CLOCK log lines.
19968 Optional argument N tells to change by that many units."
19969 (interactive "P")
19970 (cond ((and (not org-support-shift-select)
19971 (org-at-clock-log-p)
19972 (org-at-timestamp-p t))
19973 (org-clock-timestamps-down n))
19974 (t (org-shiftselect-error))))
19976 (defun org-ctrl-c-ret ()
19977 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19978 (interactive)
19979 (cond
19980 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19981 (t (call-interactively 'org-insert-heading))))
19983 (defun org-find-visible ()
19984 (let ((s (point)))
19985 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19986 (get-char-property s 'invisible)))
19988 (defun org-find-invisible ()
19989 (let ((s (point)))
19990 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19991 (not (get-char-property s 'invisible))))
19994 (defun org-copy-visible (beg end)
19995 "Copy the visible parts of the region."
19996 (interactive "r")
19997 (let (snippets s)
19998 (save-excursion
19999 (save-restriction
20000 (narrow-to-region beg end)
20001 (setq s (goto-char (point-min)))
20002 (while (not (= (point) (point-max)))
20003 (goto-char (org-find-invisible))
20004 (push (buffer-substring s (point)) snippets)
20005 (setq s (goto-char (org-find-visible))))))
20006 (kill-new (apply 'concat (nreverse snippets)))))
20008 (defun org-copy-special ()
20009 "Copy region in table or copy current subtree.
20010 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20011 See the individual commands for more information."
20012 (interactive)
20013 (call-interactively
20014 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20016 (defun org-cut-special ()
20017 "Cut region in table or cut current subtree.
20018 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20019 See the individual commands for more information."
20020 (interactive)
20021 (call-interactively
20022 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20024 (defun org-paste-special (arg)
20025 "Paste rectangular region into table, or past subtree relative to level.
20026 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20027 See the individual commands for more information."
20028 (interactive "P")
20029 (if (org-at-table-p)
20030 (org-table-paste-rectangle)
20031 (org-paste-subtree arg)))
20033 (defsubst org-in-fixed-width-region-p ()
20034 "Is point in a fixed-width region?"
20035 (save-match-data
20036 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20038 (defun org-edit-special (&optional arg)
20039 "Call a special editor for the element at point.
20040 When at a table, call the formula editor with `org-table-edit-formulas'.
20041 When in a source code block, call `org-edit-src-code'.
20042 When in a fixed-width region, call `org-edit-fixed-width-region'.
20043 When at an #+INCLUDE keyword, visit the included file.
20044 On a link, call `ffap' to visit the link at point.
20045 Otherwise, return a user error."
20046 (interactive "P")
20047 (let ((element (org-element-at-point)))
20048 (assert (not buffer-read-only) nil
20049 "Buffer is read-only: %s" (buffer-name))
20050 (case (org-element-type element)
20051 (src-block
20052 (if (not arg) (org-edit-src-code)
20053 (let* ((info (org-babel-get-src-block-info))
20054 (lang (nth 0 info))
20055 (params (nth 2 info))
20056 (session (cdr (assq :session params))))
20057 (if (not session) (org-edit-src-code)
20058 ;; At a src-block with a session and function called with
20059 ;; an ARG: switch to the buffer related to the inferior
20060 ;; process.
20061 (switch-to-buffer
20062 (funcall (intern (concat "org-babel-prep-session:" lang))
20063 session params))))))
20064 (keyword
20065 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20066 (find-file
20067 (org-remove-double-quotes
20068 (car (org-split-string (org-element-property :value element)))))
20069 (user-error "No special environment to edit here")))
20070 (table
20071 (if (eq (org-element-property :type element) 'table.el)
20072 (org-edit-src-code)
20073 (call-interactively 'org-table-edit-formulas)))
20074 ;; Only Org tables contain `table-row' type elements.
20075 (table-row (call-interactively 'org-table-edit-formulas))
20076 ((example-block export-block) (org-edit-src-code))
20077 (fixed-width (org-edit-fixed-width-region))
20078 (otherwise
20079 ;; No notable element at point. Though, we may be at a link,
20080 ;; which is an object. Thus, scan deeper.
20081 (if (eq (org-element-type (org-element-context element)) 'link)
20082 (call-interactively 'ffap)
20083 (user-error "No special environment to edit here"))))))
20085 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20086 (defun org-ctrl-c-ctrl-c (&optional arg)
20087 "Set tags in headline, or update according to changed information at point.
20089 This command does many different things, depending on context:
20091 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20092 this is what we do.
20094 - If the cursor is on a statistics cookie, update it.
20096 - If the cursor is in a headline, prompt for tags and insert them
20097 into the current line, aligned to `org-tags-column'. When called
20098 with prefix arg, realign all tags in the current buffer.
20100 - If the cursor is in one of the special #+KEYWORD lines, this
20101 triggers scanning the buffer for these lines and updating the
20102 information.
20104 - If the cursor is inside a table, realign the table. This command
20105 works even if the automatic table editor has been turned off.
20107 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20108 the entire table.
20110 - If the cursor is at a footnote reference or definition, jump to
20111 the corresponding definition or references, respectively.
20113 - If the cursor is a the beginning of a dynamic block, update it.
20115 - If the current buffer is a capture buffer, close note and file it.
20117 - If the cursor is on a <<<target>>>, update radio targets and
20118 corresponding links in this buffer.
20120 - If the cursor is on a numbered item in a plain list, renumber the
20121 ordered list.
20123 - If the cursor is on a checkbox, toggle it.
20125 - If the cursor is on a code block, evaluate it. The variable
20126 `org-confirm-babel-evaluate' can be used to control prompting
20127 before code block evaluation, by default every code block
20128 evaluation requires confirmation. Code block evaluation can be
20129 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20130 (interactive "P")
20131 (cond
20132 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20133 org-occur-highlights
20134 org-latex-fragment-image-overlays)
20135 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20136 (org-remove-occur-highlights)
20137 (org-remove-latex-fragment-image-overlays)
20138 (message "Temporary highlights/overlays removed from current buffer"))
20139 ((and (local-variable-p 'org-finish-function (current-buffer))
20140 (fboundp org-finish-function))
20141 (funcall org-finish-function))
20142 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20144 (let* ((context (org-element-context)) (type (org-element-type context)))
20145 ;; Test if point is within a blank line.
20146 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20147 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20148 (user-error "C-c C-c can do nothing useful at this location"))
20149 ;; For convenience: at the first line of a paragraph on the
20150 ;; same line as an item, apply function on that item instead.
20151 (when (eq type 'paragraph)
20152 (let ((parent (org-element-property :parent context)))
20153 (when (and (eq (org-element-type parent) 'item)
20154 (= (point-at-bol) (org-element-property :begin parent)))
20155 (setq context parent type 'item))))
20156 ;; Act according to type of element or object at point.
20157 (case type
20158 (clock (org-clock-update-time-maybe))
20159 (dynamic-block
20160 (save-excursion
20161 (goto-char (org-element-property :post-affiliated context))
20162 (org-update-dblock)))
20163 (footnote-definition
20164 (goto-char (org-element-property :post-affiliated context))
20165 (call-interactively 'org-footnote-action))
20166 (footnote-reference (call-interactively 'org-footnote-action))
20167 ((headline inlinetask)
20168 (save-excursion (goto-char (org-element-property :begin context))
20169 (call-interactively 'org-set-tags)))
20170 (item
20171 ;; At an item: a double C-u set checkbox to "[-]"
20172 ;; unconditionally, whereas a single one will toggle its
20173 ;; presence. Without an universal argument, if the item
20174 ;; has a checkbox, toggle it. Otherwise repair the list.
20175 (let* ((box (org-element-property :checkbox context))
20176 (struct (org-element-property :structure context))
20177 (old-struct (copy-tree struct))
20178 (parents (org-list-parents-alist struct))
20179 (prevs (org-list-prevs-alist struct))
20180 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20181 (org-list-set-checkbox
20182 (org-element-property :begin context) struct
20183 (cond ((equal arg '(16)) "[-]")
20184 ((and (not box) (equal arg '(4))) "[ ]")
20185 ((or (not box) (equal arg '(4))) nil)
20186 ((eq box 'on) "[ ]")
20187 (t "[X]")))
20188 ;; Mimic `org-list-write-struct' but with grabbing
20189 ;; a return value from `org-list-struct-fix-box'.
20190 (org-list-struct-fix-ind struct parents 2)
20191 (org-list-struct-fix-item-end struct)
20192 (org-list-struct-fix-bul struct prevs)
20193 (org-list-struct-fix-ind struct parents)
20194 (let ((block-item
20195 (org-list-struct-fix-box struct parents prevs orderedp)))
20196 (if (and box (equal struct old-struct))
20197 (if (equal arg '(16))
20198 (message "Checkboxes already reset")
20199 (user-error "Cannot toggle this checkbox: %s"
20200 (if (eq box 'on)
20201 "all subitems checked"
20202 "unchecked subitems")))
20203 (org-list-struct-apply-struct struct old-struct)
20204 (org-update-checkbox-count-maybe))
20205 (when block-item
20206 (message "Checkboxes were removed due to empty box at line %d"
20207 (org-current-line block-item))))))
20208 (keyword
20209 (let ((org-inhibit-startup-visibility-stuff t)
20210 (org-startup-align-all-tables nil))
20211 (when (boundp 'org-table-coordinate-overlays)
20212 (mapc 'delete-overlay org-table-coordinate-overlays)
20213 (setq org-table-coordinate-overlays nil))
20214 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20215 (message "Local setup has been refreshed"))
20216 (plain-list
20217 ;; At a plain list, with a double C-u argument, set
20218 ;; checkboxes of each item to "[-]", whereas a single one
20219 ;; will toggle their presence according to the state of the
20220 ;; first item in the list. Without an argument, repair the
20221 ;; list.
20222 (let* ((begin (org-element-property :contents-begin context))
20223 (beginm (move-marker (make-marker) begin))
20224 (struct (org-element-property :structure context))
20225 (old-struct (copy-tree struct))
20226 (first-box (save-excursion
20227 (goto-char begin)
20228 (looking-at org-list-full-item-re)
20229 (match-string-no-properties 3)))
20230 (new-box (cond ((equal arg '(16)) "[-]")
20231 ((equal arg '(4)) (unless first-box "[ ]"))
20232 ((equal first-box "[X]") "[ ]")
20233 (t "[X]"))))
20234 (cond
20235 (arg
20236 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20237 (org-list-get-all-items
20238 begin struct (org-list-prevs-alist struct))))
20239 ((and first-box (eq (point) begin))
20240 ;; For convenience, when point is at bol on the first
20241 ;; item of the list and no argument is provided, simply
20242 ;; toggle checkbox of that item, if any.
20243 (org-list-set-checkbox begin struct new-box)))
20244 (org-list-write-struct
20245 struct (org-list-parents-alist struct) old-struct)
20246 (org-update-checkbox-count-maybe)
20247 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20248 ((property-drawer node-property)
20249 (call-interactively 'org-property-action))
20250 ((radio-target target)
20251 (call-interactively 'org-update-radio-target-regexp))
20252 (statistics-cookie
20253 (call-interactively 'org-update-statistics-cookies))
20254 ((table table-cell table-row)
20255 ;; At a table, recalculate every field and align it. Also
20256 ;; send the table if necessary. If the table has
20257 ;; a `table.el' type, just give up. At a table row or
20258 ;; cell, maybe recalculate line but always align table.
20259 (if (eq (org-element-property :type context) 'table.el)
20260 (message "Use C-c ' to edit table.el tables")
20261 (let ((org-enable-table-editor t))
20262 (if (or (eq type 'table)
20263 ;; Check if point is at a TBLFM line.
20264 (and (eq type 'table-row)
20265 (= (point) (org-element-property :end context))))
20266 (save-excursion
20267 (if (org-at-TBLFM-p)
20268 (progn (require 'org-table)
20269 (org-table-calc-current-TBLFM))
20270 (goto-char (org-element-property :contents-begin context))
20271 (org-call-with-arg 'org-table-recalculate (or arg t))
20272 (orgtbl-send-table 'maybe)))
20273 (org-table-maybe-eval-formula)
20274 (cond (arg (call-interactively 'org-table-recalculate))
20275 ((org-table-maybe-recalculate-line))
20276 (t (org-table-align)))))))
20277 (timestamp (org-timestamp-change 0 'day))
20278 (otherwise
20279 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20280 (user-error
20281 "C-c C-c can do nothing useful at this location")))))))))
20283 (defun org-mode-restart ()
20284 "Restart Org-mode, to scan again for special lines.
20285 Also updates the keyword regular expressions."
20286 (interactive)
20287 (org-mode)
20288 (message "Org-mode restarted"))
20290 (defun org-kill-note-or-show-branches ()
20291 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20292 (interactive)
20293 (if (not org-finish-function)
20294 (progn
20295 (hide-subtree)
20296 (call-interactively 'show-branches))
20297 (let ((org-note-abort t))
20298 (funcall org-finish-function))))
20300 (defun org-open-line (n)
20301 "Insert a new row in tables, call `open-line' elsewhere."
20302 (interactive "*p")
20303 (if (org-at-table-p)
20304 (org-table-insert-row)
20305 (open-line n)))
20307 (defun org-return (&optional indent)
20308 "Goto next table row or insert a newline.
20309 Calls `org-table-next-row' or `newline', depending on context.
20310 See the individual commands for more information."
20311 (interactive)
20312 (let (org-ts-what)
20313 (cond
20314 ((or (bobp) (org-in-src-block-p))
20315 (if indent (newline-and-indent) (newline)))
20316 ((org-at-table-p)
20317 (org-table-justify-field-maybe)
20318 (call-interactively 'org-table-next-row))
20319 ;; when `newline-and-indent' is called within a list, make sure
20320 ;; text moved stays inside the item.
20321 ((and (org-in-item-p) indent)
20322 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20323 (progn
20324 (save-match-data (newline))
20325 (org-indent-line-to (length (match-string 0))))
20326 (let ((ind (org-get-indentation)))
20327 (newline)
20328 (if (org-looking-back org-list-end-re)
20329 (org-indent-line)
20330 (org-indent-line-to ind)))))
20331 ((and org-return-follows-link
20332 (org-at-timestamp-p t)
20333 (not (eq org-ts-what 'after)))
20334 (org-follow-timestamp-link))
20335 ((and org-return-follows-link
20336 (let ((tprop (get-text-property (point) 'face)))
20337 (or (eq tprop 'org-link)
20338 (and (listp tprop) (memq 'org-link tprop)))))
20339 (call-interactively 'org-open-at-point))
20340 ((and (org-at-heading-p)
20341 (looking-at
20342 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20343 (org-show-entry)
20344 (end-of-line 1)
20345 (newline))
20346 (t (if indent (newline-and-indent) (newline))))))
20348 (defun org-return-indent ()
20349 "Goto next table row or insert a newline and indent.
20350 Calls `org-table-next-row' or `newline-and-indent', depending on
20351 context. See the individual commands for more information."
20352 (interactive)
20353 (org-return t))
20355 (defun org-ctrl-c-star ()
20356 "Compute table, or change heading status of lines.
20357 Calls `org-table-recalculate' or `org-toggle-heading',
20358 depending on context."
20359 (interactive)
20360 (cond
20361 ((org-at-table-p)
20362 (call-interactively 'org-table-recalculate))
20364 ;; Convert all lines in region to list items
20365 (call-interactively 'org-toggle-heading))))
20367 (defun org-ctrl-c-minus ()
20368 "Insert separator line in table or modify bullet status of line.
20369 Also turns a plain line or a region of lines into list items.
20370 Calls `org-table-insert-hline', `org-toggle-item', or
20371 `org-cycle-list-bullet', depending on context."
20372 (interactive)
20373 (cond
20374 ((org-at-table-p)
20375 (call-interactively 'org-table-insert-hline))
20376 ((org-region-active-p)
20377 (call-interactively 'org-toggle-item))
20378 ((org-in-item-p)
20379 (call-interactively 'org-cycle-list-bullet))
20381 (call-interactively 'org-toggle-item))))
20383 (defun org-toggle-item (arg)
20384 "Convert headings or normal lines to items, items to normal lines.
20385 If there is no active region, only the current line is considered.
20387 If the first non blank line in the region is a headline, convert
20388 all headlines to items, shifting text accordingly.
20390 If it is an item, convert all items to normal lines.
20392 If it is normal text, change region into a list of items.
20393 With a prefix argument ARG, change the region in a single item."
20394 (interactive "P")
20395 (let ((shift-text
20396 (function
20397 ;; Shift text in current section to IND, from point to END.
20398 ;; The function leaves point to END line.
20399 (lambda (ind end)
20400 (let ((min-i 1000) (end (copy-marker end)))
20401 ;; First determine the minimum indentation (MIN-I) of
20402 ;; the text.
20403 (save-excursion
20404 (catch 'exit
20405 (while (< (point) end)
20406 (let ((i (org-get-indentation)))
20407 (cond
20408 ;; Skip blank lines and inline tasks.
20409 ((looking-at "^[ \t]*$"))
20410 ((looking-at org-outline-regexp-bol))
20411 ;; We can't find less than 0 indentation.
20412 ((zerop i) (throw 'exit (setq min-i 0)))
20413 ((< i min-i) (setq min-i i))))
20414 (forward-line))))
20415 ;; Then indent each line so that a line indented to
20416 ;; MIN-I becomes indented to IND. Ignore blank lines
20417 ;; and inline tasks in the process.
20418 (let ((delta (- ind min-i)))
20419 (while (< (point) end)
20420 (unless (or (looking-at "^[ \t]*$")
20421 (looking-at org-outline-regexp-bol))
20422 (org-indent-line-to (+ (org-get-indentation) delta)))
20423 (forward-line)))))))
20424 (skip-blanks
20425 (function
20426 ;; Return beginning of first non-blank line, starting from
20427 ;; line at POS.
20428 (lambda (pos)
20429 (save-excursion
20430 (goto-char pos)
20431 (skip-chars-forward " \r\t\n")
20432 (point-at-bol)))))
20433 beg end)
20434 ;; Determine boundaries of changes.
20435 (if (org-region-active-p)
20436 (setq beg (funcall skip-blanks (region-beginning))
20437 end (copy-marker (region-end)))
20438 (setq beg (funcall skip-blanks (point-at-bol))
20439 end (copy-marker (point-at-eol))))
20440 ;; Depending on the starting line, choose an action on the text
20441 ;; between BEG and END.
20442 (org-with-limited-levels
20443 (save-excursion
20444 (goto-char beg)
20445 (cond
20446 ;; Case 1. Start at an item: de-itemize. Note that it only
20447 ;; happens when a region is active: `org-ctrl-c-minus'
20448 ;; would call `org-cycle-list-bullet' otherwise.
20449 ((org-at-item-p)
20450 (while (< (point) end)
20451 (when (org-at-item-p)
20452 (skip-chars-forward " \t")
20453 (delete-region (point) (match-end 0)))
20454 (forward-line)))
20455 ;; Case 2. Start at an heading: convert to items.
20456 ((org-at-heading-p)
20457 (let* ((bul (org-list-bullet-string "-"))
20458 (bul-len (length bul))
20459 ;; Indentation of the first heading. It should be
20460 ;; relative to the indentation of its parent, if any.
20461 (start-ind (save-excursion
20462 (cond
20463 ((not org-adapt-indentation) 0)
20464 ((not (outline-previous-heading)) 0)
20465 (t (length (match-string 0))))))
20466 ;; Level of first heading. Further headings will be
20467 ;; compared to it to determine hierarchy in the list.
20468 (ref-level (org-reduced-level (org-outline-level))))
20469 (while (< (point) end)
20470 (let* ((level (org-reduced-level (org-outline-level)))
20471 (delta (max 0 (- level ref-level))))
20472 ;; If current headline is less indented than the first
20473 ;; one, set it as reference, in order to preserve
20474 ;; subtrees.
20475 (when (< level ref-level) (setq ref-level level))
20476 (replace-match bul t t)
20477 (org-indent-line-to (+ start-ind (* delta bul-len)))
20478 ;; Ensure all text down to END (or SECTION-END) belongs
20479 ;; to the newly created item.
20480 (let ((section-end (save-excursion
20481 (or (outline-next-heading) (point)))))
20482 (forward-line)
20483 (funcall shift-text
20484 (+ start-ind (* (1+ delta) bul-len))
20485 (min end section-end)))))))
20486 ;; Case 3. Normal line with ARG: make the first line of region
20487 ;; an item, and shift indentation of others lines to
20488 ;; set them as item's body.
20489 (arg (let* ((bul (org-list-bullet-string "-"))
20490 (bul-len (length bul))
20491 (ref-ind (org-get-indentation)))
20492 (skip-chars-forward " \t")
20493 (insert bul)
20494 (forward-line)
20495 (while (< (point) end)
20496 ;; Ensure that lines less indented than first one
20497 ;; still get included in item body.
20498 (funcall shift-text
20499 (+ ref-ind bul-len)
20500 (min end (save-excursion (or (outline-next-heading)
20501 (point)))))
20502 (forward-line))))
20503 ;; Case 4. Normal line without ARG: turn each non-item line
20504 ;; into an item.
20506 (while (< (point) end)
20507 (unless (or (org-at-heading-p) (org-at-item-p))
20508 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20509 (replace-match
20510 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20511 (forward-line))))))))
20513 (defun org-toggle-heading (&optional nstars)
20514 "Convert headings to normal text, or items or text to headings.
20515 If there is no active region, only convert the current line.
20517 With a \\[universal-argument] prefix, convert the whole list at
20518 point into heading.
20520 In a region:
20522 - If the first non blank line is a headline, remove the stars
20523 from all headlines in the region.
20525 - If it is a normal line, turn each and every normal line (i.e.,
20526 not an heading or an item) in the region into headings. If you
20527 want to convert only the first line of this region, use one
20528 universal prefix argument.
20530 - If it is a plain list item, turn all plain list items into headings.
20532 When converting a line into a heading, the number of stars is chosen
20533 such that the lines become children of the current entry. However,
20534 when a numeric prefix argument is given, its value determines the
20535 number of stars to add."
20536 (interactive "P")
20537 (let ((skip-blanks
20538 (function
20539 ;; Return beginning of first non-blank line, starting from
20540 ;; line at POS.
20541 (lambda (pos)
20542 (save-excursion
20543 (goto-char pos)
20544 (while (org-at-comment-p) (forward-line))
20545 (skip-chars-forward " \r\t\n")
20546 (point-at-bol)))))
20547 beg end toggled)
20548 ;; Determine boundaries of changes. If a universal prefix has
20549 ;; been given, put the list in a region. If region ends at a bol,
20550 ;; do not consider the last line to be in the region.
20552 (when (and current-prefix-arg (org-at-item-p))
20553 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20554 (org-mark-element))
20556 (if (org-region-active-p)
20557 (setq beg (funcall skip-blanks (region-beginning))
20558 end (copy-marker (save-excursion
20559 (goto-char (region-end))
20560 (if (bolp) (point) (point-at-eol)))))
20561 (setq beg (funcall skip-blanks (point-at-bol))
20562 end (copy-marker (point-at-eol))))
20563 ;; Ensure inline tasks don't count as headings.
20564 (org-with-limited-levels
20565 (save-excursion
20566 (goto-char beg)
20567 (cond
20568 ;; Case 1. Started at an heading: de-star headings.
20569 ((org-at-heading-p)
20570 (while (< (point) end)
20571 (when (org-at-heading-p t)
20572 (looking-at org-outline-regexp) (replace-match "")
20573 (setq toggled t))
20574 (forward-line)))
20575 ;; Case 2. Started at an item: change items into headlines.
20576 ;; One star will be added by `org-list-to-subtree'.
20577 ((org-at-item-p)
20578 (let* ((stars (make-string
20579 ;; subtract the star that will be added again by
20580 ;; `org-list-to-subtree'
20581 (if (numberp nstars) (1- nstars)
20582 (or (org-current-level) 0))
20583 ?*))
20584 (add-stars
20585 (cond (nstars "") ; stars from prefix only
20586 ((equal stars "") "") ; before first heading
20587 (org-odd-levels-only "*") ; inside heading, odd
20588 (t "")))) ; inside heading, oddeven
20589 (while (< (point) end)
20590 (when (org-at-item-p)
20591 ;; Pay attention to cases when region ends before list.
20592 (let* ((struct (org-list-struct))
20593 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20594 (save-restriction
20595 (narrow-to-region (point) list-end)
20596 (insert
20597 (org-list-to-subtree
20598 (org-list-parse-list t)
20599 '(:istart (concat stars add-stars (funcall get-stars depth))
20600 :icount (concat stars add-stars (funcall get-stars depth)))))))
20601 (setq toggled t))
20602 (forward-line))))
20603 ;; Case 3. Started at normal text: make every line an heading,
20604 ;; skipping headlines and items.
20605 (t (let* ((stars
20606 (make-string
20607 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20608 (add-stars
20609 (cond (nstars "") ; stars from prefix only
20610 ((equal stars "") "*") ; before first heading
20611 (org-odd-levels-only "**") ; inside heading, odd
20612 (t "*"))) ; inside heading, oddeven
20613 (rpl (concat stars add-stars " "))
20614 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20615 (while (< (point) (if (equal nstars '(4)) lend end))
20616 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20617 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20618 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20619 (forward-line)))))))
20620 (unless toggled (message "Cannot toggle heading from here"))))
20622 (defun org-meta-return (&optional arg)
20623 "Insert a new heading or wrap a region in a table.
20624 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20625 See the individual commands for more information."
20626 (interactive "P")
20627 (org-check-before-invisible-edit 'insert)
20628 (cond
20629 ((run-hook-with-args-until-success 'org-metareturn-hook))
20630 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20631 (newline-and-indent))
20632 ((org-at-table-p)
20633 (call-interactively 'org-table-wrap-region))
20634 (t (call-interactively 'org-insert-heading))))
20636 ;;; Menu entries
20638 (defsubst org-in-subtree-not-table-p ()
20639 "Are we in a subtree and not in a table?"
20640 (and (not (org-before-first-heading-p))
20641 (not (org-at-table-p))))
20643 ;; Define the Org-mode menus
20644 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20645 '("Tbl"
20646 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20647 ["Next Field" org-cycle (org-at-table-p)]
20648 ["Previous Field" org-shifttab (org-at-table-p)]
20649 ["Next Row" org-return (org-at-table-p)]
20650 "--"
20651 ["Blank Field" org-table-blank-field (org-at-table-p)]
20652 ["Edit Field" org-table-edit-field (org-at-table-p)]
20653 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20654 "--"
20655 ("Column"
20656 ["Move Column Left" org-metaleft (org-at-table-p)]
20657 ["Move Column Right" org-metaright (org-at-table-p)]
20658 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20659 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20660 ("Row"
20661 ["Move Row Up" org-metaup (org-at-table-p)]
20662 ["Move Row Down" org-metadown (org-at-table-p)]
20663 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20664 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20665 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20666 "--"
20667 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20668 ("Rectangle"
20669 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20670 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20671 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20672 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20673 "--"
20674 ("Calculate"
20675 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20676 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20677 ["Edit Formulas" org-edit-special (org-at-table-p)]
20678 "--"
20679 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20680 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20681 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20682 "--"
20683 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20684 "--"
20685 ["Sum Column/Rectangle" org-table-sum
20686 (or (org-at-table-p) (org-region-active-p))]
20687 ["Which Column?" org-table-current-column (org-at-table-p)])
20688 ["Debug Formulas"
20689 org-table-toggle-formula-debugger
20690 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20691 ["Show Col/Row Numbers"
20692 org-table-toggle-coordinate-overlays
20693 :style toggle
20694 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20695 "--"
20696 ["Create" org-table-create (and (not (org-at-table-p))
20697 org-enable-table-editor)]
20698 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20699 ["Import from File" org-table-import (not (org-at-table-p))]
20700 ["Export to File" org-table-export (org-at-table-p)]
20701 "--"
20702 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20704 (easy-menu-define org-org-menu org-mode-map "Org menu"
20705 '("Org"
20706 ("Show/Hide"
20707 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20708 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20709 ["Sparse Tree..." org-sparse-tree t]
20710 ["Reveal Context" org-reveal t]
20711 ["Show All" show-all t]
20712 "--"
20713 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20714 "--"
20715 ["New Heading" org-insert-heading t]
20716 ("Navigate Headings"
20717 ["Up" outline-up-heading t]
20718 ["Next" outline-next-visible-heading t]
20719 ["Previous" outline-previous-visible-heading t]
20720 ["Next Same Level" outline-forward-same-level t]
20721 ["Previous Same Level" outline-backward-same-level t]
20722 "--"
20723 ["Jump" org-goto t])
20724 ("Edit Structure"
20725 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20726 "--"
20727 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20728 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20729 "--"
20730 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20731 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20732 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20733 "--"
20734 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20735 "--"
20736 ["Copy visible text" org-copy-visible t]
20737 "--"
20738 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20739 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20740 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20741 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20742 "--"
20743 ["Sort Region/Children" org-sort t]
20744 "--"
20745 ["Convert to odd levels" org-convert-to-odd-levels t]
20746 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20747 ("Editing"
20748 ["Emphasis..." org-emphasize t]
20749 ["Edit Source Example" org-edit-special t]
20750 "--"
20751 ["Footnote new/jump" org-footnote-action t]
20752 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20753 ("Archive"
20754 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20755 "--"
20756 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20757 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20758 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20760 "--"
20761 ("Hyperlinks"
20762 ["Store Link (Global)" org-store-link t]
20763 ["Find existing link to here" org-occur-link-in-agenda-files t]
20764 ["Insert Link" org-insert-link t]
20765 ["Follow Link" org-open-at-point t]
20766 "--"
20767 ["Next link" org-next-link t]
20768 ["Previous link" org-previous-link t]
20769 "--"
20770 ["Descriptive Links"
20771 org-toggle-link-display
20772 :style radio
20773 :selected org-descriptive-links
20775 ["Literal Links"
20776 org-toggle-link-display
20777 :style radio
20778 :selected (not org-descriptive-links)])
20779 "--"
20780 ("TODO Lists"
20781 ["TODO/DONE/-" org-todo t]
20782 ("Select keyword"
20783 ["Next keyword" org-shiftright (org-at-heading-p)]
20784 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20785 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20786 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20787 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20788 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20789 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20790 "--"
20791 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20792 :selected org-enforce-todo-dependencies :style toggle :active t]
20793 "Settings for tree at point"
20794 ["Do Children sequentially" org-toggle-ordered-property :style radio
20795 :selected (org-entry-get nil "ORDERED")
20796 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20797 ["Do Children parallel" org-toggle-ordered-property :style radio
20798 :selected (not (org-entry-get nil "ORDERED"))
20799 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20800 "--"
20801 ["Set Priority" org-priority t]
20802 ["Priority Up" org-shiftup t]
20803 ["Priority Down" org-shiftdown t]
20804 "--"
20805 ["Get news from all feeds" org-feed-update-all t]
20806 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20807 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20808 ("TAGS and Properties"
20809 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20810 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20811 "--"
20812 ["Set property" org-set-property (not (org-before-first-heading-p))]
20813 ["Column view of properties" org-columns t]
20814 ["Insert Column View DBlock" org-insert-columns-dblock t])
20815 ("Dates and Scheduling"
20816 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20817 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20818 ("Change Date"
20819 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20820 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20821 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20822 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20823 ["Compute Time Range" org-evaluate-time-range t]
20824 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20825 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20826 "--"
20827 ["Custom time format" org-toggle-time-stamp-overlays
20828 :style radio :selected org-display-custom-times]
20829 "--"
20830 ["Goto Calendar" org-goto-calendar t]
20831 ["Date from Calendar" org-date-from-calendar t]
20832 "--"
20833 ["Start/Restart Timer" org-timer-start t]
20834 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20835 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20836 ["Insert Timer String" org-timer t]
20837 ["Insert Timer Item" org-timer-item t])
20838 ("Logging work"
20839 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20840 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20841 ["Clock out" org-clock-out t]
20842 ["Clock cancel" org-clock-cancel t]
20843 "--"
20844 ["Mark as default task" org-clock-mark-default-task t]
20845 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20846 ["Goto running clock" org-clock-goto t]
20847 "--"
20848 ["Display times" org-clock-display t]
20849 ["Create clock table" org-clock-report t]
20850 "--"
20851 ["Record DONE time"
20852 (progn (setq org-log-done (not org-log-done))
20853 (message "Switching to %s will %s record a timestamp"
20854 (car org-done-keywords)
20855 (if org-log-done "automatically" "not")))
20856 :style toggle :selected org-log-done])
20857 "--"
20858 ["Agenda Command..." org-agenda t]
20859 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20860 ("File List for Agenda")
20861 ("Special views current file"
20862 ["TODO Tree" org-show-todo-tree t]
20863 ["Check Deadlines" org-check-deadlines t]
20864 ["Timeline" org-timeline t]
20865 ["Tags/Property tree" org-match-sparse-tree t])
20866 "--"
20867 ["Export/Publish..." org-export-dispatch t]
20868 ("LaTeX"
20869 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20870 :selected org-cdlatex-mode]
20871 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20872 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20873 ["Modify math symbol" org-cdlatex-math-modify
20874 (org-inside-LaTeX-fragment-p)]
20875 ["Insert citation" org-reftex-citation t]
20876 "--"
20877 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20878 "--"
20879 ("MobileOrg"
20880 ["Push Files and Views" org-mobile-push t]
20881 ["Get Captured and Flagged" org-mobile-pull t]
20882 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20883 "--"
20884 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20885 "--"
20886 ("Documentation"
20887 ["Show Version" org-version t]
20888 ["Info Documentation" org-info t])
20889 ("Customize"
20890 ["Browse Org Group" org-customize t]
20891 "--"
20892 ["Expand This Menu" org-create-customize-menu
20893 (fboundp 'customize-menu-create)])
20894 ["Send bug report" org-submit-bug-report t]
20895 "--"
20896 ("Refresh/Reload"
20897 ["Refresh setup current buffer" org-mode-restart t]
20898 ["Reload Org (after update)" org-reload t]
20899 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20902 (defun org-info (&optional node)
20903 "Read documentation for Org-mode in the info system.
20904 With optional NODE, go directly to that node."
20905 (interactive)
20906 (info (format "(org)%s" (or node ""))))
20908 ;;;###autoload
20909 (defun org-submit-bug-report ()
20910 "Submit a bug report on Org-mode via mail.
20912 Don't hesitate to report any problems or inaccurate documentation.
20914 If you don't have setup sending mail from (X)Emacs, please copy the
20915 output buffer into your mail program, as it gives us important
20916 information about your Org-mode version and configuration."
20917 (interactive)
20918 (require 'reporter)
20919 (org-load-modules-maybe)
20920 (org-require-autoloaded-modules)
20921 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20922 (reporter-submit-bug-report
20923 "emacs-orgmode@gnu.org"
20924 (org-version nil 'full)
20925 (let (list)
20926 (save-window-excursion
20927 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20928 (delete-other-windows)
20929 (erase-buffer)
20930 (insert "You are about to submit a bug report to the Org-mode mailing list.
20932 We would like to add your full Org-mode and Outline configuration to the
20933 bug report. This greatly simplifies the work of the maintainer and
20934 other experts on the mailing list.
20936 HOWEVER, some variables you have customized may contain private
20937 information. The names of customers, colleagues, or friends, might
20938 appear in the form of file names, tags, todo states, or search strings.
20939 If you answer yes to the prompt, you might want to check and remove
20940 such private information before sending the email.")
20941 (add-text-properties (point-min) (point-max) '(face org-warning))
20942 (when (yes-or-no-p "Include your Org-mode configuration ")
20943 (mapatoms
20944 (lambda (v)
20945 (and (boundp v)
20946 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20947 (or (and (symbol-value v)
20948 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20949 (and
20950 (get v 'custom-type) (get v 'standard-value)
20951 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20952 (push v list)))))
20953 (kill-buffer (get-buffer "*Warn about privacy*"))
20954 list))
20955 nil nil
20956 "Remember to cover the basics, that is, what you expected to happen and
20957 what in fact did happen. You don't know how to make a good report? See
20959 http://orgmode.org/manual/Feedback.html#Feedback
20961 Your bug report will be posted to the Org-mode mailing list.
20962 ------------------------------------------------------------------------")
20963 (save-excursion
20964 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20965 (replace-match "\\1Bug: \\3 [\\2]")))))
20968 (defun org-install-agenda-files-menu ()
20969 (let ((bl (buffer-list)))
20970 (save-excursion
20971 (while bl
20972 (set-buffer (pop bl))
20973 (if (derived-mode-p 'org-mode) (setq bl nil)))
20974 (when (derived-mode-p 'org-mode)
20975 (easy-menu-change
20976 '("Org") "File List for Agenda"
20977 (append
20978 (list
20979 ["Edit File List" (org-edit-agenda-file-list) t]
20980 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20981 ["Remove Current File from List" org-remove-file t]
20982 ["Cycle through agenda files" org-cycle-agenda-files t]
20983 ["Occur in all agenda files" org-occur-in-agenda-files t]
20984 "--")
20985 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20987 ;;;; Documentation
20989 (defun org-require-autoloaded-modules ()
20990 (interactive)
20991 (mapc 'require
20992 '(org-agenda org-archive org-attach org-clock org-colview org-id
20993 org-remember org-table org-timer)))
20995 ;;;###autoload
20996 (defun org-reload (&optional uncompiled)
20997 "Reload all org lisp files.
20998 With prefix arg UNCOMPILED, load the uncompiled versions."
20999 (interactive "P")
21000 (require 'loadhist)
21001 (let* ((org-dir (org-find-library-dir "org"))
21002 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21003 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21004 (remove-re (mapconcat 'identity
21005 (mapcar (lambda (f) (concat "^" f "$"))
21006 (list (if (featurep 'xemacs)
21007 "org-colview"
21008 "org-colview-xemacs")
21009 "org" "org-loaddefs" "org-version"))
21010 "\\|"))
21011 (feats (delete-dups
21012 (mapcar 'file-name-sans-extension
21013 (mapcar 'file-name-nondirectory
21014 (delq nil
21015 (mapcar 'feature-file
21016 features))))))
21017 (lfeat (append
21018 (sort
21019 (setq feats
21020 (delq nil (mapcar
21021 (lambda (f)
21022 (if (and (string-match feature-re f)
21023 (not (string-match remove-re f)))
21024 f nil))
21025 feats)))
21026 'string-lessp)
21027 (list "org-version" "org")))
21028 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21029 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21030 load-uncore load-misses)
21031 (setq load-misses
21032 (delq 't
21033 (mapcar (lambda (f)
21034 (or (org-load-noerror-mustsuffix (concat org-dir f))
21035 (and (string= org-dir contrib-dir)
21036 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21037 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21038 (add-to-list 'load-uncore f 'append)
21041 lfeat)))
21042 (if load-uncore
21043 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21044 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21045 (if load-misses
21046 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21047 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21048 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21050 ;;;###autoload
21051 (defun org-customize ()
21052 "Call the customize function with org as argument."
21053 (interactive)
21054 (org-load-modules-maybe)
21055 (org-require-autoloaded-modules)
21056 (customize-browse 'org))
21058 (defun org-create-customize-menu ()
21059 "Create a full customization menu for Org-mode, insert it into the menu."
21060 (interactive)
21061 (org-load-modules-maybe)
21062 (org-require-autoloaded-modules)
21063 (if (fboundp 'customize-menu-create)
21064 (progn
21065 (easy-menu-change
21066 '("Org") "Customize"
21067 `(["Browse Org group" org-customize t]
21068 "--"
21069 ,(customize-menu-create 'org)
21070 ["Set" Custom-set t]
21071 ["Save" Custom-save t]
21072 ["Reset to Current" Custom-reset-current t]
21073 ["Reset to Saved" Custom-reset-saved t]
21074 ["Reset to Standard Settings" Custom-reset-standard t]))
21075 (message "\"Org\"-menu now contains full customization menu"))
21076 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21078 ;;;; Miscellaneous stuff
21080 ;;; Generally useful functions
21082 (defun org-get-at-bol (property)
21083 "Get text property PROPERTY at beginning of line."
21084 (get-text-property (point-at-bol) property))
21086 (defun org-find-text-property-in-string (prop s)
21087 "Return the first non-nil value of property PROP in string S."
21088 (or (get-text-property 0 prop s)
21089 (get-text-property (or (next-single-property-change 0 prop s) 0)
21090 prop s)))
21092 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21093 "Display the given MESSAGE as a warning."
21094 (if (fboundp 'display-warning)
21095 (display-warning 'org message
21096 (if (featurep 'xemacs) 'warning :warning))
21097 (let ((buf (get-buffer-create "*Org warnings*")))
21098 (with-current-buffer buf
21099 (goto-char (point-max))
21100 (insert "Warning (Org): " message)
21101 (unless (bolp)
21102 (newline)))
21103 (display-buffer buf)
21104 (sit-for 0))))
21106 (defun org-eval (form)
21107 "Eval FORM and return result."
21108 (condition-case error
21109 (eval form)
21110 (error (format "%%![Error: %s]" error))))
21112 (defun org-in-clocktable-p ()
21113 "Check if the cursor is in a clocktable."
21114 (let ((pos (point)) start)
21115 (save-excursion
21116 (end-of-line 1)
21117 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21118 (setq start (match-beginning 0))
21119 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21120 (>= (match-end 0) pos)
21121 start))))
21123 (defun org-in-commented-line ()
21124 "Is point in a line starting with `#'?"
21125 (equal (char-after (point-at-bol)) ?#))
21127 (defun org-in-indented-comment-line ()
21128 "Is point in a line starting with `#' after some white space?"
21129 (save-excursion
21130 (save-match-data
21131 (goto-char (point-at-bol))
21132 (looking-at "[ \t]*#"))))
21134 (defun org-in-verbatim-emphasis ()
21135 (save-match-data
21136 (and (org-in-regexp org-emph-re 2)
21137 (>= (point) (match-beginning 3))
21138 (<= (point) (match-end 4))
21139 (member (match-string 3) '("=" "~")))))
21141 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21142 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21143 (if (and marker (marker-buffer marker)
21144 (buffer-live-p (marker-buffer marker)))
21145 (progn
21146 (org-pop-to-buffer-same-window (marker-buffer marker))
21147 (if (or (> marker (point-max)) (< marker (point-min)))
21148 (widen))
21149 (goto-char marker)
21150 (org-show-context 'org-goto))
21151 (if bookmark
21152 (bookmark-jump bookmark)
21153 (error "Cannot find location"))))
21155 (defun org-quote-csv-field (s)
21156 "Quote field for inclusion in CSV material."
21157 (if (string-match "[\",]" s)
21158 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21161 (defun org-force-self-insert (N)
21162 "Needed to enforce self-insert under remapping."
21163 (interactive "p")
21164 (self-insert-command N))
21166 (defun org-string-width (s)
21167 "Compute width of string, ignoring invisible characters.
21168 This ignores character with invisibility property `org-link', and also
21169 characters with property `org-cwidth', because these will become invisible
21170 upon the next fontification round."
21171 (let (b l)
21172 (when (or (eq t buffer-invisibility-spec)
21173 (assq 'org-link buffer-invisibility-spec))
21174 (while (setq b (text-property-any 0 (length s)
21175 'invisible 'org-link s))
21176 (setq s (concat (substring s 0 b)
21177 (substring s (or (next-single-property-change
21178 b 'invisible s) (length s)))))))
21179 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21180 (setq s (concat (substring s 0 b)
21181 (substring s (or (next-single-property-change
21182 b 'org-cwidth s) (length s))))))
21183 (setq l (string-width s) b -1)
21184 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21185 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21188 (defun org-shorten-string (s maxlength)
21189 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21190 If the string is shorter or has length MAXLENGTH, just return the
21191 original string. If it is longer, the functions finds a space in the
21192 string, breaks this string off at that locations and adds three dots
21193 as ellipsis. Including the ellipsis, the string will not be longer
21194 than MAXLENGTH. If finding a good breaking point in the string does
21195 not work, the string is just chopped off in the middle of a word
21196 if necessary."
21197 (if (<= (length s) maxlength)
21199 (let* ((n (max (- maxlength 4) 1))
21200 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21201 (if (string-match re s)
21202 (concat (match-string 1 s) "...")
21203 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21205 (defun org-get-indentation (&optional line)
21206 "Get the indentation of the current line, interpreting tabs.
21207 When LINE is given, assume it represents a line and compute its indentation."
21208 (if line
21209 (if (string-match "^ *" (org-remove-tabs line))
21210 (match-end 0))
21211 (save-excursion
21212 (beginning-of-line 1)
21213 (skip-chars-forward " \t")
21214 (current-column))))
21216 (defun org-get-string-indentation (s)
21217 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21218 (let ((n -1) (i 0) (w tab-width) c)
21219 (catch 'exit
21220 (while (< (setq n (1+ n)) (length s))
21221 (setq c (aref s n))
21222 (cond ((= c ?\ ) (setq i (1+ i)))
21223 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21224 (t (throw 'exit t)))))
21227 (defun org-remove-tabs (s &optional width)
21228 "Replace tabulators in S with spaces.
21229 Assumes that s is a single line, starting in column 0."
21230 (setq width (or width tab-width))
21231 (while (string-match "\t" s)
21232 (setq s (replace-match
21233 (make-string
21234 (- (* width (/ (+ (match-beginning 0) width) width))
21235 (match-beginning 0)) ?\ )
21236 t t s)))
21239 (defun org-fix-indentation (line ind)
21240 "Fix indentation in LINE.
21241 IND is a cons cell with target and minimum indentation.
21242 If the current indentation in LINE is smaller than the minimum,
21243 leave it alone. If it is larger than ind, set it to the target."
21244 (let* ((l (org-remove-tabs line))
21245 (i (org-get-indentation l))
21246 (i1 (car ind)) (i2 (cdr ind)))
21247 (if (>= i i2) (setq l (substring line i2)))
21248 (if (> i1 0)
21249 (concat (make-string i1 ?\ ) l)
21250 l)))
21252 (defun org-remove-indentation (code &optional n)
21253 "Remove the maximum common indentation from the lines in CODE.
21254 N may optionally be the number of spaces to remove."
21255 (with-temp-buffer
21256 (insert code)
21257 (org-do-remove-indentation n)
21258 (buffer-string)))
21260 (defun org-do-remove-indentation (&optional n)
21261 "Remove the maximum common indentation from the buffer."
21262 (untabify (point-min) (point-max))
21263 (let ((min 10000) re)
21264 (if n
21265 (setq min n)
21266 (goto-char (point-min))
21267 (while (re-search-forward "^ *[^ \n]" nil t)
21268 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21269 (unless (or (= min 0) (= min 10000))
21270 (setq re (format "^ \\{%d\\}" min))
21271 (goto-char (point-min))
21272 (while (re-search-forward re nil t)
21273 (replace-match "")
21274 (end-of-line 1))
21275 min)))
21277 (defun org-fill-template (template alist)
21278 "Find each %key of ALIST in TEMPLATE and replace it."
21279 (let ((case-fold-search nil)
21280 entry key value)
21281 (setq alist (sort (copy-sequence alist)
21282 (lambda (a b) (< (length (car a)) (length (car b))))))
21283 (while (setq entry (pop alist))
21284 (setq template
21285 (replace-regexp-in-string
21286 (concat "%" (regexp-quote (car entry)))
21287 (or (cdr entry) "") template t t)))
21288 template))
21290 (defun org-base-buffer (buffer)
21291 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21292 (if (not buffer)
21293 buffer
21294 (or (buffer-base-buffer buffer)
21295 buffer)))
21297 (defun org-trim (s)
21298 "Remove whitespace at beginning and end of string."
21299 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21300 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21303 (defun org-wrap (string &optional width lines)
21304 "Wrap string to either a number of lines, or a width in characters.
21305 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21306 that costs. If there is a word longer than WIDTH, the text is actually
21307 wrapped to the length of that word.
21308 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21309 many lines, whatever width that takes.
21310 The return value is a list of lines, without newlines at the end."
21311 (let* ((words (org-split-string string "[ \t\n]+"))
21312 (maxword (apply 'max (mapcar 'org-string-width words)))
21313 w ll)
21314 (cond (width
21315 (org-do-wrap words (max maxword width)))
21316 (lines
21317 (setq w maxword)
21318 (setq ll (org-do-wrap words maxword))
21319 (if (<= (length ll) lines)
21321 (setq ll words)
21322 (while (> (length ll) lines)
21323 (setq w (1+ w))
21324 (setq ll (org-do-wrap words w)))
21325 ll))
21326 (t (error "Cannot wrap this")))))
21328 (defun org-do-wrap (words width)
21329 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21330 (let (lines line)
21331 (while words
21332 (setq line (pop words))
21333 (while (and words (< (+ (length line) (length (car words))) width))
21334 (setq line (concat line " " (pop words))))
21335 (setq lines (push line lines)))
21336 (nreverse lines)))
21338 (defun org-split-string (string &optional separators)
21339 "Splits STRING into substrings at SEPARATORS.
21340 No empty strings are returned if there are matches at the beginning
21341 and end of string."
21342 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21343 (start 0)
21344 notfirst
21345 (list nil))
21346 (while (and (string-match rexp string
21347 (if (and notfirst
21348 (= start (match-beginning 0))
21349 (< start (length string)))
21350 (1+ start) start))
21351 (< (match-beginning 0) (length string)))
21352 (setq notfirst t)
21353 (or (eq (match-beginning 0) 0)
21354 (and (eq (match-beginning 0) (match-end 0))
21355 (eq (match-beginning 0) start))
21356 (setq list
21357 (cons (substring string start (match-beginning 0))
21358 list)))
21359 (setq start (match-end 0)))
21360 (or (eq start (length string))
21361 (setq list
21362 (cons (substring string start)
21363 list)))
21364 (nreverse list)))
21366 (defun org-quote-vert (s)
21367 "Replace \"|\" with \"\\vert\"."
21368 (while (string-match "|" s)
21369 (setq s (replace-match "\\vert" t t s)))
21372 (defun org-uuidgen-p (s)
21373 "Is S an ID created by UUIDGEN?"
21374 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21376 (defun org-in-src-block-p (&optional inside)
21377 "Whether point is in a code source block.
21378 When INSIDE is non-nil, don't consider we are within a src block
21379 when point is at #+BEGIN_SRC or #+END_SRC."
21380 (let ((case-fold-search t) ov)
21381 (or (and (setq ov (overlays-at (point)))
21382 (memq 'org-block-background
21383 (overlay-properties (car ov))))
21384 (and (not inside)
21385 (save-match-data
21386 (save-excursion
21387 (beginning-of-line)
21388 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21390 (defun org-context ()
21391 "Return a list of contexts of the current cursor position.
21392 If several contexts apply, all are returned.
21393 Each context entry is a list with a symbol naming the context, and
21394 two positions indicating start and end of the context. Possible
21395 contexts are:
21397 :headline anywhere in a headline
21398 :headline-stars on the leading stars in a headline
21399 :todo-keyword on a TODO keyword (including DONE) in a headline
21400 :tags on the TAGS in a headline
21401 :priority on the priority cookie in a headline
21402 :item on the first line of a plain list item
21403 :item-bullet on the bullet/number of a plain list item
21404 :checkbox on the checkbox in a plain list item
21405 :table in an org-mode table
21406 :table-special on a special filed in a table
21407 :table-table in a table.el table
21408 :clocktable in a clocktable
21409 :src-block in a source block
21410 :link on a hyperlink
21411 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21412 :target on a <<target>>
21413 :radio-target on a <<<radio-target>>>
21414 :latex-fragment on a LaTeX fragment
21415 :latex-preview on a LaTeX fragment with overlaid preview image
21417 This function expects the position to be visible because it uses font-lock
21418 faces as a help to recognize the following contexts: :table-special, :link,
21419 and :keyword."
21420 (let* ((f (get-text-property (point) 'face))
21421 (faces (if (listp f) f (list f)))
21422 (case-fold-search t)
21423 (p (point)) clist o)
21424 ;; First the large context
21425 (cond
21426 ((org-at-heading-p t)
21427 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21428 (when (progn
21429 (beginning-of-line 1)
21430 (looking-at org-todo-line-tags-regexp))
21431 (push (org-point-in-group p 1 :headline-stars) clist)
21432 (push (org-point-in-group p 2 :todo-keyword) clist)
21433 (push (org-point-in-group p 4 :tags) clist))
21434 (goto-char p)
21435 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21436 (if (looking-at "\\[#[A-Z0-9]\\]")
21437 (push (org-point-in-group p 0 :priority) clist)))
21439 ((org-at-item-p)
21440 (push (org-point-in-group p 2 :item-bullet) clist)
21441 (push (list :item (point-at-bol)
21442 (save-excursion (org-end-of-item) (point)))
21443 clist)
21444 (and (org-at-item-checkbox-p)
21445 (push (org-point-in-group p 0 :checkbox) clist)))
21447 ((org-at-table-p)
21448 (push (list :table (org-table-begin) (org-table-end)) clist)
21449 (if (memq 'org-formula faces)
21450 (push (list :table-special
21451 (previous-single-property-change p 'face)
21452 (next-single-property-change p 'face)) clist)))
21453 ((org-at-table-p 'any)
21454 (push (list :table-table) clist)))
21455 (goto-char p)
21457 (let ((case-fold-search t))
21458 ;; New the "medium" contexts: clocktables, source blocks
21459 (cond ((org-in-clocktable-p)
21460 (push (list :clocktable
21461 (and (or (looking-at "#\\+BEGIN: clocktable")
21462 (search-backward "#+BEGIN: clocktable" nil t))
21463 (match-beginning 0))
21464 (and (re-search-forward "#\\+END:?" nil t)
21465 (match-end 0))) clist))
21466 ((org-in-src-block-p)
21467 (push (list :src-block
21468 (and (or (looking-at "#\\+BEGIN_SRC")
21469 (search-backward "#+BEGIN_SRC" nil t))
21470 (match-beginning 0))
21471 (and (search-forward "#+END_SRC" nil t)
21472 (match-beginning 0))) clist))))
21473 (goto-char p)
21475 ;; Now the small context
21476 (cond
21477 ((org-at-timestamp-p)
21478 (push (org-point-in-group p 0 :timestamp) clist))
21479 ((memq 'org-link faces)
21480 (push (list :link
21481 (previous-single-property-change p 'face)
21482 (next-single-property-change p 'face)) clist))
21483 ((memq 'org-special-keyword faces)
21484 (push (list :keyword
21485 (previous-single-property-change p 'face)
21486 (next-single-property-change p 'face)) clist))
21487 ((org-at-target-p)
21488 (push (org-point-in-group p 0 :target) clist)
21489 (goto-char (1- (match-beginning 0)))
21490 (if (looking-at org-radio-target-regexp)
21491 (push (org-point-in-group p 0 :radio-target) clist))
21492 (goto-char p))
21493 ((setq o (car (delq nil
21494 (mapcar
21495 (lambda (x)
21496 (if (memq x org-latex-fragment-image-overlays) x))
21497 (overlays-at (point))))))
21498 (push (list :latex-fragment
21499 (overlay-start o) (overlay-end o)) clist)
21500 (push (list :latex-preview
21501 (overlay-start o) (overlay-end o)) clist))
21502 ((org-inside-LaTeX-fragment-p)
21503 ;; FIXME: positions wrong.
21504 (push (list :latex-fragment (point) (point)) clist)))
21506 (setq clist (nreverse (delq nil clist)))
21507 clist))
21509 ;; FIXME: Compare with at-regexp-p Do we need both?
21510 (defun org-in-regexp (re &optional nlines visually)
21511 "Check if point is inside a match of regexp.
21512 Normally only the current line is checked, but you can include NLINES extra
21513 lines both before and after point into the search.
21514 If VISUALLY is set, require that the cursor is not after the match but
21515 really on, so that the block visually is on the match."
21516 (catch 'exit
21517 (let ((pos (point))
21518 (eol (point-at-eol (+ 1 (or nlines 0))))
21519 (inc (if visually 1 0)))
21520 (save-excursion
21521 (beginning-of-line (- 1 (or nlines 0)))
21522 (while (re-search-forward re eol t)
21523 (if (and (<= (match-beginning 0) pos)
21524 (>= (+ inc (match-end 0)) pos))
21525 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21527 (defun org-at-regexp-p (regexp)
21528 "Is point inside a match of REGEXP in the current line?"
21529 (catch 'exit
21530 (save-excursion
21531 (let ((pos (point)) (end (point-at-eol)))
21532 (beginning-of-line 1)
21533 (while (re-search-forward regexp end t)
21534 (if (and (<= (match-beginning 0) pos)
21535 (>= (match-end 0) pos))
21536 (throw 'exit t)))
21537 nil))))
21539 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21540 "Non-nil when point is between matches of START-RE and END-RE.
21542 Also return a non-nil value when point is on one of the matches.
21544 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21545 buffer positions. Default values are the positions of headlines
21546 surrounding the point.
21548 The functions returns a cons cell whose car (resp. cdr) is the
21549 position before START-RE (resp. after END-RE)."
21550 (save-match-data
21551 (let ((pos (point))
21552 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21553 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21554 beg end)
21555 (save-excursion
21556 ;; Point is on a block when on START-RE or if START-RE can be
21557 ;; found before it...
21558 (and (or (org-at-regexp-p start-re)
21559 (re-search-backward start-re limit-up t))
21560 (setq beg (match-beginning 0))
21561 ;; ... and END-RE after it...
21562 (goto-char (match-end 0))
21563 (re-search-forward end-re limit-down t)
21564 (> (setq end (match-end 0)) pos)
21565 ;; ... without another START-RE in-between.
21566 (goto-char (match-beginning 0))
21567 (not (re-search-backward start-re (1+ beg) t))
21568 ;; Return value.
21569 (cons beg end))))))
21571 (defun org-in-block-p (names)
21572 "Non-nil when point belongs to a block whose name belongs to NAMES.
21574 NAMES is a list of strings containing names of blocks.
21576 Return first block name matched, or nil. Beware that in case of
21577 nested blocks, the returned name may not belong to the closest
21578 block from point."
21579 (save-match-data
21580 (catch 'exit
21581 (let ((case-fold-search t)
21582 (lim-up (save-excursion (outline-previous-heading)))
21583 (lim-down (save-excursion (outline-next-heading))))
21584 (mapc (lambda (name)
21585 (let ((n (regexp-quote name)))
21586 (when (org-between-regexps-p
21587 (concat "^[ \t]*#\\+begin_" n)
21588 (concat "^[ \t]*#\\+end_" n)
21589 lim-up lim-down)
21590 (throw 'exit n))))
21591 names))
21592 nil)))
21594 (defun org-in-drawer-p ()
21595 "Is point within a drawer?"
21596 (save-match-data
21597 (let ((case-fold-search t)
21598 (lim-up (save-excursion (outline-previous-heading)))
21599 (lim-down (save-excursion (outline-next-heading))))
21600 (org-between-regexps-p
21601 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21602 "^[ \t]*:end:.*$"
21603 lim-up lim-down))))
21605 (defun org-occur-in-agenda-files (regexp &optional nlines)
21606 "Call `multi-occur' with buffers for all agenda files."
21607 (interactive "sOrg-files matching: \np")
21608 (let* ((files (org-agenda-files))
21609 (tnames (mapcar 'file-truename files))
21610 (extra org-agenda-text-search-extra-files)
21612 (when (eq (car extra) 'agenda-archives)
21613 (setq extra (cdr extra))
21614 (setq files (org-add-archive-files files)))
21615 (while (setq f (pop extra))
21616 (unless (member (file-truename f) tnames)
21617 (add-to-list 'files f 'append)
21618 (add-to-list 'tnames (file-truename f) 'append)))
21619 (multi-occur
21620 (mapcar (lambda (x)
21621 (with-current-buffer
21622 (or (get-file-buffer x) (find-file-noselect x))
21623 (widen)
21624 (current-buffer)))
21625 files)
21626 regexp)))
21628 (if (boundp 'occur-mode-find-occurrence-hook)
21629 ;; Emacs 23
21630 (add-hook 'occur-mode-find-occurrence-hook
21631 (lambda ()
21632 (when (derived-mode-p 'org-mode)
21633 (org-reveal))))
21634 ;; Emacs 22
21635 (defadvice occur-mode-goto-occurrence
21636 (after org-occur-reveal activate)
21637 (and (derived-mode-p 'org-mode) (org-reveal)))
21638 (defadvice occur-mode-goto-occurrence-other-window
21639 (after org-occur-reveal activate)
21640 (and (derived-mode-p 'org-mode) (org-reveal)))
21641 (defadvice occur-mode-display-occurrence
21642 (after org-occur-reveal activate)
21643 (when (derived-mode-p 'org-mode)
21644 (let ((pos (occur-mode-find-occurrence)))
21645 (with-current-buffer (marker-buffer pos)
21646 (save-excursion
21647 (goto-char pos)
21648 (org-reveal)))))))
21650 (defun org-occur-link-in-agenda-files ()
21651 "Create a link and search for it in the agendas.
21652 The link is not stored in `org-stored-links', it is just created
21653 for the search purpose."
21654 (interactive)
21655 (let ((link (condition-case nil
21656 (org-store-link nil)
21657 (error "Unable to create a link to here"))))
21658 (org-occur-in-agenda-files (regexp-quote link))))
21660 (defun org-reverse-string (string)
21661 "Return the reverse of STRING."
21662 (apply 'string (reverse (string-to-list string))))
21664 (defsubst org-uniquify (list)
21665 "Non-destructively remove duplicate elements from LIST."
21666 (let ((res (copy-sequence list))) (delete-dups res)))
21668 (defun org-uniquify-alist (alist)
21669 "Merge elements of ALIST with the same key.
21671 For example, in this alist:
21673 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21674 => '((a 1 3) (b 2))
21676 merge (a 1) and (a 3) into (a 1 3).
21678 The function returns the new ALIST."
21679 (let (rtn)
21680 (mapc
21681 (lambda (e)
21682 (let (n)
21683 (if (not (assoc (car e) rtn))
21684 (push e rtn)
21685 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21686 (setq rtn (assq-delete-all (car e) rtn))
21687 (push n rtn))))
21688 alist)
21689 rtn))
21691 (defun org-delete-all (elts list)
21692 "Remove all elements in ELTS from LIST."
21693 (while elts
21694 (setq list (delete (pop elts) list)))
21695 list)
21697 (defun org-count (cl-item cl-seq)
21698 "Count the number of occurrences of ITEM in SEQ.
21699 Taken from `count' in cl-seq.el with all keyword arguments removed."
21700 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21701 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21702 (while (< cl-start cl-end)
21703 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21704 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21705 (setq cl-start (1+ cl-start)))
21706 cl-count))
21708 (defun org-remove-if (predicate seq)
21709 "Remove everything from SEQ that fulfills PREDICATE."
21710 (let (res e)
21711 (while seq
21712 (setq e (pop seq))
21713 (if (not (funcall predicate e)) (push e res)))
21714 (nreverse res)))
21716 (defun org-remove-if-not (predicate seq)
21717 "Remove everything from SEQ that does not fulfill PREDICATE."
21718 (let (res e)
21719 (while seq
21720 (setq e (pop seq))
21721 (if (funcall predicate e) (push e res)))
21722 (nreverse res)))
21724 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21725 "Reduce two-argument FUNCTION across SEQ.
21726 Taken from `reduce' in cl-seq.el with all keyword arguments but
21727 \":initial-value\" removed."
21728 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21729 (cadr (memq :initial-value cl-keys)))
21730 (cl-seq (pop cl-seq))
21731 (t (funcall cl-func)))))
21732 (while cl-seq
21733 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21734 cl-accum))
21736 (defun org-back-over-empty-lines ()
21737 "Move backwards over whitespace, to the beginning of the first empty line.
21738 Returns the number of empty lines passed."
21739 (let ((pos (point)))
21740 (if (cdr (assoc 'heading org-blank-before-new-entry))
21741 (skip-chars-backward " \t\n\r")
21742 (unless (eobp)
21743 (forward-line -1)))
21744 (beginning-of-line 2)
21745 (goto-char (min (point) pos))
21746 (count-lines (point) pos)))
21748 (defun org-skip-whitespace ()
21749 (skip-chars-forward " \t\n\r"))
21751 (defun org-point-in-group (point group &optional context)
21752 "Check if POINT is in match-group GROUP.
21753 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21754 match. If the match group does not exist or point is not inside it,
21755 return nil."
21756 (and (match-beginning group)
21757 (>= point (match-beginning group))
21758 (<= point (match-end group))
21759 (if context
21760 (list context (match-beginning group) (match-end group))
21761 t)))
21763 (defun org-switch-to-buffer-other-window (&rest args)
21764 "Switch to buffer in a second window on the current frame.
21765 In particular, do not allow pop-up frames.
21766 Returns the newly created buffer."
21767 (org-no-popups
21768 (apply 'switch-to-buffer-other-window args)))
21770 (defun org-combine-plists (&rest plists)
21771 "Create a single property list from all plists in PLISTS.
21772 The process starts by copying the first list, and then setting properties
21773 from the other lists. Settings in the last list are the most significant
21774 ones and overrule settings in the other lists."
21775 (let ((rtn (copy-sequence (pop plists)))
21776 p v ls)
21777 (while plists
21778 (setq ls (pop plists))
21779 (while ls
21780 (setq p (pop ls) v (pop ls))
21781 (setq rtn (plist-put rtn p v))))
21782 rtn))
21784 (defun org-replace-escapes (string table)
21785 "Replace %-escapes in STRING with values in TABLE.
21786 TABLE is an association list with keys like \"%a\" and string values.
21787 The sequences in STRING may contain normal field width and padding information,
21788 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21789 so values can contain further %-escapes if they are define later in TABLE."
21790 (let ((tbl (copy-alist table))
21791 (case-fold-search nil)
21792 (pchg 0)
21793 e re rpl)
21794 (while (setq e (pop tbl))
21795 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21796 (when (and (cdr e) (string-match re (cdr e)))
21797 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21798 (safe "SREF"))
21799 (add-text-properties 0 3 (list 'sref sref) safe)
21800 (setcdr e (replace-match safe t t (cdr e)))))
21801 (while (string-match re string)
21802 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21803 (cdr e)))
21804 (setq string (replace-match rpl t t string))))
21805 (while (setq pchg (next-property-change pchg string))
21806 (let ((sref (get-text-property pchg 'sref string)))
21807 (when (and sref (string-match "SREF" string pchg))
21808 (setq string (replace-match sref t t string)))))
21809 string))
21811 (defun org-sublist (list start end)
21812 "Return a section of LIST, from START to END.
21813 Counting starts at 1."
21814 (let (rtn (c start))
21815 (setq list (nthcdr (1- start) list))
21816 (while (and list (<= c end))
21817 (push (pop list) rtn)
21818 (setq c (1+ c)))
21819 (nreverse rtn)))
21821 (defun org-find-base-buffer-visiting (file)
21822 "Like `find-buffer-visiting' but always return the base buffer and
21823 not an indirect buffer."
21824 (let ((buf (or (get-file-buffer file)
21825 (find-buffer-visiting file))))
21826 (if buf
21827 (or (buffer-base-buffer buf) buf)
21828 nil)))
21830 (defun org-image-file-name-regexp (&optional extensions)
21831 "Return regexp matching the file names of images.
21832 If EXTENSIONS is given, only match these."
21833 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21834 (image-file-name-regexp)
21835 (let ((image-file-name-extensions
21836 (or extensions
21837 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21838 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21839 (concat "\\."
21840 (regexp-opt (nconc (mapcar 'upcase
21841 image-file-name-extensions)
21842 image-file-name-extensions)
21844 "\\'"))))
21846 (defun org-file-image-p (file &optional extensions)
21847 "Return non-nil if FILE is an image."
21848 (save-match-data
21849 (string-match (org-image-file-name-regexp extensions) file)))
21851 (defun org-get-cursor-date (&optional with-time)
21852 "Return the date at cursor in as a time.
21853 This works in the calendar and in the agenda, anywhere else it just
21854 returns the current time.
21855 If WITH-TIME is non-nil, returns the time of the event at point (in
21856 the agenda) or the current time of the day."
21857 (let (date day defd tp tm hod mod)
21858 (when with-time
21859 (setq tp (get-text-property (point) 'time))
21860 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21861 (setq hod (string-to-number (match-string 1 tp))
21862 mod (string-to-number (match-string 2 tp))))
21863 (or tp (setq hod (nth 2 (decode-time (current-time)))
21864 mod (nth 1 (decode-time (current-time))))))
21865 (cond
21866 ((eq major-mode 'calendar-mode)
21867 (setq date (calendar-cursor-to-date)
21868 defd (encode-time 0 (or mod 0) (or hod 0)
21869 (nth 1 date) (nth 0 date) (nth 2 date))))
21870 ((eq major-mode 'org-agenda-mode)
21871 (setq day (get-text-property (point) 'day))
21872 (if day
21873 (setq date (calendar-gregorian-from-absolute day)
21874 defd (encode-time 0 (or mod 0) (or hod 0)
21875 (nth 1 date) (nth 0 date) (nth 2 date))))))
21876 (or defd (current-time))))
21878 (defun org-mark-subtree (&optional up)
21879 "Mark the current subtree.
21880 This puts point at the start of the current subtree, and mark at
21881 the end. If a numeric prefix UP is given, move up into the
21882 hierarchy of headlines by UP levels before marking the subtree."
21883 (interactive "P")
21884 (org-with-limited-levels
21885 (cond ((org-at-heading-p) (beginning-of-line))
21886 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21887 (t (outline-previous-visible-heading 1))))
21888 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21889 (if (org-called-interactively-p 'any)
21890 (call-interactively 'org-mark-element)
21891 (org-mark-element)))
21894 ;;; Indentation
21896 (defun org-indent-line ()
21897 "Indent line depending on context."
21898 (interactive)
21899 (let* ((pos (point))
21900 (itemp (org-at-item-p))
21901 (case-fold-search t)
21902 (org-drawer-regexp (or org-drawer-regexp "\000"))
21903 (inline-task-p (and (featurep 'org-inlinetask)
21904 (org-inlinetask-in-task-p)))
21905 (inline-re (and inline-task-p
21906 (org-inlinetask-outline-regexp)))
21907 column)
21908 (if (and orgstruct-is-++ (eq pos (point)))
21909 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21910 (indent-according-to-mode))
21911 (beginning-of-line 1)
21912 (cond
21913 ;; Headings
21914 ((looking-at org-outline-regexp) (setq column 0))
21915 ;; Footnote definition
21916 ((looking-at org-footnote-definition-re) (setq column 0))
21917 ;; Literal examples
21918 ((looking-at "[ \t]*:\\( \\|$\\)")
21919 (setq column (org-get-indentation))) ; do nothing
21920 ;; Lists
21921 ((ignore-errors (goto-char (org-in-item-p)))
21922 (setq column (if itemp
21923 (org-get-indentation)
21924 (org-list-item-body-column (point))))
21925 (goto-char pos))
21926 ;; Drawers
21927 ((and (looking-at "[ \t]*:END:")
21928 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21929 (save-excursion
21930 (goto-char (1- (match-beginning 1)))
21931 (setq column (current-column))))
21932 ;; Special blocks
21933 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21934 (save-excursion
21935 (re-search-backward
21936 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21937 (setq column (org-get-indentation (match-string 0))))
21938 ((and (not (looking-at "[ \t]*#\\+begin_"))
21939 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21940 (save-excursion
21941 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21942 (setq column
21943 (cond ((equal (downcase (match-string 1)) "src")
21944 ;; src blocks: let `org-edit-src-exit' handle them
21945 (org-get-indentation))
21946 ((equal (downcase (match-string 1)) "example")
21947 (max (org-get-indentation)
21948 (org-get-indentation (match-string 0))))
21950 (org-get-indentation (match-string 0))))))
21951 ;; This line has nothing special, look at the previous relevant
21952 ;; line to compute indentation
21954 (beginning-of-line 0)
21955 (while (and (not (bobp))
21956 (not (looking-at org-table-line-regexp))
21957 (not (looking-at org-drawer-regexp))
21958 ;; When point started in an inline task, do not move
21959 ;; above task starting line.
21960 (not (and inline-task-p (looking-at inline-re)))
21961 ;; Skip drawers, blocks, empty lines, verbatim,
21962 ;; comments, tables, footnotes definitions, lists,
21963 ;; inline tasks.
21964 (or (and (looking-at "[ \t]*:END:")
21965 (re-search-backward org-drawer-regexp nil t))
21966 (and (looking-at "[ \t]*#\\+end_")
21967 (re-search-backward "[ \t]*#\\+begin_"nil t))
21968 (looking-at "[ \t]*[\n:#|]")
21969 (looking-at org-footnote-definition-re)
21970 (and (not inline-task-p)
21971 (featurep 'org-inlinetask)
21972 (org-inlinetask-in-task-p)
21973 (or (org-inlinetask-goto-beginning) t))))
21974 (beginning-of-line 0))
21975 (cond
21976 ;; There was a list item above.
21977 ((save-excursion
21978 (and (ignore-errors (goto-char (org-in-item-p)))
21979 (goto-char
21980 (org-list-get-top-point (org-list-struct)))))
21981 (looking-at org-list-full-item-re)
21982 (setq column (length (match-string 0))))
21983 ;; There was an heading above.
21984 ((looking-at "\\*+[ \t]+")
21985 (if (not org-adapt-indentation)
21986 (setq column 0)
21987 (goto-char (match-end 0))
21988 (setq column (current-column))))
21989 ;; A drawer had started and is unfinished
21990 ((looking-at org-drawer-regexp)
21991 (goto-char (1- (match-beginning 1)))
21992 (setq column (current-column)))
21993 ;; Else, nothing noticeable found: get indentation and go on.
21994 (t (setq column (org-get-indentation))))))
21995 ;; Now apply indentation and move cursor accordingly
21996 (goto-char pos)
21997 (if (<= (current-column) (current-indentation))
21998 (org-indent-line-to column)
21999 (save-excursion (org-indent-line-to column)))
22000 ;; Special polishing for properties, see `org-property-format'
22001 (setq column (current-column))
22002 (beginning-of-line 1)
22003 (if (looking-at
22004 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
22005 (replace-match (concat (match-string 1)
22006 (format org-property-format
22007 (match-string 2) (match-string 3)))
22008 t t))
22009 (org-move-to-column column))))
22011 (defun org-indent-drawer ()
22012 "Indent the drawer at point."
22013 (interactive)
22014 (let ((p (point))
22015 (e (and (save-excursion (re-search-forward ":END:" nil t))
22016 (match-end 0)))
22017 (folded
22018 (save-excursion
22019 (end-of-line)
22020 (when (overlays-at (point))
22021 (member 'invisible (overlay-properties
22022 (car (overlays-at (point)))))))))
22023 (when folded (org-cycle))
22024 (indent-for-tab-command)
22025 (while (and (move-beginning-of-line 2) (< (point) e))
22026 (indent-for-tab-command))
22027 (goto-char p)
22028 (when folded (org-cycle)))
22029 (message "Drawer at point indented"))
22031 (defun org-indent-block ()
22032 "Indent the block at point."
22033 (interactive)
22034 (let ((p (point))
22035 (case-fold-search t)
22036 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22037 (match-end 0)))
22038 (folded
22039 (save-excursion
22040 (end-of-line)
22041 (when (overlays-at (point))
22042 (member 'invisible (overlay-properties
22043 (car (overlays-at (point)))))))))
22044 (when folded (org-cycle))
22045 (indent-for-tab-command)
22046 (while (and (move-beginning-of-line 2) (< (point) e))
22047 (indent-for-tab-command))
22048 (goto-char p)
22049 (when folded (org-cycle)))
22050 (message "Block at point indented"))
22052 (defun org-indent-region (start end)
22053 "Indent region."
22054 (interactive "r")
22055 (save-excursion
22056 (let ((line-end (org-current-line end)))
22057 (goto-char start)
22058 (while (< (org-current-line) line-end)
22059 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22060 (t (call-interactively 'org-indent-line)))
22061 (move-beginning-of-line 2)))))
22064 ;;; Filling
22066 ;; We use our own fill-paragraph and auto-fill functions.
22068 ;; `org-fill-paragraph' relies on adaptive filling and context
22069 ;; checking. Appropriate `fill-prefix' is computed with
22070 ;; `org-adaptive-fill-function'.
22072 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22073 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22074 ;; `org-adaptive-fill-function' value. Internally,
22075 ;; `org-comment-line-break-function' breaks the line.
22077 ;; `org-setup-filling' installs filling and auto-filling related
22078 ;; variables during `org-mode' initialization.
22080 (defun org-setup-filling ()
22081 (interactive)
22082 ;; Prevent auto-fill from inserting unwanted new items.
22083 (when (boundp 'fill-nobreak-predicate)
22084 (org-set-local
22085 'fill-nobreak-predicate
22086 (org-uniquify
22087 (append fill-nobreak-predicate
22088 '(org-fill-paragraph-separate-nobreak-p
22089 org-fill-line-break-nobreak-p
22090 org-fill-paragraph-with-timestamp-nobreak-p)))))
22091 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22092 (org-set-local 'auto-fill-inhibit-regexp nil)
22093 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22094 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22095 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22097 (defvar org-element-paragraph-separate) ; org-element.el
22098 (defun org-fill-paragraph-separate-nobreak-p ()
22099 "Non-nil when a new line at point would end current paragraph."
22100 (looking-at (substring org-element-paragraph-separate 1)))
22102 (defun org-fill-line-break-nobreak-p ()
22103 "Non-nil when a new line at point would create an Org line break."
22104 (save-excursion
22105 (skip-chars-backward "[ \t]")
22106 (skip-chars-backward "\\\\")
22107 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22109 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22110 "Non-nil when a new line at point would split a timestamp."
22111 (and (org-at-timestamp-p t)
22112 (not (looking-at org-ts-regexp-both))))
22114 (declare-function message-in-body-p "message" ())
22115 (defvar orgtbl-line-start-regexp) ; From org-table.el
22116 (defun org-adaptive-fill-function ()
22117 "Compute a fill prefix for the current line.
22118 Return fill prefix, as a string, or nil if current line isn't
22119 meant to be filled."
22120 (let (prefix)
22121 (catch 'exit
22122 (when (derived-mode-p 'message-mode)
22123 (save-excursion
22124 (beginning-of-line)
22125 (cond ((or (not (message-in-body-p))
22126 (looking-at orgtbl-line-start-regexp))
22127 (throw 'exit nil))
22128 ((looking-at message-cite-prefix-regexp)
22129 (throw 'exit (match-string-no-properties 0)))
22130 ((looking-at org-outline-regexp)
22131 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22132 (org-with-wide-buffer
22133 (let* ((p (line-beginning-position))
22134 (element (save-excursion
22135 (beginning-of-line)
22136 (or (ignore-errors (org-element-at-point))
22137 (user-error "An element cannot be parsed line %d"
22138 (line-number-at-pos (point))))))
22139 (type (org-element-type element))
22140 (post-affiliated (org-element-property :post-affiliated element)))
22141 (unless (and post-affiliated (< p post-affiliated))
22142 (case type
22143 (comment (looking-at "[ \t]*# ?") (match-string 0))
22144 (footnote-definition "")
22145 ((item plain-list)
22146 (make-string (org-list-item-body-column
22147 (or post-affiliated
22148 (org-element-property :begin element)))
22149 ? ))
22150 (paragraph
22151 ;; Fill prefix is usually the same as the current line,
22152 ;; except if the paragraph is at the beginning of an item.
22153 (let ((parent (org-element-property :parent element)))
22154 (cond ((eq (org-element-type parent) 'item)
22155 (make-string (org-list-item-body-column
22156 (org-element-property :begin parent))
22157 ? ))
22158 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22159 (match-string 0))
22160 (t ""))))
22161 (comment-block
22162 ;; Only fill contents if P is within block boundaries.
22163 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22164 (forward-line)
22165 (point)))
22166 (cend (save-excursion
22167 (goto-char (org-element-property :end element))
22168 (skip-chars-backward " \r\t\n")
22169 (line-beginning-position))))
22170 (when (and (>= p cbeg) (< p cend))
22171 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22172 (match-string 0)
22173 "")))))))))))
22175 (declare-function message-goto-body "message" ())
22176 (defvar message-cite-prefix-regexp) ; From message.el
22177 (defun org-fill-paragraph (&optional justify)
22178 "Fill element at point, when applicable.
22180 This function only applies to comment blocks, comments, example
22181 blocks and paragraphs. Also, as a special case, re-align table
22182 when point is at one.
22184 If JUSTIFY is non-nil (interactively, with prefix argument),
22185 justify as well. If `sentence-end-double-space' is non-nil, then
22186 period followed by one space does not end a sentence, so don't
22187 break a line there. The variable `fill-column' controls the
22188 width for filling.
22190 For convenience, when point is at a plain list, an item or
22191 a footnote definition, try to fill the first paragraph within."
22192 (interactive)
22193 (if (and (derived-mode-p 'message-mode)
22194 (or (not (message-in-body-p))
22195 (save-excursion (move-beginning-of-line 1)
22196 (looking-at message-cite-prefix-regexp))))
22197 ;; First ensure filling is correct in message-mode.
22198 (let ((fill-paragraph-function
22199 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22200 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22201 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22202 (paragraph-separate
22203 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22204 (fill-paragraph nil))
22205 (with-syntax-table org-mode-transpose-word-syntax-table
22206 ;; Move to end of line in order to get the first paragraph
22207 ;; within a plain list or a footnote definition.
22208 (let ((element (save-excursion
22209 (end-of-line)
22210 (or (ignore-errors (org-element-at-point))
22211 (user-error "An element cannot be parsed line %d"
22212 (line-number-at-pos (point)))))))
22213 ;; First check if point is in a blank line at the beginning of
22214 ;; the buffer. In that case, ignore filling.
22215 (case (org-element-type element)
22216 ;; Use major mode filling function is src blocks.
22217 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22218 ;; Align Org tables, leave table.el tables as-is.
22219 (table-row (org-table-align) t)
22220 (table
22221 (when (eq (org-element-property :type element) 'org)
22222 (save-excursion
22223 (goto-char (org-element-property :post-affiliated element))
22224 (org-table-align)))
22226 (paragraph
22227 ;; Paragraphs may contain `line-break' type objects.
22228 (let ((beg (max (point-min)
22229 (org-element-property :contents-begin element)))
22230 (end (min (point-max)
22231 (org-element-property :contents-end element))))
22232 ;; Do nothing if point is at an affiliated keyword.
22233 (if (< (line-end-position) beg) t
22234 (when (derived-mode-p 'message-mode)
22235 ;; In `message-mode', do not fill following citation
22236 ;; in current paragraph nor text before message body.
22237 (let ((body-start (save-excursion (message-goto-body))))
22238 (when body-start (setq beg (max body-start beg))))
22239 (when (save-excursion
22240 (re-search-forward
22241 (concat "^" message-cite-prefix-regexp) end t))
22242 (setq end (match-beginning 0))))
22243 ;; Fill paragraph, taking line breaks into account.
22244 ;; For that, slice the paragraph using line breaks as
22245 ;; separators, and fill the parts in reverse order to
22246 ;; avoid messing with markers.
22247 (save-excursion
22248 (goto-char end)
22249 (mapc
22250 (lambda (pos)
22251 (fill-region-as-paragraph pos (point) justify)
22252 (goto-char pos))
22253 ;; Find the list of ending positions for line breaks
22254 ;; in the current paragraph. Add paragraph
22255 ;; beginning to include first slice.
22256 (nreverse
22257 (cons beg
22258 (org-element-map
22259 (org-element--parse-objects
22260 beg end nil (org-element-restriction 'paragraph))
22261 'line-break
22262 (lambda (lb) (org-element-property :end lb)))))))
22263 t)))
22264 ;; Contents of `comment-block' type elements should be
22265 ;; filled as plain text, but only if point is within block
22266 ;; markers.
22267 (comment-block
22268 (let* ((case-fold-search t)
22269 (beg (save-excursion
22270 (goto-char (org-element-property :begin element))
22271 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22272 (forward-line)
22273 (point)))
22274 (end (save-excursion
22275 (goto-char (org-element-property :end element))
22276 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22277 (line-beginning-position))))
22278 (if (or (< (point) beg) (> (point) end)) t
22279 (fill-region-as-paragraph
22280 (save-excursion (end-of-line)
22281 (re-search-backward "^[ \t]*$" beg 'move)
22282 (line-beginning-position))
22283 (save-excursion (beginning-of-line)
22284 (re-search-forward "^[ \t]*$" end 'move)
22285 (line-beginning-position))
22286 justify))))
22287 ;; Fill comments.
22288 (comment
22289 (let ((begin (org-element-property :post-affiliated element))
22290 (end (org-element-property :end element)))
22291 (when (and (>= (point) begin) (<= (point) end))
22292 (let ((begin (save-excursion
22293 (end-of-line)
22294 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22295 (progn (forward-line) (point))
22296 begin)))
22297 (end (save-excursion
22298 (end-of-line)
22299 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22300 (1- (line-beginning-position))
22301 (skip-chars-backward " \r\t\n")
22302 (line-end-position)))))
22303 ;; Do not fill comments when at a blank line or at
22304 ;; affiliated keywords.
22305 (let ((fill-prefix (save-excursion
22306 (beginning-of-line)
22307 (looking-at "[ \t]*#")
22308 (concat (match-string 0) " "))))
22309 (when (> end begin)
22310 (save-excursion
22311 (fill-region-as-paragraph begin end justify))))))
22313 ;; Ignore every other element.
22314 (otherwise t))))))
22316 (defun org-auto-fill-function ()
22317 "Auto-fill function."
22318 ;; Check if auto-filling is meaningful.
22319 (let ((fc (current-fill-column)))
22320 (when (and fc (> (current-column) fc))
22321 (let* ((fill-prefix (org-adaptive-fill-function))
22322 ;; Enforce empty fill prefix, if required. Otherwise, it
22323 ;; will be computed again.
22324 (adaptive-fill-mode (not (equal fill-prefix ""))))
22325 (when fill-prefix (do-auto-fill))))))
22327 (defun org-comment-line-break-function (&optional soft)
22328 "Break line at point and indent, continuing comment if within one.
22329 The inserted newline is marked hard if variable
22330 `use-hard-newlines' is true, unless optional argument SOFT is
22331 non-nil."
22332 (if soft (insert-and-inherit ?\n) (newline 1))
22333 (save-excursion (forward-char -1) (delete-horizontal-space))
22334 (delete-horizontal-space)
22335 (indent-to-left-margin)
22336 (insert-before-markers-and-inherit fill-prefix))
22339 ;;; Comments
22341 ;; Org comments syntax is quite complex. It requires the entire line
22342 ;; to be just a comment. Also, even with the right syntax at the
22343 ;; beginning of line, some some elements (i.e. verse-block or
22344 ;; example-block) don't accept comments. Usual Emacs comment commands
22345 ;; cannot cope with those requirements. Therefore, Org replaces them.
22347 ;; Org still relies on `comment-dwim', but cannot trust
22348 ;; `comment-only-p'. So, `comment-region-function' and
22349 ;; `uncomment-region-function' both point
22350 ;; to`org-comment-or-uncomment-region'. Eventually,
22351 ;; `org-insert-comment' takes care of insertion of comments at the
22352 ;; beginning of line.
22354 ;; `org-setup-comments-handling' install comments related variables
22355 ;; during `org-mode' initialization.
22357 (defun org-setup-comments-handling ()
22358 (interactive)
22359 (org-set-local 'comment-use-syntax nil)
22360 (org-set-local 'comment-start "# ")
22361 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22362 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22363 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22364 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22366 (defun org-insert-comment ()
22367 "Insert an empty comment above current line.
22368 If the line is empty, insert comment at its beginning."
22369 (beginning-of-line)
22370 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22371 (org-indent-line)
22372 (insert "# "))
22374 (defvar comment-empty-lines) ; From newcomment.el.
22375 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22376 "Comment or uncomment each non-blank line in the region.
22377 Uncomment each non-blank line between BEG and END if it only
22378 contains commented lines. Otherwise, comment them."
22379 (save-restriction
22380 ;; Restrict region
22381 (narrow-to-region (save-excursion (goto-char beg)
22382 (skip-chars-forward " \r\t\n" end)
22383 (line-beginning-position))
22384 (save-excursion (goto-char end)
22385 (skip-chars-backward " \r\t\n" beg)
22386 (line-end-position)))
22387 (let ((uncommentp
22388 ;; UNCOMMENTP is non-nil when every non blank line between
22389 ;; BEG and END is a comment.
22390 (save-excursion
22391 (goto-char (point-min))
22392 (while (and (not (eobp))
22393 (let ((element (org-element-at-point)))
22394 (and (eq (org-element-type element) 'comment)
22395 (goto-char (min (point-max)
22396 (org-element-property
22397 :end element)))))))
22398 (eobp))))
22399 (if uncommentp
22400 ;; Only blank lines and comments in region: uncomment it.
22401 (save-excursion
22402 (goto-char (point-min))
22403 (while (not (eobp))
22404 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22405 (replace-match "" nil nil nil 1))
22406 (forward-line)))
22407 ;; Comment each line in region.
22408 (let ((min-indent (point-max)))
22409 ;; First find the minimum indentation across all lines.
22410 (save-excursion
22411 (goto-char (point-min))
22412 (while (and (not (eobp)) (not (zerop min-indent)))
22413 (unless (looking-at "[ \t]*$")
22414 (setq min-indent (min min-indent (current-indentation))))
22415 (forward-line)))
22416 ;; Then loop over all lines.
22417 (save-excursion
22418 (goto-char (point-min))
22419 (while (not (eobp))
22420 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22421 ;; Don't get fooled by invisible text (e.g. link path)
22422 ;; when moving to column MIN-INDENT.
22423 (let ((buffer-invisibility-spec nil))
22424 (org-move-to-column min-indent t))
22425 (insert comment-start))
22426 (forward-line))))))))
22429 ;;; Planning
22431 ;; This section contains tools to operate on timestamp objects, as
22432 ;; returned by, e.g. `org-element-context'.
22434 (defun org-timestamp-has-time-p (timestamp)
22435 "Non-nil when TIMESTAMP has a time specified."
22436 (org-element-property :hour-start timestamp))
22438 (defun org-timestamp-format (timestamp format &optional end utc)
22439 "Format a TIMESTAMP element into a string.
22441 FORMAT is a format specifier to be passed to
22442 `format-time-string'.
22444 When optional argument END is non-nil, use end of date-range or
22445 time-range, if possible.
22447 When optional argument UTC is non-nil, time will be expressed as
22448 Universal Time."
22449 (format-time-string
22450 format
22451 (apply 'encode-time
22452 (cons 0
22453 (mapcar
22454 (lambda (prop) (or (org-element-property prop timestamp) 0))
22455 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22456 '(:minute-start :hour-start :day-start :month-start
22457 :year-start)))))
22458 utc))
22460 (defun org-timestamp-split-range (timestamp &optional end)
22461 "Extract a timestamp object from a date or time range.
22463 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22464 the end of the range. Otherwise, extract its start.
22466 Return a new timestamp object sharing the same parent as
22467 TIMESTAMP."
22468 (let ((type (org-element-property :type timestamp)))
22469 (if (memq type '(active inactive diary)) timestamp
22470 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22471 ;; Set new type.
22472 (org-element-put-property
22473 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22474 ;; Copy start properties over end properties if END is
22475 ;; non-nil. Otherwise, copy end properties over `start' ones.
22476 (let ((p-alist '((:minute-start . :minute-end)
22477 (:hour-start . :hour-end)
22478 (:day-start . :day-end)
22479 (:month-start . :month-end)
22480 (:year-start . :year-end))))
22481 (dolist (p-cell p-alist)
22482 (org-element-put-property
22483 split-ts
22484 (funcall (if end 'car 'cdr) p-cell)
22485 (org-element-property
22486 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22487 ;; Eventually refresh `:raw-value'.
22488 (org-element-put-property split-ts :raw-value nil)
22489 (org-element-put-property
22490 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22492 (defun org-timestamp-translate (timestamp &optional boundary)
22493 "Apply `org-translate-time' on a TIMESTAMP object.
22494 When optional argument BOUNDARY is non-nil, it is either the
22495 symbol `start' or `end'. In this case, only translate the
22496 starting or ending part of TIMESTAMP if it is a date or time
22497 range. Otherwise, translate both parts."
22498 (if (and (not boundary)
22499 (memq (org-element-property :type timestamp)
22500 '(active-range inactive-range)))
22501 (concat
22502 (org-translate-time
22503 (org-element-property :raw-value
22504 (org-timestamp-split-range timestamp)))
22505 "--"
22506 (org-translate-time
22507 (org-element-property :raw-value
22508 (org-timestamp-split-range timestamp t))))
22509 (org-translate-time
22510 (org-element-property
22511 :raw-value
22512 (if (not boundary) timestamp
22513 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22517 ;;; Other stuff.
22519 (defun org-toggle-fixed-width-section (arg)
22520 "Toggle the fixed-width export.
22521 If there is no active region, the QUOTE keyword at the current headline is
22522 inserted or removed. When present, it causes the text between this headline
22523 and the next to be exported as fixed-width text, and unmodified.
22524 If there is an active region, this command adds or removes a colon as the
22525 first character of this line. If the first character of a line is a colon,
22526 this line is also exported in fixed-width font."
22527 (interactive "P")
22528 (let* ((cc 0)
22529 (regionp (org-region-active-p))
22530 (beg (if regionp (region-beginning) (point)))
22531 (end (if regionp (region-end)))
22532 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22533 (case-fold-search nil)
22534 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22535 off)
22536 (if regionp
22537 (save-excursion
22538 (goto-char beg)
22539 (setq cc (current-column))
22540 (beginning-of-line 1)
22541 (setq off (looking-at re))
22542 (while (> nlines 0)
22543 (setq nlines (1- nlines))
22544 (beginning-of-line 1)
22545 (cond
22546 (arg
22547 (org-move-to-column cc t)
22548 (insert ": \n")
22549 (forward-line -1))
22550 ((and off (looking-at re))
22551 (replace-match "" t t nil 1))
22552 ((not off) (org-move-to-column cc t) (insert ": ")))
22553 (forward-line 1)))
22554 (save-excursion
22555 (org-back-to-heading)
22556 (cond
22557 ((looking-at (format org-heading-keyword-regexp-format
22558 org-quote-string))
22559 (goto-char (match-end 1))
22560 (looking-at (concat " +" org-quote-string))
22561 (replace-match "" t t)
22562 (when (eolp) (insert " ")))
22563 ((looking-at org-outline-regexp)
22564 (goto-char (match-end 0))
22565 (insert org-quote-string " ")))))))
22567 (defun org-reftex-citation ()
22568 "Use reftex-citation to insert a citation into the buffer.
22569 This looks for a line like
22571 #+BIBLIOGRAPHY: foo plain option:-d
22573 and derives from it that foo.bib is the bibliography file relevant
22574 for this document. It then installs the necessary environment for RefTeX
22575 to work in this buffer and calls `reftex-citation' to insert a citation
22576 into the buffer.
22578 Export of such citations to both LaTeX and HTML is handled by the contributed
22579 package org-exp-bibtex by Taru Karttunen."
22580 (interactive)
22581 (let ((reftex-docstruct-symbol 'rds)
22582 (reftex-cite-format "\\cite{%l}")
22583 rds bib)
22584 (save-excursion
22585 (save-restriction
22586 (widen)
22587 (let ((case-fold-search t)
22588 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22589 (if (not (save-excursion
22590 (or (re-search-forward re nil t)
22591 (re-search-backward re nil t))))
22592 (error "No bibliography defined in file")
22593 (setq bib (concat (match-string 1) ".bib")
22594 rds (list (list 'bib bib)))))))
22595 (call-interactively 'reftex-citation)))
22597 ;;;; Functions extending outline functionality
22599 (defun org-beginning-of-line (&optional arg)
22600 "Go to the beginning of the current line. If that is invisible, continue
22601 to a visible line beginning. This makes the function of C-a more intuitive.
22602 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22603 first attempt, and only move to after the tags when the cursor is already
22604 beyond the end of the headline."
22605 (interactive "P")
22606 (let ((pos (point))
22607 (special (if (consp org-special-ctrl-a/e)
22608 (car org-special-ctrl-a/e)
22609 org-special-ctrl-a/e))
22610 refpos)
22611 (if (org-bound-and-true-p visual-line-mode)
22612 (beginning-of-visual-line 1)
22613 (beginning-of-line 1))
22614 (if (and arg (fboundp 'move-beginning-of-line))
22615 (call-interactively 'move-beginning-of-line)
22616 (if (bobp)
22618 (backward-char 1)
22619 (if (org-truely-invisible-p)
22620 (while (and (not (bobp)) (org-truely-invisible-p))
22621 (backward-char 1)
22622 (beginning-of-line 1))
22623 (forward-char 1))))
22624 (when special
22625 (cond
22626 ((and (looking-at org-complex-heading-regexp)
22627 (= (char-after (match-end 1)) ?\ ))
22628 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22629 (point-at-eol)))
22630 (goto-char
22631 (if (eq special t)
22632 (cond ((> pos refpos) refpos)
22633 ((= pos (point)) refpos)
22634 (t (point)))
22635 (cond ((> pos (point)) (point))
22636 ((not (eq last-command this-command)) (point))
22637 (t refpos)))))
22638 ((org-at-item-p)
22639 ;; Being at an item and not looking at an the item means point
22640 ;; was previously moved to beginning of a visual line, which
22641 ;; doesn't contain the item. Therefore, do nothing special,
22642 ;; just stay here.
22643 (when (looking-at org-list-full-item-re)
22644 ;; Set special position at first white space character after
22645 ;; bullet, and check-box, if any.
22646 (let ((after-bullet
22647 (let ((box (match-end 3)))
22648 (if (not box) (match-end 1)
22649 (let ((after (char-after box)))
22650 (if (and after (= after ? )) (1+ box) box))))))
22651 ;; Special case: Move point to special position when
22652 ;; currently after it or at beginning of line.
22653 (if (eq special t)
22654 (when (or (> pos after-bullet) (= (point) pos))
22655 (goto-char after-bullet))
22656 ;; Reversed case: Move point to special position when
22657 ;; point was already at beginning of line and command is
22658 ;; repeated.
22659 (when (and (= (point) pos) (eq last-command this-command))
22660 (goto-char after-bullet))))))))
22661 (org-no-warnings
22662 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22664 (defun org-end-of-line (&optional arg)
22665 "Go to the end of the line.
22666 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22667 tags on the first attempt, and only move to after the tags when
22668 the cursor is already beyond the end of the headline."
22669 (interactive "P")
22670 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22671 org-special-ctrl-a/e))
22672 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22673 'end-of-visual-line)
22674 ((fboundp 'move-end-of-line) 'move-end-of-line)
22675 (t 'end-of-line))))
22676 (if (or (not special) arg) (call-interactively move-fun)
22677 (let* ((element (save-excursion (beginning-of-line)
22678 (org-element-at-point)))
22679 (type (org-element-type element)))
22680 (cond
22681 ((memq type '(headline inlinetask))
22682 (let ((pos (point)))
22683 (beginning-of-line 1)
22684 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22685 (if (eq special t)
22686 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22687 (goto-char (match-beginning 1))
22688 (goto-char (match-end 0)))
22689 (if (or (< pos (match-end 0))
22690 (not (eq this-command last-command)))
22691 (goto-char (match-end 0))
22692 (goto-char (match-beginning 1))))
22693 (call-interactively move-fun))))
22694 ((org-element-property :hiddenp element)
22695 ;; If element is hidden, `move-end-of-line' would put point
22696 ;; after it. Use `end-of-line' to stay on current line.
22697 (call-interactively 'end-of-line))
22698 (t (call-interactively move-fun)))))
22699 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22701 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22702 (define-key org-mode-map "\C-e" 'org-end-of-line)
22704 (defun org-backward-sentence (&optional arg)
22705 "Go to beginning of sentence, or beginning of table field.
22706 This will call `backward-sentence' or `org-table-beginning-of-field',
22707 depending on context."
22708 (interactive "P")
22709 (cond
22710 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22711 (t (call-interactively 'backward-sentence))))
22713 (defun org-forward-sentence (&optional arg)
22714 "Go to end of sentence, or end of table field.
22715 This will call `forward-sentence' or `org-table-end-of-field',
22716 depending on context."
22717 (interactive "P")
22718 (cond
22719 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22720 (t (call-interactively 'forward-sentence))))
22722 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22723 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22725 (defun org-kill-line (&optional arg)
22726 "Kill line, to tags or end of line."
22727 (interactive "P")
22728 (cond
22729 ((or (not org-special-ctrl-k)
22730 (bolp)
22731 (not (org-at-heading-p)))
22732 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22733 org-ctrl-k-protect-subtree)
22734 (if (or (eq org-ctrl-k-protect-subtree 'error)
22735 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22736 (user-error "C-k aborted as it would kill a hidden subtree")))
22737 (call-interactively
22738 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22739 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22740 (kill-region (point) (match-beginning 1))
22741 (org-set-tags nil t))
22742 (t (kill-region (point) (point-at-eol)))))
22744 (define-key org-mode-map "\C-k" 'org-kill-line)
22746 (defun org-yank (&optional arg)
22747 "Yank. If the kill is a subtree, treat it specially.
22748 This command will look at the current kill and check if is a single
22749 subtree, or a series of subtrees[1]. If it passes the test, and if the
22750 cursor is at the beginning of a line or after the stars of a currently
22751 empty headline, then the yank is handled specially. How exactly depends
22752 on the value of the following variables, both set by default.
22754 org-yank-folded-subtrees
22755 When set, the subtree(s) will be folded after insertion, but only
22756 if doing so would now swallow text after the yanked text.
22758 org-yank-adjusted-subtrees
22759 When set, the subtree will be promoted or demoted in order to
22760 fit into the local outline tree structure, which means that the level
22761 will be adjusted so that it becomes the smaller one of the two
22762 *visible* surrounding headings.
22764 Any prefix to this command will cause `yank' to be called directly with
22765 no special treatment. In particular, a simple \\[universal-argument] prefix \
22766 will just
22767 plainly yank the text as it is.
22769 \[1] The test checks if the first non-white line is a heading
22770 and if there are no other headings with fewer stars."
22771 (interactive "P")
22772 (org-yank-generic 'yank arg))
22774 (defun org-yank-generic (command arg)
22775 "Perform some yank-like command.
22777 This function implements the behavior described in the `org-yank'
22778 documentation. However, it has been generalized to work for any
22779 interactive command with similar behavior."
22781 ;; pretend to be command COMMAND
22782 (setq this-command command)
22784 (if arg
22785 (call-interactively command)
22787 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22788 (and (org-kill-is-subtree-p)
22789 (or (bolp)
22790 (and (looking-at "[ \t]*$")
22791 (string-match
22792 "\\`\\*+\\'"
22793 (buffer-substring (point-at-bol) (point)))))))
22794 swallowp)
22795 (cond
22796 ((and subtreep org-yank-folded-subtrees)
22797 (let ((beg (point))
22798 end)
22799 (if (and subtreep org-yank-adjusted-subtrees)
22800 (org-paste-subtree nil nil 'for-yank)
22801 (call-interactively command))
22803 (setq end (point))
22804 (goto-char beg)
22805 (when (and (bolp) subtreep
22806 (not (setq swallowp
22807 (org-yank-folding-would-swallow-text beg end))))
22808 (org-with-limited-levels
22809 (or (looking-at org-outline-regexp)
22810 (re-search-forward org-outline-regexp-bol end t))
22811 (while (and (< (point) end) (looking-at org-outline-regexp))
22812 (hide-subtree)
22813 (org-cycle-show-empty-lines 'folded)
22814 (condition-case nil
22815 (outline-forward-same-level 1)
22816 (error (goto-char end))))))
22817 (when swallowp
22818 (message
22819 "Inserted text not folded because that would swallow text"))
22821 (goto-char end)
22822 (skip-chars-forward " \t\n\r")
22823 (beginning-of-line 1)
22824 (push-mark beg 'nomsg)))
22825 ((and subtreep org-yank-adjusted-subtrees)
22826 (let ((beg (point-at-bol)))
22827 (org-paste-subtree nil nil 'for-yank)
22828 (push-mark beg 'nomsg)))
22830 (call-interactively command))))))
22832 (defun org-yank-folding-would-swallow-text (beg end)
22833 "Would hide-subtree at BEG swallow any text after END?"
22834 (let (level)
22835 (org-with-limited-levels
22836 (save-excursion
22837 (goto-char beg)
22838 (when (or (looking-at org-outline-regexp)
22839 (re-search-forward org-outline-regexp-bol end t))
22840 (setq level (org-outline-level)))
22841 (goto-char end)
22842 (skip-chars-forward " \t\r\n\v\f")
22843 (if (or (eobp)
22844 (and (bolp) (looking-at org-outline-regexp)
22845 (<= (org-outline-level) level)))
22846 nil ; Nothing would be swallowed
22847 t))))) ; something would swallow
22849 (define-key org-mode-map "\C-y" 'org-yank)
22851 (defun org-truely-invisible-p ()
22852 "Check if point is at a character currently not visible.
22853 This version does not only check the character property, but also
22854 `visible-mode'."
22855 ;; Early versions of noutline don't have `outline-invisible-p'.
22856 (if (org-bound-and-true-p visible-mode)
22858 (outline-invisible-p)))
22860 (defun org-invisible-p2 ()
22861 "Check if point is at a character currently not visible."
22862 (save-excursion
22863 (if (and (eolp) (not (bobp))) (backward-char 1))
22864 ;; Early versions of noutline don't have `outline-invisible-p'.
22865 (outline-invisible-p)))
22867 (defun org-back-to-heading (&optional invisible-ok)
22868 "Call `outline-back-to-heading', but provide a better error message."
22869 (condition-case nil
22870 (outline-back-to-heading invisible-ok)
22871 (error (error "Before first headline at position %d in buffer %s"
22872 (point) (current-buffer)))))
22874 (defun org-before-first-heading-p ()
22875 "Before first heading?"
22876 (save-excursion
22877 (end-of-line)
22878 (null (re-search-backward org-outline-regexp-bol nil t))))
22880 (defun org-at-heading-p (&optional ignored)
22881 (outline-on-heading-p t))
22882 ;; Compatibility alias with Org versions < 7.8.03
22883 (defalias 'org-on-heading-p 'org-at-heading-p)
22885 (defun org-at-comment-p nil
22886 "Is cursor in a line starting with a # character?"
22887 (save-excursion
22888 (beginning-of-line)
22889 (looking-at "^#")))
22891 (defun org-at-drawer-p nil
22892 "Is cursor at a drawer keyword?"
22893 (save-excursion
22894 (move-beginning-of-line 1)
22895 (looking-at org-drawer-regexp)))
22897 (defun org-at-block-p nil
22898 "Is cursor at a block keyword?"
22899 (save-excursion
22900 (move-beginning-of-line 1)
22901 (looking-at org-block-regexp)))
22903 (defun org-point-at-end-of-empty-headline ()
22904 "If point is at the end of an empty headline, return t, else nil.
22905 If the heading only contains a TODO keyword, it is still still considered
22906 empty."
22907 (and (looking-at "[ \t]*$")
22908 (when org-todo-line-regexp
22909 (save-excursion
22910 (beginning-of-line 1)
22911 (let ((case-fold-search nil))
22912 (looking-at org-todo-line-regexp)
22913 (string= (match-string 3) ""))))))
22915 (defun org-at-heading-or-item-p ()
22916 (or (org-at-heading-p) (org-at-item-p)))
22918 (defun org-at-target-p ()
22919 (or (org-in-regexp org-radio-target-regexp)
22920 (org-in-regexp org-target-regexp)))
22921 ;; Compatibility alias with Org versions < 7.8.03
22922 (defalias 'org-on-target-p 'org-at-target-p)
22924 (defun org-up-heading-all (arg)
22925 "Move to the heading line of which the present line is a subheading.
22926 This function considers both visible and invisible heading lines.
22927 With argument, move up ARG levels."
22928 (if (fboundp 'outline-up-heading-all)
22929 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22930 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22932 (defun org-up-heading-safe ()
22933 "Move to the heading line of which the present line is a subheading.
22934 This version will not throw an error. It will return the level of the
22935 headline found, or nil if no higher level is found.
22937 Also, this function will be a lot faster than `outline-up-heading',
22938 because it relies on stars being the outline starters. This can really
22939 make a significant difference in outlines with very many siblings."
22940 (let (start-level re)
22941 (org-back-to-heading t)
22942 (setq start-level (funcall outline-level))
22943 (if (equal start-level 1)
22945 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22946 (if (re-search-backward re nil t)
22947 (funcall outline-level)))))
22949 (defun org-first-sibling-p ()
22950 "Is this heading the first child of its parents?"
22951 (interactive)
22952 (let ((re org-outline-regexp-bol)
22953 level l)
22954 (unless (org-at-heading-p t)
22955 (user-error "Not at a heading"))
22956 (setq level (funcall outline-level))
22957 (save-excursion
22958 (if (not (re-search-backward re nil t))
22960 (setq l (funcall outline-level))
22961 (< l level)))))
22963 (defun org-goto-sibling (&optional previous)
22964 "Goto the next sibling, even if it is invisible.
22965 When PREVIOUS is set, go to the previous sibling instead. Returns t
22966 when a sibling was found. When none is found, return nil and don't
22967 move point."
22968 (let ((fun (if previous 're-search-backward 're-search-forward))
22969 (pos (point))
22970 (re org-outline-regexp-bol)
22971 level l)
22972 (when (condition-case nil (org-back-to-heading t) (error nil))
22973 (setq level (funcall outline-level))
22974 (catch 'exit
22975 (or previous (forward-char 1))
22976 (while (funcall fun re nil t)
22977 (setq l (funcall outline-level))
22978 (when (< l level) (goto-char pos) (throw 'exit nil))
22979 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22980 (goto-char pos)
22981 nil))))
22983 (defun org-show-siblings ()
22984 "Show all siblings of the current headline."
22985 (save-excursion
22986 (while (org-goto-sibling) (org-flag-heading nil)))
22987 (save-excursion
22988 (while (org-goto-sibling 'previous)
22989 (org-flag-heading nil))))
22991 (defun org-goto-first-child ()
22992 "Goto the first child, even if it is invisible.
22993 Return t when a child was found. Otherwise don't move point and
22994 return nil."
22995 (let (level (pos (point)) (re org-outline-regexp-bol))
22996 (when (condition-case nil (org-back-to-heading t) (error nil))
22997 (setq level (outline-level))
22998 (forward-char 1)
22999 (if (and (re-search-forward re nil t) (> (outline-level) level))
23000 (progn (goto-char (match-beginning 0)) t)
23001 (goto-char pos) nil))))
23003 (defun org-show-hidden-entry ()
23004 "Show an entry where even the heading is hidden."
23005 (save-excursion
23006 (org-show-entry)))
23008 (defun org-flag-heading (flag &optional entry)
23009 "Flag the current heading. FLAG non-nil means make invisible.
23010 When ENTRY is non-nil, show the entire entry."
23011 (save-excursion
23012 (org-back-to-heading t)
23013 ;; Check if we should show the entire entry
23014 (if entry
23015 (progn
23016 (org-show-entry)
23017 (save-excursion
23018 (and (outline-next-heading)
23019 (org-flag-heading nil))))
23020 (outline-flag-region (max (point-min) (1- (point)))
23021 (save-excursion (outline-end-of-heading) (point))
23022 flag))))
23024 (defun org-get-next-sibling ()
23025 "Move to next heading of the same level, and return point.
23026 If there is no such heading, return nil.
23027 This is like outline-next-sibling, but invisible headings are ok."
23028 (let ((level (funcall outline-level)))
23029 (outline-next-heading)
23030 (while (and (not (eobp)) (> (funcall outline-level) level))
23031 (outline-next-heading))
23032 (if (or (eobp) (< (funcall outline-level) level))
23034 (point))))
23036 (defun org-get-last-sibling ()
23037 "Move to previous heading of the same level, and return point.
23038 If there is no such heading, return nil."
23039 (let ((opoint (point))
23040 (level (funcall outline-level)))
23041 (outline-previous-heading)
23042 (when (and (/= (point) opoint) (outline-on-heading-p t))
23043 (while (and (> (funcall outline-level) level)
23044 (not (bobp)))
23045 (outline-previous-heading))
23046 (if (< (funcall outline-level) level)
23048 (point)))))
23050 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23051 "Goto to the end of a subtree."
23052 ;; This contains an exact copy of the original function, but it uses
23053 ;; `org-back-to-heading', to make it work also in invisible
23054 ;; trees. And is uses an invisible-ok argument.
23055 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23056 ;; Furthermore, when used inside Org, finding the end of a large subtree
23057 ;; with many children and grandchildren etc, this can be much faster
23058 ;; than the outline version.
23059 (org-back-to-heading invisible-ok)
23060 (let ((first t)
23061 (level (funcall outline-level)))
23062 (if (and (derived-mode-p 'org-mode) (< level 1000))
23063 ;; A true heading (not a plain list item), in Org-mode
23064 ;; This means we can easily find the end by looking
23065 ;; only for the right number of stars. Using a regexp to do
23066 ;; this is so much faster than using a Lisp loop.
23067 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23068 (forward-char 1)
23069 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23070 ;; something else, do it the slow way
23071 (while (and (not (eobp))
23072 (or first (> (funcall outline-level) level)))
23073 (setq first nil)
23074 (outline-next-heading)))
23075 (unless to-heading
23076 (if (memq (preceding-char) '(?\n ?\^M))
23077 (progn
23078 ;; Go to end of line before heading
23079 (forward-char -1)
23080 (if (memq (preceding-char) '(?\n ?\^M))
23081 ;; leave blank line before heading
23082 (forward-char -1))))))
23083 (point))
23085 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23086 "Use Org version in org-mode, for dramatic speed-up."
23087 (if (derived-mode-p 'org-mode)
23088 (progn
23089 (org-end-of-subtree nil t)
23090 (unless (eobp) (backward-char 1)))
23091 ad-do-it))
23093 (defun org-end-of-meta-data-and-drawers ()
23094 "Jump to the first text after meta data and drawers in the current entry.
23095 This will move over empty lines, lines with planning time stamps,
23096 clocking lines, and drawers."
23097 (org-back-to-heading t)
23098 (let ((end (save-excursion (outline-next-heading) (point)))
23099 (re (concat "\\(" org-drawer-regexp "\\)"
23100 "\\|" "[ \t]*" org-keyword-time-regexp)))
23101 (forward-line 1)
23102 (while (re-search-forward re end t)
23103 (if (not (match-end 1))
23104 ;; empty or planning line
23105 (forward-line 1)
23106 ;; a drawer, find the end
23107 (re-search-forward "^[ \t]*:END:" end 'move)
23108 (forward-line 1)))
23109 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23110 (point)))
23112 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23113 "Move forward to the ARG'th subheading at same level as this one.
23114 Stop at the first and last subheadings of a superior heading.
23115 Normally this only looks at visible headings, but when INVISIBLE-OK is
23116 non-nil it will also look at invisible ones."
23117 (interactive "p")
23118 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23119 (if (and arg (< arg 0))
23120 (goto-char (point-min))
23121 (outline-next-heading))
23122 (org-at-heading-p)
23123 (let ((level (- (match-end 0) (match-beginning 0) 1))
23124 (f (if (and arg (< arg 0))
23125 're-search-backward
23126 're-search-forward))
23127 (count (if arg (abs arg) 1))
23128 (result (point)))
23129 (while (and (prog1 (> count 0)
23130 (forward-char (if (and arg (< arg 0)) -1 1)))
23131 (funcall f org-outline-regexp-bol nil 'move))
23132 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23133 (cond ((< l level) (setq count 0))
23134 ((and (= l level)
23135 (or invisible-ok
23136 (progn
23137 (goto-char (line-beginning-position))
23138 (not (outline-invisible-p)))))
23139 (setq count (1- count))
23140 (when (eq l level)
23141 (setq result (point)))))))
23142 (goto-char result))
23143 (beginning-of-line 1)))
23145 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23146 "Move backward to the ARG'th subheading at same level as this one.
23147 Stop at the first and last subheadings of a superior heading."
23148 (interactive "p")
23149 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23151 (defun org-next-block (arg &optional backward block-regexp)
23152 "Jump to the next block.
23153 With a prefix argument ARG, jump forward ARG many source blocks.
23154 When BACKWARD is non-nil, jump to the previous block.
23155 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23156 (interactive "p")
23157 (let ((re (or block-regexp org-block-regexp))
23158 (re-search-fn (or (and backward 're-search-backward)
23159 're-search-forward)))
23160 (if (looking-at re) (forward-char 1))
23161 (condition-case nil
23162 (funcall re-search-fn re nil nil arg)
23163 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23164 (goto-char (match-beginning 0)) (org-show-context)))
23166 (defun org-previous-block (arg &optional block-regexp)
23167 "Jump to the previous block.
23168 With a prefix argument ARG, jump backward ARG many source blocks.
23169 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23170 (interactive "p")
23171 (org-next-block arg t block-regexp))
23173 (defun org-forward-element ()
23174 "Move forward by one element.
23175 Move to the next element at the same level, when possible."
23176 (interactive)
23177 (cond ((eobp) (user-error "Cannot move further down"))
23178 ((org-with-limited-levels (org-at-heading-p))
23179 (let ((origin (point)))
23180 (goto-char (org-end-of-subtree nil t))
23181 (unless (org-with-limited-levels (org-at-heading-p))
23182 (goto-char origin)
23183 (user-error "Cannot move further down"))))
23185 (let* ((elem (org-element-at-point))
23186 (end (org-element-property :end elem))
23187 (parent (org-element-property :parent elem)))
23188 (cond ((and parent (= (org-element-property :contents-end parent) end))
23189 (goto-char (org-element-property :end parent)))
23190 ((integer-or-marker-p end) (goto-char end))
23191 (t (message "No element at point")))))))
23193 (defun org-backward-element ()
23194 "Move backward by one element.
23195 Move to the previous element at the same level, when possible."
23196 (interactive)
23197 (cond ((bobp) (user-error "Cannot move further up"))
23198 ((org-with-limited-levels (org-at-heading-p))
23199 ;; At a headline, move to the previous one, if any, or stay
23200 ;; here.
23201 (let ((origin (point)))
23202 (org-with-limited-levels (org-backward-heading-same-level 1))
23203 ;; When current headline has no sibling above, move to its
23204 ;; parent.
23205 (when (= (point) origin)
23206 (or (org-with-limited-levels (org-up-heading-safe))
23207 (progn (goto-char origin)
23208 (user-error "Cannot move further up"))))))
23210 (let* ((trail (org-element-at-point 'keep-trail))
23211 (elem (car trail))
23212 (prev-elem (nth 1 trail))
23213 (beg (org-element-property :begin elem)))
23214 (cond
23215 ;; Move to beginning of current element if point isn't
23216 ;; there already.
23217 ((null beg) (message "No element at point"))
23218 ((/= (point) beg) (goto-char beg))
23219 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23220 ((org-before-first-heading-p) (goto-char (point-min)))
23221 (t (org-back-to-heading)))))))
23223 (defun org-up-element ()
23224 "Move to upper element."
23225 (interactive)
23226 (if (org-with-limited-levels (org-at-heading-p))
23227 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23228 (let* ((elem (org-element-at-point))
23229 (parent (org-element-property :parent elem)))
23230 (if parent (goto-char (org-element-property :begin parent))
23231 (if (org-with-limited-levels (org-before-first-heading-p))
23232 (user-error "No surrounding element")
23233 (org-with-limited-levels (org-back-to-heading)))))))
23235 (defvar org-element-greater-elements)
23236 (defun org-down-element ()
23237 "Move to inner element."
23238 (interactive)
23239 (let ((element (org-element-at-point)))
23240 (cond
23241 ((memq (org-element-type element) '(plain-list table))
23242 (goto-char (org-element-property :contents-begin element))
23243 (forward-char))
23244 ((memq (org-element-type element) org-element-greater-elements)
23245 ;; If contents are hidden, first disclose them.
23246 (when (org-element-property :hiddenp element) (org-cycle))
23247 (goto-char (or (org-element-property :contents-begin element)
23248 (user-error "No content for this element"))))
23249 (t (user-error "No inner element")))))
23251 (defun org-drag-element-backward ()
23252 "Move backward element at point."
23253 (interactive)
23254 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23255 (let* ((trail (org-element-at-point 'keep-trail))
23256 (elem (car trail))
23257 (prev-elem (nth 1 trail)))
23258 ;; Error out if no previous element or previous element is
23259 ;; a parent of the current one.
23260 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23261 (user-error "Cannot drag element backward")
23262 (let ((pos (point)))
23263 (org-element-swap-A-B prev-elem elem)
23264 (goto-char (+ (org-element-property :begin prev-elem)
23265 (- pos (org-element-property :begin elem)))))))))
23267 (defun org-drag-element-forward ()
23268 "Move forward element at point."
23269 (interactive)
23270 (let* ((pos (point))
23271 (elem (org-element-at-point)))
23272 (when (= (point-max) (org-element-property :end elem))
23273 (user-error "Cannot drag element forward"))
23274 (goto-char (org-element-property :end elem))
23275 (let ((next-elem (org-element-at-point)))
23276 (when (or (org-element-nested-p elem next-elem)
23277 (and (eq (org-element-type next-elem) 'headline)
23278 (not (eq (org-element-type elem) 'headline))))
23279 (goto-char pos)
23280 (user-error "Cannot drag element forward"))
23281 ;; Compute new position of point: it's shifted by NEXT-ELEM
23282 ;; body's length (without final blanks) and by the length of
23283 ;; blanks between ELEM and NEXT-ELEM.
23284 (let ((size-next (- (save-excursion
23285 (goto-char (org-element-property :end next-elem))
23286 (skip-chars-backward " \r\t\n")
23287 (forward-line)
23288 ;; Small correction if buffer doesn't end
23289 ;; with a newline character.
23290 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23291 (org-element-property :begin next-elem)))
23292 (size-blank (- (org-element-property :end elem)
23293 (save-excursion
23294 (goto-char (org-element-property :end elem))
23295 (skip-chars-backward " \r\t\n")
23296 (forward-line)
23297 (point)))))
23298 (org-element-swap-A-B elem next-elem)
23299 (goto-char (+ pos size-next size-blank))))))
23301 (defun org-drag-line-forward (arg)
23302 "Drag the line at point ARG lines forward."
23303 (interactive "p")
23304 (dotimes (n (abs arg))
23305 (let ((c (current-column)))
23306 (if (< 0 arg)
23307 (progn
23308 (beginning-of-line 2)
23309 (transpose-lines 1)
23310 (beginning-of-line 0))
23311 (transpose-lines 1)
23312 (beginning-of-line -1))
23313 (org-move-to-column c))))
23315 (defun org-drag-line-backward (arg)
23316 "Drag the line at point ARG lines backward."
23317 (interactive "p")
23318 (org-drag-line-forward (- arg)))
23320 (defun org-mark-element ()
23321 "Put point at beginning of this element, mark at end.
23323 Interactively, if this command is repeated or (in Transient Mark
23324 mode) if the mark is active, it marks the next element after the
23325 ones already marked."
23326 (interactive)
23327 (let (deactivate-mark)
23328 (if (and (org-called-interactively-p 'any)
23329 (or (and (eq last-command this-command) (mark t))
23330 (and transient-mark-mode mark-active)))
23331 (set-mark
23332 (save-excursion
23333 (goto-char (mark))
23334 (goto-char (org-element-property :end (org-element-at-point)))))
23335 (let ((element (org-element-at-point)))
23336 (end-of-line)
23337 (push-mark (org-element-property :end element) t t)
23338 (goto-char (org-element-property :begin element))))))
23340 (defun org-narrow-to-element ()
23341 "Narrow buffer to current element."
23342 (interactive)
23343 (let ((elem (org-element-at-point)))
23344 (cond
23345 ((eq (car elem) 'headline)
23346 (narrow-to-region
23347 (org-element-property :begin elem)
23348 (org-element-property :end elem)))
23349 ((memq (car elem) org-element-greater-elements)
23350 (narrow-to-region
23351 (org-element-property :contents-begin elem)
23352 (org-element-property :contents-end elem)))
23354 (narrow-to-region
23355 (org-element-property :begin elem)
23356 (org-element-property :end elem))))))
23358 (defun org-transpose-element ()
23359 "Transpose current and previous elements, keeping blank lines between.
23360 Point is moved after both elements."
23361 (interactive)
23362 (org-skip-whitespace)
23363 (let ((end (org-element-property :end (org-element-at-point))))
23364 (org-drag-element-backward)
23365 (goto-char end)))
23367 (defun org-unindent-buffer ()
23368 "Un-indent the visible part of the buffer.
23369 Relative indentation (between items, inside blocks, etc.) isn't
23370 modified."
23371 (interactive)
23372 (unless (eq major-mode 'org-mode)
23373 (user-error "Cannot un-indent a buffer not in Org mode"))
23374 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23375 unindent-tree ; For byte-compiler.
23376 (unindent-tree
23377 (function
23378 (lambda (contents)
23379 (mapc
23380 (lambda (element)
23381 (if (memq (org-element-type element) '(headline section))
23382 (funcall unindent-tree (org-element-contents element))
23383 (save-excursion
23384 (save-restriction
23385 (narrow-to-region
23386 (org-element-property :begin element)
23387 (org-element-property :end element))
23388 (org-do-remove-indentation)))))
23389 (reverse contents))))))
23390 (funcall unindent-tree (org-element-contents parse-tree))))
23392 (defun org-show-subtree ()
23393 "Show everything after this heading at deeper levels."
23394 (interactive)
23395 (outline-flag-region
23396 (point)
23397 (save-excursion
23398 (org-end-of-subtree t t))
23399 nil))
23401 (defun org-show-entry ()
23402 "Show the body directly following this heading.
23403 Show the heading too, if it is currently invisible."
23404 (interactive)
23405 (save-excursion
23406 (condition-case nil
23407 (progn
23408 (org-back-to-heading t)
23409 (outline-flag-region
23410 (max (point-min) (1- (point)))
23411 (save-excursion
23412 (if (re-search-forward
23413 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23414 (match-beginning 1)
23415 (point-max)))
23416 nil)
23417 (org-cycle-hide-drawers 'children))
23418 (error nil))))
23420 (defun org-make-options-regexp (kwds &optional extra)
23421 "Make a regular expression for keyword lines."
23422 (concat
23423 "^#\\+\\("
23424 (mapconcat 'regexp-quote kwds "\\|")
23425 (if extra (concat "\\|" extra))
23426 "\\):[ \t]*\\(.*\\)"))
23428 ;; Make isearch reveal the necessary context
23429 (defun org-isearch-end ()
23430 "Reveal context after isearch exits."
23431 (when isearch-success ; only if search was successful
23432 (if (featurep 'xemacs)
23433 ;; Under XEmacs, the hook is run in the correct place,
23434 ;; we directly show the context.
23435 (org-show-context 'isearch)
23436 ;; In Emacs the hook runs *before* restoring the overlays.
23437 ;; So we have to use a one-time post-command-hook to do this.
23438 ;; (Emacs 22 has a special variable, see function `org-mode')
23439 (unless (and (boundp 'isearch-mode-end-hook-quit)
23440 isearch-mode-end-hook-quit)
23441 ;; Only when the isearch was not quitted.
23442 (org-add-hook 'post-command-hook 'org-isearch-post-command
23443 'append 'local)))
23444 (org-fix-ellipsis-at-bol)))
23446 (defun org-isearch-post-command ()
23447 "Remove self from hook, and show context."
23448 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23449 (org-show-context 'isearch))
23452 ;;;; Integration with and fixes for other packages
23454 ;;; Imenu support
23456 (defvar org-imenu-markers nil
23457 "All markers currently used by Imenu.")
23458 (make-variable-buffer-local 'org-imenu-markers)
23460 (defun org-imenu-new-marker (&optional pos)
23461 "Return a new marker for use by Imenu, and remember the marker."
23462 (let ((m (make-marker)))
23463 (move-marker m (or pos (point)))
23464 (push m org-imenu-markers)
23467 (defun org-imenu-get-tree ()
23468 "Produce the index for Imenu."
23469 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23470 (setq org-imenu-markers nil)
23471 (let* ((n org-imenu-depth)
23472 (re (concat "^" (org-get-limited-outline-regexp)))
23473 (subs (make-vector (1+ n) nil))
23474 (last-level 0)
23475 m level head0 head)
23476 (save-excursion
23477 (save-restriction
23478 (widen)
23479 (goto-char (point-max))
23480 (while (re-search-backward re nil t)
23481 (setq level (org-reduced-level (funcall outline-level)))
23482 (when (and (<= level n)
23483 (looking-at org-complex-heading-regexp)
23484 (setq head0 (org-match-string-no-properties 4)))
23485 (setq head (org-link-display-format head0)
23486 m (org-imenu-new-marker))
23487 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23488 (if (>= level last-level)
23489 (push (cons head m) (aref subs level))
23490 (push (cons head (aref subs (1+ level))) (aref subs level))
23491 (loop for i from (1+ level) to n do (aset subs i nil)))
23492 (setq last-level level)))))
23493 (aref subs 1)))
23495 (eval-after-load "imenu"
23496 '(progn
23497 (add-hook 'imenu-after-jump-hook
23498 (lambda ()
23499 (if (derived-mode-p 'org-mode)
23500 (org-show-context 'org-goto))))))
23502 (defun org-link-display-format (link)
23503 "Replace a link with its the description.
23504 If there is no description, use the link target."
23505 (save-match-data
23506 (if (string-match org-bracket-link-analytic-regexp link)
23507 (replace-match (if (match-end 5)
23508 (match-string 5 link)
23509 (concat (match-string 1 link)
23510 (match-string 3 link)))
23511 nil t link)
23512 link)))
23514 (defun org-toggle-link-display ()
23515 "Toggle the literal or descriptive display of links."
23516 (interactive)
23517 (if org-descriptive-links
23518 (progn (org-remove-from-invisibility-spec '(org-link))
23519 (org-restart-font-lock)
23520 (setq org-descriptive-links nil))
23521 (progn (add-to-invisibility-spec '(org-link))
23522 (org-restart-font-lock)
23523 (setq org-descriptive-links t))))
23525 ;; Speedbar support
23527 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23528 "Overlay marking the agenda restriction line in speedbar.")
23529 (overlay-put org-speedbar-restriction-lock-overlay
23530 'face 'org-agenda-restriction-lock)
23531 (overlay-put org-speedbar-restriction-lock-overlay
23532 'help-echo "Agendas are currently limited to this item.")
23533 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23535 (defun org-speedbar-set-agenda-restriction ()
23536 "Restrict future agenda commands to the location at point in speedbar.
23537 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23538 (interactive)
23539 (require 'org-agenda)
23540 (let (p m tp np dir txt)
23541 (cond
23542 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23543 'org-imenu t))
23544 (setq m (get-text-property p 'org-imenu-marker))
23545 (with-current-buffer (marker-buffer m)
23546 (goto-char m)
23547 (org-agenda-set-restriction-lock 'subtree)))
23548 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23549 'speedbar-function 'speedbar-find-file))
23550 (setq tp (previous-single-property-change
23551 (1+ p) 'speedbar-function)
23552 np (next-single-property-change
23553 tp 'speedbar-function)
23554 dir (speedbar-line-directory)
23555 txt (buffer-substring-no-properties (or tp (point-min))
23556 (or np (point-max))))
23557 (with-current-buffer (find-file-noselect
23558 (let ((default-directory dir))
23559 (expand-file-name txt)))
23560 (unless (derived-mode-p 'org-mode)
23561 (user-error "Cannot restrict to non-Org-mode file"))
23562 (org-agenda-set-restriction-lock 'file)))
23563 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23564 (move-overlay org-speedbar-restriction-lock-overlay
23565 (point-at-bol) (point-at-eol))
23566 (setq current-prefix-arg nil)
23567 (org-agenda-maybe-redo)))
23569 (defvar speedbar-file-key-map)
23570 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23571 (eval-after-load "speedbar"
23572 '(progn
23573 (speedbar-add-supported-extension ".org")
23574 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23575 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23576 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23577 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23578 (add-hook 'speedbar-visiting-tag-hook
23579 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23581 ;;; Fixes and Hacks for problems with other packages
23583 ;; Make flyspell not check words in links, to not mess up our keymap
23584 (defvar org-element-affiliated-keywords) ; From org-element.el
23585 (defvar org-element-block-name-alist) ; From org-element.el
23586 (defun org-mode-flyspell-verify ()
23587 "Don't let flyspell put overlays at active buttons, or on
23588 {todo,all-time,additional-option-like}-keywords."
23589 (require 'org-element) ; For `org-element-affiliated-keywords'
23590 (let ((pos (max (1- (point)) (point-min)))
23591 (word (thing-at-point 'word)))
23592 (and (not (get-text-property pos 'keymap))
23593 (not (get-text-property pos 'org-no-flyspell))
23594 (not (member word org-todo-keywords-1))
23595 (not (member word org-all-time-keywords))
23596 (not (member word org-options-keywords))
23597 (not (member word (mapcar 'car org-startup-options)))
23598 (not (member-ignore-case word org-element-affiliated-keywords))
23599 (not (member-ignore-case word (org-get-export-keywords)))
23600 (not (member-ignore-case
23601 word (mapcar 'car org-element-block-name-alist)))
23602 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23604 (defun org-remove-flyspell-overlays-in (beg end)
23605 "Remove flyspell overlays in region."
23606 (and (org-bound-and-true-p flyspell-mode)
23607 (fboundp 'flyspell-delete-region-overlays)
23608 (flyspell-delete-region-overlays beg end))
23609 (add-text-properties beg end '(org-no-flyspell t)))
23611 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23612 (eval-after-load "bookmark"
23613 '(if (boundp 'bookmark-after-jump-hook)
23614 ;; We can use the hook
23615 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23616 ;; Hook not available, use advice
23617 (defadvice bookmark-jump (after org-make-visible activate)
23618 "Make the position visible."
23619 (org-bookmark-jump-unhide))))
23621 ;; Make sure saveplace shows the location if it was hidden
23622 (eval-after-load "saveplace"
23623 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23624 "Make the position visible."
23625 (org-bookmark-jump-unhide)))
23627 ;; Make sure ecb shows the location if it was hidden
23628 (eval-after-load "ecb"
23629 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23630 "Make hierarchy visible when jumping into location from ECB tree buffer."
23631 (if (derived-mode-p 'org-mode)
23632 (org-show-context))))
23634 (defun org-bookmark-jump-unhide ()
23635 "Unhide the current position, to show the bookmark location."
23636 (and (derived-mode-p 'org-mode)
23637 (or (outline-invisible-p)
23638 (save-excursion (goto-char (max (point-min) (1- (point))))
23639 (outline-invisible-p)))
23640 (org-show-context 'bookmark-jump)))
23642 ;; Make session.el ignore our circular variable
23643 (defvar session-globals-exclude)
23644 (eval-after-load "session"
23645 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23647 ;;;; Finish up
23649 (provide 'org)
23651 (run-hooks 'org-load-hook)
23653 ;;; org.el ends here