org.el (org-agenda-prepare-buffers): Restore the point position
[org-mode.git] / lisp / org.el
blob2b5e3d0561d9d772402b83623b8ef6d3c730cb95
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 (setq exported-file
202 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
203 (message "%s %s"
204 (if compile
205 (progn (byte-compile-file exported-file 'load)
206 "Compiled and loaded")
207 (progn (load-file exported-file) "Loaded"))
208 exported-file)))
210 (defcustom org-babel-load-languages '((emacs-lisp . t))
211 "Languages which can be evaluated in Org-mode buffers.
212 This list can be used to load support for any of the languages
213 below, note that each language will depend on a different set of
214 system executables and/or Emacs modes. When a language is
215 \"loaded\", then code blocks in that language can be evaluated
216 with `org-babel-execute-src-block' bound by default to C-c
217 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
218 be set to remove code block evaluation from the C-c C-c
219 keybinding. By default only Emacs Lisp (which has no
220 requirements) is loaded."
221 :group 'org-babel
222 :set 'org-babel-do-load-languages
223 :version "24.1"
224 :type '(alist :tag "Babel Languages"
225 :key-type
226 (choice
227 (const :tag "Awk" awk)
228 (const :tag "C" C)
229 (const :tag "R" R)
230 (const :tag "Asymptote" asymptote)
231 (const :tag "Calc" calc)
232 (const :tag "Clojure" clojure)
233 (const :tag "CSS" css)
234 (const :tag "Ditaa" ditaa)
235 (const :tag "Dot" dot)
236 (const :tag "Emacs Lisp" emacs-lisp)
237 (const :tag "Fortran" fortran)
238 (const :tag "Gnuplot" gnuplot)
239 (const :tag "Haskell" haskell)
240 (const :tag "IO" io)
241 (const :tag "Java" java)
242 (const :tag "Javascript" js)
243 (const :tag "LaTeX" latex)
244 (const :tag "Ledger" ledger)
245 (const :tag "Lilypond" lilypond)
246 (const :tag "Lisp" lisp)
247 (const :tag "Makefile" makefile)
248 (const :tag "Maxima" maxima)
249 (const :tag "Matlab" matlab)
250 (const :tag "Mscgen" mscgen)
251 (const :tag "Ocaml" ocaml)
252 (const :tag "Octave" octave)
253 (const :tag "Org" org)
254 (const :tag "Perl" perl)
255 (const :tag "Pico Lisp" picolisp)
256 (const :tag "PlantUML" plantuml)
257 (const :tag "Python" python)
258 (const :tag "Ruby" ruby)
259 (const :tag "Sass" sass)
260 (const :tag "Scala" scala)
261 (const :tag "Scheme" scheme)
262 (const :tag "Screen" screen)
263 (const :tag "Shell Script" sh)
264 (const :tag "Shen" shen)
265 (const :tag "Sql" sql)
266 (const :tag "Sqlite" sqlite))
267 :value-type (boolean :tag "Activate" :value t)))
269 ;;;; Customization variables
270 (defcustom org-clone-delete-id nil
271 "Remove ID property of clones of a subtree.
272 When non-nil, clones of a subtree don't inherit the ID property.
273 Otherwise they inherit the ID property with a new unique
274 identifier."
275 :type 'boolean
276 :version "24.1"
277 :group 'org-id)
279 ;;; Version
280 (org-check-version)
282 ;;;###autoload
283 (defun org-version (&optional here full message)
284 "Show the org-mode version in the echo area.
285 With prefix argument HERE, insert it at point.
286 When FULL is non-nil, use a verbose version string.
287 When MESSAGE is non-nil, display a message with the version."
288 (interactive "P")
289 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
290 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
291 (load-suffixes (list ".el"))
292 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
293 (org-trash (or
294 (and (fboundp 'org-release) (fboundp 'org-git-version))
295 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
296 (load-suffixes save-load-suffixes)
297 (org-version (org-release))
298 (git-version (org-git-version))
299 (version (format "Org-mode version %s (%s @ %s)"
300 org-version
301 git-version
302 (if org-install-dir
303 (if (string= org-dir org-install-dir)
304 org-install-dir
305 (concat "mixed installation! " org-install-dir " and " org-dir))
306 "org-loaddefs.el can not be found!")))
307 (_version (if full version org-version)))
308 (if (org-called-interactively-p 'interactive)
309 (if here
310 (insert version)
311 (message version))
312 (if message (message _version))
313 _version)))
315 (defconst org-version (org-version))
317 ;;; Compatibility constants
319 ;;; The custom variables
321 (defgroup org nil
322 "Outline-based notes management and organizer."
323 :tag "Org"
324 :group 'outlines
325 :group 'calendar)
327 (defcustom org-mode-hook nil
328 "Mode hook for Org-mode, run after the mode was turned on."
329 :group 'org
330 :type 'hook)
332 (defcustom org-load-hook nil
333 "Hook that is run after org.el has been loaded."
334 :group 'org
335 :type 'hook)
337 (defcustom org-log-buffer-setup-hook nil
338 "Hook that is run after an Org log buffer is created."
339 :group 'org
340 :version "24.1"
341 :type 'hook)
343 (defvar org-modules) ; defined below
344 (defvar org-modules-loaded nil
345 "Have the modules been loaded already?")
347 (defun org-load-modules-maybe (&optional force)
348 "Load all extensions listed in `org-modules'."
349 (when (or force (not org-modules-loaded))
350 (mapc (lambda (ext)
351 (condition-case nil (require ext)
352 (error (message "Problems while trying to load feature `%s'" ext))))
353 org-modules)
354 (setq org-modules-loaded t)))
356 (defun org-set-modules (var value)
357 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
358 (set var value)
359 (when (featurep 'org)
360 (org-load-modules-maybe 'force)))
362 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
363 "Modules that should always be loaded together with org.el.
365 If a description starts with <C>, the file is not part of Emacs
366 and loading it will require that you have downloaded and properly
367 installed the Org mode distribution.
369 You can also use this system to load external packages (i.e. neither Org
370 core modules, nor modules from the CONTRIB directory). Just add symbols
371 to the end of the list. If the package is called org-xyz.el, then you need
372 to add the symbol `xyz', and the package must have a call to:
374 \(provide 'org-xyz)
376 For export specific modules, see also `org-export-backends'."
377 :group 'org
378 :set 'org-set-modules
379 :version "24.4"
380 :package-version '(Org . "8.0")
381 :type
382 '(set :greedy t
383 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
384 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
385 (const :tag " crypt: Encryption of subtrees" org-crypt)
386 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
387 (const :tag " docview: Links to doc-view buffers" org-docview)
388 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
389 (const :tag " habit: Track your consistency with habits" org-habit)
390 (const :tag " id: Global IDs for identifying entries" org-id)
391 (const :tag " info: Links to Info nodes" org-info)
392 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
393 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
394 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
395 (const :tag " mouse: Additional mouse support" org-mouse)
396 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
397 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
398 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
400 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
401 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
402 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
403 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
404 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
405 (const :tag "C collector: Collect properties into tables" org-collector)
406 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
407 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
408 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
409 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
410 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
411 (const :tag "C eval: Include command output as text" org-eval)
412 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
413 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
414 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
415 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
416 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
417 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
418 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
419 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
420 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export--registered-backends) ; From ox.el.
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (declare-function org-export-backend-name "ox" (backend))
442 (defcustom org-export-backends '(ascii html icalendar latex)
443 "List of export back-ends that should be always available.
445 If a description starts with <C>, the file is not part of Emacs
446 and loading it will require that you have downloaded and properly
447 installed the Org mode distribution.
449 Unlike to `org-modules', libraries in this list will not be
450 loaded along with Org, but only once the export framework is
451 needed.
453 This variable needs to be set before org.el is loaded. If you
454 need to make a change while Emacs is running, use the customize
455 interface or run the following code, where VAL stands for the new
456 value of the variable, after updating it:
458 \(progn
459 \(setq org-export--registered-backends
460 \(org-remove-if-not
461 \(lambda (backend)
462 \(let ((name (org-export-backend-name backend)))
463 \(or (memq name val)
464 \(catch 'parentp
465 \(dolist (b val)
466 \(and (org-export-derived-backend-p b name)
467 \(throw 'parentp t)))))))
468 org-export--registered-backends))
469 \(let ((new-list (mapcar 'org-export-backend-name
470 org-export--registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default 'org-export-backends new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export--registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (let ((name (org-export-backend-name backend)))
495 (or (memq name val)
496 (catch 'parentp
497 (dolist (b val)
498 (and (org-export-derived-backend-p b name)
499 (throw 'parentp t)))))))
500 org-export--registered-backends))
501 ;; Now build NEW-LIST of both new back-ends and required
502 ;; parents.
503 (let ((new-list (mapcar 'org-export-backend-name
504 org-export--registered-backends)))
505 (dolist (backend val)
506 (cond
507 ((not (load (format "ox-%s" backend) t t))
508 (message "Problems while trying to load export back-end `%s'"
509 backend))
510 ((not (memq backend new-list)) (push backend new-list))))
511 ;; Set VAR to that list with fixed dependencies.
512 (set-default var new-list))))
513 :type '(set :greedy t
514 (const :tag " ascii Export buffer to ASCII format" ascii)
515 (const :tag " beamer Export buffer to Beamer presentation" beamer)
516 (const :tag " html Export buffer to HTML format" html)
517 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
518 (const :tag " latex Export buffer to LaTeX format" latex)
519 (const :tag " man Export buffer to MAN format" man)
520 (const :tag " md Export buffer to Markdown format" md)
521 (const :tag " odt Export buffer to ODT format" odt)
522 (const :tag " org Export buffer to Org format" org)
523 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
524 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
525 (const :tag "C deck Export buffer to deck.js presentations" deck)
526 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
527 (const :tag "C groff Export buffer to Groff format" groff)
528 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
529 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
530 (const :tag "C s5 Export buffer to s5 presentations" s5)
531 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
533 (eval-after-load 'ox
534 '(mapc
535 (lambda (backend)
536 (condition-case nil (require (intern (format "ox-%s" backend)))
537 (error (message "Problems while trying to load export back-end `%s'"
538 backend))))
539 org-export-backends))
541 (defcustom org-support-shift-select nil
542 "Non-nil means make shift-cursor commands select text when possible.
544 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
545 start selecting a region, or enlarge regions started in this way.
546 In Org-mode, in special contexts, these same keys are used for
547 other purposes, important enough to compete with shift selection.
548 Org tries to balance these needs by supporting `shift-select-mode'
549 outside these special contexts, under control of this variable.
551 The default of this variable is nil, to avoid confusing behavior. Shifted
552 cursor keys will then execute Org commands in the following contexts:
553 - on a headline, changing TODO state (left/right) and priority (up/down)
554 - on a time stamp, changing the time
555 - in a plain list item, changing the bullet type
556 - in a property definition line, switching between allowed values
557 - in the BEGIN line of a clock table (changing the time block).
558 Outside these contexts, the commands will throw an error.
560 When this variable is t and the cursor is not in a special
561 context, Org-mode will support shift-selection for making and
562 enlarging regions. To make this more effective, the bullet
563 cycling will no longer happen anywhere in an item line, but only
564 if the cursor is exactly on the bullet.
566 If you set this variable to the symbol `always', then the keys
567 will not be special in headlines, property lines, and item lines,
568 to make shift selection work there as well. If this is what you
569 want, you can use the following alternative commands: `C-c C-t'
570 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
571 can be used to switch TODO sets, `C-c -' to cycle item bullet
572 types, and properties can be edited by hand or in column view.
574 However, when the cursor is on a timestamp, shift-cursor commands
575 will still edit the time stamp - this is just too good to give up.
577 XEmacs user should have this variable set to nil, because
578 `shift-select-mode' is in Emacs 23 or later only."
579 :group 'org
580 :type '(choice
581 (const :tag "Never" nil)
582 (const :tag "When outside special context" t)
583 (const :tag "Everywhere except timestamps" always)))
585 (defcustom org-loop-over-headlines-in-active-region nil
586 "Shall some commands act upon headlines in the active region?
588 When set to `t', some commands will be performed in all headlines
589 within the active region.
591 When set to `start-level', some commands will be performed in all
592 headlines within the active region, provided that these headlines
593 are of the same level than the first one.
595 When set to a string, those commands will be performed on the
596 matching headlines within the active region. Such string must be
597 a tags/property/todo match as it is used in the agenda tags view.
599 The list of commands is: `org-schedule', `org-deadline',
600 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
601 `org-archive-to-archive-sibling'. The archiving commands skip
602 already archived entries."
603 :type '(choice (const :tag "Don't loop" nil)
604 (const :tag "All headlines in active region" t)
605 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
606 (string :tag "Tags/Property/Todo matcher"))
607 :version "24.1"
608 :group 'org-todo
609 :group 'org-archive)
611 (defgroup org-startup nil
612 "Options concerning startup of Org-mode."
613 :tag "Org Startup"
614 :group 'org)
616 (defcustom org-startup-folded t
617 "Non-nil means entering Org-mode will switch to OVERVIEW.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: fold (or `overview', this is equivalent)
622 #+STARTUP: nofold (or `showall', this is equivalent)
623 #+STARTUP: content
624 #+STARTUP: showeverything
626 By default, this option is ignored when Org opens agenda files
627 for the first time. If you want the agenda to honor the startup
628 option, set `org-agenda-inhibit-startup' to nil."
629 :group 'org-startup
630 :type '(choice
631 (const :tag "nofold: show all" nil)
632 (const :tag "fold: overview" t)
633 (const :tag "content: all headlines" content)
634 (const :tag "show everything, even drawers" showeverything)))
636 (defcustom org-startup-truncated t
637 "Non-nil means entering Org-mode will set `truncate-lines'.
638 This is useful since some lines containing links can be very long and
639 uninteresting. Also tables look terrible when wrapped."
640 :group 'org-startup
641 :type 'boolean)
643 (defcustom org-startup-indented nil
644 "Non-nil means turn on `org-indent-mode' on startup.
645 This can also be configured on a per-file basis by adding one of
646 the following lines anywhere in the buffer:
648 #+STARTUP: indent
649 #+STARTUP: noindent"
650 :group 'org-structure
651 :type '(choice
652 (const :tag "Not" nil)
653 (const :tag "Globally (slow on startup in large files)" t)))
655 (defcustom org-use-sub-superscripts t
656 "Non-nil means interpret \"_\" and \"^\" for display.
657 When this option is turned on, you can use TeX-like syntax for sub- and
658 superscripts. Several characters after \"_\" or \"^\" will be
659 considered as a single item - so grouping with {} is normally not
660 needed. For example, the following things will be parsed as single
661 sub- or superscripts.
663 10^24 or 10^tau several digits will be considered 1 item.
664 10^-12 or 10^-tau a leading sign with digits or a word
665 x^2-y^3 will be read as x^2 - y^3, because items are
666 terminated by almost any nonword/nondigit char.
667 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
669 Still, ambiguity is possible - so when in doubt use {} to enclose
670 the sub/superscript. If you set this variable to the symbol
671 `{}', the braces are *required* in order to trigger
672 interpretations as sub/superscript. This can be helpful in
673 documents that need \"_\" frequently in plain text."
674 :group 'org-startup
675 :version "24.1"
676 :type '(choice
677 (const :tag "Always interpret" t)
678 (const :tag "Only with braces" {})
679 (const :tag "Never interpret" nil)))
681 (defcustom org-startup-with-beamer-mode nil
682 "Non-nil means turn on `org-beamer-mode' on startup.
683 This can also be configured on a per-file basis by adding one of
684 the following lines anywhere in the buffer:
686 #+STARTUP: beamer"
687 :group 'org-startup
688 :version "24.1"
689 :type 'boolean)
691 (defcustom org-startup-align-all-tables nil
692 "Non-nil means align all tables when visiting a file.
693 This is useful when the column width in tables is forced with <N> cookies
694 in table fields. Such tables will look correct only after the first re-align.
695 This can also be configured on a per-file basis by adding one of
696 the following lines anywhere in the buffer:
697 #+STARTUP: align
698 #+STARTUP: noalign"
699 :group 'org-startup
700 :type 'boolean)
702 (defcustom org-startup-with-inline-images nil
703 "Non-nil means show inline images when loading a new Org file.
704 This can also be configured on a per-file basis by adding one of
705 the following lines anywhere in the buffer:
706 #+STARTUP: inlineimages
707 #+STARTUP: noinlineimages"
708 :group 'org-startup
709 :version "24.1"
710 :type 'boolean)
712 (defcustom org-startup-with-latex-preview nil
713 "Non-nil means preview LaTeX fragments when loading a new Org file.
715 This can also be configured on a per-file basis by adding one of
716 the followinglines anywhere in the buffer:
717 #+STARTUP: latexpreview
718 #+STARTUP: nolatexpreview"
719 :group 'org-startup
720 :version "24.4"
721 :package-version '(Org . "8.0")
722 :type 'boolean)
724 (defcustom org-insert-mode-line-in-empty-file nil
725 "Non-nil means insert the first line setting Org-mode in empty files.
726 When the function `org-mode' is called interactively in an empty file, this
727 normally means that the file name does not automatically trigger Org-mode.
728 To ensure that the file will always be in Org-mode in the future, a
729 line enforcing Org-mode will be inserted into the buffer, if this option
730 has been set."
731 :group 'org-startup
732 :type 'boolean)
734 (defcustom org-replace-disputed-keys nil
735 "Non-nil means use alternative key bindings for some keys.
736 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
737 These keys are also used by other packages like shift-selection-mode'
738 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
739 If you want to use Org-mode together with one of these other modes,
740 or more generally if you would like to move some Org-mode commands to
741 other keys, set this variable and configure the keys with the variable
742 `org-disputed-keys'.
744 This option is only relevant at load-time of Org-mode, and must be set
745 *before* org.el is loaded. Changing it requires a restart of Emacs to
746 become effective."
747 :group 'org-startup
748 :type 'boolean)
750 (defcustom org-use-extra-keys nil
751 "Non-nil means use extra key sequence definitions for certain commands.
752 This happens automatically if you run XEmacs or if `window-system'
753 is nil. This variable lets you do the same manually. You must
754 set it before loading org.
756 Example: on Carbon Emacs 22 running graphically, with an external
757 keyboard on a Powerbook, the default way of setting M-left might
758 not work for either Alt or ESC. Setting this variable will make
759 it work for ESC."
760 :group 'org-startup
761 :type 'boolean)
763 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
765 (defcustom org-disputed-keys
766 '(([(shift up)] . [(meta p)])
767 ([(shift down)] . [(meta n)])
768 ([(shift left)] . [(meta -)])
769 ([(shift right)] . [(meta +)])
770 ([(control shift right)] . [(meta shift +)])
771 ([(control shift left)] . [(meta shift -)]))
772 "Keys for which Org-mode and other modes compete.
773 This is an alist, cars are the default keys, second element specifies
774 the alternative to use when `org-replace-disputed-keys' is t.
776 Keys can be specified in any syntax supported by `define-key'.
777 The value of this option takes effect only at Org-mode's startup,
778 therefore you'll have to restart Emacs to apply it after changing."
779 :group 'org-startup
780 :type 'alist)
782 (defun org-key (key)
783 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
784 Or return the original if not disputed.
785 Also apply the translations defined in `org-xemacs-key-equivalents'."
786 (when org-replace-disputed-keys
787 (let* ((nkey (key-description key))
788 (x (org-find-if (lambda (x)
789 (equal (key-description (car x)) nkey))
790 org-disputed-keys)))
791 (setq key (if x (cdr x) key))))
792 (when (featurep 'xemacs)
793 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
794 key)
796 (defun org-find-if (predicate seq)
797 (catch 'exit
798 (while seq
799 (if (funcall predicate (car seq))
800 (throw 'exit (car seq))
801 (pop seq)))))
803 (defun org-defkey (keymap key def)
804 "Define a key, possibly translated, as returned by `org-key'."
805 (define-key keymap (org-key key) def))
807 (defcustom org-ellipsis nil
808 "The ellipsis to use in the Org-mode outline.
809 When nil, just use the standard three dots. When a string, use that instead,
810 When a face, use the standard 3 dots, but with the specified face.
811 The change affects only Org-mode (which will then use its own display table).
812 Changing this requires executing `M-x org-mode' in a buffer to become
813 effective."
814 :group 'org-startup
815 :type '(choice (const :tag "Default" nil)
816 (face :tag "Face" :value org-warning)
817 (string :tag "String" :value "...#")))
819 (defvar org-display-table nil
820 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
822 (defgroup org-keywords nil
823 "Keywords in Org-mode."
824 :tag "Org Keywords"
825 :group 'org)
827 (defcustom org-deadline-string "DEADLINE:"
828 "String to mark deadline entries.
829 A deadline is this string, followed by a time stamp. Should be a word,
830 terminated by a colon. You can insert a schedule keyword and
831 a timestamp with \\[org-deadline].
832 Changes become only effective after restarting Emacs."
833 :group 'org-keywords
834 :type 'string)
836 (defcustom org-scheduled-string "SCHEDULED:"
837 "String to mark scheduled TODO entries.
838 A schedule is this string, followed by a time stamp. Should be a word,
839 terminated by a colon. You can insert a schedule keyword and
840 a timestamp with \\[org-schedule].
841 Changes become only effective after restarting Emacs."
842 :group 'org-keywords
843 :type 'string)
845 (defcustom org-closed-string "CLOSED:"
846 "String used as the prefix for timestamps logging closing a TODO entry."
847 :group 'org-keywords
848 :type 'string)
850 (defcustom org-clock-string "CLOCK:"
851 "String used as prefix for timestamps clocking work hours on an item."
852 :group 'org-keywords
853 :type 'string)
855 (defcustom org-closed-keep-when-no-todo nil
856 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
857 :group 'org-todo
858 :group 'org-keywords
859 :version "24.4"
860 :package-version '(Org . "8.0")
861 :type 'boolean)
863 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
864 org-scheduled-string "\\|"
865 org-deadline-string "\\|"
866 org-closed-string "\\|"
867 org-clock-string "\\)")
868 "Matches a line with planning or clock info.")
870 (defcustom org-comment-string "COMMENT"
871 "Entries starting with this keyword will never be exported.
872 An entry can be toggled between COMMENT and normal with
873 \\[org-toggle-comment].
874 Changes become only effective after restarting Emacs."
875 :group 'org-keywords
876 :type 'string)
878 (defcustom org-quote-string "QUOTE"
879 "Entries starting with this keyword will be exported in fixed-width font.
880 Quoting applies only to the text in the entry following the headline, and does
881 not extend beyond the next headline, even if that is lower level.
882 An entry can be toggled between QUOTE and normal with
883 \\[org-toggle-fixed-width-section]."
884 :group 'org-keywords
885 :type 'string)
887 (defconst org-repeat-re
888 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
889 "Regular expression for specifying repeated events.
890 After a match, group 1 contains the repeat expression.")
892 (defgroup org-structure nil
893 "Options concerning the general structure of Org-mode files."
894 :tag "Org Structure"
895 :group 'org)
897 (defgroup org-reveal-location nil
898 "Options about how to make context of a location visible."
899 :tag "Org Reveal Location"
900 :group 'org-structure)
902 (defconst org-context-choice
903 '(choice
904 (const :tag "Always" t)
905 (const :tag "Never" nil)
906 (repeat :greedy t :tag "Individual contexts"
907 (cons
908 (choice :tag "Context"
909 (const agenda)
910 (const org-goto)
911 (const occur-tree)
912 (const tags-tree)
913 (const link-search)
914 (const mark-goto)
915 (const bookmark-jump)
916 (const isearch)
917 (const default))
918 (boolean))))
919 "Contexts for the reveal options.")
921 (defcustom org-show-hierarchy-above '((default . t))
922 "Non-nil means show full hierarchy when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the hierarchy of headings
925 above the exposed location is shown.
926 Turning this off for example for sparse trees makes them very compact.
927 Instead of t, this can also be an alist specifying this option for different
928 contexts. Valid contexts are
929 agenda when exposing an entry from the agenda
930 org-goto when using the command `org-goto' on key C-c C-j
931 occur-tree when using the command `org-occur' on key C-c /
932 tags-tree when constructing a sparse tree based on tags matches
933 link-search when exposing search matches associated with a link
934 mark-goto when exposing the jump goal of a mark
935 bookmark-jump when exposing a bookmark location
936 isearch when exiting from an incremental search
937 default default for all contexts not set explicitly"
938 :group 'org-reveal-location
939 :type org-context-choice)
941 (defcustom org-show-following-heading '((default . nil))
942 "Non-nil means show following heading when revealing a location.
943 Org-mode often shows locations in an org-mode file which might have
944 been invisible before. When this is set, the heading following the
945 match is shown.
946 Turning this off for example for sparse trees makes them very compact,
947 but makes it harder to edit the location of the match. In such a case,
948 use the command \\[org-reveal] to show more context.
949 Instead of t, this can also be an alist specifying this option for different
950 contexts. See `org-show-hierarchy-above' for valid contexts."
951 :group 'org-reveal-location
952 :type org-context-choice)
954 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
955 "Non-nil means show all sibling heading when revealing a location.
956 Org-mode often shows locations in an org-mode file which might have
957 been invisible before. When this is set, the sibling of the current entry
958 heading are all made visible. If `org-show-hierarchy-above' is t,
959 the same happens on each level of the hierarchy above the current entry.
961 By default this is on for the isearch context, off for all other contexts.
962 Turning this off for example for sparse trees makes them very compact,
963 but makes it harder to edit the location of the match. In such a case,
964 use the command \\[org-reveal] to show more context.
965 Instead of t, this can also be an alist specifying this option for different
966 contexts. See `org-show-hierarchy-above' for valid contexts."
967 :group 'org-reveal-location
968 :type org-context-choice
969 :version "24.4"
970 :package-version '(Org . "8.0"))
972 (defcustom org-show-entry-below '((default . nil))
973 "Non-nil means show the entry below a headline when revealing a location.
974 Org-mode often shows locations in an org-mode file which might have
975 been invisible before. When this is set, the text below the headline that is
976 exposed is also shown.
978 By default this is off for all contexts.
979 Instead of t, this can also be an alist specifying this option for different
980 contexts. See `org-show-hierarchy-above' for valid contexts."
981 :group 'org-reveal-location
982 :type org-context-choice)
984 (defcustom org-indirect-buffer-display 'other-window
985 "How should indirect tree buffers be displayed?
986 This applies to indirect buffers created with the commands
987 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
988 Valid values are:
989 current-window Display in the current window
990 other-window Just display in another window.
991 dedicated-frame Create one new frame, and re-use it each time.
992 new-frame Make a new frame each time. Note that in this case
993 previously-made indirect buffers are kept, and you need to
994 kill these buffers yourself."
995 :group 'org-structure
996 :group 'org-agenda-windows
997 :type '(choice
998 (const :tag "In current window" current-window)
999 (const :tag "In current frame, other window" other-window)
1000 (const :tag "Each time a new frame" new-frame)
1001 (const :tag "One dedicated frame" dedicated-frame)))
1003 (defcustom org-use-speed-commands nil
1004 "Non-nil means activate single letter commands at beginning of a headline.
1005 This may also be a function to test for appropriate locations where speed
1006 commands should be active."
1007 :group 'org-structure
1008 :type '(choice
1009 (const :tag "Never" nil)
1010 (const :tag "At beginning of headline stars" t)
1011 (function)))
1013 (defcustom org-speed-commands-user nil
1014 "Alist of additional speed commands.
1015 This list will be checked before `org-speed-commands-default'
1016 when the variable `org-use-speed-commands' is non-nil
1017 and when the cursor is at the beginning of a headline.
1018 The car if each entry is a string with a single letter, which must
1019 be assigned to `self-insert-command' in the global map.
1020 The cdr is either a command to be called interactively, a function
1021 to be called, or a form to be evaluated.
1022 An entry that is just a list with a single string will be interpreted
1023 as a descriptive headline that will be added when listing the speed
1024 commands in the Help buffer using the `?' speed command."
1025 :group 'org-structure
1026 :type '(repeat :value ("k" . ignore)
1027 (choice :value ("k" . ignore)
1028 (list :tag "Descriptive Headline" (string :tag "Headline"))
1029 (cons :tag "Letter and Command"
1030 (string :tag "Command letter")
1031 (choice
1032 (function)
1033 (sexp))))))
1035 (defcustom org-bookmark-names-plist
1036 '(:last-capture "org-capture-last-stored"
1037 :last-refile "org-refile-last-stored"
1038 :last-capture-marker "org-capture-last-stored-marker")
1039 "Names for bookmarks automatically set by some Org commands.
1040 This can provide strings as names for a number of bookmakrs Org sets
1041 automatically. The following keys are currently implemented:
1042 :last-capture
1043 :last-capture-marker
1044 :last-refile
1045 When a key does not show up in the property list, the corresponding bookmark
1046 is not set."
1047 :group 'org-structure
1048 :type 'plist)
1050 (defgroup org-cycle nil
1051 "Options concerning visibility cycling in Org-mode."
1052 :tag "Org Cycle"
1053 :group 'org-structure)
1055 (defcustom org-cycle-skip-children-state-if-no-children t
1056 "Non-nil means skip CHILDREN state in entries that don't have any."
1057 :group 'org-cycle
1058 :type 'boolean)
1060 (defcustom org-cycle-max-level nil
1061 "Maximum level which should still be subject to visibility cycling.
1062 Levels higher than this will, for cycling, be treated as text, not a headline.
1063 When `org-odd-levels-only' is set, a value of N in this variable actually
1064 means 2N-1 stars as the limiting headline.
1065 When nil, cycle all levels.
1066 Note that the limiting level of cycling is also influenced by
1067 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1068 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1069 than its value."
1070 :group 'org-cycle
1071 :type '(choice
1072 (const :tag "No limit" nil)
1073 (integer :tag "Maximum level")))
1075 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1076 "Names of drawers. Drawers are not opened by cycling on the headline above.
1077 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1078 this:
1079 :DRAWERNAME:
1080 .....
1081 :END:
1082 The drawer \"PROPERTIES\" is special for capturing properties through
1083 the property API.
1085 Drawers can be defined on the per-file basis with a line like:
1087 #+DRAWERS: HIDDEN STATE PROPERTIES"
1088 :group 'org-structure
1089 :group 'org-cycle
1090 :type '(repeat (string :tag "Drawer Name")))
1092 (defcustom org-hide-block-startup nil
1093 "Non-nil means entering Org-mode will fold all blocks.
1094 This can also be set in on a per-file basis with
1096 #+STARTUP: hideblocks
1097 #+STARTUP: showblocks"
1098 :group 'org-startup
1099 :group 'org-cycle
1100 :type 'boolean)
1102 (defcustom org-cycle-global-at-bob nil
1103 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1104 This makes it possible to do global cycling without having to use S-TAB or
1105 \\[universal-argument] TAB. For this special case to work, the first line
1106 of the buffer must not be a headline -- it may be empty or some other text.
1107 When used in this way, `org-cycle-hook' is disabled temporarily to make
1108 sure the cursor stays at the beginning of the buffer. When this option is
1109 nil, don't do anything special at the beginning of the buffer."
1110 :group 'org-cycle
1111 :type 'boolean)
1113 (defcustom org-cycle-level-after-item/entry-creation t
1114 "Non-nil means cycle entry level or item indentation in new empty entries.
1116 When the cursor is at the end of an empty headline, i.e., with only stars
1117 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1118 and then all possible ancestor states, before returning to the original state.
1119 This makes data entry extremely fast: M-RET to create a new headline,
1120 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1122 When the cursor is at the end of an empty plain list item, one TAB will
1123 make it a subitem, two or more tabs will back up to make this an item
1124 higher up in the item hierarchy."
1125 :group 'org-cycle
1126 :type 'boolean)
1128 (defcustom org-cycle-emulate-tab t
1129 "Where should `org-cycle' emulate TAB.
1130 nil Never
1131 white Only in completely white lines
1132 whitestart Only at the beginning of lines, before the first non-white char
1133 t Everywhere except in headlines
1134 exc-hl-bol Everywhere except at the start of a headline
1135 If TAB is used in a place where it does not emulate TAB, the current subtree
1136 visibility is cycled."
1137 :group 'org-cycle
1138 :type '(choice (const :tag "Never" nil)
1139 (const :tag "Only in completely white lines" white)
1140 (const :tag "Before first char in a line" whitestart)
1141 (const :tag "Everywhere except in headlines" t)
1142 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1144 (defcustom org-cycle-separator-lines 2
1145 "Number of empty lines needed to keep an empty line between collapsed trees.
1146 If you leave an empty line between the end of a subtree and the following
1147 headline, this empty line is hidden when the subtree is folded.
1148 Org-mode will leave (exactly) one empty line visible if the number of
1149 empty lines is equal or larger to the number given in this variable.
1150 So the default 2 means at least 2 empty lines after the end of a subtree
1151 are needed to produce free space between a collapsed subtree and the
1152 following headline.
1154 If the number is negative, and the number of empty lines is at least -N,
1155 all empty lines are shown.
1157 Special case: when 0, never leave empty lines in collapsed view."
1158 :group 'org-cycle
1159 :type 'integer)
1160 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1162 (defcustom org-pre-cycle-hook nil
1163 "Hook that is run before visibility cycling is happening.
1164 The function(s) in this hook must accept a single argument which indicates
1165 the new state that will be set right after running this hook. The
1166 argument is a symbol. Before a global state change, it can have the values
1167 `overview', `content', or `all'. Before a local state change, it can have
1168 the values `folded', `children', or `subtree'."
1169 :group 'org-cycle
1170 :type 'hook)
1172 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1173 org-cycle-hide-drawers
1174 org-cycle-hide-inline-tasks
1175 org-cycle-show-empty-lines
1176 org-optimize-window-after-visibility-change)
1177 "Hook that is run after `org-cycle' has changed the buffer visibility.
1178 The function(s) in this hook must accept a single argument which indicates
1179 the new state that was set by the most recent `org-cycle' command. The
1180 argument is a symbol. After a global state change, it can have the values
1181 `overview', `contents', or `all'. After a local state change, it can have
1182 the values `folded', `children', or `subtree'."
1183 :group 'org-cycle
1184 :type 'hook)
1186 (defgroup org-edit-structure nil
1187 "Options concerning structure editing in Org-mode."
1188 :tag "Org Edit Structure"
1189 :group 'org-structure)
1191 (defcustom org-odd-levels-only nil
1192 "Non-nil means skip even levels and only use odd levels for the outline.
1193 This has the effect that two stars are being added/taken away in
1194 promotion/demotion commands. It also influences how levels are
1195 handled by the exporters.
1196 Changing it requires restart of `font-lock-mode' to become effective
1197 for fontification also in regions already fontified.
1198 You may also set this on a per-file basis by adding one of the following
1199 lines to the buffer:
1201 #+STARTUP: odd
1202 #+STARTUP: oddeven"
1203 :group 'org-edit-structure
1204 :group 'org-appearance
1205 :type 'boolean)
1207 (defcustom org-adapt-indentation t
1208 "Non-nil means adapt indentation to outline node level.
1210 When this variable is set, Org assumes that you write outlines by
1211 indenting text in each node to align with the headline (after the stars).
1212 The following issues are influenced by this variable:
1214 - When this is set and the *entire* text in an entry is indented, the
1215 indentation is increased by one space in a demotion command, and
1216 decreased by one in a promotion command. If any line in the entry
1217 body starts with text at column 0, indentation is not changed at all.
1219 - Property drawers and planning information is inserted indented when
1220 this variable s set. When nil, they will not be indented.
1222 - TAB indents a line relative to context. The lines below a headline
1223 will be indented when this variable is set.
1225 Note that this is all about true indentation, by adding and removing
1226 space characters. See also `org-indent.el' which does level-dependent
1227 indentation in a virtual way, i.e. at display time in Emacs."
1228 :group 'org-edit-structure
1229 :type 'boolean)
1231 (defcustom org-special-ctrl-a/e nil
1232 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1234 When t, `C-a' will bring back the cursor to the beginning of the
1235 headline text, i.e. after the stars and after a possible TODO
1236 keyword. In an item, this will be the position after bullet and
1237 check-box, if any. When the cursor is already at that position,
1238 another `C-a' will bring it to the beginning of the line.
1240 `C-e' will jump to the end of the headline, ignoring the presence
1241 of tags in the headline. A second `C-e' will then jump to the
1242 true end of the line, after any tags. This also means that, when
1243 this variable is non-nil, `C-e' also will never jump beyond the
1244 end of the heading of a folded section, i.e. not after the
1245 ellipses.
1247 When set to the symbol `reversed', the first `C-a' or `C-e' works
1248 normally, going to the true line boundary first. Only a directly
1249 following, identical keypress will bring the cursor to the
1250 special positions.
1252 This may also be a cons cell where the behavior for `C-a' and
1253 `C-e' is set separately."
1254 :group 'org-edit-structure
1255 :type '(choice
1256 (const :tag "off" nil)
1257 (const :tag "on: after stars/bullet and before tags first" t)
1258 (const :tag "reversed: true line boundary first" reversed)
1259 (cons :tag "Set C-a and C-e separately"
1260 (choice :tag "Special C-a"
1261 (const :tag "off" nil)
1262 (const :tag "on: after stars/bullet first" t)
1263 (const :tag "reversed: before stars/bullet first" reversed))
1264 (choice :tag "Special C-e"
1265 (const :tag "off" nil)
1266 (const :tag "on: before tags first" t)
1267 (const :tag "reversed: after tags first" reversed)))))
1268 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1270 (defcustom org-special-ctrl-k nil
1271 "Non-nil means `C-k' will behave specially in headlines.
1272 When nil, `C-k' will call the default `kill-line' command.
1273 When t, the following will happen while the cursor is in the headline:
1275 - When the cursor is at the beginning of a headline, kill the entire
1276 line and possible the folded subtree below the line.
1277 - When in the middle of the headline text, kill the headline up to the tags.
1278 - When after the headline text, kill the tags."
1279 :group 'org-edit-structure
1280 :type 'boolean)
1282 (defcustom org-ctrl-k-protect-subtree nil
1283 "Non-nil means, do not delete a hidden subtree with C-k.
1284 When set to the symbol `error', simply throw an error when C-k is
1285 used to kill (part-of) a headline that has hidden text behind it.
1286 Any other non-nil value will result in a query to the user, if it is
1287 OK to kill that hidden subtree. When nil, kill without remorse."
1288 :group 'org-edit-structure
1289 :version "24.1"
1290 :type '(choice
1291 (const :tag "Do not protect hidden subtrees" nil)
1292 (const :tag "Protect hidden subtrees with a security query" t)
1293 (const :tag "Never kill a hidden subtree with C-k" error)))
1295 (defcustom org-special-ctrl-o t
1296 "Non-nil means, make `C-o' insert a row in tables."
1297 :group 'org-edit-structure
1298 :type 'boolean)
1300 (defcustom org-catch-invisible-edits nil
1301 "Check if in invisible region before inserting or deleting a character.
1302 Valid values are:
1304 nil Do not check, so just do invisible edits.
1305 error Throw an error and do nothing.
1306 show Make point visible, and do the requested edit.
1307 show-and-error Make point visible, then throw an error and abort the edit.
1308 smart Make point visible, and do insertion/deletion if it is
1309 adjacent to visible text and the change feels predictable.
1310 Never delete a previously invisible character or add in the
1311 middle or right after an invisible region. Basically, this
1312 allows insertion and backward-delete right before ellipses.
1313 FIXME: maybe in this case we should not even show?"
1314 :group 'org-edit-structure
1315 :version "24.1"
1316 :type '(choice
1317 (const :tag "Do not check" nil)
1318 (const :tag "Throw error when trying to edit" error)
1319 (const :tag "Unhide, but do not do the edit" show-and-error)
1320 (const :tag "Show invisible part and do the edit" show)
1321 (const :tag "Be smart and do the right thing" smart)))
1323 (defcustom org-yank-folded-subtrees t
1324 "Non-nil means when yanking subtrees, fold them.
1325 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1326 it starts with a heading and all other headings in it are either children
1327 or siblings, then fold all the subtrees. However, do this only if no
1328 text after the yank would be swallowed into a folded tree by this action."
1329 :group 'org-edit-structure
1330 :type 'boolean)
1332 (defcustom org-yank-adjusted-subtrees nil
1333 "Non-nil means when yanking subtrees, adjust the level.
1334 With this setting, `org-paste-subtree' is used to insert the subtree, see
1335 this function for details."
1336 :group 'org-edit-structure
1337 :type 'boolean)
1339 (defcustom org-M-RET-may-split-line '((default . t))
1340 "Non-nil means M-RET will split the line at the cursor position.
1341 When nil, it will go to the end of the line before making a
1342 new line.
1343 You may also set this option in a different way for different
1344 contexts. Valid contexts are:
1346 headline when creating a new headline
1347 item when creating a new item
1348 table in a table field
1349 default the value to be used for all contexts not explicitly
1350 customized"
1351 :group 'org-structure
1352 :group 'org-table
1353 :type '(choice
1354 (const :tag "Always" t)
1355 (const :tag "Never" nil)
1356 (repeat :greedy t :tag "Individual contexts"
1357 (cons
1358 (choice :tag "Context"
1359 (const headline)
1360 (const item)
1361 (const table)
1362 (const default))
1363 (boolean)))))
1366 (defcustom org-insert-heading-respect-content nil
1367 "Non-nil means insert new headings after the current subtree.
1368 When nil, the new heading is created directly after the current line.
1369 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1370 this variable on for the duration of the command."
1371 :group 'org-structure
1372 :type 'boolean)
1374 (defcustom org-blank-before-new-entry '((heading . auto)
1375 (plain-list-item . auto))
1376 "Should `org-insert-heading' leave a blank line before new heading/item?
1377 The value is an alist, with `heading' and `plain-list-item' as CAR,
1378 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1379 which case Org will look at the surrounding headings/items and try to
1380 make an intelligent decision whether to insert a blank line or not.
1382 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1383 the setting here is ignored and no empty line is inserted to avoid breaking
1384 the list structure."
1385 :group 'org-edit-structure
1386 :type '(list
1387 (cons (const heading)
1388 (choice (const :tag "Never" nil)
1389 (const :tag "Always" t)
1390 (const :tag "Auto" auto)))
1391 (cons (const plain-list-item)
1392 (choice (const :tag "Never" nil)
1393 (const :tag "Always" t)
1394 (const :tag "Auto" auto)))))
1396 (defcustom org-insert-heading-hook nil
1397 "Hook being run after inserting a new heading."
1398 :group 'org-edit-structure
1399 :type 'hook)
1401 (defcustom org-enable-fixed-width-editor t
1402 "Non-nil means lines starting with \":\" are treated as fixed-width.
1403 This currently only means they are never auto-wrapped.
1404 When nil, such lines will be treated like ordinary lines.
1405 See also the QUOTE keyword."
1406 :group 'org-edit-structure
1407 :type 'boolean)
1409 (defcustom org-goto-auto-isearch t
1410 "Non-nil means typing characters in `org-goto' starts incremental search.
1411 When nil, you can use these keybindings to navigate the buffer:
1413 q Quit the org-goto interface
1414 n Go to the next visible heading
1415 p Go to the previous visible heading
1416 f Go one heading forward on same level
1417 b Go one heading backward on same level
1418 u Go one heading up"
1419 :group 'org-edit-structure
1420 :type 'boolean)
1422 (defgroup org-sparse-trees nil
1423 "Options concerning sparse trees in Org-mode."
1424 :tag "Org Sparse Trees"
1425 :group 'org-structure)
1427 (defcustom org-highlight-sparse-tree-matches t
1428 "Non-nil means highlight all matches that define a sparse tree.
1429 The highlights will automatically disappear the next time the buffer is
1430 changed by an edit command."
1431 :group 'org-sparse-trees
1432 :type 'boolean)
1434 (defcustom org-remove-highlights-with-change t
1435 "Non-nil means any change to the buffer will remove temporary highlights.
1436 Such highlights are created by `org-occur' and `org-clock-display'.
1437 When nil, `C-c C-c needs to be used to get rid of the highlights.
1438 The highlights created by `org-preview-latex-fragment' always need
1439 `C-c C-c' to be removed."
1440 :group 'org-sparse-trees
1441 :group 'org-time
1442 :type 'boolean)
1445 (defcustom org-occur-hook '(org-first-headline-recenter)
1446 "Hook that is run after `org-occur' has constructed a sparse tree.
1447 This can be used to recenter the window to show as much of the structure
1448 as possible."
1449 :group 'org-sparse-trees
1450 :type 'hook)
1452 (defgroup org-imenu-and-speedbar nil
1453 "Options concerning imenu and speedbar in Org-mode."
1454 :tag "Org Imenu and Speedbar"
1455 :group 'org-structure)
1457 (defcustom org-imenu-depth 2
1458 "The maximum level for Imenu access to Org-mode headlines.
1459 This also applied for speedbar access."
1460 :group 'org-imenu-and-speedbar
1461 :type 'integer)
1463 (defgroup org-table nil
1464 "Options concerning tables in Org-mode."
1465 :tag "Org Table"
1466 :group 'org)
1468 (defcustom org-enable-table-editor 'optimized
1469 "Non-nil means lines starting with \"|\" are handled by the table editor.
1470 When nil, such lines will be treated like ordinary lines.
1472 When equal to the symbol `optimized', the table editor will be optimized to
1473 do the following:
1474 - Automatic overwrite mode in front of whitespace in table fields.
1475 This makes the structure of the table stay in tact as long as the edited
1476 field does not exceed the column width.
1477 - Minimize the number of realigns. Normally, the table is aligned each time
1478 TAB or RET are pressed to move to another field. With optimization this
1479 happens only if changes to a field might have changed the column width.
1480 Optimization requires replacing the functions `self-insert-command',
1481 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1482 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1483 very good at guessing when a re-align will be necessary, but you can always
1484 force one with \\[org-ctrl-c-ctrl-c].
1486 If you would like to use the optimized version in Org-mode, but the
1487 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1489 This variable can be used to turn on and off the table editor during a session,
1490 but in order to toggle optimization, a restart is required.
1492 See also the variable `org-table-auto-blank-field'."
1493 :group 'org-table
1494 :type '(choice
1495 (const :tag "off" nil)
1496 (const :tag "on" t)
1497 (const :tag "on, optimized" optimized)))
1499 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1500 (version<= emacs-version "24.1"))
1501 "Non-nil means cluster self-insert commands for undo when possible.
1502 If this is set, then, like in the Emacs command loop, 20 consecutive
1503 characters will be undone together.
1504 This is configurable, because there is some impact on typing performance."
1505 :group 'org-table
1506 :type 'boolean)
1508 (defcustom org-table-tab-recognizes-table.el t
1509 "Non-nil means TAB will automatically notice a table.el table.
1510 When it sees such a table, it moves point into it and - if necessary -
1511 calls `table-recognize-table'."
1512 :group 'org-table-editing
1513 :type 'boolean)
1515 (defgroup org-link nil
1516 "Options concerning links in Org-mode."
1517 :tag "Org Link"
1518 :group 'org)
1520 (defvar org-link-abbrev-alist-local nil
1521 "Buffer-local version of `org-link-abbrev-alist', which see.
1522 The value of this is taken from the #+LINK lines.")
1523 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1525 (defcustom org-link-abbrev-alist nil
1526 "Alist of link abbreviations.
1527 The car of each element is a string, to be replaced at the start of a link.
1528 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1529 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1531 [[linkkey:tag][description]]
1533 The 'linkkey' must be a word word, starting with a letter, followed
1534 by letters, numbers, '-' or '_'.
1536 If REPLACE is a string, the tag will simply be appended to create the link.
1537 If the string contains \"%s\", the tag will be inserted there. If the string
1538 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1539 at that point (see the function `url-hexify-string'). If the string contains
1540 the specifier \"%(my-function)\", then the custom function `my-function' will
1541 be invoked: this function takes the tag as its only argument and must return
1542 a string.
1544 REPLACE may also be a function that will be called with the tag as the
1545 only argument to create the link, which should be returned as a string.
1547 See the manual for examples."
1548 :group 'org-link
1549 :type '(repeat
1550 (cons
1551 (string :tag "Protocol")
1552 (choice
1553 (string :tag "Format")
1554 (function)))))
1556 (defcustom org-descriptive-links t
1557 "Non-nil means Org will display descriptive links.
1558 E.g. [[http://orgmode.org][Org website]] will be displayed as
1559 \"Org Website\", hiding the link itself and just displaying its
1560 description. When set to `nil', Org will display the full links
1561 literally.
1563 You can interactively set the value of this variable by calling
1564 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1565 :group 'org-link
1566 :type 'boolean)
1568 (defcustom org-link-file-path-type 'adaptive
1569 "How the path name in file links should be stored.
1570 Valid values are:
1572 relative Relative to the current directory, i.e. the directory of the file
1573 into which the link is being inserted.
1574 absolute Absolute path, if possible with ~ for home directory.
1575 noabbrev Absolute path, no abbreviation of home directory.
1576 adaptive Use relative path for files in the current directory and sub-
1577 directories of it. For other files, use an absolute path."
1578 :group 'org-link
1579 :type '(choice
1580 (const relative)
1581 (const absolute)
1582 (const noabbrev)
1583 (const adaptive)))
1585 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1586 "Types of links that should be activated in Org-mode files.
1587 This is a list of symbols, each leading to the activation of a certain link
1588 type. In principle, it does not hurt to turn on most link types - there may
1589 be a small gain when turning off unused link types. The types are:
1591 bracket The recommended [[link][description]] or [[link]] links with hiding.
1592 angle Links in angular brackets that may contain whitespace like
1593 <bbdb:Carsten Dominik>.
1594 plain Plain links in normal text, no whitespace, like http://google.com.
1595 radio Text that is matched by a radio target, see manual for details.
1596 tag Tag settings in a headline (link to tag search).
1597 date Time stamps (link to calendar).
1598 footnote Footnote labels.
1600 Changing this variable requires a restart of Emacs to become effective."
1601 :group 'org-link
1602 :type '(set :greedy t
1603 (const :tag "Double bracket links" bracket)
1604 (const :tag "Angular bracket links" angle)
1605 (const :tag "Plain text links" plain)
1606 (const :tag "Radio target matches" radio)
1607 (const :tag "Tags" tag)
1608 (const :tag "Timestamps" date)
1609 (const :tag "Footnotes" footnote)))
1611 (defcustom org-make-link-description-function nil
1612 "Function to use for generating link descriptions from links.
1613 When nil, the link location will be used. This function must take
1614 two parameters: the first one is the link, the second one is the
1615 description generated by `org-insert-link'. The function should
1616 return the description to use."
1617 :group 'org-link
1618 :type '(choice (const nil) (function)))
1620 (defgroup org-link-store nil
1621 "Options concerning storing links in Org-mode."
1622 :tag "Org Store Link"
1623 :group 'org-link)
1625 (defcustom org-url-hexify-p t
1626 "When non-nil, hexify URL when creating a link."
1627 :type 'boolean
1628 :version "24.3"
1629 :group 'org-link-store)
1631 (defcustom org-email-link-description-format "Email %c: %.30s"
1632 "Format of the description part of a link to an email or usenet message.
1633 The following %-escapes will be replaced by corresponding information:
1635 %F full \"From\" field
1636 %f name, taken from \"From\" field, address if no name
1637 %T full \"To\" field
1638 %t first name in \"To\" field, address if no name
1639 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1640 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1641 %s subject
1642 %d date
1643 %m message-id.
1645 You may use normal field width specification between the % and the letter.
1646 This is for example useful to limit the length of the subject.
1648 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1649 :group 'org-link-store
1650 :type 'string)
1652 (defcustom org-from-is-user-regexp
1653 (let (r1 r2)
1654 (when (and user-mail-address (not (string= user-mail-address "")))
1655 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1656 (when (and user-full-name (not (string= user-full-name "")))
1657 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1658 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1659 "Regexp matched against the \"From:\" header of an email or usenet message.
1660 It should match if the message is from the user him/herself."
1661 :group 'org-link-store
1662 :type 'regexp)
1664 (defcustom org-context-in-file-links t
1665 "Non-nil means file links from `org-store-link' contain context.
1666 A search string will be added to the file name with :: as separator and
1667 used to find the context when the link is activated by the command
1668 `org-open-at-point'. When this option is t, the entire active region
1669 will be placed in the search string of the file link. If set to a
1670 positive integer, only the first n lines of context will be stored.
1672 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1673 negates this setting for the duration of the command."
1674 :group 'org-link-store
1675 :type '(choice boolean integer))
1677 (defcustom org-keep-stored-link-after-insertion nil
1678 "Non-nil means keep link in list for entire session.
1680 The command `org-store-link' adds a link pointing to the current
1681 location to an internal list. These links accumulate during a session.
1682 The command `org-insert-link' can be used to insert links into any
1683 Org-mode file (offering completion for all stored links). When this
1684 option is nil, every link which has been inserted once using \\[org-insert-link]
1685 will be removed from the list, to make completing the unused links
1686 more efficient."
1687 :group 'org-link-store
1688 :type 'boolean)
1690 (defgroup org-link-follow nil
1691 "Options concerning following links in Org-mode."
1692 :tag "Org Follow Link"
1693 :group 'org-link)
1695 (defcustom org-link-translation-function nil
1696 "Function to translate links with different syntax to Org syntax.
1697 This can be used to translate links created for example by the Planner
1698 or emacs-wiki packages to Org syntax.
1699 The function must accept two parameters, a TYPE containing the link
1700 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1701 which is everything after the link protocol. It should return a cons
1702 with possibly modified values of type and path.
1703 Org contains a function for this, so if you set this variable to
1704 `org-translate-link-from-planner', you should be able follow many
1705 links created by planner."
1706 :group 'org-link-follow
1707 :type '(choice (const nil) (function)))
1709 (defcustom org-follow-link-hook nil
1710 "Hook that is run after a link has been followed."
1711 :group 'org-link-follow
1712 :type 'hook)
1714 (defcustom org-tab-follows-link nil
1715 "Non-nil means on links TAB will follow the link.
1716 Needs to be set before org.el is loaded.
1717 This really should not be used, it does not make sense, and the
1718 implementation is bad."
1719 :group 'org-link-follow
1720 :type 'boolean)
1722 (defcustom org-return-follows-link nil
1723 "Non-nil means on links RET will follow the link.
1724 In tables, the special behavior of RET has precedence."
1725 :group 'org-link-follow
1726 :type 'boolean)
1728 (defcustom org-mouse-1-follows-link
1729 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1730 "Non-nil means mouse-1 on a link will follow the link.
1731 A longer mouse click will still set point. Does not work on XEmacs.
1732 Needs to be set before org.el is loaded."
1733 :group 'org-link-follow
1734 :type 'boolean)
1736 (defcustom org-mark-ring-length 4
1737 "Number of different positions to be recorded in the ring.
1738 Changing this requires a restart of Emacs to work correctly."
1739 :group 'org-link-follow
1740 :type 'integer)
1742 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1743 "Non-nil means internal links in Org files must exactly match a headline.
1744 When nil, the link search tries to match a phrase with all words
1745 in the search text."
1746 :group 'org-link-follow
1747 :version "24.1"
1748 :type '(choice
1749 (const :tag "Use fuzzy text search" nil)
1750 (const :tag "Match only exact headline" t)
1751 (const :tag "Match exact headline or query to create it"
1752 query-to-create)))
1754 (defcustom org-link-frame-setup
1755 '((vm . vm-visit-folder-other-frame)
1756 (vm-imap . vm-visit-imap-folder-other-frame)
1757 (gnus . org-gnus-no-new-news)
1758 (file . find-file-other-window)
1759 (wl . wl-other-frame))
1760 "Setup the frame configuration for following links.
1761 When following a link with Emacs, it may often be useful to display
1762 this link in another window or frame. This variable can be used to
1763 set this up for the different types of links.
1764 For VM, use any of
1765 `vm-visit-folder'
1766 `vm-visit-folder-other-window'
1767 `vm-visit-folder-other-frame'
1768 For Gnus, use any of
1769 `gnus'
1770 `gnus-other-frame'
1771 `org-gnus-no-new-news'
1772 For FILE, use any of
1773 `find-file'
1774 `find-file-other-window'
1775 `find-file-other-frame'
1776 For Wanderlust use any of
1777 `wl'
1778 `wl-other-frame'
1779 For the calendar, use the variable `calendar-setup'.
1780 For BBDB, it is currently only possible to display the matches in
1781 another window."
1782 :group 'org-link-follow
1783 :type '(list
1784 (cons (const vm)
1785 (choice
1786 (const vm-visit-folder)
1787 (const vm-visit-folder-other-window)
1788 (const vm-visit-folder-other-frame)))
1789 (cons (const vm-imap)
1790 (choice
1791 (const vm-visit-imap-folder)
1792 (const vm-visit-imap-folder-other-window)
1793 (const vm-visit-imap-folder-other-frame)))
1794 (cons (const gnus)
1795 (choice
1796 (const gnus)
1797 (const gnus-other-frame)
1798 (const org-gnus-no-new-news)))
1799 (cons (const file)
1800 (choice
1801 (const find-file)
1802 (const find-file-other-window)
1803 (const find-file-other-frame)))
1804 (cons (const wl)
1805 (choice
1806 (const wl)
1807 (const wl-other-frame)))))
1809 (defcustom org-display-internal-link-with-indirect-buffer nil
1810 "Non-nil means use indirect buffer to display infile links.
1811 Activating internal links (from one location in a file to another location
1812 in the same file) normally just jumps to the location. When the link is
1813 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1814 is displayed in
1815 another window. When this option is set, the other window actually displays
1816 an indirect buffer clone of the current buffer, to avoid any visibility
1817 changes to the current buffer."
1818 :group 'org-link-follow
1819 :type 'boolean)
1821 (defcustom org-open-non-existing-files nil
1822 "Non-nil means `org-open-file' will open non-existing files.
1823 When nil, an error will be generated.
1824 This variable applies only to external applications because they
1825 might choke on non-existing files. If the link is to a file that
1826 will be opened in Emacs, the variable is ignored."
1827 :group 'org-link-follow
1828 :type 'boolean)
1830 (defcustom org-open-directory-means-index-dot-org nil
1831 "Non-nil means a link to a directory really means to index.org.
1832 When nil, following a directory link will run dired or open a finder/explorer
1833 window on that directory."
1834 :group 'org-link-follow
1835 :type 'boolean)
1837 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1838 "Function and arguments to call for following mailto links.
1839 This is a list with the first element being a Lisp function, and the
1840 remaining elements being arguments to the function. In string arguments,
1841 %a will be replaced by the address, and %s will be replaced by the subject
1842 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1843 :group 'org-link-follow
1844 :type '(choice
1845 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1846 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1847 (const :tag "message-mail" (message-mail "%a" "%s"))
1848 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1850 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1851 "Non-nil means ask for confirmation before executing shell links.
1852 Shell links can be dangerous: just think about a link
1854 [[shell:rm -rf ~/*][Google Search]]
1856 This link would show up in your Org-mode document as \"Google Search\",
1857 but really it would remove your entire home directory.
1858 Therefore we advise against setting this variable to nil.
1859 Just change it to `y-or-n-p' if you want to confirm with a
1860 single keystroke rather than having to type \"yes\"."
1861 :group 'org-link-follow
1862 :type '(choice
1863 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1864 (const :tag "with y-or-n (faster)" y-or-n-p)
1865 (const :tag "no confirmation (dangerous)" nil)))
1866 (put 'org-confirm-shell-link-function
1867 'safe-local-variable
1868 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1870 (defcustom org-confirm-shell-link-not-regexp ""
1871 "A regexp to skip confirmation for shell links."
1872 :group 'org-link-follow
1873 :version "24.1"
1874 :type 'regexp)
1876 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1877 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1878 Elisp links can be dangerous: just think about a link
1880 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1882 This link would show up in your Org-mode document as \"Google Search\",
1883 but really it would remove your entire home directory.
1884 Therefore we advise against setting this variable to nil.
1885 Just change it to `y-or-n-p' if you want to confirm with a
1886 single keystroke rather than having to type \"yes\"."
1887 :group 'org-link-follow
1888 :type '(choice
1889 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1890 (const :tag "with y-or-n (faster)" y-or-n-p)
1891 (const :tag "no confirmation (dangerous)" nil)))
1892 (put 'org-confirm-shell-link-function
1893 'safe-local-variable
1894 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1896 (defcustom org-confirm-elisp-link-not-regexp ""
1897 "A regexp to skip confirmation for Elisp links."
1898 :group 'org-link-follow
1899 :version "24.1"
1900 :type 'regexp)
1902 (defconst org-file-apps-defaults-gnu
1903 '((remote . emacs)
1904 (system . mailcap)
1905 (t . mailcap))
1906 "Default file applications on a UNIX or GNU/Linux system.
1907 See `org-file-apps'.")
1909 (defconst org-file-apps-defaults-macosx
1910 '((remote . emacs)
1911 (t . "open %s")
1912 (system . "open %s")
1913 ("ps.gz" . "gv %s")
1914 ("eps.gz" . "gv %s")
1915 ("dvi" . "xdvi %s")
1916 ("fig" . "xfig %s"))
1917 "Default file applications on a MacOS X system.
1918 The system \"open\" is known as a default, but we use X11 applications
1919 for some files for which the OS does not have a good default.
1920 See `org-file-apps'.")
1922 (defconst org-file-apps-defaults-windowsnt
1923 (list
1924 '(remote . emacs)
1925 (cons t
1926 (list (if (featurep 'xemacs)
1927 'mswindows-shell-execute
1928 'w32-shell-execute)
1929 "open" 'file))
1930 (cons 'system
1931 (list (if (featurep 'xemacs)
1932 'mswindows-shell-execute
1933 'w32-shell-execute)
1934 "open" 'file)))
1935 "Default file applications on a Windows NT system.
1936 The system \"open\" is used for most files.
1937 See `org-file-apps'.")
1939 (defcustom org-file-apps
1940 '((auto-mode . emacs)
1941 ("\\.mm\\'" . default)
1942 ("\\.x?html?\\'" . default)
1943 ("\\.pdf\\'" . default))
1944 "External applications for opening `file:path' items in a document.
1945 Org-mode uses system defaults for different file types, but
1946 you can use this variable to set the application for a given file
1947 extension. The entries in this list are cons cells where the car identifies
1948 files and the cdr the corresponding command. Possible values for the
1949 file identifier are
1950 \"string\" A string as a file identifier can be interpreted in different
1951 ways, depending on its contents:
1953 - Alphanumeric characters only:
1954 Match links with this file extension.
1955 Example: (\"pdf\" . \"evince %s\")
1956 to open PDFs with evince.
1958 - Regular expression: Match links where the
1959 filename matches the regexp. If you want to
1960 use groups here, use shy groups.
1962 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1963 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1964 to open *.html and *.xhtml with firefox.
1966 - Regular expression which contains (non-shy) groups:
1967 Match links where the whole link, including \"::\", and
1968 anything after that, matches the regexp.
1969 In a custom command string, %1, %2, etc. are replaced with
1970 the parts of the link that were matched by the groups.
1971 For backwards compatibility, if a command string is given
1972 that does not use any of the group matches, this case is
1973 handled identically to the second one (i.e. match against
1974 file name only).
1975 In a custom lisp form, you can access the group matches with
1976 (match-string n link).
1978 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1979 to open [[file:document.pdf::5]] with evince at page 5.
1981 `directory' Matches a directory
1982 `remote' Matches a remote file, accessible through tramp or efs.
1983 Remote files most likely should be visited through Emacs
1984 because external applications cannot handle such paths.
1985 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1986 so all files Emacs knows how to handle. Using this with
1987 command `emacs' will open most files in Emacs. Beware that this
1988 will also open html files inside Emacs, unless you add
1989 (\"html\" . default) to the list as well.
1990 t Default for files not matched by any of the other options.
1991 `system' The system command to open files, like `open' on Windows
1992 and Mac OS X, and mailcap under GNU/Linux. This is the command
1993 that will be selected if you call `C-c C-o' with a double
1994 \\[universal-argument] \\[universal-argument] prefix.
1996 Possible values for the command are:
1997 `emacs' The file will be visited by the current Emacs process.
1998 `default' Use the default application for this file type, which is the
1999 association for t in the list, most likely in the system-specific
2000 part.
2001 This can be used to overrule an unwanted setting in the
2002 system-specific variable.
2003 `system' Use the system command for opening files, like \"open\".
2004 This command is specified by the entry whose car is `system'.
2005 Most likely, the system-specific version of this variable
2006 does define this command, but you can overrule/replace it
2007 here.
2008 string A command to be executed by a shell; %s will be replaced
2009 by the path to the file.
2010 sexp A Lisp form which will be evaluated. The file path will
2011 be available in the Lisp variable `file'.
2012 For more examples, see the system specific constants
2013 `org-file-apps-defaults-macosx'
2014 `org-file-apps-defaults-windowsnt'
2015 `org-file-apps-defaults-gnu'."
2016 :group 'org-link-follow
2017 :type '(repeat
2018 (cons (choice :value ""
2019 (string :tag "Extension")
2020 (const :tag "System command to open files" system)
2021 (const :tag "Default for unrecognized files" t)
2022 (const :tag "Remote file" remote)
2023 (const :tag "Links to a directory" directory)
2024 (const :tag "Any files that have Emacs modes"
2025 auto-mode))
2026 (choice :value ""
2027 (const :tag "Visit with Emacs" emacs)
2028 (const :tag "Use default" default)
2029 (const :tag "Use the system command" system)
2030 (string :tag "Command")
2031 (sexp :tag "Lisp form")))))
2033 (defcustom org-doi-server-url "http://dx.doi.org/"
2034 "The URL of the DOI server."
2035 :type 'string
2036 :version "24.3"
2037 :group 'org-link-follow)
2039 (defgroup org-refile nil
2040 "Options concerning refiling entries in Org-mode."
2041 :tag "Org Refile"
2042 :group 'org)
2044 (defcustom org-directory "~/org"
2045 "Directory with org files.
2046 This is just a default location to look for Org files. There is no need
2047 at all to put your files into this directory. It is only used in the
2048 following situations:
2050 1. When a capture template specifies a target file that is not an
2051 absolute path. The path will then be interpreted relative to
2052 `org-directory'
2053 2. When a capture note is filed away in an interactive way (when exiting the
2054 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2055 with `org-directory' as the default path."
2056 :group 'org-refile
2057 :group 'org-capture
2058 :type 'directory)
2060 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2061 "Default target for storing notes.
2062 Used as a fall back file for org-capture.el, for templates that
2063 do not specify a target file."
2064 :group 'org-refile
2065 :group 'org-capture
2066 :type '(choice
2067 (const :tag "Default from remember-data-file" nil)
2068 file))
2070 (defcustom org-goto-interface 'outline
2071 "The default interface to be used for `org-goto'.
2072 Allowed values are:
2073 outline The interface shows an outline of the relevant file
2074 and the correct heading is found by moving through
2075 the outline or by searching with incremental search.
2076 outline-path-completion Headlines in the current buffer are offered via
2077 completion. This is the interface also used by
2078 the refile command."
2079 :group 'org-refile
2080 :type '(choice
2081 (const :tag "Outline" outline)
2082 (const :tag "Outline-path-completion" outline-path-completion)))
2084 (defcustom org-goto-max-level 5
2085 "Maximum target level when running `org-goto' with refile interface."
2086 :group 'org-refile
2087 :type 'integer)
2089 (defcustom org-reverse-note-order nil
2090 "Non-nil means store new notes at the beginning of a file or entry.
2091 When nil, new notes will be filed to the end of a file or entry.
2092 This can also be a list with cons cells of regular expressions that
2093 are matched against file names, and values."
2094 :group 'org-capture
2095 :group 'org-refile
2096 :type '(choice
2097 (const :tag "Reverse always" t)
2098 (const :tag "Reverse never" nil)
2099 (repeat :tag "By file name regexp"
2100 (cons regexp boolean))))
2102 (defcustom org-log-refile nil
2103 "Information to record when a task is refiled.
2105 Possible values are:
2107 nil Don't add anything
2108 time Add a time stamp to the task
2109 note Prompt for a note and add it with template `org-log-note-headings'
2111 This option can also be set with on a per-file-basis with
2113 #+STARTUP: nologrefile
2114 #+STARTUP: logrefile
2115 #+STARTUP: lognoterefile
2117 You can have local logging settings for a subtree by setting the LOGGING
2118 property to one or more of these keywords.
2120 When bulk-refiling from the agenda, the value `note' is forbidden and
2121 will temporarily be changed to `time'."
2122 :group 'org-refile
2123 :group 'org-progress
2124 :version "24.1"
2125 :type '(choice
2126 (const :tag "No logging" nil)
2127 (const :tag "Record timestamp" time)
2128 (const :tag "Record timestamp with note." note)))
2130 (defcustom org-refile-targets nil
2131 "Targets for refiling entries with \\[org-refile].
2132 This is a list of cons cells. Each cell contains:
2133 - a specification of the files to be considered, either a list of files,
2134 or a symbol whose function or variable value will be used to retrieve
2135 a file name or a list of file names. If you use `org-agenda-files' for
2136 that, all agenda files will be scanned for targets. Nil means consider
2137 headings in the current buffer.
2138 - A specification of how to find candidate refile targets. This may be
2139 any of:
2140 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2141 This tag has to be present in all target headlines, inheritance will
2142 not be considered.
2143 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2144 todo keyword.
2145 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2146 headlines that are refiling targets.
2147 - a cons cell (:level . N). Any headline of level N is considered a target.
2148 Note that, when `org-odd-levels-only' is set, level corresponds to
2149 order in hierarchy, not to the number of stars.
2150 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2151 Note that, when `org-odd-levels-only' is set, level corresponds to
2152 order in hierarchy, not to the number of stars.
2154 Each element of this list generates a set of possible targets.
2155 The union of these sets is presented (with completion) to
2156 the user by `org-refile'.
2158 You can set the variable `org-refile-target-verify-function' to a function
2159 to verify each headline found by the simple criteria above.
2161 When this variable is nil, all top-level headlines in the current buffer
2162 are used, equivalent to the value `((nil . (:level . 1))'."
2163 :group 'org-refile
2164 :type '(repeat
2165 (cons
2166 (choice :value org-agenda-files
2167 (const :tag "All agenda files" org-agenda-files)
2168 (const :tag "Current buffer" nil)
2169 (function) (variable) (file))
2170 (choice :tag "Identify target headline by"
2171 (cons :tag "Specific tag" (const :value :tag) (string))
2172 (cons :tag "TODO keyword" (const :value :todo) (string))
2173 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2174 (cons :tag "Level number" (const :value :level) (integer))
2175 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2177 (defcustom org-refile-target-verify-function nil
2178 "Function to verify if the headline at point should be a refile target.
2179 The function will be called without arguments, with point at the
2180 beginning of the headline. It should return t and leave point
2181 where it is if the headline is a valid target for refiling.
2183 If the target should not be selected, the function must return nil.
2184 In addition to this, it may move point to a place from where the search
2185 should be continued. For example, the function may decide that the entire
2186 subtree of the current entry should be excluded and move point to the end
2187 of the subtree."
2188 :group 'org-refile
2189 :type '(choice
2190 (const nil)
2191 (function)))
2193 (defcustom org-refile-use-cache nil
2194 "Non-nil means cache refile targets to speed up the process.
2195 The cache for a particular file will be updated automatically when
2196 the buffer has been killed, or when any of the marker used for flagging
2197 refile targets no longer points at a live buffer.
2198 If you have added new entries to a buffer that might themselves be targets,
2199 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2200 find that easier, `C-u C-u C-u C-c C-w'."
2201 :group 'org-refile
2202 :version "24.1"
2203 :type 'boolean)
2205 (defcustom org-refile-use-outline-path nil
2206 "Non-nil means provide refile targets as paths.
2207 So a level 3 headline will be available as level1/level2/level3.
2209 When the value is `file', also include the file name (without directory)
2210 into the path. In this case, you can also stop the completion after
2211 the file name, to get entries inserted as top level in the file.
2213 When `full-file-path', include the full file path."
2214 :group 'org-refile
2215 :type '(choice
2216 (const :tag "Not" nil)
2217 (const :tag "Yes" t)
2218 (const :tag "Start with file name" file)
2219 (const :tag "Start with full file path" full-file-path)))
2221 (defcustom org-outline-path-complete-in-steps t
2222 "Non-nil means complete the outline path in hierarchical steps.
2223 When Org-mode uses the refile interface to select an outline path
2224 \(see variable `org-refile-use-outline-path'), the completion of
2225 the path can be done is a single go, or if can be done in steps down
2226 the headline hierarchy. Going in steps is probably the best if you
2227 do not use a special completion package like `ido' or `icicles'.
2228 However, when using these packages, going in one step can be very
2229 fast, while still showing the whole path to the entry."
2230 :group 'org-refile
2231 :type 'boolean)
2233 (defcustom org-refile-allow-creating-parent-nodes nil
2234 "Non-nil means allow to create new nodes as refile targets.
2235 New nodes are then created by adding \"/new node name\" to the completion
2236 of an existing node. When the value of this variable is `confirm',
2237 new node creation must be confirmed by the user (recommended)
2238 When nil, the completion must match an existing entry.
2240 Note that, if the new heading is not seen by the criteria
2241 listed in `org-refile-targets', multiple instances of the same
2242 heading would be created by trying again to file under the new
2243 heading."
2244 :group 'org-refile
2245 :type '(choice
2246 (const :tag "Never" nil)
2247 (const :tag "Always" t)
2248 (const :tag "Prompt for confirmation" confirm)))
2250 (defcustom org-refile-active-region-within-subtree nil
2251 "Non-nil means also refile active region within a subtree.
2253 By default `org-refile' doesn't allow refiling regions if they
2254 don't contain a set of subtrees, but it might be convenient to
2255 do so sometimes: in that case, the first line of the region is
2256 converted to a headline before refiling."
2257 :group 'org-refile
2258 :version "24.1"
2259 :type 'boolean)
2261 (defgroup org-todo nil
2262 "Options concerning TODO items in Org-mode."
2263 :tag "Org TODO"
2264 :group 'org)
2266 (defgroup org-progress nil
2267 "Options concerning Progress logging in Org-mode."
2268 :tag "Org Progress"
2269 :group 'org-time)
2271 (defvar org-todo-interpretation-widgets
2272 '((:tag "Sequence (cycling hits every state)" sequence)
2273 (:tag "Type (cycling directly to DONE)" type))
2274 "The available interpretation symbols for customizing `org-todo-keywords'.
2275 Interested libraries should add to this list.")
2277 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2278 "List of TODO entry keyword sequences and their interpretation.
2279 \\<org-mode-map>This is a list of sequences.
2281 Each sequence starts with a symbol, either `sequence' or `type',
2282 indicating if the keywords should be interpreted as a sequence of
2283 action steps, or as different types of TODO items. The first
2284 keywords are states requiring action - these states will select a headline
2285 for inclusion into the global TODO list Org-mode produces. If one of
2286 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2287 signify that no further action is necessary. If \"|\" is not found,
2288 the last keyword is treated as the only DONE state of the sequence.
2290 The command \\[org-todo] cycles an entry through these states, and one
2291 additional state where no keyword is present. For details about this
2292 cycling, see the manual.
2294 TODO keywords and interpretation can also be set on a per-file basis with
2295 the special #+SEQ_TODO and #+TYP_TODO lines.
2297 Each keyword can optionally specify a character for fast state selection
2298 \(in combination with the variable `org-use-fast-todo-selection')
2299 and specifiers for state change logging, using the same syntax that
2300 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2301 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2302 indicates to record a time stamp each time this state is selected.
2304 Each keyword may also specify if a timestamp or a note should be
2305 recorded when entering or leaving the state, by adding additional
2306 characters in the parenthesis after the keyword. This looks like this:
2307 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2308 record only the time of the state change. With X and Y being either
2309 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2310 Y when leaving the state if and only if the *target* state does not
2311 define X. You may omit any of the fast-selection key or X or /Y,
2312 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2314 For backward compatibility, this variable may also be just a list
2315 of keywords. In this case the interpretation (sequence or type) will be
2316 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2317 :group 'org-todo
2318 :group 'org-keywords
2319 :type '(choice
2320 (repeat :tag "Old syntax, just keywords"
2321 (string :tag "Keyword"))
2322 (repeat :tag "New syntax"
2323 (cons
2324 (choice
2325 :tag "Interpretation"
2326 ;;Quick and dirty way to see
2327 ;;`org-todo-interpretations'. This takes the
2328 ;;place of item arguments
2329 :convert-widget
2330 (lambda (widget)
2331 (widget-put widget
2332 :args (mapcar
2333 #'(lambda (x)
2334 (widget-convert
2335 (cons 'const x)))
2336 org-todo-interpretation-widgets))
2337 widget))
2338 (repeat
2339 (string :tag "Keyword"))))))
2341 (defvar org-todo-keywords-1 nil
2342 "All TODO and DONE keywords active in a buffer.")
2343 (make-variable-buffer-local 'org-todo-keywords-1)
2344 (defvar org-todo-keywords-for-agenda nil)
2345 (defvar org-done-keywords-for-agenda nil)
2346 (defvar org-drawers-for-agenda nil)
2347 (defvar org-todo-keyword-alist-for-agenda nil)
2348 (defvar org-tag-alist-for-agenda nil
2349 "Alist of all tags from all agenda files.")
2350 (defvar org-tag-groups-alist-for-agenda nil
2351 "Alist of all groups tags from all current agenda files.")
2352 (defvar org-tag-groups-alist nil)
2353 (make-variable-buffer-local 'org-tag-groups-alist)
2354 (defvar org-agenda-contributing-files nil)
2355 (defvar org-not-done-keywords nil)
2356 (make-variable-buffer-local 'org-not-done-keywords)
2357 (defvar org-done-keywords nil)
2358 (make-variable-buffer-local 'org-done-keywords)
2359 (defvar org-todo-heads nil)
2360 (make-variable-buffer-local 'org-todo-heads)
2361 (defvar org-todo-sets nil)
2362 (make-variable-buffer-local 'org-todo-sets)
2363 (defvar org-todo-log-states nil)
2364 (make-variable-buffer-local 'org-todo-log-states)
2365 (defvar org-todo-kwd-alist nil)
2366 (make-variable-buffer-local 'org-todo-kwd-alist)
2367 (defvar org-todo-key-alist nil)
2368 (make-variable-buffer-local 'org-todo-key-alist)
2369 (defvar org-todo-key-trigger nil)
2370 (make-variable-buffer-local 'org-todo-key-trigger)
2372 (defcustom org-todo-interpretation 'sequence
2373 "Controls how TODO keywords are interpreted.
2374 This variable is in principle obsolete and is only used for
2375 backward compatibility, if the interpretation of todo keywords is
2376 not given already in `org-todo-keywords'. See that variable for
2377 more information."
2378 :group 'org-todo
2379 :group 'org-keywords
2380 :type '(choice (const sequence)
2381 (const type)))
2383 (defcustom org-use-fast-todo-selection t
2384 "Non-nil means use the fast todo selection scheme with C-c C-t.
2385 This variable describes if and under what circumstances the cycling
2386 mechanism for TODO keywords will be replaced by a single-key, direct
2387 selection scheme.
2389 When nil, fast selection is never used.
2391 When the symbol `prefix', it will be used when `org-todo' is called
2392 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2393 `C-u t' in an agenda buffer.
2395 When t, fast selection is used by default. In this case, the prefix
2396 argument forces cycling instead.
2398 In all cases, the special interface is only used if access keys have
2399 actually been assigned by the user, i.e. if keywords in the configuration
2400 are followed by a letter in parenthesis, like TODO(t)."
2401 :group 'org-todo
2402 :type '(choice
2403 (const :tag "Never" nil)
2404 (const :tag "By default" t)
2405 (const :tag "Only with C-u C-c C-t" prefix)))
2407 (defcustom org-provide-todo-statistics t
2408 "Non-nil means update todo statistics after insert and toggle.
2409 ALL-HEADLINES means update todo statistics by including headlines
2410 with no TODO keyword as well, counting them as not done.
2411 A list of TODO keywords means the same, but skip keywords that are
2412 not in this list.
2414 When this is set, todo statistics is updated in the parent of the
2415 current entry each time a todo state is changed."
2416 :group 'org-todo
2417 :type '(choice
2418 (const :tag "Yes, only for TODO entries" t)
2419 (const :tag "Yes, including all entries" 'all-headlines)
2420 (repeat :tag "Yes, for TODOs in this list"
2421 (string :tag "TODO keyword"))
2422 (other :tag "No TODO statistics" nil)))
2424 (defcustom org-hierarchical-todo-statistics t
2425 "Non-nil means TODO statistics covers just direct children.
2426 When nil, all entries in the subtree are considered.
2427 This has only an effect if `org-provide-todo-statistics' is set.
2428 To set this to nil for only a single subtree, use a COOKIE_DATA
2429 property and include the word \"recursive\" into the value."
2430 :group 'org-todo
2431 :type 'boolean)
2433 (defcustom org-after-todo-state-change-hook nil
2434 "Hook which is run after the state of a TODO item was changed.
2435 The new state (a string with a TODO keyword, or nil) is available in the
2436 Lisp variable `org-state'."
2437 :group 'org-todo
2438 :type 'hook)
2440 (defvar org-blocker-hook nil
2441 "Hook for functions that are allowed to block a state change.
2443 Functions in this hook should not modify the buffer.
2444 Each function gets as its single argument a property list,
2445 see `org-trigger-hook' for more information about this list.
2447 If any of the functions in this hook returns nil, the state change
2448 is blocked.")
2450 (defvar org-trigger-hook nil
2451 "Hook for functions that are triggered by a state change.
2453 Each function gets as its single argument a property list with at
2454 least the following elements:
2456 (:type type-of-change :position pos-at-entry-start
2457 :from old-state :to new-state)
2459 Depending on the type, more properties may be present.
2461 This mechanism is currently implemented for:
2463 TODO state changes
2464 ------------------
2465 :type todo-state-change
2466 :from previous state (keyword as a string), or nil, or a symbol
2467 'todo' or 'done', to indicate the general type of state.
2468 :to new state, like in :from")
2470 (defcustom org-enforce-todo-dependencies nil
2471 "Non-nil means undone TODO entries will block switching the parent to DONE.
2472 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2473 be blocked if any prior sibling is not yet done.
2474 Finally, if the parent is blocked because of ordered siblings of its own,
2475 the child will also be blocked."
2476 :set (lambda (var val)
2477 (set var val)
2478 (if val
2479 (add-hook 'org-blocker-hook
2480 'org-block-todo-from-children-or-siblings-or-parent)
2481 (remove-hook 'org-blocker-hook
2482 'org-block-todo-from-children-or-siblings-or-parent)))
2483 :group 'org-todo
2484 :type 'boolean)
2486 (defcustom org-enforce-todo-checkbox-dependencies nil
2487 "Non-nil means unchecked boxes will block switching the parent to DONE.
2488 When this is nil, checkboxes have no influence on switching TODO states.
2489 When non-nil, you first need to check off all check boxes before the TODO
2490 entry can be switched to DONE.
2491 This variable needs to be set before org.el is loaded, and you need to
2492 restart Emacs after a change to make the change effective. The only way
2493 to change is while Emacs is running is through the customize interface."
2494 :set (lambda (var val)
2495 (set var val)
2496 (if val
2497 (add-hook 'org-blocker-hook
2498 'org-block-todo-from-checkboxes)
2499 (remove-hook 'org-blocker-hook
2500 'org-block-todo-from-checkboxes)))
2501 :group 'org-todo
2502 :type 'boolean)
2504 (defcustom org-treat-insert-todo-heading-as-state-change nil
2505 "Non-nil means inserting a TODO heading is treated as state change.
2506 So when the command \\[org-insert-todo-heading] is used, state change
2507 logging will apply if appropriate. When nil, the new TODO item will
2508 be inserted directly, and no logging will take place."
2509 :group 'org-todo
2510 :type 'boolean)
2512 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2513 "Non-nil means switching TODO states with S-cursor counts as state change.
2514 This is the default behavior. However, setting this to nil allows a
2515 convenient way to select a TODO state and bypass any logging associated
2516 with that."
2517 :group 'org-todo
2518 :type 'boolean)
2520 (defcustom org-todo-state-tags-triggers nil
2521 "Tag changes that should be triggered by TODO state changes.
2522 This is a list. Each entry is
2524 (state-change (tag . flag) .......)
2526 State-change can be a string with a state, and empty string to indicate the
2527 state that has no TODO keyword, or it can be one of the symbols `todo'
2528 or `done', meaning any not-done or done state, respectively."
2529 :group 'org-todo
2530 :group 'org-tags
2531 :type '(repeat
2532 (cons (choice :tag "When changing to"
2533 (const :tag "Not-done state" todo)
2534 (const :tag "Done state" done)
2535 (string :tag "State"))
2536 (repeat
2537 (cons :tag "Tag action"
2538 (string :tag "Tag")
2539 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2541 (defcustom org-log-done nil
2542 "Information to record when a task moves to the DONE state.
2544 Possible values are:
2546 nil Don't add anything, just change the keyword
2547 time Add a time stamp to the task
2548 note Prompt for a note and add it with template `org-log-note-headings'
2550 This option can also be set with on a per-file-basis with
2552 #+STARTUP: nologdone
2553 #+STARTUP: logdone
2554 #+STARTUP: lognotedone
2556 You can have local logging settings for a subtree by setting the LOGGING
2557 property to one or more of these keywords."
2558 :group 'org-todo
2559 :group 'org-progress
2560 :type '(choice
2561 (const :tag "No logging" nil)
2562 (const :tag "Record CLOSED timestamp" time)
2563 (const :tag "Record CLOSED timestamp with note." note)))
2565 ;; Normalize old uses of org-log-done.
2566 (cond
2567 ((eq org-log-done t) (setq org-log-done 'time))
2568 ((and (listp org-log-done) (memq 'done org-log-done))
2569 (setq org-log-done 'note)))
2571 (defcustom org-log-reschedule nil
2572 "Information to record when the scheduling date of a tasks is modified.
2574 Possible values are:
2576 nil Don't add anything, just change the date
2577 time Add a time stamp to the task
2578 note Prompt for a note and add it with template `org-log-note-headings'
2580 This option can also be set with on a per-file-basis with
2582 #+STARTUP: nologreschedule
2583 #+STARTUP: logreschedule
2584 #+STARTUP: lognotereschedule"
2585 :group 'org-todo
2586 :group 'org-progress
2587 :type '(choice
2588 (const :tag "No logging" nil)
2589 (const :tag "Record timestamp" time)
2590 (const :tag "Record timestamp with note." note)))
2592 (defcustom org-log-redeadline nil
2593 "Information to record when the deadline date of a tasks is modified.
2595 Possible values are:
2597 nil Don't add anything, just change the date
2598 time Add a time stamp to the task
2599 note Prompt for a note and add it with template `org-log-note-headings'
2601 This option can also be set with on a per-file-basis with
2603 #+STARTUP: nologredeadline
2604 #+STARTUP: logredeadline
2605 #+STARTUP: lognoteredeadline
2607 You can have local logging settings for a subtree by setting the LOGGING
2608 property to one or more of these keywords."
2609 :group 'org-todo
2610 :group 'org-progress
2611 :type '(choice
2612 (const :tag "No logging" nil)
2613 (const :tag "Record timestamp" time)
2614 (const :tag "Record timestamp with note." note)))
2616 (defcustom org-log-note-clock-out nil
2617 "Non-nil means record a note when clocking out of an item.
2618 This can also be configured on a per-file basis by adding one of
2619 the following lines anywhere in the buffer:
2621 #+STARTUP: lognoteclock-out
2622 #+STARTUP: nolognoteclock-out"
2623 :group 'org-todo
2624 :group 'org-progress
2625 :type 'boolean)
2627 (defcustom org-log-done-with-time t
2628 "Non-nil means the CLOSED time stamp will contain date and time.
2629 When nil, only the date will be recorded."
2630 :group 'org-progress
2631 :type 'boolean)
2633 (defcustom org-log-note-headings
2634 '((done . "CLOSING NOTE %t")
2635 (state . "State %-12s from %-12S %t")
2636 (note . "Note taken on %t")
2637 (reschedule . "Rescheduled from %S on %t")
2638 (delschedule . "Not scheduled, was %S on %t")
2639 (redeadline . "New deadline from %S on %t")
2640 (deldeadline . "Removed deadline, was %S on %t")
2641 (refile . "Refiled on %t")
2642 (clock-out . ""))
2643 "Headings for notes added to entries.
2644 The value is an alist, with the car being a symbol indicating the note
2645 context, and the cdr is the heading to be used. The heading may also be the
2646 empty string.
2647 %t in the heading will be replaced by a time stamp.
2648 %T will be an active time stamp instead the default inactive one
2649 %d will be replaced by a short-format time stamp.
2650 %D will be replaced by an active short-format time stamp.
2651 %s will be replaced by the new TODO state, in double quotes.
2652 %S will be replaced by the old TODO state, in double quotes.
2653 %u will be replaced by the user name.
2654 %U will be replaced by the full user name.
2656 In fact, it is not a good idea to change the `state' entry, because
2657 agenda log mode depends on the format of these entries."
2658 :group 'org-todo
2659 :group 'org-progress
2660 :type '(list :greedy t
2661 (cons (const :tag "Heading when closing an item" done) string)
2662 (cons (const :tag
2663 "Heading when changing todo state (todo sequence only)"
2664 state) string)
2665 (cons (const :tag "Heading when just taking a note" note) string)
2666 (cons (const :tag "Heading when clocking out" clock-out) string)
2667 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2668 (cons (const :tag "Heading when rescheduling" reschedule) string)
2669 (cons (const :tag "Heading when changing deadline" redeadline) string)
2670 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2671 (cons (const :tag "Heading when refiling" refile) string)))
2673 (unless (assq 'note org-log-note-headings)
2674 (push '(note . "%t") org-log-note-headings))
2676 (defcustom org-log-into-drawer nil
2677 "Non-nil means insert state change notes and time stamps into a drawer.
2678 When nil, state changes notes will be inserted after the headline and
2679 any scheduling and clock lines, but not inside a drawer.
2681 The value of this variable should be the name of the drawer to use.
2682 LOGBOOK is proposed as the default drawer for this purpose, you can
2683 also set this to a string to define the drawer of your choice.
2685 A value of t is also allowed, representing \"LOGBOOK\".
2687 A value of t or nil can also be set with on a per-file-basis with
2689 #+STARTUP: logdrawer
2690 #+STARTUP: nologdrawer
2692 If this variable is set, `org-log-state-notes-insert-after-drawers'
2693 will be ignored.
2695 You can set the property LOG_INTO_DRAWER to overrule this setting for
2696 a subtree."
2697 :group 'org-todo
2698 :group 'org-progress
2699 :type '(choice
2700 (const :tag "Not into a drawer" nil)
2701 (const :tag "LOGBOOK" t)
2702 (string :tag "Other")))
2704 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2706 (defun org-log-into-drawer ()
2707 "Return the value of `org-log-into-drawer', but let properties overrule.
2708 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2709 used instead of the default value."
2710 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2711 (cond
2712 ((not p) org-log-into-drawer)
2713 ((equal p "nil") nil)
2714 ((equal p "t") "LOGBOOK")
2715 (t p))))
2717 (defcustom org-log-state-notes-insert-after-drawers nil
2718 "Non-nil means insert state change notes after any drawers in entry.
2719 Only the drawers that *immediately* follow the headline and the
2720 deadline/scheduled line are skipped.
2721 When nil, insert notes right after the heading and perhaps the line
2722 with deadline/scheduling if present.
2724 This variable will have no effect if `org-log-into-drawer' is
2725 set."
2726 :group 'org-todo
2727 :group 'org-progress
2728 :type 'boolean)
2730 (defcustom org-log-states-order-reversed t
2731 "Non-nil means the latest state note will be directly after heading.
2732 When nil, the state change notes will be ordered according to time.
2734 This option can also be set with on a per-file-basis with
2736 #+STARTUP: logstatesreversed
2737 #+STARTUP: nologstatesreversed"
2738 :group 'org-todo
2739 :group 'org-progress
2740 :type 'boolean)
2742 (defcustom org-todo-repeat-to-state nil
2743 "The TODO state to which a repeater should return the repeating task.
2744 By default this is the first task in a TODO sequence, or the previous state
2745 in a TODO_TYP set. But you can specify another task here.
2746 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2747 :group 'org-todo
2748 :version "24.1"
2749 :type '(choice (const :tag "Head of sequence" nil)
2750 (string :tag "Specific state")))
2752 (defcustom org-log-repeat 'time
2753 "Non-nil means record moving through the DONE state when triggering repeat.
2754 An auto-repeating task is immediately switched back to TODO when
2755 marked DONE. If you are not logging state changes (by adding \"@\"
2756 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2757 record a closing note, there will be no record of the task moving
2758 through DONE. This variable forces taking a note anyway.
2760 nil Don't force a record
2761 time Record a time stamp
2762 note Prompt for a note and add it with template `org-log-note-headings'
2764 This option can also be set with on a per-file-basis with
2766 #+STARTUP: nologrepeat
2767 #+STARTUP: logrepeat
2768 #+STARTUP: lognoterepeat
2770 You can have local logging settings for a subtree by setting the LOGGING
2771 property to one or more of these keywords."
2772 :group 'org-todo
2773 :group 'org-progress
2774 :type '(choice
2775 (const :tag "Don't force a record" nil)
2776 (const :tag "Force recording the DONE state" time)
2777 (const :tag "Force recording a note with the DONE state" note)))
2780 (defgroup org-priorities nil
2781 "Priorities in Org-mode."
2782 :tag "Org Priorities"
2783 :group 'org-todo)
2785 (defcustom org-enable-priority-commands t
2786 "Non-nil means priority commands are active.
2787 When nil, these commands will be disabled, so that you never accidentally
2788 set a priority."
2789 :group 'org-priorities
2790 :type 'boolean)
2792 (defcustom org-highest-priority ?A
2793 "The highest priority of TODO items. A character like ?A, ?B etc.
2794 Must have a smaller ASCII number than `org-lowest-priority'."
2795 :group 'org-priorities
2796 :type 'character)
2798 (defcustom org-lowest-priority ?C
2799 "The lowest priority of TODO items. A character like ?A, ?B etc.
2800 Must have a larger ASCII number than `org-highest-priority'."
2801 :group 'org-priorities
2802 :type 'character)
2804 (defcustom org-default-priority ?B
2805 "The default priority of TODO items.
2806 This is the priority an item gets if no explicit priority is given.
2807 When starting to cycle on an empty priority the first step in the cycle
2808 depends on `org-priority-start-cycle-with-default'. The resulting first
2809 step priority must not exceed the range from `org-highest-priority' to
2810 `org-lowest-priority' which means that `org-default-priority' has to be
2811 in this range exclusive or inclusive the range boundaries. Else the
2812 first step refuses to set the default and the second will fall back
2813 to (depending on the command used) the highest or lowest priority."
2814 :group 'org-priorities
2815 :type 'character)
2817 (defcustom org-priority-start-cycle-with-default t
2818 "Non-nil means start with default priority when starting to cycle.
2819 When this is nil, the first step in the cycle will be (depending on the
2820 command used) one higher or lower than the default priority.
2821 See also `org-default-priority'."
2822 :group 'org-priorities
2823 :type 'boolean)
2825 (defcustom org-get-priority-function nil
2826 "Function to extract the priority from a string.
2827 The string is normally the headline. If this is nil Org computes the
2828 priority from the priority cookie like [#A] in the headline. It returns
2829 an integer, increasing by 1000 for each priority level.
2830 The user can set a different function here, which should take a string
2831 as an argument and return the numeric priority."
2832 :group 'org-priorities
2833 :version "24.1"
2834 :type '(choice
2835 (const nil)
2836 (function)))
2838 (defgroup org-time nil
2839 "Options concerning time stamps and deadlines in Org-mode."
2840 :tag "Org Time"
2841 :group 'org)
2843 (defcustom org-insert-labeled-timestamps-at-point nil
2844 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2845 When nil, these labeled time stamps are forces into the second line of an
2846 entry, just after the headline. When scheduling from the global TODO list,
2847 the time stamp will always be forced into the second line."
2848 :group 'org-time
2849 :type 'boolean)
2851 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2852 "Formats for `format-time-string' which are used for time stamps.
2853 It is not recommended to change this constant.")
2855 (defcustom org-time-stamp-rounding-minutes '(0 5)
2856 "Number of minutes to round time stamps to.
2857 These are two values, the first applies when first creating a time stamp.
2858 The second applies when changing it with the commands `S-up' and `S-down'.
2859 When changing the time stamp, this means that it will change in steps
2860 of N minutes, as given by the second value.
2862 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2863 numbers should be factors of 60, so for example 5, 10, 15.
2865 When this is larger than 1, you can still force an exact time stamp by using
2866 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2867 and by using a prefix arg to `S-up/down' to specify the exact number
2868 of minutes to shift."
2869 :group 'org-time
2870 :get #'(lambda (var) ; Make sure both elements are there
2871 (if (integerp (default-value var))
2872 (list (default-value var) 5)
2873 (default-value var)))
2874 :type '(list
2875 (integer :tag "when inserting times")
2876 (integer :tag "when modifying times")))
2878 ;; Normalize old customizations of this variable.
2879 (when (integerp org-time-stamp-rounding-minutes)
2880 (setq org-time-stamp-rounding-minutes
2881 (list org-time-stamp-rounding-minutes
2882 org-time-stamp-rounding-minutes)))
2884 (defcustom org-display-custom-times nil
2885 "Non-nil means overlay custom formats over all time stamps.
2886 The formats are defined through the variable `org-time-stamp-custom-formats'.
2887 To turn this on on a per-file basis, insert anywhere in the file:
2888 #+STARTUP: customtime"
2889 :group 'org-time
2890 :set 'set-default
2891 :type 'sexp)
2892 (make-variable-buffer-local 'org-display-custom-times)
2894 (defcustom org-time-stamp-custom-formats
2895 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2896 "Custom formats for time stamps. See `format-time-string' for the syntax.
2897 These are overlaid over the default ISO format if the variable
2898 `org-display-custom-times' is set. Time like %H:%M should be at the
2899 end of the second format. The custom formats are also honored by export
2900 commands, if custom time display is turned on at the time of export."
2901 :group 'org-time
2902 :type 'sexp)
2904 (defun org-time-stamp-format (&optional long inactive)
2905 "Get the right format for a time string."
2906 (let ((f (if long (cdr org-time-stamp-formats)
2907 (car org-time-stamp-formats))))
2908 (if inactive
2909 (concat "[" (substring f 1 -1) "]")
2910 f)))
2912 (defcustom org-time-clocksum-format
2913 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2914 "The format string used when creating CLOCKSUM lines.
2915 This is also used when Org mode generates a time duration.
2917 The value can be a single format string containing two
2918 %-sequences, which will be filled with the number of hours and
2919 minutes in that order.
2921 Alternatively, the value can be a plist associating any of the
2922 keys :years, :months, :weeks, :days, :hours or :minutes with
2923 format strings. The time duration is formatted using only the
2924 time components that are needed and concatenating the results.
2925 If a time unit in absent, it falls back to the next smallest
2926 unit.
2928 The keys :require-years, :require-months, :require-days,
2929 :require-weeks, :require-hours, :require-minutes are also
2930 meaningful. A non-nil value for these keys indicates that the
2931 corresponding time component should always be included, even if
2932 its value is 0.
2935 For example,
2937 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2938 :require-minutes t)
2940 means durations longer than a day will be expressed in days,
2941 hours and minutes, and durations less than a day will always be
2942 expressed in hours and minutes (even for durations less than an
2943 hour).
2945 The value
2947 \(:days \"%dd\" :minutes \"%dm\")
2949 means durations longer than a day will be expressed in days and
2950 minutes, and durations less than a day will be expressed entirely
2951 in minutes (even for durations longer than an hour)."
2952 :group 'org-time
2953 :group 'org-clock
2954 :version "24.4"
2955 :package-version '(Org . "8.0")
2956 :type '(choice (string :tag "Format string")
2957 (set :tag "Plist"
2958 (group :inline t (const :tag "Years" :years)
2959 (string :tag "Format string"))
2960 (group :inline t
2961 (const :tag "Always show years" :require-years)
2962 (const t))
2963 (group :inline t (const :tag "Months" :months)
2964 (string :tag "Format string"))
2965 (group :inline t
2966 (const :tag "Always show months" :require-months)
2967 (const t))
2968 (group :inline t (const :tag "Weeks" :weeks)
2969 (string :tag "Format string"))
2970 (group :inline t
2971 (const :tag "Always show weeks" :require-weeks)
2972 (const t))
2973 (group :inline t (const :tag "Days" :days)
2974 (string :tag "Format string"))
2975 (group :inline t
2976 (const :tag "Always show days" :require-days)
2977 (const t))
2978 (group :inline t (const :tag "Hours" :hours)
2979 (string :tag "Format string"))
2980 (group :inline t
2981 (const :tag "Always show hours" :require-hours)
2982 (const t))
2983 (group :inline t (const :tag "Minutes" :minutes)
2984 (string :tag "Format string"))
2985 (group :inline t
2986 (const :tag "Always show minutes" :require-minutes)
2987 (const t)))))
2989 (defcustom org-time-clocksum-use-fractional nil
2990 "When non-nil, \\[org-clock-display] uses fractional times.
2991 See `org-time-clocksum-format' for more on time clock formats."
2992 :group 'org-time
2993 :group 'org-clock
2994 :version "24.3"
2995 :type 'boolean)
2997 (defcustom org-time-clocksum-use-effort-durations nil
2998 "When non-nil, \\[org-clock-display] uses effort durations.
2999 E.g. by default, one day is considered to be a 8 hours effort,
3000 so a task that has been clocked for 16 hours will be displayed
3001 as during 2 days in the clock display or in the clocktable.
3003 See `org-effort-durations' on how to set effort durations
3004 and `org-time-clocksum-format' for more on time clock formats."
3005 :group 'org-time
3006 :group 'org-clock
3007 :version "24.4"
3008 :package-version '(Org . "8.0")
3009 :type 'boolean)
3011 (defcustom org-time-clocksum-fractional-format "%.2f"
3012 "The format string used when creating CLOCKSUM lines,
3013 or when Org mode generates a time duration, if
3014 `org-time-clocksum-use-fractional' is enabled.
3016 The value can be a single format string containing one
3017 %-sequence, which will be filled with the number of hours as
3018 a float.
3020 Alternatively, the value can be a plist associating any of the
3021 keys :years, :months, :weeks, :days, :hours or :minutes with
3022 a format string. The time duration is formatted using the
3023 largest time unit which gives a non-zero integer part. If all
3024 specified formats have zero integer part, the smallest time unit
3025 is used."
3026 :group 'org-time
3027 :type '(choice (string :tag "Format string")
3028 (set (group :inline t (const :tag "Years" :years)
3029 (string :tag "Format string"))
3030 (group :inline t (const :tag "Months" :months)
3031 (string :tag "Format string"))
3032 (group :inline t (const :tag "Weeks" :weeks)
3033 (string :tag "Format string"))
3034 (group :inline t (const :tag "Days" :days)
3035 (string :tag "Format string"))
3036 (group :inline t (const :tag "Hours" :hours)
3037 (string :tag "Format string"))
3038 (group :inline t (const :tag "Minutes" :minutes)
3039 (string :tag "Format string")))))
3041 (defcustom org-deadline-warning-days 14
3042 "Number of days before expiration during which a deadline becomes active.
3043 This variable governs the display in sparse trees and in the agenda.
3044 When 0 or negative, it means use this number (the absolute value of it)
3045 even if a deadline has a different individual lead time specified.
3047 Custom commands can set this variable in the options section."
3048 :group 'org-time
3049 :group 'org-agenda-daily/weekly
3050 :type 'integer)
3052 (defcustom org-scheduled-delay-days 0
3053 "Number of days before a scheduled item becomes active.
3054 This variable governs the display in sparse trees and in the agenda.
3055 The default value (i.e. 0) means: don't delay scheduled item.
3056 When negative, it means use this number (the absolute value of it)
3057 even if a scheduled item has a different individual delay time
3058 specified.
3060 Custom commands can set this variable in the options section."
3061 :group 'org-time
3062 :group 'org-agenda-daily/weekly
3063 :version "24.4"
3064 :package-version '(Org . "8.0")
3065 :type 'integer)
3067 (defcustom org-read-date-prefer-future t
3068 "Non-nil means assume future for incomplete date input from user.
3069 This affects the following situations:
3070 1. The user gives a month but not a year.
3071 For example, if it is April and you enter \"feb 2\", this will be read
3072 as Feb 2, *next* year. \"May 5\", however, will be this year.
3073 2. The user gives a day, but no month.
3074 For example, if today is the 15th, and you enter \"3\", Org-mode will
3075 read this as the third of *next* month. However, if you enter \"17\",
3076 it will be considered as *this* month.
3078 If you set this variable to the symbol `time', then also the following
3079 will work:
3081 3. If the user gives a time.
3082 If the time is before now, it will be interpreted as tomorrow.
3084 Currently none of this works for ISO week specifications.
3086 When this option is nil, the current day, month and year will always be
3087 used as defaults.
3089 See also `org-agenda-jump-prefer-future'."
3090 :group 'org-time
3091 :type '(choice
3092 (const :tag "Never" nil)
3093 (const :tag "Check month and day" t)
3094 (const :tag "Check month, day, and time" time)))
3096 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3097 "Should the agenda jump command prefer the future for incomplete dates?
3098 The default is to do the same as configured in `org-read-date-prefer-future'.
3099 But you can also set a deviating value here.
3100 This may t or nil, or the symbol `org-read-date-prefer-future'."
3101 :group 'org-agenda
3102 :group 'org-time
3103 :version "24.1"
3104 :type '(choice
3105 (const :tag "Use org-read-date-prefer-future"
3106 org-read-date-prefer-future)
3107 (const :tag "Never" nil)
3108 (const :tag "Always" t)))
3110 (defcustom org-read-date-force-compatible-dates t
3111 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3113 Depending on the system Emacs is running on, certain dates cannot
3114 be represented with the type used internally to represent time.
3115 Dates between 1970-1-1 and 2038-1-1 can always be represented
3116 correctly. Some systems allow for earlier dates, some for later,
3117 some for both. One way to find out it to insert any date into an
3118 Org buffer, putting the cursor on the year and hitting S-up and
3119 S-down to test the range.
3121 When this variable is set to t, the date/time prompt will not let
3122 you specify dates outside the 1970-2037 range, so it is certain that
3123 these dates will work in whatever version of Emacs you are
3124 running, and also that you can move a file from one Emacs implementation
3125 to another. WHenever Org is forcing the year for you, it will display
3126 a message and beep.
3128 When this variable is nil, Org will check if the date is
3129 representable in the specific Emacs implementation you are using.
3130 If not, it will force a year, usually the current year, and beep
3131 to remind you. Currently this setting is not recommended because
3132 the likelihood that you will open your Org files in an Emacs that
3133 has limited date range is not negligible.
3135 A workaround for this problem is to use diary sexp dates for time
3136 stamps outside of this range."
3137 :group 'org-time
3138 :version "24.1"
3139 :type 'boolean)
3141 (defcustom org-read-date-display-live t
3142 "Non-nil means display current interpretation of date prompt live.
3143 This display will be in an overlay, in the minibuffer."
3144 :group 'org-time
3145 :type 'boolean)
3147 (defcustom org-read-date-popup-calendar t
3148 "Non-nil means pop up a calendar when prompting for a date.
3149 In the calendar, the date can be selected with mouse-1. However, the
3150 minibuffer will also be active, and you can simply enter the date as well.
3151 When nil, only the minibuffer will be available."
3152 :group 'org-time
3153 :type 'boolean)
3154 (org-defvaralias 'org-popup-calendar-for-date-prompt
3155 'org-read-date-popup-calendar)
3157 (make-obsolete-variable
3158 'org-read-date-minibuffer-setup-hook
3159 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3160 (defcustom org-read-date-minibuffer-setup-hook nil
3161 "Hook to be used to set up keys for the date/time interface.
3162 Add key definitions to `minibuffer-local-map', which will be a
3163 temporary copy.
3165 WARNING: This option is obsolete, you should use
3166 `org-read-date-minibuffer-local-map' to set up keys."
3167 :group 'org-time
3168 :type 'hook)
3170 (defcustom org-extend-today-until 0
3171 "The hour when your day really ends. Must be an integer.
3172 This has influence for the following applications:
3173 - When switching the agenda to \"today\". It it is still earlier than
3174 the time given here, the day recognized as TODAY is actually yesterday.
3175 - When a date is read from the user and it is still before the time given
3176 here, the current date and time will be assumed to be yesterday, 23:59.
3177 Also, timestamps inserted in capture templates follow this rule.
3179 IMPORTANT: This is a feature whose implementation is and likely will
3180 remain incomplete. Really, it is only here because past midnight seems to
3181 be the favorite working time of John Wiegley :-)"
3182 :group 'org-time
3183 :type 'integer)
3185 (defcustom org-use-effective-time nil
3186 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3187 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3188 \"effective time\" of any timestamps between midnight and 8am will be
3189 23:59 of the previous day."
3190 :group 'org-time
3191 :version "24.1"
3192 :type 'boolean)
3194 (defcustom org-use-last-clock-out-time-as-effective-time nil
3195 "When non-nil, use the last clock out time for `org-todo'.
3196 Note that this option has precedence over the combined use of
3197 `org-use-effective-time' and `org-extend-today-until'."
3198 :group 'org-time
3199 :version "24.4"
3200 :package-version '(Org . "8.0")
3201 :type 'boolean)
3203 (defcustom org-edit-timestamp-down-means-later nil
3204 "Non-nil means S-down will increase the time in a time stamp.
3205 When nil, S-up will increase."
3206 :group 'org-time
3207 :type 'boolean)
3209 (defcustom org-calendar-follow-timestamp-change t
3210 "Non-nil means make the calendar window follow timestamp changes.
3211 When a timestamp is modified and the calendar window is visible, it will be
3212 moved to the new date."
3213 :group 'org-time
3214 :type 'boolean)
3216 (defgroup org-tags nil
3217 "Options concerning tags in Org-mode."
3218 :tag "Org Tags"
3219 :group 'org)
3221 (defcustom org-tag-alist nil
3222 "List of tags allowed in Org-mode files.
3223 When this list is nil, Org-mode will base TAG input on what is already in the
3224 buffer.
3225 The value of this variable is an alist, the car of each entry must be a
3226 keyword as a string, the cdr may be a character that is used to select
3227 that tag through the fast-tag-selection interface.
3228 See the manual for details."
3229 :group 'org-tags
3230 :type '(repeat
3231 (choice
3232 (cons (string :tag "Tag name")
3233 (character :tag "Access char"))
3234 (list :tag "Start radio group"
3235 (const :startgroup)
3236 (option (string :tag "Group description")))
3237 (list :tag "Group tags delimiter"
3238 (const :grouptags))
3239 (list :tag "End radio group"
3240 (const :endgroup)
3241 (option (string :tag "Group description")))
3242 (const :tag "New line" (:newline)))))
3244 (defcustom org-tag-persistent-alist nil
3245 "List of tags that will always appear in all Org-mode files.
3246 This is in addition to any in buffer settings or customizations
3247 of `org-tag-alist'.
3248 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3249 The value of this variable is an alist, the car of each entry must be a
3250 keyword as a string, the cdr may be a character that is used to select
3251 that tag through the fast-tag-selection interface.
3252 See the manual for details.
3253 To disable these tags on a per-file basis, insert anywhere in the file:
3254 #+STARTUP: noptag"
3255 :group 'org-tags
3256 :type '(repeat
3257 (choice
3258 (cons (string :tag "Tag name")
3259 (character :tag "Access char"))
3260 (const :tag "Start radio group" (:startgroup))
3261 (const :tag "Group tags delimiter" (:grouptags))
3262 (const :tag "End radio group" (:endgroup))
3263 (const :tag "New line" (:newline)))))
3265 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3266 "If non-nil, always offer completion for all tags of all agenda files.
3267 Instead of customizing this variable directly, you might want to
3268 set it locally for capture buffers, because there no list of
3269 tags in that file can be created dynamically (there are none).
3271 (add-hook 'org-capture-mode-hook
3272 (lambda ()
3273 (set (make-local-variable
3274 'org-complete-tags-always-offer-all-agenda-tags)
3275 t)))"
3276 :group 'org-tags
3277 :version "24.1"
3278 :type 'boolean)
3280 (defvar org-file-tags nil
3281 "List of tags that can be inherited by all entries in the file.
3282 The tags will be inherited if the variable `org-use-tag-inheritance'
3283 says they should be.
3284 This variable is populated from #+FILETAGS lines.")
3286 (defcustom org-use-fast-tag-selection 'auto
3287 "Non-nil means use fast tag selection scheme.
3288 This is a special interface to select and deselect tags with single keys.
3289 When nil, fast selection is never used.
3290 When the symbol `auto', fast selection is used if and only if selection
3291 characters for tags have been configured, either through the variable
3292 `org-tag-alist' or through a #+TAGS line in the buffer.
3293 When t, fast selection is always used and selection keys are assigned
3294 automatically if necessary."
3295 :group 'org-tags
3296 :type '(choice
3297 (const :tag "Always" t)
3298 (const :tag "Never" nil)
3299 (const :tag "When selection characters are configured" auto)))
3301 (defcustom org-fast-tag-selection-single-key nil
3302 "Non-nil means fast tag selection exits after first change.
3303 When nil, you have to press RET to exit it.
3304 During fast tag selection, you can toggle this flag with `C-c'.
3305 This variable can also have the value `expert'. In this case, the window
3306 displaying the tags menu is not even shown, until you press C-c again."
3307 :group 'org-tags
3308 :type '(choice
3309 (const :tag "No" nil)
3310 (const :tag "Yes" t)
3311 (const :tag "Expert" expert)))
3313 (defvar org-fast-tag-selection-include-todo nil
3314 "Non-nil means fast tags selection interface will also offer TODO states.
3315 This is an undocumented feature, you should not rely on it.")
3317 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3318 "The column to which tags should be indented in a headline.
3319 If this number is positive, it specifies the column. If it is negative,
3320 it means that the tags should be flushright to that column. For example,
3321 -80 works well for a normal 80 character screen.
3322 When 0, place tags directly after headline text, with only one space in
3323 between."
3324 :group 'org-tags
3325 :type 'integer)
3327 (defcustom org-auto-align-tags t
3328 "Non-nil keeps tags aligned when modifying headlines.
3329 Some operations (i.e. demoting) change the length of a headline and
3330 therefore shift the tags around. With this option turned on, after
3331 each such operation the tags are again aligned to `org-tags-column'."
3332 :group 'org-tags
3333 :type 'boolean)
3335 (defcustom org-use-tag-inheritance t
3336 "Non-nil means tags in levels apply also for sublevels.
3337 When nil, only the tags directly given in a specific line apply there.
3338 This may also be a list of tags that should be inherited, or a regexp that
3339 matches tags that should be inherited. Additional control is possible
3340 with the variable `org-tags-exclude-from-inheritance' which gives an
3341 explicit list of tags to be excluded from inheritance, even if the value of
3342 `org-use-tag-inheritance' would select it for inheritance.
3344 If this option is t, a match early-on in a tree can lead to a large
3345 number of matches in the subtree when constructing the agenda or creating
3346 a sparse tree. If you only want to see the first match in a tree during
3347 a search, check out the variable `org-tags-match-list-sublevels'."
3348 :group 'org-tags
3349 :type '(choice
3350 (const :tag "Not" nil)
3351 (const :tag "Always" t)
3352 (repeat :tag "Specific tags" (string :tag "Tag"))
3353 (regexp :tag "Tags matched by regexp")))
3355 (defcustom org-tags-exclude-from-inheritance nil
3356 "List of tags that should never be inherited.
3357 This is a way to exclude a few tags from inheritance. For way to do
3358 the opposite, to actively allow inheritance for selected tags,
3359 see the variable `org-use-tag-inheritance'."
3360 :group 'org-tags
3361 :type '(repeat (string :tag "Tag")))
3363 (defun org-tag-inherit-p (tag)
3364 "Check if TAG is one that should be inherited."
3365 (cond
3366 ((member tag org-tags-exclude-from-inheritance) nil)
3367 ((eq org-use-tag-inheritance t) t)
3368 ((not org-use-tag-inheritance) nil)
3369 ((stringp org-use-tag-inheritance)
3370 (string-match org-use-tag-inheritance tag))
3371 ((listp org-use-tag-inheritance)
3372 (member tag org-use-tag-inheritance))
3373 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3375 (defcustom org-tags-match-list-sublevels t
3376 "Non-nil means list also sublevels of headlines matching a search.
3377 This variable applies to tags/property searches, and also to stuck
3378 projects because this search is based on a tags match as well.
3380 When set to the symbol `indented', sublevels are indented with
3381 leading dots.
3383 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3384 the sublevels of a headline matching a tag search often also match
3385 the same search. Listing all of them can create very long lists.
3386 Setting this variable to nil causes subtrees of a match to be skipped.
3388 This variable is semi-obsolete and probably should always be true. It
3389 is better to limit inheritance to certain tags using the variables
3390 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3391 :group 'org-tags
3392 :type '(choice
3393 (const :tag "No, don't list them" nil)
3394 (const :tag "Yes, do list them" t)
3395 (const :tag "List them, indented with leading dots" indented)))
3397 (defcustom org-tags-sort-function nil
3398 "When set, tags are sorted using this function as a comparator."
3399 :group 'org-tags
3400 :type '(choice
3401 (const :tag "No sorting" nil)
3402 (const :tag "Alphabetical" string<)
3403 (const :tag "Reverse alphabetical" string>)
3404 (function :tag "Custom function" nil)))
3406 (defvar org-tags-history nil
3407 "History of minibuffer reads for tags.")
3408 (defvar org-last-tags-completion-table nil
3409 "The last used completion table for tags.")
3410 (defvar org-after-tags-change-hook nil
3411 "Hook that is run after the tags in a line have changed.")
3413 (defgroup org-properties nil
3414 "Options concerning properties in Org-mode."
3415 :tag "Org Properties"
3416 :group 'org)
3418 (defcustom org-property-format "%-10s %s"
3419 "How property key/value pairs should be formatted by `indent-line'.
3420 When `indent-line' hits a property definition, it will format the line
3421 according to this format, mainly to make sure that the values are
3422 lined-up with respect to each other."
3423 :group 'org-properties
3424 :type 'string)
3426 (defcustom org-properties-postprocess-alist nil
3427 "Alist of properties and functions to adjust inserted values.
3428 Elements of this alist must be of the form
3430 ([string] [function])
3432 where [string] must be a property name and [function] must be a
3433 lambda expression: this lambda expression must take one argument,
3434 the value to adjust, and return the new value as a string.
3436 For example, this element will allow the property \"Remaining\"
3437 to be updated wrt the relation between the \"Effort\" property
3438 and the clock summary:
3440 ((\"Remaining\" (lambda(value)
3441 (let ((clocksum (org-clock-sum-current-item))
3442 (effort (org-duration-string-to-minutes
3443 (org-entry-get (point) \"Effort\"))))
3444 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3445 :group 'org-properties
3446 :version "24.1"
3447 :type '(alist :key-type (string :tag "Property")
3448 :value-type (function :tag "Function")))
3450 (defcustom org-use-property-inheritance nil
3451 "Non-nil means properties apply also for sublevels.
3453 This setting is chiefly used during property searches. Turning it on can
3454 cause significant overhead when doing a search, which is why it is not
3455 on by default.
3457 When nil, only the properties directly given in the current entry count.
3458 When t, every property is inherited. The value may also be a list of
3459 properties that should have inheritance, or a regular expression matching
3460 properties that should be inherited.
3462 However, note that some special properties use inheritance under special
3463 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3464 and the properties ending in \"_ALL\" when they are used as descriptor
3465 for valid values of a property.
3467 Note for programmers:
3468 When querying an entry with `org-entry-get', you can control if inheritance
3469 should be used. By default, `org-entry-get' looks only at the local
3470 properties. You can request inheritance by setting the inherit argument
3471 to t (to force inheritance) or to `selective' (to respect the setting
3472 in this variable)."
3473 :group 'org-properties
3474 :type '(choice
3475 (const :tag "Not" nil)
3476 (const :tag "Always" t)
3477 (repeat :tag "Specific properties" (string :tag "Property"))
3478 (regexp :tag "Properties matched by regexp")))
3480 (defun org-property-inherit-p (property)
3481 "Check if PROPERTY is one that should be inherited."
3482 (cond
3483 ((eq org-use-property-inheritance t) t)
3484 ((not org-use-property-inheritance) nil)
3485 ((stringp org-use-property-inheritance)
3486 (string-match org-use-property-inheritance property))
3487 ((listp org-use-property-inheritance)
3488 (member property org-use-property-inheritance))
3489 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3491 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3492 "The default column format, if no other format has been defined.
3493 This variable can be set on the per-file basis by inserting a line
3495 #+COLUMNS: %25ITEM ....."
3496 :group 'org-properties
3497 :type 'string)
3499 (defcustom org-columns-ellipses ".."
3500 "The ellipses to be used when a field in column view is truncated.
3501 When this is the empty string, as many characters as possible are shown,
3502 but then there will be no visual indication that the field has been truncated.
3503 When this is a string of length N, the last N characters of a truncated
3504 field are replaced by this string. If the column is narrower than the
3505 ellipses string, only part of the ellipses string will be shown."
3506 :group 'org-properties
3507 :type 'string)
3509 (defcustom org-columns-modify-value-for-display-function nil
3510 "Function that modifies values for display in column view.
3511 For example, it can be used to cut out a certain part from a time stamp.
3512 The function must take 2 arguments:
3514 column-title The title of the column (*not* the property name)
3515 value The value that should be modified.
3517 The function should return the value that should be displayed,
3518 or nil if the normal value should be used."
3519 :group 'org-properties
3520 :type '(choice (const nil) (function)))
3522 (defcustom org-effort-property "Effort"
3523 "The property that is being used to keep track of effort estimates.
3524 Effort estimates given in this property need to have the format H:MM."
3525 :group 'org-properties
3526 :group 'org-progress
3527 :type '(string :tag "Property"))
3529 (defconst org-global-properties-fixed
3530 '(("VISIBILITY_ALL" . "folded children content all")
3531 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3532 "List of property/value pairs that can be inherited by any entry.
3534 These are fixed values, for the preset properties. The user variable
3535 that can be used to add to this list is `org-global-properties'.
3537 The entries in this list are cons cells where the car is a property
3538 name and cdr is a string with the value. If the value represents
3539 multiple items like an \"_ALL\" property, separate the items by
3540 spaces.")
3542 (defcustom org-global-properties nil
3543 "List of property/value pairs that can be inherited by any entry.
3545 This list will be combined with the constant `org-global-properties-fixed'.
3547 The entries in this list are cons cells where the car is a property
3548 name and cdr is a string with the value.
3550 You can set buffer-local values for the same purpose in the variable
3551 `org-file-properties' this by adding lines like
3553 #+PROPERTY: NAME VALUE"
3554 :group 'org-properties
3555 :type '(repeat
3556 (cons (string :tag "Property")
3557 (string :tag "Value"))))
3559 (defvar org-file-properties nil
3560 "List of property/value pairs that can be inherited by any entry.
3561 Valid for the current buffer.
3562 This variable is populated from #+PROPERTY lines.")
3563 (make-variable-buffer-local 'org-file-properties)
3565 (defgroup org-agenda nil
3566 "Options concerning agenda views in Org-mode."
3567 :tag "Org Agenda"
3568 :group 'org)
3570 (defvar org-category nil
3571 "Variable used by org files to set a category for agenda display.
3572 Such files should use a file variable to set it, for example
3574 # -*- mode: org; org-category: \"ELisp\"
3576 or contain a special line
3578 #+CATEGORY: ELisp
3580 If the file does not specify a category, then file's base name
3581 is used instead.")
3582 (make-variable-buffer-local 'org-category)
3583 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3585 (defcustom org-agenda-files nil
3586 "The files to be used for agenda display.
3587 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3588 \\[org-remove-file]. You can also use customize to edit the list.
3590 If an entry is a directory, all files in that directory that are matched by
3591 `org-agenda-file-regexp' will be part of the file list.
3593 If the value of the variable is not a list but a single file name, then
3594 the list of agenda files is actually stored and maintained in that file, one
3595 agenda file per line. In this file paths can be given relative to
3596 `org-directory'. Tilde expansion and environment variable substitution
3597 are also made."
3598 :group 'org-agenda
3599 :type '(choice
3600 (repeat :tag "List of files and directories" file)
3601 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3603 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3604 "Regular expression to match files for `org-agenda-files'.
3605 If any element in the list in that variable contains a directory instead
3606 of a normal file, all files in that directory that are matched by this
3607 regular expression will be included."
3608 :group 'org-agenda
3609 :type 'regexp)
3611 (defcustom org-agenda-text-search-extra-files nil
3612 "List of extra files to be searched by text search commands.
3613 These files will be searched in addition to the agenda files by the
3614 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3615 Note that these files will only be searched for text search commands,
3616 not for the other agenda views like todo lists, tag searches or the weekly
3617 agenda. This variable is intended to list notes and possibly archive files
3618 that should also be searched by these two commands.
3619 In fact, if the first element in the list is the symbol `agenda-archives',
3620 then all archive files of all agenda files will be added to the search
3621 scope."
3622 :group 'org-agenda
3623 :type '(set :greedy t
3624 (const :tag "Agenda Archives" agenda-archives)
3625 (repeat :inline t (file))))
3627 (org-defvaralias 'org-agenda-multi-occur-extra-files
3628 'org-agenda-text-search-extra-files)
3630 (defcustom org-agenda-skip-unavailable-files nil
3631 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3632 A nil value means to remove them, after a query, from the list."
3633 :group 'org-agenda
3634 :type 'boolean)
3636 (defcustom org-calendar-to-agenda-key [?c]
3637 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3638 The command `org-calendar-goto-agenda' will be bound to this key. The
3639 default is the character `c' because then `c' can be used to switch back and
3640 forth between agenda and calendar."
3641 :group 'org-agenda
3642 :type 'sexp)
3644 (defcustom org-calendar-insert-diary-entry-key [?i]
3645 "The key to be installed in `calendar-mode-map' for adding diary entries.
3646 This option is irrelevant until `org-agenda-diary-file' has been configured
3647 to point to an Org-mode file. When that is the case, the command
3648 `org-agenda-diary-entry' will be bound to the key given here, by default
3649 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3650 if you want to continue doing this, you need to change this to a different
3651 key."
3652 :group 'org-agenda
3653 :type 'sexp)
3655 (defcustom org-agenda-diary-file 'diary-file
3656 "File to which to add new entries with the `i' key in agenda and calendar.
3657 When this is the symbol `diary-file', the functionality in the Emacs
3658 calendar will be used to add entries to the `diary-file'. But when this
3659 points to a file, `org-agenda-diary-entry' will be used instead."
3660 :group 'org-agenda
3661 :type '(choice
3662 (const :tag "The standard Emacs diary file" diary-file)
3663 (file :tag "Special Org file diary entries")))
3665 (eval-after-load "calendar"
3666 '(progn
3667 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3668 'org-calendar-goto-agenda)
3669 (add-hook 'calendar-mode-hook
3670 (lambda ()
3671 (unless (eq org-agenda-diary-file 'diary-file)
3672 (define-key calendar-mode-map
3673 org-calendar-insert-diary-entry-key
3674 'org-agenda-diary-entry))))))
3676 (defgroup org-latex nil
3677 "Options for embedding LaTeX code into Org-mode."
3678 :tag "Org LaTeX"
3679 :group 'org)
3681 (defcustom org-format-latex-options
3682 '(:foreground default :background default :scale 1.0
3683 :html-foreground "Black" :html-background "Transparent"
3684 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3685 "Options for creating images from LaTeX fragments.
3686 This is a property list with the following properties:
3687 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3688 `default' means use the foreground of the default face.
3689 `auto' means use the foreground from the text face.
3690 :background the background color, or \"Transparent\".
3691 `default' means use the background of the default face.
3692 `auto' means use the background from the text face.
3693 :scale a scaling factor for the size of the images, to get more pixels
3694 :html-foreground, :html-background, :html-scale
3695 the same numbers for HTML export.
3696 :matchers a list indicating which matchers should be used to
3697 find LaTeX fragments. Valid members of this list are:
3698 \"begin\" find environments
3699 \"$1\" find single characters surrounded by $.$
3700 \"$\" find math expressions surrounded by $...$
3701 \"$$\" find math expressions surrounded by $$....$$
3702 \"\\(\" find math expressions surrounded by \\(...\\)
3703 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3704 :group 'org-latex
3705 :type 'plist)
3707 (defcustom org-format-latex-signal-error t
3708 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3709 When nil, just push out a message."
3710 :group 'org-latex
3711 :version "24.1"
3712 :type 'boolean)
3714 (defcustom org-latex-to-mathml-jar-file nil
3715 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3716 Use this to specify additional executable file say a jar file.
3718 When using MathToWeb as the converter, specify the full-path to
3719 your mathtoweb.jar file."
3720 :group 'org-latex
3721 :version "24.1"
3722 :type '(choice
3723 (const :tag "None" nil)
3724 (file :tag "JAR file" :must-match t)))
3726 (defcustom org-latex-to-mathml-convert-command nil
3727 "Command to convert LaTeX fragments to MathML.
3728 Replace format-specifiers in the command as noted below and use
3729 `shell-command' to convert LaTeX to MathML.
3730 %j: Executable file in fully expanded form as specified by
3731 `org-latex-to-mathml-jar-file'.
3732 %I: Input LaTeX file in fully expanded form
3733 %o: Output MathML file
3734 This command is used by `org-create-math-formula'.
3736 When using MathToWeb as the converter, set this to
3737 \"java -jar %j -unicode -force -df %o %I\"."
3738 :group 'org-latex
3739 :version "24.1"
3740 :type '(choice
3741 (const :tag "None" nil)
3742 (string :tag "\nShell command")))
3744 (defcustom org-latex-create-formula-image-program 'dvipng
3745 "Program to convert LaTeX fragments with.
3747 dvipng Process the LaTeX fragments to dvi file, then convert
3748 dvi files to png files using dvipng.
3749 This will also include processing of non-math environments.
3750 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3751 to convert pdf files to png files"
3752 :group 'org-latex
3753 :version "24.1"
3754 :type '(choice
3755 (const :tag "dvipng" dvipng)
3756 (const :tag "imagemagick" imagemagick)))
3758 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3759 "Path to store latex preview images.
3760 A relative path here creates many directories relative to the
3761 processed org files paths. An absolute path puts all preview
3762 images at the same place."
3763 :group 'org-latex
3764 :version "24.3"
3765 :type 'string)
3767 (defun org-format-latex-mathml-available-p ()
3768 "Return t if `org-latex-to-mathml-convert-command' is usable."
3769 (save-match-data
3770 (when (and (boundp 'org-latex-to-mathml-convert-command)
3771 org-latex-to-mathml-convert-command)
3772 (let ((executable (car (split-string
3773 org-latex-to-mathml-convert-command))))
3774 (when (executable-find executable)
3775 (if (string-match
3776 "%j" org-latex-to-mathml-convert-command)
3777 (file-readable-p org-latex-to-mathml-jar-file)
3778 t))))))
3780 (defcustom org-format-latex-header "\\documentclass{article}
3781 \\usepackage[usenames]{color}
3782 \[PACKAGES]
3783 \[DEFAULT-PACKAGES]
3784 \\pagestyle{empty} % do not remove
3785 % The settings below are copied from fullpage.sty
3786 \\setlength{\\textwidth}{\\paperwidth}
3787 \\addtolength{\\textwidth}{-3cm}
3788 \\setlength{\\oddsidemargin}{1.5cm}
3789 \\addtolength{\\oddsidemargin}{-2.54cm}
3790 \\setlength{\\evensidemargin}{\\oddsidemargin}
3791 \\setlength{\\textheight}{\\paperheight}
3792 \\addtolength{\\textheight}{-\\headheight}
3793 \\addtolength{\\textheight}{-\\headsep}
3794 \\addtolength{\\textheight}{-\\footskip}
3795 \\addtolength{\\textheight}{-3cm}
3796 \\setlength{\\topmargin}{1.5cm}
3797 \\addtolength{\\topmargin}{-2.54cm}"
3798 "The document header used for processing LaTeX fragments.
3799 It is imperative that this header make sure that no page number
3800 appears on the page. The package defined in the variables
3801 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3802 will either replace the placeholder \"[PACKAGES]\" in this
3803 header, or they will be appended."
3804 :group 'org-latex
3805 :type 'string)
3807 (defun org-set-packages-alist (var val)
3808 "Set the packages alist and make sure it has 3 elements per entry."
3809 (set var (mapcar (lambda (x)
3810 (if (and (consp x) (= (length x) 2))
3811 (list (car x) (nth 1 x) t)
3813 val)))
3815 (defun org-get-packages-alist (var)
3816 "Get the packages alist and make sure it has 3 elements per entry."
3817 (mapcar (lambda (x)
3818 (if (and (consp x) (= (length x) 2))
3819 (list (car x) (nth 1 x) t)
3821 (default-value var)))
3823 (defcustom org-latex-default-packages-alist
3824 '(("AUTO" "inputenc" t)
3825 ("T1" "fontenc" t)
3826 ("" "fixltx2e" nil)
3827 ("" "graphicx" t)
3828 ("" "longtable" nil)
3829 ("" "float" nil)
3830 ("" "wrapfig" nil)
3831 ("" "rotating" nil)
3832 ("normalem" "ulem" t)
3833 ("" "amsmath" t)
3834 ("" "textcomp" t)
3835 ("" "marvosym" t)
3836 ("" "wasysym" t)
3837 ("" "amssymb" t)
3838 ("" "hyperref" nil)
3839 "\\tolerance=1000")
3840 "Alist of default packages to be inserted in the header.
3842 Change this only if one of the packages here causes an
3843 incompatibility with another package you are using.
3845 The packages in this list are needed by one part or another of
3846 Org mode to function properly:
3848 - inputenc, fontenc: for basic font and character selection
3849 - fixltx2e: Important patches of LaTeX itself
3850 - graphicx: for including images
3851 - longtable: For multipage tables
3852 - float, wrapfig: for figure placement
3853 - rotating: for sideways figures and tables
3854 - ulem: for underline and strike-through
3855 - amsmath: for subscript and superscript and math environments
3856 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3857 for interpreting the entities in `org-entities'. You can skip
3858 some of these packages if you don't use any of their symbols.
3859 - hyperref: for cross references
3861 Therefore you should not modify this variable unless you know
3862 what you are doing. The one reason to change it anyway is that
3863 you might be loading some other package that conflicts with one
3864 of the default packages. Each cell is of the format
3865 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3866 the package also needs to be included when compiling LaTeX
3867 snippets into images for inclusion into non-LaTeX output."
3868 :group 'org-latex
3869 :group 'org-export-latex
3870 :set 'org-set-packages-alist
3871 :get 'org-get-packages-alist
3872 :version "24.1"
3873 :type '(repeat
3874 (choice
3875 (list :tag "options/package pair"
3876 (string :tag "options")
3877 (string :tag "package")
3878 (boolean :tag "Snippet"))
3879 (string :tag "A line of LaTeX"))))
3881 (defcustom org-latex-packages-alist nil
3882 "Alist of packages to be inserted in every LaTeX header.
3884 These will be inserted after `org-latex-default-packages-alist'.
3885 Each cell is of the format:
3887 \(\"options\" \"package\" snippet-flag)
3889 SNIPPET-FLAG, when t, indicates that this package is also needed
3890 when turning LaTeX snippets into images for inclusion into
3891 non-LaTeX output.
3893 Make sure that you only list packages here which:
3895 - you want in every file
3896 - do not conflict with the setup in `org-format-latex-header'.
3897 - do not conflict with the default packages in
3898 `org-latex-default-packages-alist'."
3899 :group 'org-latex
3900 :group 'org-export-latex
3901 :set 'org-set-packages-alist
3902 :get 'org-get-packages-alist
3903 :type '(repeat
3904 (choice
3905 (list :tag "options/package pair"
3906 (string :tag "options")
3907 (string :tag "package")
3908 (boolean :tag "Snippet"))
3909 (string :tag "A line of LaTeX"))))
3911 (defgroup org-appearance nil
3912 "Settings for Org-mode appearance."
3913 :tag "Org Appearance"
3914 :group 'org)
3916 (defcustom org-level-color-stars-only nil
3917 "Non-nil means fontify only the stars in each headline.
3918 When nil, the entire headline is fontified.
3919 Changing it requires restart of `font-lock-mode' to become effective
3920 also in regions already fontified."
3921 :group 'org-appearance
3922 :type 'boolean)
3924 (defcustom org-hide-leading-stars nil
3925 "Non-nil means hide the first N-1 stars in a headline.
3926 This works by using the face `org-hide' for these stars. This
3927 face is white for a light background, and black for a dark
3928 background. You may have to customize the face `org-hide' to
3929 make this work.
3930 Changing it requires restart of `font-lock-mode' to become effective
3931 also in regions already fontified.
3932 You may also set this on a per-file basis by adding one of the following
3933 lines to the buffer:
3935 #+STARTUP: hidestars
3936 #+STARTUP: showstars"
3937 :group 'org-appearance
3938 :type 'boolean)
3940 (defcustom org-hidden-keywords nil
3941 "List of symbols corresponding to keywords to be hidden the org buffer.
3942 For example, a value '(title) for this list will make the document's title
3943 appear in the buffer without the initial #+TITLE: keyword."
3944 :group 'org-appearance
3945 :version "24.1"
3946 :type '(set (const :tag "#+AUTHOR" author)
3947 (const :tag "#+DATE" date)
3948 (const :tag "#+EMAIL" email)
3949 (const :tag "#+TITLE" title)))
3951 (defcustom org-custom-properties nil
3952 "List of properties (as strings) with a special meaning.
3953 The default use of these custom properties is to let the user
3954 hide them with `org-toggle-custom-properties-visibility'."
3955 :group 'org-properties
3956 :group 'org-appearance
3957 :version "24.3"
3958 :type '(repeat (string :tag "Property Name")))
3960 (defcustom org-fontify-done-headline nil
3961 "Non-nil means change the face of a headline if it is marked DONE.
3962 Normally, only the TODO/DONE keyword indicates the state of a headline.
3963 When this is non-nil, the headline after the keyword is set to the
3964 `org-headline-done' as an additional indication."
3965 :group 'org-appearance
3966 :type 'boolean)
3968 (defcustom org-fontify-emphasized-text t
3969 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3970 Changing this variable requires a restart of Emacs to take effect."
3971 :group 'org-appearance
3972 :type 'boolean)
3974 (defcustom org-fontify-whole-heading-line nil
3975 "Non-nil means fontify the whole line for headings.
3976 This is useful when setting a background color for the
3977 org-level-* faces."
3978 :group 'org-appearance
3979 :type 'boolean)
3981 (defcustom org-highlight-latex-and-related nil
3982 "Non-nil means highlight LaTeX related syntax in the buffer.
3983 When non nil, the value should be a list containing any of the
3984 following symbols:
3985 `latex' Highlight LaTeX snippets and environments.
3986 `script' Highlight subscript and superscript.
3987 `entities' Highlight entities."
3988 :group 'org-appearance
3989 :version "24.4"
3990 :package-version '(Org . "8.0")
3991 :type '(choice
3992 (const :tag "No highlighting" nil)
3993 (set :greedy t :tag "Highlight"
3994 (const :tag "LaTeX snippets and environments" latex)
3995 (const :tag "Subscript and superscript" script)
3996 (const :tag "Entities" entities))))
3998 (defcustom org-hide-emphasis-markers nil
3999 "Non-nil mean font-lock should hide the emphasis marker characters."
4000 :group 'org-appearance
4001 :type 'boolean)
4003 (defcustom org-pretty-entities nil
4004 "Non-nil means show entities as UTF8 characters.
4005 When nil, the \\name form remains in the buffer."
4006 :group 'org-appearance
4007 :version "24.1"
4008 :type 'boolean)
4010 (defcustom org-pretty-entities-include-sub-superscripts t
4011 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4012 :group 'org-appearance
4013 :version "24.1"
4014 :type 'boolean)
4016 (defvar org-emph-re nil
4017 "Regular expression for matching emphasis.
4018 After a match, the match groups contain these elements:
4019 0 The match of the full regular expression, including the characters
4020 before and after the proper match
4021 1 The character before the proper match, or empty at beginning of line
4022 2 The proper match, including the leading and trailing markers
4023 3 The leading marker like * or /, indicating the type of highlighting
4024 4 The text between the emphasis markers, not including the markers
4025 5 The character after the match, empty at the end of a line")
4026 (defvar org-verbatim-re nil
4027 "Regular expression for matching verbatim text.")
4028 (defvar org-emphasis-regexp-components) ; defined just below
4029 (defvar org-emphasis-alist) ; defined just below
4030 (defun org-set-emph-re (var val)
4031 "Set variable and compute the emphasis regular expression."
4032 (set var val)
4033 (when (and (boundp 'org-emphasis-alist)
4034 (boundp 'org-emphasis-regexp-components)
4035 org-emphasis-alist org-emphasis-regexp-components)
4036 (let* ((e org-emphasis-regexp-components)
4037 (pre (car e))
4038 (post (nth 1 e))
4039 (border (nth 2 e))
4040 (body (nth 3 e))
4041 (nl (nth 4 e))
4042 (body1 (concat body "*?"))
4043 (markers (mapconcat 'car org-emphasis-alist ""))
4044 (vmarkers (mapconcat
4045 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4046 org-emphasis-alist "")))
4047 ;; make sure special characters appear at the right position in the class
4048 (if (string-match "\\^" markers)
4049 (setq markers (concat (replace-match "" t t markers) "^")))
4050 (if (string-match "-" markers)
4051 (setq markers (concat (replace-match "" t t markers) "-")))
4052 (if (string-match "\\^" vmarkers)
4053 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4054 (if (string-match "-" vmarkers)
4055 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4056 (if (> nl 0)
4057 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4058 (int-to-string nl) "\\}")))
4059 ;; Make the regexp
4060 (setq org-emph-re
4061 (concat "\\([" pre "]\\|^\\)"
4062 "\\("
4063 "\\([" markers "]\\)"
4064 "\\("
4065 "[^" border "]\\|"
4066 "[^" border "]"
4067 body1
4068 "[^" border "]"
4069 "\\)"
4070 "\\3\\)"
4071 "\\([" post "]\\|$\\)"))
4072 (setq org-verbatim-re
4073 (concat "\\([" pre "]\\|^\\)"
4074 "\\("
4075 "\\([" vmarkers "]\\)"
4076 "\\("
4077 "[^" border "]\\|"
4078 "[^" border "]"
4079 body1
4080 "[^" border "]"
4081 "\\)"
4082 "\\3\\)"
4083 "\\([" post "]\\|$\\)")))))
4085 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4086 ;; set this option proved cumbersome. See this message/thread:
4087 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4088 (defvar org-emphasis-regexp-components
4089 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4090 "Components used to build the regular expression for emphasis.
4091 This is a list with five entries. Terminology: In an emphasis string
4092 like \" *strong word* \", we call the initial space PREMATCH, the final
4093 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4094 and \"trong wor\" is the body. The different components in this variable
4095 specify what is allowed/forbidden in each part:
4097 pre Chars allowed as prematch. Beginning of line will be allowed too.
4098 post Chars allowed as postmatch. End of line will be allowed too.
4099 border The chars *forbidden* as border characters.
4100 body-regexp A regexp like \".\" to match a body character. Don't use
4101 non-shy groups here, and don't allow newline here.
4102 newline The maximum number of newlines allowed in an emphasis exp.
4104 You need to reload Org or to restart Emacs after customizing this.")
4106 (defcustom org-emphasis-alist
4107 `(("*" bold)
4108 ("/" italic)
4109 ("_" underline)
4110 ("=" org-code verbatim)
4111 ("~" org-verbatim verbatim)
4112 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4113 "Alist of characters and faces to emphasize text.
4114 Text starting and ending with a special character will be emphasized,
4115 for example *bold*, _underlined_ and /italic/. This variable sets the
4116 marker characters and the face to be used by font-lock for highlighting
4117 in Org-mode Emacs buffers.
4119 You need to reload Org or to restart Emacs after customizing this."
4120 :group 'org-appearance
4121 :set 'org-set-emph-re
4122 :version "24.4"
4123 :package-version '(Org . "8.0")
4124 :type '(repeat
4125 (list
4126 (string :tag "Marker character")
4127 (choice
4128 (face :tag "Font-lock-face")
4129 (plist :tag "Face property list"))
4130 (option (const verbatim)))))
4132 (defvar org-protecting-blocks
4133 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4134 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4135 This is needed for font-lock setup.")
4137 ;;; Miscellaneous options
4139 (defgroup org-completion nil
4140 "Completion in Org-mode."
4141 :tag "Org Completion"
4142 :group 'org)
4144 (defcustom org-completion-use-ido nil
4145 "Non-nil means use ido completion wherever possible.
4146 Note that `ido-mode' must be active for this variable to be relevant.
4147 If you decide to turn this variable on, you might well want to turn off
4148 `org-outline-path-complete-in-steps'.
4149 See also `org-completion-use-iswitchb'."
4150 :group 'org-completion
4151 :type 'boolean)
4153 (defcustom org-completion-use-iswitchb nil
4154 "Non-nil means use iswitchb completion wherever possible.
4155 Note that `iswitchb-mode' must be active for this variable to be relevant.
4156 If you decide to turn this variable on, you might well want to turn off
4157 `org-outline-path-complete-in-steps'.
4158 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4159 :group 'org-completion
4160 :type 'boolean)
4162 (defcustom org-completion-fallback-command 'hippie-expand
4163 "The expansion command called by \\[pcomplete] in normal context.
4164 Normal means, no org-mode-specific context."
4165 :group 'org-completion
4166 :type 'function)
4168 ;;; Functions and variables from their packages
4169 ;; Declared here to avoid compiler warnings
4171 ;; XEmacs only
4172 (defvar outline-mode-menu-heading)
4173 (defvar outline-mode-menu-show)
4174 (defvar outline-mode-menu-hide)
4175 (defvar zmacs-regions) ; XEmacs regions
4177 ;; Emacs only
4178 (defvar mark-active)
4180 ;; Various packages
4181 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4182 (declare-function calendar-forward-day "cal-move" (arg))
4183 (declare-function calendar-goto-date "cal-move" (date))
4184 (declare-function calendar-goto-today "cal-move" ())
4185 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4186 (defvar calc-embedded-close-formula)
4187 (defvar calc-embedded-open-formula)
4188 (declare-function cdlatex-tab "ext:cdlatex" ())
4189 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4190 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4191 (defvar font-lock-unfontify-region-function)
4192 (declare-function iswitchb-read-buffer "iswitchb"
4193 (prompt &optional default require-match start matches-set))
4194 (defvar iswitchb-temp-buflist)
4195 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4196 (defvar org-agenda-tags-todo-honor-ignore-options)
4197 (declare-function org-agenda-skip "org-agenda" ())
4198 (declare-function
4199 org-agenda-format-item "org-agenda"
4200 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4201 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4202 (declare-function org-agenda-change-all-lines "org-agenda"
4203 (newhead hdmarker &optional fixface just-this))
4204 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4205 (declare-function org-agenda-maybe-redo "org-agenda" ())
4206 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4207 (beg end))
4208 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4209 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4210 "org-agenda" (&optional end))
4211 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4212 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4213 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4214 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4215 (declare-function org-indent-mode "org-indent" (&optional arg))
4216 (declare-function parse-time-string "parse-time" (string))
4217 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4218 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4219 (defvar remember-data-file)
4220 (defvar texmathp-why)
4221 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4222 (declare-function table--at-cell-p "table" (position &optional object at-column))
4224 (defvar org-latex-regexps)
4226 ;;; Autoload and prepare some org modules
4228 ;; Some table stuff that needs to be defined here, because it is used
4229 ;; by the functions setting up org-mode or checking for table context.
4231 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4232 "Detect an org-type or table-type table.")
4233 (defconst org-table-line-regexp "^[ \t]*|"
4234 "Detect an org-type table line.")
4235 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4236 "Detect an org-type table line.")
4237 (defconst org-table-hline-regexp "^[ \t]*|-"
4238 "Detect an org-type table hline.")
4239 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4240 "Detect a table-type table hline.")
4241 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4242 "Detect the first line outside a table when searching from within it.
4243 This works for both table types.")
4245 ;; Autoload the functions in org-table.el that are needed by functions here.
4247 (eval-and-compile
4248 (org-autoload "org-table"
4249 '(org-table-begin org-table-blank-field org-table-end)))
4251 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4252 "Detect a #+TBLFM line.")
4254 ;;;###autoload
4255 (defun turn-on-orgtbl ()
4256 "Unconditionally turn on `orgtbl-mode'."
4257 (require 'org-table)
4258 (orgtbl-mode 1))
4260 (defun org-at-table-p (&optional table-type)
4261 "Return t if the cursor is inside an org-type table.
4262 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4263 (if org-enable-table-editor
4264 (save-excursion
4265 (beginning-of-line 1)
4266 (looking-at (if table-type org-table-any-line-regexp
4267 org-table-line-regexp)))
4268 nil))
4269 (defsubst org-table-p () (org-at-table-p))
4271 (defun org-at-table.el-p ()
4272 "Return t if and only if we are at a table.el table."
4273 (and (org-at-table-p 'any)
4274 (save-excursion
4275 (goto-char (org-table-begin 'any))
4276 (looking-at org-table1-hline-regexp))))
4278 (defun org-table-recognize-table.el ()
4279 "If there is a table.el table nearby, recognize it and move into it."
4280 (if org-table-tab-recognizes-table.el
4281 (if (org-at-table.el-p)
4282 (progn
4283 (beginning-of-line 1)
4284 (if (looking-at org-table-dataline-regexp)
4286 (if (looking-at org-table1-hline-regexp)
4287 (progn
4288 (beginning-of-line 2)
4289 (if (looking-at org-table-any-border-regexp)
4290 (beginning-of-line -1)))))
4291 (if (re-search-forward "|" (org-table-end t) t)
4292 (progn
4293 (require 'table)
4294 (if (table--at-cell-p (point))
4296 (message "recognizing table.el table...")
4297 (table-recognize-table)
4298 (message "recognizing table.el table...done")))
4299 (error "This should not happen"))
4301 nil)
4302 nil))
4304 (defun org-at-table-hline-p ()
4305 "Return t if the cursor is inside a hline in a table."
4306 (if org-enable-table-editor
4307 (save-excursion
4308 (beginning-of-line 1)
4309 (looking-at org-table-hline-regexp))
4310 nil))
4312 (defun org-table-map-tables (function &optional quietly)
4313 "Apply FUNCTION to the start of all tables in the buffer."
4314 (save-excursion
4315 (save-restriction
4316 (widen)
4317 (goto-char (point-min))
4318 (while (re-search-forward org-table-any-line-regexp nil t)
4319 (unless quietly
4320 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4321 (beginning-of-line 1)
4322 (when (and (looking-at org-table-line-regexp)
4323 ;; Exclude tables in src/example/verbatim/clocktable blocks
4324 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4325 (save-excursion (funcall function))
4326 (or (looking-at org-table-line-regexp)
4327 (forward-char 1)))
4328 (re-search-forward org-table-any-border-regexp nil 1))))
4329 (unless quietly (message "Mapping tables: done")))
4331 ;; Declare and autoload functions from org-agenda.el
4333 (eval-and-compile
4334 (org-autoload "org-agenda"
4335 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4337 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4338 (declare-function org-clock-update-mode-line "org-clock" ())
4339 (declare-function org-resolve-clocks "org-clock"
4340 (&optional also-non-dangling-p prompt last-valid))
4342 (defun org-at-TBLFM-p (&optional pos)
4343 "Return t when point (or POS) is in #+TBLFM line."
4344 (save-excursion
4345 (let ((pos pos)))
4346 (goto-char (or pos (point)))
4347 (beginning-of-line 1)
4348 (looking-at org-TBLFM-regexp)))
4350 (defvar org-clock-start-time)
4351 (defvar org-clock-marker (make-marker)
4352 "Marker recording the last clock-in.")
4353 (defvar org-clock-hd-marker (make-marker)
4354 "Marker recording the last clock-in, but the headline position.")
4355 (defvar org-clock-heading ""
4356 "The heading of the current clock entry.")
4357 (defun org-clock-is-active ()
4358 "Return the buffer where the clock is currently running.
4359 Return nil if no clock is running."
4360 (marker-buffer org-clock-marker))
4362 (eval-and-compile
4363 (org-autoload "org-clock" '(org-clock-remove-overlays
4364 org-clock-update-time-maybe
4365 org-clocktable-shift)))
4367 (defun org-check-running-clock ()
4368 "Check if the current buffer contains the running clock.
4369 If yes, offer to stop it and to save the buffer with the changes."
4370 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4371 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4372 (buffer-name))))
4373 (org-clock-out)
4374 (when (y-or-n-p "Save changed buffer?")
4375 (save-buffer))))
4377 (defun org-clocktable-try-shift (dir n)
4378 "Check if this line starts a clock table, if yes, shift the time block."
4379 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4380 (org-clocktable-shift dir n)))
4382 ;;;###autoload
4383 (defun org-clock-persistence-insinuate ()
4384 "Set up hooks for clock persistence."
4385 (require 'org-clock)
4386 (add-hook 'org-mode-hook 'org-clock-load)
4387 (add-hook 'kill-emacs-hook 'org-clock-save))
4389 ;; Define the variable already here, to make sure we have it.
4390 (defvar org-indent-mode nil
4391 "Non-nil if Org-Indent mode is enabled.
4392 Use the command `org-indent-mode' to change this variable.")
4394 ;; Autoload archiving code
4395 ;; The stuff that is needed for cycling and tags has to be defined here.
4397 (defgroup org-archive nil
4398 "Options concerning archiving in Org-mode."
4399 :tag "Org Archive"
4400 :group 'org-structure)
4402 (defcustom org-archive-location "%s_archive::"
4403 "The location where subtrees should be archived.
4405 The value of this variable is a string, consisting of two parts,
4406 separated by a double-colon. The first part is a filename and
4407 the second part is a headline.
4409 When the filename is omitted, archiving happens in the same file.
4410 %s in the filename will be replaced by the current file
4411 name (without the directory part). Archiving to a different file
4412 is useful to keep archived entries from contributing to the
4413 Org-mode Agenda.
4415 The archived entries will be filed as subtrees of the specified
4416 headline. When the headline is omitted, the subtrees are simply
4417 filed away at the end of the file, as top-level entries. Also in
4418 the heading you can use %s to represent the file name, this can be
4419 useful when using the same archive for a number of different files.
4421 Here are a few examples:
4422 \"%s_archive::\"
4423 If the current file is Projects.org, archive in file
4424 Projects.org_archive, as top-level trees. This is the default.
4426 \"::* Archived Tasks\"
4427 Archive in the current file, under the top-level headline
4428 \"* Archived Tasks\".
4430 \"~/org/archive.org::\"
4431 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4433 \"~/org/archive.org::* From %s\"
4434 Archive in file ~/org/archive.org (absolute path), under headlines
4435 \"From FILENAME\" where file name is the current file name.
4437 \"~/org/datetree.org::datetree/* Finished Tasks\"
4438 The \"datetree/\" string is special, signifying to archive
4439 items to the datetree. Items are placed in either the CLOSED
4440 date of the item, or the current date if there is no CLOSED date.
4441 The heading will be a subentry to the current date. There doesn't
4442 need to be a heading, but there always needs to be a slash after
4443 datetree. For example, to store archived items directly in the
4444 datetree, use \"~/org/datetree.org::datetree/\".
4446 \"basement::** Finished Tasks\"
4447 Archive in file ./basement (relative path), as level 3 trees
4448 below the level 2 heading \"** Finished Tasks\".
4450 You may set this option on a per-file basis by adding to the buffer a
4451 line like
4453 #+ARCHIVE: basement::** Finished Tasks
4455 You may also define it locally for a subtree by setting an ARCHIVE property
4456 in the entry. If such a property is found in an entry, or anywhere up
4457 the hierarchy, it will be used."
4458 :group 'org-archive
4459 :type 'string)
4461 (defcustom org-archive-tag "ARCHIVE"
4462 "The tag that marks a subtree as archived.
4463 An archived subtree does not open during visibility cycling, and does
4464 not contribute to the agenda listings.
4465 After changing this, font-lock must be restarted in the relevant buffers to
4466 get the proper fontification."
4467 :group 'org-archive
4468 :group 'org-keywords
4469 :type 'string)
4471 (defcustom org-agenda-skip-archived-trees t
4472 "Non-nil means the agenda will skip any items located in archived trees.
4473 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4474 variable is no longer recommended, you should leave it at the value t.
4475 Instead, use the key `v' to cycle the archives-mode in the agenda."
4476 :group 'org-archive
4477 :group 'org-agenda-skip
4478 :type 'boolean)
4480 (defcustom org-columns-skip-archived-trees t
4481 "Non-nil means ignore archived trees when creating column view."
4482 :group 'org-archive
4483 :group 'org-properties
4484 :type 'boolean)
4486 (defcustom org-cycle-open-archived-trees nil
4487 "Non-nil means `org-cycle' will open archived trees.
4488 An archived tree is a tree marked with the tag ARCHIVE.
4489 When nil, archived trees will stay folded. You can still open them with
4490 normal outline commands like `show-all', but not with the cycling commands."
4491 :group 'org-archive
4492 :group 'org-cycle
4493 :type 'boolean)
4495 (defcustom org-sparse-tree-open-archived-trees nil
4496 "Non-nil means sparse tree construction shows matches in archived trees.
4497 When nil, matches in these trees are highlighted, but the trees are kept in
4498 collapsed state."
4499 :group 'org-archive
4500 :group 'org-sparse-trees
4501 :type 'boolean)
4503 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4504 "The default date type when building a sparse tree.
4505 When this is nil, a date is a scheduled or a deadline timestamp.
4506 Otherwise, these types are allowed:
4508 all: all timestamps
4509 active: only active timestamps (<...>)
4510 inactive: only inactive timestamps (<...)
4511 scheduled: only scheduled timestamps
4512 deadline: only deadline timestamps"
4513 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4514 (const :tag "All timestamps" all)
4515 (const :tag "Only active timestamps" active)
4516 (const :tag "Only inactive timestamps" inactive)
4517 (const :tag "Only scheduled timestamps" scheduled)
4518 (const :tag "Only deadline timestamps" deadline)
4519 (const :tag "Only closed timestamps" closed))
4520 :version "24.3"
4521 :group 'org-sparse-trees)
4523 (defun org-cycle-hide-archived-subtrees (state)
4524 "Re-hide all archived subtrees after a visibility state change."
4525 (when (and (not org-cycle-open-archived-trees)
4526 (not (memq state '(overview folded))))
4527 (save-excursion
4528 (let* ((globalp (memq state '(contents all)))
4529 (beg (if globalp (point-min) (point)))
4530 (end (if globalp (point-max) (org-end-of-subtree t))))
4531 (org-hide-archived-subtrees beg end)
4532 (goto-char beg)
4533 (if (looking-at (concat ".*:" org-archive-tag ":"))
4534 (message "%s" (substitute-command-keys
4535 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4537 (defun org-force-cycle-archived ()
4538 "Cycle subtree even if it is archived."
4539 (interactive)
4540 (setq this-command 'org-cycle)
4541 (let ((org-cycle-open-archived-trees t))
4542 (call-interactively 'org-cycle)))
4544 (defun org-hide-archived-subtrees (beg end)
4545 "Re-hide all archived subtrees after a visibility state change."
4546 (save-excursion
4547 (let* ((re (concat ":" org-archive-tag ":")))
4548 (goto-char beg)
4549 (while (re-search-forward re end t)
4550 (when (org-at-heading-p)
4551 (org-flag-subtree t)
4552 (org-end-of-subtree t))))))
4554 (declare-function outline-end-of-heading "outline" ())
4555 (declare-function outline-flag-region "outline" (from to flag))
4556 (defun org-flag-subtree (flag)
4557 (save-excursion
4558 (org-back-to-heading t)
4559 (outline-end-of-heading)
4560 (outline-flag-region (point)
4561 (progn (org-end-of-subtree t) (point))
4562 flag)))
4564 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4566 (eval-and-compile
4567 (org-autoload "org-archive"
4568 '(org-add-archive-files)))
4570 ;; Autoload Column View Code
4572 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4573 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4574 (declare-function org-columns-compute "org-colview" (property))
4576 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4577 '(org-columns-number-to-string
4578 org-columns-get-format-and-top-level
4579 org-columns-compute
4580 org-columns-remove-overlays))
4582 ;; Autoload ID code
4584 (declare-function org-id-store-link "org-id")
4585 (declare-function org-id-locations-load "org-id")
4586 (declare-function org-id-locations-save "org-id")
4587 (defvar org-id-track-globally)
4588 (org-autoload "org-id"
4589 '(org-id-new
4590 org-id-copy
4591 org-id-get-with-outline-path-completion
4592 org-id-get-with-outline-drilling))
4594 ;;; Variables for pre-computed regular expressions, all buffer local
4596 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4597 "Matches first line of a hidden block.")
4598 (make-variable-buffer-local 'org-drawer-regexp)
4599 (defvar org-todo-regexp nil
4600 "Matches any of the TODO state keywords.")
4601 (make-variable-buffer-local 'org-todo-regexp)
4602 (defvar org-not-done-regexp nil
4603 "Matches any of the TODO state keywords except the last one.")
4604 (make-variable-buffer-local 'org-not-done-regexp)
4605 (defvar org-not-done-heading-regexp nil
4606 "Matches a TODO headline that is not done.")
4607 (make-variable-buffer-local 'org-not-done-regexp)
4608 (defvar org-todo-line-regexp nil
4609 "Matches a headline and puts TODO state into group 2 if present.")
4610 (make-variable-buffer-local 'org-todo-line-regexp)
4611 (defvar org-complex-heading-regexp nil
4612 "Matches a headline and puts everything into groups:
4613 group 1: the stars
4614 group 2: The todo keyword, maybe
4615 group 3: Priority cookie
4616 group 4: True headline
4617 group 5: Tags")
4618 (make-variable-buffer-local 'org-complex-heading-regexp)
4619 (defvar org-complex-heading-regexp-format nil
4620 "Printf format to make regexp to match an exact headline.
4621 This regexp will match the headline of any node which has the
4622 exact headline text that is put into the format, but may have any
4623 TODO state, priority and tags.")
4624 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4625 (defvar org-todo-line-tags-regexp nil
4626 "Matches a headline and puts TODO state into group 2 if present.
4627 Also put tags into group 4 if tags are present.")
4628 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4629 (defvar org-ds-keyword-length 12
4630 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4631 (make-variable-buffer-local 'org-ds-keyword-length)
4632 (defvar org-deadline-regexp nil
4633 "Matches the DEADLINE keyword.")
4634 (make-variable-buffer-local 'org-deadline-regexp)
4635 (defvar org-deadline-time-regexp nil
4636 "Matches the DEADLINE keyword together with a time stamp.")
4637 (make-variable-buffer-local 'org-deadline-time-regexp)
4638 (defvar org-deadline-time-hour-regexp nil
4639 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4640 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4641 (defvar org-deadline-line-regexp nil
4642 "Matches the DEADLINE keyword and the rest of the line.")
4643 (make-variable-buffer-local 'org-deadline-line-regexp)
4644 (defvar org-scheduled-regexp nil
4645 "Matches the SCHEDULED keyword.")
4646 (make-variable-buffer-local 'org-scheduled-regexp)
4647 (defvar org-scheduled-time-regexp nil
4648 "Matches the SCHEDULED keyword together with a time stamp.")
4649 (make-variable-buffer-local 'org-scheduled-time-regexp)
4650 (defvar org-scheduled-time-hour-regexp nil
4651 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4652 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4653 (defvar org-closed-time-regexp nil
4654 "Matches the CLOSED keyword together with a time stamp.")
4655 (make-variable-buffer-local 'org-closed-time-regexp)
4657 (defvar org-keyword-time-regexp nil
4658 "Matches any of the 4 keywords, together with the time stamp.")
4659 (make-variable-buffer-local 'org-keyword-time-regexp)
4660 (defvar org-keyword-time-not-clock-regexp nil
4661 "Matches any of the 3 keywords, together with the time stamp.")
4662 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4663 (defvar org-maybe-keyword-time-regexp nil
4664 "Matches a timestamp, possibly preceded by a keyword.")
4665 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4666 (defvar org-all-time-keywords nil
4667 "List of time keywords.")
4668 (make-variable-buffer-local 'org-all-time-keywords)
4670 (defconst org-plain-time-of-day-regexp
4671 (concat
4672 "\\(\\<[012]?[0-9]"
4673 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4674 "\\(--?"
4675 "\\(\\<[012]?[0-9]"
4676 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4677 "\\)?")
4678 "Regular expression to match a plain time or time range.
4679 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4680 groups carry important information:
4681 0 the full match
4682 1 the first time, range or not
4683 8 the second time, if it is a range.")
4685 (defconst org-plain-time-extension-regexp
4686 (concat
4687 "\\(\\<[012]?[0-9]"
4688 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4689 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4690 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4691 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4692 groups carry important information:
4693 0 the full match
4694 7 hours of duration
4695 9 minutes of duration")
4697 (defconst org-stamp-time-of-day-regexp
4698 (concat
4699 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4700 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4701 "\\(--?"
4702 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4703 "Regular expression to match a timestamp time or time range.
4704 After a match, the following groups carry important information:
4705 0 the full match
4706 1 date plus weekday, for back referencing to make sure both times are on the same day
4707 2 the first time, range or not
4708 4 the second time, if it is a range.")
4710 (defconst org-startup-options
4711 '(("fold" org-startup-folded t)
4712 ("overview" org-startup-folded t)
4713 ("nofold" org-startup-folded nil)
4714 ("showall" org-startup-folded nil)
4715 ("showeverything" org-startup-folded showeverything)
4716 ("content" org-startup-folded content)
4717 ("indent" org-startup-indented t)
4718 ("noindent" org-startup-indented nil)
4719 ("hidestars" org-hide-leading-stars t)
4720 ("showstars" org-hide-leading-stars nil)
4721 ("odd" org-odd-levels-only t)
4722 ("oddeven" org-odd-levels-only nil)
4723 ("align" org-startup-align-all-tables t)
4724 ("noalign" org-startup-align-all-tables nil)
4725 ("inlineimages" org-startup-with-inline-images t)
4726 ("noinlineimages" org-startup-with-inline-images nil)
4727 ("latexpreview" org-startup-with-latex-preview t)
4728 ("nolatexpreview" org-startup-with-latex-preview nil)
4729 ("customtime" org-display-custom-times t)
4730 ("logdone" org-log-done time)
4731 ("lognotedone" org-log-done note)
4732 ("nologdone" org-log-done nil)
4733 ("lognoteclock-out" org-log-note-clock-out t)
4734 ("nolognoteclock-out" org-log-note-clock-out nil)
4735 ("logrepeat" org-log-repeat state)
4736 ("lognoterepeat" org-log-repeat note)
4737 ("logdrawer" org-log-into-drawer t)
4738 ("nologdrawer" org-log-into-drawer nil)
4739 ("logstatesreversed" org-log-states-order-reversed t)
4740 ("nologstatesreversed" org-log-states-order-reversed nil)
4741 ("nologrepeat" org-log-repeat nil)
4742 ("logreschedule" org-log-reschedule time)
4743 ("lognotereschedule" org-log-reschedule note)
4744 ("nologreschedule" org-log-reschedule nil)
4745 ("logredeadline" org-log-redeadline time)
4746 ("lognoteredeadline" org-log-redeadline note)
4747 ("nologredeadline" org-log-redeadline nil)
4748 ("logrefile" org-log-refile time)
4749 ("lognoterefile" org-log-refile note)
4750 ("nologrefile" org-log-refile nil)
4751 ("fninline" org-footnote-define-inline t)
4752 ("nofninline" org-footnote-define-inline nil)
4753 ("fnlocal" org-footnote-section nil)
4754 ("fnauto" org-footnote-auto-label t)
4755 ("fnprompt" org-footnote-auto-label nil)
4756 ("fnconfirm" org-footnote-auto-label confirm)
4757 ("fnplain" org-footnote-auto-label plain)
4758 ("fnadjust" org-footnote-auto-adjust t)
4759 ("nofnadjust" org-footnote-auto-adjust nil)
4760 ("constcgs" constants-unit-system cgs)
4761 ("constSI" constants-unit-system SI)
4762 ("noptag" org-tag-persistent-alist nil)
4763 ("hideblocks" org-hide-block-startup t)
4764 ("nohideblocks" org-hide-block-startup nil)
4765 ("beamer" org-startup-with-beamer-mode t)
4766 ("entitiespretty" org-pretty-entities t)
4767 ("entitiesplain" org-pretty-entities nil))
4768 "Variable associated with STARTUP options for org-mode.
4769 Each element is a list of three items: the startup options (as written
4770 in the #+STARTUP line), the corresponding variable, and the value to set
4771 this variable to if the option is found. An optional forth element PUSH
4772 means to push this value onto the list in the variable.")
4774 (defun org-update-property-plist (key val props)
4775 "Update PROPS with KEY and VAL."
4776 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4777 (key (if appending (substring key 0 (- (length key) 1)) key))
4778 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4779 (previous (cdr (assoc key props))))
4780 (if appending
4781 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4782 (cons (cons key val) remainder))))
4784 (defconst org-block-regexp
4785 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4786 "Regular expression for hiding blocks.")
4787 (defconst org-heading-keyword-regexp-format
4788 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4789 "Printf format for a regexp matching a headline with some keyword.
4790 This regexp will match the headline of any node which has the
4791 exact keyword that is put into the format. The keyword isn't in
4792 any group by default, but the stars and the body are.")
4793 (defconst org-heading-keyword-maybe-regexp-format
4794 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4795 "Printf format for a regexp matching a headline, possibly with some keyword.
4796 This regexp can match any headline with the specified keyword, or
4797 without a keyword. The keyword isn't in any group by default,
4798 but the stars and the body are.")
4800 (defcustom org-group-tags t
4801 "When non-nil (the default), use group tags.
4802 This can be turned on/off through `org-toggle-tags-groups'."
4803 :group 'org-tags
4804 :group 'org-startup
4805 :type 'boolean)
4807 (defun org-toggle-tags-groups ()
4808 "Toggle support for group tags.
4809 Support for group tags is controlled by the option
4810 `org-group-tags', which is non-nil by default."
4811 (interactive)
4812 (setq org-group-tags (not org-group-tags))
4813 (cond ((and (derived-mode-p 'org-agenda-mode)
4814 org-group-tags)
4815 (org-agenda-redo))
4816 ((derived-mode-p 'org-mode)
4817 (let ((org-inhibit-startup t)) (org-mode))))
4818 (message "Groups tags support has been turned %s"
4819 (if org-group-tags "on" "off")))
4821 (defun org-set-regexps-and-options-for-tags ()
4822 "Precompute variables used for tags."
4823 (when (derived-mode-p 'org-mode)
4824 (org-set-local 'org-file-tags nil)
4825 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4826 (splitre "[ \t]+")
4827 (start 0)
4828 tags ftags key value)
4829 (save-excursion
4830 (save-restriction
4831 (widen)
4832 (goto-char (point-min))
4833 (while (re-search-forward re nil t)
4834 (setq key (upcase (org-match-string-no-properties 1))
4835 value (org-match-string-no-properties 2))
4836 (if (stringp value) (setq value (org-trim value)))
4837 (cond
4838 ((equal key "TAGS")
4839 (setq tags (append tags (if tags '("\\n") nil)
4840 (org-split-string value splitre))))
4841 ((equal key "FILETAGS")
4842 (when (string-match "\\S-" value)
4843 (setq ftags
4844 (append
4845 ftags
4846 (apply 'append
4847 (mapcar (lambda (x) (org-split-string x ":"))
4848 (org-split-string value)))))))))))
4849 ;; Process the file tags.
4850 (and ftags (org-set-local 'org-file-tags
4851 (mapcar 'org-add-prop-inherited ftags)))
4852 (org-set-local 'org-tag-groups-alist nil)
4853 ;; Process the tags.
4854 (when (and (not tags) org-tag-alist)
4855 (setq tags
4856 (mapcar
4857 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4858 ((eq (car tg) :endgroup) "}")
4859 ((eq (car tg) :grouptags) ":")
4860 ((eq (car tg) :newline) "\n")
4861 (t (concat (car tg)
4862 (if (characterp (cdr tg))
4863 (format "(%s)" (char-to-string (cdr tg))) "")))))
4864 org-tag-alist)))
4865 (let (e tgs g)
4866 (while (setq e (pop tags))
4867 (cond
4868 ((equal e "{")
4869 (progn (push '(:startgroup) tgs)
4870 (when (equal (nth 1 tags) ":")
4871 (push (list (replace-regexp-in-string
4872 "(.+)$" "" (nth 0 tags)))
4873 org-tag-groups-alist)
4874 (setq g 0))))
4875 ((equal e ":") (push '(:grouptags) tgs))
4876 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4877 ((equal e "\\n") (push '(:newline) tgs))
4878 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4879 (push (cons (match-string 1 e)
4880 (string-to-char (match-string 2 e))) tgs)
4881 (if (and g (> g 0))
4882 (setcar org-tag-groups-alist
4883 (append (car org-tag-groups-alist)
4884 (list (match-string 1 e)))))
4885 (if g (setq g (1+ g))))
4886 (t (push (list e) tgs)
4887 (if (and g (> g 0))
4888 (setcar org-tag-groups-alist
4889 (append (car org-tag-groups-alist) (list e))))
4890 (if g (setq g (1+ g))))))
4891 (org-set-local 'org-tag-alist nil)
4892 (while (setq e (pop tgs))
4893 (or (and (stringp (car e))
4894 (assoc (car e) org-tag-alist))
4895 (push e org-tag-alist)))
4896 ;; Return a list with tag variables
4897 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4899 (defvar org-ota nil)
4900 (defun org-set-regexps-and-options ()
4901 "Precompute regular expressions used in the current buffer."
4902 (when (derived-mode-p 'org-mode)
4903 (org-set-local 'org-todo-kwd-alist nil)
4904 (org-set-local 'org-todo-key-alist nil)
4905 (org-set-local 'org-todo-key-trigger nil)
4906 (org-set-local 'org-todo-keywords-1 nil)
4907 (org-set-local 'org-done-keywords nil)
4908 (org-set-local 'org-todo-heads nil)
4909 (org-set-local 'org-todo-sets nil)
4910 (org-set-local 'org-todo-log-states nil)
4911 (org-set-local 'org-file-properties nil)
4912 (let ((re (org-make-options-regexp
4913 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4914 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4915 "SETUPFILE" "OPTIONS")
4916 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4917 (splitre "[ \t]+")
4918 (scripts org-use-sub-superscripts)
4919 kwds kws0 kwsa key log value cat arch const links hw dws
4920 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4921 (start 0))
4922 (save-excursion
4923 (save-restriction
4924 (widen)
4925 (goto-char (point-min))
4926 (while
4927 (or (and
4928 ext-setup-or-nil
4929 (not org-ota)
4930 (let (ret)
4931 (with-temp-buffer
4932 (insert ext-setup-or-nil)
4933 (let ((major-mode 'org-mode) org-ota)
4934 (setq ret (save-match-data
4935 (org-set-regexps-and-options-for-tags)))))
4936 ;; Append setupfile tags to existing tags
4937 (setq org-ota t)
4938 (setq org-file-tags
4939 (delq nil (append org-file-tags (nth 0 ret)))
4940 org-tag-alist
4941 (delq nil (append org-tag-alist (nth 1 ret)))
4942 org-tag-groups-alist
4943 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4944 (and ext-setup-or-nil
4945 (string-match re ext-setup-or-nil start)
4946 (setq start (match-end 0)))
4947 (and (setq ext-setup-or-nil nil start 0)
4948 (re-search-forward re nil t)))
4949 (setq key (upcase (match-string 1 ext-setup-or-nil))
4950 value (org-match-string-no-properties 2 ext-setup-or-nil))
4951 (if (stringp value) (setq value (org-trim value)))
4952 (cond
4953 ((equal key "CATEGORY")
4954 (setq cat value))
4955 ((member key '("SEQ_TODO" "TODO"))
4956 (push (cons 'sequence (org-split-string value splitre)) kwds))
4957 ((equal key "TYP_TODO")
4958 (push (cons 'type (org-split-string value splitre)) kwds))
4959 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4960 ;; general TODO-like setup
4961 (push (cons (intern (downcase (match-string 1 key)))
4962 (org-split-string value splitre)) kwds))
4963 ((equal key "COLUMNS")
4964 (org-set-local 'org-columns-default-format value))
4965 ((equal key "LINK")
4966 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4967 (push (cons (match-string 1 value)
4968 (org-trim (match-string 2 value)))
4969 links)))
4970 ((equal key "PRIORITIES")
4971 (setq prio (org-split-string value " +")))
4972 ((equal key "PROPERTY")
4973 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4974 (setq props (org-update-property-plist (match-string 1 value)
4975 (match-string 2 value)
4976 props))))
4977 ((equal key "DRAWERS")
4978 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4979 ((equal key "CONSTANTS")
4980 (org-table-set-constants))
4981 ((equal key "STARTUP")
4982 (let ((opts (org-split-string value splitre))
4983 l var val)
4984 (while (setq l (pop opts))
4985 (when (setq l (assoc l org-startup-options))
4986 (setq var (nth 1 l) val (nth 2 l))
4987 (if (not (nth 3 l))
4988 (set (make-local-variable var) val)
4989 (if (not (listp (symbol-value var)))
4990 (set (make-local-variable var) nil))
4991 (set (make-local-variable var) (symbol-value var))
4992 (add-to-list var val))))))
4993 ((equal key "ARCHIVE")
4994 (setq arch value)
4995 (remove-text-properties 0 (length arch)
4996 '(face t fontified t) arch))
4997 ((equal key "OPTIONS")
4998 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4999 (setq scripts (read (match-string 2 value)))))
5000 ((and (equal key "SETUPFILE")
5001 ;; Prevent checking in Gnus messages
5002 (not buffer-read-only))
5003 (setq setup-contents (org-file-contents
5004 (expand-file-name
5005 (org-remove-double-quotes value))
5006 'noerror))
5007 (if (not ext-setup-or-nil)
5008 (setq ext-setup-or-nil setup-contents start 0)
5009 (setq ext-setup-or-nil
5010 (concat (substring ext-setup-or-nil 0 start)
5011 "\n" setup-contents "\n"
5012 (substring ext-setup-or-nil start)))))))
5013 ;; search for property blocks
5014 (goto-char (point-min))
5015 (while (re-search-forward org-block-regexp nil t)
5016 (when (equal "PROPERTY" (upcase (match-string 1)))
5017 (setq value (replace-regexp-in-string
5018 "[\n\r]" " " (match-string 4)))
5019 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5020 (setq props (org-update-property-plist (match-string 1 value)
5021 (match-string 2 value)
5022 props)))))))
5023 (org-set-local 'org-use-sub-superscripts scripts)
5024 (when cat
5025 (org-set-local 'org-category (intern cat))
5026 (push (cons "CATEGORY" cat) props))
5027 (when prio
5028 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5029 (setq prio (mapcar 'string-to-char prio))
5030 (org-set-local 'org-highest-priority (nth 0 prio))
5031 (org-set-local 'org-lowest-priority (nth 1 prio))
5032 (org-set-local 'org-default-priority (nth 2 prio)))
5033 (and props (org-set-local 'org-file-properties (nreverse props)))
5034 (and drawers (org-set-local 'org-drawers drawers))
5035 (and arch (org-set-local 'org-archive-location arch))
5036 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5037 ;; Process the TODO keywords
5038 (unless kwds
5039 ;; Use the global values as if they had been given locally.
5040 (setq kwds (default-value 'org-todo-keywords))
5041 (if (stringp (car kwds))
5042 (setq kwds (list (cons org-todo-interpretation
5043 (default-value 'org-todo-keywords)))))
5044 (setq kwds (reverse kwds)))
5045 (setq kwds (nreverse kwds))
5046 (let (inter kws kw)
5047 (while (setq kws (pop kwds))
5048 (let ((kws (or
5049 (run-hook-with-args-until-success
5050 'org-todo-setup-filter-hook kws)
5051 kws)))
5052 (setq inter (pop kws) sep (member "|" kws)
5053 kws0 (delete "|" (copy-sequence kws))
5054 kwsa nil
5055 kws1 (mapcar
5056 (lambda (x)
5057 ;; 1 2
5058 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5059 (progn
5060 (setq kw (match-string 1 x)
5061 key (and (match-end 2) (match-string 2 x))
5062 log (org-extract-log-state-settings x))
5063 (push (cons kw (and key (string-to-char key))) kwsa)
5064 (and log (push log org-todo-log-states))
5066 (error "Invalid TODO keyword %s" x)))
5067 kws0)
5068 kwsa (if kwsa (append '((:startgroup))
5069 (nreverse kwsa)
5070 '((:endgroup))))
5071 hw (car kws1)
5072 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5073 tail (list inter hw (car dws) (org-last dws))))
5074 (add-to-list 'org-todo-heads hw 'append)
5075 (push kws1 org-todo-sets)
5076 (setq org-done-keywords (append org-done-keywords dws nil))
5077 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5078 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5079 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5080 (setq org-todo-sets (nreverse org-todo-sets)
5081 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5082 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5083 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5084 ;; Compute the regular expressions and other local variables.
5085 ;; Using `org-outline-regexp-bol' would complicate them much,
5086 ;; because of the fixed white space at the end of that string.
5087 (if (not org-done-keywords)
5088 (setq org-done-keywords (and org-todo-keywords-1
5089 (list (org-last org-todo-keywords-1)))))
5090 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5091 (length org-scheduled-string)
5092 (length org-clock-string)
5093 (length org-closed-string)))
5094 org-drawer-regexp
5095 (concat "^[ \t]*:\\("
5096 (mapconcat 'regexp-quote org-drawers "\\|")
5097 "\\):[ \t]*$")
5098 org-not-done-keywords
5099 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5100 org-todo-regexp
5101 (concat "\\("
5102 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5103 "\\)")
5104 org-not-done-regexp
5105 (concat "\\("
5106 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5107 "\\)")
5108 org-not-done-heading-regexp
5109 (format org-heading-keyword-regexp-format org-not-done-regexp)
5110 org-todo-line-regexp
5111 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5112 org-complex-heading-regexp
5113 (concat "^\\(\\*+\\)"
5114 "\\(?: +" org-todo-regexp "\\)?"
5115 "\\(?: +\\(\\[#.\\]\\)\\)?"
5116 "\\(?: +\\(.*?\\)\\)??"
5117 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5118 "[ \t]*$")
5119 org-complex-heading-regexp-format
5120 (concat "^\\(\\*+\\)"
5121 "\\(?: +" org-todo-regexp "\\)?"
5122 "\\(?: +\\(\\[#.\\]\\)\\)?"
5123 "\\(?: +"
5124 ;; Stats cookies can be stuck to body.
5125 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5126 "\\(%s\\)"
5127 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5128 "\\)"
5129 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5130 "[ \t]*$")
5131 org-todo-line-tags-regexp
5132 (concat "^\\(\\*+\\)"
5133 "\\(?: +" org-todo-regexp "\\)?"
5134 "\\(?: +\\(.*?\\)\\)??"
5135 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5136 "[ \t]*$")
5137 org-deadline-regexp (concat "\\<" org-deadline-string)
5138 org-deadline-time-regexp
5139 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5140 org-deadline-time-hour-regexp
5141 (concat "\\<" org-deadline-string
5142 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5143 org-deadline-line-regexp
5144 (concat "\\<\\(" org-deadline-string "\\).*")
5145 org-scheduled-regexp
5146 (concat "\\<" org-scheduled-string)
5147 org-scheduled-time-regexp
5148 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5149 org-scheduled-time-hour-regexp
5150 (concat "\\<" org-scheduled-string
5151 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5152 org-closed-time-regexp
5153 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5154 org-keyword-time-regexp
5155 (concat "\\<\\(" org-scheduled-string
5156 "\\|" org-deadline-string
5157 "\\|" org-closed-string
5158 "\\|" org-clock-string "\\)"
5159 " *[[<]\\([^]>]+\\)[]>]")
5160 org-keyword-time-not-clock-regexp
5161 (concat "\\<\\(" org-scheduled-string
5162 "\\|" org-deadline-string
5163 "\\|" org-closed-string
5164 "\\)"
5165 " *[[<]\\([^]>]+\\)[]>]")
5166 org-maybe-keyword-time-regexp
5167 (concat "\\(\\<\\(" org-scheduled-string
5168 "\\|" org-deadline-string
5169 "\\|" org-closed-string
5170 "\\|" org-clock-string "\\)\\)?"
5171 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5172 org-all-time-keywords
5173 (mapcar (lambda (w) (substring w 0 -1))
5174 (list org-scheduled-string org-deadline-string
5175 org-clock-string org-closed-string)))
5176 (setq org-ota nil)
5177 (org-compute-latex-and-related-regexp))))
5179 (defun org-file-contents (file &optional noerror)
5180 "Return the contents of FILE, as a string."
5181 (if (or (not file)
5182 (not (file-readable-p file)))
5183 (if noerror
5184 (message "Cannot read file \"%s\"" file)
5185 (error "Cannot read file \"%s\"" file))
5186 (with-temp-buffer
5187 (insert-file-contents file)
5188 (buffer-string))))
5190 (defun org-extract-log-state-settings (x)
5191 "Extract the log state setting from a TODO keyword string.
5192 This will extract info from a string like \"WAIT(w@/!)\"."
5193 (let (kw key log1 log2)
5194 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5195 (setq kw (match-string 1 x)
5196 key (and (match-end 2) (match-string 2 x))
5197 log1 (and (match-end 3) (match-string 3 x))
5198 log2 (and (match-end 4) (match-string 4 x)))
5199 (and (or log1 log2)
5200 (list kw
5201 (and log1 (if (equal log1 "!") 'time 'note))
5202 (and log2 (if (equal log2 "!") 'time 'note)))))))
5204 (defun org-remove-keyword-keys (list)
5205 "Remove a pair of parenthesis at the end of each string in LIST."
5206 (mapcar (lambda (x)
5207 (if (string-match "(.*)$" x)
5208 (substring x 0 (match-beginning 0))
5210 list))
5212 (defun org-assign-fast-keys (alist)
5213 "Assign fast keys to a keyword-key alist.
5214 Respect keys that are already there."
5215 (let (new e (alt ?0))
5216 (while (setq e (pop alist))
5217 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5218 (cdr e)) ;; Key already assigned.
5219 (push e new)
5220 (let ((clist (string-to-list (downcase (car e))))
5221 (used (append new alist)))
5222 (when (= (car clist) ?@)
5223 (pop clist))
5224 (while (and clist (rassoc (car clist) used))
5225 (pop clist))
5226 (unless clist
5227 (while (rassoc alt used)
5228 (incf alt)))
5229 (push (cons (car e) (or (car clist) alt)) new))))
5230 (nreverse new)))
5232 ;;; Some variables used in various places
5234 (defvar org-window-configuration nil
5235 "Used in various places to store a window configuration.")
5236 (defvar org-selected-window nil
5237 "Used in various places to store a window configuration.")
5238 (defvar org-finish-function nil
5239 "Function to be called when `C-c C-c' is used.
5240 This is for getting out of special buffers like capture.")
5243 ;; FIXME: Occasionally check by commenting these, to make sure
5244 ;; no other functions uses these, forgetting to let-bind them.
5245 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5246 (defvar org-last-state)
5247 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5249 ;; Defined somewhere in this file, but used before definition.
5250 (defvar org-entities) ;; defined in org-entities.el
5251 (defvar org-struct-menu)
5252 (defvar org-org-menu)
5253 (defvar org-tbl-menu)
5255 ;;;; Define the Org-mode
5257 ;; We use a before-change function to check if a table might need
5258 ;; an update.
5259 (defvar org-table-may-need-update t
5260 "Indicates that a table might need an update.
5261 This variable is set by `org-before-change-function'.
5262 `org-table-align' sets it back to nil.")
5263 (defun org-before-change-function (beg end)
5264 "Every change indicates that a table might need an update."
5265 (setq org-table-may-need-update t))
5266 (defvar org-mode-map)
5267 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5268 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5269 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5270 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5271 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5272 (defvar org-table-buffer-is-an nil)
5274 (defvar bidi-paragraph-direction)
5275 (defvar buffer-face-mode-face)
5277 (require 'outline)
5278 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5279 (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"))
5280 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5282 ;; Other stuff we need.
5283 (require 'time-date)
5284 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5285 (require 'easymenu)
5286 (require 'overlay)
5288 ;; (require 'org-macs) moved higher up in the file before it is first used
5289 (require 'org-entities)
5290 ;; (require 'org-compat) moved higher up in the file before it is first used
5291 (require 'org-faces)
5292 (require 'org-list)
5293 (require 'org-pcomplete)
5294 (require 'org-src)
5295 (require 'org-footnote)
5296 (require 'org-macro)
5298 ;; babel
5299 (require 'ob)
5301 ;;;###autoload
5302 (define-derived-mode org-mode outline-mode "Org"
5303 "Outline-based notes management and organizer, alias
5304 \"Carsten's outline-mode for keeping track of everything.\"
5306 Org-mode develops organizational tasks around a NOTES file which
5307 contains information about projects as plain text. Org-mode is
5308 implemented on top of outline-mode, which is ideal to keep the content
5309 of large files well structured. It supports ToDo items, deadlines and
5310 time stamps, which magically appear in the diary listing of the Emacs
5311 calendar. Tables are easily created with a built-in table editor.
5312 Plain text URL-like links connect to websites, emails (VM), Usenet
5313 messages (Gnus), BBDB entries, and any files related to the project.
5314 For printing and sharing of notes, an Org-mode file (or a part of it)
5315 can be exported as a structured ASCII or HTML file.
5317 The following commands are available:
5319 \\{org-mode-map}"
5321 ;; Get rid of Outline menus, they are not needed
5322 ;; Need to do this here because define-derived-mode sets up
5323 ;; the keymap so late. Still, it is a waste to call this each time
5324 ;; we switch another buffer into org-mode.
5325 (if (featurep 'xemacs)
5326 (when (boundp 'outline-mode-menu-heading)
5327 ;; Assume this is Greg's port, it uses easymenu
5328 (easy-menu-remove outline-mode-menu-heading)
5329 (easy-menu-remove outline-mode-menu-show)
5330 (easy-menu-remove outline-mode-menu-hide))
5331 (define-key org-mode-map [menu-bar headings] 'undefined)
5332 (define-key org-mode-map [menu-bar hide] 'undefined)
5333 (define-key org-mode-map [menu-bar show] 'undefined))
5335 (org-load-modules-maybe)
5336 (easy-menu-add org-org-menu)
5337 (easy-menu-add org-tbl-menu)
5338 (org-install-agenda-files-menu)
5339 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5340 (add-to-invisibility-spec '(org-cwidth))
5341 (add-to-invisibility-spec '(org-hide-block . t))
5342 (when (featurep 'xemacs)
5343 (org-set-local 'line-move-ignore-invisible t))
5344 (org-set-local 'outline-regexp org-outline-regexp)
5345 (org-set-local 'outline-level 'org-outline-level)
5346 (setq bidi-paragraph-direction 'left-to-right)
5347 (when (and org-ellipsis
5348 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5349 (fboundp 'make-glyph-code))
5350 (unless org-display-table
5351 (setq org-display-table (make-display-table)))
5352 (set-display-table-slot
5353 org-display-table 4
5354 (vconcat (mapcar
5355 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5356 org-ellipsis)))
5357 (if (stringp org-ellipsis) org-ellipsis "..."))))
5358 (setq buffer-display-table org-display-table))
5359 (org-set-regexps-and-options-for-tags)
5360 (org-set-regexps-and-options)
5361 (org-set-font-lock-defaults)
5362 (when (and org-tag-faces (not org-tags-special-faces-re))
5363 ;; tag faces set outside customize.... force initialization.
5364 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5365 ;; Calc embedded
5366 (org-set-local 'calc-embedded-open-mode "# ")
5367 ;; Modify a few syntax entries
5368 (modify-syntax-entry ?@ "w")
5369 (modify-syntax-entry ?\" "\"")
5370 (if org-startup-truncated (setq truncate-lines t))
5371 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5372 (org-set-local 'font-lock-unfontify-region-function
5373 'org-unfontify-region)
5374 ;; Activate before-change-function
5375 (org-set-local 'org-table-may-need-update t)
5376 (org-add-hook 'before-change-functions 'org-before-change-function nil
5377 'local)
5378 ;; Check for running clock before killing a buffer
5379 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5380 ;; Initialize macros templates.
5381 (org-macro-initialize-templates)
5382 ;; Initialize radio targets.
5383 (org-update-radio-target-regexp)
5384 ;; Indentation.
5385 (org-set-local 'indent-line-function 'org-indent-line)
5386 (org-set-local 'indent-region-function 'org-indent-region)
5387 ;; Filling and auto-filling.
5388 (org-setup-filling)
5389 ;; Comments.
5390 (org-setup-comments-handling)
5391 ;; Beginning/end of defun
5392 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5393 (org-set-local 'end-of-defun-function 'org-forward-element)
5394 ;; Next error for sparse trees
5395 (org-set-local 'next-error-function 'org-occur-next-match)
5396 ;; Make sure dependence stuff works reliably, even for users who set it
5397 ;; too late :-(
5398 (if org-enforce-todo-dependencies
5399 (add-hook 'org-blocker-hook
5400 'org-block-todo-from-children-or-siblings-or-parent)
5401 (remove-hook 'org-blocker-hook
5402 'org-block-todo-from-children-or-siblings-or-parent))
5403 (if org-enforce-todo-checkbox-dependencies
5404 (add-hook 'org-blocker-hook
5405 'org-block-todo-from-checkboxes)
5406 (remove-hook 'org-blocker-hook
5407 'org-block-todo-from-checkboxes))
5409 ;; Align options lines
5410 (org-set-local
5411 'align-mode-rules-list
5412 '((org-in-buffer-settings
5413 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5414 (modes . '(org-mode)))))
5416 ;; Imenu
5417 (org-set-local 'imenu-create-index-function
5418 'org-imenu-get-tree)
5420 ;; Make isearch reveal context
5421 (if (or (featurep 'xemacs)
5422 (not (boundp 'outline-isearch-open-invisible-function)))
5423 ;; Emacs 21 and XEmacs make use of the hook
5424 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5425 ;; Emacs 22 deals with this through a special variable
5426 (org-set-local 'outline-isearch-open-invisible-function
5427 (lambda (&rest ignore) (org-show-context 'isearch)))
5428 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5430 ;; Setup the pcomplete hooks
5431 (set (make-local-variable 'pcomplete-command-completion-function)
5432 'org-pcomplete-initial)
5433 (set (make-local-variable 'pcomplete-command-name-function)
5434 'org-command-at-point)
5435 (set (make-local-variable 'pcomplete-default-completion-function)
5436 'ignore)
5437 (set (make-local-variable 'pcomplete-parse-arguments-function)
5438 'org-parse-arguments)
5439 (set (make-local-variable 'pcomplete-termination-string) "")
5440 (when (>= emacs-major-version 23)
5441 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5443 ;; If empty file that did not turn on org-mode automatically, make it to.
5444 (if (and org-insert-mode-line-in-empty-file
5445 (org-called-interactively-p 'any)
5446 (= (point-min) (point-max)))
5447 (insert "# -*- mode: org -*-\n\n"))
5448 (unless org-inhibit-startup
5449 (org-unmodified
5450 (and org-startup-with-beamer-mode (org-beamer-mode))
5451 (when org-startup-align-all-tables
5452 (org-table-map-tables 'org-table-align 'quietly))
5453 (when org-startup-with-inline-images
5454 (org-display-inline-images))
5455 (when org-startup-with-latex-preview
5456 (org-preview-latex-fragment))
5457 (unless org-inhibit-startup-visibility-stuff
5458 (org-set-startup-visibility))))
5459 ;; Try to set org-hide correctly
5460 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5462 ;; Update `customize-package-emacs-version-alist'
5463 (add-to-list 'customize-package-emacs-version-alist
5464 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5465 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5466 ("8.0" . "24.4")))
5468 (defvar org-mode-transpose-word-syntax-table
5469 (let ((st (make-syntax-table)))
5470 (mapc (lambda(c) (modify-syntax-entry
5471 (string-to-char (car c)) "w p" st))
5472 org-emphasis-alist)
5473 st))
5475 (when (fboundp 'abbrev-table-put)
5476 (abbrev-table-put org-mode-abbrev-table
5477 :parents (list text-mode-abbrev-table)))
5479 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5481 (defsubst org-fix-ellipsis-at-bol ()
5482 (save-excursion (goto-char (window-start)) (recenter 0)))
5484 (defun org-find-invisible-foreground ()
5485 (let ((candidates (remove
5486 "unspecified-bg"
5487 (nconc
5488 (list (face-background 'default)
5489 (face-background 'org-default))
5490 (mapcar
5491 (lambda (alist)
5492 (when (boundp alist)
5493 (cdr (assoc 'background-color (symbol-value alist)))))
5494 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5495 (list (face-foreground 'org-hide))))))
5496 (car (remove nil candidates))))
5498 (defun org-current-time (&optional rounding-minutes past)
5499 "Current time, possibly rounded to ROUNDING-MINUTES.
5500 When ROUNDING-MINUTES is not an integer, fall back on the car of
5501 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5502 the rounding returns a past time."
5503 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5504 (car org-time-stamp-rounding-minutes)))
5505 (time (decode-time)) res)
5506 (if (< r 1)
5507 (current-time)
5508 (setq res
5509 (apply 'encode-time
5510 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5511 (nthcdr 2 time))))
5512 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5513 (seconds-to-time (- (org-float-time res) (* r 60)))
5514 res))))
5516 (defun org-today ()
5517 "Return today date, considering `org-extend-today-until'."
5518 (time-to-days
5519 (time-subtract (current-time)
5520 (list 0 (* 3600 org-extend-today-until) 0))))
5522 ;;;; Font-Lock stuff, including the activators
5524 (defvar org-mouse-map (make-sparse-keymap))
5525 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5526 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5527 (when org-mouse-1-follows-link
5528 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5529 (when org-tab-follows-link
5530 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5531 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5533 (require 'font-lock)
5535 (defconst org-non-link-chars "]\t\n\r<>")
5536 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5537 "shell" "elisp" "doi" "message"))
5538 (defvar org-link-types-re nil
5539 "Matches a link that has a url-like prefix like \"http:\"")
5540 (defvar org-link-re-with-space nil
5541 "Matches a link with spaces, optional angular brackets around it.")
5542 (defvar org-link-re-with-space2 nil
5543 "Matches a link with spaces, optional angular brackets around it.")
5544 (defvar org-link-re-with-space3 nil
5545 "Matches a link with spaces, only for internal part in bracket links.")
5546 (defvar org-angle-link-re nil
5547 "Matches link with angular brackets, spaces are allowed.")
5548 (defvar org-plain-link-re nil
5549 "Matches plain link, without spaces.")
5550 (defvar org-bracket-link-regexp nil
5551 "Matches a link in double brackets.")
5552 (defvar org-bracket-link-analytic-regexp nil
5553 "Regular expression used to analyze links.
5554 Here is what the match groups contain after a match:
5555 1: http:
5556 2: http
5557 3: path
5558 4: [desc]
5559 5: desc")
5560 (defvar org-bracket-link-analytic-regexp++ nil
5561 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5562 (defvar org-any-link-re nil
5563 "Regular expression matching any link.")
5565 (defconst org-match-sexp-depth 3
5566 "Number of stacked braces for sub/superscript matching.")
5568 (defun org-create-multibrace-regexp (left right n)
5569 "Create a regular expression which will match a balanced sexp.
5570 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5571 as single character strings.
5572 The regexp returned will match the entire expression including the
5573 delimiters. It will also define a single group which contains the
5574 match except for the outermost delimiters. The maximum depth of
5575 stacked delimiters is N. Escaping delimiters is not possible."
5576 (let* ((nothing (concat "[^" left right "]*?"))
5577 (or "\\|")
5578 (re nothing)
5579 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5580 (while (> n 1)
5581 (setq n (1- n)
5582 re (concat re or next)
5583 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5584 (concat left "\\(" re "\\)" right)))
5586 (defvar org-match-substring-regexp
5587 (concat
5588 "\\(\\S-\\)\\([_^]\\)\\("
5589 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5590 "\\|"
5591 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5592 "\\|"
5593 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5594 "The regular expression matching a sub- or superscript.")
5596 (defvar org-match-substring-with-braces-regexp
5597 (concat
5598 "\\(\\S-\\)\\([_^]\\)\\("
5599 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5600 "\\)")
5601 "The regular expression matching a sub- or superscript, forcing braces.")
5603 (defun org-make-link-regexps ()
5604 "Update the link regular expressions.
5605 This should be called after the variable `org-link-types' has changed."
5606 (setq org-link-types-re
5607 (concat
5608 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5609 org-link-re-with-space
5610 (concat
5611 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5612 "\\([^" org-non-link-chars " ]"
5613 "[^" org-non-link-chars "]*"
5614 "[^" org-non-link-chars " ]\\)>?")
5615 org-link-re-with-space2
5616 (concat
5617 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5618 "\\([^" org-non-link-chars " ]"
5619 "[^\t\n\r]*"
5620 "[^" org-non-link-chars " ]\\)>?")
5621 org-link-re-with-space3
5622 (concat
5623 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5624 "\\([^" org-non-link-chars " ]"
5625 "[^\t\n\r]*\\)")
5626 org-angle-link-re
5627 (concat
5628 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5629 "\\([^" org-non-link-chars " ]"
5630 "[^" org-non-link-chars "]*"
5631 "\\)>")
5632 org-plain-link-re
5633 (concat
5634 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5635 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5636 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5637 org-bracket-link-regexp
5638 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5639 org-bracket-link-analytic-regexp
5640 (concat
5641 "\\[\\["
5642 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5643 "\\([^]]+\\)"
5644 "\\]"
5645 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5646 "\\]")
5647 org-bracket-link-analytic-regexp++
5648 (concat
5649 "\\[\\["
5650 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5651 "\\([^]]+\\)"
5652 "\\]"
5653 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5654 "\\]")
5655 org-any-link-re
5656 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5657 org-angle-link-re "\\)\\|\\("
5658 org-plain-link-re "\\)")))
5660 (org-make-link-regexps)
5662 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5663 "Regular expression for fast time stamp matching.")
5664 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5665 "Regular expression for fast time stamp matching.")
5666 (defconst org-ts-regexp0
5667 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5668 "Regular expression matching time strings for analysis.
5669 This one does not require the space after the date, so it can be used
5670 on a string that terminates immediately after the date.")
5671 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5672 "Regular expression matching time strings for analysis.")
5673 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5674 "Regular expression matching time stamps, with groups.")
5675 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5676 "Regular expression matching time stamps (also [..]), with groups.")
5677 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5678 "Regular expression matching a time stamp range.")
5679 (defconst org-tr-regexp-both
5680 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5681 "Regular expression matching a time stamp range.")
5682 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5683 org-ts-regexp "\\)?")
5684 "Regular expression matching a time stamp or time stamp range.")
5685 (defconst org-tsr-regexp-both
5686 (concat org-ts-regexp-both "\\(--?-?"
5687 org-ts-regexp-both "\\)?")
5688 "Regular expression matching a time stamp or time stamp range.
5689 The time stamps may be either active or inactive.")
5691 (defvar org-emph-face nil)
5693 (defun org-do-emphasis-faces (limit)
5694 "Run through the buffer and add overlays to emphasized strings."
5695 (let (rtn a)
5696 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5697 (if (not (= (char-after (match-beginning 3))
5698 (char-after (match-beginning 4))))
5699 (progn
5700 (setq rtn t)
5701 (setq a (assoc (match-string 3) org-emphasis-alist))
5702 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5703 'face
5704 (nth 1 a))
5705 (and (nth 2 a)
5706 (org-remove-flyspell-overlays-in
5707 (match-beginning 0) (match-end 0)))
5708 (add-text-properties (match-beginning 2) (match-end 2)
5709 '(font-lock-multiline t org-emphasis t))
5710 (when org-hide-emphasis-markers
5711 (add-text-properties (match-end 4) (match-beginning 5)
5712 '(invisible org-link))
5713 (add-text-properties (match-beginning 3) (match-end 3)
5714 '(invisible org-link)))))
5715 (backward-char 1))
5716 rtn))
5718 (defun org-emphasize (&optional char)
5719 "Insert or change an emphasis, i.e. a font like bold or italic.
5720 If there is an active region, change that region to a new emphasis.
5721 If there is no region, just insert the marker characters and position
5722 the cursor between them.
5723 CHAR should be the marker character. If it is a space, it means to
5724 remove the emphasis of the selected region.
5725 If CHAR is not given (for example in an interactive call) it will be
5726 prompted for."
5727 (interactive)
5728 (let ((erc org-emphasis-regexp-components)
5729 (prompt "")
5730 (string "") beg end move c s)
5731 (if (org-region-active-p)
5732 (setq beg (region-beginning) end (region-end)
5733 string (buffer-substring beg end))
5734 (setq move t))
5736 (unless char
5737 (message "Emphasis marker or tag: [%s]"
5738 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5739 (setq char (read-char-exclusive)))
5740 (if (equal char ?\ )
5741 (setq s "" move nil)
5742 (unless (assoc (char-to-string char) org-emphasis-alist)
5743 (user-error "No such emphasis marker: \"%c\"" char))
5744 (setq s (char-to-string char)))
5745 (while (and (> (length string) 1)
5746 (equal (substring string 0 1) (substring string -1))
5747 (assoc (substring string 0 1) org-emphasis-alist))
5748 (setq string (substring string 1 -1)))
5749 (setq string (concat s string s))
5750 (if beg (delete-region beg end))
5751 (unless (or (bolp)
5752 (string-match (concat "[" (nth 0 erc) "\n]")
5753 (char-to-string (char-before (point)))))
5754 (insert " "))
5755 (unless (or (eobp)
5756 (string-match (concat "[" (nth 1 erc) "\n]")
5757 (char-to-string (char-after (point)))))
5758 (insert " ") (backward-char 1))
5759 (insert string)
5760 (and move (backward-char 1))))
5762 (defconst org-nonsticky-props
5763 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5765 (defsubst org-rear-nonsticky-at (pos)
5766 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5768 (defun org-activate-plain-links (limit)
5769 "Run through the buffer and add overlays to links."
5770 (let (f hl)
5771 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5772 (not (org-in-src-block-p)))
5773 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5774 (setq f (get-text-property (match-beginning 0) 'face))
5775 (setq hl (org-match-string-no-properties 0))
5776 (if (or (eq f 'org-tag)
5777 (and (listp f) (memq 'org-tag f)))
5779 (add-text-properties (match-beginning 0) (match-end 0)
5780 (list 'mouse-face 'highlight
5781 'face 'org-link
5782 'htmlize-link `(:uri ,hl)
5783 'keymap org-mouse-map))
5784 (org-rear-nonsticky-at (match-end 0)))
5785 t)))
5787 (defun org-activate-code (limit)
5788 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5789 (progn
5790 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5791 (remove-text-properties (match-beginning 0) (match-end 0)
5792 '(display t invisible t intangible t))
5793 t)))
5795 (defcustom org-src-fontify-natively nil
5796 "When non-nil, fontify code in code blocks."
5797 :type 'boolean
5798 :version "24.1"
5799 :group 'org-appearance
5800 :group 'org-babel)
5802 (defcustom org-allow-promoting-top-level-subtree nil
5803 "When non-nil, allow promoting a top level subtree.
5804 The leading star of the top level headline will be replaced
5805 by a #."
5806 :type 'boolean
5807 :version "24.1"
5808 :group 'org-appearance)
5810 (defun org-fontify-meta-lines-and-blocks (limit)
5811 (condition-case nil
5812 (org-fontify-meta-lines-and-blocks-1 limit)
5813 (error (message "org-mode fontification error"))))
5815 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5816 "Fontify #+ lines and blocks."
5817 (let ((case-fold-search t))
5818 (if (re-search-forward
5819 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5820 limit t)
5821 (let ((beg (match-beginning 0))
5822 (block-start (match-end 0))
5823 (block-end nil)
5824 (lang (match-string 7))
5825 (beg1 (line-beginning-position 2))
5826 (dc1 (downcase (match-string 2)))
5827 (dc3 (downcase (match-string 3)))
5828 end end1 quoting block-type ovl)
5829 (cond
5830 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5831 ;; a single line of backend-specific content
5832 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5833 (remove-text-properties (match-beginning 0) (match-end 0)
5834 '(display t invisible t intangible t))
5835 (add-text-properties (match-beginning 1) (match-end 3)
5836 '(font-lock-fontified t face org-meta-line))
5837 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5838 '(font-lock-fontified t face org-block))
5839 ; for backend-specific code
5841 ((and (match-end 4) (equal dc3 "+begin"))
5842 ;; Truly a block
5843 (setq block-type (downcase (match-string 5))
5844 quoting (member block-type org-protecting-blocks))
5845 (when (re-search-forward
5846 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5847 nil t) ;; on purpose, we look further than LIMIT
5848 (setq end (min (point-max) (match-end 0))
5849 end1 (min (point-max) (1- (match-beginning 0))))
5850 (setq block-end (match-beginning 0))
5851 (when quoting
5852 (remove-text-properties beg end
5853 '(display t invisible t intangible t)))
5854 (add-text-properties
5855 beg end
5856 '(font-lock-fontified t font-lock-multiline t))
5857 (add-text-properties beg beg1 '(face org-meta-line))
5858 (add-text-properties end1 (min (point-max) (1+ end))
5859 '(face org-meta-line)) ; for end_src
5860 (cond
5861 ((and lang (not (string= lang "")) org-src-fontify-natively)
5862 (org-src-font-lock-fontify-block lang block-start block-end)
5863 ;; remove old background overlays
5864 (mapc (lambda (ov)
5865 (if (eq (overlay-get ov 'face) 'org-block-background)
5866 (delete-overlay ov)))
5867 (overlays-at (/ (+ beg1 block-end) 2)))
5868 ;; add a background overlay
5869 (setq ovl (make-overlay beg1 block-end))
5870 (overlay-put ovl 'face 'org-block-background)
5871 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5872 (quoting
5873 (add-text-properties beg1 (min (point-max) (1+ end1))
5874 '(face org-block))) ; end of source block
5875 ((not org-fontify-quote-and-verse-blocks))
5876 ((string= block-type "quote")
5877 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5878 ((string= block-type "verse")
5879 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5880 (add-text-properties beg beg1 '(face org-block-begin-line))
5881 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5882 '(face org-block-end-line))
5884 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5885 (add-text-properties
5886 beg (match-end 3)
5887 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5888 '(font-lock-fontified t invisible t)
5889 '(font-lock-fontified t face org-document-info-keyword)))
5890 (add-text-properties
5891 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5892 (if (string-equal dc1 "+title:")
5893 '(font-lock-fontified t face org-document-title)
5894 '(font-lock-fontified t face org-document-info))))
5895 ((or (equal dc1 "+results")
5896 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5897 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5898 "+call:" "+header:" "+headers:" "+name:"))
5899 (and (match-end 4) (equal dc3 "+attr")))
5900 (add-text-properties
5901 beg (match-end 0)
5902 '(font-lock-fontified t face org-meta-line))
5904 ((member dc3 '(" " ""))
5905 (add-text-properties
5906 beg (match-end 0)
5907 '(font-lock-fontified t face font-lock-comment-face)))
5908 ((not (member (char-after beg) '(?\ ?\t)))
5909 ;; just any other in-buffer setting, but not indented
5910 (add-text-properties
5911 beg (match-end 0)
5912 '(font-lock-fontified t face org-meta-line))
5914 (t nil))))))
5916 (defun org-activate-angle-links (limit)
5917 "Run through the buffer and add overlays to links."
5918 (if (and (re-search-forward org-angle-link-re limit t)
5919 (not (org-in-src-block-p)))
5920 (progn
5921 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5922 (add-text-properties (match-beginning 0) (match-end 0)
5923 (list 'mouse-face 'highlight
5924 'keymap org-mouse-map))
5925 (org-rear-nonsticky-at (match-end 0))
5926 t)))
5928 (defun org-activate-footnote-links (limit)
5929 "Run through the buffer and add overlays to footnotes."
5930 (let ((fn (org-footnote-next-reference-or-definition limit)))
5931 (when fn
5932 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5933 (org-remove-flyspell-overlays-in beg end)
5934 (add-text-properties beg end
5935 (list 'mouse-face 'highlight
5936 'keymap org-mouse-map
5937 'help-echo
5938 (if (= (point-at-bol) beg)
5939 "Footnote definition"
5940 "Footnote reference")
5941 'font-lock-fontified t
5942 'font-lock-multiline t
5943 'face 'org-footnote))))))
5945 (defun org-activate-bracket-links (limit)
5946 "Run through the buffer and add overlays to bracketed links."
5947 (if (and (re-search-forward org-bracket-link-regexp limit t)
5948 (not (org-in-src-block-p)))
5949 (let* ((hl (org-match-string-no-properties 1))
5950 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5951 (ip (org-maybe-intangible
5952 (list 'invisible 'org-link
5953 'keymap org-mouse-map 'mouse-face 'highlight
5954 'font-lock-multiline t 'help-echo help
5955 'htmlize-link `(:uri ,hl))))
5956 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5957 'font-lock-multiline t 'help-echo help
5958 'htmlize-link `(:uri ,hl))))
5959 ;; We need to remove the invisible property here. Table narrowing
5960 ;; may have made some of this invisible.
5961 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5962 (remove-text-properties (match-beginning 0) (match-end 0)
5963 '(invisible nil))
5964 (if (match-end 3)
5965 (progn
5966 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5967 (org-rear-nonsticky-at (match-beginning 3))
5968 (add-text-properties (match-beginning 3) (match-end 3) vp)
5969 (org-rear-nonsticky-at (match-end 3))
5970 (add-text-properties (match-end 3) (match-end 0) ip)
5971 (org-rear-nonsticky-at (match-end 0)))
5972 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5973 (org-rear-nonsticky-at (match-beginning 1))
5974 (add-text-properties (match-beginning 1) (match-end 1) vp)
5975 (org-rear-nonsticky-at (match-end 1))
5976 (add-text-properties (match-end 1) (match-end 0) ip)
5977 (org-rear-nonsticky-at (match-end 0)))
5978 t)))
5980 (defun org-activate-dates (limit)
5981 "Run through the buffer and add overlays to dates."
5982 (if (and (re-search-forward org-tsr-regexp-both limit t)
5983 (not (equal (char-before (match-beginning 0)) 91)))
5984 (progn
5985 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5986 (add-text-properties (match-beginning 0) (match-end 0)
5987 (list 'mouse-face 'highlight
5988 'keymap org-mouse-map))
5989 (org-rear-nonsticky-at (match-end 0))
5990 (when org-display-custom-times
5991 (if (match-end 3)
5992 (org-display-custom-time (match-beginning 3) (match-end 3)))
5993 (org-display-custom-time (match-beginning 1) (match-end 1)))
5994 t)))
5996 (defvar org-target-link-regexp nil
5997 "Regular expression matching radio targets in plain text.")
5998 (make-variable-buffer-local 'org-target-link-regexp)
5999 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6000 "Regular expression matching a link target.")
6001 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6002 "Regular expression matching a radio target.")
6003 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6004 "Regular expression matching any target.")
6006 (defun org-activate-target-links (limit)
6007 "Run through the buffer and add overlays to target matches."
6008 (when org-target-link-regexp
6009 (let ((case-fold-search t))
6010 (if (re-search-forward org-target-link-regexp limit t)
6011 (progn
6012 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6013 (add-text-properties (match-beginning 0) (match-end 0)
6014 (list 'mouse-face 'highlight
6015 'keymap org-mouse-map
6016 'help-echo "Radio target link"
6017 'org-linked-text t))
6018 (org-rear-nonsticky-at (match-end 0))
6019 t)))))
6021 (defun org-update-radio-target-regexp ()
6022 "Find all radio targets in this file and update the regular expression."
6023 (interactive)
6024 (when (memq 'radio org-activate-links)
6025 (setq org-target-link-regexp
6026 (org-make-target-link-regexp (org-all-targets 'radio)))
6027 (org-restart-font-lock)))
6029 (defun org-hide-wide-columns (limit)
6030 (let (s e)
6031 (setq s (text-property-any (point) (or limit (point-max))
6032 'org-cwidth t))
6033 (when s
6034 (setq e (next-single-property-change s 'org-cwidth))
6035 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6036 (goto-char e)
6037 t)))
6039 (defvar org-latex-and-related-regexp nil
6040 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6041 (defvar org-match-substring-regexp)
6042 (defvar org-match-substring-with-braces-regexp)
6044 (defun org-compute-latex-and-related-regexp ()
6045 "Compute regular expression for LaTeX, entities and sub/superscript.
6046 Result depends on variable `org-highlight-latex-and-related'."
6047 (org-set-local
6048 'org-latex-and-related-regexp
6049 (let* ((re-sub
6050 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6051 ((eq org-use-sub-superscripts '{})
6052 (list org-match-substring-with-braces-regexp))
6053 (org-use-sub-superscripts (list org-match-substring-regexp))))
6054 (re-latex
6055 (when (memq 'latex org-highlight-latex-and-related)
6056 (let ((matchers (plist-get org-format-latex-options :matchers)))
6057 (delq nil
6058 (mapcar (lambda (x)
6059 (and (member (car x) matchers) (nth 1 x)))
6060 org-latex-regexps)))))
6061 (re-entities
6062 (when (memq 'entities org-highlight-latex-and-related)
6063 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6064 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6066 (defun org-do-latex-and-related (limit)
6067 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6068 LIMIT bounds the search for syntax to highlight. Stop at first
6069 highlighted object, if any. Return t if some highlighting was
6070 done, nil otherwise."
6071 (when (org-string-nw-p org-latex-and-related-regexp)
6072 (catch 'found
6073 (while (re-search-forward org-latex-and-related-regexp limit t)
6074 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6075 'face))
6076 '(org-code org-verbatim underline))
6077 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6078 '(?_ ?^))
6080 0)))
6081 (font-lock-prepend-text-property
6082 (+ offset (match-beginning 0)) (match-end 0)
6083 'face 'org-latex-and-related)
6084 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6085 '(font-lock-multiline t)))
6086 (throw 'found t)))
6087 nil)))
6089 (defun org-restart-font-lock ()
6090 "Restart `font-lock-mode', to force refontification."
6091 (when (and (boundp 'font-lock-mode) font-lock-mode)
6092 (font-lock-mode -1)
6093 (font-lock-mode 1)))
6095 (defun org-all-targets (&optional radio)
6096 "Return a list of all targets in this file.
6097 When optional argument RADIO is non-nil, only find radio
6098 targets."
6099 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6100 (save-excursion
6101 (goto-char (point-min))
6102 (while (re-search-forward re nil t)
6103 ;; Make sure point is really within the object.
6104 (backward-char)
6105 (let ((obj (org-element-context)))
6106 (when (memq (org-element-type obj) '(radio-target target))
6107 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6108 rtn)))
6110 (defun org-make-target-link-regexp (targets)
6111 "Make regular expression matching all strings in TARGETS.
6112 The regular expression finds the targets also if there is a line break
6113 between words."
6114 (and targets
6115 (concat
6116 "\\<\\("
6117 (mapconcat
6118 (lambda (x)
6119 (setq x (regexp-quote x))
6120 (while (string-match " +" x)
6121 (setq x (replace-match "\\s-+" t t x)))
6123 targets
6124 "\\|")
6125 "\\)\\>")))
6127 (defun org-activate-tags (limit)
6128 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6129 (progn
6130 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6131 (add-text-properties (match-beginning 1) (match-end 1)
6132 (list 'mouse-face 'highlight
6133 'keymap org-mouse-map))
6134 (org-rear-nonsticky-at (match-end 1))
6135 t)))
6137 (defun org-outline-level ()
6138 "Compute the outline level of the heading at point.
6139 If this is called at a normal headline, the level is the number of stars.
6140 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6141 (save-excursion
6142 (if (not (condition-case nil
6143 (org-back-to-heading t)
6144 (error nil)))
6146 (looking-at org-outline-regexp)
6147 (1- (- (match-end 0) (match-beginning 0))))))
6149 (defvar org-font-lock-keywords nil)
6151 (defsubst org-re-property (property &optional literal)
6152 "Return a regexp matching a PROPERTY line.
6153 Match group 3 will be set to the value if it exists."
6154 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6155 (if literal property (regexp-quote property))
6156 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6158 (defconst org-property-re
6159 (org-re-property ".*?" 'literal)
6160 "Regular expression matching a property line.
6161 There are four matching groups:
6162 1: :PROPKEY: including the leading and trailing colon,
6163 2: PROPKEY without the leading and trailing colon,
6164 3: PROPVAL without leading or trailing spaces,
6165 4: the indentation of the current line,
6166 5: trailing whitespace.")
6168 (defvar org-font-lock-hook nil
6169 "Functions to be called for special font lock stuff.")
6171 (defvar org-font-lock-set-keywords-hook nil
6172 "Functions that can manipulate `org-font-lock-extra-keywords'.
6173 This is called after `org-font-lock-extra-keywords' is defined, but before
6174 it is installed to be used by font lock. This can be useful if something
6175 needs to be inserted at a specific position in the font-lock sequence.")
6177 (defun org-font-lock-hook (limit)
6178 "Run `org-font-lock-hook' within LIMIT."
6179 (run-hook-with-args 'org-font-lock-hook limit))
6181 (defun org-set-font-lock-defaults ()
6182 "Set font lock defaults for the current buffer."
6183 (let* ((em org-fontify-emphasized-text)
6184 (lk org-activate-links)
6185 (org-font-lock-extra-keywords
6186 (list
6187 ;; Call the hook
6188 '(org-font-lock-hook)
6189 ;; Headlines
6190 `(,(if org-fontify-whole-heading-line
6191 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6192 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6193 (1 (org-get-level-face 1))
6194 (2 (org-get-level-face 2))
6195 (3 (org-get-level-face 3)))
6196 ;; Table lines
6197 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6198 (1 'org-table t))
6199 ;; Table internals
6200 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6201 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6202 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6203 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6204 ;; Drawers
6205 (list org-drawer-regexp '(0 'org-special-keyword t))
6206 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6207 ;; Properties
6208 (list org-property-re
6209 '(1 'org-special-keyword t)
6210 '(3 'org-property-value t))
6211 ;; Links
6212 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6213 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6214 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6215 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6216 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6217 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6218 (if (memq 'footnote lk) '(org-activate-footnote-links))
6219 ;; Targets.
6220 (list org-any-target-regexp '(0 'org-target t))
6221 ;; Diary sexps.
6222 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6223 ;; Macro
6224 '("{{{.+}}}" (0 'org-macro t))
6225 '(org-hide-wide-columns (0 nil append))
6226 ;; TODO keyword
6227 (list (format org-heading-keyword-regexp-format
6228 org-todo-regexp)
6229 '(2 (org-get-todo-face 2) t))
6230 ;; DONE
6231 (if org-fontify-done-headline
6232 (list (format org-heading-keyword-regexp-format
6233 (concat
6234 "\\(?:"
6235 (mapconcat 'regexp-quote org-done-keywords "\\|")
6236 "\\)"))
6237 '(2 'org-headline-done t))
6238 nil)
6239 ;; Priorities
6240 '(org-font-lock-add-priority-faces)
6241 ;; Tags
6242 '(org-font-lock-add-tag-faces)
6243 ;; Tags groups
6244 (if (and org-group-tags org-tag-groups-alist)
6245 (list (concat org-outline-regexp-bol ".+\\(:"
6246 (regexp-opt (mapcar 'car org-tag-groups-alist))
6247 ":\\).*$")
6248 '(1 'org-tag-group prepend)))
6249 ;; Special keywords
6250 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6251 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6252 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6253 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6254 ;; Emphasis
6255 (if em
6256 (if (featurep 'xemacs)
6257 '(org-do-emphasis-faces (0 nil append))
6258 '(org-do-emphasis-faces)))
6259 ;; Checkboxes
6260 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6261 1 'org-checkbox prepend)
6262 (if (cdr (assq 'checkbox org-list-automatic-rules))
6263 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6264 (0 (org-get-checkbox-statistics-face) t)))
6265 ;; Description list items
6266 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6267 1 'org-list-dt prepend)
6268 ;; ARCHIVEd headings
6269 (list (concat
6270 org-outline-regexp-bol
6271 "\\(.*:" org-archive-tag ":.*\\)")
6272 '(1 'org-archived prepend))
6273 ;; Specials
6274 '(org-do-latex-and-related)
6275 '(org-fontify-entities)
6276 '(org-raise-scripts)
6277 ;; Code
6278 '(org-activate-code (1 'org-code t))
6279 ;; COMMENT
6280 (list (format org-heading-keyword-regexp-format
6281 (concat "\\("
6282 org-comment-string "\\|" org-quote-string
6283 "\\)"))
6284 '(2 'org-special-keyword t))
6285 ;; Blocks and meta lines
6286 '(org-fontify-meta-lines-and-blocks))))
6287 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6288 (run-hooks 'org-font-lock-set-keywords-hook)
6289 ;; Now set the full font-lock-keywords
6290 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6291 (org-set-local 'font-lock-defaults
6292 '(org-font-lock-keywords t nil nil backward-paragraph))
6293 (kill-local-variable 'font-lock-keywords) nil))
6295 (defun org-toggle-pretty-entities ()
6296 "Toggle the composition display of entities as UTF8 characters."
6297 (interactive)
6298 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6299 (org-restart-font-lock)
6300 (if org-pretty-entities
6301 (message "Entities are now displayed as UTF8 characters")
6302 (save-restriction
6303 (widen)
6304 (org-decompose-region (point-min) (point-max))
6305 (message "Entities are now displayed as plain text"))))
6307 (defvar org-custom-properties-overlays nil
6308 "List of overlays used for custom properties.")
6309 (make-variable-buffer-local 'org-custom-properties-overlays)
6311 (defun org-toggle-custom-properties-visibility ()
6312 "Display or hide properties in `org-custom-properties'."
6313 (interactive)
6314 (if org-custom-properties-overlays
6315 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6316 (setq org-custom-properties-overlays nil))
6317 (unless (not org-custom-properties)
6318 (save-excursion
6319 (save-restriction
6320 (widen)
6321 (goto-char (point-min))
6322 (while (re-search-forward org-property-re nil t)
6323 (mapc (lambda(p)
6324 (when (equal p (substring (match-string 1) 1 -1))
6325 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6326 (overlay-put o 'invisible t)
6327 (overlay-put o 'org-custom-property t)
6328 (push o org-custom-properties-overlays))))
6329 org-custom-properties)))))))
6331 (defun org-fontify-entities (limit)
6332 "Find an entity to fontify."
6333 (let (ee)
6334 (when org-pretty-entities
6335 (catch 'match
6336 (while (re-search-forward
6337 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6338 limit t)
6339 (if (and (not (org-in-indented-comment-line))
6340 (setq ee (org-entity-get (match-string 1)))
6341 (= (length (nth 6 ee)) 1))
6342 (let*
6343 ((end (if (equal (match-string 2) "{}")
6344 (match-end 2)
6345 (match-end 1))))
6346 (add-text-properties
6347 (match-beginning 0) end
6348 (list 'font-lock-fontified t))
6349 (compose-region (match-beginning 0) end
6350 (nth 6 ee) nil)
6351 (backward-char 1)
6352 (throw 'match t))))
6353 nil))))
6355 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6356 "Fontify string S like in Org-mode."
6357 (with-temp-buffer
6358 (insert s)
6359 (let ((org-odd-levels-only odd-levels))
6360 (org-mode)
6361 (font-lock-fontify-buffer)
6362 (buffer-string))))
6364 (defvar org-m nil)
6365 (defvar org-l nil)
6366 (defvar org-f nil)
6367 (defun org-get-level-face (n)
6368 "Get the right face for match N in font-lock matching of headlines."
6369 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6370 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6371 (if org-cycle-level-faces
6372 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6373 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6374 (cond
6375 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6376 ((eq n 2) org-f)
6377 (t (if org-level-color-stars-only nil org-f))))
6380 (defun org-get-todo-face (kwd)
6381 "Get the right face for a TODO keyword KWD.
6382 If KWD is a number, get the corresponding match group."
6383 (if (numberp kwd) (setq kwd (match-string kwd)))
6384 (or (org-face-from-face-or-color
6385 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6386 (and (member kwd org-done-keywords) 'org-done)
6387 'org-todo))
6389 (defun org-face-from-face-or-color (context inherit face-or-color)
6390 "Create a face list that inherits INHERIT, but sets the foreground color.
6391 When FACE-OR-COLOR is not a string, just return it."
6392 (if (stringp face-or-color)
6393 (list :inherit inherit
6394 (cdr (assoc context org-faces-easy-properties))
6395 face-or-color)
6396 face-or-color))
6398 (defun org-font-lock-add-tag-faces (limit)
6399 "Add the special tag faces."
6400 (when (and org-tag-faces org-tags-special-faces-re)
6401 (while (re-search-forward org-tags-special-faces-re limit t)
6402 (add-text-properties (match-beginning 1) (match-end 1)
6403 (list 'face (org-get-tag-face 1)
6404 'font-lock-fontified t))
6405 (backward-char 1))))
6407 (defun org-font-lock-add-priority-faces (limit)
6408 "Add the special priority faces."
6409 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6410 (when (save-match-data (org-at-heading-p))
6411 (add-text-properties
6412 (match-beginning 0) (match-end 0)
6413 (list 'face (or (org-face-from-face-or-color
6414 'priority 'org-priority
6415 (cdr (assoc (char-after (match-beginning 1))
6416 org-priority-faces)))
6417 'org-priority)
6418 'font-lock-fontified t)))))
6420 (defun org-get-tag-face (kwd)
6421 "Get the right face for a TODO keyword KWD.
6422 If KWD is a number, get the corresponding match group."
6423 (if (numberp kwd) (setq kwd (match-string kwd)))
6424 (or (org-face-from-face-or-color
6425 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6426 'org-tag))
6428 (defun org-unfontify-region (beg end &optional maybe_loudly)
6429 "Remove fontification and activation overlays from links."
6430 (font-lock-default-unfontify-region beg end)
6431 (let* ((buffer-undo-list t)
6432 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6433 (inhibit-modification-hooks t)
6434 deactivate-mark buffer-file-name buffer-file-truename)
6435 (org-decompose-region beg end)
6436 (remove-text-properties beg end
6437 '(mouse-face t keymap t org-linked-text t
6438 invisible t intangible t
6439 org-no-flyspell t org-emphasis t))
6440 (org-remove-font-lock-display-properties beg end)))
6442 (defconst org-script-display '(((raise -0.3) (height 0.7))
6443 ((raise 0.3) (height 0.7))
6444 ((raise -0.5))
6445 ((raise 0.5)))
6446 "Display properties for showing superscripts and subscripts.")
6448 (defun org-remove-font-lock-display-properties (beg end)
6449 "Remove specific display properties that have been added by font lock.
6450 The will remove the raise properties that are used to show superscripts
6451 and subscripts."
6452 (let (next prop)
6453 (while (< beg end)
6454 (setq next (next-single-property-change beg 'display nil end)
6455 prop (get-text-property beg 'display))
6456 (if (member prop org-script-display)
6457 (put-text-property beg next 'display nil))
6458 (setq beg next))))
6460 (defun org-raise-scripts (limit)
6461 "Add raise properties to sub/superscripts."
6462 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6463 (if (re-search-forward
6464 (if (eq org-use-sub-superscripts t)
6465 org-match-substring-regexp
6466 org-match-substring-with-braces-regexp)
6467 limit t)
6468 (let* ((pos (point)) table-p comment-p
6469 (mpos (match-beginning 3))
6470 (emph-p (get-text-property mpos 'org-emphasis))
6471 (link-p (get-text-property mpos 'mouse-face))
6472 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6473 (goto-char (point-at-bol))
6474 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6475 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6476 (goto-char pos)
6477 ;; Handle a_b^c
6478 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6479 (if (or comment-p emph-p link-p keyw-p)
6481 (put-text-property (match-beginning 3) (match-end 0)
6482 'display
6483 (if (equal (char-after (match-beginning 2)) ?^)
6484 (nth (if table-p 3 1) org-script-display)
6485 (nth (if table-p 2 0) org-script-display)))
6486 (add-text-properties (match-beginning 2) (match-end 2)
6487 (list 'invisible t
6488 'org-dwidth t 'org-dwidth-n 1))
6489 (if (and (eq (char-after (match-beginning 3)) ?{)
6490 (eq (char-before (match-end 3)) ?}))
6491 (progn
6492 (add-text-properties
6493 (match-beginning 3) (1+ (match-beginning 3))
6494 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6495 (add-text-properties
6496 (1- (match-end 3)) (match-end 3)
6497 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6498 t)))))
6500 ;;;; Visibility cycling, including org-goto and indirect buffer
6502 ;;; Cycling
6504 (defvar org-cycle-global-status nil)
6505 (make-variable-buffer-local 'org-cycle-global-status)
6506 (put 'org-cycle-global-status 'org-state t)
6507 (defvar org-cycle-subtree-status nil)
6508 (make-variable-buffer-local 'org-cycle-subtree-status)
6509 (put 'org-cycle-subtree-status 'org-state t)
6511 (defvar org-inlinetask-min-level)
6513 (defun org-unlogged-message (&rest args)
6514 "Display a message, but avoid logging it in the *Messages* buffer."
6515 (let ((message-log-max nil))
6516 (apply 'message args)))
6518 ;;;###autoload
6519 (defun org-cycle (&optional arg)
6520 "TAB-action and visibility cycling for Org-mode.
6522 This is the command invoked in Org-mode by the TAB key. Its main purpose
6523 is outline visibility cycling, but it also invokes other actions
6524 in special contexts.
6526 - When this function is called with a prefix argument, rotate the entire
6527 buffer through 3 states (global cycling)
6528 1. OVERVIEW: Show only top-level headlines.
6529 2. CONTENTS: Show all headlines of all levels, but no body text.
6530 3. SHOW ALL: Show everything.
6531 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6532 determined by the variable `org-startup-folded', and by any VISIBILITY
6533 properties in the buffer.
6534 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6535 including any drawers.
6537 - When inside a table, re-align the table and move to the next field.
6539 - When point is at the beginning of a headline, rotate the subtree started
6540 by this line through 3 different states (local cycling)
6541 1. FOLDED: Only the main headline is shown.
6542 2. CHILDREN: The main headline and the direct children are shown.
6543 From this state, you can move to one of the children
6544 and zoom in further.
6545 3. SUBTREE: Show the entire subtree, including body text.
6546 If there is no subtree, switch directly from CHILDREN to FOLDED.
6548 - When point is at the beginning of an empty headline and the variable
6549 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6550 of the headline by demoting and promoting it to likely levels. This
6551 speeds up creation document structure by pressing TAB once or several
6552 times right after creating a new headline.
6554 - When there is a numeric prefix, go up to a heading with level ARG, do
6555 a `show-subtree' and return to the previous cursor position. If ARG
6556 is negative, go up that many levels.
6558 - When point is not at the beginning of a headline, execute the global
6559 binding for TAB, which is re-indenting the line. See the option
6560 `org-cycle-emulate-tab' for details.
6562 - Special case: if point is at the beginning of the buffer and there is
6563 no headline in line 1, this function will act as if called with prefix arg
6564 (C-u TAB, same as S-TAB) also when called without prefix arg.
6565 But only if also the variable `org-cycle-global-at-bob' is t."
6566 (interactive "P")
6567 (org-load-modules-maybe)
6568 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6569 (and org-cycle-level-after-item/entry-creation
6570 (or (org-cycle-level)
6571 (org-cycle-item-indentation))))
6572 (let* ((limit-level
6573 (or org-cycle-max-level
6574 (and (boundp 'org-inlinetask-min-level)
6575 org-inlinetask-min-level
6576 (1- org-inlinetask-min-level))))
6577 (nstars (and limit-level
6578 (if org-odd-levels-only
6579 (and limit-level (1- (* limit-level 2)))
6580 limit-level)))
6581 (org-outline-regexp
6582 (if (not (derived-mode-p 'org-mode))
6583 outline-regexp
6584 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6585 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6586 (not (looking-at org-outline-regexp))))
6587 (org-cycle-hook
6588 (if bob-special
6589 (delq 'org-optimize-window-after-visibility-change
6590 (copy-sequence org-cycle-hook))
6591 org-cycle-hook))
6592 (pos (point)))
6594 (if (or bob-special (equal arg '(4)))
6595 ;; special case: use global cycling
6596 (setq arg t))
6598 (cond
6600 ((equal arg '(16))
6601 (setq last-command 'dummy)
6602 (org-set-startup-visibility)
6603 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6605 ((equal arg '(64))
6606 (show-all)
6607 (org-unlogged-message "Entire buffer visible, including drawers"))
6609 ;; Table: enter it or move to the next field.
6610 ((org-at-table-p 'any)
6611 (if (org-at-table.el-p)
6612 (message "Use C-c ' to edit table.el tables")
6613 (if arg (org-table-edit-field t)
6614 (org-table-justify-field-maybe)
6615 (call-interactively 'org-table-next-field))))
6617 ((run-hook-with-args-until-success
6618 'org-tab-after-check-for-table-hook))
6620 ;; Global cycling: delegate to `org-cycle-internal-global'.
6621 ((eq arg t) (org-cycle-internal-global))
6623 ;; Drawers: delegate to `org-flag-drawer'.
6624 ((and org-drawers org-drawer-regexp
6625 (save-excursion
6626 (beginning-of-line 1)
6627 (looking-at org-drawer-regexp)))
6628 (org-flag-drawer ; toggle block visibility
6629 (not (get-char-property (match-end 0) 'invisible))))
6631 ;; Show-subtree, ARG levels up from here.
6632 ((integerp arg)
6633 (save-excursion
6634 (org-back-to-heading)
6635 (outline-up-heading (if (< arg 0) (- arg)
6636 (- (funcall outline-level) arg)))
6637 (org-show-subtree)))
6639 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6640 ((and (featurep 'org-inlinetask)
6641 (org-inlinetask-at-task-p)
6642 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6643 (org-inlinetask-toggle-visibility))
6645 ((org-try-cdlatex-tab))
6647 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6648 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6649 (save-excursion (beginning-of-line 1)
6650 (looking-at org-outline-regexp)))
6651 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6652 (org-cycle-internal-local))
6654 ;; From there: TAB emulation and template completion.
6655 (buffer-read-only (org-back-to-heading))
6657 ((run-hook-with-args-until-success
6658 'org-tab-after-check-for-cycling-hook))
6660 ((org-try-structure-completion))
6662 ((run-hook-with-args-until-success
6663 'org-tab-before-tab-emulation-hook))
6665 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6666 (or (not (bolp))
6667 (not (looking-at org-outline-regexp))))
6668 (call-interactively (global-key-binding "\t")))
6670 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6671 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6672 (or (and (eq org-cycle-emulate-tab 'white)
6673 (= (match-end 0) (point-at-eol)))
6674 (and (eq org-cycle-emulate-tab 'whitestart)
6675 (>= (match-end 0) pos))))
6677 (eq org-cycle-emulate-tab t))
6678 (call-interactively (global-key-binding "\t")))
6680 (t (save-excursion
6681 (org-back-to-heading)
6682 (org-cycle)))))))
6684 (defun org-cycle-internal-global ()
6685 "Do the global cycling action."
6686 ;; Hack to avoid display of messages for .org attachments in Gnus
6687 (let ((ga (string-match "\\*fontification" (buffer-name))))
6688 (cond
6689 ((and (eq last-command this-command)
6690 (eq org-cycle-global-status 'overview))
6691 ;; We just created the overview - now do table of contents
6692 ;; This can be slow in very large buffers, so indicate action
6693 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6694 (unless ga (org-unlogged-message "CONTENTS..."))
6695 (org-content)
6696 (unless ga (org-unlogged-message "CONTENTS...done"))
6697 (setq org-cycle-global-status 'contents)
6698 (run-hook-with-args 'org-cycle-hook 'contents))
6700 ((and (eq last-command this-command)
6701 (eq org-cycle-global-status 'contents))
6702 ;; We just showed the table of contents - now show everything
6703 (run-hook-with-args 'org-pre-cycle-hook 'all)
6704 (show-all)
6705 (unless ga (org-unlogged-message "SHOW ALL"))
6706 (setq org-cycle-global-status 'all)
6707 (run-hook-with-args 'org-cycle-hook 'all))
6710 ;; Default action: go to overview
6711 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6712 (org-overview)
6713 (unless ga (org-unlogged-message "OVERVIEW"))
6714 (setq org-cycle-global-status 'overview)
6715 (run-hook-with-args 'org-cycle-hook 'overview)))))
6717 (defun org-cycle-internal-local ()
6718 "Do the local cycling action."
6719 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6720 ;; First, determine end of headline (EOH), end of subtree or item
6721 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6722 (save-excursion
6723 (if (org-at-item-p)
6724 (progn
6725 (beginning-of-line)
6726 (setq struct (org-list-struct))
6727 (setq eoh (point-at-eol))
6728 (setq eos (org-list-get-item-end-before-blank (point) struct))
6729 (setq has-children (org-list-has-child-p (point) struct)))
6730 (org-back-to-heading)
6731 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6732 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6733 (setq has-children
6734 (or (save-excursion
6735 (let ((level (funcall outline-level)))
6736 (outline-next-heading)
6737 (and (org-at-heading-p t)
6738 (> (funcall outline-level) level))))
6739 (save-excursion
6740 (org-list-search-forward (org-item-beginning-re) eos t)))))
6741 ;; Determine end invisible part of buffer (EOL)
6742 (beginning-of-line 2)
6743 ;; XEmacs doesn't have `next-single-char-property-change'
6744 (if (featurep 'xemacs)
6745 (while (and (not (eobp)) ;; this is like `next-line'
6746 (get-char-property (1- (point)) 'invisible))
6747 (beginning-of-line 2))
6748 (while (and (not (eobp)) ;; this is like `next-line'
6749 (get-char-property (1- (point)) 'invisible))
6750 (goto-char (next-single-char-property-change (point) 'invisible))
6751 (and (eolp) (beginning-of-line 2))))
6752 (setq eol (point)))
6753 ;; Find out what to do next and set `this-command'
6754 (cond
6755 ((= eos eoh)
6756 ;; Nothing is hidden behind this heading
6757 (unless (org-before-first-heading-p)
6758 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6759 (org-unlogged-message "EMPTY ENTRY")
6760 (setq org-cycle-subtree-status nil)
6761 (save-excursion
6762 (goto-char eos)
6763 (outline-next-heading)
6764 (if (outline-invisible-p) (org-flag-heading nil))))
6765 ((and (or (>= eol eos)
6766 (not (string-match "\\S-" (buffer-substring eol eos))))
6767 (or has-children
6768 (not (setq children-skipped
6769 org-cycle-skip-children-state-if-no-children))))
6770 ;; Entire subtree is hidden in one line: children view
6771 (unless (org-before-first-heading-p)
6772 (run-hook-with-args 'org-pre-cycle-hook 'children))
6773 (if (org-at-item-p)
6774 (org-list-set-item-visibility (point-at-bol) struct 'children)
6775 (org-show-entry)
6776 (org-with-limited-levels (show-children))
6777 ;; FIXME: This slows down the func way too much.
6778 ;; How keep drawers hidden in subtree anyway?
6779 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6780 ;; (org-cycle-hide-drawers 'subtree))
6782 ;; Fold every list in subtree to top-level items.
6783 (when (eq org-cycle-include-plain-lists 'integrate)
6784 (save-excursion
6785 (org-back-to-heading)
6786 (while (org-list-search-forward (org-item-beginning-re) eos t)
6787 (beginning-of-line 1)
6788 (let* ((struct (org-list-struct))
6789 (prevs (org-list-prevs-alist struct))
6790 (end (org-list-get-bottom-point struct)))
6791 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6792 (org-list-get-all-items (point) struct prevs))
6793 (goto-char (if (< end eos) end eos)))))))
6794 (org-unlogged-message "CHILDREN")
6795 (save-excursion
6796 (goto-char eos)
6797 (outline-next-heading)
6798 (if (outline-invisible-p) (org-flag-heading nil)))
6799 (setq org-cycle-subtree-status 'children)
6800 (unless (org-before-first-heading-p)
6801 (run-hook-with-args 'org-cycle-hook 'children)))
6802 ((or children-skipped
6803 (and (eq last-command this-command)
6804 (eq org-cycle-subtree-status 'children)))
6805 ;; We just showed the children, or no children are there,
6806 ;; now show everything.
6807 (unless (org-before-first-heading-p)
6808 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6809 (outline-flag-region eoh eos nil)
6810 (org-unlogged-message
6811 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6812 (setq org-cycle-subtree-status 'subtree)
6813 (unless (org-before-first-heading-p)
6814 (run-hook-with-args 'org-cycle-hook 'subtree)))
6816 ;; Default action: hide the subtree.
6817 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6818 (outline-flag-region eoh eos t)
6819 (org-unlogged-message "FOLDED")
6820 (setq org-cycle-subtree-status 'folded)
6821 (unless (org-before-first-heading-p)
6822 (run-hook-with-args 'org-cycle-hook 'folded))))))
6824 ;;;###autoload
6825 (defun org-global-cycle (&optional arg)
6826 "Cycle the global visibility. For details see `org-cycle'.
6827 With \\[universal-argument] prefix arg, switch to startup visibility.
6828 With a numeric prefix, show all headlines up to that level."
6829 (interactive "P")
6830 (let ((org-cycle-include-plain-lists
6831 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6832 (cond
6833 ((integerp arg)
6834 (show-all)
6835 (hide-sublevels arg)
6836 (setq org-cycle-global-status 'contents))
6837 ((equal arg '(4))
6838 (org-set-startup-visibility)
6839 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6841 (org-cycle '(4))))))
6843 (defun org-set-startup-visibility ()
6844 "Set the visibility required by startup options and properties."
6845 (cond
6846 ((eq org-startup-folded t)
6847 (org-cycle '(4)))
6848 ((eq org-startup-folded 'content)
6849 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6850 (org-cycle '(4)) (org-cycle '(4)))))
6851 (unless (eq org-startup-folded 'showeverything)
6852 (if org-hide-block-startup (org-hide-block-all))
6853 (org-set-visibility-according-to-property 'no-cleanup)
6854 (org-cycle-hide-archived-subtrees 'all)
6855 (org-cycle-hide-drawers 'all)
6856 (org-cycle-show-empty-lines t)))
6858 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6859 "Switch subtree visibilities according to :VISIBILITY: property."
6860 (interactive)
6861 (let (org-show-entry-below state)
6862 (save-excursion
6863 (goto-char (point-min))
6864 (while (re-search-forward
6865 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6866 nil t)
6867 (setq state (match-string 1))
6868 (save-excursion
6869 (org-back-to-heading t)
6870 (hide-subtree)
6871 (org-reveal)
6872 (cond
6873 ((equal state '("fold" "folded"))
6874 (hide-subtree))
6875 ((equal state "children")
6876 (org-show-hidden-entry)
6877 (show-children))
6878 ((equal state "content")
6879 (save-excursion
6880 (save-restriction
6881 (org-narrow-to-subtree)
6882 (org-content))))
6883 ((member state '("all" "showall"))
6884 (show-subtree)))))
6885 (unless no-cleanup
6886 (org-cycle-hide-archived-subtrees 'all)
6887 (org-cycle-hide-drawers 'all)
6888 (org-cycle-show-empty-lines 'all)))))
6890 ;; This function uses outline-regexp instead of the more fundamental
6891 ;; org-outline-regexp so that org-cycle-global works outside of Org
6892 ;; buffers, where outline-regexp is needed.
6893 (defun org-overview ()
6894 "Switch to overview mode, showing only top-level headlines.
6895 Really, this shows all headlines with level equal or greater than the level
6896 of the first headline in the buffer. This is important, because if the
6897 first headline is not level one, then (hide-sublevels 1) gives confusing
6898 results."
6899 (interactive)
6900 (let ((pos (point))
6901 (level (save-excursion
6902 (goto-char (point-min))
6903 (if (re-search-forward (concat "^" outline-regexp) nil t)
6904 (progn
6905 (goto-char (match-beginning 0))
6906 (funcall outline-level))))))
6907 (and level (hide-sublevels level))
6908 (recenter '(4))
6909 (goto-char pos)))
6911 (defun org-content (&optional arg)
6912 "Show all headlines in the buffer, like a table of contents.
6913 With numerical argument N, show content up to level N."
6914 (interactive "P")
6915 (save-excursion
6916 ;; Visit all headings and show their offspring
6917 (and (integerp arg) (org-overview))
6918 (goto-char (point-max))
6919 (catch 'exit
6920 (while (and (progn (condition-case nil
6921 (outline-previous-visible-heading 1)
6922 (error (goto-char (point-min))))
6924 (looking-at org-outline-regexp))
6925 (if (integerp arg)
6926 (show-children (1- arg))
6927 (show-branches))
6928 (if (bobp) (throw 'exit nil))))))
6931 (defun org-optimize-window-after-visibility-change (state)
6932 "Adjust the window after a change in outline visibility.
6933 This function is the default value of the hook `org-cycle-hook'."
6934 (when (get-buffer-window (current-buffer))
6935 (cond
6936 ((eq state 'content) nil)
6937 ((eq state 'all) nil)
6938 ((eq state 'folded) nil)
6939 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6940 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6942 (defun org-remove-empty-overlays-at (pos)
6943 "Remove outline overlays that do not contain non-white stuff."
6944 (mapc
6945 (lambda (o)
6946 (and (eq 'outline (overlay-get o 'invisible))
6947 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6948 (overlay-end o))))
6949 (delete-overlay o)))
6950 (overlays-at pos)))
6952 (defun org-clean-visibility-after-subtree-move ()
6953 "Fix visibility issues after moving a subtree."
6954 ;; First, find a reasonable region to look at:
6955 ;; Start two siblings above, end three below
6956 (let* ((beg (save-excursion
6957 (and (org-get-last-sibling)
6958 (org-get-last-sibling))
6959 (point)))
6960 (end (save-excursion
6961 (and (org-get-next-sibling)
6962 (org-get-next-sibling)
6963 (org-get-next-sibling))
6964 (if (org-at-heading-p)
6965 (point-at-eol)
6966 (point))))
6967 (level (looking-at "\\*+"))
6968 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6969 (save-excursion
6970 (save-restriction
6971 (narrow-to-region beg end)
6972 (when re
6973 ;; Properly fold already folded siblings
6974 (goto-char (point-min))
6975 (while (re-search-forward re nil t)
6976 (if (and (not (outline-invisible-p))
6977 (save-excursion
6978 (goto-char (point-at-eol)) (outline-invisible-p)))
6979 (hide-entry))))
6980 (org-cycle-show-empty-lines 'overview)
6981 (org-cycle-hide-drawers 'overview)))))
6983 (defun org-cycle-show-empty-lines (state)
6984 "Show empty lines above all visible headlines.
6985 The region to be covered depends on STATE when called through
6986 `org-cycle-hook'. Lisp program can use t for STATE to get the
6987 entire buffer covered. Note that an empty line is only shown if there
6988 are at least `org-cycle-separator-lines' empty lines before the headline."
6989 (when (not (= org-cycle-separator-lines 0))
6990 (save-excursion
6991 (let* ((n (abs org-cycle-separator-lines))
6992 (re (cond
6993 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6994 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6995 (t (let ((ns (number-to-string (- n 2))))
6996 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6997 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6998 beg end b e)
6999 (cond
7000 ((memq state '(overview contents t))
7001 (setq beg (point-min) end (point-max)))
7002 ((memq state '(children folded))
7003 (setq beg (point) end (progn (org-end-of-subtree t t)
7004 (beginning-of-line 2)
7005 (point)))))
7006 (when beg
7007 (goto-char beg)
7008 (while (re-search-forward re end t)
7009 (unless (get-char-property (match-end 1) 'invisible)
7010 (setq e (match-end 1))
7011 (if (< org-cycle-separator-lines 0)
7012 (setq b (save-excursion
7013 (goto-char (match-beginning 0))
7014 (org-back-over-empty-lines)
7015 (if (save-excursion
7016 (goto-char (max (point-min) (1- (point))))
7017 (org-at-heading-p))
7018 (1- (point))
7019 (point))))
7020 (setq b (match-beginning 1)))
7021 (outline-flag-region b e nil)))))))
7022 ;; Never hide empty lines at the end of the file.
7023 (save-excursion
7024 (goto-char (point-max))
7025 (outline-previous-heading)
7026 (outline-end-of-heading)
7027 (if (and (looking-at "[ \t\n]+")
7028 (= (match-end 0) (point-max)))
7029 (outline-flag-region (point) (match-end 0) nil))))
7031 (defun org-show-empty-lines-in-parent ()
7032 "Move to the parent and re-show empty lines before visible headlines."
7033 (save-excursion
7034 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7035 (org-cycle-show-empty-lines context))))
7037 (defun org-files-list ()
7038 "Return `org-agenda-files' list, plus all open org-mode files.
7039 This is useful for operations that need to scan all of a user's
7040 open and agenda-wise Org files."
7041 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7042 (dolist (buf (buffer-list))
7043 (with-current-buffer buf
7044 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7045 (let ((file (expand-file-name (buffer-file-name))))
7046 (unless (member file files)
7047 (push file files))))))
7048 files))
7050 (defsubst org-entry-beginning-position ()
7051 "Return the beginning position of the current entry."
7052 (save-excursion (outline-back-to-heading t) (point)))
7054 (defsubst org-entry-end-position ()
7055 "Return the end position of the current entry."
7056 (save-excursion (outline-next-heading) (point)))
7058 (defun org-cycle-hide-drawers (state)
7059 "Re-hide all drawers after a visibility state change."
7060 (when (and (derived-mode-p 'org-mode)
7061 (not (memq state '(overview folded contents))))
7062 (save-excursion
7063 (let* ((globalp (memq state '(contents all)))
7064 (beg (if globalp (point-min) (point)))
7065 (end (if globalp (point-max)
7066 (if (eq state 'children)
7067 (save-excursion (outline-next-heading) (point))
7068 (org-end-of-subtree t)))))
7069 (goto-char beg)
7070 (while (re-search-forward org-drawer-regexp end t)
7071 (org-flag-drawer t))))))
7073 (defun org-cycle-hide-inline-tasks (state)
7074 "Re-hide inline task when switching to 'contents visibility state."
7075 (when (and (eq state 'contents)
7076 (boundp 'org-inlinetask-min-level)
7077 org-inlinetask-min-level)
7078 (hide-sublevels (1- org-inlinetask-min-level))))
7080 (defun org-flag-drawer (flag)
7081 "When FLAG is non-nil, hide the drawer we are within.
7082 Otherwise make it visible."
7083 (save-excursion
7084 (beginning-of-line 1)
7085 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7086 (let ((b (match-end 0)))
7087 (if (re-search-forward
7088 "^[ \t]*:END:"
7089 (save-excursion (outline-next-heading) (point)) t)
7090 (outline-flag-region b (point-at-eol) flag)
7091 (user-error ":END: line missing at position %s" b))))))
7093 (defun org-subtree-end-visible-p ()
7094 "Is the end of the current subtree visible?"
7095 (pos-visible-in-window-p
7096 (save-excursion (org-end-of-subtree t) (point))))
7098 (defun org-first-headline-recenter (&optional N)
7099 "Move cursor to the first headline and recenter the headline.
7100 Optional argument N means put the headline into the Nth line of the window."
7101 (goto-char (point-min))
7102 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7103 (beginning-of-line)
7104 (recenter (prefix-numeric-value N))))
7106 ;;; Saving and restoring visibility
7108 (defun org-outline-overlay-data (&optional use-markers)
7109 "Return a list of the locations of all outline overlays.
7110 These are overlays with the `invisible' property value `outline'.
7111 The return value is a list of cons cells, with start and stop
7112 positions for each overlay.
7113 If USE-MARKERS is set, return the positions as markers."
7114 (let (beg end)
7115 (save-excursion
7116 (save-restriction
7117 (widen)
7118 (delq nil
7119 (mapcar (lambda (o)
7120 (when (eq (overlay-get o 'invisible) 'outline)
7121 (setq beg (overlay-start o)
7122 end (overlay-end o))
7123 (and beg end (> end beg)
7124 (if use-markers
7125 (cons (move-marker (make-marker) beg)
7126 (move-marker (make-marker) end))
7127 (cons beg end)))))
7128 (overlays-in (point-min) (point-max))))))))
7130 (defun org-set-outline-overlay-data (data)
7131 "Create visibility overlays for all positions in DATA.
7132 DATA should have been made by `org-outline-overlay-data'."
7133 (let (o)
7134 (save-excursion
7135 (save-restriction
7136 (widen)
7137 (show-all)
7138 (mapc (lambda (c)
7139 (outline-flag-region (car c) (cdr c) t))
7140 data)))))
7142 ;;; Folding of blocks
7144 (defvar org-hide-block-overlays nil
7145 "Overlays hiding blocks.")
7146 (make-variable-buffer-local 'org-hide-block-overlays)
7148 (defun org-block-map (function &optional start end)
7149 "Call FUNCTION at the head of all source blocks in the current buffer.
7150 Optional arguments START and END can be used to limit the range."
7151 (let ((start (or start (point-min)))
7152 (end (or end (point-max))))
7153 (save-excursion
7154 (goto-char start)
7155 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7156 (save-excursion
7157 (save-match-data
7158 (goto-char (match-beginning 0))
7159 (funcall function)))))))
7161 (defun org-hide-block-toggle-all ()
7162 "Toggle the visibility of all blocks in the current buffer."
7163 (org-block-map #'org-hide-block-toggle))
7165 (defun org-hide-block-all ()
7166 "Fold all blocks in the current buffer."
7167 (interactive)
7168 (org-show-block-all)
7169 (org-block-map #'org-hide-block-toggle-maybe))
7171 (defun org-show-block-all ()
7172 "Unfold all blocks in the current buffer."
7173 (interactive)
7174 (mapc 'delete-overlay org-hide-block-overlays)
7175 (setq org-hide-block-overlays nil))
7177 (defun org-hide-block-toggle-maybe ()
7178 "Toggle visibility of block at point."
7179 (interactive)
7180 (let ((case-fold-search t))
7181 (if (save-excursion
7182 (beginning-of-line 1)
7183 (looking-at org-block-regexp))
7184 (progn (org-hide-block-toggle)
7185 t) ;; to signal that we took action
7186 nil))) ;; to signal that we did not
7188 (defun org-hide-block-toggle (&optional force)
7189 "Toggle the visibility of the current block."
7190 (interactive)
7191 (save-excursion
7192 (beginning-of-line)
7193 (if (re-search-forward org-block-regexp nil t)
7194 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7195 (end (match-end 0)) ;; end of entire body
7197 (if (memq t (mapcar (lambda (overlay)
7198 (eq (overlay-get overlay 'invisible)
7199 'org-hide-block))
7200 (overlays-at start)))
7201 (if (or (not force) (eq force 'off))
7202 (mapc (lambda (ov)
7203 (when (member ov org-hide-block-overlays)
7204 (setq org-hide-block-overlays
7205 (delq ov org-hide-block-overlays)))
7206 (when (eq (overlay-get ov 'invisible)
7207 'org-hide-block)
7208 (delete-overlay ov)))
7209 (overlays-at start)))
7210 (setq ov (make-overlay start end))
7211 (overlay-put ov 'invisible 'org-hide-block)
7212 ;; make the block accessible to isearch
7213 (overlay-put
7214 ov 'isearch-open-invisible
7215 (lambda (ov)
7216 (when (member ov org-hide-block-overlays)
7217 (setq org-hide-block-overlays
7218 (delq ov org-hide-block-overlays)))
7219 (when (eq (overlay-get ov 'invisible)
7220 'org-hide-block)
7221 (delete-overlay ov))))
7222 (push ov org-hide-block-overlays)))
7223 (user-error "Not looking at a source block"))))
7225 ;; org-tab-after-check-for-cycling-hook
7226 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7227 ;; Remove overlays when changing major mode
7228 (add-hook 'org-mode-hook
7229 (lambda () (org-add-hook 'change-major-mode-hook
7230 'org-show-block-all 'append 'local)))
7232 ;;; Org-goto
7234 (defvar org-goto-window-configuration nil)
7235 (defvar org-goto-marker nil)
7236 (defvar org-goto-map)
7237 (defun org-goto-map ()
7238 "Set the keymap `org-goto'."
7239 (setq org-goto-map
7240 (let ((map (make-sparse-keymap)))
7241 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7242 mouse-drag-region universal-argument org-occur))
7243 cmd)
7244 (while (setq cmd (pop cmds))
7245 (substitute-key-definition cmd cmd map global-map)))
7246 (suppress-keymap map)
7247 (org-defkey map "\C-m" 'org-goto-ret)
7248 (org-defkey map [(return)] 'org-goto-ret)
7249 (org-defkey map [(left)] 'org-goto-left)
7250 (org-defkey map [(right)] 'org-goto-right)
7251 (org-defkey map [(control ?g)] 'org-goto-quit)
7252 (org-defkey map "\C-i" 'org-cycle)
7253 (org-defkey map [(tab)] 'org-cycle)
7254 (org-defkey map [(down)] 'outline-next-visible-heading)
7255 (org-defkey map [(up)] 'outline-previous-visible-heading)
7256 (if org-goto-auto-isearch
7257 (if (fboundp 'define-key-after)
7258 (define-key-after map [t] 'org-goto-local-auto-isearch)
7259 nil)
7260 (org-defkey map "q" 'org-goto-quit)
7261 (org-defkey map "n" 'outline-next-visible-heading)
7262 (org-defkey map "p" 'outline-previous-visible-heading)
7263 (org-defkey map "f" 'outline-forward-same-level)
7264 (org-defkey map "b" 'outline-backward-same-level)
7265 (org-defkey map "u" 'outline-up-heading))
7266 (org-defkey map "/" 'org-occur)
7267 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7268 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7269 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7270 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7271 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7272 map)))
7274 (defconst org-goto-help
7275 "Browse buffer copy, to find location or copy text.%s
7276 RET=jump to location C-g=quit and return to previous location
7277 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7279 (defvar org-goto-start-pos) ; dynamically scoped parameter
7281 (defun org-goto (&optional alternative-interface)
7282 "Look up a different location in the current file, keeping current visibility.
7284 When you want look-up or go to a different location in a
7285 document, the fastest way is often to fold the entire buffer and
7286 then dive into the tree. This method has the disadvantage, that
7287 the previous location will be folded, which may not be what you
7288 want.
7290 This command works around this by showing a copy of the current
7291 buffer in an indirect buffer, in overview mode. You can dive
7292 into the tree in that copy, use org-occur and incremental search
7293 to find a location. When pressing RET or `Q', the command
7294 returns to the original buffer in which the visibility is still
7295 unchanged. After RET it will also jump to the location selected
7296 in the indirect buffer and expose the headline hierarchy above.
7298 With a prefix argument, use the alternative interface: e.g. if
7299 `org-goto-interface' is 'outline use 'outline-path-completion."
7300 (interactive "P")
7301 (org-goto-map)
7302 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7303 (org-refile-use-outline-path t)
7304 (org-refile-target-verify-function nil)
7305 (interface
7306 (if (not alternative-interface)
7307 org-goto-interface
7308 (if (eq org-goto-interface 'outline)
7309 'outline-path-completion
7310 'outline)))
7311 (org-goto-start-pos (point))
7312 (selected-point
7313 (if (eq interface 'outline)
7314 (car (org-get-location (current-buffer) org-goto-help))
7315 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7316 (org-refile-check-position pa)
7317 (nth 3 pa)))))
7318 (if selected-point
7319 (progn
7320 (org-mark-ring-push org-goto-start-pos)
7321 (goto-char selected-point)
7322 (if (or (outline-invisible-p) (org-invisible-p2))
7323 (org-show-context 'org-goto)))
7324 (message "Quit"))))
7326 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7327 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7328 (defvar org-goto-local-auto-isearch-map) ; defined below
7330 (defun org-get-location (buf help)
7331 "Let the user select a location in the Org-mode buffer BUF.
7332 This function uses a recursive edit. It returns the selected position
7333 or nil."
7334 (org-no-popups
7335 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7336 (isearch-hide-immediately nil)
7337 (isearch-search-fun-function
7338 (lambda () 'org-goto-local-search-headings))
7339 (org-goto-selected-point org-goto-exit-command))
7340 (save-excursion
7341 (save-window-excursion
7342 (delete-other-windows)
7343 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7344 (org-pop-to-buffer-same-window
7345 (condition-case nil
7346 (make-indirect-buffer (current-buffer) "*org-goto*")
7347 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7348 (with-output-to-temp-buffer "*Org Help*"
7349 (princ (format help (if org-goto-auto-isearch
7350 " Just type for auto-isearch."
7351 " n/p/f/b/u to navigate, q to quit."))))
7352 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7353 (setq buffer-read-only nil)
7354 (let ((org-startup-truncated t)
7355 (org-startup-folded nil)
7356 (org-startup-align-all-tables nil))
7357 (org-mode)
7358 (org-overview))
7359 (setq buffer-read-only t)
7360 (if (and (boundp 'org-goto-start-pos)
7361 (integer-or-marker-p org-goto-start-pos))
7362 (let ((org-show-hierarchy-above t)
7363 (org-show-siblings t)
7364 (org-show-following-heading t))
7365 (goto-char org-goto-start-pos)
7366 (and (outline-invisible-p) (org-show-context)))
7367 (goto-char (point-min)))
7368 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7369 (message "Select location and press RET")
7370 (use-local-map org-goto-map)
7371 (recursive-edit)))
7372 (kill-buffer "*org-goto*")
7373 (cons org-goto-selected-point org-goto-exit-command))))
7375 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7376 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7377 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7378 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7380 (defun org-goto-local-search-headings (string bound noerror)
7381 "Search and make sure that any matches are in headlines."
7382 (catch 'return
7383 (while (if isearch-forward
7384 (search-forward string bound noerror)
7385 (search-backward string bound noerror))
7386 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7387 (and (member :headline context)
7388 (not (member :tags context))))
7389 (throw 'return (point))))))
7391 (defun org-goto-local-auto-isearch ()
7392 "Start isearch."
7393 (interactive)
7394 (goto-char (point-min))
7395 (let ((keys (this-command-keys)))
7396 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7397 (isearch-mode t)
7398 (isearch-process-search-char (string-to-char keys)))))
7400 (defun org-goto-ret (&optional arg)
7401 "Finish `org-goto' by going to the new location."
7402 (interactive "P")
7403 (setq org-goto-selected-point (point)
7404 org-goto-exit-command 'return)
7405 (throw 'exit nil))
7407 (defun org-goto-left ()
7408 "Finish `org-goto' by going to the new location."
7409 (interactive)
7410 (if (org-at-heading-p)
7411 (progn
7412 (beginning-of-line 1)
7413 (setq org-goto-selected-point (point)
7414 org-goto-exit-command 'left)
7415 (throw 'exit nil))
7416 (user-error "Not on a heading")))
7418 (defun org-goto-right ()
7419 "Finish `org-goto' by going to the new location."
7420 (interactive)
7421 (if (org-at-heading-p)
7422 (progn
7423 (setq org-goto-selected-point (point)
7424 org-goto-exit-command 'right)
7425 (throw 'exit nil))
7426 (user-error "Not on a heading")))
7428 (defun org-goto-quit ()
7429 "Finish `org-goto' without cursor motion."
7430 (interactive)
7431 (setq org-goto-selected-point nil)
7432 (setq org-goto-exit-command 'quit)
7433 (throw 'exit nil))
7435 ;;; Indirect buffer display of subtrees
7437 (defvar org-indirect-dedicated-frame nil
7438 "This is the frame being used for indirect tree display.")
7439 (defvar org-last-indirect-buffer nil)
7441 (defun org-tree-to-indirect-buffer (&optional arg)
7442 "Create indirect buffer and narrow it to current subtree.
7443 With a numerical prefix ARG, go up to this level and then take that tree.
7444 If ARG is negative, go up that many levels.
7446 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7447 indirect buffer previously made with this command, to avoid proliferation of
7448 indirect buffers. However, when you call the command with a \
7449 \\[universal-argument] prefix, or
7450 when `org-indirect-buffer-display' is `new-frame', the last buffer
7451 is kept so that you can work with several indirect buffers at the same time.
7452 If `org-indirect-buffer-display' is `dedicated-frame', the \
7453 \\[universal-argument] prefix also
7454 requests that a new frame be made for the new buffer, so that the dedicated
7455 frame is not changed."
7456 (interactive "P")
7457 (let ((cbuf (current-buffer))
7458 (cwin (selected-window))
7459 (pos (point))
7460 beg end level heading ibuf)
7461 (save-excursion
7462 (org-back-to-heading t)
7463 (when (numberp arg)
7464 (setq level (org-outline-level))
7465 (if (< arg 0) (setq arg (+ level arg)))
7466 (while (> (setq level (org-outline-level)) arg)
7467 (org-up-heading-safe)))
7468 (setq beg (point)
7469 heading (org-get-heading))
7470 (org-end-of-subtree t t)
7471 (if (org-at-heading-p) (backward-char 1))
7472 (setq end (point)))
7473 (if (and (buffer-live-p org-last-indirect-buffer)
7474 (not (eq org-indirect-buffer-display 'new-frame))
7475 (not arg))
7476 (kill-buffer org-last-indirect-buffer))
7477 (setq ibuf (org-get-indirect-buffer cbuf)
7478 org-last-indirect-buffer ibuf)
7479 (cond
7480 ((or (eq org-indirect-buffer-display 'new-frame)
7481 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7482 (select-frame (make-frame))
7483 (delete-other-windows)
7484 (org-pop-to-buffer-same-window ibuf)
7485 (org-set-frame-title heading))
7486 ((eq org-indirect-buffer-display 'dedicated-frame)
7487 (raise-frame
7488 (select-frame (or (and org-indirect-dedicated-frame
7489 (frame-live-p org-indirect-dedicated-frame)
7490 org-indirect-dedicated-frame)
7491 (setq org-indirect-dedicated-frame (make-frame)))))
7492 (delete-other-windows)
7493 (org-pop-to-buffer-same-window ibuf)
7494 (org-set-frame-title (concat "Indirect: " heading)))
7495 ((eq org-indirect-buffer-display 'current-window)
7496 (org-pop-to-buffer-same-window ibuf))
7497 ((eq org-indirect-buffer-display 'other-window)
7498 (pop-to-buffer ibuf))
7499 (t (error "Invalid value")))
7500 (if (featurep 'xemacs)
7501 (save-excursion (org-mode) (turn-on-font-lock)))
7502 (narrow-to-region beg end)
7503 (show-all)
7504 (goto-char pos)
7505 (run-hook-with-args 'org-cycle-hook 'all)
7506 (and (window-live-p cwin) (select-window cwin))))
7508 (defun org-get-indirect-buffer (&optional buffer)
7509 (setq buffer (or buffer (current-buffer)))
7510 (let ((n 1) (base (buffer-name buffer)) bname)
7511 (while (buffer-live-p
7512 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7513 (setq n (1+ n)))
7514 (condition-case nil
7515 (make-indirect-buffer buffer bname 'clone)
7516 (error (make-indirect-buffer buffer bname)))))
7518 (defun org-set-frame-title (title)
7519 "Set the title of the current frame to the string TITLE."
7520 ;; FIXME: how to name a single frame in XEmacs???
7521 (unless (featurep 'xemacs)
7522 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7524 ;;;; Structure editing
7526 ;;; Inserting headlines
7528 (defun org-previous-line-empty-p (&optional next)
7529 "Is the previous line a blank line?
7530 When NEXT is non-nil, check the next line instead."
7531 (save-excursion
7532 (and (not (bobp))
7533 (or (beginning-of-line (if next 2 0)) t)
7534 (save-match-data
7535 (looking-at "[ \t]*$")))))
7537 (defun org-insert-heading (&optional arg invisible-ok)
7538 "Insert a new heading or item with same depth at point.
7539 If point is in a plain list and ARG is nil, create a new list item.
7540 With one universal prefix argument, insert a heading even in lists.
7541 With two universal prefix arguments, insert the heading at the end
7542 of the parent subtree.
7544 If point is at the beginning of a headline, insert a sibling before
7545 the current headline. If point is not at the beginning, split the line
7546 and create a new headline with the text in the current line after point
7547 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7549 If point is at the beginning of a normal line, turn this line into
7550 a heading.
7552 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7553 This is important for non-interactive uses of the command."
7554 (interactive "P")
7555 (if (org-called-interactively-p 'any) (org-reveal))
7556 (let ((itemp (org-in-item-p))
7557 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7558 (respect-content (or org-insert-heading-respect-content
7559 (equal arg '(16))))
7560 (initial-content "")
7561 (adjust-empty-lines t))
7563 (cond
7565 ((or (= (buffer-size) 0)
7566 (and (not (save-excursion
7567 (and (ignore-errors (org-back-to-heading invisible-ok))
7568 (org-at-heading-p))))
7569 (or arg (not itemp))))
7570 ;; At beginning of buffer or so high up that only a heading
7571 ;; makes sense.
7572 (insert
7573 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7574 (if (org-in-src-block-p) ",* " "* "))
7575 (run-hooks 'org-insert-heading-hook))
7577 ((and itemp (not (equal arg '(4))))
7578 ;; Insert an item
7579 (org-insert-item))
7582 ;; Insert a heading
7583 (save-restriction
7584 (widen)
7585 (let* ((level nil)
7586 (on-heading (org-at-heading-p))
7587 (empty-line-p (if on-heading
7588 (org-previous-line-empty-p)
7589 ;; We will decide later
7590 nil))
7591 ;; Get a level string to fall back on
7592 (fix-level
7593 (save-excursion
7594 (org-back-to-heading t)
7595 (if (org-previous-line-empty-p) (setq empty-line-p t))
7596 (looking-at org-outline-regexp)
7597 (make-string (1- (length (match-string 0))) ?*)))
7598 (stars
7599 (save-excursion
7600 (condition-case nil
7601 (progn
7602 (org-back-to-heading invisible-ok)
7603 (when (and (not on-heading)
7604 (featurep 'org-inlinetask)
7605 (integerp org-inlinetask-min-level)
7606 (>= (length (match-string 0))
7607 org-inlinetask-min-level))
7608 ;; Find a heading level before the inline task
7609 (while (and (setq level (org-up-heading-safe))
7610 (>= level org-inlinetask-min-level)))
7611 (if (org-at-heading-p)
7612 (org-back-to-heading invisible-ok)
7613 (error "This should not happen")))
7614 (unless (and (save-excursion
7615 (save-match-data
7616 (org-backward-heading-same-level
7617 1 invisible-ok))
7618 (= (point) (match-beginning 0)))
7619 (not (org-previous-line-empty-p t)))
7620 (setq empty-line-p (or empty-line-p
7621 (org-previous-line-empty-p))))
7622 (match-string 0))
7623 (error (or fix-level "* ")))))
7624 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7625 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7626 pos hide-previous previous-pos)
7628 ;; If we insert after content, move there and clean up whitespace
7629 (when respect-content
7630 (org-end-of-subtree nil t)
7631 (skip-chars-backward " \r\n")
7632 (and (looking-at "[ \t]+") (replace-match ""))
7633 (unless (eobp) (forward-char 1))
7634 (when (looking-at "^\\*")
7635 (unless (bobp) (backward-char 1))
7636 (insert "\n")))
7638 ;; If we are splitting, grab the text that should be moved to the new headline
7639 (when may-split
7640 (if (org-on-heading-p)
7641 ;; This is a heading, we split intelligently (keeping tags)
7642 (let ((pos (point)))
7643 (goto-char (point-at-bol))
7644 (unless (looking-at org-complex-heading-regexp)
7645 (error "This should not happen"))
7646 (when (and (match-beginning 4)
7647 (> pos (match-beginning 4))
7648 (< pos (match-end 4)))
7649 (setq initial-content (buffer-substring pos (match-end 4)))
7650 (goto-char pos)
7651 (delete-region (point) (match-end 4))
7652 (if (looking-at "[ \t]*$")
7653 (replace-match "")
7654 (insert (make-string (length initial-content) ?\ )))
7655 (setq initial-content (org-trim initial-content)))
7656 (goto-char pos))
7657 ;; a normal line
7658 (unless (bolp)
7659 (setq initial-content (buffer-substring (point) (point-at-eol)))
7660 (delete-region (point) (point-at-eol))
7661 (setq initial-content (org-trim initial-content)))))
7663 ;; If we are at the beginning of the line, insert before it. Else after
7664 (cond
7665 ((and (bolp) (looking-at "[ \t]*$")))
7666 ((and (bolp) (not (looking-at "[ \t]*$")))
7667 (open-line 1))
7669 (goto-char (point-at-eol))
7670 (insert "\n")))
7672 ;; Insert the new heading
7673 (insert stars)
7674 (just-one-space)
7675 (insert initial-content)
7676 (when adjust-empty-lines
7677 (if (or (not blank)
7678 (and blank (not (org-previous-line-empty-p))))
7679 (org-N-empty-lines-before-current (if blank 1 0))))
7680 (run-hooks 'org-insert-heading-hook)))))))
7682 (defun org-N-empty-lines-before-current (N)
7683 "Make the number of empty lines before current exactly N.
7684 So this will delete or add empty lines."
7685 (save-excursion
7686 (goto-char (point-at-bol))
7687 (if (looking-back "\\s-+" nil 'greedy)
7688 (replace-match ""))
7689 (or (bobp) (insert "\n"))
7690 (while (> N 0)
7691 (insert "\n")
7692 (setq N (1- N)))))
7694 (defun org-get-heading (&optional no-tags no-todo)
7695 "Return the heading of the current entry, without the stars.
7696 When NO-TAGS is non-nil, don't include tags.
7697 When NO-TODO is non-nil, don't include TODO keywords."
7698 (save-excursion
7699 (org-back-to-heading t)
7700 (cond
7701 ((and no-tags no-todo)
7702 (looking-at org-complex-heading-regexp)
7703 (match-string 4))
7704 (no-tags
7705 (looking-at (concat org-outline-regexp
7706 "\\(.*?\\)"
7707 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7708 (match-string 1))
7709 (no-todo
7710 (looking-at org-todo-line-regexp)
7711 (match-string 3))
7712 (t (looking-at org-heading-regexp)
7713 (match-string 2)))))
7715 (defvar orgstruct-mode) ; defined below
7717 (defun org-heading-components ()
7718 "Return the components of the current heading.
7719 This is a list with the following elements:
7720 - the level as an integer
7721 - the reduced level, different if `org-odd-levels-only' is set.
7722 - the TODO keyword, or nil
7723 - the priority character, like ?A, or nil if no priority is given
7724 - the headline text itself, or the tags string if no headline text
7725 - the tags string, or nil."
7726 (save-excursion
7727 (org-back-to-heading t)
7728 (if (let (case-fold-search)
7729 (looking-at
7730 (if orgstruct-mode
7731 org-heading-regexp
7732 org-complex-heading-regexp)))
7733 (if orgstruct-mode
7734 (list (length (match-string 1))
7735 (org-reduced-level (length (match-string 1)))
7738 (match-string 2)
7739 nil)
7740 (list (length (match-string 1))
7741 (org-reduced-level (length (match-string 1)))
7742 (org-match-string-no-properties 2)
7743 (and (match-end 3) (aref (match-string 3) 2))
7744 (org-match-string-no-properties 4)
7745 (org-match-string-no-properties 5))))))
7747 (defun org-get-entry ()
7748 "Get the entry text, after heading, entire subtree."
7749 (save-excursion
7750 (org-back-to-heading t)
7751 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7753 (defun org-insert-heading-after-current ()
7754 "Insert a new heading with same level as current, after current subtree."
7755 (interactive)
7756 (org-back-to-heading)
7757 (org-insert-heading)
7758 (org-move-subtree-down)
7759 (end-of-line 1))
7761 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7762 "Insert heading with `org-insert-heading-respect-content' set to t."
7763 (interactive "P")
7764 (let ((org-insert-heading-respect-content t))
7765 (org-insert-heading '(4) invisible-ok)))
7767 (defun org-insert-todo-heading-respect-content (&optional force-state)
7768 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7769 (interactive "P")
7770 (let ((org-insert-heading-respect-content t))
7771 (org-insert-todo-heading force-state '(4))))
7773 (defun org-insert-todo-heading (arg &optional force-heading)
7774 "Insert a new heading with the same level and TODO state as current heading.
7775 If the heading has no TODO state, or if the state is DONE, use the first
7776 state (TODO by default). Also one prefix arg, force first state. With two
7777 prefix args, force inserting at the end of the parent subtree."
7778 (interactive "P")
7779 (when (or force-heading (not (org-insert-item 'checkbox)))
7780 (org-insert-heading (or (and (equal arg '(16)) '(16))
7781 force-heading))
7782 (save-excursion
7783 (org-back-to-heading)
7784 (outline-previous-heading)
7785 (looking-at org-todo-line-regexp))
7786 (let*
7787 ((new-mark-x
7788 (if (or arg
7789 (not (match-beginning 2))
7790 (member (match-string 2) org-done-keywords))
7791 (car org-todo-keywords-1)
7792 (match-string 2)))
7793 (new-mark
7795 (run-hook-with-args-until-success
7796 'org-todo-get-default-hook new-mark-x nil)
7797 new-mark-x)))
7798 (beginning-of-line 1)
7799 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7800 (if org-treat-insert-todo-heading-as-state-change
7801 (org-todo new-mark)
7802 (insert new-mark " "))))
7803 (when org-provide-todo-statistics
7804 (org-update-parent-todo-statistics))))
7806 (defun org-insert-subheading (arg)
7807 "Insert a new subheading and demote it.
7808 Works for outline headings and for plain lists alike."
7809 (interactive "P")
7810 (org-insert-heading arg)
7811 (cond
7812 ((org-at-heading-p) (org-do-demote))
7813 ((org-at-item-p) (org-indent-item))))
7815 (defun org-insert-todo-subheading (arg)
7816 "Insert a new subheading with TODO keyword or checkbox and demote it.
7817 Works for outline headings and for plain lists alike."
7818 (interactive "P")
7819 (org-insert-todo-heading arg)
7820 (cond
7821 ((org-at-heading-p) (org-do-demote))
7822 ((org-at-item-p) (org-indent-item))))
7824 ;;; Promotion and Demotion
7826 (defvar org-after-demote-entry-hook nil
7827 "Hook run after an entry has been demoted.
7828 The cursor will be at the beginning of the entry.
7829 When a subtree is being demoted, the hook will be called for each node.")
7831 (defvar org-after-promote-entry-hook nil
7832 "Hook run after an entry has been promoted.
7833 The cursor will be at the beginning of the entry.
7834 When a subtree is being promoted, the hook will be called for each node.")
7836 (defun org-promote-subtree ()
7837 "Promote the entire subtree.
7838 See also `org-promote'."
7839 (interactive)
7840 (save-excursion
7841 (org-with-limited-levels (org-map-tree 'org-promote)))
7842 (org-fix-position-after-promote))
7844 (defun org-demote-subtree ()
7845 "Demote the entire subtree. See `org-demote'.
7846 See also `org-promote'."
7847 (interactive)
7848 (save-excursion
7849 (org-with-limited-levels (org-map-tree 'org-demote)))
7850 (org-fix-position-after-promote))
7853 (defun org-do-promote ()
7854 "Promote the current heading higher up the tree.
7855 If the region is active in `transient-mark-mode', promote all headings
7856 in the region."
7857 (interactive)
7858 (save-excursion
7859 (if (org-region-active-p)
7860 (org-map-region 'org-promote (region-beginning) (region-end))
7861 (org-promote)))
7862 (org-fix-position-after-promote))
7864 (defun org-do-demote ()
7865 "Demote the current heading lower down the tree.
7866 If the region is active in `transient-mark-mode', demote all headings
7867 in the region."
7868 (interactive)
7869 (save-excursion
7870 (if (org-region-active-p)
7871 (org-map-region 'org-demote (region-beginning) (region-end))
7872 (org-demote)))
7873 (org-fix-position-after-promote))
7875 (defun org-fix-position-after-promote ()
7876 "Make sure that after pro/demotion cursor position is right."
7877 (let ((pos (point)))
7878 (when (save-excursion
7879 (beginning-of-line 1)
7880 (looking-at org-todo-line-regexp)
7881 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7882 (cond ((eobp) (insert " "))
7883 ((eolp) (insert " "))
7884 ((equal (char-after) ?\ ) (forward-char 1))))))
7886 (defun org-current-level ()
7887 "Return the level of the current entry, or nil if before the first headline.
7888 The level is the number of stars at the beginning of the headline."
7889 (save-excursion
7890 (org-with-limited-levels
7891 (if (ignore-errors (org-back-to-heading t))
7892 (funcall outline-level)))))
7894 (defun org-get-previous-line-level ()
7895 "Return the outline depth of the last headline before the current line.
7896 Returns 0 for the first headline in the buffer, and nil if before the
7897 first headline."
7898 (let ((current-level (org-current-level))
7899 (prev-level (when (> (line-number-at-pos) 1)
7900 (save-excursion
7901 (beginning-of-line 0)
7902 (org-current-level)))))
7903 (cond ((null current-level) nil) ; Before first headline
7904 ((null prev-level) 0) ; At first headline
7905 (prev-level))))
7907 (defun org-reduced-level (l)
7908 "Compute the effective level of a heading.
7909 This takes into account the setting of `org-odd-levels-only'."
7910 (cond
7911 ((zerop l) 0)
7912 (org-odd-levels-only (1+ (floor (/ l 2))))
7913 (t l)))
7915 (defun org-level-increment ()
7916 "Return the number of stars that will be added or removed at a
7917 time to headlines when structure editing, based on the value of
7918 `org-odd-levels-only'."
7919 (if org-odd-levels-only 2 1))
7921 (defun org-get-valid-level (level &optional change)
7922 "Rectify a level change under the influence of `org-odd-levels-only'
7923 LEVEL is a current level, CHANGE is by how much the level should be
7924 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7925 even level numbers will become the next higher odd number."
7926 (if org-odd-levels-only
7927 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7928 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7929 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7930 (max 1 (+ level (or change 0)))))
7932 (if (boundp 'define-obsolete-function-alias)
7933 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7934 (define-obsolete-function-alias 'org-get-legal-level
7935 'org-get-valid-level)
7936 (define-obsolete-function-alias 'org-get-legal-level
7937 'org-get-valid-level "23.1")))
7939 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7940 ;; ̀org-with-limited-levels'
7941 (defun org-promote ()
7942 "Promote the current heading higher up the tree.
7943 If the region is active in `transient-mark-mode', promote all headings
7944 in the region."
7945 (org-back-to-heading t)
7946 (let* ((level (save-match-data (funcall outline-level)))
7947 (after-change-functions (remove 'flyspell-after-change-function
7948 after-change-functions))
7949 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7950 (diff (abs (- level (length up-head) -1))))
7951 (cond ((and (= level 1) org-called-with-limited-levels
7952 org-allow-promoting-top-level-subtree)
7953 (replace-match "# " nil t))
7954 ((= level 1)
7955 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7956 (t (replace-match up-head nil t)))
7957 ;; Fixup tag positioning
7958 (unless (= level 1)
7959 (and org-auto-align-tags (org-set-tags nil t))
7960 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7961 (run-hooks 'org-after-promote-entry-hook)))
7963 (defun org-demote ()
7964 "Demote the current heading lower down the tree.
7965 If the region is active in `transient-mark-mode', demote all headings
7966 in the region."
7967 (org-back-to-heading t)
7968 (let* ((level (save-match-data (funcall outline-level)))
7969 (after-change-functions (remove 'flyspell-after-change-function
7970 after-change-functions))
7971 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7972 (diff (abs (- level (length down-head) -1))))
7973 (replace-match down-head nil t)
7974 ;; Fixup tag positioning
7975 (and org-auto-align-tags (org-set-tags nil t))
7976 (if org-adapt-indentation (org-fixup-indentation diff))
7977 (run-hooks 'org-after-demote-entry-hook)))
7979 (defun org-cycle-level ()
7980 "Cycle the level of an empty headline through possible states.
7981 This goes first to child, then to parent, level, then up the hierarchy.
7982 After top level, it switches back to sibling level."
7983 (interactive)
7984 (let ((org-adapt-indentation nil))
7985 (when (org-point-at-end-of-empty-headline)
7986 (setq this-command 'org-cycle-level) ; Only needed for caching
7987 (let ((cur-level (org-current-level))
7988 (prev-level (org-get-previous-line-level)))
7989 (cond
7990 ;; If first headline in file, promote to top-level.
7991 ((= prev-level 0)
7992 (loop repeat (/ (- cur-level 1) (org-level-increment))
7993 do (org-do-promote)))
7994 ;; If same level as prev, demote one.
7995 ((= prev-level cur-level)
7996 (org-do-demote))
7997 ;; If parent is top-level, promote to top level if not already.
7998 ((= prev-level 1)
7999 (loop repeat (/ (- cur-level 1) (org-level-increment))
8000 do (org-do-promote)))
8001 ;; If top-level, return to prev-level.
8002 ((= cur-level 1)
8003 (loop repeat (/ (- prev-level 1) (org-level-increment))
8004 do (org-do-demote)))
8005 ;; If less than prev-level, promote one.
8006 ((< cur-level prev-level)
8007 (org-do-promote))
8008 ;; If deeper than prev-level, promote until higher than
8009 ;; prev-level.
8010 ((> cur-level prev-level)
8011 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8012 do (org-do-promote))))
8013 t))))
8015 (defun org-map-tree (fun)
8016 "Call FUN for every heading underneath the current one."
8017 (org-back-to-heading)
8018 (let ((level (funcall outline-level)))
8019 (save-excursion
8020 (funcall fun)
8021 (while (and (progn
8022 (outline-next-heading)
8023 (> (funcall outline-level) level))
8024 (not (eobp)))
8025 (funcall fun)))))
8027 (defun org-map-region (fun beg end)
8028 "Call FUN for every heading between BEG and END."
8029 (let ((org-ignore-region t))
8030 (save-excursion
8031 (setq end (copy-marker end))
8032 (goto-char beg)
8033 (if (and (re-search-forward org-outline-regexp-bol nil t)
8034 (< (point) end))
8035 (funcall fun))
8036 (while (and (progn
8037 (outline-next-heading)
8038 (< (point) end))
8039 (not (eobp)))
8040 (funcall fun)))))
8042 (defvar org-property-end-re) ; silence byte-compiler
8043 (defun org-fixup-indentation (diff)
8044 "Change the indentation in the current entry by DIFF.
8045 However, if any line in the current entry has no indentation, or if it
8046 would end up with no indentation after the change, nothing at all is done."
8047 (save-excursion
8048 (let ((end (save-excursion (outline-next-heading)
8049 (point-marker)))
8050 (prohibit (if (> diff 0)
8051 "^\\S-"
8052 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8053 col)
8054 (unless (save-excursion (end-of-line 1)
8055 (re-search-forward prohibit end t))
8056 (while (and (< (point) end)
8057 (re-search-forward "^[ \t]+" end t))
8058 (goto-char (match-end 0))
8059 (setq col (current-column))
8060 (if (< diff 0) (replace-match ""))
8061 (org-indent-to-column (+ diff col))))
8062 (move-marker end nil))))
8064 (defun org-convert-to-odd-levels ()
8065 "Convert an org-mode file with all levels allowed to one with odd levels.
8066 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8067 level 5 etc."
8068 (interactive)
8069 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8070 (let ((outline-level 'org-outline-level)
8071 (org-odd-levels-only nil) n)
8072 (save-excursion
8073 (goto-char (point-min))
8074 (while (re-search-forward "^\\*\\*+ " nil t)
8075 (setq n (- (length (match-string 0)) 2))
8076 (while (>= (setq n (1- n)) 0)
8077 (org-demote))
8078 (end-of-line 1))))))
8080 (defun org-convert-to-oddeven-levels ()
8081 "Convert an org-mode file with only odd levels to one with odd/even levels.
8082 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8083 file contains a section with an even level, conversion would
8084 destroy the structure of the file. An error is signaled in this
8085 case."
8086 (interactive)
8087 (goto-char (point-min))
8088 ;; First check if there are no even levels
8089 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8090 (org-show-context t)
8091 (error "Not all levels are odd in this file. Conversion not possible"))
8092 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8093 (let ((outline-regexp org-outline-regexp)
8094 (outline-level 'org-outline-level)
8095 (org-odd-levels-only nil) n)
8096 (save-excursion
8097 (goto-char (point-min))
8098 (while (re-search-forward "^\\*\\*+ " nil t)
8099 (setq n (/ (1- (length (match-string 0))) 2))
8100 (while (>= (setq n (1- n)) 0)
8101 (org-promote))
8102 (end-of-line 1))))))
8104 (defun org-tr-level (n)
8105 "Make N odd if required."
8106 (if org-odd-levels-only (1+ (/ n 2)) n))
8108 ;;; Vertical tree motion, cutting and pasting of subtrees
8110 (defun org-move-subtree-up (&optional arg)
8111 "Move the current subtree up past ARG headlines of the same level."
8112 (interactive "p")
8113 (org-move-subtree-down (- (prefix-numeric-value arg))))
8115 (defun org-move-subtree-down (&optional arg)
8116 "Move the current subtree down past ARG headlines of the same level."
8117 (interactive "p")
8118 (setq arg (prefix-numeric-value arg))
8119 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8120 'org-get-last-sibling))
8121 (ins-point (make-marker))
8122 (cnt (abs arg))
8123 (col (current-column))
8124 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8125 ;; Select the tree
8126 (org-back-to-heading)
8127 (setq beg0 (point))
8128 (save-excursion
8129 (setq ne-beg (org-back-over-empty-lines))
8130 (setq beg (point)))
8131 (save-match-data
8132 (save-excursion (outline-end-of-heading)
8133 (setq folded (outline-invisible-p)))
8134 (outline-end-of-subtree))
8135 (outline-next-heading)
8136 (setq ne-end (org-back-over-empty-lines))
8137 (setq end (point))
8138 (goto-char beg0)
8139 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8140 ;; include less whitespace
8141 (save-excursion
8142 (goto-char beg)
8143 (forward-line (- ne-beg ne-end))
8144 (setq beg (point))))
8145 ;; Find insertion point, with error handling
8146 (while (> cnt 0)
8147 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8148 (progn (goto-char beg0)
8149 (user-error "Cannot move past superior level or buffer limit")))
8150 (setq cnt (1- cnt)))
8151 (if (> arg 0)
8152 ;; Moving forward - still need to move over subtree
8153 (progn (org-end-of-subtree t t)
8154 (save-excursion
8155 (org-back-over-empty-lines)
8156 (or (bolp) (newline)))))
8157 (setq ne-ins (org-back-over-empty-lines))
8158 (move-marker ins-point (point))
8159 (setq txt (buffer-substring beg end))
8160 (org-save-markers-in-region beg end)
8161 (delete-region beg end)
8162 (org-remove-empty-overlays-at beg)
8163 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8164 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8165 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8166 (let ((bbb (point)))
8167 (insert-before-markers txt)
8168 (org-reinstall-markers-in-region bbb)
8169 (move-marker ins-point bbb))
8170 (or (bolp) (insert "\n"))
8171 (setq ins-end (point))
8172 (goto-char ins-point)
8173 (org-skip-whitespace)
8174 (when (and (< arg 0)
8175 (org-first-sibling-p)
8176 (> ne-ins ne-beg))
8177 ;; Move whitespace back to beginning
8178 (save-excursion
8179 (goto-char ins-end)
8180 (let ((kill-whole-line t))
8181 (kill-line (- ne-ins ne-beg)) (point)))
8182 (insert (make-string (- ne-ins ne-beg) ?\n)))
8183 (move-marker ins-point nil)
8184 (if folded
8185 (hide-subtree)
8186 (org-show-entry)
8187 (show-children)
8188 (org-cycle-hide-drawers 'children))
8189 (org-clean-visibility-after-subtree-move)
8190 ;; move back to the initial column we were at
8191 (move-to-column col)))
8193 (defvar org-subtree-clip ""
8194 "Clipboard for cut and paste of subtrees.
8195 This is actually only a copy of the kill, because we use the normal kill
8196 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8198 (defvar org-subtree-clip-folded nil
8199 "Was the last copied subtree folded?
8200 This is used to fold the tree back after pasting.")
8202 (defun org-cut-subtree (&optional n)
8203 "Cut the current subtree into the clipboard.
8204 With prefix arg N, cut this many sequential subtrees.
8205 This is a short-hand for marking the subtree and then cutting it."
8206 (interactive "p")
8207 (org-copy-subtree n 'cut))
8209 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8210 "Copy the current subtree it in the clipboard.
8211 With prefix arg N, copy this many sequential subtrees.
8212 This is a short-hand for marking the subtree and then copying it.
8213 If CUT is non-nil, actually cut the subtree.
8214 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8215 of some markers in the region, even if CUT is non-nil. This is
8216 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8217 (interactive "p")
8218 (let (beg end folded (beg0 (point)))
8219 (if (org-called-interactively-p 'any)
8220 (org-back-to-heading nil) ; take what looks like a subtree
8221 (org-back-to-heading t)) ; take what is really there
8222 (setq beg (point))
8223 (skip-chars-forward " \t\r\n")
8224 (save-match-data
8225 (if nosubtrees
8226 (outline-next-heading)
8227 (save-excursion (outline-end-of-heading)
8228 (setq folded (outline-invisible-p)))
8229 (condition-case nil
8230 (org-forward-heading-same-level (1- n) t)
8231 (error nil))
8232 (org-end-of-subtree t t)))
8233 (setq end (point))
8234 (goto-char beg0)
8235 (when (> end beg)
8236 (setq org-subtree-clip-folded folded)
8237 (when (or cut force-store-markers)
8238 (org-save-markers-in-region beg end))
8239 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8240 (setq org-subtree-clip (current-kill 0))
8241 (message "%s: Subtree(s) with %d characters"
8242 (if cut "Cut" "Copied")
8243 (length org-subtree-clip)))))
8245 (defun org-paste-subtree (&optional level tree for-yank)
8246 "Paste the clipboard as a subtree, with modification of headline level.
8247 The entire subtree is promoted or demoted in order to match a new headline
8248 level.
8250 If the cursor is at the beginning of a headline, the same level as
8251 that headline is used to paste the tree.
8253 If not, the new level is derived from the *visible* headings
8254 before and after the insertion point, and taken to be the inferior headline
8255 level of the two. So if the previous visible heading is level 3 and the
8256 next is level 4 (or vice versa), level 4 will be used for insertion.
8257 This makes sure that the subtree remains an independent subtree and does
8258 not swallow low level entries.
8260 You can also force a different level, either by using a numeric prefix
8261 argument, or by inserting the heading marker by hand. For example, if the
8262 cursor is after \"*****\", then the tree will be shifted to level 5.
8264 If optional TREE is given, use this text instead of the kill ring.
8266 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8267 move back over whitespace before inserting, and move point to the end of
8268 the inserted text when done."
8269 (interactive "P")
8270 (setq tree (or tree (and kill-ring (current-kill 0))))
8271 (unless (org-kill-is-subtree-p tree)
8272 (user-error "%s"
8273 (substitute-command-keys
8274 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8275 (org-with-limited-levels
8276 (let* ((visp (not (outline-invisible-p)))
8277 (txt tree)
8278 (^re_ "\\(\\*+\\)[ \t]*")
8279 (old-level (if (string-match org-outline-regexp-bol txt)
8280 (- (match-end 0) (match-beginning 0) 1)
8281 -1))
8282 (force-level (cond (level (prefix-numeric-value level))
8283 ((and (looking-at "[ \t]*$")
8284 (string-match
8285 "^\\*+$" (buffer-substring
8286 (point-at-bol) (point))))
8287 (- (match-end 1) (match-beginning 1)))
8288 ((and (bolp)
8289 (looking-at org-outline-regexp))
8290 (- (match-end 0) (point) 1))))
8291 (previous-level (save-excursion
8292 (condition-case nil
8293 (progn
8294 (outline-previous-visible-heading 1)
8295 (if (looking-at ^re_)
8296 (- (match-end 0) (match-beginning 0) 1)
8298 (error 1))))
8299 (next-level (save-excursion
8300 (condition-case nil
8301 (progn
8302 (or (looking-at org-outline-regexp)
8303 (outline-next-visible-heading 1))
8304 (if (looking-at ^re_)
8305 (- (match-end 0) (match-beginning 0) 1)
8307 (error 1))))
8308 (new-level (or force-level (max previous-level next-level)))
8309 (shift (if (or (= old-level -1)
8310 (= new-level -1)
8311 (= old-level new-level))
8313 (- new-level old-level)))
8314 (delta (if (> shift 0) -1 1))
8315 (func (if (> shift 0) 'org-demote 'org-promote))
8316 (org-odd-levels-only nil)
8317 beg end newend)
8318 ;; Remove the forced level indicator
8319 (if force-level
8320 (delete-region (point-at-bol) (point)))
8321 ;; Paste
8322 (beginning-of-line (if (bolp) 1 2))
8323 (setq beg (point))
8324 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8325 (insert-before-markers txt)
8326 (unless (string-match "\n\\'" txt) (insert "\n"))
8327 (setq newend (point))
8328 (org-reinstall-markers-in-region beg)
8329 (setq end (point))
8330 (goto-char beg)
8331 (skip-chars-forward " \t\n\r")
8332 (setq beg (point))
8333 (if (and (outline-invisible-p) visp)
8334 (save-excursion (outline-show-heading)))
8335 ;; Shift if necessary
8336 (unless (= shift 0)
8337 (save-restriction
8338 (narrow-to-region beg end)
8339 (while (not (= shift 0))
8340 (org-map-region func (point-min) (point-max))
8341 (setq shift (+ delta shift)))
8342 (goto-char (point-min))
8343 (setq newend (point-max))))
8344 (when (or (org-called-interactively-p 'interactive) for-yank)
8345 (message "Clipboard pasted as level %d subtree" new-level))
8346 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8347 kill-ring
8348 (eq org-subtree-clip (current-kill 0))
8349 org-subtree-clip-folded)
8350 ;; The tree was folded before it was killed/copied
8351 (hide-subtree))
8352 (and for-yank (goto-char newend)))))
8354 (defun org-kill-is-subtree-p (&optional txt)
8355 "Check if the current kill is an outline subtree, or a set of trees.
8356 Returns nil if kill does not start with a headline, or if the first
8357 headline level is not the largest headline level in the tree.
8358 So this will actually accept several entries of equal levels as well,
8359 which is OK for `org-paste-subtree'.
8360 If optional TXT is given, check this string instead of the current kill."
8361 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8362 (re (org-get-limited-outline-regexp))
8363 (^re (concat "^" re))
8364 (start-level (and kill
8365 (string-match
8366 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8367 kill)
8368 (- (match-end 2) (match-beginning 2) 1)))
8369 (start (1+ (or (match-beginning 2) -1))))
8370 (if (not start-level)
8371 (progn
8372 nil) ;; does not even start with a heading
8373 (catch 'exit
8374 (while (setq start (string-match ^re kill (1+ start)))
8375 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8376 (throw 'exit nil)))
8377 t))))
8379 (defvar org-markers-to-move nil
8380 "Markers that should be moved with a cut-and-paste operation.
8381 Those markers are stored together with their positions relative to
8382 the start of the region.")
8384 (defun org-save-markers-in-region (beg end)
8385 "Check markers in region.
8386 If these markers are between BEG and END, record their position relative
8387 to BEG, so that after moving the block of text, we can put the markers back
8388 into place.
8389 This function gets called just before an entry or tree gets cut from the
8390 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8391 called immediately, to move the markers with the entries."
8392 (setq org-markers-to-move nil)
8393 (when (featurep 'org-clock)
8394 (org-clock-save-markers-for-cut-and-paste beg end))
8395 (when (featurep 'org-agenda)
8396 (org-agenda-save-markers-for-cut-and-paste beg end)))
8398 (defun org-check-and-save-marker (marker beg end)
8399 "Check if MARKER is between BEG and END.
8400 If yes, remember the marker and the distance to BEG."
8401 (when (and (marker-buffer marker)
8402 (equal (marker-buffer marker) (current-buffer)))
8403 (if (and (>= marker beg) (< marker end))
8404 (push (cons marker (- marker beg)) org-markers-to-move))))
8406 (defun org-reinstall-markers-in-region (beg)
8407 "Move all remembered markers to their position relative to BEG."
8408 (mapc (lambda (x)
8409 (move-marker (car x) (+ beg (cdr x))))
8410 org-markers-to-move)
8411 (setq org-markers-to-move nil))
8413 (defun org-narrow-to-subtree ()
8414 "Narrow buffer to the current subtree."
8415 (interactive)
8416 (save-excursion
8417 (save-match-data
8418 (org-with-limited-levels
8419 (narrow-to-region
8420 (progn (org-back-to-heading t) (point))
8421 (progn (org-end-of-subtree t t)
8422 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8423 (point)))))))
8425 (defun org-narrow-to-block ()
8426 "Narrow buffer to the current block."
8427 (interactive)
8428 (let* ((case-fold-search t)
8429 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8430 "^[ \t]*#\\+end_.*")))
8431 (if blockp
8432 (narrow-to-region (car blockp) (cdr blockp))
8433 (user-error "Not in a block"))))
8435 (eval-when-compile
8436 (defvar org-property-drawer-re))
8438 (defvar org-property-start-re) ;; defined below
8439 (defun org-clone-subtree-with-time-shift (n &optional shift)
8440 "Clone the task (subtree) at point N times.
8441 The clones will be inserted as siblings.
8443 In interactive use, the user will be prompted for the number of
8444 clones to be produced. If the entry has a timestamp, the user
8445 will also be prompted for a time shift, which may be a repeater
8446 as used in time stamps, for example `+3d'. To disable this,
8447 you can call the function with a universal prefix argument.
8449 When a valid repeater is given and the entry contains any time
8450 stamps, the clones will become a sequence in time, with time
8451 stamps in the subtree shifted for each clone produced. If SHIFT
8452 is nil or the empty string, time stamps will be left alone. The
8453 ID property of the original subtree is removed.
8455 If the original subtree did contain time stamps with a repeater,
8456 the following will happen:
8457 - the repeater will be removed in each clone
8458 - an additional clone will be produced, with the current, unshifted
8459 date(s) in the entry.
8460 - the original entry will be placed *after* all the clones, with
8461 repeater intact.
8462 - the start days in the repeater in the original entry will be shifted
8463 to past the last clone.
8464 In this way you can spell out a number of instances of a repeating task,
8465 and still retain the repeater to cover future instances of the task."
8466 (interactive "nNumber of clones to produce: ")
8467 (let ((shift
8468 (or shift
8469 (if (and (not (equal current-prefix-arg '(4)))
8470 (save-excursion
8471 (re-search-forward org-ts-regexp-both
8472 (save-excursion
8473 (org-end-of-subtree t)
8474 (point)) t)))
8475 (read-from-minibuffer
8476 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8477 ""))) ;; No time shift
8478 (n-no-remove -1)
8479 (drawer-re org-drawer-regexp)
8480 beg end template task idprop
8481 shift-n shift-what doshift nmin nmax)
8482 (if (not (and (integerp n) (> n 0)))
8483 (error "Invalid number of replications %s" n))
8484 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8485 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8486 shift)))
8487 (error "Invalid shift specification %s" shift))
8488 (when doshift
8489 (setq shift-n (string-to-number (match-string 1 shift))
8490 shift-what (cdr (assoc (match-string 2 shift)
8491 '(("d" . day) ("w" . week)
8492 ("m" . month) ("y" . year))))))
8493 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8494 (setq nmin 1 nmax n)
8495 (org-back-to-heading t)
8496 (setq beg (point))
8497 (setq idprop (org-entry-get nil "ID"))
8498 (org-end-of-subtree t t)
8499 (or (bolp) (insert "\n"))
8500 (setq end (point))
8501 (setq template (buffer-substring beg end))
8502 (when (and doshift
8503 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8504 (delete-region beg end)
8505 (setq end beg)
8506 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8507 (goto-char end)
8508 (loop for n from nmin to nmax do
8509 ;; prepare clone
8510 (with-temp-buffer
8511 (insert template)
8512 (org-mode)
8513 (goto-char (point-min))
8514 (org-show-subtree)
8515 (and idprop (if org-clone-delete-id
8516 (org-entry-delete nil "ID")
8517 (org-id-get-create t)))
8518 (unless (= n 0)
8519 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8520 (kill-whole-line))
8521 (goto-char (point-min))
8522 (while (re-search-forward drawer-re nil t)
8523 (mapc (lambda (d)
8524 (org-remove-empty-drawer-at d (point))) org-drawers)))
8525 (goto-char (point-min))
8526 (when doshift
8527 (while (re-search-forward org-ts-regexp-both nil t)
8528 (org-timestamp-change (* n shift-n) shift-what))
8529 (unless (= n n-no-remove)
8530 (goto-char (point-min))
8531 (while (re-search-forward org-ts-regexp nil t)
8532 (save-excursion
8533 (goto-char (match-beginning 0))
8534 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8535 (delete-region (match-beginning 1) (match-end 1)))))))
8536 (setq task (buffer-string)))
8537 (insert task))
8538 (goto-char beg)))
8540 ;;; Outline Sorting
8542 (defun org-sort (with-case)
8543 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8544 Optional argument WITH-CASE means sort case-sensitively."
8545 (interactive "P")
8546 (cond
8547 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8548 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8550 (org-call-with-arg 'org-sort-entries with-case))))
8552 (defun org-sort-remove-invisible (s)
8553 "Remove invisible links from string S."
8554 (remove-text-properties 0 (length s) org-rm-props s)
8555 (while (string-match org-bracket-link-regexp s)
8556 (setq s (replace-match (if (match-end 2)
8557 (match-string 3 s)
8558 (match-string 1 s)) t t s)))
8559 (let ((st (format " %s " s)))
8560 (while (string-match org-emph-re st)
8561 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8562 (setq s (substring st 1 -1)))
8565 (defvar org-priority-regexp) ; defined later in the file
8567 (defvar org-after-sorting-entries-or-items-hook nil
8568 "Hook that is run after a bunch of entries or items have been sorted.
8569 When children are sorted, the cursor is in the parent line when this
8570 hook gets called. When a region or a plain list is sorted, the cursor
8571 will be in the first entry of the sorted region/list.")
8573 (defun org-sort-entries
8574 (&optional with-case sorting-type getkey-func compare-func property)
8575 "Sort entries on a certain level of an outline tree.
8576 If there is an active region, the entries in the region are sorted.
8577 Else, if the cursor is before the first entry, sort the top-level items.
8578 Else, the children of the entry at point are sorted.
8580 Sorting can be alphabetically, numerically, by date/time as given by
8581 a time stamp, by a property, by priority order, or by a custom function.
8583 The command prompts for the sorting type unless it has been given to the
8584 function through the SORTING-TYPE argument, which needs to be a character,
8585 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8586 precise meaning of each character:
8588 n Numerically, by converting the beginning of the entry/item to a number.
8589 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8590 o By order of TODO keywords.
8591 t By date/time, either the first active time stamp in the entry, or, if
8592 none exist, by the first inactive one.
8593 s By the scheduled date/time.
8594 d By deadline date/time.
8595 c By creation time, which is assumed to be the first inactive time stamp
8596 at the beginning of a line.
8597 p By priority according to the cookie.
8598 r By the value of a property.
8600 Capital letters will reverse the sort order.
8602 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8603 called with point at the beginning of the record. It must return either
8604 a string or a number that should serve as the sorting key for that record.
8606 Comparing entries ignores case by default. However, with an optional argument
8607 WITH-CASE, the sorting considers case as well.
8609 Sorting is done against the visible part of the headlines, it ignores hidden
8610 links."
8611 (interactive "P")
8612 (let ((case-func (if with-case 'identity 'downcase))
8613 (cmstr
8614 ;; The clock marker is lost when using `sort-subr', let's
8615 ;; store the clocking string.
8616 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8617 (save-excursion
8618 (goto-char org-clock-marker)
8619 (looking-back "^.*") (match-string-no-properties 0))))
8620 start beg end stars re re2
8621 txt what tmp)
8622 ;; Find beginning and end of region to sort
8623 (cond
8624 ((org-region-active-p)
8625 ;; we will sort the region
8626 (setq end (region-end)
8627 what "region")
8628 (goto-char (region-beginning))
8629 (if (not (org-at-heading-p)) (outline-next-heading))
8630 (setq start (point)))
8631 ((or (org-at-heading-p)
8632 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8633 ;; we will sort the children of the current headline
8634 (org-back-to-heading)
8635 (setq start (point)
8636 end (progn (org-end-of-subtree t t)
8637 (or (bolp) (insert "\n"))
8638 (org-back-over-empty-lines)
8639 (point))
8640 what "children")
8641 (goto-char start)
8642 (show-subtree)
8643 (outline-next-heading))
8645 ;; we will sort the top-level entries in this file
8646 (goto-char (point-min))
8647 (or (org-at-heading-p) (outline-next-heading))
8648 (setq start (point))
8649 (goto-char (point-max))
8650 (beginning-of-line 1)
8651 (when (looking-at ".*?\\S-")
8652 ;; File ends in a non-white line
8653 (end-of-line 1)
8654 (insert "\n"))
8655 (setq end (point-max))
8656 (setq what "top-level")
8657 (goto-char start)
8658 (show-all)))
8660 (setq beg (point))
8661 (if (>= beg end) (user-error "Nothing to sort"))
8663 (looking-at "\\(\\*+\\)")
8664 (setq stars (match-string 1)
8665 re (concat "^" (regexp-quote stars) " +")
8666 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8667 txt (buffer-substring beg end))
8668 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8669 (if (and (not (equal stars "*")) (string-match re2 txt))
8670 (user-error "Region to sort contains a level above the first entry"))
8672 (unless sorting-type
8673 (message
8674 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8675 [t]ime [s]cheduled [d]eadline [c]reated
8676 A/N/P/R/O/F/T/S/D/C means reversed:"
8677 what)
8678 (setq sorting-type (read-char-exclusive))
8680 (unless getkey-func
8681 (and (= (downcase sorting-type) ?f)
8682 (setq getkey-func
8683 (org-icompleting-read "Sort using function: "
8684 obarray 'fboundp t nil nil))
8685 (setq getkey-func (intern getkey-func))))
8687 (and (= (downcase sorting-type) ?r)
8688 (not property)
8689 (setq property
8690 (org-icompleting-read "Property: "
8691 (mapcar 'list (org-buffer-property-keys t))
8692 nil t))))
8694 (message "Sorting entries...")
8696 (save-restriction
8697 (narrow-to-region start end)
8698 (let ((dcst (downcase sorting-type))
8699 (case-fold-search nil)
8700 (now (current-time)))
8701 (sort-subr
8702 (/= dcst sorting-type)
8703 ;; This function moves to the beginning character of the "record" to
8704 ;; be sorted.
8705 (lambda nil
8706 (if (re-search-forward re nil t)
8707 (goto-char (match-beginning 0))
8708 (goto-char (point-max))))
8709 ;; This function moves to the last character of the "record" being
8710 ;; sorted.
8711 (lambda nil
8712 (save-match-data
8713 (condition-case nil
8714 (outline-forward-same-level 1)
8715 (error
8716 (goto-char (point-max))))))
8717 ;; This function returns the value that gets sorted against.
8718 (lambda nil
8719 (cond
8720 ((= dcst ?n)
8721 (if (looking-at org-complex-heading-regexp)
8722 (string-to-number (org-sort-remove-invisible (match-string 4)))
8723 nil))
8724 ((= dcst ?a)
8725 (if (looking-at org-complex-heading-regexp)
8726 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8727 nil))
8728 ((= dcst ?t)
8729 (let ((end (save-excursion (outline-next-heading) (point))))
8730 (if (or (re-search-forward org-ts-regexp end t)
8731 (re-search-forward org-ts-regexp-both end t))
8732 (org-time-string-to-seconds (match-string 0))
8733 (org-float-time now))))
8734 ((= dcst ?c)
8735 (let ((end (save-excursion (outline-next-heading) (point))))
8736 (if (re-search-forward
8737 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8738 end t)
8739 (org-time-string-to-seconds (match-string 0))
8740 (org-float-time now))))
8741 ((= dcst ?s)
8742 (let ((end (save-excursion (outline-next-heading) (point))))
8743 (if (re-search-forward org-scheduled-time-regexp end t)
8744 (org-time-string-to-seconds (match-string 1))
8745 (org-float-time now))))
8746 ((= dcst ?d)
8747 (let ((end (save-excursion (outline-next-heading) (point))))
8748 (if (re-search-forward org-deadline-time-regexp end t)
8749 (org-time-string-to-seconds (match-string 1))
8750 (org-float-time now))))
8751 ((= dcst ?p)
8752 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8753 (string-to-char (match-string 2))
8754 org-default-priority))
8755 ((= dcst ?r)
8756 (or (org-entry-get nil property) ""))
8757 ((= dcst ?o)
8758 (if (looking-at org-complex-heading-regexp)
8759 (- 9999 (length (member (match-string 2)
8760 org-todo-keywords-1)))))
8761 ((= dcst ?f)
8762 (if getkey-func
8763 (progn
8764 (setq tmp (funcall getkey-func))
8765 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8766 tmp)
8767 (error "Invalid key function `%s'" getkey-func)))
8768 (t (error "Invalid sorting type `%c'" sorting-type))))
8770 (cond
8771 ((= dcst ?a) 'string<)
8772 ((= dcst ?f) compare-func)
8773 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8774 (run-hooks 'org-after-sorting-entries-or-items-hook)
8775 ;; Reset the clock marker if needed
8776 (when cmstr
8777 (save-excursion
8778 (goto-char start)
8779 (search-forward cmstr nil t)
8780 (move-marker org-clock-marker (point))))
8781 (message "Sorting entries...done")))
8783 (defun org-do-sort (table what &optional with-case sorting-type)
8784 "Sort TABLE of WHAT according to SORTING-TYPE.
8785 The user will be prompted for the SORTING-TYPE if the call to this
8786 function does not specify it. WHAT is only for the prompt, to indicate
8787 what is being sorted. The sorting key will be extracted from
8788 the car of the elements of the table.
8789 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8790 (unless sorting-type
8791 (message
8792 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8793 what)
8794 (setq sorting-type (read-char-exclusive)))
8795 (let ((dcst (downcase sorting-type))
8796 extractfun comparefun)
8797 ;; Define the appropriate functions
8798 (cond
8799 ((= dcst ?n)
8800 (setq extractfun 'string-to-number
8801 comparefun (if (= dcst sorting-type) '< '>)))
8802 ((= dcst ?a)
8803 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8804 (lambda(x) (downcase (org-sort-remove-invisible x))))
8805 comparefun (if (= dcst sorting-type)
8806 'string<
8807 (lambda (a b) (and (not (string< a b))
8808 (not (string= a b)))))))
8809 ((= dcst ?t)
8810 (setq extractfun
8811 (lambda (x)
8812 (if (or (string-match org-ts-regexp x)
8813 (string-match org-ts-regexp-both x))
8814 (org-float-time
8815 (org-time-string-to-time (match-string 0 x)))
8817 comparefun (if (= dcst sorting-type) '< '>)))
8818 (t (error "Invalid sorting type `%c'" sorting-type)))
8820 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8821 table)
8822 (lambda (a b) (funcall comparefun (car a) (car b))))))
8825 ;;; The orgstruct minor mode
8827 ;; Define a minor mode which can be used in other modes in order to
8828 ;; integrate the org-mode structure editing commands.
8830 ;; This is really a hack, because the org-mode structure commands use
8831 ;; keys which normally belong to the major mode. Here is how it
8832 ;; works: The minor mode defines all the keys necessary to operate the
8833 ;; structure commands, but wraps the commands into a function which
8834 ;; tests if the cursor is currently at a headline or a plain list
8835 ;; item. If that is the case, the structure command is used,
8836 ;; temporarily setting many Org-mode variables like regular
8837 ;; expressions for filling etc. However, when any of those keys is
8838 ;; used at a different location, function uses `key-binding' to look
8839 ;; up if the key has an associated command in another currently active
8840 ;; keymap (minor modes, major mode, global), and executes that
8841 ;; command. There might be problems if any of the keys is otherwise
8842 ;; used as a prefix key.
8844 (defcustom orgstruct-heading-prefix-regexp nil
8845 "Regexp that matches the custom prefix of Org headlines in
8846 orgstruct(++)-mode."
8847 :group 'org
8848 :version "24.4"
8849 :package-version '(Org . "8.0")
8850 :type 'string)
8851 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8853 (defcustom orgstruct-setup-hook nil
8854 "Hook run after orgstruct-mode-map is filled."
8855 :group 'org
8856 :version "24.4"
8857 :package-version '(Org . "8.0")
8858 :type 'hook)
8860 (defvar orgstruct-initialized nil)
8862 (defvar org-local-vars nil
8863 "List of local variables, for use by `orgstruct-mode'.")
8865 ;;;###autoload
8866 (define-minor-mode orgstruct-mode
8867 "Toggle the minor mode `orgstruct-mode'.
8868 This mode is for using Org-mode structure commands in other
8869 modes. The following keys behave as if Org-mode were active, if
8870 the cursor is on a headline, or on a plain list item (both as
8871 defined by Org-mode)."
8872 nil " OrgStruct" (make-sparse-keymap)
8873 (funcall (if orgstruct-mode
8874 'add-to-invisibility-spec
8875 'remove-from-invisibility-spec)
8876 '(outline . t))
8877 (when orgstruct-mode
8878 (org-load-modules-maybe)
8879 (unless orgstruct-initialized
8880 (orgstruct-setup)
8881 (setq orgstruct-initialized t))))
8883 ;;;###autoload
8884 (defun turn-on-orgstruct ()
8885 "Unconditionally turn on `orgstruct-mode'."
8886 (orgstruct-mode 1))
8888 (defvar org-fb-vars nil)
8889 (make-variable-buffer-local 'org-fb-vars)
8890 (defun orgstruct++-mode (&optional arg)
8891 "Toggle `orgstruct-mode', the enhanced version of it.
8892 In addition to setting orgstruct-mode, this also exports all
8893 indentation and autofilling variables from org-mode into the
8894 buffer. It will also recognize item context in multiline items."
8895 (interactive "P")
8896 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8897 (if (< arg 1)
8898 (progn (orgstruct-mode -1)
8899 (mapc (lambda(v)
8900 (org-set-local (car v)
8901 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8902 org-fb-vars))
8903 (orgstruct-mode 1)
8904 (setq org-fb-vars nil)
8905 (unless org-local-vars
8906 (setq org-local-vars (org-get-local-variables)))
8907 (let (var val)
8908 (mapc
8909 (lambda (x)
8910 (when (string-match
8911 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8912 (symbol-name (car x)))
8913 (setq var (car x) val (nth 1 x))
8914 (push (list var `(quote ,(eval var))) org-fb-vars)
8915 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8916 org-local-vars)
8917 (org-set-local 'orgstruct-is-++ t))))
8919 (defvar orgstruct-is-++ nil
8920 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8921 (make-variable-buffer-local 'orgstruct-is-++)
8923 ;;;###autoload
8924 (defun turn-on-orgstruct++ ()
8925 "Unconditionally turn on `orgstruct++-mode'."
8926 (orgstruct++-mode 1))
8928 (defun orgstruct-error ()
8929 "Error when there is no default binding for a structure key."
8930 (interactive)
8931 (funcall (if (fboundp 'user-error)
8932 'user-error
8933 'error)
8934 "This key has no function outside structure elements"))
8936 (defun orgstruct-setup ()
8937 "Setup orgstruct keymap."
8938 (dolist (cell '((org-demote . t)
8939 (org-metaleft . t)
8940 (org-metaright . t)
8941 (org-promote . t)
8942 (org-shiftmetaleft . t)
8943 (org-shiftmetaright . t)
8944 org-backward-element
8945 org-backward-heading-same-level
8946 org-ctrl-c-ret
8947 org-ctrl-c-minus
8948 org-ctrl-c-star
8949 org-cycle
8950 org-forward-heading-same-level
8951 org-insert-heading
8952 org-insert-heading-respect-content
8953 org-kill-note-or-show-branches
8954 org-mark-subtree
8955 org-meta-return
8956 org-metadown
8957 org-metaup
8958 org-narrow-to-subtree
8959 org-promote-subtree
8960 org-reveal
8961 org-shiftdown
8962 org-shiftleft
8963 org-shiftmetadown
8964 org-shiftmetaup
8965 org-shiftright
8966 org-shifttab
8967 org-shifttab
8968 org-shiftup
8969 org-show-subtree
8970 org-sort
8971 org-up-element
8972 outline-demote
8973 outline-next-visible-heading
8974 outline-previous-visible-heading
8975 outline-promote
8976 outline-up-heading
8977 show-children))
8978 (let ((f (or (car-safe cell) cell))
8979 (disable-when-heading-prefix (cdr-safe cell)))
8980 (when (fboundp f)
8981 (let ((new-bindings))
8982 (dolist (binding (nconc (where-is-internal f org-mode-map)
8983 (where-is-internal f outline-mode-map)))
8984 (push binding new-bindings)
8985 ;; TODO use local-function-key-map
8986 (dolist (rep '(("<tab>" . "TAB")
8987 ("<return>" . "RET")
8988 ("<escape>" . "ESC")
8989 ("<delete>" . "DEL")))
8990 (setq binding (read-kbd-macro
8991 (let ((case-fold-search))
8992 (replace-regexp-in-string
8993 (regexp-quote (cdr rep))
8994 (car rep)
8995 (key-description binding)))))
8996 (pushnew binding new-bindings :test 'equal)))
8997 (dolist (binding new-bindings)
8998 (let ((key (lookup-key orgstruct-mode-map binding)))
8999 (when (or (not key) (numberp key))
9000 (condition-case nil
9001 (org-defkey orgstruct-mode-map
9002 binding
9003 (orgstruct-make-binding f binding disable-when-heading-prefix))
9004 (error nil)))))))))
9005 (run-hooks 'orgstruct-setup-hook))
9007 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9008 "Create a function for binding in the structure minor mode.
9009 FUN is the command to call inside a table. KEY is the key that
9010 should be checked in for a command to execute outside of tables.
9011 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
9012 if `orgstruct-heading-prefix-regexp' is non-nil."
9013 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9014 (let ((nname name)
9015 (i 0))
9016 (while (fboundp (intern nname))
9017 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9018 (setq name (intern nname)))
9019 (eval
9020 (let ((bindings '((org-heading-regexp
9021 (concat "^"
9022 orgstruct-heading-prefix-regexp
9023 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9024 (org-outline-regexp
9025 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9026 (org-outline-regexp-bol
9027 (concat "^" org-outline-regexp))
9028 (outline-regexp org-outline-regexp)
9029 (outline-heading-end-regexp "\n")
9030 (outline-level 'org-outline-level)
9031 (outline-heading-alist))))
9032 `(defun ,name (arg)
9033 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9034 "Outside of structure, run the binding of `"
9035 (key-description key) "'."
9036 (when disable-when-heading-prefix
9037 (concat
9038 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9039 "back to the default binding due to limitations of Org's implementation of\n"
9040 "`" (symbol-name fun) "'.")))
9041 (interactive "p")
9042 (let* ((disable
9043 ,(when disable-when-heading-prefix
9044 '(and orgstruct-heading-prefix-regexp
9045 (not (string= orgstruct-heading-prefix-regexp "")))))
9046 (fallback
9047 (or disable
9048 (not
9049 (let* ,bindings
9050 (org-context-p 'headline 'item
9051 ,(when (memq fun
9052 '(org-insert-heading
9053 org-insert-heading-respect-content
9054 org-meta-return))
9055 '(when orgstruct-is-++
9056 'item-body))))))))
9057 (if fallback
9058 (let* ((orgstruct-mode)
9059 (binding
9060 (loop with key = ,key
9061 for rep in
9062 '(nil
9063 ("<\\([^>]*\\)tab>" . "\\1TAB")
9064 ("<\\([^>]*\\)return>" . "\\1RET")
9065 ("<\\([^>]*\\)escape>" . "\\1ESC")
9066 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9068 (when rep
9069 (setq key (read-kbd-macro
9070 (let ((case-fold-search))
9071 (replace-regexp-in-string
9072 (car rep)
9073 (cdr rep)
9074 (key-description key))))))
9075 thereis (key-binding key))))
9076 (if (keymapp binding)
9077 (set-temporary-overlay-map binding)
9078 (let ((func (or binding
9079 (unless disable
9080 'orgstruct-error))))
9081 (when func
9082 (call-interactively func)))))
9083 (org-run-like-in-org-mode
9084 (lambda ()
9085 (interactive)
9086 (let* ,bindings
9087 (call-interactively ',fun)))))))))
9088 name))
9090 (defun org-contextualize-keys (alist contexts)
9091 "Return valid elements in ALIST depending on CONTEXTS.
9093 `org-agenda-custom-commands' or `org-capture-templates' are the
9094 values used for ALIST, and `org-agenda-custom-commands-contexts'
9095 or `org-capture-templates-contexts' are the associated contexts
9096 definitions."
9097 (let ((contexts
9098 ;; normalize contexts
9099 (mapcar
9100 (lambda(c) (cond ((listp (cadr c))
9101 (list (car c) (car c) (cadr c)))
9102 ((string= "" (cadr c))
9103 (list (car c) (car c) (caddr c)))
9104 (t c))) contexts))
9105 (a alist) c r s)
9106 ;; loop over all commands or templates
9107 (while (setq c (pop a))
9108 (let (vrules repl)
9109 (cond
9110 ((not (assoc (car c) contexts))
9111 (push c r))
9112 ((and (assoc (car c) contexts)
9113 (setq vrules (org-contextualize-validate-key
9114 (car c) contexts)))
9115 (mapc (lambda (vr)
9116 (when (not (equal (car vr) (cadr vr)))
9117 (setq repl vr))) vrules)
9118 (if (not repl) (push c r)
9119 (push (cadr repl) s)
9120 (push
9121 (cons (car c)
9122 (cdr (or (assoc (cadr repl) alist)
9123 (error "Undefined key `%s' as contextual replacement for `%s'"
9124 (cadr repl) (car c)))))
9125 r))))))
9126 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9127 (delq
9129 (delete-dups
9130 (mapcar (lambda (x)
9131 (let ((tpl (car x)))
9132 (when (not (delq
9134 (mapcar (lambda(y)
9135 (equal y tpl)) s))) x)))
9136 (reverse r))))))
9138 (defun org-contextualize-validate-key (key contexts)
9139 "Check CONTEXTS for agenda or capture KEY."
9140 (let (r rr res)
9141 (while (setq r (pop contexts))
9142 (mapc
9143 (lambda (rr)
9144 (when
9145 (and (equal key (car r))
9146 (if (functionp rr) (funcall rr)
9147 (or (and (eq (car rr) 'in-file)
9148 (buffer-file-name)
9149 (string-match (cdr rr) (buffer-file-name)))
9150 (and (eq (car rr) 'in-mode)
9151 (string-match (cdr rr) (symbol-name major-mode)))
9152 (and (eq (car rr) 'in-buffer)
9153 (string-match (cdr rr) (buffer-name)))
9154 (when (and (eq (car rr) 'not-in-file)
9155 (buffer-file-name))
9156 (not (string-match (cdr rr) (buffer-file-name))))
9157 (when (eq (car rr) 'not-in-mode)
9158 (not (string-match (cdr rr) (symbol-name major-mode))))
9159 (when (eq (car rr) 'not-in-buffer)
9160 (not (string-match (cdr rr) (buffer-name)))))))
9161 (push r res)))
9162 (car (last r))))
9163 (delete-dups (delq nil res))))
9165 (defun org-context-p (&rest contexts)
9166 "Check if local context is any of CONTEXTS.
9167 Possible values in the list of contexts are `table', `headline', and `item'."
9168 (let ((pos (point)))
9169 (goto-char (point-at-bol))
9170 (prog1 (or (and (memq 'table contexts)
9171 (looking-at "[ \t]*|"))
9172 (and (memq 'headline contexts)
9173 (looking-at org-outline-regexp))
9174 (and (memq 'item contexts)
9175 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9176 (and (memq 'item-body contexts)
9177 (org-in-item-p)))
9178 (goto-char pos))))
9180 (defun org-get-local-variables ()
9181 "Return a list of all local variables in an Org mode buffer."
9182 (let (varlist)
9183 (with-current-buffer (get-buffer-create "*Org tmp*")
9184 (erase-buffer)
9185 (org-mode)
9186 (setq varlist (buffer-local-variables)))
9187 (kill-buffer "*Org tmp*")
9188 (delq nil
9189 (mapcar
9190 (lambda (x)
9191 (setq x
9192 (if (symbolp x)
9193 (list x)
9194 (list (car x) (cdr x))))
9195 (if (and (not (get (car x) 'org-state))
9196 (string-match
9197 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9198 (symbol-name (car x))))
9199 x nil))
9200 varlist))))
9202 (defun org-clone-local-variables (from-buffer &optional regexp)
9203 "Clone local variables from FROM-BUFFER.
9204 Optional argument REGEXP selects variables to clone."
9205 (mapc
9206 (lambda (pair)
9207 (and (symbolp (car pair))
9208 (or (null regexp)
9209 (string-match regexp (symbol-name (car pair))))
9210 (set (make-local-variable (car pair))
9211 (cdr pair))))
9212 (buffer-local-variables from-buffer)))
9214 ;;;###autoload
9215 (defun org-run-like-in-org-mode (cmd)
9216 "Run a command, pretending that the current buffer is in Org-mode.
9217 This will temporarily bind local variables that are typically bound in
9218 Org-mode to the values they have in Org-mode, and then interactively
9219 call CMD."
9220 (org-load-modules-maybe)
9221 (unless org-local-vars
9222 (setq org-local-vars (org-get-local-variables)))
9223 (let (binds)
9224 (dolist (var org-local-vars)
9225 (when (or (not (boundp (car var)))
9226 (eq (symbol-value (car var))
9227 (default-value (car var))))
9228 (push (list (car var) `(quote ,(cadr var))) binds)))
9229 (eval `(let ,binds
9230 (call-interactively (quote ,cmd))))))
9232 ;;;; Archiving
9234 (defun org-get-category (&optional pos force-refresh)
9235 "Get the category applying to position POS."
9236 (save-match-data
9237 (if force-refresh (org-refresh-category-properties))
9238 (let ((pos (or pos (point))))
9239 (or (get-text-property pos 'org-category)
9240 (progn (org-refresh-category-properties)
9241 (get-text-property pos 'org-category))))))
9243 (defun org-refresh-category-properties ()
9244 "Refresh category text properties in the buffer."
9245 (let ((case-fold-search t)
9246 (inhibit-read-only t)
9247 (def-cat (cond
9248 ((null org-category)
9249 (if buffer-file-name
9250 (file-name-sans-extension
9251 (file-name-nondirectory buffer-file-name))
9252 "???"))
9253 ((symbolp org-category) (symbol-name org-category))
9254 (t org-category)))
9255 beg end cat pos optionp)
9256 (org-with-silent-modifications
9257 (save-excursion
9258 (save-restriction
9259 (widen)
9260 (goto-char (point-min))
9261 (put-text-property (point) (point-max) 'org-category def-cat)
9262 (while (re-search-forward
9263 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9264 (setq pos (match-end 0)
9265 optionp (equal (char-after (match-beginning 0)) ?#)
9266 cat (org-trim (match-string 2)))
9267 (if optionp
9268 (setq beg (point-at-bol) end (point-max))
9269 (org-back-to-heading t)
9270 (setq beg (point) end (org-end-of-subtree t t)))
9271 (put-text-property beg end 'org-category cat)
9272 (put-text-property beg end 'org-category-position beg)
9273 (goto-char pos)))))))
9275 (defun org-refresh-properties (dprop tprop)
9276 "Refresh buffer text properties.
9277 DPROP is the drawer property and TPROP is the corresponding text
9278 property to set."
9279 (let ((case-fold-search t)
9280 (inhibit-read-only t) p)
9281 (org-with-silent-modifications
9282 (save-excursion
9283 (save-restriction
9284 (widen)
9285 (goto-char (point-min))
9286 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9287 (setq p (org-match-string-no-properties 1))
9288 (save-excursion
9289 (org-back-to-heading t)
9290 (put-text-property
9291 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9294 ;;;; Link Stuff
9296 ;;; Link abbreviations
9298 (defun org-link-expand-abbrev (link)
9299 "Apply replacements as defined in `org-link-abbrev-alist'."
9300 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9301 (let* ((key (match-string 1 link))
9302 (as (or (assoc key org-link-abbrev-alist-local)
9303 (assoc key org-link-abbrev-alist)))
9304 (tag (and (match-end 2) (match-string 3 link)))
9305 rpl)
9306 (if (not as)
9307 link
9308 (setq rpl (cdr as))
9309 (cond
9310 ((symbolp rpl) (funcall rpl tag))
9311 ((string-match "%(\\([^)]+\\))" rpl)
9312 (replace-match
9313 (save-match-data
9314 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9315 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9316 ((string-match "%h" rpl)
9317 (replace-match (url-hexify-string (or tag "")) t t rpl))
9318 (t (concat rpl tag)))))
9319 link))
9321 ;;; Storing and inserting links
9323 (defvar org-insert-link-history nil
9324 "Minibuffer history for links inserted with `org-insert-link'.")
9326 (defvar org-stored-links nil
9327 "Contains the links stored with `org-store-link'.")
9329 (defvar org-store-link-plist nil
9330 "Plist with info about the most recently link created with `org-store-link'.")
9332 (defvar org-link-protocols nil
9333 "Link protocols added to Org-mode using `org-add-link-type'.")
9335 (defvar org-store-link-functions nil
9336 "List of functions that are called to create and store a link.
9337 Each function will be called in turn until one returns a non-nil
9338 value. Each function should check if it is responsible for creating
9339 this link (for example by looking at the major mode).
9340 If not, it must exit and return nil.
9341 If yes, it should return a non-nil value after a calling
9342 `org-store-link-props' with a list of properties and values.
9343 Special properties are:
9345 :type The link prefix, like \"http\". This must be given.
9346 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9347 This is obligatory as well.
9348 :description Optional default description for the second pair
9349 of brackets in an Org-mode link. The user can still change
9350 this when inserting this link into an Org-mode buffer.
9352 In addition to these, any additional properties can be specified
9353 and then used in capture templates.")
9355 (defun org-add-link-type (type &optional follow export)
9356 "Add TYPE to the list of `org-link-types'.
9357 Re-compute all regular expressions depending on `org-link-types'
9359 FOLLOW and EXPORT are two functions.
9361 FOLLOW should take the link path as the single argument and do whatever
9362 is necessary to follow the link, for example find a file or display
9363 a mail message.
9365 EXPORT should format the link path for export to one of the export formats.
9366 It should be a function accepting three arguments:
9368 path the path of the link, the text after the prefix (like \"http:\")
9369 desc the description of the link, if any, or a description added by
9370 org-export-normalize-links if there is none
9371 format the export format, a symbol like `html' or `latex' or `ascii'..
9373 The function may use the FORMAT information to return different values
9374 depending on the format. The return value will be put literally into
9375 the exported file. If the return value is nil, this means Org should
9376 do what it normally does with links which do not have EXPORT defined.
9378 Org-mode has a built-in default for exporting links. If you are happy with
9379 this default, there is no need to define an export function for the link
9380 type. For a simple example of an export function, see `org-bbdb.el'."
9381 (add-to-list 'org-link-types type t)
9382 (org-make-link-regexps)
9383 (if (assoc type org-link-protocols)
9384 (setcdr (assoc type org-link-protocols) (list follow export))
9385 (push (list type follow export) org-link-protocols)))
9387 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9388 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9390 ;;;###autoload
9391 (defun org-store-link (arg)
9392 "\\<org-mode-map>Store an org-link to the current location.
9393 This link is added to `org-stored-links' and can later be inserted
9394 into an org-buffer with \\[org-insert-link].
9396 For some link types, a prefix arg is interpreted.
9397 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9398 For file links, arg negates `org-context-in-file-links'.
9400 A double prefix arg force skipping storing functions that are not
9401 part of Org's core.
9403 A triple prefix arg force storing a link for each line in the
9404 active region."
9405 (interactive "P")
9406 (org-load-modules-maybe)
9407 (if (and (equal arg '(64)) (org-region-active-p))
9408 (save-excursion
9409 (let ((end (region-end)))
9410 (goto-char (region-beginning))
9411 (set-mark (point))
9412 (while (< (point-at-eol) end)
9413 (move-end-of-line 1) (activate-mark)
9414 (let (current-prefix-arg)
9415 (call-interactively 'org-store-link))
9416 (move-beginning-of-line 2)
9417 (set-mark (point)))))
9418 (org-with-limited-levels
9419 (setq org-store-link-plist nil)
9420 (let (link cpltxt desc description search
9421 txt custom-id agenda-link sfuns sfunsn)
9422 (cond
9424 ;; Store a link using an external link type
9425 ((and (not (equal arg '(16)))
9426 (setq sfuns
9427 (delq
9428 nil (mapcar (lambda (f)
9429 (let (fs) (if (funcall f) (push f fs))))
9430 org-store-link-functions))
9431 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9432 (or (and (cdr sfuns)
9433 (funcall (intern
9434 (completing-read
9435 "Which function for creating the link? "
9436 sfunsn t (car sfunsn)))))
9437 (funcall (caar sfuns)))
9438 (setq link (plist-get org-store-link-plist :link)
9439 desc (or (plist-get org-store-link-plist
9440 :description) link))))
9442 ;; Store a link from a source code buffer
9443 ((org-src-edit-buffer-p)
9444 (let (label gc)
9445 (while (or (not label)
9446 (save-excursion
9447 (save-restriction
9448 (widen)
9449 (goto-char (point-min))
9450 (re-search-forward
9451 (regexp-quote (format org-coderef-label-format label))
9452 nil t))))
9453 (when label (message "Label exists already") (sit-for 2))
9454 (setq label (read-string "Code line label: " label)))
9455 (end-of-line 1)
9456 (setq link (format org-coderef-label-format label))
9457 (setq gc (- 79 (length link)))
9458 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9459 (insert link)
9460 (setq link (concat "(" label ")") desc nil)))
9462 ;; We are in the agenda, link to referenced location
9463 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9464 (let ((m (or (get-text-property (point) 'org-hd-marker)
9465 (get-text-property (point) 'org-marker))))
9466 (when m
9467 (org-with-point-at m
9468 (setq agenda-link
9469 (if (org-called-interactively-p 'any)
9470 (call-interactively 'org-store-link)
9471 (org-store-link nil)))))))
9473 ((eq major-mode 'calendar-mode)
9474 (let ((cd (calendar-cursor-to-date)))
9475 (setq link
9476 (format-time-string
9477 (car org-time-stamp-formats)
9478 (apply 'encode-time
9479 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9480 nil nil nil))))
9481 (org-store-link-props :type "calendar" :date cd)))
9483 ((eq major-mode 'help-mode)
9484 (setq link (concat "help:" (save-excursion
9485 (goto-char (point-min))
9486 (looking-at "^[^ ]+")
9487 (match-string 0))))
9488 (org-store-link-props :type "help"))
9490 ((eq major-mode 'w3-mode)
9491 (setq cpltxt (if (and (buffer-name)
9492 (not (string-match "Untitled" (buffer-name))))
9493 (buffer-name)
9494 (url-view-url t))
9495 link (url-view-url t))
9496 (org-store-link-props :type "w3" :url (url-view-url t)))
9498 ((eq major-mode 'image-mode)
9499 (setq cpltxt (concat "file:"
9500 (abbreviate-file-name buffer-file-name))
9501 link cpltxt)
9502 (org-store-link-props :type "image" :file buffer-file-name))
9504 ;; In dired, store a link to the file of the current line
9505 ((eq major-mode 'dired-mode)
9506 (let ((file (dired-get-filename nil t)))
9507 (setq file (if file
9508 (abbreviate-file-name
9509 (expand-file-name (dired-get-filename nil t)))
9510 ;; otherwise, no file so use current directory.
9511 default-directory))
9512 (setq cpltxt (concat "file:" file)
9513 link cpltxt)))
9515 ((setq search (run-hook-with-args-until-success
9516 'org-create-file-search-functions))
9517 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9518 "::" search))
9519 (setq cpltxt (or description link)))
9521 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9522 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9523 (cond
9524 ;; Store a link using the target at point
9525 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9526 (setq cpltxt
9527 (concat "file:"
9528 (abbreviate-file-name
9529 (buffer-file-name (buffer-base-buffer)))
9530 "::" (match-string 1))
9531 link cpltxt))
9532 ((and (featurep 'org-id)
9533 (or (eq org-id-link-to-org-use-id t)
9534 (and (org-called-interactively-p 'any)
9535 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9536 (and (eq org-id-link-to-org-use-id
9537 'create-if-interactive-and-no-custom-id)
9538 (not custom-id))))
9539 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9540 ;; Store a link using the ID at point
9541 (setq link (condition-case nil
9542 (prog1 (org-id-store-link)
9543 (setq desc (plist-get org-store-link-plist
9544 :description)))
9545 (error
9546 ;; Probably before first headline, link only to file
9547 (concat "file:"
9548 (abbreviate-file-name
9549 (buffer-file-name (buffer-base-buffer))))))))
9551 ;; Just link to current headline
9552 (setq cpltxt (concat "file:"
9553 (abbreviate-file-name
9554 (buffer-file-name (buffer-base-buffer)))))
9555 ;; Add a context search string
9556 (when (org-xor org-context-in-file-links arg)
9557 (let* ((ee (org-element-at-point))
9558 (et (org-element-type ee))
9559 (ev (plist-get (cadr ee) :value))
9560 (ek (plist-get (cadr ee) :key))
9561 (eok (and (stringp ek) (string-match "name" ek))))
9562 (setq txt (cond
9563 ((org-at-heading-p) nil)
9564 ((and (eq et 'keyword) eok) ev)
9565 ((org-region-active-p)
9566 (buffer-substring (region-beginning) (region-end)))))
9567 (when (or (null txt) (string-match "\\S-" txt))
9568 (setq cpltxt
9569 (concat cpltxt "::"
9570 (condition-case nil
9571 (org-make-org-heading-search-string txt)
9572 (error "")))
9573 desc (or (and (eq et 'keyword) eok ev)
9574 (nth 4 (ignore-errors (org-heading-components)))
9575 "NONE")))))
9576 (if (string-match "::\\'" cpltxt)
9577 (setq cpltxt (substring cpltxt 0 -2)))
9578 (setq link cpltxt))))
9580 ((buffer-file-name (buffer-base-buffer))
9581 ;; Just link to this file here.
9582 (setq cpltxt (concat "file:"
9583 (abbreviate-file-name
9584 (buffer-file-name (buffer-base-buffer)))))
9585 ;; Add a context string.
9586 (when (org-xor org-context-in-file-links arg)
9587 (setq txt (if (org-region-active-p)
9588 (buffer-substring (region-beginning) (region-end))
9589 (buffer-substring (point-at-bol) (point-at-eol))))
9590 ;; Only use search option if there is some text.
9591 (when (string-match "\\S-" txt)
9592 (setq cpltxt
9593 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9594 desc "NONE")))
9595 (setq link cpltxt))
9597 ((org-called-interactively-p 'interactive)
9598 (user-error "No method for storing a link from this buffer"))
9600 (t (setq link nil)))
9602 ;; We're done setting link and desc, clean up
9603 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9604 (setq link (or link cpltxt)
9605 desc (or desc cpltxt))
9606 (cond ((equal desc "NONE") (setq desc nil))
9607 ((string-match org-bracket-link-analytic-regexp desc)
9608 (let ((d0 (match-string 3 desc))
9609 (p0 (match-string 5 desc)))
9610 (setq desc
9611 (replace-regexp-in-string
9612 org-bracket-link-regexp
9613 (concat (or p0 d0)
9614 (if (equal (length (match-string 0 desc))
9615 (length desc)) "*" "")) desc)))))
9617 ;; Return the link
9618 (if (not (and (or (org-called-interactively-p 'any)
9619 executing-kbd-macro) link))
9620 (or agenda-link (and link (org-make-link-string link desc)))
9621 (push (list link desc) org-stored-links)
9622 (message "Stored: %s" (or desc link))
9623 (when custom-id
9624 (setq link (concat "file:" (abbreviate-file-name
9625 (buffer-file-name)) "::#" custom-id))
9626 (push (list link desc) org-stored-links)))))))
9628 (defun org-store-link-props (&rest plist)
9629 "Store link properties, extract names and addresses."
9630 (let (x adr)
9631 (when (setq x (plist-get plist :from))
9632 (setq adr (mail-extract-address-components x))
9633 (setq plist (plist-put plist :fromname (car adr)))
9634 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9635 (when (setq x (plist-get plist :to))
9636 (setq adr (mail-extract-address-components x))
9637 (setq plist (plist-put plist :toname (car adr)))
9638 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9639 (let ((from (plist-get plist :from))
9640 (to (plist-get plist :to)))
9641 (when (and from to org-from-is-user-regexp)
9642 (setq plist
9643 (plist-put plist :fromto
9644 (if (string-match org-from-is-user-regexp from)
9645 (concat "to %t")
9646 (concat "from %f"))))))
9647 (setq org-store-link-plist plist))
9649 (defun org-add-link-props (&rest plist)
9650 "Add these properties to the link property list."
9651 (let (key value)
9652 (while plist
9653 (setq key (pop plist) value (pop plist))
9654 (setq org-store-link-plist
9655 (plist-put org-store-link-plist key value)))))
9657 (defun org-email-link-description (&optional fmt)
9658 "Return the description part of an email link.
9659 This takes information from `org-store-link-plist' and formats it
9660 according to FMT (default from `org-email-link-description-format')."
9661 (setq fmt (or fmt org-email-link-description-format))
9662 (let* ((p org-store-link-plist)
9663 (to (plist-get p :toaddress))
9664 (from (plist-get p :fromaddress))
9665 (table
9666 (list
9667 (cons "%c" (plist-get p :fromto))
9668 (cons "%F" (plist-get p :from))
9669 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9670 (cons "%T" (plist-get p :to))
9671 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9672 (cons "%s" (plist-get p :subject))
9673 (cons "%d" (plist-get p :date))
9674 (cons "%m" (plist-get p :message-id)))))
9675 (when (string-match "%c" fmt)
9676 ;; Check if the user wrote this message
9677 (if (and org-from-is-user-regexp from to
9678 (save-match-data (string-match org-from-is-user-regexp from)))
9679 (setq fmt (replace-match "to %t" t t fmt))
9680 (setq fmt (replace-match "from %f" t t fmt))))
9681 (org-replace-escapes fmt table)))
9683 (defun org-make-org-heading-search-string (&optional string)
9684 "Make search string for the current headline or STRING."
9685 (let ((s (or string
9686 (and (derived-mode-p 'org-mode)
9687 (save-excursion
9688 (org-back-to-heading t)
9689 (org-element-property :raw-value (org-element-at-point))))))
9690 (lines org-context-in-file-links))
9691 (or string (setq s (concat "*" s))) ; Add * for headlines
9692 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9693 (when (and string (integerp lines) (> lines 0))
9694 (let ((slines (org-split-string s "\n")))
9695 (when (< lines (length slines))
9696 (setq s (mapconcat
9697 'identity
9698 (reverse (nthcdr (- (length slines) lines)
9699 (reverse slines))) "\n")))))
9700 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9702 (defun org-make-link-string (link &optional description)
9703 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9704 (unless (string-match "\\S-" link)
9705 (error "Empty link"))
9706 (when (and description
9707 (stringp description)
9708 (not (string-match "\\S-" description)))
9709 (setq description nil))
9710 (when (stringp description)
9711 ;; Remove brackets from the description, they are fatal.
9712 (while (string-match "\\[" description)
9713 (setq description (replace-match "{" t t description)))
9714 (while (string-match "\\]" description)
9715 (setq description (replace-match "}" t t description))))
9716 (when (equal link description)
9717 ;; No description needed, it is identical
9718 (setq description nil))
9719 (when (and (not description)
9720 (not (string-match (org-image-file-name-regexp) link))
9721 (not (equal link (org-link-escape link))))
9722 (setq description (org-extract-attributes link)))
9723 (setq link
9724 (cond ((string-match (org-image-file-name-regexp) link) link)
9725 ((string-match org-link-types-re link)
9726 (concat (match-string 1 link)
9727 (org-link-escape (substring link (match-end 1)))))
9728 (t (org-link-escape link))))
9729 (concat "[[" link "]"
9730 (if description (concat "[" description "]") "")
9731 "]"))
9733 (defconst org-link-escape-chars
9734 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9735 "List of characters that should be escaped in link.
9736 This is the list that is used for internal purposes.")
9738 (defconst org-link-escape-chars-browser
9739 '(?\ ?\")
9740 "List of escapes for characters that are problematic in links.
9741 This is the list that is used before handing over to the browser.")
9743 (defun org-link-escape (text &optional table merge)
9744 "Return percent escaped representation of TEXT.
9745 TEXT is a string with the text to escape.
9746 Optional argument TABLE is a list with characters that should be
9747 escaped. When nil, `org-link-escape-chars' is used.
9748 If optional argument MERGE is set, merge TABLE into
9749 `org-link-escape-chars'."
9750 (cond
9751 ((and table merge)
9752 (mapc (lambda (defchr)
9753 (unless (member defchr table)
9754 (setq table (cons defchr table)))) org-link-escape-chars))
9755 ((null table)
9756 (setq table org-link-escape-chars)))
9757 (mapconcat
9758 (lambda (char)
9759 (if (or (member char table)
9760 (and (or (< char 32) (= char 37) (> char 126))
9761 org-url-hexify-p))
9762 (mapconcat (lambda (sequence-element)
9763 (format "%%%.2X" sequence-element))
9764 (or (encode-coding-char char 'utf-8)
9765 (error "Unable to percent escape character: %s"
9766 (char-to-string char))) "")
9767 (char-to-string char))) text ""))
9769 (defun org-link-unescape (str)
9770 "Unhex hexified Unicode strings as returned from the JavaScript function
9771 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9772 (unless (and (null str) (string= "" str))
9773 (let ((pos 0) (case-fold-search t) unhexed)
9774 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9775 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9776 (setq str (replace-match unhexed t t str))
9777 (setq pos (+ pos (length unhexed))))))
9778 str)
9780 (defun org-link-unescape-compound (hex)
9781 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9782 Note: this function also decodes single byte encodings like
9783 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9784 (save-match-data
9785 (let* ((bytes (cdr (split-string hex "%")))
9786 (ret "")
9787 (eat 0)
9788 (sum 0))
9789 (while bytes
9790 (let* ((val (string-to-number (pop bytes) 16))
9791 (shift-xor
9792 (if (= 0 eat)
9793 (cond
9794 ((>= val 252) (cons 6 252))
9795 ((>= val 248) (cons 5 248))
9796 ((>= val 240) (cons 4 240))
9797 ((>= val 224) (cons 3 224))
9798 ((>= val 192) (cons 2 192))
9799 (t (cons 0 0)))
9800 (cons 6 128))))
9801 (if (>= val 192) (setq eat (car shift-xor)))
9802 (setq val (logxor val (cdr shift-xor)))
9803 (setq sum (+ (lsh sum (car shift-xor)) val))
9804 (if (> eat 0) (setq eat (- eat 1)))
9805 (cond
9806 ((= 0 eat) ;multi byte
9807 (setq ret (concat ret (org-char-to-string sum)))
9808 (setq sum 0))
9809 ((not bytes) ; single byte(s)
9810 (setq ret (org-link-unescape-single-byte-sequence hex))))
9811 )) ;; end (while bytes
9812 ret )))
9814 (defun org-link-unescape-single-byte-sequence (hex)
9815 "Unhexify hex-encoded single byte character sequences."
9816 (mapconcat (lambda (byte)
9817 (char-to-string (string-to-number byte 16)))
9818 (cdr (split-string hex "%")) ""))
9820 (defun org-xor (a b)
9821 "Exclusive or."
9822 (if a (not b) b))
9824 (defun org-fixup-message-id-for-http (s)
9825 "Replace special characters in a message id, so it can be used in an http query."
9826 (when (string-match "%" s)
9827 (setq s (mapconcat (lambda (c)
9828 (if (eq c ?%)
9829 "%25"
9830 (char-to-string c)))
9831 s "")))
9832 (while (string-match "<" s)
9833 (setq s (replace-match "%3C" t t s)))
9834 (while (string-match ">" s)
9835 (setq s (replace-match "%3E" t t s)))
9836 (while (string-match "@" s)
9837 (setq s (replace-match "%40" t t s)))
9840 (defun org-link-prettify (link)
9841 "Return a human-readable representation of LINK.
9842 The car of LINK must be a raw link the cdr of LINK must be either
9843 a link description or nil."
9844 (let ((desc (or (cadr link) "<no description>")))
9845 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9846 "<" (car link) ">")))
9848 ;;;###autoload
9849 (defun org-insert-link-global ()
9850 "Insert a link like Org-mode does.
9851 This command can be called in any mode to insert a link in Org-mode syntax."
9852 (interactive)
9853 (org-load-modules-maybe)
9854 (org-run-like-in-org-mode 'org-insert-link))
9856 (defun org-insert-all-links (&optional keep)
9857 "Insert all links in `org-stored-links'."
9858 (interactive "P")
9859 (let ((links (copy-sequence org-stored-links)) l)
9860 (while (setq l (if keep (pop links) (pop org-stored-links)))
9861 (insert "- ")
9862 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9863 (insert "\n"))))
9865 (defun org-link-fontify-links-to-this-file ()
9866 "Fontify links to the current file in `org-stored-links'."
9867 (let ((f (buffer-file-name)) a b)
9868 (setq a (mapcar (lambda(l)
9869 (let ((ll (car l)))
9870 (when (and (string-match "^file:\\(.+\\)::" ll)
9871 (equal f (expand-file-name (match-string 1 ll))))
9872 ll)))
9873 org-stored-links))
9874 (when (featurep 'org-id)
9875 (setq b (mapcar (lambda(l)
9876 (let ((ll (car l)))
9877 (when (and (string-match "^id:\\(.+\\)$" ll)
9878 (equal f (expand-file-name
9879 (or (org-id-find-id-file
9880 (match-string 1 ll)) ""))))
9881 ll)))
9882 org-stored-links)))
9883 (mapcar (lambda(l)
9884 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9885 (delq nil (append a b)))))
9887 (defvar org-link-links-in-this-file nil)
9888 (defun org-insert-link (&optional complete-file link-location default-description)
9889 "Insert a link. At the prompt, enter the link.
9891 Completion can be used to insert any of the link protocol prefixes like
9892 http or ftp in use.
9894 The history can be used to select a link previously stored with
9895 `org-store-link'. When the empty string is entered (i.e. if you just
9896 press RET at the prompt), the link defaults to the most recently
9897 stored link. As SPC triggers completion in the minibuffer, you need to
9898 use M-SPC or C-q SPC to force the insertion of a space character.
9900 You will also be prompted for a description, and if one is given, it will
9901 be displayed in the buffer instead of the link.
9903 If there is already a link at point, this command will allow you to edit link
9904 and description parts.
9906 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9907 be selected using completion. The path to the file will be relative to the
9908 current directory if the file is in the current directory or a subdirectory.
9909 Otherwise, the link will be the absolute path as completed in the minibuffer
9910 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9911 option `org-link-file-path-type'.
9913 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9914 the current directory or below.
9916 With three \\[universal-argument] prefixes, negate the meaning of
9917 `org-keep-stored-link-after-insertion'.
9919 If `org-make-link-description-function' is non-nil, this function will be
9920 called with the link target, and the result will be the default
9921 link description.
9923 If the LINK-LOCATION parameter is non-nil, this value will be
9924 used as the link location instead of reading one interactively.
9926 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9927 be used as the default description."
9928 (interactive "P")
9929 (let* ((wcf (current-window-configuration))
9930 (origbuf (current-buffer))
9931 (region (if (org-region-active-p)
9932 (buffer-substring (region-beginning) (region-end))))
9933 (remove (and region (list (region-beginning) (region-end))))
9934 (desc region)
9935 tmphist ; byte-compile incorrectly complains about this
9936 (link link-location)
9937 (abbrevs org-link-abbrev-alist-local)
9938 entry file all-prefixes auto-desc)
9939 (cond
9940 (link-location) ; specified by arg, just use it.
9941 ((org-in-regexp org-bracket-link-regexp 1)
9942 ;; We do have a link at point, and we are going to edit it.
9943 (setq remove (list (match-beginning 0) (match-end 0)))
9944 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9945 (setq link (read-string "Link: "
9946 (org-link-unescape
9947 (org-match-string-no-properties 1)))))
9948 ((or (org-in-regexp org-angle-link-re)
9949 (org-in-regexp org-plain-link-re))
9950 ;; Convert to bracket link
9951 (setq remove (list (match-beginning 0) (match-end 0))
9952 link (read-string "Link: "
9953 (org-remove-angle-brackets (match-string 0)))))
9954 ((member complete-file '((4) (16)))
9955 ;; Completing read for file names.
9956 (setq link (org-file-complete-link complete-file)))
9958 ;; Read link, with completion for stored links.
9959 (org-link-fontify-links-to-this-file)
9960 (org-switch-to-buffer-other-window "*Org Links*")
9961 (with-current-buffer "*Org Links*"
9962 (erase-buffer)
9963 (insert "Insert a link.
9964 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9965 (when org-stored-links
9966 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9967 (insert (mapconcat 'org-link-prettify
9968 (reverse org-stored-links) "\n")))
9969 (goto-char (point-min)))
9970 (let ((cw (selected-window)))
9971 (select-window (get-buffer-window "*Org Links*" 'visible))
9972 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9973 (unless (pos-visible-in-window-p (point-max))
9974 (org-fit-window-to-buffer))
9975 (and (window-live-p cw) (select-window cw)))
9976 ;; Fake a link history, containing the stored links.
9977 (setq tmphist (append (mapcar 'car org-stored-links)
9978 org-insert-link-history))
9979 (setq all-prefixes (append (mapcar 'car abbrevs)
9980 (mapcar 'car org-link-abbrev-alist)
9981 org-link-types))
9982 (unwind-protect
9983 (progn
9984 (setq link
9985 (org-completing-read
9986 "Link: "
9987 (append
9988 (mapcar (lambda (x) (concat x ":"))
9989 all-prefixes)
9990 (mapcar 'car org-stored-links))
9991 nil nil nil
9992 'tmphist
9993 (caar org-stored-links)))
9994 (if (not (string-match "\\S-" link))
9995 (user-error "No link selected"))
9996 (mapc (lambda(l)
9997 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9998 org-stored-links)
9999 (if (or (member link all-prefixes)
10000 (and (equal ":" (substring link -1))
10001 (member (substring link 0 -1) all-prefixes)
10002 (setq link (substring link 0 -1))))
10003 (setq link (with-current-buffer origbuf
10004 (org-link-try-special-completion link)))))
10005 (set-window-configuration wcf)
10006 (kill-buffer "*Org Links*"))
10007 (setq entry (assoc link org-stored-links))
10008 (or entry (push link org-insert-link-history))
10009 (setq desc (or desc (nth 1 entry)))))
10011 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10012 (not org-keep-stored-link-after-insertion))
10013 (setq org-stored-links (delq (assoc link org-stored-links)
10014 org-stored-links)))
10016 (if (and (string-match org-plain-link-re link)
10017 (not (string-match org-ts-regexp link)))
10018 ;; URL-like link, normalize the use of angular brackets.
10019 (setq link (org-remove-angle-brackets link)))
10021 ;; Check if we are linking to the current file with a search
10022 ;; option If yes, simplify the link by using only the search
10023 ;; option.
10024 (when (and buffer-file-name
10025 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10026 (let* ((path (match-string 1 link))
10027 (case-fold-search nil)
10028 (search (match-string 2 link)))
10029 (save-match-data
10030 (if (equal (file-truename buffer-file-name) (file-truename path))
10031 ;; We are linking to this same file, with a search option
10032 (setq link search)))))
10034 ;; Check if we can/should use a relative path. If yes, simplify the link
10035 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10036 (let* ((type (match-string 1 link))
10037 (path (match-string 2 link))
10038 (origpath path)
10039 (case-fold-search nil))
10040 (cond
10041 ((or (eq org-link-file-path-type 'absolute)
10042 (equal complete-file '(16)))
10043 (setq path (abbreviate-file-name (expand-file-name path))))
10044 ((eq org-link-file-path-type 'noabbrev)
10045 (setq path (expand-file-name path)))
10046 ((eq org-link-file-path-type 'relative)
10047 (setq path (file-relative-name path)))
10049 (save-match-data
10050 (if (string-match (concat "^" (regexp-quote
10051 (expand-file-name
10052 (file-name-as-directory
10053 default-directory))))
10054 (expand-file-name path))
10055 ;; We are linking a file with relative path name.
10056 (setq path (substring (expand-file-name path)
10057 (match-end 0)))
10058 (setq path (abbreviate-file-name (expand-file-name path)))))))
10059 (setq link (concat type path))
10060 (if (equal desc origpath)
10061 (setq desc path))))
10063 (if org-make-link-description-function
10064 (setq desc
10065 (or (condition-case nil
10066 (funcall org-make-link-description-function link desc)
10067 (error (progn (message "Can't get link description from `%s'"
10068 (symbol-name org-make-link-description-function))
10069 (sit-for 2) nil)))
10070 (read-string "Description: " default-description)))
10071 (if default-description (setq desc default-description)
10072 (setq desc (or (and auto-desc desc)
10073 (read-string "Description: " desc)))))
10075 (unless (string-match "\\S-" desc) (setq desc nil))
10076 (if remove (apply 'delete-region remove))
10077 (insert (org-make-link-string link desc))))
10079 (defun org-link-try-special-completion (type)
10080 "If there is completion support for link type TYPE, offer it."
10081 (let ((fun (intern (concat "org-" type "-complete-link"))))
10082 (if (functionp fun)
10083 (funcall fun)
10084 (read-string "Link (no completion support): " (concat type ":")))))
10086 (defun org-file-complete-link (&optional arg)
10087 "Create a file link using completion."
10088 (let (file link)
10089 (setq file (org-iread-file-name "File: "))
10090 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10091 (pwd1 (file-name-as-directory (abbreviate-file-name
10092 (expand-file-name ".")))))
10093 (cond
10094 ((equal arg '(16))
10095 (setq link (concat
10096 "file:"
10097 (abbreviate-file-name (expand-file-name file)))))
10098 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10099 (setq link (concat "file:" (match-string 1 file))))
10100 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10101 (expand-file-name file))
10102 (setq link (concat
10103 "file:" (match-string 1 (expand-file-name file)))))
10104 (t (setq link (concat "file:" file)))))
10105 link))
10107 (defun org-iread-file-name (&rest args)
10108 "Read-file-name using `ido-mode' speedup if available.
10109 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10110 See `read-file-name' for a description of parameters."
10111 (org-without-partial-completion
10112 (if (and org-completion-use-ido
10113 (fboundp 'ido-read-file-name)
10114 (boundp 'ido-mode) ido-mode
10115 (listp (second args)))
10116 (let ((ido-enter-matching-directory nil))
10117 (apply 'ido-read-file-name args))
10118 (apply 'read-file-name args))))
10120 (defun org-completing-read (&rest args)
10121 "Completing-read with SPACE being a normal character."
10122 (let ((enable-recursive-minibuffers t)
10123 (minibuffer-local-completion-map
10124 (copy-keymap minibuffer-local-completion-map)))
10125 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10126 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10127 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10128 (apply 'org-icompleting-read args)))
10130 (defun org-completing-read-no-i (&rest args)
10131 (let (org-completion-use-ido org-completion-use-iswitchb)
10132 (apply 'org-completing-read args)))
10134 (defun org-iswitchb-completing-read (prompt choices &rest args)
10135 "Use iswitch as a completing-read replacement to choose from choices.
10136 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10137 from."
10138 (let* ((iswitchb-use-virtual-buffers nil)
10139 (iswitchb-make-buflist-hook
10140 (lambda ()
10141 (setq iswitchb-temp-buflist choices))))
10142 (iswitchb-read-buffer prompt)))
10144 (defun org-icompleting-read (&rest args)
10145 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10146 (org-without-partial-completion
10147 (if (and org-completion-use-ido
10148 (fboundp 'ido-completing-read)
10149 (boundp 'ido-mode) ido-mode
10150 (listp (second args)))
10151 (let ((ido-enter-matching-directory nil))
10152 (apply 'ido-completing-read (concat (car args))
10153 (if (consp (car (nth 1 args)))
10154 (mapcar 'car (nth 1 args))
10155 (nth 1 args))
10156 (cddr args)))
10157 (if (and org-completion-use-iswitchb
10158 (boundp 'iswitchb-mode) iswitchb-mode
10159 (listp (second args)))
10160 (apply 'org-iswitchb-completing-read (concat (car args))
10161 (if (consp (car (nth 1 args)))
10162 (mapcar 'car (nth 1 args))
10163 (nth 1 args))
10164 (cddr args))
10165 (apply 'completing-read args)))))
10167 (defun org-extract-attributes (s)
10168 "Extract the attributes cookie from a string and set as text property."
10169 (let (a attr (start 0) key value)
10170 (save-match-data
10171 (when (string-match "{{\\([^}]+\\)}}$" s)
10172 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10173 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10174 (setq key (match-string 1 a) value (match-string 2 a)
10175 start (match-end 0)
10176 attr (plist-put attr (intern key) value))))
10177 (org-add-props s nil 'org-attr attr))
10180 ;;; Opening/following a link
10182 (defvar org-link-search-failed nil)
10184 (defvar org-open-link-functions nil
10185 "Hook for functions finding a plain text link.
10186 These functions must take a single argument, the link content.
10187 They will be called for links that look like [[link text][description]]
10188 when LINK TEXT does not have a protocol like \"http:\" and does not look
10189 like a filename (e.g. \"./blue.png\").
10191 These functions will be called *before* Org attempts to resolve the
10192 link by doing text searches in the current buffer - so if you want a
10193 link \"[[target]]\" to still find \"<<target>>\", your function should
10194 handle this as a special case.
10196 When the function does handle the link, it must return a non-nil value.
10197 If it decides that it is not responsible for this link, it must return
10198 nil to indicate that that Org-mode can continue with other options
10199 like exact and fuzzy text search.")
10201 (defun org-next-link (&optional search-backward)
10202 "Move forward to the next link.
10203 If the link is in hidden text, expose it."
10204 (interactive "P")
10205 (when (and org-link-search-failed (eq this-command last-command))
10206 (goto-char (point-min))
10207 (message "Link search wrapped back to beginning of buffer"))
10208 (setq org-link-search-failed nil)
10209 (let* ((pos (point))
10210 (ct (org-context))
10211 (a (assoc :link ct))
10212 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10213 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10214 ((looking-at org-any-link-re)
10215 ;; Don't stay stuck at link without an org-link face
10216 (forward-char (if search-backward -1 1))))
10217 (if (funcall srch-fun org-any-link-re nil t)
10218 (progn
10219 (goto-char (match-beginning 0))
10220 (if (outline-invisible-p) (org-show-context)))
10221 (goto-char pos)
10222 (setq org-link-search-failed t)
10223 (message "No further link found"))))
10225 (defun org-previous-link ()
10226 "Move backward to the previous link.
10227 If the link is in hidden text, expose it."
10228 (interactive)
10229 (funcall 'org-next-link t))
10231 (defun org-translate-link (s)
10232 "Translate a link string if a translation function has been defined."
10233 (if (and org-link-translation-function
10234 (fboundp org-link-translation-function)
10235 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10236 (progn
10237 (setq s (funcall org-link-translation-function
10238 (match-string 1 s) (match-string 2 s)))
10239 (concat (car s) ":" (cdr s)))
10242 (defun org-translate-link-from-planner (type path)
10243 "Translate a link from Emacs Planner syntax so that Org can follow it.
10244 This is still an experimental function, your mileage may vary."
10245 (cond
10246 ((member type '("http" "https" "news" "ftp"))
10247 ;; standard Internet links are the same.
10248 nil)
10249 ((and (equal type "irc") (string-match "^//" path))
10250 ;; Planner has two / at the beginning of an irc link, we have 1.
10251 ;; We should have zero, actually....
10252 (setq path (substring path 1)))
10253 ((and (equal type "lisp") (string-match "^/" path))
10254 ;; Planner has a slash, we do not.
10255 (setq type "elisp" path (substring path 1)))
10256 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10257 ;; A typical message link. Planner has the id after the final slash,
10258 ;; we separate it with a hash mark
10259 (setq path (concat (match-string 1 path) "#"
10260 (org-remove-angle-brackets (match-string 2 path))))))
10261 (cons type path))
10263 (defun org-find-file-at-mouse (ev)
10264 "Open file link or URL at mouse."
10265 (interactive "e")
10266 (mouse-set-point ev)
10267 (org-open-at-point 'in-emacs))
10269 (defun org-open-at-mouse (ev)
10270 "Open file link or URL at mouse.
10271 See the docstring of `org-open-file' for details."
10272 (interactive "e")
10273 (mouse-set-point ev)
10274 (if (eq major-mode 'org-agenda-mode)
10275 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10276 (org-open-at-point))
10278 (defvar org-window-config-before-follow-link nil
10279 "The window configuration before following a link.
10280 This is saved in case the need arises to restore it.")
10282 (defvar org-open-link-marker (make-marker)
10283 "Marker pointing to the location where `org-open-at-point; was called.")
10285 ;;;###autoload
10286 (defun org-open-at-point-global ()
10287 "Follow a link like Org-mode does.
10288 This command can be called in any mode to follow a link that has
10289 Org-mode syntax."
10290 (interactive)
10291 (org-run-like-in-org-mode 'org-open-at-point))
10293 ;;;###autoload
10294 (defun org-open-link-from-string (s &optional arg reference-buffer)
10295 "Open a link in the string S, as if it was in Org-mode."
10296 (interactive "sLink: \nP")
10297 (let ((reference-buffer (or reference-buffer (current-buffer))))
10298 (with-temp-buffer
10299 (let ((org-inhibit-startup (not reference-buffer)))
10300 (org-mode)
10301 (insert s)
10302 (goto-char (point-min))
10303 (when reference-buffer
10304 (setq org-link-abbrev-alist-local
10305 (with-current-buffer reference-buffer
10306 org-link-abbrev-alist-local)))
10307 (org-open-at-point arg reference-buffer)))))
10309 (defvar org-open-at-point-functions nil
10310 "Hook that is run when following a link at point.
10312 Functions in this hook must return t if they identify and follow
10313 a link at point. If they don't find anything interesting at point,
10314 they must return nil.")
10316 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10317 (defun org-open-at-point (&optional arg reference-buffer)
10318 "Open link at or after point.
10319 If there is no link at point, this function will search forward up to
10320 the end of the current line.
10321 Normally, files will be opened by an appropriate application. If the
10322 optional prefix argument ARG is non-nil, Emacs will visit the file.
10323 With a double prefix argument, try to open outside of Emacs, in the
10324 application the system uses for this file type."
10325 (interactive "P")
10326 ;; if in a code block, then open the block's results
10327 (unless (call-interactively #'org-babel-open-src-block-result)
10328 (org-load-modules-maybe)
10329 (move-marker org-open-link-marker (point))
10330 (setq org-window-config-before-follow-link (current-window-configuration))
10331 (org-remove-occur-highlights nil nil t)
10332 (cond
10333 ((and (org-at-heading-p)
10334 (not (org-at-timestamp-p t))
10335 (not (org-in-regexp
10336 (concat org-plain-link-re "\\|"
10337 org-bracket-link-regexp "\\|"
10338 org-angle-link-re "\\|"
10339 "[ \t]:[^ \t\n]+:[ \t]*$")))
10340 (not (get-text-property (point) 'org-linked-text)))
10341 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10342 (lk0 (car lkall))
10343 (lk (if (stringp lk0) (list lk0) lk0))
10344 (lkend (cdr lkall)))
10345 (mapcar (lambda(l)
10346 (search-forward l nil lkend)
10347 (goto-char (match-beginning 0))
10348 (org-open-at-point))
10349 lk))
10350 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10351 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10352 ((and (org-at-timestamp-p t)
10353 (not (org-in-regexp org-bracket-link-regexp)))
10354 (org-follow-timestamp-link))
10355 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10356 (not (org-in-regexp org-any-link-re)))
10357 (org-footnote-action))
10359 (let (type path link line search (pos (point)))
10360 (catch 'match
10361 (save-excursion
10362 (skip-chars-forward "^]\n\r")
10363 (when (org-in-regexp org-bracket-link-regexp 1)
10364 (setq link (org-extract-attributes
10365 (org-link-unescape (org-match-string-no-properties 1))))
10366 (while (string-match " *\n *" link)
10367 (setq link (replace-match " " t t link)))
10368 (setq link (org-link-expand-abbrev link))
10369 (cond
10370 ((or (file-name-absolute-p link)
10371 (string-match "^\\.\\.?/" link))
10372 (setq type "file" path link))
10373 ((string-match org-link-re-with-space3 link)
10374 (setq type (match-string 1 link) path (match-string 2 link)))
10375 ((string-match "^help:+\\(.+\\)" link)
10376 (setq type "help" path (match-string 1 link)))
10377 (t (setq type "thisfile" path link)))
10378 (throw 'match t)))
10380 (when (get-text-property (point) 'org-linked-text)
10381 (setq type "thisfile"
10382 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10383 (1+ (point)) (point))
10384 path (buffer-substring
10385 (or (previous-single-property-change pos 'org-linked-text)
10386 (point-min))
10387 (or (next-single-property-change pos 'org-linked-text)
10388 (point-max)))
10389 ;; Ensure we will search for a <<<radio>>> link, not
10390 ;; a simple reference like <<ref>>
10391 path (concat "<" path))
10392 (throw 'match t))
10394 (save-excursion
10395 (when (or (org-in-regexp org-angle-link-re)
10396 (let ((match (org-in-regexp org-plain-link-re)))
10397 ;; Check a plain link is not within a bracket link
10398 (and match
10399 (save-excursion
10400 (progn
10401 (goto-char (car match))
10402 (not (org-in-regexp org-bracket-link-regexp))))))
10403 (let ((line_ending (save-excursion (end-of-line) (point))))
10404 ;; We are in a line before a plain or bracket link
10405 (or (re-search-forward org-plain-link-re line_ending t)
10406 (re-search-forward org-bracket-link-regexp line_ending t))))
10407 (setq type (match-string 1)
10408 path (org-link-unescape (match-string 2)))
10409 (throw 'match t)))
10410 (save-excursion
10411 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10412 (setq type "tags"
10413 path (match-string 1))
10414 (while (string-match ":" path)
10415 (setq path (replace-match "+" t t path)))
10416 (throw 'match t)))
10417 (when (org-in-regexp "<\\([^><\n]+\\)>")
10418 (setq type "tree-match"
10419 path (match-string 1))
10420 (throw 'match t)))
10421 (unless path
10422 (user-error "No link found"))
10424 ;; switch back to reference buffer
10425 ;; needed when if called in a temporary buffer through
10426 ;; org-open-link-from-string
10427 (with-current-buffer (or reference-buffer (current-buffer))
10429 ;; Remove any trailing spaces in path
10430 (if (string-match " +\\'" path)
10431 (setq path (replace-match "" t t path)))
10432 (if (and org-link-translation-function
10433 (fboundp org-link-translation-function))
10434 ;; Check if we need to translate the link
10435 (let ((tmp (funcall org-link-translation-function type path)))
10436 (setq type (car tmp) path (cdr tmp))))
10438 (cond
10440 ((assoc type org-link-protocols)
10441 (funcall (nth 1 (assoc type org-link-protocols)) path))
10443 ((equal type "help")
10444 (let ((f-or-v (intern path)))
10445 (cond ((fboundp f-or-v)
10446 (describe-function f-or-v))
10447 ((boundp f-or-v)
10448 (describe-variable f-or-v))
10449 (t (error "Not a known function or variable")))))
10451 ((equal type "mailto")
10452 (let ((cmd (car org-link-mailto-program))
10453 (args (cdr org-link-mailto-program)) args1
10454 (address path) (subject "") a)
10455 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10456 (setq address (match-string 1 path)
10457 subject (org-link-escape (match-string 2 path))))
10458 (while args
10459 (cond
10460 ((not (stringp (car args))) (push (pop args) args1))
10461 (t (setq a (pop args))
10462 (if (string-match "%a" a)
10463 (setq a (replace-match address t t a)))
10464 (if (string-match "%s" a)
10465 (setq a (replace-match subject t t a)))
10466 (push a args1))))
10467 (apply cmd (nreverse args1))))
10469 ((member type '("http" "https" "ftp" "news"))
10470 (browse-url
10471 (concat type ":"
10472 (if (org-string-match-p
10473 (concat "[[:nonascii:]"
10474 org-link-escape-chars-browser "]")
10475 path)
10476 (org-link-escape path org-link-escape-chars-browser)
10477 path))))
10479 ((string= type "doi")
10480 (browse-url
10481 (concat org-doi-server-url
10482 (if (org-string-match-p
10483 (concat "[[:nonascii:]"
10484 org-link-escape-chars-browser "]")
10485 path)
10486 (org-link-escape path org-link-escape-chars-browser)
10487 path))))
10489 ((member type '("message"))
10490 (browse-url (concat type ":" path)))
10492 ((string= type "tags")
10493 (org-tags-view arg path))
10495 ((string= type "tree-match")
10496 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10498 ((string= type "file")
10499 (if (string-match "::\\([0-9]+\\)\\'" path)
10500 (setq line (string-to-number (match-string 1 path))
10501 path (substring path 0 (match-beginning 0)))
10502 (if (string-match "::\\(.+\\)\\'" path)
10503 (setq search (match-string 1 path)
10504 path (substring path 0 (match-beginning 0)))))
10505 (if (string-match "[*?{]" (file-name-nondirectory path))
10506 (dired path)
10507 (org-open-file path arg line search)))
10509 ((string= type "shell")
10510 (let ((buf (generate-new-buffer "*Org Shell Output"))
10511 (cmd path))
10512 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10513 (string-match org-confirm-shell-link-not-regexp cmd))
10514 (not org-confirm-shell-link-function)
10515 (funcall org-confirm-shell-link-function
10516 (format "Execute \"%s\" in shell? "
10517 (org-add-props cmd nil
10518 'face 'org-warning))))
10519 (progn
10520 (message "Executing %s" cmd)
10521 (shell-command cmd buf)
10522 (if (featurep 'midnight)
10523 (setq clean-buffer-list-kill-buffer-names
10524 (cons buf clean-buffer-list-kill-buffer-names))))
10525 (error "Abort"))))
10527 ((string= type "elisp")
10528 (let ((cmd path))
10529 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10530 (string-match org-confirm-elisp-link-not-regexp cmd))
10531 (not org-confirm-elisp-link-function)
10532 (funcall org-confirm-elisp-link-function
10533 (format "Execute \"%s\" as elisp? "
10534 (org-add-props cmd nil
10535 'face 'org-warning))))
10536 (message "%s => %s" cmd
10537 (if (equal (string-to-char cmd) ?\()
10538 (eval (read cmd))
10539 (call-interactively (read cmd))))
10540 (error "Abort"))))
10542 ((and (string= type "thisfile")
10543 (or (run-hook-with-args-until-success
10544 'org-open-link-functions path)
10545 (and link
10546 (string-match "^id:" link)
10547 (or (featurep 'org-id) (require 'org-id))
10548 (progn
10549 (funcall (nth 1 (assoc "id" org-link-protocols))
10550 (substring path 3))
10551 t)))))
10553 ((string= type "thisfile")
10554 (if arg
10555 (switch-to-buffer-other-window
10556 (org-get-buffer-for-internal-link (current-buffer)))
10557 (org-mark-ring-push))
10558 (let ((cmd `(org-link-search
10559 ,path
10560 ,(cond ((equal arg '(4)) ''occur)
10561 ((equal arg '(16)) ''org-occur))
10562 ,pos)))
10563 (condition-case nil (let ((org-link-search-inhibit-query t))
10564 (eval cmd))
10565 (error (progn (widen) (eval cmd))))))
10567 (t (browse-url-at-point)))))))
10568 (move-marker org-open-link-marker nil)
10569 (run-hook-with-args 'org-follow-link-hook)))
10571 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10572 "Offer links in the current entry and return the selected link.
10573 If there is only one link, return it.
10574 If NTH is an integer, return the NTH link found.
10575 If ZERO is a string, check also this string for a link, and if
10576 there is one, return it."
10577 (with-current-buffer buffer
10578 (save-excursion
10579 (save-restriction
10580 (widen)
10581 (goto-char marker)
10582 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10583 "\\(" org-angle-link-re "\\)\\|"
10584 "\\(" org-plain-link-re "\\)"))
10585 (cnt ?0)
10586 (in-emacs (if (integerp nth) nil nth))
10587 have-zero end links link c)
10588 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10589 (push (match-string 0 zero) links)
10590 (setq cnt (1- cnt) have-zero t))
10591 (save-excursion
10592 (org-back-to-heading t)
10593 (setq end (save-excursion (outline-next-heading) (point)))
10594 (while (re-search-forward re end t)
10595 (push (match-string 0) links))
10596 (setq links (org-uniquify (reverse links))))
10597 (cond
10598 ((null links)
10599 (message "No links"))
10600 ((equal (length links) 1)
10601 (setq link (car links)))
10602 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10603 (setq link (nth (if have-zero nth (1- nth)) links)))
10604 (t ; we have to select a link
10605 (save-excursion
10606 (save-window-excursion
10607 (delete-other-windows)
10608 (with-output-to-temp-buffer "*Select Link*"
10609 (mapc (lambda (l)
10610 (if (not (string-match org-bracket-link-regexp l))
10611 (princ (format "[%c] %s\n" (incf cnt)
10612 (org-remove-angle-brackets l)))
10613 (if (match-end 3)
10614 (princ (format "[%c] %s (%s)\n" (incf cnt)
10615 (match-string 3 l) (match-string 1 l)))
10616 (princ (format "[%c] %s\n" (incf cnt)
10617 (match-string 1 l))))))
10618 links))
10619 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10620 (message "Select link to open, RET to open all:")
10621 (setq c (read-char-exclusive))
10622 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10623 (when (equal c ?q) (error "Abort"))
10624 (if (equal c ?\C-m)
10625 (setq link links)
10626 (setq nth (- c ?0))
10627 (if have-zero (setq nth (1+ nth)))
10628 (unless (and (integerp nth) (>= (length links) nth))
10629 (user-error "Invalid link selection"))
10630 (setq link (nth (1- nth) links)))))
10631 (cons link end))))))
10633 ;; Add special file links that specify the way of opening
10635 (org-add-link-type "file+sys" 'org-open-file-with-system)
10636 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10637 (defun org-open-file-with-system (path)
10638 "Open file at PATH using the system way of opening it."
10639 (org-open-file path 'system))
10640 (defun org-open-file-with-emacs (path)
10641 "Open file at PATH in Emacs."
10642 (org-open-file path 'emacs))
10645 ;;; File search
10647 (defvar org-create-file-search-functions nil
10648 "List of functions to construct the right search string for a file link.
10649 These functions are called in turn with point at the location to
10650 which the link should point.
10652 A function in the hook should first test if it would like to
10653 handle this file type, for example by checking the `major-mode'
10654 or the file extension. If it decides not to handle this file, it
10655 should just return nil to give other functions a chance. If it
10656 does handle the file, it must return the search string to be used
10657 when following the link. The search string will be part of the
10658 file link, given after a double colon, and `org-open-at-point'
10659 will automatically search for it. If special measures must be
10660 taken to make the search successful, another function should be
10661 added to the companion hook `org-execute-file-search-functions',
10662 which see.
10664 A function in this hook may also use `setq' to set the variable
10665 `description' to provide a suggestion for the descriptive text to
10666 be used for this link when it gets inserted into an Org-mode
10667 buffer with \\[org-insert-link].")
10669 (defvar org-execute-file-search-functions nil
10670 "List of functions to execute a file search triggered by a link.
10672 Functions added to this hook must accept a single argument, the
10673 search string that was part of the file link, the part after the
10674 double colon. The function must first check if it would like to
10675 handle this search, for example by checking the `major-mode' or
10676 the file extension. If it decides not to handle this search, it
10677 should just return nil to give other functions a chance. If it
10678 does handle the search, it must return a non-nil value to keep
10679 other functions from trying.
10681 Each function can access the current prefix argument through the
10682 variable `current-prefix-arg'. Note that a single prefix is used
10683 to force opening a link in Emacs, so it may be good to only use a
10684 numeric or double prefix to guide the search function.
10686 In case this is needed, a function in this hook can also restore
10687 the window configuration before `org-open-at-point' was called using:
10689 (set-window-configuration org-window-config-before-follow-link)")
10691 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10692 (defun org-link-search (s &optional type avoid-pos stealth)
10693 "Search for a link search option.
10694 If S is surrounded by forward slashes, it is interpreted as a
10695 regular expression. In org-mode files, this will create an `org-occur'
10696 sparse tree. In ordinary files, `occur' will be used to list matches.
10697 If the current buffer is in `dired-mode', grep will be used to search
10698 in all files. If AVOID-POS is given, ignore matches near that position.
10700 When optional argument STEALTH is non-nil, do not modify
10701 visibility around point, thus ignoring
10702 `org-show-hierarchy-above', `org-show-following-heading' and
10703 `org-show-siblings' variables."
10704 (let ((case-fold-search t)
10705 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10706 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10707 (append '(("") (" ") ("\t") ("\n"))
10708 org-emphasis-alist)
10709 "\\|") "\\)"))
10710 (pos (point))
10711 (pre nil) (post nil)
10712 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10713 (cond
10714 ;; First check if there are any special search functions
10715 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10716 ;; Now try the builtin stuff
10717 ((and (equal (string-to-char s0) ?#)
10718 (> (length s0) 1)
10719 (save-excursion
10720 (goto-char (point-min))
10721 (and
10722 (re-search-forward
10723 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10724 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10725 (setq type 'dedicated
10726 pos (match-beginning 0))))
10727 ;; There is an exact target for this
10728 (goto-char pos)
10729 (org-back-to-heading t)))
10730 ((save-excursion
10731 (goto-char (point-min))
10732 (and
10733 (re-search-forward
10734 (concat "<<" (regexp-quote s0) ">>") nil t)
10735 (setq type 'dedicated
10736 pos (match-beginning 0))))
10737 ;; There is an exact target for this
10738 (goto-char pos))
10739 ((save-excursion
10740 (goto-char (point-min))
10741 (and
10742 (re-search-forward
10743 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10744 (setq type 'dedicated pos (match-beginning 0))))
10745 ;; Found an element with a matching #+name affiliated keyword.
10746 (goto-char pos))
10747 ((and (string-match "^(\\(.*\\))$" s0)
10748 (save-excursion
10749 (goto-char (point-min))
10750 (and
10751 (re-search-forward
10752 (concat "[^[]" (regexp-quote
10753 (format org-coderef-label-format
10754 (match-string 1 s0))))
10755 nil t)
10756 (setq type 'dedicated
10757 pos (1+ (match-beginning 0))))))
10758 ;; There is a coderef target for this
10759 (goto-char pos))
10760 ((string-match "^/\\(.*\\)/$" s)
10761 ;; A regular expression
10762 (cond
10763 ((derived-mode-p 'org-mode)
10764 (org-occur (match-string 1 s)))
10765 (t (org-do-occur (match-string 1 s)))))
10766 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10767 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10768 (goto-char (point-min))
10769 (cond
10770 ((let (case-fold-search)
10771 (re-search-forward (format org-complex-heading-regexp-format
10772 (regexp-quote s))
10773 nil t))
10774 ;; OK, found a match
10775 (setq type 'dedicated)
10776 (goto-char (match-beginning 0)))
10777 ((and (not org-link-search-inhibit-query)
10778 (eq org-link-search-must-match-exact-headline 'query-to-create)
10779 (y-or-n-p "No match - create this as a new heading? "))
10780 (goto-char (point-max))
10781 (or (bolp) (newline))
10782 (insert "* " s "\n")
10783 (beginning-of-line 0))
10785 (goto-char pos)
10786 (error "No match"))))
10788 ;; A normal search string
10789 (when (equal (string-to-char s) ?*)
10790 ;; Anchor on headlines, post may include tags.
10791 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10792 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10793 s (substring s 1)))
10794 (remove-text-properties
10795 0 (length s)
10796 '(face nil mouse-face nil keymap nil fontified nil) s)
10797 ;; Make a series of regular expressions to find a match
10798 (setq words (org-split-string s "[ \n\r\t]+")
10800 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10801 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10802 "\\)" markers)
10803 re2a_ (concat "\\(" (mapconcat 'downcase words
10804 "[ \t\r\n]+") "\\)[ \t\r\n]")
10805 re2a (concat "[ \t\r\n]" re2a_)
10806 re4_ (concat "\\(" (mapconcat 'downcase words
10807 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10808 re4 (concat "[^a-zA-Z_]" re4_)
10810 re1 (concat pre re2 post)
10811 re3 (concat pre (if pre re4_ re4) post)
10812 re5 (concat pre ".*" re4)
10813 re2 (concat pre re2)
10814 re2a (concat pre (if pre re2a_ re2a))
10815 re4 (concat pre (if pre re4_ re4))
10816 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10817 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10818 re5 "\\)"))
10819 (cond
10820 ((eq type 'org-occur) (org-occur reall))
10821 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10822 (t (goto-char (point-min))
10823 (setq type 'fuzzy)
10824 (if (or (and (org-search-not-self 1 re0 nil t)
10825 (setq type 'dedicated))
10826 (org-search-not-self 1 re1 nil t)
10827 (org-search-not-self 1 re2 nil t)
10828 (org-search-not-self 1 re2a nil t)
10829 (org-search-not-self 1 re3 nil t)
10830 (org-search-not-self 1 re4 nil t)
10831 (org-search-not-self 1 re5 nil t))
10832 (goto-char (match-beginning 1))
10833 (goto-char pos)
10834 (error "No match"))))))
10835 (and (derived-mode-p 'org-mode)
10836 (not stealth)
10837 (org-show-context 'link-search))
10838 type))
10840 (defun org-search-not-self (group &rest args)
10841 "Execute `re-search-forward', but only accept matches that do not
10842 enclose the position of `org-open-link-marker'."
10843 (let ((m org-open-link-marker))
10844 (catch 'exit
10845 (while (apply 're-search-forward args)
10846 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10847 (goto-char (match-end group))
10848 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10849 (> (match-beginning 0) (marker-position m))
10850 (< (match-end 0) (marker-position m)))
10851 (save-match-data
10852 (or (not (org-in-regexp
10853 org-bracket-link-analytic-regexp 1))
10854 (not (match-end 4)) ; no description
10855 (and (<= (match-beginning 4) (point))
10856 (>= (match-end 4) (point))))))
10857 (throw 'exit (point))))))))
10859 (defun org-get-buffer-for-internal-link (buffer)
10860 "Return a buffer to be used for displaying the link target of internal links."
10861 (cond
10862 ((not org-display-internal-link-with-indirect-buffer)
10863 buffer)
10864 ((string-match "(Clone)$" (buffer-name buffer))
10865 (message "Buffer is already a clone, not making another one")
10866 ;; we also do not modify visibility in this case
10867 buffer)
10868 (t ; make a new indirect buffer for displaying the link
10869 (let* ((bn (buffer-name buffer))
10870 (ibn (concat bn "(Clone)"))
10871 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10872 (with-current-buffer ib (org-overview))
10873 ib))))
10875 (defun org-do-occur (regexp &optional cleanup)
10876 "Call the Emacs command `occur'.
10877 If CLEANUP is non-nil, remove the printout of the regular expression
10878 in the *Occur* buffer. This is useful if the regex is long and not useful
10879 to read."
10880 (occur regexp)
10881 (when cleanup
10882 (let ((cwin (selected-window)) win beg end)
10883 (when (setq win (get-buffer-window "*Occur*"))
10884 (select-window win))
10885 (goto-char (point-min))
10886 (when (re-search-forward "match[a-z]+" nil t)
10887 (setq beg (match-end 0))
10888 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10889 (setq end (1- (match-beginning 0)))))
10890 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10891 (goto-char (point-min))
10892 (select-window cwin))))
10894 ;;; The mark ring for links jumps
10896 (defvar org-mark-ring nil
10897 "Mark ring for positions before jumps in Org-mode.")
10898 (defvar org-mark-ring-last-goto nil
10899 "Last position in the mark ring used to go back.")
10900 ;; Fill and close the ring
10901 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10902 (loop for i from 1 to org-mark-ring-length do
10903 (push (make-marker) org-mark-ring))
10904 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10905 org-mark-ring)
10907 (defun org-mark-ring-push (&optional pos buffer)
10908 "Put the current position or POS into the mark ring and rotate it."
10909 (interactive)
10910 (setq pos (or pos (point)))
10911 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10912 (move-marker (car org-mark-ring)
10913 (or pos (point))
10914 (or buffer (current-buffer)))
10915 (message "%s"
10916 (substitute-command-keys
10917 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10919 (defun org-mark-ring-goto (&optional n)
10920 "Jump to the previous position in the mark ring.
10921 With prefix arg N, jump back that many stored positions. When
10922 called several times in succession, walk through the entire ring.
10923 Org-mode commands jumping to a different position in the current file,
10924 or to another Org-mode file, automatically push the old position
10925 onto the ring."
10926 (interactive "p")
10927 (let (p m)
10928 (if (eq last-command this-command)
10929 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10930 (setq p org-mark-ring))
10931 (setq org-mark-ring-last-goto p)
10932 (setq m (car p))
10933 (org-pop-to-buffer-same-window (marker-buffer m))
10934 (goto-char m)
10935 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10937 (defun org-remove-angle-brackets (s)
10938 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10939 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10941 (defun org-add-angle-brackets (s)
10942 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10943 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10945 (defun org-remove-double-quotes (s)
10946 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10947 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10950 ;;; Following specific links
10952 (defun org-follow-timestamp-link ()
10953 "Open an agenda view for the time-stamp date/range at point."
10954 (cond
10955 ((org-at-date-range-p t)
10956 (let ((org-agenda-start-on-weekday)
10957 (t1 (match-string 1))
10958 (t2 (match-string 2)) tt1 tt2)
10959 (setq tt1 (time-to-days (org-time-string-to-time t1))
10960 tt2 (time-to-days (org-time-string-to-time t2)))
10961 (let ((org-agenda-buffer-tmp-name
10962 (format "*Org Agenda(a:%s)"
10963 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10964 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10965 ((org-at-timestamp-p t)
10966 (let ((org-agenda-buffer-tmp-name
10967 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10968 (org-agenda-list nil (time-to-days (org-time-string-to-time
10969 (substring (match-string 1) 0 10)))
10970 1)))
10971 (t (error "This should not happen"))))
10974 ;;; Following file links
10975 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10976 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10977 (declare-function mailcap-mime-info
10978 "mailcap" (string &optional request no-decode))
10979 (defvar org-wait nil)
10980 (defun org-open-file (path &optional in-emacs line search)
10981 "Open the file at PATH.
10982 First, this expands any special file name abbreviations. Then the
10983 configuration variable `org-file-apps' is checked if it contains an
10984 entry for this file type, and if yes, the corresponding command is launched.
10986 If no application is found, Emacs simply visits the file.
10988 With optional prefix argument IN-EMACS, Emacs will visit the file.
10989 With a double \\[universal-argument] \\[universal-argument] \
10990 prefix arg, Org tries to avoid opening in Emacs
10991 and to use an external application to visit the file.
10993 Optional LINE specifies a line to go to, optional SEARCH a string
10994 to search for. If LINE or SEARCH is given, the file will be
10995 opened in Emacs, unless an entry from org-file-apps that makes
10996 use of groups in a regexp matches.
10998 If you want to change the way frames are used when following a
10999 link, please customize `org-link-frame-setup'.
11001 If the file does not exist, an error is thrown."
11002 (let* ((file (if (equal path "")
11003 buffer-file-name
11004 (substitute-in-file-name (expand-file-name path))))
11005 (file-apps (append org-file-apps (org-default-apps)))
11006 (apps (org-remove-if
11007 'org-file-apps-entry-match-against-dlink-p file-apps))
11008 (apps-dlink (org-remove-if-not
11009 'org-file-apps-entry-match-against-dlink-p file-apps))
11010 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11011 (dirp (if remp nil (file-directory-p file)))
11012 (file (if (and dirp org-open-directory-means-index-dot-org)
11013 (concat (file-name-as-directory file) "index.org")
11014 file))
11015 (a-m-a-p (assq 'auto-mode apps))
11016 (dfile (downcase file))
11017 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11018 (link (cond ((and (eq line nil)
11019 (eq search nil))
11020 file)
11021 (line
11022 (concat file "::" (number-to-string line)))
11023 (search
11024 (concat file "::" search))))
11025 (dlink (downcase link))
11026 (old-buffer (current-buffer))
11027 (old-pos (point))
11028 (old-mode major-mode)
11029 ext cmd link-match-data)
11030 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11031 (setq ext (match-string 1 dfile))
11032 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11033 (setq ext (match-string 1 dfile))))
11034 (cond
11035 ((member in-emacs '((16) system))
11036 (setq cmd (cdr (assoc 'system apps))))
11037 (in-emacs (setq cmd 'emacs))
11039 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11040 (and dirp (cdr (assoc 'directory apps)))
11041 ; first, try matching against apps-dlink
11042 ; if we get a match here, store the match data for later
11043 (let ((match (assoc-default dlink apps-dlink
11044 'string-match)))
11045 (if match
11046 (progn (setq link-match-data (match-data))
11047 match)
11048 (progn (setq in-emacs (or in-emacs line search))
11049 nil))) ; if we have no match in apps-dlink,
11050 ; always open the file in emacs if line or search
11051 ; is given (for backwards compatibility)
11052 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11053 'string-match)
11054 (cdr (assoc ext apps))
11055 (cdr (assoc t apps))))))
11056 (when (eq cmd 'system)
11057 (setq cmd (cdr (assoc 'system apps))))
11058 (when (eq cmd 'default)
11059 (setq cmd (cdr (assoc t apps))))
11060 (when (eq cmd 'mailcap)
11061 (require 'mailcap)
11062 (mailcap-parse-mailcaps)
11063 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11064 (command (mailcap-mime-info mime-type)))
11065 (if (stringp command)
11066 (setq cmd command)
11067 (setq cmd 'emacs))))
11068 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11069 (not (file-exists-p file))
11070 (not org-open-non-existing-files))
11071 (user-error "No such file: %s" file))
11072 (cond
11073 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11074 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11075 (while (string-match "['\"]%s['\"]" cmd)
11076 (setq cmd (replace-match "%s" t t cmd)))
11077 (while (string-match "%s" cmd)
11078 (setq cmd (replace-match
11079 (save-match-data
11080 (shell-quote-argument
11081 (convert-standard-filename file)))
11082 t t cmd)))
11084 ;; Replace "%1", "%2" etc. in command with group matches from regex
11085 (save-match-data
11086 (let ((match-index 1)
11087 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11088 (set-match-data link-match-data)
11089 (while (<= match-index number-of-groups)
11090 (let ((regex (concat "%" (number-to-string match-index)))
11091 (replace-with (match-string match-index dlink)))
11092 (while (string-match regex cmd)
11093 (setq cmd (replace-match replace-with t t cmd))))
11094 (setq match-index (+ match-index 1)))))
11096 (save-window-excursion
11097 (message "Running %s...done" cmd)
11098 (start-process-shell-command cmd nil cmd)
11099 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11100 ((or (stringp cmd)
11101 (eq cmd 'emacs))
11102 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11103 (widen)
11104 (if line (org-goto-line line)
11105 (if search (org-link-search search))))
11106 ((consp cmd)
11107 (let ((file (convert-standard-filename file)))
11108 (save-match-data
11109 (set-match-data link-match-data)
11110 (eval cmd))))
11111 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11112 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11113 (or (not (equal old-buffer (current-buffer)))
11114 (not (equal old-pos (point))))
11115 (org-mark-ring-push old-pos old-buffer))))
11117 (defun org-file-apps-entry-match-against-dlink-p (entry)
11118 "This function returns non-nil if `entry' uses a regular
11119 expression which should be matched against the whole link by
11120 org-open-file.
11122 It assumes that is the case when the entry uses a regular
11123 expression which has at least one grouping construct and the
11124 action is either a lisp form or a command string containing
11125 '%1', i.e. using at least one subexpression match as a
11126 parameter."
11127 (let ((selector (car entry))
11128 (action (cdr entry)))
11129 (if (stringp selector)
11130 (and (> (regexp-opt-depth selector) 0)
11131 (or (and (stringp action)
11132 (string-match "%[0-9]" action))
11133 (consp action)))
11134 nil)))
11136 (defun org-default-apps ()
11137 "Return the default applications for this operating system."
11138 (cond
11139 ((eq system-type 'darwin)
11140 org-file-apps-defaults-macosx)
11141 ((eq system-type 'windows-nt)
11142 org-file-apps-defaults-windowsnt)
11143 (t org-file-apps-defaults-gnu)))
11145 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11146 "Convert extensions to regular expressions in the cars of LIST.
11147 Also, weed out any non-string entries, because the return value is used
11148 only for regexp matching.
11149 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11150 point to the symbol `emacs', indicating that the file should
11151 be opened in Emacs."
11152 (append
11153 (delq nil
11154 (mapcar (lambda (x)
11155 (if (not (stringp (car x)))
11157 (if (string-match "\\W" (car x))
11159 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11160 list))
11161 (if add-auto-mode
11162 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11164 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11165 (defun org-file-remote-p (file)
11166 "Test whether FILE specifies a location on a remote system.
11167 Return non-nil if the location is indeed remote.
11169 For example, the filename \"/user@host:/foo\" specifies a location
11170 on the system \"/user@host:\"."
11171 (cond ((fboundp 'file-remote-p)
11172 (file-remote-p file))
11173 ((fboundp 'tramp-handle-file-remote-p)
11174 (tramp-handle-file-remote-p file))
11175 ((and (boundp 'ange-ftp-name-format)
11176 (string-match (car ange-ftp-name-format) file))
11177 t)))
11180 ;;;; Refiling
11182 (defun org-get-org-file ()
11183 "Read a filename, with default directory `org-directory'."
11184 (let ((default (or org-default-notes-file remember-data-file)))
11185 (read-file-name (format "File name [%s]: " default)
11186 (file-name-as-directory org-directory)
11187 default)))
11189 (defun org-notes-order-reversed-p ()
11190 "Check if the current file should receive notes in reversed order."
11191 (cond
11192 ((not org-reverse-note-order) nil)
11193 ((eq t org-reverse-note-order) t)
11194 ((not (listp org-reverse-note-order)) nil)
11195 (t (catch 'exit
11196 (let ((all org-reverse-note-order)
11197 entry)
11198 (while (setq entry (pop all))
11199 (if (string-match (car entry) buffer-file-name)
11200 (throw 'exit (cdr entry))))
11201 nil)))))
11203 (defvar org-refile-target-table nil
11204 "The list of refile targets, created by `org-refile'.")
11206 (defvar org-agenda-new-buffers nil
11207 "Buffers created to visit agenda files.")
11209 (defvar org-refile-cache nil
11210 "Cache for refile targets.")
11212 (defvar org-refile-markers nil
11213 "All the markers used for caching refile locations.")
11215 (defun org-refile-marker (pos)
11216 "Get a new refile marker, but only if caching is in use."
11217 (if (not org-refile-use-cache)
11219 (let ((m (make-marker)))
11220 (move-marker m pos)
11221 (push m org-refile-markers)
11222 m)))
11224 (defun org-refile-cache-clear ()
11225 "Clear the refile cache and disable all the markers."
11226 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11227 (setq org-refile-markers nil)
11228 (setq org-refile-cache nil)
11229 (message "Refile cache has been cleared"))
11231 (defun org-refile-cache-check-set (set)
11232 "Check if all the markers in the cache still have live buffers."
11233 (let (marker)
11234 (catch 'exit
11235 (while (and set (setq marker (nth 3 (pop set))))
11236 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11237 (when (and marker (null (marker-buffer marker)))
11238 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11239 (sit-for 3)
11240 (throw 'exit nil)))
11241 t)))
11243 (defun org-refile-cache-put (set &rest identifiers)
11244 "Push the refile targets SET into the cache, under IDENTIFIERS."
11245 (let* ((key (sha1 (prin1-to-string identifiers)))
11246 (entry (assoc key org-refile-cache)))
11247 (if entry
11248 (setcdr entry set)
11249 (push (cons key set) org-refile-cache))))
11251 (defun org-refile-cache-get (&rest identifiers)
11252 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11253 (cond
11254 ((not org-refile-cache) nil)
11255 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11257 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11258 org-refile-cache))))
11259 (and set (org-refile-cache-check-set set) set)))))
11261 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11262 "Produce a table with refile targets."
11263 (let ((case-fold-search nil)
11264 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11265 (entries (or org-refile-targets '((nil . (:level . 1)))))
11266 targets tgs txt re files f desc descre fast-path-p level pos0)
11267 (message "Getting targets...")
11268 (with-current-buffer (or default-buffer (current-buffer))
11269 (while (setq entry (pop entries))
11270 (setq files (car entry) desc (cdr entry))
11271 (setq fast-path-p nil)
11272 (cond
11273 ((null files) (setq files (list (current-buffer))))
11274 ((eq files 'org-agenda-files)
11275 (setq files (org-agenda-files 'unrestricted)))
11276 ((and (symbolp files) (fboundp files))
11277 (setq files (funcall files)))
11278 ((and (symbolp files) (boundp files))
11279 (setq files (symbol-value files))))
11280 (if (stringp files) (setq files (list files)))
11281 (cond
11282 ((eq (car desc) :tag)
11283 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11284 ((eq (car desc) :todo)
11285 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11286 ((eq (car desc) :regexp)
11287 (setq descre (cdr desc)))
11288 ((eq (car desc) :level)
11289 (setq descre (concat "^\\*\\{" (number-to-string
11290 (if org-odd-levels-only
11291 (1- (* 2 (cdr desc)))
11292 (cdr desc)))
11293 "\\}[ \t]")))
11294 ((eq (car desc) :maxlevel)
11295 (setq fast-path-p t)
11296 (setq descre (concat "^\\*\\{1," (number-to-string
11297 (if org-odd-levels-only
11298 (1- (* 2 (cdr desc)))
11299 (cdr desc)))
11300 "\\}[ \t]")))
11301 (t (error "Bad refiling target description %s" desc)))
11302 (while (setq f (pop files))
11303 (with-current-buffer
11304 (if (bufferp f) f (org-get-agenda-file-buffer f))
11306 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11307 (progn
11308 (if (bufferp f) (setq f (buffer-file-name
11309 (buffer-base-buffer f))))
11310 (setq f (and f (expand-file-name f)))
11311 (if (eq org-refile-use-outline-path 'file)
11312 (push (list (file-name-nondirectory f) f nil nil) tgs))
11313 (save-excursion
11314 (save-restriction
11315 (widen)
11316 (goto-char (point-min))
11317 (while (re-search-forward descre nil t)
11318 (goto-char (setq pos0 (point-at-bol)))
11319 (catch 'next
11320 (when org-refile-target-verify-function
11321 (save-match-data
11322 (or (funcall org-refile-target-verify-function)
11323 (throw 'next t))))
11324 (when (and (looking-at org-complex-heading-regexp)
11325 (not (member (match-string 4) excluded-entries))
11326 (match-string 4))
11327 (setq level (org-reduced-level
11328 (- (match-end 1) (match-beginning 1)))
11329 txt (org-link-display-format (match-string 4))
11330 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11331 re (format org-complex-heading-regexp-format
11332 (regexp-quote (match-string 4))))
11333 (when org-refile-use-outline-path
11334 (setq txt (mapconcat
11335 'org-protect-slash
11336 (append
11337 (if (eq org-refile-use-outline-path
11338 'file)
11339 (list (file-name-nondirectory
11340 (buffer-file-name
11341 (buffer-base-buffer))))
11342 (if (eq org-refile-use-outline-path
11343 'full-file-path)
11344 (list (buffer-file-name
11345 (buffer-base-buffer)))))
11346 (org-get-outline-path fast-path-p
11347 level txt)
11348 (list txt))
11349 "/")))
11350 (push (list txt f re (org-refile-marker (point)))
11351 tgs)))
11352 (when (= (point) pos0)
11353 ;; verification function has not moved point
11354 (goto-char (point-at-eol))))))))
11355 (when org-refile-use-cache
11356 (org-refile-cache-put tgs (buffer-file-name) descre))
11357 (setq targets (append tgs targets))))))
11358 (message "Getting targets...done")
11359 (nreverse targets)))
11361 (defun org-protect-slash (s)
11362 (while (string-match "/" s)
11363 (setq s (replace-match "\\" t t s)))
11366 (defvar org-olpa (make-vector 20 nil))
11368 (defun org-get-outline-path (&optional fastp level heading)
11369 "Return the outline path to the current entry, as a list.
11371 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11372 routine which makes outline path derivations for an entire file,
11373 avoiding backtracing. Refile target collection makes use of that."
11374 (if fastp
11375 (progn
11376 (if (> level 19)
11377 (error "Outline path failure, more than 19 levels"))
11378 (loop for i from level upto 19 do
11379 (aset org-olpa i nil))
11380 (prog1
11381 (delq nil (append org-olpa nil))
11382 (aset org-olpa level heading)))
11383 (let (rtn case-fold-search)
11384 (save-excursion
11385 (save-restriction
11386 (widen)
11387 (while (org-up-heading-safe)
11388 (when (looking-at org-complex-heading-regexp)
11389 (push (org-trim
11390 (replace-regexp-in-string
11391 ;; Remove statistical/checkboxes cookies
11392 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11393 (org-match-string-no-properties 4)))
11394 rtn)))
11395 rtn)))))
11397 (defun org-format-outline-path (path &optional width prefix separator)
11398 "Format the outline path PATH for display.
11399 WIDTH is the maximum number of characters that is available.
11400 PREFIX is a prefix to be included in the returned string,
11401 such as the file name.
11402 SEPARATOR is inserted between the different parts of the path,
11403 the default is \"/\"."
11404 (setq width (or width 79))
11405 (if prefix (setq width (- width (length prefix))))
11406 (if (not path)
11407 (or prefix "")
11408 (let* ((nsteps (length path))
11409 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11410 (maxwidth (if (<= total-width width)
11411 10000 ;; everything fits
11412 ;; we need to shorten the level headings
11413 (/ (- width nsteps) nsteps)))
11414 (org-odd-levels-only nil)
11415 (n 0)
11416 (total (1+ (length prefix))))
11417 (setq maxwidth (max maxwidth 10))
11418 (concat prefix
11419 (if prefix (or separator "/"))
11420 (mapconcat
11421 (lambda (h)
11422 (setq n (1+ n))
11423 (if (and (= n nsteps) (< maxwidth 10000))
11424 (setq maxwidth (- total-width total)))
11425 (if (< (length h) maxwidth)
11426 (progn (setq total (+ total (length h) 1)) h)
11427 (setq h (substring h 0 (- maxwidth 2))
11428 total (+ total maxwidth 1))
11429 (if (string-match "[ \t]+\\'" h)
11430 (setq h (substring h 0 (match-beginning 0))))
11431 (setq h (concat h "..")))
11432 (org-add-props h nil 'face
11433 (nth (% (1- n) org-n-level-faces)
11434 org-level-faces))
11436 path (or separator "/"))))))
11438 (defun org-display-outline-path (&optional file current separator just-return-string)
11439 "Display the current outline path in the echo area.
11441 If FILE is non-nil, prepend the output with the file name.
11442 If CURRENT is non-nil, append the current heading to the output.
11443 SEPARATOR is passed through to `org-format-outline-path'. It separates
11444 the different parts of the path and defaults to \"/\".
11445 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11446 (interactive "P")
11447 (let* (case-fold-search
11448 (bfn (buffer-file-name (buffer-base-buffer)))
11449 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11450 res)
11451 (if current (setq path (append path
11452 (save-excursion
11453 (org-back-to-heading t)
11454 (if (looking-at org-complex-heading-regexp)
11455 (list (match-string 4)))))))
11456 (setq res
11457 (org-format-outline-path
11458 path
11459 (1- (frame-width))
11460 (and file bfn (concat (file-name-nondirectory bfn) separator))
11461 separator))
11462 (if just-return-string
11463 (org-no-properties res)
11464 (org-unlogged-message "%s" res))))
11466 (defvar org-refile-history nil
11467 "History for refiling operations.")
11469 (defvar org-after-refile-insert-hook nil
11470 "Hook run after `org-refile' has inserted its stuff at the new location.
11471 Note that this is still *before* the stuff will be removed from
11472 the *old* location.")
11474 (defvar org-capture-last-stored-marker)
11475 (defvar org-refile-keep nil
11476 "Non-nil means `org-refile' will copy instead of refile.")
11478 (defun org-copy ()
11479 "Like `org-refile', but copy."
11480 (interactive)
11481 (let ((org-refile-keep t))
11482 (funcall 'org-refile nil nil nil "Copy")))
11484 (defun org-refile (&optional goto default-buffer rfloc msg)
11485 "Move the entry or entries at point to another heading.
11486 The list of target headings is compiled using the information in
11487 `org-refile-targets', which see.
11489 At the target location, the entry is filed as a subitem of the target
11490 heading. Depending on `org-reverse-note-order', the new subitem will
11491 either be the first or the last subitem.
11493 If there is an active region, all entries in that region will be moved.
11494 However, the region must fulfill the requirement that the first heading
11495 is the first one sets the top-level of the moved text - at most siblings
11496 below it are allowed.
11498 With prefix arg GOTO, the command will only visit the target location
11499 and not actually move anything.
11501 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11502 go to the location where the last refiling operation has put the subtree.
11504 With a numeric prefix argument of `2', refile to the running clock.
11506 With a numeric prefix argument of `3', emulate `org-refile-keep'
11507 being set to `t' and copy to the target location, don't move it.
11508 Beware that keeping refiled entries may result in duplicated ID
11509 properties.
11511 RFLOC can be a refile location obtained in a different way.
11513 MSG is a string to replace \"Refile\" in the default prompt with
11514 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11516 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11518 If you are using target caching (see `org-refile-use-cache'),
11519 you have to clear the target cache in order to find new targets.
11520 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11521 prefix argument (`C-u C-u C-u C-c C-w')."
11523 (interactive "P")
11524 (if (member goto '(0 (64)))
11525 (org-refile-cache-clear)
11526 (let* ((actionmsg (or msg "Refile"))
11527 (cbuf (current-buffer))
11528 (regionp (org-region-active-p))
11529 (region-start (and regionp (region-beginning)))
11530 (region-end (and regionp (region-end)))
11531 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11532 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11533 pos it nbuf file re level reversed)
11534 (setq last-command nil)
11535 (when regionp
11536 (goto-char region-start)
11537 (or (bolp) (goto-char (point-at-bol)))
11538 (setq region-start (point))
11539 (unless (or (org-kill-is-subtree-p
11540 (buffer-substring region-start region-end))
11541 (prog1 org-refile-active-region-within-subtree
11542 (let ((s (point-at-eol)))
11543 (org-toggle-heading)
11544 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11545 (user-error "The region is not a (sequence of) subtree(s)")))
11546 (if (equal goto '(16))
11547 (org-refile-goto-last-stored)
11548 (when (or
11549 (and (equal goto 2)
11550 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11551 (prog1
11552 (setq it (list (or org-clock-heading "running clock")
11553 (buffer-file-name
11554 (marker-buffer org-clock-hd-marker))
11556 (marker-position org-clock-hd-marker)))
11557 (setq goto nil)))
11558 (setq it (or rfloc
11559 (let (heading-text)
11560 (save-excursion
11561 (unless goto
11562 (org-back-to-heading t)
11563 (setq heading-text
11564 (nth 4 (org-heading-components))))
11566 (org-refile-get-location
11567 (cond (goto "Goto")
11568 (regionp (concat actionmsg " region to"))
11569 (t (concat actionmsg " subtree \""
11570 heading-text "\" to")))
11571 default-buffer
11572 (and (not (equal '(4) goto))
11573 org-refile-allow-creating-parent-nodes)
11574 goto))))))
11575 (setq file (nth 1 it)
11576 re (nth 2 it)
11577 pos (nth 3 it))
11578 (if (and (not goto)
11580 (equal (buffer-file-name) file)
11581 (if regionp
11582 (and (>= pos region-start)
11583 (<= pos region-end))
11584 (and (>= pos (point))
11585 (< pos (save-excursion
11586 (org-end-of-subtree t t))))))
11587 (error "Cannot refile to position inside the tree or region"))
11589 (setq nbuf (or (find-buffer-visiting file)
11590 (find-file-noselect file)))
11591 (if (and goto (not (equal goto 3)))
11592 (progn
11593 (org-pop-to-buffer-same-window nbuf)
11594 (goto-char pos)
11595 (org-show-context 'org-goto))
11596 (if regionp
11597 (progn
11598 (org-kill-new (buffer-substring region-start region-end))
11599 (org-save-markers-in-region region-start region-end))
11600 (org-copy-subtree 1 nil t))
11601 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11602 (find-file-noselect file)))
11603 (setq reversed (org-notes-order-reversed-p))
11604 (save-excursion
11605 (save-restriction
11606 (widen)
11607 (if pos
11608 (progn
11609 (goto-char pos)
11610 (looking-at org-outline-regexp)
11611 (setq level (org-get-valid-level (funcall outline-level) 1))
11612 (goto-char
11613 (if reversed
11614 (or (outline-next-heading) (point-max))
11615 (or (save-excursion (org-get-next-sibling))
11616 (org-end-of-subtree t t)
11617 (point-max)))))
11618 (setq level 1)
11619 (if (not reversed)
11620 (goto-char (point-max))
11621 (goto-char (point-min))
11622 (or (outline-next-heading) (goto-char (point-max)))))
11623 (if (not (bolp)) (newline))
11624 (org-paste-subtree level)
11625 (when org-log-refile
11626 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11627 (unless (eq org-log-refile 'note)
11628 (save-excursion (org-add-log-note))))
11629 (and org-auto-align-tags
11630 (let ((org-loop-over-headlines-in-active-region nil))
11631 (org-set-tags nil t)))
11632 (let ((bookmark-name (plist-get org-bookmark-names-plist
11633 :last-refile)))
11634 (when bookmark-name
11635 (with-demoted-errors
11636 (bookmark-set bookmark-name))))
11637 ;; If we are refiling for capture, make sure that the
11638 ;; last-capture pointers point here
11639 (when (org-bound-and-true-p org-refile-for-capture)
11640 (let ((bookmark-name (plist-get org-bookmark-names-plist
11641 :last-capture-marker)))
11642 (when bookmark-name
11643 (with-demoted-errors
11644 (bookmark-set bookmark-name))))
11645 (move-marker org-capture-last-stored-marker (point)))
11646 (if (fboundp 'deactivate-mark) (deactivate-mark))
11647 (run-hooks 'org-after-refile-insert-hook))))
11648 (unless org-refile-keep
11649 (if regionp
11650 (delete-region (point) (+ (point) (- region-end region-start)))
11651 (delete-region
11652 (and (org-back-to-heading t) (point))
11653 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11654 (when (featurep 'org-inlinetask)
11655 (org-inlinetask-remove-END-maybe))
11656 (setq org-markers-to-move nil)
11657 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11659 (defun org-refile-goto-last-stored ()
11660 "Go to the location where the last refile was stored."
11661 (interactive)
11662 (bookmark-jump "org-refile-last-stored")
11663 (message "This is the location of the last refile"))
11665 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11666 no-exclude)
11667 "Prompt the user for a refile location, using PROMPT.
11668 PROMPT should not be suffixed with a colon and a space, because
11669 this function appends the default value from
11670 `org-refile-history' automatically, if that is not empty.
11671 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11672 this is used for the GOTO interface."
11673 (let ((org-refile-targets org-refile-targets)
11674 (org-refile-use-outline-path org-refile-use-outline-path)
11675 excluded-entries)
11676 (when (and (derived-mode-p 'org-mode)
11677 (not org-refile-use-cache)
11678 (not no-exclude))
11679 (org-map-tree
11680 (lambda()
11681 (setq excluded-entries
11682 (append excluded-entries (list (org-get-heading t t)))))))
11683 (setq org-refile-target-table
11684 (org-refile-get-targets default-buffer excluded-entries)))
11685 (unless org-refile-target-table
11686 (user-error "No refile targets"))
11687 (let* ((cbuf (current-buffer))
11688 (partial-completion-mode nil)
11689 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11690 (cfunc (if (and org-refile-use-outline-path
11691 org-outline-path-complete-in-steps)
11692 'org-olpath-completing-read
11693 'org-icompleting-read))
11694 (extra (if org-refile-use-outline-path "/" ""))
11695 (cbnex (concat (buffer-name) extra))
11696 (filename (and cfn (expand-file-name cfn)))
11697 (tbl (mapcar
11698 (lambda (x)
11699 (if (and (not (member org-refile-use-outline-path
11700 '(file full-file-path)))
11701 (not (equal filename (nth 1 x))))
11702 (cons (concat (car x) extra " ("
11703 (file-name-nondirectory (nth 1 x)) ")")
11704 (cdr x))
11705 (cons (concat (car x) extra) (cdr x))))
11706 org-refile-target-table))
11707 (completion-ignore-case t)
11708 cdef
11709 (prompt (concat prompt
11710 (or (and (car org-refile-history)
11711 (concat " (default " (car org-refile-history) ")"))
11712 (and (assoc cbnex tbl) (setq cdef cbnex)
11713 (concat " (default " cbnex ")"))) ": "))
11714 pa answ parent-target child parent old-hist)
11715 (setq old-hist org-refile-history)
11716 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11717 nil 'org-refile-history (or cdef (car org-refile-history))))
11718 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11719 (org-refile-check-position pa)
11720 (if pa
11721 (progn
11722 (when (or (not org-refile-history)
11723 (not (eq old-hist org-refile-history))
11724 (not (equal (car pa) (car org-refile-history))))
11725 (setq org-refile-history
11726 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11727 org-refile-history
11728 (cdr org-refile-history))))
11729 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11730 (pop org-refile-history)))
11732 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11733 (progn
11734 (setq parent (match-string 1 answ)
11735 child (match-string 2 answ))
11736 (setq parent-target (or (assoc parent tbl)
11737 (assoc (concat parent "/") tbl)))
11738 (when (and parent-target
11739 (or (eq new-nodes t)
11740 (and (eq new-nodes 'confirm)
11741 (y-or-n-p (format "Create new node \"%s\"? "
11742 child)))))
11743 (org-refile-new-child parent-target child)))
11744 (user-error "Invalid target location")))))
11746 (declare-function org-string-nw-p "org-macs" (s))
11747 (defun org-refile-check-position (refile-pointer)
11748 "Check if the refile pointer matches the headline to which it points."
11749 (let* ((file (nth 1 refile-pointer))
11750 (re (nth 2 refile-pointer))
11751 (pos (nth 3 refile-pointer))
11752 buffer)
11753 (if (and (not (markerp pos)) (not file))
11754 (user-error "Please save the buffer to a file before refiling")
11755 (when (org-string-nw-p re)
11756 (setq buffer (if (markerp pos)
11757 (marker-buffer pos)
11758 (or (find-buffer-visiting file)
11759 (find-file-noselect file))))
11760 (with-current-buffer buffer
11761 (save-excursion
11762 (save-restriction
11763 (widen)
11764 (goto-char pos)
11765 (beginning-of-line 1)
11766 (unless (org-looking-at-p re)
11767 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11769 (defun org-refile-new-child (parent-target child)
11770 "Use refile target PARENT-TARGET to add new CHILD below it."
11771 (unless parent-target
11772 (error "Cannot find parent for new node"))
11773 (let ((file (nth 1 parent-target))
11774 (pos (nth 3 parent-target))
11775 level)
11776 (with-current-buffer (or (find-buffer-visiting file)
11777 (find-file-noselect file))
11778 (save-excursion
11779 (save-restriction
11780 (widen)
11781 (if pos
11782 (goto-char pos)
11783 (goto-char (point-max))
11784 (if (not (bolp)) (newline)))
11785 (when (looking-at org-outline-regexp)
11786 (setq level (funcall outline-level))
11787 (org-end-of-subtree t t))
11788 (org-back-over-empty-lines)
11789 (insert "\n" (make-string
11790 (if pos (org-get-valid-level level 1) 1) ?*)
11791 " " child "\n")
11792 (beginning-of-line 0)
11793 (list (concat (car parent-target) "/" child) file "" (point)))))))
11795 (defun org-olpath-completing-read (prompt collection &rest args)
11796 "Read an outline path like a file name."
11797 (let ((thetable collection)
11798 (org-completion-use-ido nil) ; does not work with ido.
11799 (org-completion-use-iswitchb nil)) ; or iswitchb
11800 (apply
11801 'org-icompleting-read prompt
11802 (lambda (string predicate &optional flag)
11803 (let (rtn r f (l (length string)))
11804 (cond
11805 ((eq flag nil)
11806 ;; try completion
11807 (try-completion string thetable))
11808 ((eq flag t)
11809 ;; all-completions
11810 (setq rtn (all-completions string thetable predicate))
11811 (mapcar
11812 (lambda (x)
11813 (setq r (substring x l))
11814 (if (string-match " ([^)]*)$" x)
11815 (setq f (match-string 0 x))
11816 (setq f ""))
11817 (if (string-match "/" r)
11818 (concat string (substring r 0 (match-end 0)) f)
11820 rtn))
11821 ((eq flag 'lambda)
11822 ;; exact match?
11823 (assoc string thetable)))))
11824 args)))
11826 ;;;; Dynamic blocks
11828 (defun org-find-dblock (name)
11829 "Find the first dynamic block with name NAME in the buffer.
11830 If not found, stay at current position and return nil."
11831 (let ((case-fold-search t) pos)
11832 (save-excursion
11833 (goto-char (point-min))
11834 (setq pos (and (re-search-forward
11835 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11836 (match-beginning 0))))
11837 (if pos (goto-char pos))
11838 pos))
11840 (defconst org-dblock-start-re
11841 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11842 "Matches the start line of a dynamic block, with parameters.")
11844 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11845 "Matches the end of a dynamic block.")
11847 (defun org-create-dblock (plist)
11848 "Create a dynamic block section, with parameters taken from PLIST.
11849 PLIST must contain a :name entry which is used as name of the block."
11850 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11851 (end-of-line 1)
11852 (newline))
11853 (let ((col (current-column))
11854 (name (plist-get plist :name)))
11855 (insert "#+BEGIN: " name)
11856 (while plist
11857 (if (eq (car plist) :name)
11858 (setq plist (cddr plist))
11859 (insert " " (prin1-to-string (pop plist)))))
11860 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11861 (beginning-of-line -2)))
11863 (defun org-prepare-dblock ()
11864 "Prepare dynamic block for refresh.
11865 This empties the block, puts the cursor at the insert position and returns
11866 the property list including an extra property :name with the block name."
11867 (unless (looking-at org-dblock-start-re)
11868 (user-error "Not at a dynamic block"))
11869 (let* ((begdel (1+ (match-end 0)))
11870 (name (org-no-properties (match-string 1)))
11871 (params (append (list :name name)
11872 (read (concat "(" (match-string 3) ")")))))
11873 (save-excursion
11874 (beginning-of-line 1)
11875 (skip-chars-forward " \t")
11876 (setq params (plist-put params :indentation-column (current-column))))
11877 (unless (re-search-forward org-dblock-end-re nil t)
11878 (error "Dynamic block not terminated"))
11879 (setq params
11880 (append params
11881 (list :content (buffer-substring
11882 begdel (match-beginning 0)))))
11883 (delete-region begdel (match-beginning 0))
11884 (goto-char begdel)
11885 (open-line 1)
11886 params))
11888 (defun org-map-dblocks (&optional command)
11889 "Apply COMMAND to all dynamic blocks in the current buffer.
11890 If COMMAND is not given, use `org-update-dblock'."
11891 (let ((cmd (or command 'org-update-dblock)))
11892 (save-excursion
11893 (goto-char (point-min))
11894 (while (re-search-forward org-dblock-start-re nil t)
11895 (goto-char (match-beginning 0))
11896 (save-excursion
11897 (condition-case nil
11898 (funcall cmd)
11899 (error (message "Error during update of dynamic block"))))
11900 (unless (re-search-forward org-dblock-end-re nil t)
11901 (error "Dynamic block not terminated"))))))
11903 (defun org-dblock-update (&optional arg)
11904 "User command for updating dynamic blocks.
11905 Update the dynamic block at point. With prefix ARG, update all dynamic
11906 blocks in the buffer."
11907 (interactive "P")
11908 (if arg
11909 (org-update-all-dblocks)
11910 (or (looking-at org-dblock-start-re)
11911 (org-beginning-of-dblock))
11912 (org-update-dblock)))
11914 (defun org-update-dblock ()
11915 "Update the dynamic block at point.
11916 This means to empty the block, parse for parameters and then call
11917 the correct writing function."
11918 (interactive)
11919 (save-window-excursion
11920 (let* ((pos (point))
11921 (line (org-current-line))
11922 (params (org-prepare-dblock))
11923 (name (plist-get params :name))
11924 (indent (plist-get params :indentation-column))
11925 (cmd (intern (concat "org-dblock-write:" name))))
11926 (message "Updating dynamic block `%s' at line %d..." name line)
11927 (funcall cmd params)
11928 (message "Updating dynamic block `%s' at line %d...done" name line)
11929 (goto-char pos)
11930 (when (and indent (> indent 0))
11931 (setq indent (make-string indent ?\ ))
11932 (save-excursion
11933 (org-beginning-of-dblock)
11934 (forward-line 1)
11935 (while (not (looking-at org-dblock-end-re))
11936 (insert indent)
11937 (beginning-of-line 2))
11938 (when (looking-at org-dblock-end-re)
11939 (and (looking-at "[ \t]+")
11940 (replace-match ""))
11941 (insert indent)))))))
11943 (defun org-beginning-of-dblock ()
11944 "Find the beginning of the dynamic block at point.
11945 Error if there is no such block at point."
11946 (let ((pos (point))
11947 beg)
11948 (end-of-line 1)
11949 (if (and (re-search-backward org-dblock-start-re nil t)
11950 (setq beg (match-beginning 0))
11951 (re-search-forward org-dblock-end-re nil t)
11952 (> (match-end 0) pos))
11953 (goto-char beg)
11954 (goto-char pos)
11955 (error "Not in a dynamic block"))))
11957 (defun org-update-all-dblocks ()
11958 "Update all dynamic blocks in the buffer.
11959 This function can be used in a hook."
11960 (interactive)
11961 (when (derived-mode-p 'org-mode)
11962 (org-map-dblocks 'org-update-dblock)))
11965 ;;;; Completion
11967 (declare-function org-export-backend-name "org-export" (cl-x))
11968 (declare-function org-export-backend-options "org-export" (cl-x))
11969 (defun org-get-export-keywords ()
11970 "Return a list of all currently understood export keywords.
11971 Export keywords include options, block names, attributes and
11972 keywords relative to each registered export back-end."
11973 (let (keywords)
11974 (dolist (backend
11975 (org-bound-and-true-p org-export--registered-backends)
11976 (delq nil keywords))
11977 ;; Back-end name (for keywords, like #+LATEX:)
11978 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11979 (dolist (option-entry (org-export-backend-options backend))
11980 ;; Back-end options.
11981 (push (nth 1 option-entry) keywords)))))
11983 (defconst org-options-keywords
11984 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11985 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11986 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11987 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11988 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11990 (defcustom org-structure-template-alist
11991 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11992 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11993 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11994 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11995 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11996 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11997 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11998 "<literal style=\"latex\">\n?\n</literal>")
11999 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12000 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12001 "<literal style=\"html\">\n?\n</literal>")
12002 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12003 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12004 ("A" "#+ASCII: " "")
12005 ("i" "#+INDEX: ?" "#+INDEX: ?")
12006 ("I" "#+INCLUDE: %file ?"
12007 "<include file=%file markup=\"?\">"))
12008 "Structure completion elements.
12009 This is a list of abbreviation keys and values. The value gets inserted
12010 if you type `<' followed by the key and then press the completion key,
12011 usually `M-TAB'. %file will be replaced by a file name after prompting
12012 for the file using completion. The cursor will be placed at the position
12013 of the `?` in the template.
12014 There are two templates for each key, the first uses the original Org syntax,
12015 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12016 the default when the /org-mtags.el/ module has been loaded. See also the
12017 variable `org-mtags-prefer-muse-templates'."
12018 :group 'org-completion
12019 :type '(repeat
12020 (list
12021 (string :tag "Key")
12022 (string :tag "Template")
12023 (string :tag "Muse Template"))))
12025 (defun org-try-structure-completion ()
12026 "Try to complete a structure template before point.
12027 This looks for strings like \"<e\" on an otherwise empty line and
12028 expands them."
12029 (let ((l (buffer-substring (point-at-bol) (point)))
12031 (when (and (looking-at "[ \t]*$")
12032 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12033 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12034 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12035 (match-beginning 1)) a)
12036 t)))
12038 (defun org-complete-expand-structure-template (start cell)
12039 "Expand a structure template."
12040 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12041 (rpl (nth (if musep 2 1) cell))
12042 (ind ""))
12043 (delete-region start (point))
12044 (when (string-match "\\`#\\+" rpl)
12045 (cond
12046 ((bolp))
12047 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12048 (setq ind (buffer-substring (point-at-bol) (point))))
12049 (t (newline))))
12050 (setq start (point))
12051 (if (string-match "%file" rpl)
12052 (setq rpl (replace-match
12053 (concat
12054 "\""
12055 (save-match-data
12056 (abbreviate-file-name (read-file-name "Include file: ")))
12057 "\"")
12058 t t rpl)))
12059 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12060 (concat "\n" ind)))
12061 (insert rpl)
12062 (if (re-search-backward "\\?" start t) (delete-char 1))))
12064 ;;;; TODO, DEADLINE, Comments
12066 (defun org-toggle-comment ()
12067 "Change the COMMENT state of an entry."
12068 (interactive)
12069 (save-excursion
12070 (org-back-to-heading)
12071 (let (case-fold-search)
12072 (cond
12073 ((looking-at (format org-heading-keyword-regexp-format
12074 org-comment-string))
12075 (goto-char (match-end 1))
12076 (looking-at (concat " +" org-comment-string))
12077 (replace-match "" t t)
12078 (when (eolp) (insert " ")))
12079 ((looking-at org-outline-regexp)
12080 (goto-char (match-end 0))
12081 (insert org-comment-string " "))))))
12083 (defvar org-last-todo-state-is-todo nil
12084 "This is non-nil when the last TODO state change led to a TODO state.
12085 If the last change removed the TODO tag or switched to DONE, then
12086 this is nil.")
12088 (defvar org-setting-tags nil) ; dynamically skipped
12090 (defvar org-todo-setup-filter-hook nil
12091 "Hook for functions that pre-filter todo specs.
12092 Each function takes a todo spec and returns either nil or the spec
12093 transformed into canonical form." )
12095 (defvar org-todo-get-default-hook nil
12096 "Hook for functions that get a default item for todo.
12097 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12098 nil or a string to be used for the todo mark." )
12100 (defvar org-agenda-headline-snapshot-before-repeat)
12102 (defun org-current-effective-time ()
12103 "Return current time adjusted for `org-extend-today-until' variable."
12104 (let* ((ct (org-current-time))
12105 (dct (decode-time ct))
12106 (ct1
12107 (cond
12108 (org-use-last-clock-out-time-as-effective-time
12109 (or (org-clock-get-last-clock-out-time) ct))
12110 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12111 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12112 (t ct))))
12113 ct1))
12115 (defun org-todo-yesterday (&optional arg)
12116 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12117 (interactive "P")
12118 (if (eq major-mode 'org-agenda-mode)
12119 (apply 'org-agenda-todo-yesterday arg)
12120 (let* ((hour (third (decode-time
12121 (org-current-time))))
12122 (org-extend-today-until (1+ hour)))
12123 (org-todo arg))))
12125 (defvar org-block-entry-blocking ""
12126 "First entry preventing the TODO state change.")
12128 (defun org-todo (&optional arg)
12129 "Change the TODO state of an item.
12130 The state of an item is given by a keyword at the start of the heading,
12131 like
12132 *** TODO Write paper
12133 *** DONE Call mom
12135 The different keywords are specified in the variable `org-todo-keywords'.
12136 By default the available states are \"TODO\" and \"DONE\".
12137 So for this example: when the item starts with TODO, it is changed to DONE.
12138 When it starts with DONE, the DONE is removed. And when neither TODO nor
12139 DONE are present, add TODO at the beginning of the heading.
12141 With \\[universal-argument] prefix arg, use completion to determine the new \
12142 state.
12143 With numeric prefix arg, switch to that state.
12144 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12145 keywords (nextset).
12146 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12147 With a numeric prefix arg of 0, inhibit note taking for the change.
12149 For calling through lisp, arg is also interpreted in the following way:
12150 'none -> empty state
12151 \"\"(empty string) -> switch to empty state
12152 'done -> switch to DONE
12153 'nextset -> switch to the next set of keywords
12154 'previousset -> switch to the previous set of keywords
12155 \"WAITING\" -> switch to the specified keyword, but only if it
12156 really is a member of `org-todo-keywords'."
12157 (interactive "P")
12158 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12159 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12160 'region-start-level 'region))
12161 org-loop-over-headlines-in-active-region)
12162 (org-map-entries
12163 `(org-todo ,arg)
12164 org-loop-over-headlines-in-active-region
12165 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12166 (if (equal arg '(16)) (setq arg 'nextset))
12167 (let ((org-blocker-hook org-blocker-hook)
12168 commentp
12169 case-fold-search)
12170 (when (equal arg '(64))
12171 (setq arg nil org-blocker-hook nil))
12172 (when (and org-blocker-hook
12173 (or org-inhibit-blocking
12174 (org-entry-get nil "NOBLOCKING")))
12175 (setq org-blocker-hook nil))
12176 (save-excursion
12177 (catch 'exit
12178 (org-back-to-heading t)
12179 (when (looking-at (concat "^\\*+ " org-comment-string))
12180 (org-toggle-comment)
12181 (setq commentp t))
12182 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12183 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12184 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12185 (let* ((match-data (match-data))
12186 (startpos (point-at-bol))
12187 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12188 (org-log-done org-log-done)
12189 (org-log-repeat org-log-repeat)
12190 (org-todo-log-states org-todo-log-states)
12191 (org-inhibit-logging
12192 (if (equal arg 0)
12193 (progn (setq arg nil) 'note) org-inhibit-logging))
12194 (this (match-string 1))
12195 (hl-pos (match-beginning 0))
12196 (head (org-get-todo-sequence-head this))
12197 (ass (assoc head org-todo-kwd-alist))
12198 (interpret (nth 1 ass))
12199 (done-word (nth 3 ass))
12200 (final-done-word (nth 4 ass))
12201 (org-last-state (or this ""))
12202 (completion-ignore-case t)
12203 (member (member this org-todo-keywords-1))
12204 (tail (cdr member))
12205 (org-state (cond
12206 ((and org-todo-key-trigger
12207 (or (and (equal arg '(4))
12208 (eq org-use-fast-todo-selection 'prefix))
12209 (and (not arg) org-use-fast-todo-selection
12210 (not (eq org-use-fast-todo-selection
12211 'prefix)))))
12212 ;; Use fast selection
12213 (org-fast-todo-selection))
12214 ((and (equal arg '(4))
12215 (or (not org-use-fast-todo-selection)
12216 (not org-todo-key-trigger)))
12217 ;; Read a state with completion
12218 (org-icompleting-read
12219 "State: " (mapcar 'list org-todo-keywords-1)
12220 nil t))
12221 ((eq arg 'right)
12222 (if this
12223 (if tail (car tail) nil)
12224 (car org-todo-keywords-1)))
12225 ((eq arg 'left)
12226 (if (equal member org-todo-keywords-1)
12228 (if this
12229 (nth (- (length org-todo-keywords-1)
12230 (length tail) 2)
12231 org-todo-keywords-1)
12232 (org-last org-todo-keywords-1))))
12233 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12234 (setq arg nil))) ; hack to fall back to cycling
12235 (arg
12236 ;; user or caller requests a specific state
12237 (cond
12238 ((equal arg "") nil)
12239 ((eq arg 'none) nil)
12240 ((eq arg 'done) (or done-word (car org-done-keywords)))
12241 ((eq arg 'nextset)
12242 (or (car (cdr (member head org-todo-heads)))
12243 (car org-todo-heads)))
12244 ((eq arg 'previousset)
12245 (let ((org-todo-heads (reverse org-todo-heads)))
12246 (or (car (cdr (member head org-todo-heads)))
12247 (car org-todo-heads))))
12248 ((car (member arg org-todo-keywords-1)))
12249 ((stringp arg)
12250 (user-error "State `%s' not valid in this file" arg))
12251 ((nth (1- (prefix-numeric-value arg))
12252 org-todo-keywords-1))))
12253 ((null member) (or head (car org-todo-keywords-1)))
12254 ((equal this final-done-word) nil) ;; -> make empty
12255 ((null tail) nil) ;; -> first entry
12256 ((memq interpret '(type priority))
12257 (if (eq this-command last-command)
12258 (car tail)
12259 (if (> (length tail) 0)
12260 (or done-word (car org-done-keywords))
12261 nil)))
12263 (car tail))))
12264 (org-state (or
12265 (run-hook-with-args-until-success
12266 'org-todo-get-default-hook org-state org-last-state)
12267 org-state))
12268 (next (if org-state (concat " " org-state " ") " "))
12269 (change-plist (list :type 'todo-state-change :from this :to org-state
12270 :position startpos))
12271 dolog now-done-p)
12272 (when org-blocker-hook
12273 (setq org-last-todo-state-is-todo
12274 (not (member this org-done-keywords)))
12275 (unless (save-excursion
12276 (save-match-data
12277 (org-with-wide-buffer
12278 (run-hook-with-args-until-failure
12279 'org-blocker-hook change-plist))))
12280 (if (org-called-interactively-p 'interactive)
12281 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12282 this org-state org-block-entry-blocking)
12283 ;; fail silently
12284 (message "TODO state change from %s to %s blocked (by \"%s\")"
12285 this org-state org-block-entry-blocking)
12286 (throw 'exit nil))))
12287 (store-match-data match-data)
12288 (replace-match next t t)
12289 (unless (pos-visible-in-window-p hl-pos)
12290 (message "TODO state changed to %s" (org-trim next)))
12291 (unless head
12292 (setq head (org-get-todo-sequence-head org-state)
12293 ass (assoc head org-todo-kwd-alist)
12294 interpret (nth 1 ass)
12295 done-word (nth 3 ass)
12296 final-done-word (nth 4 ass)))
12297 (when (memq arg '(nextset previousset))
12298 (message "Keyword-Set %d/%d: %s"
12299 (- (length org-todo-sets) -1
12300 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12301 (length org-todo-sets)
12302 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12303 (setq org-last-todo-state-is-todo
12304 (not (member org-state org-done-keywords)))
12305 (setq now-done-p (and (member org-state org-done-keywords)
12306 (not (member this org-done-keywords))))
12307 (and logging (org-local-logging logging))
12308 (when (and (or org-todo-log-states org-log-done)
12309 (not (eq org-inhibit-logging t))
12310 (not (memq arg '(nextset previousset))))
12311 ;; we need to look at recording a time and note
12312 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12313 (nth 2 (assoc this org-todo-log-states))))
12314 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12315 (setq dolog 'time))
12316 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12317 (and org-state
12318 (member org-state org-not-done-keywords)
12319 (not (member this org-not-done-keywords))))
12320 ;; This is now a todo state and was not one before
12321 ;; If there was a CLOSED time stamp, get rid of it.
12322 (org-add-planning-info nil nil 'closed))
12323 (when (and now-done-p org-log-done)
12324 ;; It is now done, and it was not done before
12325 (org-add-planning-info 'closed (org-current-effective-time))
12326 (if (and (not dolog) (eq 'note org-log-done))
12327 (org-add-log-setup 'done org-state this 'findpos 'note)))
12328 (when (and org-state dolog)
12329 ;; This is a non-nil state, and we need to log it
12330 (org-add-log-setup 'state org-state this 'findpos dolog)))
12331 ;; Fixup tag positioning
12332 (org-todo-trigger-tag-changes org-state)
12333 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12334 (when org-provide-todo-statistics
12335 (org-update-parent-todo-statistics))
12336 (run-hooks 'org-after-todo-state-change-hook)
12337 (if (and arg (not (member org-state org-done-keywords)))
12338 (setq head (org-get-todo-sequence-head org-state)))
12339 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12340 ;; Do we need to trigger a repeat?
12341 (when now-done-p
12342 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12343 ;; This is for the agenda, take a snapshot of the headline.
12344 (save-match-data
12345 (setq org-agenda-headline-snapshot-before-repeat
12346 (org-get-heading))))
12347 (org-auto-repeat-maybe org-state))
12348 ;; Fixup cursor location if close to the keyword
12349 (if (and (outline-on-heading-p)
12350 (not (bolp))
12351 (save-excursion (beginning-of-line 1)
12352 (looking-at org-todo-line-regexp))
12353 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12354 (progn
12355 (goto-char (or (match-end 2) (match-end 1)))
12356 (and (looking-at " ") (just-one-space))))
12357 (when org-trigger-hook
12358 (save-excursion
12359 (run-hook-with-args 'org-trigger-hook change-plist)))
12360 (when commentp (org-toggle-comment))))))))
12362 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12363 "Block turning an entry into a TODO, using the hierarchy.
12364 This checks whether the current task should be blocked from state
12365 changes. Such blocking occurs when:
12367 1. The task has children which are not all in a completed state.
12369 2. A task has a parent with the property :ORDERED:, and there
12370 are siblings prior to the current task with incomplete
12371 status.
12373 3. The parent of the task is blocked because it has siblings that should
12374 be done first, or is child of a block grandparent TODO entry."
12376 (if (not org-enforce-todo-dependencies)
12377 t ; if locally turned off don't block
12378 (catch 'dont-block
12379 ;; If this is not a todo state change, or if this entry is already DONE,
12380 ;; do not block
12381 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12382 (member (plist-get change-plist :from)
12383 (cons 'done org-done-keywords))
12384 (member (plist-get change-plist :to)
12385 (cons 'todo org-not-done-keywords))
12386 (not (plist-get change-plist :to)))
12387 (throw 'dont-block t))
12388 ;; If this task has children, and any are undone, it's blocked
12389 (save-excursion
12390 (org-back-to-heading t)
12391 (let ((this-level (funcall outline-level)))
12392 (outline-next-heading)
12393 (let ((child-level (funcall outline-level)))
12394 (while (and (not (eobp))
12395 (> child-level this-level))
12396 ;; this todo has children, check whether they are all
12397 ;; completed
12398 (if (and (not (org-entry-is-done-p))
12399 (org-entry-is-todo-p))
12400 (progn (setq org-block-entry-blocking (org-get-heading))
12401 (throw 'dont-block nil)))
12402 (outline-next-heading)
12403 (setq child-level (funcall outline-level))))))
12404 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12405 ;; any previous siblings are undone, it's blocked
12406 (save-excursion
12407 (org-back-to-heading t)
12408 (let* ((pos (point))
12409 (parent-pos (and (org-up-heading-safe) (point))))
12410 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12411 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12412 (forward-line 1)
12413 (re-search-forward org-not-done-heading-regexp pos t))
12414 (setq org-block-entry-blocking (match-string 0))
12415 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12416 ;; Search further up the hierarchy, to see if an ancestor is blocked
12417 (while t
12418 (goto-char parent-pos)
12419 (if (not (looking-at org-not-done-heading-regexp))
12420 (throw 'dont-block t)) ; do not block, parent is not a TODO
12421 (setq pos (point))
12422 (setq parent-pos (and (org-up-heading-safe) (point)))
12423 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12424 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12425 (forward-line 1)
12426 (re-search-forward org-not-done-heading-regexp pos t)
12427 (setq org-block-entry-blocking (org-get-heading)))
12428 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12430 (defcustom org-track-ordered-property-with-tag nil
12431 "Should the ORDERED property also be shown as a tag?
12432 The ORDERED property decides if an entry should require subtasks to be
12433 completed in sequence. Since a property is not very visible, setting
12434 this option means that toggling the ORDERED property with the command
12435 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12436 not relevant for the behavior, but it makes things more visible.
12438 Note that toggling the tag with tags commands will not change the property
12439 and therefore not influence behavior!
12441 This can be t, meaning the tag ORDERED should be used, It can also be a
12442 string to select a different tag for this task."
12443 :group 'org-todo
12444 :type '(choice
12445 (const :tag "No tracking" nil)
12446 (const :tag "Track with ORDERED tag" t)
12447 (string :tag "Use other tag")))
12449 (defun org-toggle-ordered-property ()
12450 "Toggle the ORDERED property of the current entry.
12451 For better visibility, you can track the value of this property with a tag.
12452 See variable `org-track-ordered-property-with-tag'."
12453 (interactive)
12454 (let* ((t1 org-track-ordered-property-with-tag)
12455 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12456 (save-excursion
12457 (org-back-to-heading)
12458 (if (org-entry-get nil "ORDERED")
12459 (progn
12460 (org-delete-property "ORDERED" "PROPERTIES")
12461 (and tag (org-toggle-tag tag 'off))
12462 (message "Subtasks can be completed in arbitrary order"))
12463 (org-entry-put nil "ORDERED" "t")
12464 (and tag (org-toggle-tag tag 'on))
12465 (message "Subtasks must be completed in sequence")))))
12467 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12468 (defun org-block-todo-from-checkboxes (change-plist)
12469 "Block turning an entry into a TODO, using checkboxes.
12470 This checks whether the current task should be blocked from state
12471 changes because there are unchecked boxes in this entry."
12472 (if (not org-enforce-todo-checkbox-dependencies)
12473 t ; if locally turned off don't block
12474 (catch 'dont-block
12475 ;; If this is not a todo state change, or if this entry is already DONE,
12476 ;; do not block
12477 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12478 (member (plist-get change-plist :from)
12479 (cons 'done org-done-keywords))
12480 (member (plist-get change-plist :to)
12481 (cons 'todo org-not-done-keywords))
12482 (not (plist-get change-plist :to)))
12483 (throw 'dont-block t))
12484 ;; If this task has checkboxes that are not checked, it's blocked
12485 (save-excursion
12486 (org-back-to-heading t)
12487 (let ((beg (point)) end)
12488 (outline-next-heading)
12489 (setq end (point))
12490 (goto-char beg)
12491 (if (org-list-search-forward
12492 (concat (org-item-beginning-re)
12493 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12494 "\\[[- ]\\]")
12495 end t)
12496 (progn
12497 (if (boundp 'org-blocked-by-checkboxes)
12498 (setq org-blocked-by-checkboxes t))
12499 (throw 'dont-block nil)))))
12500 t))) ; do not block
12502 (defun org-entry-blocked-p ()
12503 "Is the current entry blocked?"
12504 (org-with-silent-modifications
12505 (if (org-entry-get nil "NOBLOCKING")
12506 nil ;; Never block this entry
12507 (not (run-hook-with-args-until-failure
12508 'org-blocker-hook
12509 (list :type 'todo-state-change
12510 :position (point)
12511 :from 'todo
12512 :to 'done))))))
12514 (defun org-update-statistics-cookies (all)
12515 "Update the statistics cookie, either from TODO or from checkboxes.
12516 This should be called with the cursor in a line with a statistics cookie."
12517 (interactive "P")
12518 (if all
12519 (progn
12520 (org-update-checkbox-count 'all)
12521 (org-map-entries 'org-update-parent-todo-statistics))
12522 (if (not (org-at-heading-p))
12523 (org-update-checkbox-count)
12524 (let ((pos (point-marker))
12525 end l1 l2)
12526 (ignore-errors (org-back-to-heading t))
12527 (if (not (org-at-heading-p))
12528 (org-update-checkbox-count)
12529 (setq l1 (org-outline-level))
12530 (setq end (save-excursion
12531 (outline-next-heading)
12532 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12533 (point)))
12534 (if (and (save-excursion
12535 (re-search-forward
12536 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12537 (not (save-excursion (re-search-forward
12538 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12539 (org-update-checkbox-count)
12540 (if (and l2 (> l2 l1))
12541 (progn
12542 (goto-char end)
12543 (org-update-parent-todo-statistics))
12544 (goto-char pos)
12545 (beginning-of-line 1)
12546 (while (re-search-forward
12547 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12548 (point-at-eol) t)
12549 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12550 (goto-char pos)
12551 (move-marker pos nil)))))
12553 (defvar org-entry-property-inherited-from) ;; defined below
12554 (defun org-update-parent-todo-statistics ()
12555 "Update any statistics cookie in the parent of the current headline.
12556 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12557 the entire subtree and this will travel up the hierarchy and update
12558 statistics everywhere."
12559 (let* ((prop (save-excursion (org-up-heading-safe)
12560 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12561 (recursive (or (not org-hierarchical-todo-statistics)
12562 (and prop (string-match "\\<recursive\\>" prop))))
12563 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12565 (first t)
12566 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12567 level ltoggle l1 new ndel
12568 (cnt-all 0) (cnt-done 0) is-percent kwd
12569 checkbox-beg ov ovs ove cookie-present)
12570 (catch 'exit
12571 (save-excursion
12572 (beginning-of-line 1)
12573 (setq ltoggle (funcall outline-level))
12574 ;; Three situations are to consider:
12576 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12577 ;; to the top-level ancestor on the headline;
12579 ;; 2. If parent has "recursive" property, repeat up to the
12580 ;; headline setting that property, taking inheritance into
12581 ;; account;
12583 ;; 3. Else, move up to direct parent and proceed only once.
12584 (while (and (setq level (org-up-heading-safe))
12585 (or recursive first)
12586 (>= (point) lim))
12587 (setq first nil cookie-present nil)
12588 (unless (and level
12589 (not (string-match
12590 "\\<checkbox\\>"
12591 (downcase (or (org-entry-get nil "COOKIE_DATA")
12592 "")))))
12593 (throw 'exit nil))
12594 (while (re-search-forward box-re (point-at-eol) t)
12595 (setq cnt-all 0 cnt-done 0 cookie-present t)
12596 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12597 (save-match-data
12598 (unless (outline-next-heading) (throw 'exit nil))
12599 (while (and (looking-at org-complex-heading-regexp)
12600 (> (setq l1 (length (match-string 1))) level))
12601 (setq kwd (and (or recursive (= l1 ltoggle))
12602 (match-string 2)))
12603 (if (or (eq org-provide-todo-statistics 'all-headlines)
12604 (and (listp org-provide-todo-statistics)
12605 (or (member kwd org-provide-todo-statistics)
12606 (member kwd org-done-keywords))))
12607 (setq cnt-all (1+ cnt-all))
12608 (if (eq org-provide-todo-statistics t)
12609 (and kwd (setq cnt-all (1+ cnt-all)))))
12610 (and (member kwd org-done-keywords)
12611 (setq cnt-done (1+ cnt-done)))
12612 (outline-next-heading)))
12613 (setq new
12614 (if is-percent
12615 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12616 (format "[%d/%d]" cnt-done cnt-all))
12617 ndel (- (match-end 0) checkbox-beg))
12618 ;; handle overlays when updating cookie from column view
12619 (when (setq ov (car (overlays-at checkbox-beg)))
12620 (setq ovs (overlay-start ov) ove (overlay-end ov))
12621 (delete-overlay ov))
12622 (goto-char checkbox-beg)
12623 (insert new)
12624 (delete-region (point) (+ (point) ndel))
12625 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12626 (when ov (move-overlay ov ovs ove)))
12627 (when cookie-present
12628 (run-hook-with-args 'org-after-todo-statistics-hook
12629 cnt-done (- cnt-all cnt-done))))))
12630 (run-hooks 'org-todo-statistics-hook)))
12632 (defvar org-after-todo-statistics-hook nil
12633 "Hook that is called after a TODO statistics cookie has been updated.
12634 Each function is called with two arguments: the number of not-done entries
12635 and the number of done entries.
12637 For example, the following function, when added to this hook, will switch
12638 an entry to DONE when all children are done, and back to TODO when new
12639 entries are set to a TODO status. Note that this hook is only called
12640 when there is a statistics cookie in the headline!
12642 (defun org-summary-todo (n-done n-not-done)
12643 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12644 (let (org-log-done org-log-states) ; turn off logging
12645 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12648 (defvar org-todo-statistics-hook nil
12649 "Hook that is run whenever Org thinks TODO statistics should be updated.
12650 This hook runs even if there is no statistics cookie present, in which case
12651 `org-after-todo-statistics-hook' would not run.")
12653 (defun org-todo-trigger-tag-changes (state)
12654 "Apply the changes defined in `org-todo-state-tags-triggers'."
12655 (let ((l org-todo-state-tags-triggers)
12656 changes)
12657 (when (or (not state) (equal state ""))
12658 (setq changes (append changes (cdr (assoc "" l)))))
12659 (when (and (stringp state) (> (length state) 0))
12660 (setq changes (append changes (cdr (assoc state l)))))
12661 (when (member state org-not-done-keywords)
12662 (setq changes (append changes (cdr (assoc 'todo l)))))
12663 (when (member state org-done-keywords)
12664 (setq changes (append changes (cdr (assoc 'done l)))))
12665 (dolist (c changes)
12666 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12668 (defun org-local-logging (value)
12669 "Get logging settings from a property VALUE."
12670 (let* (words w a)
12671 ;; directly set the variables, they are already local.
12672 (setq org-log-done nil
12673 org-log-repeat nil
12674 org-todo-log-states nil)
12675 (setq words (org-split-string value))
12676 (while (setq w (pop words))
12677 (cond
12678 ((setq a (assoc w org-startup-options))
12679 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12680 (set (nth 1 a) (nth 2 a))))
12681 ((setq a (org-extract-log-state-settings w))
12682 (and (member (car a) org-todo-keywords-1)
12683 (push a org-todo-log-states)))))))
12685 (defun org-get-todo-sequence-head (kwd)
12686 "Return the head of the TODO sequence to which KWD belongs.
12687 If KWD is not set, check if there is a text property remembering the
12688 right sequence."
12689 (let (p)
12690 (cond
12691 ((not kwd)
12692 (or (get-text-property (point-at-bol) 'org-todo-head)
12693 (progn
12694 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12695 nil (point-at-eol)))
12696 (get-text-property p 'org-todo-head))))
12697 ((not (member kwd org-todo-keywords-1))
12698 (car org-todo-keywords-1))
12699 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12701 (defun org-fast-todo-selection ()
12702 "Fast TODO keyword selection with single keys.
12703 Returns the new TODO keyword, or nil if no state change should occur."
12704 (let* ((fulltable org-todo-key-alist)
12705 (done-keywords org-done-keywords) ;; needed for the faces.
12706 (maxlen (apply 'max (mapcar
12707 (lambda (x)
12708 (if (stringp (car x)) (string-width (car x)) 0))
12709 fulltable)))
12710 (expert nil)
12711 (fwidth (+ maxlen 3 1 3))
12712 (ncol (/ (- (window-width) 4) fwidth))
12713 tg cnt e c tbl
12714 groups ingroup)
12715 (save-excursion
12716 (save-window-excursion
12717 (if expert
12718 (set-buffer (get-buffer-create " *Org todo*"))
12719 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12720 (erase-buffer)
12721 (org-set-local 'org-done-keywords done-keywords)
12722 (setq tbl fulltable cnt 0)
12723 (while (setq e (pop tbl))
12724 (cond
12725 ((equal e '(:startgroup))
12726 (push '() groups) (setq ingroup t)
12727 (when (not (= cnt 0))
12728 (setq cnt 0)
12729 (insert "\n"))
12730 (insert "{ "))
12731 ((equal e '(:endgroup))
12732 (setq ingroup nil cnt 0)
12733 (insert "}\n"))
12734 ((equal e '(:newline))
12735 (when (not (= cnt 0))
12736 (setq cnt 0)
12737 (insert "\n")
12738 (setq e (car tbl))
12739 (while (equal (car tbl) '(:newline))
12740 (insert "\n")
12741 (setq tbl (cdr tbl)))))
12743 (setq tg (car e) c (cdr e))
12744 (if ingroup (push tg (car groups)))
12745 (setq tg (org-add-props tg nil 'face
12746 (org-get-todo-face tg)))
12747 (if (and (= cnt 0) (not ingroup)) (insert " "))
12748 (insert "[" c "] " tg (make-string
12749 (- fwidth 4 (length tg)) ?\ ))
12750 (when (= (setq cnt (1+ cnt)) ncol)
12751 (insert "\n")
12752 (if ingroup (insert " "))
12753 (setq cnt 0)))))
12754 (insert "\n")
12755 (goto-char (point-min))
12756 (if (not expert) (org-fit-window-to-buffer))
12757 (message "[a-z..]:Set [SPC]:clear")
12758 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12759 (cond
12760 ((or (= c ?\C-g)
12761 (and (= c ?q) (not (rassoc c fulltable))))
12762 (setq quit-flag t))
12763 ((= c ?\ ) nil)
12764 ((setq e (rassoc c fulltable) tg (car e))
12766 (t (setq quit-flag t)))))))
12768 (defun org-entry-is-todo-p ()
12769 (member (org-get-todo-state) org-not-done-keywords))
12771 (defun org-entry-is-done-p ()
12772 (member (org-get-todo-state) org-done-keywords))
12774 (defun org-get-todo-state ()
12775 "Return the TODO keyword of the current subtree."
12776 (save-excursion
12777 (org-back-to-heading t)
12778 (and (looking-at org-todo-line-regexp)
12779 (match-end 2)
12780 (match-string 2))))
12782 (defun org-at-date-range-p (&optional inactive-ok)
12783 "Is the cursor inside a date range?"
12784 (interactive)
12785 (save-excursion
12786 (catch 'exit
12787 (let ((pos (point)))
12788 (skip-chars-backward "^[<\r\n")
12789 (skip-chars-backward "<[")
12790 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12791 (>= (match-end 0) pos)
12792 (throw 'exit t))
12793 (skip-chars-backward "^<[\r\n")
12794 (skip-chars-backward "<[")
12795 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12796 (>= (match-end 0) pos)
12797 (throw 'exit t)))
12798 nil)))
12800 (defun org-get-repeat (&optional tagline)
12801 "Check if there is a deadline/schedule with repeater in this entry."
12802 (save-match-data
12803 (save-excursion
12804 (org-back-to-heading t)
12805 (and (re-search-forward (if tagline
12806 (concat tagline "\\s-*" org-repeat-re)
12807 org-repeat-re)
12808 (org-entry-end-position) t)
12809 (match-string-no-properties 1)))))
12811 (defvar org-last-changed-timestamp)
12812 (defvar org-last-inserted-timestamp)
12813 (defvar org-log-post-message)
12814 (defvar org-log-note-purpose)
12815 (defvar org-log-note-how)
12816 (defvar org-log-note-extra)
12817 (defun org-auto-repeat-maybe (done-word)
12818 "Check if the current headline contains a repeated deadline/schedule.
12819 If yes, set TODO state back to what it was and change the base date
12820 of repeating deadline/scheduled time stamps to new date.
12821 This function is run automatically after each state change to a DONE state."
12822 ;; last-state is dynamically scoped into this function
12823 (let* ((repeat (org-get-repeat))
12824 (aa (assoc org-last-state org-todo-kwd-alist))
12825 (interpret (nth 1 aa))
12826 (head (nth 2 aa))
12827 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12828 (msg "Entry repeats: ")
12829 (org-log-done nil)
12830 (org-todo-log-states nil)
12831 re type n what ts time to-state)
12832 (when repeat
12833 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12834 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12835 org-todo-repeat-to-state))
12836 (unless (and to-state (member to-state org-todo-keywords-1))
12837 (setq to-state (if (eq interpret 'type) org-last-state head)))
12838 (org-todo to-state)
12839 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12840 (org-entry-put nil "LAST_REPEAT" (format-time-string
12841 (org-time-stamp-format t t))))
12842 (when org-log-repeat
12843 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12844 (memq 'org-add-log-note post-command-hook))
12845 ;; OK, we are already setup for some record
12846 (if (eq org-log-repeat 'note)
12847 ;; make sure we take a note, not only a time stamp
12848 (setq org-log-note-how 'note))
12849 ;; Set up for taking a record
12850 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12851 org-last-state
12852 'findpos org-log-repeat)))
12853 (org-back-to-heading t)
12854 (org-add-planning-info nil nil 'closed)
12855 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12856 org-deadline-time-regexp "\\)\\|\\("
12857 org-ts-regexp "\\)"))
12858 (while (re-search-forward
12859 re (save-excursion (outline-next-heading) (point)) t)
12860 (setq type (if (match-end 1) org-scheduled-string
12861 (if (match-end 3) org-deadline-string "Plain:"))
12862 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12863 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12864 (setq n (string-to-number (match-string 2 ts))
12865 what (match-string 3 ts))
12866 (if (equal what "w") (setq n (* n 7) what "d"))
12867 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12868 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12869 ;; Preparation, see if we need to modify the start date for the change
12870 (when (match-end 1)
12871 (setq time (save-match-data (org-time-string-to-time ts)))
12872 (cond
12873 ((equal (match-string 1 ts) ".")
12874 ;; Shift starting date to today
12875 (org-timestamp-change
12876 (- (org-today) (time-to-days time))
12877 'day))
12878 ((equal (match-string 1 ts) "+")
12879 (let ((nshiftmax 10) (nshift 0))
12880 (while (or (= nshift 0)
12881 (<= (time-to-days time)
12882 (time-to-days (current-time))))
12883 (when (= (incf nshift) nshiftmax)
12884 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12885 (error "Abort")))
12886 (org-timestamp-change n (cdr (assoc what whata)))
12887 (org-at-timestamp-p t)
12888 (setq ts (match-string 1))
12889 (setq time (save-match-data (org-time-string-to-time ts)))))
12890 (org-timestamp-change (- n) (cdr (assoc what whata)))
12891 ;; rematch, so that we have everything in place for the real shift
12892 (org-at-timestamp-p t)
12893 (setq ts (match-string 1))
12894 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12895 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12896 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12897 (setq org-log-post-message msg)
12898 (message "%s" msg))))
12900 (defun org-show-todo-tree (arg)
12901 "Make a compact tree which shows all headlines marked with TODO.
12902 The tree will show the lines where the regexp matches, and all higher
12903 headlines above the match.
12904 With a \\[universal-argument] prefix, prompt for a regexp to match.
12905 With a numeric prefix N, construct a sparse tree for the Nth element
12906 of `org-todo-keywords-1'."
12907 (interactive "P")
12908 (let ((case-fold-search nil)
12909 (kwd-re
12910 (cond ((null arg) org-not-done-regexp)
12911 ((equal arg '(4))
12912 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12913 (mapcar 'list org-todo-keywords-1))))
12914 (concat "\\("
12915 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12916 "\\)\\>")))
12917 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12918 (regexp-quote (nth (1- (prefix-numeric-value arg))
12919 org-todo-keywords-1)))
12920 (t (user-error "Invalid prefix argument: %s" arg)))))
12921 (message "%d TODO entries found"
12922 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12924 (defun org-deadline (arg &optional time)
12925 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12926 With one universal prefix argument, remove any deadline from the item.
12927 With two universal prefix arguments, prompt for a warning delay.
12928 With argument TIME, set the deadline at the corresponding date. TIME
12929 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12930 (interactive "P")
12931 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12932 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12933 'region-start-level 'region))
12934 org-loop-over-headlines-in-active-region)
12935 (org-map-entries
12936 `(org-deadline ',arg ,time)
12937 org-loop-over-headlines-in-active-region
12938 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12939 (let* ((old-date (org-entry-get nil "DEADLINE"))
12940 (old-date-time (if old-date (org-time-string-to-time old-date)))
12941 (repeater (and old-date
12942 (string-match
12943 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12944 old-date)
12945 (match-string 1 old-date))))
12946 (cond
12947 ((equal arg '(4))
12948 (when (and old-date org-log-redeadline)
12949 (org-add-log-setup 'deldeadline nil old-date 'findpos
12950 org-log-redeadline))
12951 (org-remove-timestamp-with-keyword org-deadline-string)
12952 (message "Item no longer has a deadline."))
12953 ((equal arg '(16))
12954 (save-excursion
12955 (if (re-search-forward
12956 org-deadline-time-regexp
12957 (save-excursion (outline-next-heading) (point)) t)
12958 (let* ((rpl0 (match-string 1))
12959 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12960 (replace-match
12961 (concat org-deadline-string
12962 " <" rpl
12963 (format " -%dd"
12964 (abs
12965 (- (time-to-days
12966 (save-match-data
12967 (org-read-date nil t nil "Warn starting from" old-date-time)))
12968 (time-to-days old-date-time))))
12969 ">") t t))
12970 (user-error "No deadline information to update"))))
12972 (org-add-planning-info 'deadline time 'closed)
12973 (when (and old-date org-log-redeadline
12974 (not (equal old-date
12975 (substring org-last-inserted-timestamp 1 -1))))
12976 (org-add-log-setup 'redeadline nil old-date 'findpos
12977 org-log-redeadline))
12978 (when repeater
12979 (save-excursion
12980 (org-back-to-heading t)
12981 (when (re-search-forward (concat org-deadline-string " "
12982 org-last-inserted-timestamp)
12983 (save-excursion
12984 (outline-next-heading) (point)) t)
12985 (goto-char (1- (match-end 0)))
12986 (insert " " repeater)
12987 (setq org-last-inserted-timestamp
12988 (concat (substring org-last-inserted-timestamp 0 -1)
12989 " " repeater
12990 (substring org-last-inserted-timestamp -1))))))
12991 (message "Deadline on %s" org-last-inserted-timestamp))))))
12993 (defun org-schedule (arg &optional time)
12994 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12995 With one universal prefix argument, remove any scheduling date from the item.
12996 With two universal prefix arguments, prompt for a delay cookie.
12997 With argument TIME, scheduled at the corresponding date. TIME can
12998 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12999 (interactive "P")
13000 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13001 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13002 'region-start-level 'region))
13003 org-loop-over-headlines-in-active-region)
13004 (org-map-entries
13005 `(org-schedule ',arg ,time)
13006 org-loop-over-headlines-in-active-region
13007 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13008 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13009 (old-date-time (if old-date (org-time-string-to-time old-date)))
13010 (repeater (and old-date
13011 (string-match
13012 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13013 old-date)
13014 (match-string 1 old-date))))
13015 (cond
13016 ((equal arg '(4))
13017 (progn
13018 (when (and old-date org-log-reschedule)
13019 (org-add-log-setup 'delschedule nil old-date 'findpos
13020 org-log-reschedule))
13021 (org-remove-timestamp-with-keyword org-scheduled-string)
13022 (message "Item is no longer scheduled.")))
13023 ((equal arg '(16))
13024 (save-excursion
13025 (if (re-search-forward
13026 org-scheduled-time-regexp
13027 (save-excursion (outline-next-heading) (point)) t)
13028 (let* ((rpl0 (match-string 1))
13029 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13030 (replace-match
13031 (concat org-scheduled-string
13032 " <" rpl
13033 (format " -%dd"
13034 (abs
13035 (- (time-to-days
13036 (save-match-data
13037 (org-read-date nil t nil "Delay until" old-date-time)))
13038 (time-to-days old-date-time))))
13039 ">") t t))
13040 (user-error "No scheduled information to update"))))
13042 (org-add-planning-info 'scheduled time 'closed)
13043 (when (and old-date org-log-reschedule
13044 (not (equal old-date
13045 (substring org-last-inserted-timestamp 1 -1))))
13046 (org-add-log-setup 'reschedule nil old-date 'findpos
13047 org-log-reschedule))
13048 (when repeater
13049 (save-excursion
13050 (org-back-to-heading t)
13051 (when (re-search-forward (concat org-scheduled-string " "
13052 org-last-inserted-timestamp)
13053 (save-excursion
13054 (outline-next-heading) (point)) t)
13055 (goto-char (1- (match-end 0)))
13056 (insert " " repeater)
13057 (setq org-last-inserted-timestamp
13058 (concat (substring org-last-inserted-timestamp 0 -1)
13059 " " repeater
13060 (substring org-last-inserted-timestamp -1))))))
13061 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13063 (defun org-get-scheduled-time (pom &optional inherit)
13064 "Get the scheduled time as a time tuple, of a format suitable
13065 for calling org-schedule with, or if there is no scheduling,
13066 returns nil."
13067 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13068 (when time
13069 (apply 'encode-time (org-parse-time-string time)))))
13071 (defun org-get-deadline-time (pom &optional inherit)
13072 "Get the deadline as a time tuple, of a format suitable for
13073 calling org-deadline with, or if there is no scheduling, returns
13074 nil."
13075 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13076 (when time
13077 (apply 'encode-time (org-parse-time-string time)))))
13079 (defun org-remove-timestamp-with-keyword (keyword)
13080 "Remove all time stamps with KEYWORD in the current entry."
13081 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13082 beg)
13083 (save-excursion
13084 (org-back-to-heading t)
13085 (setq beg (point))
13086 (outline-next-heading)
13087 (while (re-search-backward re beg t)
13088 (replace-match "")
13089 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13090 (equal (char-before) ?\ ))
13091 (backward-delete-char 1)
13092 (if (string-match "^[ \t]*$" (buffer-substring
13093 (point-at-bol) (point-at-eol)))
13094 (delete-region (point-at-bol)
13095 (min (point-max) (1+ (point-at-eol))))))))))
13097 (defun org-add-planning-info (what &optional time &rest remove)
13098 "Insert new timestamp with keyword in the line directly after the headline.
13099 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13100 If non is given, the user is prompted for a date.
13101 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13102 be removed."
13103 (interactive)
13104 (let (org-time-was-given org-end-time-was-given ts
13105 end default-time default-input)
13107 (catch 'exit
13108 (when (and (memq what '(scheduled deadline))
13109 (or (not time)
13110 (and (stringp time)
13111 (string-match "^[-+]+[0-9]" time))))
13112 ;; Try to get a default date/time from existing timestamp
13113 (save-excursion
13114 (org-back-to-heading t)
13115 (setq end (save-excursion (outline-next-heading) (point)))
13116 (when (re-search-forward (if (eq what 'scheduled)
13117 org-scheduled-time-regexp
13118 org-deadline-time-regexp)
13119 end t)
13120 (setq ts (match-string 1)
13121 default-time
13122 (apply 'encode-time (org-parse-time-string ts))
13123 default-input (and ts (org-get-compact-tod ts))))))
13124 (when what
13125 (setq time
13126 (if (stringp time)
13127 ;; This is a string (relative or absolute), set proper date
13128 (apply 'encode-time
13129 (org-read-date-analyze
13130 time default-time (decode-time default-time)))
13131 ;; If necessary, get the time from the user
13132 (or time (org-read-date nil 'to-time nil nil
13133 default-time default-input)))))
13135 (when (and org-insert-labeled-timestamps-at-point
13136 (member what '(scheduled deadline)))
13137 (insert
13138 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13139 (org-insert-time-stamp time org-time-was-given
13140 nil nil nil (list org-end-time-was-given))
13141 (setq what nil))
13142 (save-excursion
13143 (save-restriction
13144 (let (col list elt ts buffer-invisibility-spec)
13145 (org-back-to-heading t)
13146 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13147 (goto-char (match-end 1))
13148 (setq col (current-column))
13149 (goto-char (match-end 0))
13150 (if (eobp) (insert "\n") (forward-char 1))
13151 (when (and (not what)
13152 (not (looking-at
13153 (concat "[ \t]*"
13154 org-keyword-time-not-clock-regexp))))
13155 ;; Nothing to add, nothing to remove...... :-)
13156 (throw 'exit nil))
13157 (if (and (not (looking-at org-outline-regexp))
13158 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13159 "[^\r\n]*"))
13160 (not (equal (match-string 1) org-clock-string)))
13161 (narrow-to-region (match-beginning 0) (match-end 0))
13162 (insert-before-markers "\n")
13163 (backward-char 1)
13164 (narrow-to-region (point) (point))
13165 (and org-adapt-indentation (org-indent-to-column col)))
13166 ;; Check if we have to remove something.
13167 (setq list (cons what remove))
13168 (while list
13169 (setq elt (pop list))
13170 (when (or (and (eq elt 'scheduled)
13171 (re-search-forward org-scheduled-time-regexp nil t))
13172 (and (eq elt 'deadline)
13173 (re-search-forward org-deadline-time-regexp nil t))
13174 (and (eq elt 'closed)
13175 (re-search-forward org-closed-time-regexp nil t)))
13176 (replace-match "")
13177 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13178 (and (looking-at "[ \t]+") (replace-match ""))
13179 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13180 (when what
13181 (insert
13182 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13183 (cond ((eq what 'scheduled) org-scheduled-string)
13184 ((eq what 'deadline) org-deadline-string)
13185 ((eq what 'closed) org-closed-string))
13186 " ")
13187 (setq ts (org-insert-time-stamp
13188 time
13189 (or org-time-was-given
13190 (and (eq what 'closed) org-log-done-with-time))
13191 (eq what 'closed)
13192 nil nil (list org-end-time-was-given)))
13193 (insert
13194 (if (not (or (bolp) (eq (char-before) ?\ )
13195 (memq (char-after) '(32 10))
13196 (eobp))) " " ""))
13197 (end-of-line 1))
13198 (goto-char (point-min))
13199 (widen)
13200 (if (and (looking-at "[ \t]*\n")
13201 (equal (char-before) ?\n))
13202 (delete-region (1- (point)) (point-at-eol)))
13203 ts))))))
13205 (defvar org-log-note-marker (make-marker))
13206 (defvar org-log-note-purpose nil)
13207 (defvar org-log-note-state nil)
13208 (defvar org-log-note-previous-state nil)
13209 (defvar org-log-note-how nil)
13210 (defvar org-log-note-extra nil)
13211 (defvar org-log-note-window-configuration nil)
13212 (defvar org-log-note-return-to (make-marker))
13213 (defvar org-log-note-effective-time nil
13214 "Remembered current time so that dynamically scoped
13215 `org-extend-today-until' affects tha timestamps in state change
13216 log")
13218 (defvar org-log-post-message nil
13219 "Message to be displayed after a log note has been stored.
13220 The auto-repeater uses this.")
13222 (defun org-add-note ()
13223 "Add a note to the current entry.
13224 This is done in the same way as adding a state change note."
13225 (interactive)
13226 (org-add-log-setup 'note nil nil 'findpos nil))
13228 (defvar org-property-end-re)
13229 (defun org-add-log-setup (&optional purpose state prev-state
13230 findpos how extra)
13231 "Set up the post command hook to take a note.
13232 If this is about to TODO state change, the new state is expected in STATE.
13233 When FINDPOS is non-nil, find the correct position for the note in
13234 the current entry. If not, assume that it can be inserted at point.
13235 HOW is an indicator what kind of note should be created.
13236 EXTRA is additional text that will be inserted into the notes buffer."
13237 (let* ((org-log-into-drawer (org-log-into-drawer))
13238 (drawer (cond ((stringp org-log-into-drawer)
13239 org-log-into-drawer)
13240 (org-log-into-drawer "LOGBOOK"))))
13241 (save-restriction
13242 (save-excursion
13243 (when findpos
13244 (org-back-to-heading t)
13245 (narrow-to-region (point) (save-excursion
13246 (outline-next-heading) (point)))
13247 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13248 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13249 "[^\r\n]*\\)?"))
13250 (goto-char (match-end 0))
13251 (cond
13252 (drawer
13253 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13254 nil t)
13255 (progn
13256 (goto-char (match-end 0))
13257 (or org-log-states-order-reversed
13258 (and (re-search-forward org-property-end-re nil t)
13259 (goto-char (1- (match-beginning 0))))))
13260 (insert "\n:" drawer ":\n:END:")
13261 (beginning-of-line 0)
13262 (org-indent-line)
13263 (beginning-of-line 2)
13264 (org-indent-line)
13265 (end-of-line 0)))
13266 ((and org-log-state-notes-insert-after-drawers
13267 (save-excursion
13268 (forward-line) (looking-at org-drawer-regexp)))
13269 (forward-line)
13270 (while (looking-at org-drawer-regexp)
13271 (goto-char (match-end 0))
13272 (re-search-forward org-property-end-re (point-max) t)
13273 (forward-line))
13274 (forward-line -1)))
13275 (unless org-log-states-order-reversed
13276 (and (= (char-after) ?\n) (forward-char 1))
13277 (org-skip-over-state-notes)
13278 (skip-chars-backward " \t\n\r")))
13279 (move-marker org-log-note-marker (point))
13280 (setq org-log-note-purpose purpose
13281 org-log-note-state state
13282 org-log-note-previous-state prev-state
13283 org-log-note-how how
13284 org-log-note-extra extra
13285 org-log-note-effective-time (org-current-effective-time))
13286 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13288 (defun org-skip-over-state-notes ()
13289 "Skip past the list of State notes in an entry."
13290 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13291 (when (ignore-errors (goto-char (org-in-item-p)))
13292 (let* ((struct (org-list-struct))
13293 (prevs (org-list-prevs-alist struct)))
13294 (while (looking-at "[ \t]*- State")
13295 (goto-char (or (org-list-get-next-item (point) struct prevs)
13296 (org-list-get-item-end (point) struct)))))))
13298 (defun org-add-log-note (&optional purpose)
13299 "Pop up a window for taking a note, and add this note later at point."
13300 (remove-hook 'post-command-hook 'org-add-log-note)
13301 (setq org-log-note-window-configuration (current-window-configuration))
13302 (delete-other-windows)
13303 (move-marker org-log-note-return-to (point))
13304 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13305 (goto-char org-log-note-marker)
13306 (org-switch-to-buffer-other-window "*Org Note*")
13307 (erase-buffer)
13308 (if (memq org-log-note-how '(time state))
13309 (let (current-prefix-arg) (org-store-log-note))
13310 (let ((org-inhibit-startup t)) (org-mode))
13311 (insert (format "# Insert note for %s.
13312 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13313 (cond
13314 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13315 ((eq org-log-note-purpose 'done) "closed todo item")
13316 ((eq org-log-note-purpose 'state)
13317 (format "state change from \"%s\" to \"%s\""
13318 (or org-log-note-previous-state "")
13319 (or org-log-note-state "")))
13320 ((eq org-log-note-purpose 'reschedule)
13321 "rescheduling")
13322 ((eq org-log-note-purpose 'delschedule)
13323 "no longer scheduled")
13324 ((eq org-log-note-purpose 'redeadline)
13325 "changing deadline")
13326 ((eq org-log-note-purpose 'deldeadline)
13327 "removing deadline")
13328 ((eq org-log-note-purpose 'refile)
13329 "refiling")
13330 ((eq org-log-note-purpose 'note)
13331 "this entry")
13332 (t (error "This should not happen")))))
13333 (if org-log-note-extra (insert org-log-note-extra))
13334 (org-set-local 'org-finish-function 'org-store-log-note)
13335 (run-hooks 'org-log-buffer-setup-hook)))
13337 (defvar org-note-abort nil) ; dynamically scoped
13338 (defun org-store-log-note ()
13339 "Finish taking a log note, and insert it to where it belongs."
13340 (let ((txt (buffer-string)))
13341 (kill-buffer (current-buffer))
13342 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13343 lines ind bul)
13344 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13345 (setq txt (replace-match "" t t txt)))
13346 (if (string-match "\\s-+\\'" txt)
13347 (setq txt (replace-match "" t t txt)))
13348 (setq lines (org-split-string txt "\n"))
13349 (when (and note (string-match "\\S-" note))
13350 (setq note
13351 (org-replace-escapes
13352 note
13353 (list (cons "%u" (user-login-name))
13354 (cons "%U" user-full-name)
13355 (cons "%t" (format-time-string
13356 (org-time-stamp-format 'long 'inactive)
13357 org-log-note-effective-time))
13358 (cons "%T" (format-time-string
13359 (org-time-stamp-format 'long nil)
13360 org-log-note-effective-time))
13361 (cons "%d" (format-time-string
13362 (org-time-stamp-format nil 'inactive)
13363 org-log-note-effective-time))
13364 (cons "%D" (format-time-string
13365 (org-time-stamp-format nil nil)
13366 org-log-note-effective-time))
13367 (cons "%s" (if org-log-note-state
13368 (concat "\"" org-log-note-state "\"")
13369 ""))
13370 (cons "%S" (if org-log-note-previous-state
13371 (concat "\"" org-log-note-previous-state "\"")
13372 "\"\"")))))
13373 (if lines (setq note (concat note " \\\\")))
13374 (push note lines))
13375 (when (or current-prefix-arg org-note-abort)
13376 (when org-log-into-drawer
13377 (org-remove-empty-drawer-at
13378 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13379 org-log-note-marker))
13380 (setq lines nil))
13381 (when lines
13382 (with-current-buffer (marker-buffer org-log-note-marker)
13383 (save-excursion
13384 (goto-char org-log-note-marker)
13385 (move-marker org-log-note-marker nil)
13386 (end-of-line 1)
13387 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13388 (setq ind (save-excursion
13389 (if (ignore-errors (goto-char (org-in-item-p)))
13390 (let ((struct (org-list-struct)))
13391 (org-list-get-ind
13392 (org-list-get-top-point struct) struct))
13393 (skip-chars-backward " \r\t\n")
13394 (cond
13395 ((and (org-at-heading-p)
13396 org-adapt-indentation)
13397 (1+ (org-current-level)))
13398 ((org-at-heading-p) 0)
13399 (t (org-get-indentation))))))
13400 (setq bul (org-list-bullet-string "-"))
13401 (org-indent-line-to ind)
13402 (insert bul (pop lines))
13403 (let ((ind-body (+ (length bul) ind)))
13404 (while lines
13405 (insert "\n")
13406 (org-indent-line-to ind-body)
13407 (insert (pop lines))))
13408 (message "Note stored")
13409 (org-back-to-heading t)
13410 (org-cycle-hide-drawers 'children))
13411 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13412 ;; from within `org-add-log-note' because `buffer-undo-list'
13413 ;; is then modified outside of `org-with-remote-undo'.
13414 (when (eq this-command 'org-agenda-todo)
13415 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13416 ;; Don't add undo information when called from `org-agenda-todo'
13417 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13418 (set-window-configuration org-log-note-window-configuration)
13419 (with-current-buffer (marker-buffer org-log-note-return-to)
13420 (goto-char org-log-note-return-to))
13421 (move-marker org-log-note-return-to nil)
13422 (and org-log-post-message (message "%s" org-log-post-message))))
13424 (defun org-remove-empty-drawer-at (drawer pos)
13425 "Remove an empty drawer DRAWER at position POS.
13426 POS may also be a marker."
13427 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13428 (save-excursion
13429 (save-restriction
13430 (widen)
13431 (goto-char pos)
13432 (if (org-in-regexp
13433 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13434 (replace-match ""))))))
13436 (defvar org-ts-type nil)
13437 (defun org-sparse-tree (&optional arg type)
13438 "Create a sparse tree, prompt for the details.
13439 This command can create sparse trees. You first need to select the type
13440 of match used to create the tree:
13442 t Show all TODO entries.
13443 T Show entries with a specific TODO keyword.
13444 m Show entries selected by a tags/property match.
13445 p Enter a property name and its value (both with completion on existing
13446 names/values) and show entries with that property.
13447 r Show entries matching a regular expression (`/' can be used as well).
13448 b Show deadlines and scheduled items before a date.
13449 a Show deadlines and scheduled items after a date.
13450 d Show deadlines due within `org-deadline-warning-days'.
13451 D Show deadlines and scheduled items between a date range."
13452 (interactive "P")
13453 (let (ans kwd value ts-type)
13454 (setq type (or type org-sparse-tree-default-date-type))
13455 (setq org-ts-type type)
13456 (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"
13457 (cond ((eq type 'all) "all timestamps")
13458 ((eq type 'scheduled) "only scheduled")
13459 ((eq type 'deadline) "only deadline")
13460 ((eq type 'active) "only active timestamps")
13461 ((eq type 'inactive) "only inactive timestamps")
13462 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13463 ((eq type 'closed) "with a closed time-stamp")
13464 (t "scheduled/deadline")))
13465 (setq ans (read-char-exclusive))
13466 (cond
13467 ((equal ans ?c)
13468 (org-sparse-tree
13469 arg (cadr (member type '(scheduled-or-deadline
13470 all scheduled deadline active inactive closed)))))
13471 ((equal ans ?d)
13472 (call-interactively 'org-check-deadlines))
13473 ((equal ans ?b)
13474 (call-interactively 'org-check-before-date))
13475 ((equal ans ?a)
13476 (call-interactively 'org-check-after-date))
13477 ((equal ans ?D)
13478 (call-interactively 'org-check-dates-range))
13479 ((equal ans ?t)
13480 (call-interactively 'org-show-todo-tree))
13481 ((equal ans ?T)
13482 (org-show-todo-tree '(4)))
13483 ((member ans '(?T ?m))
13484 (call-interactively 'org-match-sparse-tree))
13485 ((member ans '(?p ?P))
13486 (setq kwd (org-icompleting-read "Property: "
13487 (mapcar 'list (org-buffer-property-keys))))
13488 (setq value (org-icompleting-read "Value: "
13489 (mapcar 'list (org-property-values kwd))))
13490 (unless (string-match "\\`{.*}\\'" value)
13491 (setq value (concat "\"" value "\"")))
13492 (org-match-sparse-tree arg (concat kwd "=" value)))
13493 ((member ans '(?r ?R ?/))
13494 (call-interactively 'org-occur))
13495 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13497 (defvar org-occur-highlights nil
13498 "List of overlays used for occur matches.")
13499 (make-variable-buffer-local 'org-occur-highlights)
13500 (defvar org-occur-parameters nil
13501 "Parameters of the active org-occur calls.
13502 This is a list, each call to org-occur pushes as cons cell,
13503 containing the regular expression and the callback, onto the list.
13504 The list can contain several entries if `org-occur' has been called
13505 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13506 will only contain one set of parameters. When the highlights are
13507 removed (for example with `C-c C-c', or with the next edit (depending
13508 on `org-remove-highlights-with-change'), this variable is emptied
13509 as well.")
13510 (make-variable-buffer-local 'org-occur-parameters)
13512 (defun org-occur (regexp &optional keep-previous callback)
13513 "Make a compact tree which shows all matches of REGEXP.
13514 The tree will show the lines where the regexp matches, and all higher
13515 headlines above the match. It will also show the heading after the match,
13516 to make sure editing the matching entry is easy.
13517 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13518 call to `org-occur' will be kept, to allow stacking of calls to this
13519 command.
13520 If CALLBACK is non-nil, it is a function which is called to confirm
13521 that the match should indeed be shown."
13522 (interactive "sRegexp: \nP")
13523 (when (equal regexp "")
13524 (user-error "Regexp cannot be empty"))
13525 (unless keep-previous
13526 (org-remove-occur-highlights nil nil t))
13527 (push (cons regexp callback) org-occur-parameters)
13528 (let ((cnt 0))
13529 (save-excursion
13530 (goto-char (point-min))
13531 (if (or (not keep-previous) ; do not want to keep
13532 (not org-occur-highlights)) ; no previous matches
13533 ;; hide everything
13534 (org-overview))
13535 (while (re-search-forward regexp nil t)
13536 (when (or (not callback)
13537 (save-match-data (funcall callback)))
13538 (setq cnt (1+ cnt))
13539 (when org-highlight-sparse-tree-matches
13540 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13541 (org-show-context 'occur-tree))))
13542 (when org-remove-highlights-with-change
13543 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13544 nil 'local))
13545 (unless org-sparse-tree-open-archived-trees
13546 (org-hide-archived-subtrees (point-min) (point-max)))
13547 (run-hooks 'org-occur-hook)
13548 (if (org-called-interactively-p 'interactive)
13549 (message "%d match(es) for regexp %s" cnt regexp))
13550 cnt))
13552 (defun org-occur-next-match (&optional n reset)
13553 "Function for `next-error-function' to find sparse tree matches.
13554 N is the number of matches to move, when negative move backwards.
13555 RESET is entirely ignored - this function always goes back to the
13556 starting point when no match is found."
13557 (let* ((limit (if (< n 0) (point-min) (point-max)))
13558 (search-func (if (< n 0)
13559 'previous-single-char-property-change
13560 'next-single-char-property-change))
13561 (n (abs n))
13562 (pos (point))
13564 (catch 'exit
13565 (while (setq p1 (funcall search-func (point) 'org-type))
13566 (when (equal p1 limit)
13567 (goto-char pos)
13568 (error "No more matches"))
13569 (when (equal (get-char-property p1 'org-type) 'org-occur)
13570 (setq n (1- n))
13571 (when (= n 0)
13572 (goto-char p1)
13573 (throw 'exit (point))))
13574 (goto-char p1))
13575 (goto-char p1)
13576 (error "No more matches"))))
13578 (defun org-show-context (&optional key)
13579 "Make sure point and context are visible.
13580 How much context is shown depends upon the variables
13581 `org-show-hierarchy-above', `org-show-following-heading',
13582 `org-show-entry-below' and `org-show-siblings'."
13583 (let ((heading-p (org-at-heading-p t))
13584 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13585 (following-p (org-get-alist-option org-show-following-heading key))
13586 (entry-p (org-get-alist-option org-show-entry-below key))
13587 (siblings-p (org-get-alist-option org-show-siblings key)))
13588 ;; Show heading or entry text
13589 (if (and heading-p (not entry-p))
13590 (org-flag-heading nil) ; only show the heading
13591 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13592 (org-show-hidden-entry))) ; show entire entry
13593 (when following-p
13594 ;; Show next sibling, or heading below text
13595 (save-excursion
13596 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13597 (org-flag-heading nil))))
13598 (when siblings-p (org-show-siblings))
13599 (when hierarchy-p
13600 ;; show all higher headings, possibly with siblings
13601 (save-excursion
13602 (while (and (condition-case nil
13603 (progn (org-up-heading-all 1) t)
13604 (error nil))
13605 (not (bobp)))
13606 (org-flag-heading nil)
13607 (when siblings-p (org-show-siblings)))))
13608 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13610 (defvar org-reveal-start-hook nil
13611 "Hook run before revealing a location.")
13613 (defun org-reveal (&optional siblings)
13614 "Show current entry, hierarchy above it, and the following headline.
13615 This can be used to show a consistent set of context around locations
13616 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13617 not t for the search context.
13619 With optional argument SIBLINGS, on each level of the hierarchy all
13620 siblings are shown. This repairs the tree structure to what it would
13621 look like when opened with hierarchical calls to `org-cycle'.
13622 With double optional argument \\[universal-argument] \\[universal-argument], \
13623 go to the parent and show the
13624 entire tree."
13625 (interactive "P")
13626 (run-hooks 'org-reveal-start-hook)
13627 (let ((org-show-hierarchy-above t)
13628 (org-show-following-heading t)
13629 (org-show-siblings (if siblings t org-show-siblings)))
13630 (org-show-context nil))
13631 (when (equal siblings '(16))
13632 (save-excursion
13633 (when (org-up-heading-safe)
13634 (org-show-subtree)
13635 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13637 (defun org-highlight-new-match (beg end)
13638 "Highlight from BEG to END and mark the highlight is an occur headline."
13639 (let ((ov (make-overlay beg end)))
13640 (overlay-put ov 'face 'secondary-selection)
13641 (overlay-put ov 'org-type 'org-occur)
13642 (push ov org-occur-highlights)))
13644 (defun org-remove-occur-highlights (&optional beg end noremove)
13645 "Remove the occur highlights from the buffer.
13646 BEG and END are ignored. If NOREMOVE is nil, remove this function
13647 from the `before-change-functions' in the current buffer."
13648 (interactive)
13649 (unless org-inhibit-highlight-removal
13650 (mapc 'delete-overlay org-occur-highlights)
13651 (setq org-occur-highlights nil)
13652 (setq org-occur-parameters nil)
13653 (unless noremove
13654 (remove-hook 'before-change-functions
13655 'org-remove-occur-highlights 'local))))
13657 ;;;; Priorities
13659 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13660 "Regular expression matching the priority indicator.")
13662 (defvar org-remove-priority-next-time nil)
13664 (defun org-priority-up ()
13665 "Increase the priority of the current item."
13666 (interactive)
13667 (org-priority 'up))
13669 (defun org-priority-down ()
13670 "Decrease the priority of the current item."
13671 (interactive)
13672 (org-priority 'down))
13674 (defun org-priority (&optional action show)
13675 "Change the priority of an item.
13676 ACTION can be `set', `up', `down', or a character."
13677 (interactive "P")
13678 (if (equal action '(4))
13679 (org-show-priority)
13680 (unless org-enable-priority-commands
13681 (user-error "Priority commands are disabled"))
13682 (setq action (or action 'set))
13683 (let (current new news have remove)
13684 (save-excursion
13685 (org-back-to-heading t)
13686 (if (looking-at org-priority-regexp)
13687 (setq current (string-to-char (match-string 2))
13688 have t))
13689 (cond
13690 ((eq action 'remove)
13691 (setq remove t new ?\ ))
13692 ((or (eq action 'set)
13693 (if (featurep 'xemacs) (characterp action) (integerp action)))
13694 (if (not (eq action 'set))
13695 (setq new action)
13696 (message "Priority %c-%c, SPC to remove: "
13697 org-highest-priority org-lowest-priority)
13698 (save-match-data
13699 (setq new (read-char-exclusive))))
13700 (if (and (= (upcase org-highest-priority) org-highest-priority)
13701 (= (upcase org-lowest-priority) org-lowest-priority))
13702 (setq new (upcase new)))
13703 (cond ((equal new ?\ ) (setq remove t))
13704 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13705 (user-error "Priority must be between `%c' and `%c'"
13706 org-highest-priority org-lowest-priority))))
13707 ((eq action 'up)
13708 (setq new (if have
13709 (1- current) ; normal cycling
13710 ;; last priority was empty
13711 (if (eq last-command this-command)
13712 org-lowest-priority ; wrap around empty to lowest
13713 ;; default
13714 (if org-priority-start-cycle-with-default
13715 org-default-priority
13716 (1- org-default-priority))))))
13717 ((eq action 'down)
13718 (setq new (if have
13719 (1+ current) ; normal cycling
13720 ;; last priority was empty
13721 (if (eq last-command this-command)
13722 org-highest-priority ; wrap around empty to highest
13723 ;; default
13724 (if org-priority-start-cycle-with-default
13725 org-default-priority
13726 (1+ org-default-priority))))))
13727 (t (user-error "Invalid action")))
13728 (if (or (< (upcase new) org-highest-priority)
13729 (> (upcase new) org-lowest-priority))
13730 (if (and (memq action '(up down))
13731 (not have) (not (eq last-command this-command)))
13732 ;; `new' is from default priority
13733 (error
13734 "The default can not be set, see `org-default-priority' why")
13735 ;; normal cycling: `new' is beyond highest/lowest priority
13736 ;; and is wrapped around to the empty priority
13737 (setq remove t)))
13738 (setq news (format "%c" new))
13739 (if have
13740 (if remove
13741 (replace-match "" t t nil 1)
13742 (replace-match news t t nil 2))
13743 (if remove
13744 (user-error "No priority cookie found in line")
13745 (let ((case-fold-search nil))
13746 (looking-at org-todo-line-regexp))
13747 (if (match-end 2)
13748 (progn
13749 (goto-char (match-end 2))
13750 (insert " [#" news "]"))
13751 (goto-char (match-beginning 3))
13752 (insert "[#" news "] "))))
13753 (org-preserve-lc (org-set-tags nil 'align)))
13754 (if remove
13755 (message "Priority removed")
13756 (message "Priority of current item set to %s" news)))))
13758 (defun org-show-priority ()
13759 "Show the priority of the current item.
13760 This priority is composed of the main priority given with the [#A] cookies,
13761 and by additional input from the age of a schedules or deadline entry."
13762 (interactive)
13763 (let ((pri (if (eq major-mode 'org-agenda-mode)
13764 (org-get-at-bol 'priority)
13765 (save-excursion
13766 (save-match-data
13767 (beginning-of-line)
13768 (and (looking-at org-heading-regexp)
13769 (org-get-priority (match-string 0))))))))
13770 (message "Priority is %d" (if pri pri -1000))))
13772 (defun org-get-priority (s)
13773 "Find priority cookie and return priority."
13774 (save-match-data
13775 (if (functionp org-get-priority-function)
13776 (funcall org-get-priority-function)
13777 (if (not (string-match org-priority-regexp s))
13778 (* 1000 (- org-lowest-priority org-default-priority))
13779 (* 1000 (- org-lowest-priority
13780 (string-to-char (match-string 2 s))))))))
13782 ;;;; Tags
13784 (defvar org-agenda-archives-mode)
13785 (defvar org-map-continue-from nil
13786 "Position from where mapping should continue.
13787 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13789 (defvar org-scanner-tags nil
13790 "The current tag list while the tags scanner is running.")
13791 (defvar org-trust-scanner-tags nil
13792 "Should `org-get-tags-at' use the tags for the scanner.
13793 This is for internal dynamical scoping only.
13794 When this is non-nil, the function `org-get-tags-at' will return the value
13795 of `org-scanner-tags' instead of building the list by itself. This
13796 can lead to large speed-ups when the tags scanner is used in a file with
13797 many entries, and when the list of tags is retrieved, for example to
13798 obtain a list of properties. Building the tags list for each entry in such
13799 a file becomes an N^2 operation - but with this variable set, it scales
13800 as N.")
13802 (defun org-scan-tags (action matcher todo-only &optional start-level)
13803 "Sca headline tags with inheritance and produce output ACTION.
13805 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13806 or `agenda' to produce an entry list for an agenda view. It can also be
13807 a Lisp form or a function that should be called at each matched headline, in
13808 this case the return value is a list of all return values from these calls.
13810 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13811 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13812 only lines with a not-done TODO keyword are included in the output.
13813 This should be the same variable that was scoped into
13814 and set by `org-make-tags-matcher' when it constructed MATCHER.
13816 START-LEVEL can be a string with asterisks, reducing the scope to
13817 headlines matching this string."
13818 (require 'org-agenda)
13819 (let* ((re (concat "^"
13820 (if start-level
13821 ;; Get the correct level to match
13822 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13823 org-outline-regexp)
13824 " *\\(\\<\\("
13825 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13826 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13827 (props (list 'face 'default
13828 'done-face 'org-agenda-done
13829 'undone-face 'default
13830 'mouse-face 'highlight
13831 'org-not-done-regexp org-not-done-regexp
13832 'org-todo-regexp org-todo-regexp
13833 'org-complex-heading-regexp org-complex-heading-regexp
13834 'help-echo
13835 (format "mouse-2 or RET jump to org file %s"
13836 (abbreviate-file-name
13837 (or (buffer-file-name (buffer-base-buffer))
13838 (buffer-name (buffer-base-buffer)))))))
13839 (org-map-continue-from nil)
13840 lspos tags tags-list
13841 (tags-alist (list (cons 0 org-file-tags)))
13842 (llast 0) rtn rtn1 level category i txt
13843 todo marker entry priority)
13844 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13845 (setq action (list 'lambda nil action)))
13846 (save-excursion
13847 (goto-char (point-min))
13848 (when (eq action 'sparse-tree)
13849 (org-overview)
13850 (org-remove-occur-highlights))
13851 (while (let (case-fold-search)
13852 (re-search-forward re nil t))
13853 (setq org-map-continue-from nil)
13854 (catch :skip
13855 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13856 tags (if (match-end 4) (org-match-string-no-properties 4)))
13857 (goto-char (setq lspos (match-beginning 0)))
13858 (setq level (org-reduced-level (org-outline-level))
13859 category (org-get-category))
13860 (setq i llast llast level)
13861 ;; remove tag lists from same and sublevels
13862 (while (>= i level)
13863 (when (setq entry (assoc i tags-alist))
13864 (setq tags-alist (delete entry tags-alist)))
13865 (setq i (1- i)))
13866 ;; add the next tags
13867 (when tags
13868 (setq tags (org-split-string tags ":")
13869 tags-alist
13870 (cons (cons level tags) tags-alist)))
13871 ;; compile tags for current headline
13872 (setq tags-list
13873 (if org-use-tag-inheritance
13874 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13875 tags)
13876 org-scanner-tags tags-list)
13877 (when org-use-tag-inheritance
13878 (setcdr (car tags-alist)
13879 (mapcar (lambda (x)
13880 (setq x (copy-sequence x))
13881 (org-add-prop-inherited x))
13882 (cdar tags-alist))))
13883 (when (and tags org-use-tag-inheritance
13884 (or (not (eq t org-use-tag-inheritance))
13885 org-tags-exclude-from-inheritance))
13886 ;; selective inheritance, remove uninherited ones
13887 (setcdr (car tags-alist)
13888 (org-remove-uninherited-tags (cdar tags-alist))))
13889 (when (and
13891 ;; eval matcher only when the todo condition is OK
13892 (and (or (not todo-only) (member todo org-not-done-keywords))
13893 (let ((case-fold-search t) (org-trust-scanner-tags t))
13894 (eval matcher)))
13896 ;; Call the skipper, but return t if it does not skip,
13897 ;; so that the `and' form continues evaluating
13898 (progn
13899 (unless (eq action 'sparse-tree) (org-agenda-skip))
13902 ;; Check if timestamps are deselecting this entry
13903 (or (not todo-only)
13904 (and (member todo org-not-done-keywords)
13905 (or (not org-agenda-tags-todo-honor-ignore-options)
13906 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13908 ;; select this headline
13909 (cond
13910 ((eq action 'sparse-tree)
13911 (and org-highlight-sparse-tree-matches
13912 (org-get-heading) (match-end 0)
13913 (org-highlight-new-match
13914 (match-beginning 1) (match-end 1)))
13915 (org-show-context 'tags-tree))
13916 ((eq action 'agenda)
13917 (setq txt (org-agenda-format-item
13919 (concat
13920 (if (eq org-tags-match-list-sublevels 'indented)
13921 (make-string (1- level) ?.) "")
13922 (org-get-heading))
13923 level category
13924 tags-list)
13925 priority (org-get-priority txt))
13926 (goto-char lspos)
13927 (setq marker (org-agenda-new-marker))
13928 (org-add-props txt props
13929 'org-marker marker 'org-hd-marker marker 'org-category category
13930 'todo-state todo
13931 'priority priority 'type "tagsmatch")
13932 (push txt rtn))
13933 ((functionp action)
13934 (setq org-map-continue-from nil)
13935 (save-excursion
13936 (setq rtn1 (funcall action))
13937 (push rtn1 rtn)))
13938 (t (user-error "Invalid action")))
13940 ;; if we are to skip sublevels, jump to end of subtree
13941 (unless org-tags-match-list-sublevels
13942 (org-end-of-subtree t)
13943 (backward-char 1))))
13944 ;; Get the correct position from where to continue
13945 (if org-map-continue-from
13946 (goto-char org-map-continue-from)
13947 (and (= (point) lspos) (end-of-line 1)))))
13948 (when (and (eq action 'sparse-tree)
13949 (not org-sparse-tree-open-archived-trees))
13950 (org-hide-archived-subtrees (point-min) (point-max)))
13951 (nreverse rtn)))
13953 (defun org-remove-uninherited-tags (tags)
13954 "Remove all tags that are not inherited from the list TAGS."
13955 (cond
13956 ((eq org-use-tag-inheritance t)
13957 (if org-tags-exclude-from-inheritance
13958 (org-delete-all org-tags-exclude-from-inheritance tags)
13959 tags))
13960 ((not org-use-tag-inheritance) nil)
13961 ((stringp org-use-tag-inheritance)
13962 (delq nil (mapcar
13963 (lambda (x)
13964 (if (and (string-match org-use-tag-inheritance x)
13965 (not (member x org-tags-exclude-from-inheritance)))
13966 x nil))
13967 tags)))
13968 ((listp org-use-tag-inheritance)
13969 (delq nil (mapcar
13970 (lambda (x)
13971 (if (member x org-use-tag-inheritance) x nil))
13972 tags)))))
13974 (defun org-match-sparse-tree (&optional todo-only match)
13975 "Create a sparse tree according to tags string MATCH.
13976 MATCH can contain positive and negative selection of tags, like
13977 \"+WORK+URGENT-WITHBOSS\".
13978 If optional argument TODO-ONLY is non-nil, only select lines that are
13979 also TODO lines."
13980 (interactive "P")
13981 (org-agenda-prepare-buffers (list (current-buffer)))
13982 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13984 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13986 (defvar org-cached-props nil)
13987 (defun org-cached-entry-get (pom property)
13988 (if (or (eq t org-use-property-inheritance)
13989 (and (stringp org-use-property-inheritance)
13990 (string-match org-use-property-inheritance property))
13991 (and (listp org-use-property-inheritance)
13992 (member property org-use-property-inheritance)))
13993 ;; Caching is not possible, check it directly
13994 (org-entry-get pom property 'inherit)
13995 ;; Get all properties, so that we can do complicated checks easily
13996 (cdr (assoc property (or org-cached-props
13997 (setq org-cached-props
13998 (org-entry-properties pom)))))))
14000 (defun org-global-tags-completion-table (&optional files)
14001 "Return the list of all tags in all agenda buffer/files.
14002 Optional FILES argument is a list of files which can be used
14003 instead of the agenda files."
14004 (save-excursion
14005 (org-uniquify
14006 (delq nil
14007 (apply 'append
14008 (mapcar
14009 (lambda (file)
14010 (set-buffer (find-file-noselect file))
14011 (append (org-get-buffer-tags)
14012 (mapcar (lambda (x) (if (stringp (car-safe x))
14013 (list (car-safe x)) nil))
14014 org-tag-alist)))
14015 (if (and files (car files))
14016 files
14017 (org-agenda-files))))))))
14019 (defun org-make-tags-matcher (match)
14020 "Create the TAGS/TODO matcher form for the selection string MATCH.
14022 The variable `todo-only' is scoped dynamically into this function.
14023 It will be set to t if the matcher restricts matching to TODO entries,
14024 otherwise will not be touched.
14026 Returns a cons of the selection string MATCH and the constructed
14027 lisp form implementing the matcher. The matcher is to be evaluated
14028 at an Org entry, with point on the headline, and returns t if the
14029 entry matches the selection string MATCH. The returned lisp form
14030 references two variables with information about the entry, which
14031 must be bound around the form's evaluation: todo, the TODO keyword
14032 at the entry (or nil of none); and tags-list, the list of all tags
14033 at the entry including inherited ones. Additionally, the category
14034 of the entry (if any) must be specified as the text property
14035 'org-category on the headline.
14037 See also `org-scan-tags'.
14039 (declare (special todo-only))
14040 (unless (boundp 'todo-only)
14041 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14042 (unless match
14043 ;; Get a new match request, with completion against the global
14044 ;; tags table and the local tags in current buffer
14045 (let ((org-last-tags-completion-table
14046 (org-uniquify
14047 (delq nil (append (org-get-buffer-tags)
14048 (org-global-tags-completion-table))))))
14049 (setq match (org-completing-read-no-i
14050 "Match: " 'org-tags-completion-function nil nil nil
14051 'org-tags-history))))
14053 ;; Parse the string and create a lisp form
14054 (let ((match0 match)
14055 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14056 minus tag mm
14057 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14058 orterms term orlist re-p str-p level-p level-op time-p
14059 prop-p pn pv po gv rest (start 0) (ss 0))
14060 ;; Expand group tags
14061 (setq match (org-tags-expand match))
14063 ;; Check if there is a TODO part of this match, which would be the
14064 ;; part after a "/". TO make sure that this slash is not part of
14065 ;; a property value to be matched against, we also check that there
14066 ;; is no " after that slash.
14067 ;; First, find the last slash
14068 (while (string-match "/+" match ss)
14069 (setq start (match-beginning 0) ss (match-end 0)))
14070 (if (and (string-match "/+" match start)
14071 (not (save-match-data (string-match "\"" match start))))
14072 ;; match contains also a todo-matching request
14073 (progn
14074 (setq tagsmatch (substring match 0 (match-beginning 0))
14075 todomatch (substring match (match-end 0)))
14076 (if (string-match "^!" todomatch)
14077 (setq todo-only t todomatch (substring todomatch 1)))
14078 (if (string-match "^\\s-*$" todomatch)
14079 (setq todomatch nil)))
14080 ;; only matching tags
14081 (setq tagsmatch match todomatch nil))
14083 ;; Make the tags matcher
14084 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14085 (setq tagsmatcher t)
14086 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14087 (while (setq term (pop orterms))
14088 (while (and (equal (substring term -1) "\\") orterms)
14089 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14090 (while (string-match re term)
14091 (setq rest (substring term (match-end 0))
14092 minus (and (match-end 1)
14093 (equal (match-string 1 term) "-"))
14094 tag (save-match-data (replace-regexp-in-string
14095 "\\\\-" "-"
14096 (match-string 2 term)))
14097 re-p (equal (string-to-char tag) ?{)
14098 level-p (match-end 4)
14099 prop-p (match-end 5)
14100 mm (cond
14101 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14102 (level-p
14103 (setq level-op (org-op-to-function (match-string 3 term)))
14104 `(,level-op level ,(string-to-number
14105 (match-string 4 term))))
14106 (prop-p
14107 (setq pn (match-string 5 term)
14108 po (match-string 6 term)
14109 pv (match-string 7 term)
14110 re-p (equal (string-to-char pv) ?{)
14111 str-p (equal (string-to-char pv) ?\")
14112 time-p (save-match-data
14113 (string-match "^\"[[<].*[]>]\"$" pv))
14114 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14115 (if time-p (setq pv (org-matcher-time pv)))
14116 (setq po (org-op-to-function po (if time-p 'time str-p)))
14117 (cond
14118 ((equal pn "CATEGORY")
14119 (setq gv '(get-text-property (point) 'org-category)))
14120 ((equal pn "TODO")
14121 (setq gv 'todo))
14123 (setq gv `(org-cached-entry-get nil ,pn))))
14124 (if re-p
14125 (if (eq po 'org<>)
14126 `(not (string-match ,pv (or ,gv "")))
14127 `(string-match ,pv (or ,gv "")))
14128 (if str-p
14129 `(,po (or ,gv "") ,pv)
14130 `(,po (string-to-number (or ,gv ""))
14131 ,(string-to-number pv) ))))
14132 (t `(member ,tag tags-list)))
14133 mm (if minus (list 'not mm) mm)
14134 term rest)
14135 (push mm tagsmatcher))
14136 (push (if (> (length tagsmatcher) 1)
14137 (cons 'and tagsmatcher)
14138 (car tagsmatcher))
14139 orlist)
14140 (setq tagsmatcher nil))
14141 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14142 (setq tagsmatcher
14143 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14144 ;; Make the todo matcher
14145 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14146 (setq todomatcher t)
14147 (setq orterms (org-split-string todomatch "|") orlist nil)
14148 (while (setq term (pop orterms))
14149 (while (string-match re term)
14150 (setq minus (and (match-end 1)
14151 (equal (match-string 1 term) "-"))
14152 kwd (match-string 2 term)
14153 re-p (equal (string-to-char kwd) ?{)
14154 term (substring term (match-end 0))
14155 mm (if re-p
14156 `(string-match ,(substring kwd 1 -1) todo)
14157 (list 'equal 'todo kwd))
14158 mm (if minus (list 'not mm) mm))
14159 (push mm todomatcher))
14160 (push (if (> (length todomatcher) 1)
14161 (cons 'and todomatcher)
14162 (car todomatcher))
14163 orlist)
14164 (setq todomatcher nil))
14165 (setq todomatcher (if (> (length orlist) 1)
14166 (cons 'or orlist) (car orlist))))
14168 ;; Return the string and lisp forms of the matcher
14169 (setq matcher (if todomatcher
14170 (list 'and tagsmatcher todomatcher)
14171 tagsmatcher))
14172 (when todo-only
14173 (setq matcher (list 'and '(member todo org-not-done-keywords)
14174 matcher)))
14175 (cons match0 matcher)))
14177 (defun org-tags-expand (match &optional single-as-list downcased)
14178 "Expand group tags in MATCH.
14180 This replaces every group tag in MATCH with a regexp tag search.
14181 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14182 will be replaced like this:
14184 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14185 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14186 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14188 Replacing by a regexp preserves the structure of the match.
14189 E.g., this expansion
14191 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14193 will match anything tagged with \"Lab\" and \"Home\", or tagged
14194 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14196 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14197 assumed to be a single group tag, and the function will return
14198 the list of tags in this group.
14200 When DOWNCASE is non-nil, expand downcased TAGS."
14201 (if org-group-tags
14202 (let* ((case-fold-search t)
14203 (stable org-mode-syntax-table)
14204 (tal (or org-tag-groups-alist-for-agenda
14205 org-tag-groups-alist))
14206 (tal (if downcased
14207 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14208 (tml (mapcar 'car tal))
14209 (rtnmatch match) rpl)
14210 ;; @ and _ are allowed as word-components in tags
14211 (modify-syntax-entry ?@ "w" stable)
14212 (modify-syntax-entry ?_ "w" stable)
14213 (while (and tml
14214 (with-syntax-table stable
14215 (string-match
14216 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14217 (regexp-opt tml) "\\>\\)") rtnmatch)))
14218 (let* ((dir (match-string 1 rtnmatch))
14219 (tag (match-string 2 rtnmatch))
14220 (tag (if downcased (downcase tag) tag)))
14221 (setq tml (delete tag tml))
14222 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14223 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14224 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14225 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14226 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14227 (if single-as-list
14228 (or (reverse rpl) (list rtnmatch))
14229 rtnmatch))
14230 (if single-as-list (list (if downcased (downcase match) match))
14231 match)))
14233 (defun org-op-to-function (op &optional stringp)
14234 "Turn an operator into the appropriate function."
14235 (setq op
14236 (cond
14237 ((equal op "<" ) '(< string< org-time<))
14238 ((equal op ">" ) '(> org-string> org-time>))
14239 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14240 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14241 ((member op '("=" "==")) '(= string= org-time=))
14242 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14243 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14245 (defun org<> (a b) (not (= a b)))
14246 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14247 (defun org-string>= (a b) (not (string< a b)))
14248 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14249 (defun org-string<> (a b) (not (string= a b)))
14250 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14251 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14252 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14253 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14254 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14255 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14256 (defun org-2ft (s)
14257 "Convert S to a floating point time.
14258 If S is already a number, just return it. If it is a string, parse
14259 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14260 (cond
14261 ((numberp s) s)
14262 ((stringp s)
14263 (condition-case nil
14264 (float-time (apply 'encode-time (org-parse-time-string s)))
14265 (error 0.)))
14266 (t 0.)))
14268 (defun org-time-today ()
14269 "Time in seconds today at 0:00.
14270 Returns the float number of seconds since the beginning of the
14271 epoch to the beginning of today (00:00)."
14272 (float-time (apply 'encode-time
14273 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14275 (defun org-matcher-time (s)
14276 "Interpret a time comparison value."
14277 (save-match-data
14278 (cond
14279 ((string= s "<now>") (float-time))
14280 ((string= s "<today>") (org-time-today))
14281 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14282 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14283 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14284 (+ (org-time-today)
14285 (* (string-to-number (match-string 1 s))
14286 (cdr (assoc (match-string 2 s)
14287 '(("d" . 86400.0) ("w" . 604800.0)
14288 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14289 (t (org-2ft s)))))
14291 (defun org-match-any-p (re list)
14292 "Does re match any element of list?"
14293 (setq list (mapcar (lambda (x) (string-match re x)) list))
14294 (delq nil list))
14296 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14297 (defvar org-tags-overlay (make-overlay 1 1))
14298 (org-detach-overlay org-tags-overlay)
14300 (defun org-get-local-tags-at (&optional pos)
14301 "Get a list of tags defined in the current headline."
14302 (org-get-tags-at pos 'local))
14304 (defun org-get-local-tags ()
14305 "Get a list of tags defined in the current headline."
14306 (org-get-tags-at nil 'local))
14308 (defun org-get-tags-at (&optional pos local)
14309 "Get a list of all headline tags applicable at POS.
14310 POS defaults to point. If tags are inherited, the list contains
14311 the targets in the same sequence as the headlines appear, i.e.
14312 the tags of the current headline come last.
14313 When LOCAL is non-nil, only return tags from the current headline,
14314 ignore inherited ones."
14315 (interactive)
14316 (if (and org-trust-scanner-tags
14317 (or (not pos) (equal pos (point)))
14318 (not local))
14319 org-scanner-tags
14320 (let (tags ltags lastpos parent)
14321 (save-excursion
14322 (save-restriction
14323 (widen)
14324 (goto-char (or pos (point)))
14325 (save-match-data
14326 (catch 'done
14327 (condition-case nil
14328 (progn
14329 (org-back-to-heading t)
14330 (while (not (equal lastpos (point)))
14331 (setq lastpos (point))
14332 (when (looking-at
14333 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14334 (setq ltags (org-split-string
14335 (org-match-string-no-properties 1) ":"))
14336 (when parent
14337 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14338 (setq tags (append
14339 (if parent
14340 (org-remove-uninherited-tags ltags)
14341 ltags)
14342 tags)))
14343 (or org-use-tag-inheritance (throw 'done t))
14344 (if local (throw 'done t))
14345 (or (org-up-heading-safe) (error nil))
14346 (setq parent t)))
14347 (error nil)))))
14348 (if local
14349 tags
14350 (reverse (delete-dups
14351 (reverse (append
14352 (org-remove-uninherited-tags
14353 org-file-tags) tags)))))))))
14355 (defun org-add-prop-inherited (s)
14356 (add-text-properties 0 (length s) '(inherited t) s)
14359 (defun org-toggle-tag (tag &optional onoff)
14360 "Toggle the tag TAG for the current line.
14361 If ONOFF is `on' or `off', don't toggle but set to this state."
14362 (let (res current)
14363 (save-excursion
14364 (org-back-to-heading t)
14365 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14366 (point-at-eol) t)
14367 (progn
14368 (setq current (match-string 1))
14369 (replace-match ""))
14370 (setq current ""))
14371 (setq current (nreverse (org-split-string current ":")))
14372 (cond
14373 ((eq onoff 'on)
14374 (setq res t)
14375 (or (member tag current) (push tag current)))
14376 ((eq onoff 'off)
14377 (or (not (member tag current)) (setq current (delete tag current))))
14378 (t (if (member tag current)
14379 (setq current (delete tag current))
14380 (setq res t)
14381 (push tag current))))
14382 (end-of-line 1)
14383 (if current
14384 (progn
14385 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14386 (org-set-tags nil t))
14387 (delete-horizontal-space))
14388 (run-hooks 'org-after-tags-change-hook))
14389 res))
14391 (defun org-align-tags-here (to-col)
14392 ;; Assumes that this is a headline
14393 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14394 (beginning-of-line 1)
14395 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14396 (< pos (match-beginning 2)))
14397 (progn
14398 (setq tags-l (- (match-end 2) (match-beginning 2)))
14399 (goto-char (match-beginning 1))
14400 (insert " ")
14401 (delete-region (point) (1+ (match-beginning 2)))
14402 (setq ncol (max (current-column)
14403 (1+ col)
14404 (if (> to-col 0)
14405 to-col
14406 (- (abs to-col) tags-l))))
14407 (setq p (point))
14408 (insert (make-string (- ncol (current-column)) ?\ ))
14409 (setq ncol (current-column))
14410 (when indent-tabs-mode (tabify p (point-at-eol)))
14411 (org-move-to-column (min ncol col) t))
14412 (goto-char pos))))
14414 (defun org-set-tags-command (&optional arg just-align)
14415 "Call the set-tags command for the current entry."
14416 (interactive "P")
14417 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14418 (org-set-tags arg just-align)
14419 (save-excursion
14420 (unless (and (org-region-active-p)
14421 org-loop-over-headlines-in-active-region)
14422 (org-back-to-heading t))
14423 (org-set-tags arg just-align))))
14425 (defun org-set-tags-to (data)
14426 "Set the tags of the current entry to DATA, replacing the current tags.
14427 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14428 If DATA is nil or the empty string, any tags will be removed."
14429 (interactive "sTags: ")
14430 (setq data
14431 (cond
14432 ((eq data nil) "")
14433 ((equal data "") "")
14434 ((stringp data)
14435 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14436 ":"))
14437 ((listp data)
14438 (concat ":" (mapconcat 'identity data ":") ":"))))
14439 (when data
14440 (save-excursion
14441 (org-back-to-heading t)
14442 (when (looking-at org-complex-heading-regexp)
14443 (if (match-end 5)
14444 (progn
14445 (goto-char (match-beginning 5))
14446 (insert data)
14447 (delete-region (point) (point-at-eol))
14448 (org-set-tags nil 'align))
14449 (goto-char (point-at-eol))
14450 (insert " " data)
14451 (org-set-tags nil 'align)))
14452 (beginning-of-line 1)
14453 (if (looking-at ".*?\\([ \t]+\\)$")
14454 (delete-region (match-beginning 1) (match-end 1))))))
14456 (defun org-align-all-tags ()
14457 "Align the tags i all headings."
14458 (interactive)
14459 (save-excursion
14460 (or (ignore-errors (org-back-to-heading t))
14461 (outline-next-heading))
14462 (if (org-at-heading-p)
14463 (org-set-tags t)
14464 (message "No headings"))))
14466 (defvar org-indent-indentation-per-level)
14467 (defun org-set-tags (&optional arg just-align)
14468 "Set the tags for the current headline.
14469 With prefix ARG, realign all tags in headings in the current buffer."
14470 (interactive "P")
14471 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14472 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14473 'region-start-level 'region))
14474 org-loop-over-headlines-in-active-region)
14475 (org-map-entries
14476 ;; We don't use ARG and JUST-ALIGN here these args are not
14477 ;; useful when looping over headlines
14478 `(org-set-tags)
14479 org-loop-over-headlines-in-active-region
14480 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14481 (let* ((re org-outline-regexp-bol)
14482 (current (unless arg (org-get-tags-string)))
14483 (col (current-column))
14484 (org-setting-tags t)
14485 table current-tags inherited-tags ; computed below when needed
14486 tags p0 c0 c1 rpl di tc level)
14487 (if arg
14488 (save-excursion
14489 (goto-char (point-min))
14490 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14491 (while (re-search-forward re nil t)
14492 (org-set-tags nil t)
14493 (end-of-line 1)))
14494 (message "All tags realigned to column %d" org-tags-column))
14495 (if just-align
14496 (setq tags current)
14497 ;; Get a new set of tags from the user
14498 (save-excursion
14499 (setq table (append org-tag-persistent-alist
14500 (or org-tag-alist (org-get-buffer-tags))
14501 (and
14502 org-complete-tags-always-offer-all-agenda-tags
14503 (org-global-tags-completion-table
14504 (org-agenda-files))))
14505 org-last-tags-completion-table table
14506 current-tags (org-split-string current ":")
14507 inherited-tags (nreverse
14508 (nthcdr (length current-tags)
14509 (nreverse (org-get-tags-at))))
14510 tags
14511 (if (or (eq t org-use-fast-tag-selection)
14512 (and org-use-fast-tag-selection
14513 (delq nil (mapcar 'cdr table))))
14514 (org-fast-tag-selection
14515 current-tags inherited-tags table
14516 (if org-fast-tag-selection-include-todo
14517 org-todo-key-alist))
14518 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14519 (org-trim
14520 (org-icompleting-read "Tags: "
14521 'org-tags-completion-function
14522 nil nil current 'org-tags-history))))))
14523 (while (string-match "[-+&]+" tags)
14524 ;; No boolean logic, just a list
14525 (setq tags (replace-match ":" t t tags))))
14527 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14529 (if org-tags-sort-function
14530 (setq tags (mapconcat 'identity
14531 (sort (org-split-string
14532 tags (org-re "[^[:alnum:]_@#%]+"))
14533 org-tags-sort-function) ":")))
14535 (if (string-match "\\`[\t ]*\\'" tags)
14536 (setq tags "")
14537 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14538 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14540 ;; Insert new tags at the correct column
14541 (beginning-of-line 1)
14542 (setq level (or (and (looking-at org-outline-regexp)
14543 (- (match-end 0) (point) 1))
14545 (cond
14546 ((and (equal current "") (equal tags "")))
14547 ((re-search-forward
14548 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14549 (point-at-eol) t)
14550 (if (equal tags "")
14551 (setq rpl "")
14552 (goto-char (match-beginning 0))
14553 (setq c0 (current-column)
14554 ;; compute offset for the case of org-indent-mode active
14555 di (if org-indent-mode
14556 (* (1- org-indent-indentation-per-level) (1- level))
14558 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14559 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14560 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14561 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14562 (replace-match rpl t t)
14563 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14564 tags)
14565 (t (error "Tags alignment failed")))
14566 (org-move-to-column col)
14567 (unless just-align
14568 (run-hooks 'org-after-tags-change-hook))))))
14570 (defun org-change-tag-in-region (beg end tag off)
14571 "Add or remove TAG for each entry in the region.
14572 This works in the agenda, and also in an org-mode buffer."
14573 (interactive
14574 (list (region-beginning) (region-end)
14575 (let ((org-last-tags-completion-table
14576 (if (derived-mode-p 'org-mode)
14577 (org-uniquify
14578 (delq nil (append (org-get-buffer-tags)
14579 (org-global-tags-completion-table))))
14580 (org-global-tags-completion-table))))
14581 (org-icompleting-read
14582 "Tag: " 'org-tags-completion-function nil nil nil
14583 'org-tags-history))
14584 (progn
14585 (message "[s]et or [r]emove? ")
14586 (equal (read-char-exclusive) ?r))))
14587 (if (fboundp 'deactivate-mark) (deactivate-mark))
14588 (let ((agendap (equal major-mode 'org-agenda-mode))
14589 l1 l2 m buf pos newhead (cnt 0))
14590 (goto-char end)
14591 (setq l2 (1- (org-current-line)))
14592 (goto-char beg)
14593 (setq l1 (org-current-line))
14594 (loop for l from l1 to l2 do
14595 (org-goto-line l)
14596 (setq m (get-text-property (point) 'org-hd-marker))
14597 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14598 (and agendap m))
14599 (setq buf (if agendap (marker-buffer m) (current-buffer))
14600 pos (if agendap m (point)))
14601 (with-current-buffer buf
14602 (save-excursion
14603 (save-restriction
14604 (goto-char pos)
14605 (setq cnt (1+ cnt))
14606 (org-toggle-tag tag (if off 'off 'on))
14607 (setq newhead (org-get-heading)))))
14608 (and agendap (org-agenda-change-all-lines newhead m))))
14609 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14611 (defun org-tags-completion-function (string predicate &optional flag)
14612 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14613 (confirm (lambda (x) (stringp (car x)))))
14614 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14615 (setq s1 (match-string 1 string)
14616 s2 (match-string 2 string))
14617 (setq s1 "" s2 string))
14618 (cond
14619 ((eq flag nil)
14620 ;; try completion
14621 (setq rtn (try-completion s2 ctable confirm))
14622 (if (stringp rtn)
14623 (setq rtn
14624 (concat s1 s2 (substring rtn (length s2))
14625 (if (and org-add-colon-after-tag-completion
14626 (assoc rtn ctable))
14627 ":" ""))))
14628 rtn)
14629 ((eq flag t)
14630 ;; all-completions
14631 (all-completions s2 ctable confirm))
14632 ((eq flag 'lambda)
14633 ;; exact match?
14634 (assoc s2 ctable)))))
14636 (defun org-fast-tag-insert (kwd tags face &optional end)
14637 "Insert KDW, and the TAGS, the latter with face FACE.
14638 Also insert END."
14639 (insert (format "%-12s" (concat kwd ":"))
14640 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14641 (or end "")))
14643 (defun org-fast-tag-show-exit (flag)
14644 (save-excursion
14645 (org-goto-line 3)
14646 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14647 (replace-match ""))
14648 (when flag
14649 (end-of-line 1)
14650 (org-move-to-column (- (window-width) 19) t)
14651 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14653 (defun org-set-current-tags-overlay (current prefix)
14654 "Add an overlay to CURRENT tag with PREFIX."
14655 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14656 (if (featurep 'xemacs)
14657 (org-overlay-display org-tags-overlay (concat prefix s)
14658 'secondary-selection)
14659 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14660 (org-overlay-display org-tags-overlay (concat prefix s)))))
14662 (defvar org-last-tag-selection-key nil)
14663 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14664 "Fast tag selection with single keys.
14665 CURRENT is the current list of tags in the headline, INHERITED is the
14666 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14667 possibly with grouping information. TODO-TABLE is a similar table with
14668 TODO keywords, should these have keys assigned to them.
14669 If the keys are nil, a-z are automatically assigned.
14670 Returns the new tags string, or nil to not change the current settings."
14671 (let* ((fulltable (append table todo-table))
14672 (maxlen (apply 'max (mapcar
14673 (lambda (x)
14674 (if (stringp (car x)) (string-width (car x)) 0))
14675 fulltable)))
14676 (buf (current-buffer))
14677 (expert (eq org-fast-tag-selection-single-key 'expert))
14678 (buffer-tags nil)
14679 (fwidth (+ maxlen 3 1 3))
14680 (ncol (/ (- (window-width) 4) fwidth))
14681 (i-face 'org-done)
14682 (c-face 'org-todo)
14683 tg cnt e c char c1 c2 ntable tbl rtn
14684 ov-start ov-end ov-prefix
14685 (exit-after-next org-fast-tag-selection-single-key)
14686 (done-keywords org-done-keywords)
14687 groups ingroup)
14688 (save-excursion
14689 (beginning-of-line 1)
14690 (if (looking-at
14691 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14692 (setq ov-start (match-beginning 1)
14693 ov-end (match-end 1)
14694 ov-prefix "")
14695 (setq ov-start (1- (point-at-eol))
14696 ov-end (1+ ov-start))
14697 (skip-chars-forward "^\n\r")
14698 (setq ov-prefix
14699 (concat
14700 (buffer-substring (1- (point)) (point))
14701 (if (> (current-column) org-tags-column)
14703 (make-string (- org-tags-column (current-column)) ?\ ))))))
14704 (move-overlay org-tags-overlay ov-start ov-end)
14705 (save-window-excursion
14706 (if expert
14707 (set-buffer (get-buffer-create " *Org tags*"))
14708 (delete-other-windows)
14709 (split-window-vertically)
14710 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14711 (erase-buffer)
14712 (org-set-local 'org-done-keywords done-keywords)
14713 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14714 (org-fast-tag-insert "Current" current c-face "\n\n")
14715 (org-fast-tag-show-exit exit-after-next)
14716 (org-set-current-tags-overlay current ov-prefix)
14717 (setq tbl fulltable char ?a cnt 0)
14718 (while (setq e (pop tbl))
14719 (cond
14720 ((equal (car e) :startgroup)
14721 (push '() groups) (setq ingroup t)
14722 (when (not (= cnt 0))
14723 (setq cnt 0)
14724 (insert "\n"))
14725 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14726 ((equal (car e) :endgroup)
14727 (setq ingroup nil cnt 0)
14728 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14729 ((equal e '(:newline))
14730 (when (not (= cnt 0))
14731 (setq cnt 0)
14732 (insert "\n")
14733 (setq e (car tbl))
14734 (while (equal (car tbl) '(:newline))
14735 (insert "\n")
14736 (setq tbl (cdr tbl)))))
14737 ((equal e '(:grouptags)) nil)
14739 (setq tg (copy-sequence (car e)) c2 nil)
14740 (if (cdr e)
14741 (setq c (cdr e))
14742 ;; automatically assign a character.
14743 (setq c1 (string-to-char
14744 (downcase (substring
14745 tg (if (= (string-to-char tg) ?@) 1 0)))))
14746 (if (or (rassoc c1 ntable) (rassoc c1 table))
14747 (while (or (rassoc char ntable) (rassoc char table))
14748 (setq char (1+ char)))
14749 (setq c2 c1))
14750 (setq c (or c2 char)))
14751 (if ingroup (push tg (car groups)))
14752 (setq tg (org-add-props tg nil 'face
14753 (cond
14754 ((not (assoc tg table))
14755 (org-get-todo-face tg))
14756 ((member tg current) c-face)
14757 ((member tg inherited) i-face))))
14758 (if (equal (caar tbl) :grouptags)
14759 (org-add-props tg nil 'face 'org-tag-group))
14760 (if (and (= cnt 0) (not ingroup)) (insert " "))
14761 (insert "[" c "] " tg (make-string
14762 (- fwidth 4 (length tg)) ?\ ))
14763 (push (cons tg c) ntable)
14764 (when (= (setq cnt (1+ cnt)) ncol)
14765 (insert "\n")
14766 (if ingroup (insert " "))
14767 (setq cnt 0)))))
14768 (setq ntable (nreverse ntable))
14769 (insert "\n")
14770 (goto-char (point-min))
14771 (if (not expert) (org-fit-window-to-buffer))
14772 (setq rtn
14773 (catch 'exit
14774 (while t
14775 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14776 (if (not groups) "no " "")
14777 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14778 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14779 (setq org-last-tag-selection-key c)
14780 (cond
14781 ((= c ?\r) (throw 'exit t))
14782 ((= c ?!)
14783 (setq groups (not groups))
14784 (goto-char (point-min))
14785 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14786 ((= c ?\C-c)
14787 (if (not expert)
14788 (org-fast-tag-show-exit
14789 (setq exit-after-next (not exit-after-next)))
14790 (setq expert nil)
14791 (delete-other-windows)
14792 (set-window-buffer (split-window-vertically) " *Org tags*")
14793 (org-switch-to-buffer-other-window " *Org tags*")
14794 (org-fit-window-to-buffer)))
14795 ((or (= c ?\C-g)
14796 (and (= c ?q) (not (rassoc c ntable))))
14797 (org-detach-overlay org-tags-overlay)
14798 (setq quit-flag t))
14799 ((= c ?\ )
14800 (setq current nil)
14801 (if exit-after-next (setq exit-after-next 'now)))
14802 ((= c ?\t)
14803 (condition-case nil
14804 (setq tg (org-icompleting-read
14805 "Tag: "
14806 (or buffer-tags
14807 (with-current-buffer buf
14808 (org-get-buffer-tags)))))
14809 (quit (setq tg "")))
14810 (when (string-match "\\S-" tg)
14811 (add-to-list 'buffer-tags (list tg))
14812 (if (member tg current)
14813 (setq current (delete tg current))
14814 (push tg current)))
14815 (if exit-after-next (setq exit-after-next 'now)))
14816 ((setq e (rassoc c todo-table) tg (car e))
14817 (with-current-buffer buf
14818 (save-excursion (org-todo tg)))
14819 (if exit-after-next (setq exit-after-next 'now)))
14820 ((setq e (rassoc c ntable) tg (car e))
14821 (if (member tg current)
14822 (setq current (delete tg current))
14823 (loop for g in groups do
14824 (if (member tg g)
14825 (mapc (lambda (x)
14826 (setq current (delete x current)))
14827 g)))
14828 (push tg current))
14829 (if exit-after-next (setq exit-after-next 'now))))
14831 ;; Create a sorted list
14832 (setq current
14833 (sort current
14834 (lambda (a b)
14835 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14836 (if (eq exit-after-next 'now) (throw 'exit t))
14837 (goto-char (point-min))
14838 (beginning-of-line 2)
14839 (delete-region (point) (point-at-eol))
14840 (org-fast-tag-insert "Current" current c-face)
14841 (org-set-current-tags-overlay current ov-prefix)
14842 (while (re-search-forward
14843 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14844 (setq tg (match-string 1))
14845 (add-text-properties
14846 (match-beginning 1) (match-end 1)
14847 (list 'face
14848 (cond
14849 ((member tg current) c-face)
14850 ((member tg inherited) i-face)
14851 (t (get-text-property (match-beginning 1) 'face))))))
14852 (goto-char (point-min)))))
14853 (org-detach-overlay org-tags-overlay)
14854 (if rtn
14855 (mapconcat 'identity current ":")
14856 nil))))
14858 (defun org-get-tags-string ()
14859 "Get the TAGS string in the current headline."
14860 (unless (org-at-heading-p t)
14861 (user-error "Not on a heading"))
14862 (save-excursion
14863 (beginning-of-line 1)
14864 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14865 (org-match-string-no-properties 1)
14866 "")))
14868 (defun org-get-tags ()
14869 "Get the list of tags specified in the current headline."
14870 (org-split-string (org-get-tags-string) ":"))
14872 (defun org-get-buffer-tags ()
14873 "Get a table of all tags used in the buffer, for completion."
14874 (let (tags)
14875 (save-excursion
14876 (goto-char (point-min))
14877 (while (re-search-forward
14878 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14879 (when (equal (char-after (point-at-bol 0)) ?*)
14880 (mapc (lambda (x) (add-to-list 'tags x))
14881 (org-split-string (org-match-string-no-properties 1) ":")))))
14882 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14883 (mapcar 'list tags)))
14885 ;;;; The mapping API
14887 (defun org-map-entries (func &optional match scope &rest skip)
14888 "Call FUNC at each headline selected by MATCH in SCOPE.
14890 FUNC is a function or a lisp form. The function will be called without
14891 arguments, with the cursor positioned at the beginning of the headline.
14892 The return values of all calls to the function will be collected and
14893 returned as a list.
14895 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14896 does not need to preserve point. After evaluation, the cursor will be
14897 moved to the end of the line (presumably of the headline of the
14898 processed entry) and search continues from there. Under some
14899 circumstances, this may not produce the wanted results. For example,
14900 if you have removed (e.g. archived) the current (sub)tree it could
14901 mean that the next entry will be skipped entirely. In such cases, you
14902 can specify the position from where search should continue by making
14903 FUNC set the variable `org-map-continue-from' to the desired buffer
14904 position.
14906 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14907 Only headlines that are matched by this query will be considered during
14908 the iteration. When MATCH is nil or t, all headlines will be
14909 visited by the iteration.
14911 SCOPE determines the scope of this command. It can be any of:
14913 nil The current buffer, respecting the restriction if any
14914 tree The subtree started with the entry at point
14915 region The entries within the active region, if any
14916 region-start-level
14917 The entries within the active region, but only those at
14918 the same level than the first one.
14919 file The current buffer, without restriction
14920 file-with-archives
14921 The current buffer, and any archives associated with it
14922 agenda All agenda files
14923 agenda-with-archives
14924 All agenda files with any archive files associated with them
14925 \(file1 file2 ...)
14926 If this is a list, all files in the list will be scanned
14928 The remaining args are treated as settings for the skipping facilities of
14929 the scanner. The following items can be given here:
14931 archive skip trees with the archive tag
14932 comment skip trees with the COMMENT keyword
14933 function or Emacs Lisp form:
14934 will be used as value for `org-agenda-skip-function', so
14935 whenever the function returns a position, FUNC will not be
14936 called for that entry and search will continue from the
14937 position returned
14939 If your function needs to retrieve the tags including inherited tags
14940 at the *current* entry, you can use the value of the variable
14941 `org-scanner-tags' which will be much faster than getting the value
14942 with `org-get-tags-at'. If your function gets properties with
14943 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14944 to t around the call to `org-entry-properties' to get the same speedup.
14945 Note that if your function moves around to retrieve tags and properties at
14946 a *different* entry, you cannot use these techniques."
14947 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14948 (not (org-region-active-p)))
14949 (let* ((org-agenda-archives-mode nil) ; just to make sure
14950 (org-agenda-skip-archived-trees (memq 'archive skip))
14951 (org-agenda-skip-comment-trees (memq 'comment skip))
14952 (org-agenda-skip-function
14953 (car (org-delete-all '(comment archive) skip)))
14954 (org-tags-match-list-sublevels t)
14955 (start-level (eq scope 'region-start-level))
14956 matcher file res
14957 org-todo-keywords-for-agenda
14958 org-done-keywords-for-agenda
14959 org-todo-keyword-alist-for-agenda
14960 org-drawers-for-agenda
14961 org-tag-alist-for-agenda
14962 todo-only)
14964 (cond
14965 ((eq match t) (setq matcher t))
14966 ((eq match nil) (setq matcher t))
14967 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14969 (save-window-excursion
14970 (save-restriction
14971 (cond ((eq scope 'tree)
14972 (org-back-to-heading t)
14973 (org-narrow-to-subtree)
14974 (setq scope nil))
14975 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14976 (org-region-active-p))
14977 ;; If needed, set start-level to a string like "2"
14978 (when start-level
14979 (save-excursion
14980 (goto-char (region-beginning))
14981 (unless (org-at-heading-p) (outline-next-heading))
14982 (setq start-level (org-current-level))))
14983 (narrow-to-region (region-beginning)
14984 (save-excursion
14985 (goto-char (region-end))
14986 (unless (and (bolp) (org-at-heading-p))
14987 (outline-next-heading))
14988 (point)))
14989 (setq scope nil)))
14991 (if (not scope)
14992 (progn
14993 (org-agenda-prepare-buffers
14994 (list (buffer-file-name (current-buffer))))
14995 (setq res (org-scan-tags func matcher todo-only start-level)))
14996 ;; Get the right scope
14997 (cond
14998 ((and scope (listp scope) (symbolp (car scope)))
14999 (setq scope (eval scope)))
15000 ((eq scope 'agenda)
15001 (setq scope (org-agenda-files t)))
15002 ((eq scope 'agenda-with-archives)
15003 (setq scope (org-agenda-files t))
15004 (setq scope (org-add-archive-files scope)))
15005 ((eq scope 'file)
15006 (setq scope (list (buffer-file-name))))
15007 ((eq scope 'file-with-archives)
15008 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15009 (org-agenda-prepare-buffers scope)
15010 (while (setq file (pop scope))
15011 (with-current-buffer (org-find-base-buffer-visiting file)
15012 (save-excursion
15013 (save-restriction
15014 (widen)
15015 (goto-char (point-min))
15016 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15017 res)))
15019 ;;;; Properties
15021 ;;; Setting and retrieving properties
15023 (defconst org-special-properties
15024 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15025 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15026 "The special properties valid in Org-mode.
15028 These are properties that are not defined in the property drawer,
15029 but in some other way.")
15031 (defconst org-default-properties
15032 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15033 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15034 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15035 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15036 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15037 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15038 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15039 "Some properties that are used by Org-mode for various purposes.
15040 Being in this list makes sure that they are offered for completion.")
15042 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15043 "Regular expression matching the first line of a property drawer.")
15045 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15046 "Regular expression matching the last line of a property drawer.")
15048 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15049 "Regular expression matching the first line of a property drawer.")
15051 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15052 "Regular expression matching the first line of a property drawer.")
15054 (defconst org-property-drawer-re
15055 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15056 org-property-end-re "\\)\n?")
15057 "Matches an entire property drawer.")
15059 (defconst org-clock-drawer-re
15060 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15061 org-property-end-re "\\)\n?")
15062 "Matches an entire clock drawer.")
15064 (defun org-property-action ()
15065 "Do an action on properties."
15066 (interactive)
15067 (let (c)
15068 (org-at-property-p)
15069 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15070 (setq c (read-char-exclusive))
15071 (cond
15072 ((equal c ?s)
15073 (call-interactively 'org-set-property))
15074 ((equal c ?d)
15075 (call-interactively 'org-delete-property))
15076 ((equal c ?D)
15077 (call-interactively 'org-delete-property-globally))
15078 ((equal c ?c)
15079 (call-interactively 'org-compute-property-at-point))
15080 (t (user-error "No such property action %c" c)))))
15082 (defun org-inc-effort ()
15083 "Increment the value of the effort property in the current entry."
15084 (interactive)
15085 (org-set-effort nil t))
15087 (defvar org-clock-effort) ;; Defined in org-clock.el
15088 (defvar org-clock-current-task) ;; Defined in org-clock.el
15089 (defun org-set-effort (&optional value increment)
15090 "Set the effort property of the current entry.
15091 With numerical prefix arg, use the nth allowed value, 0 stands for the
15092 10th allowed value.
15094 When INCREMENT is non-nil, set the property to the next allowed value."
15095 (interactive "P")
15096 (if (equal value 0) (setq value 10))
15097 (let* ((completion-ignore-case t)
15098 (prop org-effort-property)
15099 (cur (org-entry-get nil prop))
15100 (allowed (org-property-get-allowed-values nil prop 'table))
15101 (existing (mapcar 'list (org-property-values prop)))
15102 (heading (nth 4 (org-heading-components)))
15104 (val (cond
15105 ((stringp value) value)
15106 ((and allowed (integerp value))
15107 (or (car (nth (1- value) allowed))
15108 (car (org-last allowed))))
15109 ((and allowed increment)
15110 (or (caadr (member (list cur) allowed))
15111 (user-error "Allowed effort values are not set")))
15112 (allowed
15113 (message "Select 1-9,0, [RET%s]: %s"
15114 (if cur (concat "=" cur) "")
15115 (mapconcat 'car allowed " "))
15116 (setq rpl (read-char-exclusive))
15117 (if (equal rpl ?\r)
15119 (setq rpl (- rpl ?0))
15120 (if (equal rpl 0) (setq rpl 10))
15121 (if (and (> rpl 0) (<= rpl (length allowed)))
15122 (car (nth (1- rpl) allowed))
15123 (org-completing-read "Effort: " allowed nil))))
15125 (let (org-completion-use-ido org-completion-use-iswitchb)
15126 (org-completing-read
15127 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15128 (concat "[" cur "]") "")
15129 ": ")
15130 existing nil nil "" nil cur))))))
15131 (unless (equal (org-entry-get nil prop) val)
15132 (org-entry-put nil prop val))
15133 (save-excursion
15134 (org-back-to-heading t)
15135 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15136 (when (string= heading org-clock-current-task)
15137 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15138 (org-clock-update-mode-line))
15139 (message "%s is now %s" prop val)))
15141 (defun org-at-property-p ()
15142 "Is cursor inside a property drawer?"
15143 (save-excursion
15144 (when (equal 'node-property (car (org-element-at-point)))
15145 (beginning-of-line 1)
15146 (looking-at org-property-re))))
15148 (defun org-get-property-block (&optional beg end force)
15149 "Return the (beg . end) range of the body of the property drawer.
15150 BEG and END are the beginning and end of the current subtree, or of
15151 the part before the first headline. If they are not given, they will
15152 be found. If the drawer does not exist and FORCE is non-nil, create
15153 the drawer."
15154 (catch 'exit
15155 (save-excursion
15156 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15157 (progn (org-back-to-heading t) (point))))
15158 (end (or end (and (not (outline-next-heading)) (point-max))
15159 (point))))
15160 (goto-char beg)
15161 (if (re-search-forward org-property-start-re end t)
15162 (setq beg (1+ (match-end 0)))
15163 (if force
15164 (save-excursion
15165 (org-insert-property-drawer)
15166 (setq end (progn (outline-next-heading) (point))))
15167 (throw 'exit nil))
15168 (goto-char beg)
15169 (if (re-search-forward org-property-start-re end t)
15170 (setq beg (1+ (match-end 0)))))
15171 (if (re-search-forward org-property-end-re end t)
15172 (setq end (match-beginning 0))
15173 (or force (throw 'exit nil))
15174 (goto-char beg)
15175 (setq end beg)
15176 (org-indent-line)
15177 (insert ":END:\n"))
15178 (cons beg end)))))
15180 (defun org-entry-properties (&optional pom which specific)
15181 "Get all properties of the entry at point-or-marker POM.
15182 This includes the TODO keyword, the tags, time strings for deadline,
15183 scheduled, and clocking, and any additional properties defined in the
15184 entry. The return value is an alist, keys may occur multiple times
15185 if the property key was used several times.
15186 POM may also be nil, in which case the current entry is used.
15187 If WHICH is nil or `all', get all properties. If WHICH is
15188 `special' or `standard', only get that subclass. If WHICH
15189 is a string only get exactly this property. SPECIFIC can be a string, the
15190 specific property we are interested in. Specifying it can speed
15191 things up because then unnecessary parsing is avoided."
15192 (setq which (or which 'all))
15193 (org-with-point-at pom
15194 (let ((clockstr (substring org-clock-string 0 -1))
15195 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15196 (case-fold-search nil)
15197 beg end range props sum-props key key1 value string clocksum clocksumt)
15198 (save-excursion
15199 (when (condition-case nil
15200 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15201 (error nil))
15202 (setq beg (point))
15203 (setq sum-props (get-text-property (point) 'org-summaries))
15204 (setq clocksum (get-text-property (point) :org-clock-minutes)
15205 clocksumt (get-text-property (point) :org-clock-minutes-today))
15206 (outline-next-heading)
15207 (setq end (point))
15208 (when (memq which '(all special))
15209 ;; Get the special properties, like TODO and tags
15210 (goto-char beg)
15211 (when (and (or (not specific) (string= specific "TODO"))
15212 (looking-at org-todo-line-regexp) (match-end 2))
15213 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15214 (when (and (or (not specific) (string= specific "PRIORITY"))
15215 (looking-at org-priority-regexp))
15216 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15217 (when (or (not specific) (string= specific "FILE"))
15218 (push (cons "FILE" buffer-file-name) props))
15219 (when (and (or (not specific) (string= specific "TAGS"))
15220 (setq value (org-get-tags-string))
15221 (string-match "\\S-" value))
15222 (push (cons "TAGS" value) props))
15223 (when (and (or (not specific) (string= specific "ALLTAGS"))
15224 (setq value (org-get-tags-at)))
15225 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15226 ":"))
15227 props))
15228 (when (or (not specific) (string= specific "BLOCKED"))
15229 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15230 (when (or (not specific)
15231 (member specific
15232 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15233 "TIMESTAMP" "TIMESTAMP_IA")))
15234 (catch 'match
15235 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15236 (setq key (if (match-end 1)
15237 (substring (org-match-string-no-properties 1)
15238 0 -1))
15239 string (if (equal key clockstr)
15240 (org-trim
15241 (buffer-substring-no-properties
15242 (match-beginning 3) (goto-char
15243 (point-at-eol))))
15244 (substring (org-match-string-no-properties 3)
15245 1 -1)))
15246 ;; Get the correct property name from the key. This is
15247 ;; necessary if the user has configured time keywords.
15248 (setq key1 (concat key ":"))
15249 (cond
15250 ((not key)
15251 (setq key
15252 (if (= (char-after (match-beginning 3)) ?\[)
15253 "TIMESTAMP_IA" "TIMESTAMP")))
15254 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15255 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15256 ((equal key1 org-closed-string) (setq key "CLOSED"))
15257 ((equal key1 org-clock-string) (setq key "CLOCK")))
15258 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15259 (progn
15260 (push (cons key string) props)
15261 ;; no need to search further if match is found
15262 (throw 'match t))
15263 (when (or (equal key "CLOCK") (not (assoc key props)))
15264 (push (cons key string) props)))))))
15266 (when (memq which '(all standard))
15267 ;; Get the standard properties, like :PROP: ...
15268 (setq range (org-get-property-block beg end))
15269 (when range
15270 (goto-char (car range))
15271 (while (re-search-forward org-property-re
15272 (cdr range) t)
15273 (setq key (org-match-string-no-properties 2)
15274 value (org-trim (or (org-match-string-no-properties 3) "")))
15275 (unless (member key excluded)
15276 (push (cons key (or value "")) props)))))
15277 (if clocksum
15278 (push (cons "CLOCKSUM"
15279 (org-columns-number-to-string (/ (float clocksum) 60.)
15280 'add_times))
15281 props))
15282 (if clocksumt
15283 (push (cons "CLOCKSUM_T"
15284 (org-columns-number-to-string (/ (float clocksumt) 60.)
15285 'add_times))
15286 props))
15287 (unless (assoc "CATEGORY" props)
15288 (push (cons "CATEGORY" (org-get-category)) props))
15289 (append sum-props (nreverse props)))))))
15291 (defun org-entry-get (pom property &optional inherit literal-nil)
15292 "Get value of PROPERTY for entry or content at point-or-marker POM.
15293 If INHERIT is non-nil and the entry does not have the property,
15294 then also check higher levels of the hierarchy.
15295 If INHERIT is the symbol `selective', use inheritance only if the setting
15296 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15297 If the property is present but empty, the return value is the empty string.
15298 If the property is not present at all, nil is returned.
15300 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15301 do not interpret it as the list atom nil. This is used for inheritance
15302 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15303 (org-with-point-at pom
15304 (if (and inherit (if (eq inherit 'selective)
15305 (org-property-inherit-p property)
15307 (org-entry-get-with-inheritance property literal-nil)
15308 (if (member property org-special-properties)
15309 ;; We need a special property. Use `org-entry-properties' to
15310 ;; retrieve it, but specify the wanted property
15311 (cdr (assoc property (org-entry-properties nil 'special property)))
15312 (let ((range (org-get-property-block)))
15313 (when (and range (not (eq (car range) (cdr range))))
15314 (let* ((props (list (or (assoc property org-file-properties)
15315 (assoc property org-global-properties)
15316 (assoc property org-global-properties-fixed))))
15317 (ap (lambda (key)
15318 (when (re-search-forward
15319 (org-re-property key) (cdr range) t)
15320 (setq props
15321 (org-update-property-plist
15323 (if (match-end 3)
15324 (org-match-string-no-properties 3) "")
15325 props)))))
15326 val)
15327 (goto-char (car range))
15328 (funcall ap property)
15329 (goto-char (car range))
15330 (while (funcall ap (concat property "+")))
15331 (setq val (cdr (assoc property props)))
15332 (when val (if literal-nil val (org-not-nil val))))))))))
15334 (defun org-property-or-variable-value (var &optional inherit)
15335 "Check if there is a property fixing the value of VAR.
15336 If yes, return this value. If not, return the current value of the variable."
15337 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15338 (if (and prop (stringp prop) (string-match "\\S-" prop))
15339 (read prop)
15340 (symbol-value var))))
15342 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15343 "Delete the property PROPERTY from entry at point-or-marker POM.
15344 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15345 an empty drawer to delete."
15346 (org-with-point-at pom
15347 (if (member property org-special-properties)
15348 nil ; cannot delete these properties.
15349 (let ((range (org-get-property-block)))
15350 (if (and range
15351 (goto-char (car range))
15352 (re-search-forward
15353 (org-re-property property)
15354 (cdr range) t))
15355 (progn
15356 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15357 (and delete-empty-drawer
15358 (org-remove-empty-drawer-at
15359 delete-empty-drawer (car range)))
15361 nil)))))
15363 ;; Multi-values properties are properties that contain multiple values
15364 ;; These values are assumed to be single words, separated by whitespace.
15365 (defun org-entry-add-to-multivalued-property (pom property value)
15366 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15367 (let* ((old (org-entry-get pom property))
15368 (values (and old (org-split-string old "[ \t]"))))
15369 (setq value (org-entry-protect-space value))
15370 (unless (member value values)
15371 (setq values (append values (list value)))
15372 (org-entry-put pom property
15373 (mapconcat 'identity values " ")))))
15375 (defun org-entry-remove-from-multivalued-property (pom property value)
15376 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15377 (let* ((old (org-entry-get pom property))
15378 (values (and old (org-split-string old "[ \t]"))))
15379 (setq value (org-entry-protect-space value))
15380 (when (member value values)
15381 (setq values (delete value values))
15382 (org-entry-put pom property
15383 (mapconcat 'identity values " ")))))
15385 (defun org-entry-member-in-multivalued-property (pom property value)
15386 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15387 (let* ((old (org-entry-get pom property))
15388 (values (and old (org-split-string old "[ \t]"))))
15389 (setq value (org-entry-protect-space value))
15390 (member value values)))
15392 (defun org-entry-get-multivalued-property (pom property)
15393 "Return a list of values in a multivalued property."
15394 (let* ((value (org-entry-get pom property))
15395 (values (and value (org-split-string value "[ \t]"))))
15396 (mapcar 'org-entry-restore-space values)))
15398 (defun org-entry-put-multivalued-property (pom property &rest values)
15399 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15400 VALUES should be a list of strings. Spaces will be protected."
15401 (org-entry-put pom property
15402 (mapconcat 'org-entry-protect-space values " "))
15403 (let* ((value (org-entry-get pom property))
15404 (values (and value (org-split-string value "[ \t]"))))
15405 (mapcar 'org-entry-restore-space values)))
15407 (defun org-entry-protect-space (s)
15408 "Protect spaces and newline in string S."
15409 (while (string-match " " s)
15410 (setq s (replace-match "%20" t t s)))
15411 (while (string-match "\n" s)
15412 (setq s (replace-match "%0A" t t s)))
15415 (defun org-entry-restore-space (s)
15416 "Restore spaces and newline in string S."
15417 (while (string-match "%20" s)
15418 (setq s (replace-match " " t t s)))
15419 (while (string-match "%0A" s)
15420 (setq s (replace-match "\n" t t s)))
15423 (defvar org-entry-property-inherited-from (make-marker)
15424 "Marker pointing to the entry from where a property was inherited.
15425 Each call to `org-entry-get-with-inheritance' will set this marker to the
15426 location of the entry where the inheritance search matched. If there was
15427 no match, the marker will point nowhere.
15428 Note that also `org-entry-get' calls this function, if the INHERIT flag
15429 is set.")
15431 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15432 "Get PROPERTY of entry or content at point, search higher levels if needed.
15433 The search will stop at the first ancestor which has the property defined.
15434 If the value found is \"nil\", return nil to show that the property
15435 should be considered as undefined (this is the meaning of nil here).
15436 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15437 (move-marker org-entry-property-inherited-from nil)
15438 (let (tmp)
15439 (save-excursion
15440 (save-restriction
15441 (widen)
15442 (catch 'ex
15443 (while t
15444 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15445 (or (ignore-errors (org-back-to-heading t))
15446 (goto-char (point-min)))
15447 (move-marker org-entry-property-inherited-from (point))
15448 (throw 'ex tmp))
15449 (or (ignore-errors (org-up-heading-safe))
15450 (throw 'ex nil))))))
15451 (setq tmp (or tmp
15452 (cdr (assoc property org-file-properties))
15453 (cdr (assoc property org-global-properties))
15454 (cdr (assoc property org-global-properties-fixed))))
15455 (if literal-nil tmp (org-not-nil tmp))))
15457 (defvar org-property-changed-functions nil
15458 "Hook called when the value of a property has changed.
15459 Each hook function should accept two arguments, the name of the property
15460 and the new value.")
15462 (defun org-entry-put (pom property value)
15463 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15464 (org-with-point-at pom
15465 (org-back-to-heading t)
15466 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15467 range)
15468 (cond
15469 ((equal property "TODO")
15470 (when (and (stringp value) (string-match "\\S-" value)
15471 (not (member value org-todo-keywords-1)))
15472 (user-error "\"%s\" is not a valid TODO state" value))
15473 (if (or (not value)
15474 (not (string-match "\\S-" value)))
15475 (setq value 'none))
15476 (org-todo value)
15477 (org-set-tags nil 'align))
15478 ((equal property "PRIORITY")
15479 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15480 (string-to-char value) ?\ ))
15481 (org-set-tags nil 'align))
15482 ((equal property "CLOCKSUM")
15483 (if (not (re-search-forward
15484 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15485 (error "Cannot find a clock log")
15486 (goto-char (- (match-end 1) 2))
15487 (cond
15488 ((eq value 'earlier) (org-timestamp-down))
15489 ((eq value 'later) (org-timestamp-up)))
15490 (org-clock-sum-current-item)))
15491 ((equal property "SCHEDULED")
15492 (if (re-search-forward org-scheduled-time-regexp end t)
15493 (cond
15494 ((eq value 'earlier) (org-timestamp-change -1 'day))
15495 ((eq value 'later) (org-timestamp-change 1 'day))
15496 (t (call-interactively 'org-schedule)))
15497 (call-interactively 'org-schedule)))
15498 ((equal property "DEADLINE")
15499 (if (re-search-forward org-deadline-time-regexp end t)
15500 (cond
15501 ((eq value 'earlier) (org-timestamp-change -1 'day))
15502 ((eq value 'later) (org-timestamp-change 1 'day))
15503 (t (call-interactively 'org-deadline)))
15504 (call-interactively 'org-deadline)))
15505 ((member property org-special-properties)
15506 (error "The %s property can not yet be set with `org-entry-put'"
15507 property))
15508 (t ; a non-special property
15509 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15510 (setq range (org-get-property-block beg end 'force))
15511 (goto-char (car range))
15512 (if (re-search-forward
15513 (org-re-property property) (cdr range) t)
15514 (progn
15515 (delete-region (match-beginning 0) (match-end 0))
15516 (goto-char (match-beginning 0)))
15517 (goto-char (cdr range))
15518 (insert "\n")
15519 (backward-char 1)
15520 (org-indent-line))
15521 (insert ":" property ":")
15522 (and value (insert " " value))
15523 (org-indent-line)))))
15524 (run-hook-with-args 'org-property-changed-functions property value)))
15526 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15527 "Get all property keys in the current buffer.
15528 With INCLUDE-SPECIALS, also list the special properties that reflect things
15529 like tags and TODO state.
15530 With INCLUDE-DEFAULTS, also include properties that has special meaning
15531 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15532 and others.
15533 With INCLUDE-COLUMNS, also include property names given in COLUMN
15534 formats in the current buffer."
15535 (let (rtn range cfmt s p)
15536 (save-excursion
15537 (save-restriction
15538 (widen)
15539 (goto-char (point-min))
15540 (while (re-search-forward org-property-start-re nil t)
15541 (setq range (org-get-property-block))
15542 (goto-char (car range))
15543 (while (re-search-forward org-property-re
15544 (cdr range) t)
15545 (add-to-list 'rtn (org-match-string-no-properties 2)))
15546 (outline-next-heading))))
15548 (when include-specials
15549 (setq rtn (append org-special-properties rtn)))
15551 (when include-defaults
15552 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15553 (add-to-list 'rtn org-effort-property))
15555 (when include-columns
15556 (save-excursion
15557 (save-restriction
15558 (widen)
15559 (goto-char (point-min))
15560 (while (re-search-forward
15561 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15562 nil t)
15563 (setq cfmt (match-string 2) s 0)
15564 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15565 cfmt s)
15566 (setq s (match-end 0)
15567 p (match-string 1 cfmt))
15568 (unless (or (equal p "ITEM")
15569 (member p org-special-properties))
15570 (add-to-list 'rtn (match-string 1 cfmt))))))))
15572 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15574 (defun org-property-values (key)
15575 "Return a list of all values of property KEY in the current buffer."
15576 (save-excursion
15577 (save-restriction
15578 (widen)
15579 (goto-char (point-min))
15580 (let ((re (org-re-property key))
15581 values)
15582 (while (re-search-forward re nil t)
15583 (add-to-list 'values (org-trim (match-string 3))))
15584 (delete "" values)))))
15586 (defun org-insert-property-drawer ()
15587 "Insert a property drawer into the current entry."
15588 (org-back-to-heading t)
15589 (looking-at org-outline-regexp)
15590 (let ((indent (if org-adapt-indentation
15591 (- (match-end 0) (match-beginning 0))
15593 (beg (point))
15594 (re (concat "^[ \t]*" org-keyword-time-regexp))
15595 end hiddenp)
15596 (outline-next-heading)
15597 (setq end (point))
15598 (goto-char beg)
15599 (while (re-search-forward re end t))
15600 (setq hiddenp (outline-invisible-p))
15601 (end-of-line 1)
15602 (and (equal (char-after) ?\n) (forward-char 1))
15603 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15604 (if (member (match-string 1) '("CLOCK:" ":END:"))
15605 ;; just skip this line
15606 (beginning-of-line 2)
15607 ;; Drawer start, find the end
15608 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15609 (beginning-of-line 1)))
15610 (org-skip-over-state-notes)
15611 (skip-chars-backward " \t\n\r")
15612 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15613 (forward-char 1))
15614 (goto-char (point-at-eol))
15615 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15616 (beginning-of-line 0)
15617 (org-indent-to-column indent)
15618 (beginning-of-line 2)
15619 (org-indent-to-column indent)
15620 (beginning-of-line 0)
15621 (if hiddenp
15622 (save-excursion
15623 (org-back-to-heading t)
15624 (hide-entry))
15625 (org-flag-drawer t))))
15627 (defun org-insert-drawer (&optional arg drawer)
15628 "Insert a drawer at point.
15630 Optional argument DRAWER, when non-nil, is a string representing
15631 drawer's name. Otherwise, the user is prompted for a name.
15633 If a region is active, insert the drawer around that region
15634 instead.
15636 Point is left between drawer's boundaries."
15637 (interactive "P")
15638 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15639 "LOGBOOK"))
15640 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15641 ;; internally by Org. They are meant to be inserted
15642 ;; automatically.
15643 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15644 ;; Remove system drawers from list. Note: For some reason,
15645 ;; `org-completing-read' ignores the predicate while
15646 ;; `completing-read' handles it fine.
15647 (drawer (if arg "PROPERTIES"
15648 (or drawer
15649 (completing-read
15650 "Drawer: " org-drawers
15651 (lambda (d) (not (member d system-drawers))))))))
15652 (cond
15653 ;; With C-u, fall back on `org-insert-property-drawer'
15654 (arg (org-insert-property-drawer))
15655 ;; With an active region, insert a drawer at point.
15656 ((not (org-region-active-p))
15657 (progn
15658 (unless (bolp) (insert "\n"))
15659 (insert (format ":%s:\n\n:END:\n" drawer))
15660 (forward-line -2)))
15661 ;; Otherwise, insert the drawer at point
15663 (let ((rbeg (region-beginning))
15664 (rend (copy-marker (region-end))))
15665 (unwind-protect
15666 (progn
15667 (goto-char rbeg)
15668 (beginning-of-line)
15669 (when (save-excursion
15670 (re-search-forward org-outline-regexp-bol rend t))
15671 (user-error "Drawers cannot contain headlines"))
15672 ;; Position point at the beginning of the first
15673 ;; non-blank line in region. Insert drawer's opening
15674 ;; there, then indent it.
15675 (org-skip-whitespace)
15676 (beginning-of-line)
15677 (insert ":" drawer ":\n")
15678 (forward-line -1)
15679 (indent-for-tab-command)
15680 ;; Move point to the beginning of the first blank line
15681 ;; after the last non-blank line in region. Insert
15682 ;; drawer's closing, then indent it.
15683 (goto-char rend)
15684 (skip-chars-backward " \r\t\n")
15685 (insert "\n:END:")
15686 (deactivate-mark t)
15687 (indent-for-tab-command)
15688 (unless (eolp) (insert "\n")))
15689 ;; Clear marker, whatever the outcome of insertion is.
15690 (set-marker rend nil)))))))
15692 (defvar org-property-set-functions-alist nil
15693 "Property set function alist.
15694 Each entry should have the following format:
15696 (PROPERTY . READ-FUNCTION)
15698 The read function will be called with the same argument as
15699 `org-completing-read'.")
15701 (defun org-set-property-function (property)
15702 "Get the function that should be used to set PROPERTY.
15703 This is computed according to `org-property-set-functions-alist'."
15704 (or (cdr (assoc property org-property-set-functions-alist))
15705 'org-completing-read))
15707 (defun org-read-property-value (property)
15708 "Read PROPERTY value from user."
15709 (let* ((completion-ignore-case t)
15710 (allowed (org-property-get-allowed-values nil property 'table))
15711 (cur (org-entry-get nil property))
15712 (prompt (concat property " value"
15713 (if (and cur (string-match "\\S-" cur))
15714 (concat " [" cur "]") "") ": "))
15715 (set-function (org-set-property-function property))
15716 (val (if allowed
15717 (funcall set-function prompt allowed nil
15718 (not (get-text-property 0 'org-unrestricted
15719 (caar allowed))))
15720 (let (org-completion-use-ido org-completion-use-iswitchb)
15721 (funcall set-function prompt
15722 (mapcar 'list (org-property-values property))
15723 nil nil "" nil cur)))))
15724 (if (equal val "")
15726 val)))
15728 (defvar org-last-set-property nil)
15729 (defvar org-last-set-property-value nil)
15730 (defun org-read-property-name ()
15731 "Read a property name."
15732 (let* ((completion-ignore-case t)
15733 (keys (org-buffer-property-keys nil t t))
15734 (default-prop (or (save-excursion
15735 (save-match-data
15736 (beginning-of-line)
15737 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15738 (null (string= (match-string 1) "END"))
15739 (match-string 1))))
15740 org-last-set-property))
15741 (property (org-icompleting-read
15742 (concat "Property"
15743 (if default-prop (concat " [" default-prop "]") "")
15744 ": ")
15745 (mapcar 'list keys)
15746 nil nil nil nil
15747 default-prop)))
15748 (if (member property keys)
15749 property
15750 (or (cdr (assoc (downcase property)
15751 (mapcar (lambda (x) (cons (downcase x) x))
15752 keys)))
15753 property))))
15755 (defun org-set-property-and-value (use-last)
15756 "Allow to set [PROPERTY]: [value] direction from prompt.
15757 When use-default, don't even ask, just use the last
15758 \"[PROPERTY]: [value]\" string from the history."
15759 (interactive "P")
15760 (let* ((completion-ignore-case t)
15761 (pv (or (and use-last org-last-set-property-value)
15762 (org-completing-read
15763 "Enter a \"[Property]: [value]\" pair: "
15764 nil nil nil nil nil
15765 org-last-set-property-value)))
15766 prop val)
15767 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15768 (setq prop (match-string 1 pv)
15769 val (match-string 2 pv))
15770 (org-set-property prop val))))
15772 (defun org-set-property (property value)
15773 "In the current entry, set PROPERTY to VALUE.
15774 When called interactively, this will prompt for a property name, offering
15775 completion on existing and default properties. And then it will prompt
15776 for a value, offering completion either on allowed values (via an inherited
15777 xxx_ALL property) or on existing values in other instances of this property
15778 in the current file."
15779 (interactive (list nil nil))
15780 (let* ((property (or property (org-read-property-name)))
15781 (value (or value (org-read-property-value property)))
15782 (fn (cdr (assoc property org-properties-postprocess-alist))))
15783 (setq org-last-set-property property)
15784 (setq org-last-set-property-value (concat property ": " value))
15785 ;; Possibly postprocess the inserted value:
15786 (when fn (setq value (funcall fn value)))
15787 (unless (equal (org-entry-get nil property) value)
15788 (org-entry-put nil property value))))
15790 (defun org-delete-property (property &optional delete-empty-drawer)
15791 "In the current entry, delete PROPERTY.
15792 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15793 an empty drawer to delete."
15794 (interactive
15795 (let* ((completion-ignore-case t)
15796 (prop (org-icompleting-read "Property: "
15797 (org-entry-properties nil 'standard))))
15798 (list prop)))
15799 (message "Property %s %s" property
15800 (if (org-entry-delete nil property delete-empty-drawer)
15801 "deleted"
15802 "was not present in the entry")))
15804 (defun org-delete-property-globally (property)
15805 "Remove PROPERTY globally, from all entries."
15806 (interactive
15807 (let* ((completion-ignore-case t)
15808 (prop (org-icompleting-read
15809 "Globally remove property: "
15810 (mapcar 'list (org-buffer-property-keys)))))
15811 (list prop)))
15812 (save-excursion
15813 (save-restriction
15814 (widen)
15815 (goto-char (point-min))
15816 (let ((cnt 0))
15817 (while (re-search-forward
15818 (org-re-property property)
15819 nil t)
15820 (setq cnt (1+ cnt))
15821 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15822 (message "Property \"%s\" removed from %d entries" property cnt)))))
15824 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15826 (defun org-compute-property-at-point ()
15827 "Compute the property at point.
15828 This looks for an enclosing column format, extracts the operator and
15829 then applies it to the property in the column format's scope."
15830 (interactive)
15831 (unless (org-at-property-p)
15832 (user-error "Not at a property"))
15833 (let ((prop (org-match-string-no-properties 2)))
15834 (org-columns-get-format-and-top-level)
15835 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15836 (user-error "No operator defined for property %s" prop))
15837 (org-columns-compute prop)))
15839 (defvar org-property-allowed-value-functions nil
15840 "Hook for functions supplying allowed values for a specific property.
15841 The functions must take a single argument, the name of the property, and
15842 return a flat list of allowed values. If \":ETC\" is one of
15843 the values, this means that these values are intended as defaults for
15844 completion, but that other values should be allowed too.
15845 The functions must return nil if they are not responsible for this
15846 property.")
15848 (defun org-property-get-allowed-values (pom property &optional table)
15849 "Get allowed values for the property PROPERTY.
15850 When TABLE is non-nil, return an alist that can directly be used for
15851 completion."
15852 (let (vals)
15853 (cond
15854 ((equal property "TODO")
15855 (setq vals (org-with-point-at pom
15856 (append org-todo-keywords-1 '("")))))
15857 ((equal property "PRIORITY")
15858 (let ((n org-lowest-priority))
15859 (while (>= n org-highest-priority)
15860 (push (char-to-string n) vals)
15861 (setq n (1- n)))))
15862 ((member property org-special-properties))
15863 ((setq vals (run-hook-with-args-until-success
15864 'org-property-allowed-value-functions property)))
15866 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15867 (when (and vals (string-match "\\S-" vals))
15868 (setq vals (car (read-from-string (concat "(" vals ")"))))
15869 (setq vals (mapcar (lambda (x)
15870 (cond ((stringp x) x)
15871 ((numberp x) (number-to-string x))
15872 ((symbolp x) (symbol-name x))
15873 (t "???")))
15874 vals)))))
15875 (when (member ":ETC" vals)
15876 (setq vals (remove ":ETC" vals))
15877 (org-add-props (car vals) '(org-unrestricted t)))
15878 (if table (mapcar 'list vals) vals)))
15880 (defun org-property-previous-allowed-value (&optional previous)
15881 "Switch to the next allowed value for this property."
15882 (interactive)
15883 (org-property-next-allowed-value t))
15885 (defun org-property-next-allowed-value (&optional previous)
15886 "Switch to the next allowed value for this property."
15887 (interactive)
15888 (unless (org-at-property-p)
15889 (user-error "Not at a property"))
15890 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15891 (key (match-string 2))
15892 (value (match-string 3))
15893 (allowed (or (org-property-get-allowed-values (point) key)
15894 (and (member value '("[ ]" "[-]" "[X]"))
15895 '("[ ]" "[X]"))))
15896 (heading (save-match-data (nth 4 (org-heading-components))))
15897 nval)
15898 (unless allowed
15899 (user-error "Allowed values for this property have not been defined"))
15900 (if previous (setq allowed (reverse allowed)))
15901 (if (member value allowed)
15902 (setq nval (car (cdr (member value allowed)))))
15903 (setq nval (or nval (car allowed)))
15904 (if (equal nval value)
15905 (user-error "Only one allowed value for this property"))
15906 (org-at-property-p)
15907 (replace-match (concat " :" key ": " nval) t t)
15908 (org-indent-line)
15909 (beginning-of-line 1)
15910 (skip-chars-forward " \t")
15911 (when (equal prop org-effort-property)
15912 (save-excursion
15913 (org-back-to-heading t)
15914 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15915 (when (string= org-clock-current-task heading)
15916 (setq org-clock-effort nval)
15917 (org-clock-update-mode-line)))
15918 (run-hook-with-args 'org-property-changed-functions key nval)))
15920 (defun org-find-olp (path &optional this-buffer)
15921 "Return a marker pointing to the entry at outline path OLP.
15922 If anything goes wrong, throw an error.
15923 You can wrap this call to catch the error like this:
15925 (condition-case msg
15926 (org-mobile-locate-entry (match-string 4))
15927 (error (nth 1 msg)))
15929 The return value will then be either a string with the error message,
15930 or a marker if everything is OK.
15932 If THIS-BUFFER is set, the outline path does not contain a file,
15933 only headings."
15934 (let* ((file (if this-buffer buffer-file-name (pop path)))
15935 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15936 (level 1)
15937 (lmin 1)
15938 (lmax 1)
15939 limit re end found pos heading cnt flevel)
15940 (unless buffer (error "File not found :%s" file))
15941 (with-current-buffer buffer
15942 (save-excursion
15943 (save-restriction
15944 (widen)
15945 (setq limit (point-max))
15946 (goto-char (point-min))
15947 (while (setq heading (pop path))
15948 (setq re (format org-complex-heading-regexp-format
15949 (regexp-quote heading)))
15950 (setq cnt 0 pos (point))
15951 (while (re-search-forward re end t)
15952 (setq level (- (match-end 1) (match-beginning 1)))
15953 (if (and (>= level lmin) (<= level lmax))
15954 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15955 (when (= cnt 0) (error "Heading not found on level %d: %s"
15956 lmax heading))
15957 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15958 lmax heading))
15959 (goto-char found)
15960 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15961 (setq end (save-excursion (org-end-of-subtree t t))))
15962 (when (org-at-heading-p)
15963 (point-marker)))))))
15965 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15966 "Find node HEADING in BUFFER.
15967 Return a marker to the heading if it was found, or nil if not.
15968 If POS-ONLY is set, return just the position instead of a marker.
15970 The heading text must match exact, but it may have a TODO keyword,
15971 a priority cookie and tags in the standard locations."
15972 (with-current-buffer (or buffer (current-buffer))
15973 (save-excursion
15974 (save-restriction
15975 (widen)
15976 (goto-char (point-min))
15977 (let (case-fold-search)
15978 (if (re-search-forward
15979 (format org-complex-heading-regexp-format
15980 (regexp-quote heading)) nil t)
15981 (if pos-only
15982 (match-beginning 0)
15983 (move-marker (make-marker) (match-beginning 0)))))))))
15985 (defun org-find-exact-heading-in-directory (heading &optional dir)
15986 "Find Org node headline HEADING in all .org files in directory DIR.
15987 When the target headline is found, return a marker to this location."
15988 (let ((files (directory-files (or dir default-directory)
15989 nil "\\`[^.#].*\\.org\\'"))
15990 file visiting m buffer)
15991 (catch 'found
15992 (while (setq file (pop files))
15993 (message "trying %s" file)
15994 (setq visiting (org-find-base-buffer-visiting file))
15995 (setq buffer (or visiting (find-file-noselect file)))
15996 (setq m (org-find-exact-headline-in-buffer
15997 heading buffer))
15998 (when (and (not m) (not visiting)) (kill-buffer buffer))
15999 (and m (throw 'found m))))))
16001 (defun org-find-entry-with-id (ident)
16002 "Locate the entry that contains the ID property with exact value IDENT.
16003 IDENT can be a string, a symbol or a number, this function will search for
16004 the string representation of it.
16005 Return the position where this entry starts, or nil if there is no such entry."
16006 (interactive "sID: ")
16007 (let ((id (cond
16008 ((stringp ident) ident)
16009 ((symbol-name ident) (symbol-name ident))
16010 ((numberp ident) (number-to-string ident))
16011 (t (error "IDENT %s must be a string, symbol or number" ident))))
16012 (case-fold-search nil))
16013 (save-excursion
16014 (save-restriction
16015 (widen)
16016 (goto-char (point-min))
16017 (when (re-search-forward
16018 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16019 nil t)
16020 (org-back-to-heading t)
16021 (point))))))
16023 ;;;; Timestamps
16025 (defvar org-last-changed-timestamp nil)
16026 (defvar org-last-inserted-timestamp nil
16027 "The last time stamp inserted with `org-insert-time-stamp'.")
16028 (defvar org-time-was-given) ; dynamically scoped parameter
16029 (defvar org-end-time-was-given) ; dynamically scoped parameter
16030 (defvar org-ts-what) ; dynamically scoped parameter
16032 (defun org-time-stamp (arg &optional inactive)
16033 "Prompt for a date/time and insert a time stamp.
16034 If the user specifies a time like HH:MM or if this command is
16035 called with at least one prefix argument, the time stamp contains
16036 the date and the time. Otherwise, only the date is be included.
16038 All parts of a date not specified by the user is filled in from
16039 the current date/time. So if you just press return without
16040 typing anything, the time stamp will represent the current
16041 date/time.
16043 If there is already a timestamp at the cursor, it will be
16044 modified.
16046 With two universal prefix arguments, insert an active timestamp
16047 with the current time without prompting the user.
16049 When called from lisp, the timestamp is inactive if INACTIVE is
16050 non-nil."
16051 (interactive "P")
16052 (let* ((ts nil)
16053 (default-time
16054 ;; Default time is either today, or, when entering a range,
16055 ;; the range start.
16056 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16057 (save-excursion
16058 (re-search-backward
16059 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16060 (- (point) 20) t)))
16061 (apply 'encode-time (org-parse-time-string (match-string 1)))
16062 (current-time)))
16063 (default-input (and ts (org-get-compact-tod ts)))
16064 (repeater (save-excursion
16065 (save-match-data
16066 (beginning-of-line)
16067 (when (re-search-forward
16068 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16069 (save-excursion (progn (end-of-line) (point))) t)
16070 (match-string 0)))))
16071 org-time-was-given org-end-time-was-given time)
16072 (cond
16073 ((and (org-at-timestamp-p t)
16074 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16075 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16076 (insert "--")
16077 (setq time (let ((this-command this-command))
16078 (org-read-date arg 'totime nil nil
16079 default-time default-input inactive)))
16080 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16081 ((org-at-timestamp-p t)
16082 (setq time (let ((this-command this-command))
16083 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16084 (when (org-at-timestamp-p t) ; just to get the match data
16085 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16086 (replace-match "")
16087 (setq org-last-changed-timestamp
16088 (org-insert-time-stamp
16089 time (or org-time-was-given arg)
16090 inactive nil nil (list org-end-time-was-given)))
16091 (when repeater (goto-char (1- (point))) (insert " " repeater)
16092 (setq org-last-changed-timestamp
16093 (concat (substring org-last-inserted-timestamp 0 -1)
16094 " " repeater ">"))))
16095 (message "Timestamp updated"))
16096 ((equal arg '(16))
16097 (org-insert-time-stamp (current-time) t inactive))
16099 (setq time (let ((this-command this-command))
16100 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16101 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16102 nil nil (list org-end-time-was-given))))))
16104 ;; FIXME: can we use this for something else, like computing time differences?
16105 (defun org-get-compact-tod (s)
16106 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16107 (let* ((t1 (match-string 1 s))
16108 (h1 (string-to-number (match-string 2 s)))
16109 (m1 (string-to-number (match-string 3 s)))
16110 (t2 (and (match-end 4) (match-string 5 s)))
16111 (h2 (and t2 (string-to-number (match-string 6 s))))
16112 (m2 (and t2 (string-to-number (match-string 7 s))))
16113 dh dm)
16114 (if (not t2)
16116 (setq dh (- h2 h1) dm (- m2 m1))
16117 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16118 (concat t1 "+" (number-to-string dh)
16119 (and (/= 0 dm) (format ":%02d" dm)))))))
16121 (defun org-time-stamp-inactive (&optional arg)
16122 "Insert an inactive time stamp.
16123 An inactive time stamp is enclosed in square brackets instead of angle
16124 brackets. It is inactive in the sense that it does not trigger agenda entries,
16125 does not link to the calendar and cannot be changed with the S-cursor keys.
16126 So these are more for recording a certain time/date."
16127 (interactive "P")
16128 (org-time-stamp arg 'inactive))
16130 (defvar org-date-ovl (make-overlay 1 1))
16131 (overlay-put org-date-ovl 'face 'org-date-selected)
16132 (org-detach-overlay org-date-ovl)
16134 (defvar org-ans1) ; dynamically scoped parameter
16135 (defvar org-ans2) ; dynamically scoped parameter
16137 (defvar org-plain-time-of-day-regexp) ; defined below
16139 (defvar org-overriding-default-time nil) ; dynamically scoped
16140 (defvar org-read-date-overlay nil)
16141 (defvar org-dcst nil) ; dynamically scoped
16142 (defvar org-read-date-history nil)
16143 (defvar org-read-date-final-answer nil)
16144 (defvar org-read-date-analyze-futurep nil)
16145 (defvar org-read-date-analyze-forced-year nil)
16146 (defvar org-read-date-inactive)
16148 (defvar org-read-date-minibuffer-local-map
16149 (let* ((org-replace-disputed-keys nil)
16150 (map (make-sparse-keymap)))
16151 (set-keymap-parent map minibuffer-local-map)
16152 (org-defkey map (kbd ".")
16153 (lambda () (interactive)
16154 ;; Are we at the beginning of the prompt?
16155 (if (looking-back "^[^:]+: ")
16156 (org-eval-in-calendar '(calendar-goto-today))
16157 (insert "."))))
16158 (org-defkey map (kbd "C-.")
16159 (lambda () (interactive)
16160 (org-eval-in-calendar '(calendar-goto-today))))
16161 (org-defkey map [(meta shift left)]
16162 (lambda () (interactive)
16163 (org-eval-in-calendar '(calendar-backward-month 1))))
16164 (org-defkey map [(meta shift right)]
16165 (lambda () (interactive)
16166 (org-eval-in-calendar '(calendar-forward-month 1))))
16167 (org-defkey map [(meta shift up)]
16168 (lambda () (interactive)
16169 (org-eval-in-calendar '(calendar-backward-year 1))))
16170 (org-defkey map [(meta shift down)]
16171 (lambda () (interactive)
16172 (org-eval-in-calendar '(calendar-forward-year 1))))
16173 (org-defkey map [?\e (shift left)]
16174 (lambda () (interactive)
16175 (org-eval-in-calendar '(calendar-backward-month 1))))
16176 (org-defkey map [?\e (shift right)]
16177 (lambda () (interactive)
16178 (org-eval-in-calendar '(calendar-forward-month 1))))
16179 (org-defkey map [?\e (shift up)]
16180 (lambda () (interactive)
16181 (org-eval-in-calendar '(calendar-backward-year 1))))
16182 (org-defkey map [?\e (shift down)]
16183 (lambda () (interactive)
16184 (org-eval-in-calendar '(calendar-forward-year 1))))
16185 (org-defkey map [(shift up)]
16186 (lambda () (interactive)
16187 (org-eval-in-calendar '(calendar-backward-week 1))))
16188 (org-defkey map [(shift down)]
16189 (lambda () (interactive)
16190 (org-eval-in-calendar '(calendar-forward-week 1))))
16191 (org-defkey map [(shift left)]
16192 (lambda () (interactive)
16193 (org-eval-in-calendar '(calendar-backward-day 1))))
16194 (org-defkey map [(shift right)]
16195 (lambda () (interactive)
16196 (org-eval-in-calendar '(calendar-forward-day 1))))
16197 (org-defkey map "!"
16198 (lambda () (interactive)
16199 (org-eval-in-calendar '(diary-view-entries))
16200 (message "")))
16201 (org-defkey map ">"
16202 (lambda () (interactive)
16203 (org-eval-in-calendar '(scroll-calendar-left 1))))
16204 (org-defkey map "<"
16205 (lambda () (interactive)
16206 (org-eval-in-calendar '(scroll-calendar-right 1))))
16207 (org-defkey map "\C-v"
16208 (lambda () (interactive)
16209 (org-eval-in-calendar
16210 '(calendar-scroll-left-three-months 1))))
16211 (org-defkey map "\M-v"
16212 (lambda () (interactive)
16213 (org-eval-in-calendar
16214 '(calendar-scroll-right-three-months 1))))
16215 map)
16216 "Keymap for minibuffer commands when using `org-read-date'.")
16218 (defun org-read-date (&optional org-with-time to-time from-string prompt
16219 default-time default-input inactive)
16220 "Read a date, possibly a time, and make things smooth for the user.
16221 The prompt will suggest to enter an ISO date, but you can also enter anything
16222 which will at least partially be understood by `parse-time-string'.
16223 Unrecognized parts of the date will default to the current day, month, year,
16224 hour and minute. If this command is called to replace a timestamp at point,
16225 or to enter the second timestamp of a range, the default time is taken
16226 from the existing stamp. Furthermore, the command prefers the future,
16227 so if you are giving a date where the year is not given, and the day-month
16228 combination is already past in the current year, it will assume you
16229 mean next year. For details, see the manual. A few examples:
16231 3-2-5 --> 2003-02-05
16232 feb 15 --> currentyear-02-15
16233 2/15 --> currentyear-02-15
16234 sep 12 9 --> 2009-09-12
16235 12:45 --> today 12:45
16236 22 sept 0:34 --> currentyear-09-22 0:34
16237 12 --> currentyear-currentmonth-12
16238 Fri --> nearest Friday after today
16239 -Tue --> last Tuesday
16240 etc.
16242 Furthermore you can specify a relative date by giving, as the *first* thing
16243 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16244 change in days weeks, months, years.
16245 With a single plus or minus, the date is relative to today. With a double
16246 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16247 +4d --> four days from today
16248 +4 --> same as above
16249 +2w --> two weeks from today
16250 ++5 --> five days from default date
16252 The function understands only English month and weekday abbreviations.
16254 While prompting, a calendar is popped up - you can also select the
16255 date with the mouse (button 1). The calendar shows a period of three
16256 months. To scroll it to other months, use the keys `>' and `<'.
16257 If you don't like the calendar, turn it off with
16258 \(setq org-read-date-popup-calendar nil)
16260 With optional argument TO-TIME, the date will immediately be converted
16261 to an internal time.
16262 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16263 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16264 still enter a time, and this function will inform the calling routine
16265 about this change. The calling routine may then choose to change the
16266 format used to insert the time stamp into the buffer to include the time.
16267 With optional argument FROM-STRING, read from this string instead from
16268 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16269 the time/date that is used for everything that is not specified by the
16270 user."
16271 (require 'parse-time)
16272 (let* ((org-time-stamp-rounding-minutes
16273 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16274 (org-dcst org-display-custom-times)
16275 (ct (org-current-time))
16276 (org-def (or org-overriding-default-time default-time ct))
16277 (org-defdecode (decode-time org-def))
16278 (dummy (progn
16279 (when (< (nth 2 org-defdecode) org-extend-today-until)
16280 (setcar (nthcdr 2 org-defdecode) -1)
16281 (setcar (nthcdr 1 org-defdecode) 59)
16282 (setq org-def (apply 'encode-time org-defdecode)
16283 org-defdecode (decode-time org-def)))))
16284 (mouse-autoselect-window nil) ; Don't let the mouse jump
16285 (calendar-frame-setup nil)
16286 (calendar-setup nil)
16287 (calendar-move-hook nil)
16288 (calendar-view-diary-initially-flag nil)
16289 (calendar-view-holidays-initially-flag nil)
16290 (timestr (format-time-string
16291 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16292 (prompt (concat (if prompt (concat prompt " ") "")
16293 (format "Date+time [%s]: " timestr)))
16294 ans (org-ans0 "") org-ans1 org-ans2 final)
16296 (cond
16297 (from-string (setq ans from-string))
16298 (org-read-date-popup-calendar
16299 (save-excursion
16300 (save-window-excursion
16301 (calendar)
16302 (org-eval-in-calendar '(setq cursor-type nil) t)
16303 (unwind-protect
16304 (progn
16305 (calendar-forward-day (- (time-to-days org-def)
16306 (calendar-absolute-from-gregorian
16307 (calendar-current-date))))
16308 (org-eval-in-calendar nil t)
16309 (let* ((old-map (current-local-map))
16310 (map (copy-keymap calendar-mode-map))
16311 (minibuffer-local-map
16312 (copy-keymap org-read-date-minibuffer-local-map)))
16313 (org-defkey map (kbd "RET") 'org-calendar-select)
16314 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16315 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16316 (unwind-protect
16317 (progn
16318 (use-local-map map)
16319 (setq org-read-date-inactive inactive)
16320 (add-hook 'post-command-hook 'org-read-date-display)
16321 (setq org-ans0 (read-string prompt default-input
16322 'org-read-date-history nil))
16323 ;; org-ans0: from prompt
16324 ;; org-ans1: from mouse click
16325 ;; org-ans2: from calendar motion
16326 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16327 (remove-hook 'post-command-hook 'org-read-date-display)
16328 (use-local-map old-map)
16329 (when org-read-date-overlay
16330 (delete-overlay org-read-date-overlay)
16331 (setq org-read-date-overlay nil)))))
16332 (bury-buffer "*Calendar*")))))
16334 (t ; Naked prompt only
16335 (unwind-protect
16336 (setq ans (read-string prompt default-input
16337 'org-read-date-history timestr))
16338 (when org-read-date-overlay
16339 (delete-overlay org-read-date-overlay)
16340 (setq org-read-date-overlay nil)))))
16342 (setq final (org-read-date-analyze ans org-def org-defdecode))
16344 (when org-read-date-analyze-forced-year
16345 (message "Year was forced into %s"
16346 (if org-read-date-force-compatible-dates
16347 "compatible range (1970-2037)"
16348 "range representable on this machine"))
16349 (ding))
16351 ;; One round trip to get rid of 34th of August and stuff like that....
16352 (setq final (decode-time (apply 'encode-time final)))
16354 (setq org-read-date-final-answer ans)
16356 (if to-time
16357 (apply 'encode-time final)
16358 (if (and (boundp 'org-time-was-given) org-time-was-given)
16359 (format "%04d-%02d-%02d %02d:%02d"
16360 (nth 5 final) (nth 4 final) (nth 3 final)
16361 (nth 2 final) (nth 1 final))
16362 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16364 (defvar org-def)
16365 (defvar org-defdecode)
16366 (defvar org-with-time)
16367 (defun org-read-date-display ()
16368 "Display the current date prompt interpretation in the minibuffer."
16369 (when org-read-date-display-live
16370 (when org-read-date-overlay
16371 (delete-overlay org-read-date-overlay))
16372 (when (minibufferp (current-buffer))
16373 (save-excursion
16374 (end-of-line 1)
16375 (while (not (equal (buffer-substring
16376 (max (point-min) (- (point) 4)) (point))
16377 " "))
16378 (insert " ")))
16379 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16380 " " (or org-ans1 org-ans2)))
16381 (org-end-time-was-given nil)
16382 (f (org-read-date-analyze ans org-def org-defdecode))
16383 (fmts (if org-dcst
16384 org-time-stamp-custom-formats
16385 org-time-stamp-formats))
16386 (fmt (if (or org-with-time
16387 (and (boundp 'org-time-was-given) org-time-was-given))
16388 (cdr fmts)
16389 (car fmts)))
16390 (txt (format-time-string fmt (apply 'encode-time f)))
16391 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16392 (txt (concat "=> " txt)))
16393 (when (and org-end-time-was-given
16394 (string-match org-plain-time-of-day-regexp txt))
16395 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16396 org-end-time-was-given
16397 (substring txt (match-end 0)))))
16398 (when org-read-date-analyze-futurep
16399 (setq txt (concat txt " (=>F)")))
16400 (setq org-read-date-overlay
16401 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16402 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16404 (defun org-read-date-analyze (ans org-def org-defdecode)
16405 "Analyze the combined answer of the date prompt."
16406 ;; FIXME: cleanup and comment
16407 (let ((nowdecode (decode-time (current-time)))
16408 delta deltan deltaw deltadef year month day
16409 hour minute second wday pm h2 m2 tl wday1
16410 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16411 (setq org-read-date-analyze-futurep nil
16412 org-read-date-analyze-forced-year nil)
16413 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16414 (setq ans "+0"))
16416 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16417 (setq ans (replace-match "" t t ans)
16418 deltan (car delta)
16419 deltaw (nth 1 delta)
16420 deltadef (nth 2 delta)))
16422 ;; Check if there is an iso week date in there. If yes, store the
16423 ;; info and postpone interpreting it until the rest of the parsing
16424 ;; is done.
16425 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16426 (setq iso-year (if (match-end 1)
16427 (org-small-year-to-year
16428 (string-to-number (match-string 1 ans))))
16429 iso-weekday (if (match-end 3)
16430 (string-to-number (match-string 3 ans)))
16431 iso-week (string-to-number (match-string 2 ans)))
16432 (setq ans (replace-match "" t t ans)))
16434 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16435 (when (string-match
16436 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16437 (setq year (if (match-end 2)
16438 (string-to-number (match-string 2 ans))
16439 (progn (setq kill-year t)
16440 (string-to-number (format-time-string "%Y"))))
16441 month (string-to-number (match-string 3 ans))
16442 day (string-to-number (match-string 4 ans)))
16443 (if (< year 100) (setq year (+ 2000 year)))
16444 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16445 t nil ans)))
16447 ;; Help matching dotted european dates
16448 (when (string-match
16449 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16450 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16451 (setq kill-year t)
16452 (string-to-number (format-time-string "%Y")))
16453 day (string-to-number (match-string 1 ans))
16454 month (string-to-number (match-string 2 ans))
16455 ans (replace-match (format "%04d-%02d-%02d" year month day)
16456 t nil ans)))
16458 ;; Help matching american dates, like 5/30 or 5/30/7
16459 (when (string-match
16460 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16461 (setq year (if (match-end 4)
16462 (string-to-number (match-string 4 ans))
16463 (progn (setq kill-year t)
16464 (string-to-number (format-time-string "%Y"))))
16465 month (string-to-number (match-string 1 ans))
16466 day (string-to-number (match-string 2 ans)))
16467 (if (< year 100) (setq year (+ 2000 year)))
16468 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16469 t nil ans)))
16470 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16471 ;; If there is a time with am/pm, and *no* time without it, we convert
16472 ;; so that matching will be successful.
16473 (loop for i from 1 to 2 do ; twice, for end time as well
16474 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16475 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16476 (setq hour (string-to-number (match-string 1 ans))
16477 minute (if (match-end 3)
16478 (string-to-number (match-string 3 ans))
16480 pm (equal ?p
16481 (string-to-char (downcase (match-string 4 ans)))))
16482 (if (and (= hour 12) (not pm))
16483 (setq hour 0)
16484 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16485 (setq ans (replace-match (format "%02d:%02d" hour minute)
16486 t t ans))))
16488 ;; Check if a time range is given as a duration
16489 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16490 (setq hour (string-to-number (match-string 1 ans))
16491 h2 (+ hour (string-to-number (match-string 3 ans)))
16492 minute (string-to-number (match-string 2 ans))
16493 m2 (+ minute (if (match-end 5) (string-to-number
16494 (match-string 5 ans))0)))
16495 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16496 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16497 t t ans)))
16499 ;; Check if there is a time range
16500 (when (boundp 'org-end-time-was-given)
16501 (setq org-time-was-given nil)
16502 (when (and (string-match org-plain-time-of-day-regexp ans)
16503 (match-end 8))
16504 (setq org-end-time-was-given (match-string 8 ans))
16505 (setq ans (concat (substring ans 0 (match-beginning 7))
16506 (substring ans (match-end 7))))))
16508 (setq tl (parse-time-string ans)
16509 day (or (nth 3 tl) (nth 3 org-defdecode))
16510 month (or (nth 4 tl)
16511 (if (and org-read-date-prefer-future
16512 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16513 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16514 (nth 4 org-defdecode)))
16515 year (or (and (not kill-year) (nth 5 tl))
16516 (if (and org-read-date-prefer-future
16517 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16518 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16519 (nth 5 org-defdecode)))
16520 hour (or (nth 2 tl) (nth 2 org-defdecode))
16521 minute (or (nth 1 tl) (nth 1 org-defdecode))
16522 second (or (nth 0 tl) 0)
16523 wday (nth 6 tl))
16525 (when (and (eq org-read-date-prefer-future 'time)
16526 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16527 (equal day (nth 3 nowdecode))
16528 (equal month (nth 4 nowdecode))
16529 (equal year (nth 5 nowdecode))
16530 (nth 2 tl)
16531 (or (< (nth 2 tl) (nth 2 nowdecode))
16532 (and (= (nth 2 tl) (nth 2 nowdecode))
16533 (nth 1 tl)
16534 (< (nth 1 tl) (nth 1 nowdecode)))))
16535 (setq day (1+ day)
16536 futurep t))
16538 ;; Special date definitions below
16539 (cond
16540 (iso-week
16541 ;; There was an iso week
16542 (require 'cal-iso)
16543 (setq futurep nil)
16544 (setq year (or iso-year year)
16545 day (or iso-weekday wday 1)
16546 wday nil ; to make sure that the trigger below does not match
16547 iso-date (calendar-gregorian-from-absolute
16548 (calendar-absolute-from-iso
16549 (list iso-week day year))))
16550 ; FIXME: Should we also push ISO weeks into the future?
16551 ; (when (and org-read-date-prefer-future
16552 ; (not iso-year)
16553 ; (< (calendar-absolute-from-gregorian iso-date)
16554 ; (time-to-days (current-time))))
16555 ; (setq year (1+ year)
16556 ; iso-date (calendar-gregorian-from-absolute
16557 ; (calendar-absolute-from-iso
16558 ; (list iso-week day year)))))
16559 (setq month (car iso-date)
16560 year (nth 2 iso-date)
16561 day (nth 1 iso-date)))
16562 (deltan
16563 (setq futurep nil)
16564 (unless deltadef
16565 (let ((now (decode-time (current-time))))
16566 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16567 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16568 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16569 ((equal deltaw "m") (setq month (+ month deltan)))
16570 ((equal deltaw "y") (setq year (+ year deltan)))))
16571 ((and wday (not (nth 3 tl)))
16572 ;; Weekday was given, but no day, so pick that day in the week
16573 ;; on or after the derived date.
16574 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16575 (unless (equal wday wday1)
16576 (setq day (+ day (% (- wday wday1 -7) 7))))))
16577 (if (and (boundp 'org-time-was-given)
16578 (nth 2 tl))
16579 (setq org-time-was-given t))
16580 (if (< year 100) (setq year (+ 2000 year)))
16581 ;; Check of the date is representable
16582 (if org-read-date-force-compatible-dates
16583 (progn
16584 (if (< year 1970)
16585 (setq year 1970 org-read-date-analyze-forced-year t))
16586 (if (> year 2037)
16587 (setq year 2037 org-read-date-analyze-forced-year t)))
16588 (condition-case nil
16589 (ignore (encode-time second minute hour day month year))
16590 (error
16591 (setq year (nth 5 org-defdecode))
16592 (setq org-read-date-analyze-forced-year t))))
16593 (setq org-read-date-analyze-futurep futurep)
16594 (list second minute hour day month year)))
16596 (defvar parse-time-weekdays)
16597 (defun org-read-date-get-relative (s today default)
16598 "Check string S for special relative date string.
16599 TODAY and DEFAULT are internal times, for today and for a default.
16600 Return shift list (N what def-flag)
16601 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16602 N is the number of WHATs to shift.
16603 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16604 the DEFAULT date rather than TODAY."
16605 (require 'parse-time)
16606 (when (and
16607 (string-match
16608 (concat
16609 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16610 "\\([0-9]+\\)?"
16611 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16612 "\\([ \t]\\|$\\)") s)
16613 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16614 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16615 (string-to-char (substring (match-string 1 s) -1))
16616 ?+))
16617 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16618 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16619 (what (if (match-end 3) (match-string 3 s) "d"))
16620 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16621 (date (if rel default today))
16622 (wday (nth 6 (decode-time date)))
16623 delta)
16624 (if wday1
16625 (progn
16626 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16627 (if (= delta 0) (setq delta 7))
16628 (if (= dir ?-)
16629 (progn
16630 (setq delta (- delta 7))
16631 (if (= delta 0) (setq delta -7))))
16632 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16633 (list delta "d" rel))
16634 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16636 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16637 "Turn a user-specified date into the internal representation.
16638 The internal representation needed by the calendar is (month day year).
16639 This is a wrapper to handle the brain-dead convention in calendar that
16640 user function argument order change dependent on argument order."
16641 (if (boundp 'calendar-date-style)
16642 (cond
16643 ((eq calendar-date-style 'american)
16644 (list arg1 arg2 arg3))
16645 ((eq calendar-date-style 'european)
16646 (list arg2 arg1 arg3))
16647 ((eq calendar-date-style 'iso)
16648 (list arg2 arg3 arg1)))
16649 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16650 (if (org-bound-and-true-p european-calendar-style)
16651 (list arg2 arg1 arg3)
16652 (list arg1 arg2 arg3)))))
16654 (defun org-eval-in-calendar (form &optional keepdate)
16655 "Eval FORM in the calendar window and return to current window.
16656 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16657 otherwise stick to the current value of `org-ans2'."
16658 (let ((sf (selected-frame))
16659 (sw (selected-window)))
16660 (select-window (get-buffer-window "*Calendar*" t))
16661 (eval form)
16662 (when (and (not keepdate) (calendar-cursor-to-date))
16663 (let* ((date (calendar-cursor-to-date))
16664 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16665 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16666 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16667 (select-window sw)
16668 (org-select-frame-set-input-focus sf)))
16670 (defun org-calendar-select ()
16671 "Return to `org-read-date' with the date currently selected.
16672 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16673 (interactive)
16674 (when (calendar-cursor-to-date)
16675 (let* ((date (calendar-cursor-to-date))
16676 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16677 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16678 (if (active-minibuffer-window) (exit-minibuffer))))
16680 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16681 "Insert a date stamp for the date given by the internal TIME.
16682 WITH-HM means use the stamp format that includes the time of the day.
16683 INACTIVE means use square brackets instead of angular ones, so that the
16684 stamp will not contribute to the agenda.
16685 PRE and POST are optional strings to be inserted before and after the
16686 stamp.
16687 The command returns the inserted time stamp."
16688 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16689 stamp)
16690 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16691 (insert-before-markers (or pre ""))
16692 (when (listp extra)
16693 (setq extra (car extra))
16694 (if (and (stringp extra)
16695 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16696 (setq extra (format "-%02d:%02d"
16697 (string-to-number (match-string 1 extra))
16698 (string-to-number (match-string 2 extra))))
16699 (setq extra nil)))
16700 (when extra
16701 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16702 (insert-before-markers (setq stamp (format-time-string fmt time)))
16703 (insert-before-markers (or post ""))
16704 (setq org-last-inserted-timestamp stamp)))
16706 (defun org-toggle-time-stamp-overlays ()
16707 "Toggle the use of custom time stamp formats."
16708 (interactive)
16709 (setq org-display-custom-times (not org-display-custom-times))
16710 (unless org-display-custom-times
16711 (let ((p (point-min)) (bmp (buffer-modified-p)))
16712 (while (setq p (next-single-property-change p 'display))
16713 (if (and (get-text-property p 'display)
16714 (eq (get-text-property p 'face) 'org-date))
16715 (remove-text-properties
16716 p (setq p (next-single-property-change p 'display))
16717 '(display t))))
16718 (set-buffer-modified-p bmp)))
16719 (if (featurep 'xemacs)
16720 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16721 (org-restart-font-lock)
16722 (setq org-table-may-need-update t)
16723 (if org-display-custom-times
16724 (message "Time stamps are overlaid with custom format")
16725 (message "Time stamp overlays removed")))
16727 (defun org-display-custom-time (beg end)
16728 "Overlay modified time stamp format over timestamp between BEG and END."
16729 (let* ((ts (buffer-substring beg end))
16730 t1 w1 with-hm tf time str w2 (off 0))
16731 (save-match-data
16732 (setq t1 (org-parse-time-string ts t))
16733 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16734 (setq off (- (match-end 0) (match-beginning 0)))))
16735 (setq end (- end off))
16736 (setq w1 (- end beg)
16737 with-hm (and (nth 1 t1) (nth 2 t1))
16738 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16739 time (org-fix-decoded-time t1)
16740 str (org-add-props
16741 (format-time-string
16742 (substring tf 1 -1) (apply 'encode-time time))
16743 nil 'mouse-face 'highlight)
16744 w2 (length str))
16745 (if (not (= w2 w1))
16746 (add-text-properties (1+ beg) (+ 2 beg)
16747 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16748 (if (featurep 'xemacs)
16749 (progn
16750 (put-text-property beg end 'invisible t)
16751 (put-text-property beg end 'end-glyph (make-glyph str)))
16752 (put-text-property beg end 'display str))))
16754 (defun org-translate-time (string)
16755 "Translate all timestamps in STRING to custom format.
16756 But do this only if the variable `org-display-custom-times' is set."
16757 (when org-display-custom-times
16758 (save-match-data
16759 (let* ((start 0)
16760 (re org-ts-regexp-both)
16761 t1 with-hm inactive tf time str beg end)
16762 (while (setq start (string-match re string start))
16763 (setq beg (match-beginning 0)
16764 end (match-end 0)
16765 t1 (save-match-data
16766 (org-parse-time-string (substring string beg end) t))
16767 with-hm (and (nth 1 t1) (nth 2 t1))
16768 inactive (equal (substring string beg (1+ beg)) "[")
16769 tf (funcall (if with-hm 'cdr 'car)
16770 org-time-stamp-custom-formats)
16771 time (org-fix-decoded-time t1)
16772 str (format-time-string
16773 (concat
16774 (if inactive "[" "<") (substring tf 1 -1)
16775 (if inactive "]" ">"))
16776 (apply 'encode-time time))
16777 string (replace-match str t t string)
16778 start (+ start (length str)))))))
16779 string)
16781 (defun org-fix-decoded-time (time)
16782 "Set 0 instead of nil for the first 6 elements of time.
16783 Don't touch the rest."
16784 (let ((n 0))
16785 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16787 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16789 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16790 "Difference between TIMESTAMP-STRING and now in days.
16791 If SECONDS is non-nil, return the difference in seconds."
16792 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16793 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16794 (funcall fdiff (current-time)))))
16796 (defun org-deadline-close (timestamp-string &optional ndays)
16797 "Is the time in TIMESTAMP-STRING close to the current date?"
16798 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16799 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16800 (not (org-entry-is-done-p))))
16802 (defun org-get-wdays (ts &optional delay zero-delay)
16803 "Get the deadline lead time appropriate for timestring TS.
16804 When DELAY is non-nil, get the delay time for scheduled items
16805 instead of the deadline lead time. When ZERO-DELAY is non-nil
16806 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16807 don't try to find the delay cookie in the scheduled timestamp."
16808 (let ((tv (if delay org-scheduled-delay-days
16809 org-deadline-warning-days)))
16810 (cond
16811 ((or (and delay (< tv 0))
16812 (and delay zero-delay (<= tv 0))
16813 (and (not delay) (<= tv 0)))
16814 ;; Enforce this value no matter what
16815 (- tv))
16816 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16817 ;; lead time is specified.
16818 (floor (* (string-to-number (match-string 1 ts))
16819 (cdr (assoc (match-string 2 ts)
16820 '(("d" . 1) ("w" . 7)
16821 ("m" . 30.4) ("y" . 365.25)
16822 ("h" . 0.041667)))))))
16823 ;; go for the default.
16824 (t tv))))
16826 (defun org-calendar-select-mouse (ev)
16827 "Return to `org-read-date' with the date currently selected.
16828 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16829 (interactive "e")
16830 (mouse-set-point ev)
16831 (when (calendar-cursor-to-date)
16832 (let* ((date (calendar-cursor-to-date))
16833 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16834 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16835 (if (active-minibuffer-window) (exit-minibuffer))))
16837 (defun org-check-deadlines (ndays)
16838 "Check if there are any deadlines due or past due.
16839 A deadline is considered due if it happens within `org-deadline-warning-days'
16840 days from today's date. If the deadline appears in an entry marked DONE,
16841 it is not shown. The prefix arg NDAYS can be used to test that many
16842 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16843 (interactive "P")
16844 (let* ((org-warn-days
16845 (cond
16846 ((equal ndays '(4)) 100000)
16847 (ndays (prefix-numeric-value ndays))
16848 (t (abs org-deadline-warning-days))))
16849 (case-fold-search nil)
16850 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16851 (callback
16852 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16854 (message "%d deadlines past-due or due within %d days"
16855 (org-occur regexp nil callback)
16856 org-warn-days)))
16858 (defsubst org-re-timestamp (type)
16859 "Return a regexp for timestamp TYPE.
16860 Allowed values for TYPE are:
16862 all: all timestamps
16863 active: only active timestamps (<...>)
16864 inactive: only inactive timestamps ([...])
16865 scheduled: only scheduled timestamps
16866 deadline: only deadline timestamps
16867 closed: only closed time-stamps
16869 When TYPE is nil, fall back on returning a regexp that matches
16870 both scheduled and deadline timestamps."
16871 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16872 ((eq type 'active) org-ts-regexp)
16873 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16874 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16875 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16876 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16877 ((eq type 'scheduled-or-deadline)
16878 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16880 (defun org-check-before-date (date)
16881 "Check if there are deadlines or scheduled entries before DATE."
16882 (interactive (list (org-read-date)))
16883 (let ((case-fold-search nil)
16884 (regexp (org-re-timestamp org-ts-type))
16885 (callback
16886 (lambda () (time-less-p
16887 (org-time-string-to-time (match-string 1))
16888 (org-time-string-to-time date)))))
16889 (message "%d entries before %s"
16890 (org-occur regexp nil callback) date)))
16892 (defun org-check-after-date (date)
16893 "Check if there are deadlines or scheduled entries after DATE."
16894 (interactive (list (org-read-date)))
16895 (let ((case-fold-search nil)
16896 (regexp (org-re-timestamp org-ts-type))
16897 (callback
16898 (lambda () (not
16899 (time-less-p
16900 (org-time-string-to-time (match-string 1))
16901 (org-time-string-to-time date))))))
16902 (message "%d entries after %s"
16903 (org-occur regexp nil callback) date)))
16905 (defun org-check-dates-range (start-date end-date)
16906 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16907 (interactive (list (org-read-date nil nil nil "Range starts")
16908 (org-read-date nil nil nil "Range end")))
16909 (let ((case-fold-search nil)
16910 (regexp (org-re-timestamp org-ts-type))
16911 (callback
16912 (lambda ()
16913 (let ((match (match-string 1)))
16914 (and
16915 (not (time-less-p
16916 (org-time-string-to-time match)
16917 (org-time-string-to-time start-date)))
16918 (time-less-p
16919 (org-time-string-to-time match)
16920 (org-time-string-to-time end-date)))))))
16921 (message "%d entries between %s and %s"
16922 (org-occur regexp nil callback) start-date end-date)))
16924 (defun org-evaluate-time-range (&optional to-buffer)
16925 "Evaluate a time range by computing the difference between start and end.
16926 Normally the result is just printed in the echo area, but with prefix arg
16927 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16928 If the time range is actually in a table, the result is inserted into the
16929 next column.
16930 For time difference computation, a year is assumed to be exactly 365
16931 days in order to avoid rounding problems."
16932 (interactive "P")
16934 (org-clock-update-time-maybe)
16935 (save-excursion
16936 (unless (org-at-date-range-p t)
16937 (goto-char (point-at-bol))
16938 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16939 (if (not (org-at-date-range-p t))
16940 (user-error "Not at a time-stamp range, and none found in current line")))
16941 (let* ((ts1 (match-string 1))
16942 (ts2 (match-string 2))
16943 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16944 (match-end (match-end 0))
16945 (time1 (org-time-string-to-time ts1))
16946 (time2 (org-time-string-to-time ts2))
16947 (t1 (org-float-time time1))
16948 (t2 (org-float-time time2))
16949 (diff (abs (- t2 t1)))
16950 (negative (< (- t2 t1) 0))
16951 ;; (ys (floor (* 365 24 60 60)))
16952 (ds (* 24 60 60))
16953 (hs (* 60 60))
16954 (fy "%dy %dd %02d:%02d")
16955 (fy1 "%dy %dd")
16956 (fd "%dd %02d:%02d")
16957 (fd1 "%dd")
16958 (fh "%02d:%02d")
16959 y d h m align)
16960 (if havetime
16961 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16963 d (floor (/ diff ds)) diff (mod diff ds)
16964 h (floor (/ diff hs)) diff (mod diff hs)
16965 m (floor (/ diff 60)))
16966 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16968 d (floor (+ (/ diff ds) 0.5))
16969 h 0 m 0))
16970 (if (not to-buffer)
16971 (message "%s" (org-make-tdiff-string y d h m))
16972 (if (org-at-table-p)
16973 (progn
16974 (goto-char match-end)
16975 (setq align t)
16976 (and (looking-at " *|") (goto-char (match-end 0))))
16977 (goto-char match-end))
16978 (if (looking-at
16979 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16980 (replace-match ""))
16981 (if negative (insert " -"))
16982 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16983 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16984 (insert " " (format fh h m))))
16985 (if align (org-table-align))
16986 (message "Time difference inserted")))))
16988 (defun org-make-tdiff-string (y d h m)
16989 (let ((fmt "")
16990 (l nil))
16991 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16992 l (push y l)))
16993 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16994 l (push d l)))
16995 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16996 l (push h l)))
16997 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16998 l (push m l)))
16999 (apply 'format fmt (nreverse l))))
17001 (defun org-time-string-to-time (s &optional buffer pos)
17002 "Convert a timestamp string into internal time."
17003 (condition-case errdata
17004 (apply 'encode-time (org-parse-time-string s))
17005 (error (error "Bad timestamp `%s'%s\nError was: %s"
17006 s (if (not (and buffer pos))
17008 (format " at %d in buffer `%s'" pos buffer))
17009 (cdr errdata)))))
17011 (defun org-time-string-to-seconds (s)
17012 "Convert a timestamp string to a number of seconds."
17013 (org-float-time (org-time-string-to-time s)))
17015 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17016 "Convert a time stamp to an absolute day number.
17017 If there is a specifier for a cyclic time stamp, get the closest
17018 date to DAYNR.
17019 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17020 The variable `date' is bound by the calendar when this is called."
17021 (cond
17022 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17023 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17024 daynr
17025 (+ daynr 1000)))
17026 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17027 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17028 (time-to-days (current-time))) (match-string 0 s)
17029 prefer show-all))
17030 (t (time-to-days
17031 (condition-case errdata
17032 (apply 'encode-time (org-parse-time-string s))
17033 (error (error "Bad timestamp `%s'%s\nError was: %s"
17034 s (if (not (and buffer pos))
17036 (format " at %d in buffer `%s'" pos buffer))
17037 (cdr errdata))))))))
17039 (defun org-days-to-iso-week (days)
17040 "Return the iso week number."
17041 (require 'cal-iso)
17042 (car (calendar-iso-from-absolute days)))
17044 (defun org-small-year-to-year (year)
17045 "Convert 2-digit years into 4-digit years.
17046 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17047 The year 2000 cannot be abbreviated. Any year larger than 99
17048 is returned unchanged."
17049 (if (< year 38)
17050 (setq year (+ 2000 year))
17051 (if (< year 100)
17052 (setq year (+ 1900 year))))
17053 year)
17055 (defun org-time-from-absolute (d)
17056 "Return the time corresponding to date D.
17057 D may be an absolute day number, or a calendar-type list (month day year)."
17058 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17059 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17061 (defun org-calendar-holiday ()
17062 "List of holidays, for Diary display in Org-mode."
17063 (require 'holidays)
17064 (let ((hl (funcall
17065 (if (fboundp 'calendar-check-holidays)
17066 'calendar-check-holidays 'check-calendar-holidays) date)))
17067 (if hl (mapconcat 'identity hl "; "))))
17069 (defun org-diary-sexp-entry (sexp entry date)
17070 "Process a SEXP diary ENTRY for DATE."
17071 (require 'diary-lib)
17072 (let ((result (if calendar-debug-sexp
17073 (let ((stack-trace-on-error t))
17074 (eval (car (read-from-string sexp))))
17075 (condition-case nil
17076 (eval (car (read-from-string sexp)))
17077 (error
17078 (beep)
17079 (message "Bad sexp at line %d in %s: %s"
17080 (org-current-line)
17081 (buffer-file-name) sexp)
17082 (sleep-for 2))))))
17083 (cond ((stringp result) (split-string result "; "))
17084 ((and (consp result)
17085 (not (consp (cdr result)))
17086 (stringp (cdr result))) (cdr result))
17087 ((and (consp result)
17088 (stringp (car result))) result)
17089 (result entry))))
17091 (defun org-diary-to-ical-string (frombuf)
17092 "Get iCalendar entries from diary entries in buffer FROMBUF.
17093 This uses the icalendar.el library."
17094 (let* ((tmpdir (if (featurep 'xemacs)
17095 (temp-directory)
17096 temporary-file-directory))
17097 (tmpfile (make-temp-name
17098 (expand-file-name "orgics" tmpdir)))
17099 buf rtn b e)
17100 (with-current-buffer frombuf
17101 (icalendar-export-region (point-min) (point-max) tmpfile)
17102 (setq buf (find-buffer-visiting tmpfile))
17103 (set-buffer buf)
17104 (goto-char (point-min))
17105 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17106 (setq b (match-beginning 0)))
17107 (goto-char (point-max))
17108 (if (re-search-backward "^END:VEVENT" nil t)
17109 (setq e (match-end 0)))
17110 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17111 (kill-buffer buf)
17112 (delete-file tmpfile)
17113 rtn))
17115 (defun org-closest-date (start current change prefer show-all)
17116 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17117 When PREFER is `past', return a date that is either CURRENT or past.
17118 When PREFER is `future', return a date that is either CURRENT or future.
17119 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17120 ;; Make the proper lists from the dates
17121 (catch 'exit
17122 (let ((a1 '(("h" . hour)
17123 ("d" . day)
17124 ("w" . week)
17125 ("m" . month)
17126 ("y" . year)))
17127 (shour (nth 2 (org-parse-time-string start)))
17128 dn dw sday cday n1 n2 n0
17129 d m y y1 y2 date1 date2 nmonths nm ny m2)
17131 (setq start (org-date-to-gregorian start)
17132 current (org-date-to-gregorian
17133 (if show-all
17134 current
17135 (time-to-days (current-time))))
17136 sday (calendar-absolute-from-gregorian start)
17137 cday (calendar-absolute-from-gregorian current))
17139 (if (<= cday sday) (throw 'exit sday))
17141 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17142 (setq dn (string-to-number (match-string 1 change))
17143 dw (cdr (assoc (match-string 2 change) a1)))
17144 (user-error "Invalid change specifier: %s" change))
17145 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17146 (cond
17147 ((eq dw 'hour)
17148 (let ((missing-hours
17149 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17150 dn)))
17151 (setq n1 (if (zerop missing-hours) cday
17152 (- cday (1+ (floor (/ missing-hours 24)))))
17153 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17154 ((eq dw 'day)
17155 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17156 n2 (+ n1 dn)))
17157 ((eq dw 'year)
17158 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17159 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17160 (setq date1 (list m d y1)
17161 n1 (calendar-absolute-from-gregorian date1)
17162 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17163 n2 (calendar-absolute-from-gregorian date2)))
17164 ((eq dw 'month)
17165 ;; approx number of month between the two dates
17166 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17167 ;; How often does dn fit in there?
17168 (setq d (nth 1 start) m (car start) y (nth 2 start)
17169 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17170 m (+ m nm)
17171 ny (floor (/ m 12))
17172 y (+ y ny)
17173 m (- m (* ny 12)))
17174 (while (> m 12) (setq m (- m 12) y (1+ y)))
17175 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17176 (setq m2 (+ m dn) y2 y)
17177 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17178 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17179 (while (<= n2 cday)
17180 (setq n1 n2 m m2 y y2)
17181 (setq m2 (+ m dn) y2 y)
17182 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17183 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17184 ;; Make sure n1 is the earlier date
17185 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17186 (if show-all
17187 (cond
17188 ((eq prefer 'past) (if (= cday n2) n2 n1))
17189 ((eq prefer 'future) (if (= cday n1) n1 n2))
17190 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17191 (cond
17192 ((eq prefer 'past) (if (= cday n2) n2 n1))
17193 ((eq prefer 'future) (if (= cday n1) n1 n2))
17194 (t (if (= cday n1) n1 n2)))))))
17196 (defun org-date-to-gregorian (date)
17197 "Turn any specification of DATE into a Gregorian date for the calendar."
17198 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17199 ((and (listp date) (= (length date) 3)) date)
17200 ((stringp date)
17201 (setq date (org-parse-time-string date))
17202 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17203 ((listp date)
17204 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17206 (defun org-parse-time-string (s &optional nodefault)
17207 "Parse the standard Org-mode time string.
17208 This should be a lot faster than the normal `parse-time-string'.
17209 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17210 hour and minute fields will be nil if not given."
17211 (cond ((string-match org-ts-regexp0 s)
17212 (list 0
17213 (if (or (match-beginning 8) (not nodefault))
17214 (string-to-number (or (match-string 8 s) "0")))
17215 (if (or (match-beginning 7) (not nodefault))
17216 (string-to-number (or (match-string 7 s) "0")))
17217 (string-to-number (match-string 4 s))
17218 (string-to-number (match-string 3 s))
17219 (string-to-number (match-string 2 s))
17220 nil nil nil))
17221 ((string-match "^<[^>]+>$" s)
17222 (decode-time (seconds-to-time (org-matcher-time s))))
17223 (t (error "Not a standard Org-mode time string: %s" s))))
17225 (defun org-timestamp-up (&optional arg)
17226 "Increase the date item at the cursor by one.
17227 If the cursor is on the year, change the year. If it is on the month,
17228 the day or the time, change that.
17229 With prefix ARG, change by that many units."
17230 (interactive "p")
17231 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17233 (defun org-timestamp-down (&optional arg)
17234 "Decrease the date item at the cursor by one.
17235 If the cursor is on the year, change the year. If it is on the month,
17236 the day or the time, change that.
17237 With prefix ARG, change by that many units."
17238 (interactive "p")
17239 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17241 (defun org-timestamp-up-day (&optional arg)
17242 "Increase the date in the time stamp by one day.
17243 With prefix ARG, change that many days."
17244 (interactive "p")
17245 (if (and (not (org-at-timestamp-p t))
17246 (org-at-heading-p))
17247 (org-todo 'up)
17248 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17250 (defun org-timestamp-down-day (&optional arg)
17251 "Decrease the date in the time stamp by one day.
17252 With prefix ARG, change that many days."
17253 (interactive "p")
17254 (if (and (not (org-at-timestamp-p t))
17255 (org-at-heading-p))
17256 (org-todo 'down)
17257 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17259 (defun org-at-timestamp-p (&optional inactive-ok)
17260 "Determine if the cursor is in or at a timestamp."
17261 (interactive)
17262 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17263 (pos (point))
17264 (ans (or (looking-at tsr)
17265 (save-excursion
17266 (skip-chars-backward "^[<\n\r\t")
17267 (if (> (point) (point-min)) (backward-char 1))
17268 (and (looking-at tsr)
17269 (> (- (match-end 0) pos) -1))))))
17270 (and ans
17271 (boundp 'org-ts-what)
17272 (setq org-ts-what
17273 (cond
17274 ((= pos (match-beginning 0)) 'bracket)
17275 ;; Point is considered to be "on the bracket" whether
17276 ;; it's really on it or right after it.
17277 ((= pos (1- (match-end 0))) 'bracket)
17278 ((= pos (match-end 0)) 'after)
17279 ((org-pos-in-match-range pos 2) 'year)
17280 ((org-pos-in-match-range pos 3) 'month)
17281 ((org-pos-in-match-range pos 7) 'hour)
17282 ((org-pos-in-match-range pos 8) 'minute)
17283 ((or (org-pos-in-match-range pos 4)
17284 (org-pos-in-match-range pos 5)) 'day)
17285 ((and (> pos (or (match-end 8) (match-end 5)))
17286 (< pos (match-end 0)))
17287 (- pos (or (match-end 8) (match-end 5))))
17288 (t 'day))))
17289 ans))
17291 (defun org-toggle-timestamp-type ()
17292 "Toggle the type (<active> or [inactive]) of a time stamp."
17293 (interactive)
17294 (when (org-at-timestamp-p t)
17295 (let ((beg (match-beginning 0)) (end (match-end 0))
17296 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17297 (save-excursion
17298 (goto-char beg)
17299 (while (re-search-forward "[][<>]" end t)
17300 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17301 t t)))
17302 (message "Timestamp is now %sactive"
17303 (if (equal (char-after beg) ?<) "" "in")))))
17305 (defun org-at-clock-log-p nil
17306 "Is the cursor on the clock log line?"
17307 (save-excursion
17308 (move-beginning-of-line 1)
17309 (looking-at "^[ \t]*CLOCK:")))
17311 (defvar org-clock-history) ; defined in org-clock.el
17312 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17313 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17314 "Change the date in the time stamp at point.
17315 The date will be changed by N times WHAT. WHAT can be `day', `month',
17316 `year', `minute', `second'. If WHAT is not given, the cursor position
17317 in the timestamp determines what will be changed.
17318 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17319 (let ((origin (point)) origin-cat
17320 with-hm inactive
17321 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17322 org-ts-what
17323 extra rem
17324 ts time time0 fixnext clrgx)
17325 (if (not (org-at-timestamp-p t))
17326 (user-error "Not at a timestamp"))
17327 (if (and (not what) (eq org-ts-what 'bracket))
17328 (org-toggle-timestamp-type)
17329 ;; Point isn't on brackets. Remember the part of the time-stamp
17330 ;; the point was in. Indeed, size of time-stamps may change,
17331 ;; but point must be kept in the same category nonetheless.
17332 (setq origin-cat org-ts-what)
17333 (if (and (not what) (not (eq org-ts-what 'day))
17334 org-display-custom-times
17335 (get-text-property (point) 'display)
17336 (not (get-text-property (1- (point)) 'display)))
17337 (setq org-ts-what 'day))
17338 (setq org-ts-what (or what org-ts-what)
17339 inactive (= (char-after (match-beginning 0)) ?\[)
17340 ts (match-string 0))
17341 (replace-match "")
17342 (when (string-match
17343 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17345 (setq extra (match-string 1 ts))
17346 (if suppress-tmp-delay
17347 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17348 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17349 (setq with-hm t))
17350 (setq time0 (org-parse-time-string ts))
17351 (when (and updown
17352 (eq org-ts-what 'minute)
17353 (not current-prefix-arg))
17354 ;; This looks like s-up and s-down. Change by one rounding step.
17355 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17356 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17357 (setcar (cdr time0) (+ (nth 1 time0)
17358 (if (> n 0) (- rem) (- dm rem))))))
17359 (setq time
17360 (encode-time (or (car time0) 0)
17361 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17362 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17363 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17364 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17365 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17366 (nthcdr 6 time0)))
17367 (when (and (member org-ts-what '(hour minute))
17368 extra
17369 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17370 (setq extra (org-modify-ts-extra
17371 extra
17372 (if (eq org-ts-what 'hour) 2 5)
17373 n dm)))
17374 (when (integerp org-ts-what)
17375 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17376 (if (eq what 'calendar)
17377 (let ((cal-date (org-get-date-from-calendar)))
17378 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17379 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17380 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17381 (setcar time0 (or (car time0) 0))
17382 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17383 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17384 (setq time (apply 'encode-time time0))))
17385 ;; Insert the new time-stamp, and ensure point stays in the same
17386 ;; category as before (i.e. not after the last position in that
17387 ;; category).
17388 (let ((pos (point)))
17389 ;; Stay before inserted string. `save-excursion' is of no use.
17390 (setq org-last-changed-timestamp
17391 (org-insert-time-stamp time with-hm inactive nil nil extra))
17392 (goto-char pos))
17393 (save-match-data
17394 (looking-at org-ts-regexp3)
17395 (goto-char (cond
17396 ;; `day' category ends before `hour' if any, or at
17397 ;; the end of the day name.
17398 ((eq origin-cat 'day)
17399 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17400 ((eq origin-cat 'hour) (min (match-end 7) origin))
17401 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17402 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17403 ;; `year' and `month' have both fixed size: point
17404 ;; couldn't have moved into another part.
17405 (t origin))))
17406 ;; Update clock if on a CLOCK line.
17407 (org-clock-update-time-maybe)
17408 ;; Maybe adjust the closest clock in `org-clock-history'
17409 (when org-clock-adjust-closest
17410 (if (not (and (org-at-clock-log-p)
17411 (< 1 (length (delq nil (mapcar 'marker-position
17412 org-clock-history))))))
17413 (message "No clock to adjust")
17414 (cond ((save-excursion ; fix previous clock?
17415 (re-search-backward org-ts-regexp0 nil t)
17416 (org-looking-back (concat org-clock-string " \\[")))
17417 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17418 ((save-excursion ; fix next clock?
17419 (re-search-backward org-ts-regexp0 nil t)
17420 (looking-at (concat org-ts-regexp0 "\\] =>")))
17421 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17422 (save-window-excursion
17423 ;; Find closest clock to point, adjust the previous/next one in history
17424 (let* ((p (save-excursion (org-back-to-heading t)))
17425 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17426 (clfixnth
17427 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17428 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17429 (if (not clfixpos)
17430 (message "No clock to adjust")
17431 (save-excursion
17432 (org-goto-marker-or-bmk clfixpos)
17433 (org-show-subtree)
17434 (when (re-search-forward clrgx nil t)
17435 (goto-char (match-beginning 1))
17436 (let (org-clock-adjust-closest)
17437 (org-timestamp-change n org-ts-what updown))
17438 (message "Clock adjusted in %s for heading: %s"
17439 (file-name-nondirectory (buffer-file-name))
17440 (org-get-heading t t)))))))))
17441 ;; Try to recenter the calendar window, if any.
17442 (if (and org-calendar-follow-timestamp-change
17443 (get-buffer-window "*Calendar*" t)
17444 (memq org-ts-what '(day month year)))
17445 (org-recenter-calendar (time-to-days time))))))
17447 (defun org-modify-ts-extra (s pos n dm)
17448 "Change the different parts of the lead-time and repeat fields in timestamp."
17449 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17450 ng h m new rem)
17451 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17452 (cond
17453 ((or (org-pos-in-match-range pos 2)
17454 (org-pos-in-match-range pos 3))
17455 (setq m (string-to-number (match-string 3 s))
17456 h (string-to-number (match-string 2 s)))
17457 (if (org-pos-in-match-range pos 2)
17458 (setq h (+ h n))
17459 (setq n (* dm (org-no-warnings (signum n))))
17460 (when (not (= 0 (setq rem (% m dm))))
17461 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17462 (setq m (+ m n)))
17463 (if (< m 0) (setq m (+ m 60) h (1- h)))
17464 (if (> m 59) (setq m (- m 60) h (1+ h)))
17465 (setq h (min 24 (max 0 h)))
17466 (setq ng 1 new (format "-%02d:%02d" h m)))
17467 ((org-pos-in-match-range pos 6)
17468 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17469 ((org-pos-in-match-range pos 5)
17470 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17472 ((org-pos-in-match-range pos 9)
17473 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17474 ((org-pos-in-match-range pos 8)
17475 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17477 (when ng
17478 (setq s (concat
17479 (substring s 0 (match-beginning ng))
17481 (substring s (match-end ng))))))
17484 (defun org-recenter-calendar (date)
17485 "If the calendar is visible, recenter it to DATE."
17486 (let ((cwin (get-buffer-window "*Calendar*" t)))
17487 (when cwin
17488 (let ((calendar-move-hook nil))
17489 (with-selected-window cwin
17490 (calendar-goto-date (if (listp date) date
17491 (calendar-gregorian-from-absolute date))))))))
17493 (defun org-goto-calendar (&optional arg)
17494 "Go to the Emacs calendar at the current date.
17495 If there is a time stamp in the current line, go to that date.
17496 A prefix ARG can be used to force the current date."
17497 (interactive "P")
17498 (let ((tsr org-ts-regexp) diff
17499 (calendar-move-hook nil)
17500 (calendar-view-holidays-initially-flag nil)
17501 (calendar-view-diary-initially-flag nil))
17502 (if (or (org-at-timestamp-p)
17503 (save-excursion
17504 (beginning-of-line 1)
17505 (looking-at (concat ".*" tsr))))
17506 (let ((d1 (time-to-days (current-time)))
17507 (d2 (time-to-days
17508 (org-time-string-to-time (match-string 1)))))
17509 (setq diff (- d2 d1))))
17510 (calendar)
17511 (calendar-goto-today)
17512 (if (and diff (not arg)) (calendar-forward-day diff))))
17514 (defun org-get-date-from-calendar ()
17515 "Return a list (month day year) of date at point in calendar."
17516 (with-current-buffer "*Calendar*"
17517 (save-match-data
17518 (calendar-cursor-to-date))))
17520 (defun org-date-from-calendar ()
17521 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17522 If there is already a time stamp at the cursor position, update it."
17523 (interactive)
17524 (if (org-at-timestamp-p t)
17525 (org-timestamp-change 0 'calendar)
17526 (let ((cal-date (org-get-date-from-calendar)))
17527 (org-insert-time-stamp
17528 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17530 (defcustom org-effort-durations
17531 `(("h" . 60)
17532 ("d" . ,(* 60 8))
17533 ("w" . ,(* 60 8 5))
17534 ("m" . ,(* 60 8 5 4))
17535 ("y" . ,(* 60 8 5 40)))
17536 "Conversion factor to minutes for an effort modifier.
17538 Each entry has the form (MODIFIER . MINUTES).
17540 In an effort string, a number followed by MODIFIER is multiplied
17541 by the specified number of MINUTES to obtain an effort in
17542 minutes.
17544 For example, if the value of this variable is ((\"hours\" . 60)), then an
17545 effort string \"2hours\" is equivalent to 120 minutes."
17546 :group 'org-agenda
17547 :version "24.1"
17548 :type '(alist :key-type (string :tag "Modifier")
17549 :value-type (number :tag "Minutes")))
17551 (defun org-minutes-to-clocksum-string (m)
17552 "Format number of minutes as a clocksum string.
17553 The format is determined by `org-time-clocksum-format',
17554 `org-time-clocksum-use-fractional' and
17555 `org-time-clocksum-fractional-format' and
17556 `org-time-clocksum-use-effort-durations'."
17557 (let ((clocksum "")
17558 (m (round m)) ; Don't allow fractions of minutes
17559 h d w mo y fmt n)
17560 (setq h (if org-time-clocksum-use-effort-durations
17561 (cdr (assoc "h" org-effort-durations)) 60)
17562 d (if org-time-clocksum-use-effort-durations
17563 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17564 w (if org-time-clocksum-use-effort-durations
17565 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17566 mo (if org-time-clocksum-use-effort-durations
17567 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17568 y (if org-time-clocksum-use-effort-durations
17569 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17570 ;; fractional format
17571 (if org-time-clocksum-use-fractional
17572 (cond
17573 ;; single format string
17574 ((stringp org-time-clocksum-fractional-format)
17575 (format org-time-clocksum-fractional-format (/ m (float h))))
17576 ;; choice of fractional formats for different time units
17577 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17578 (> (/ (truncate m) (* y d h)) 0))
17579 (format fmt (/ m (* y d (float h)))))
17580 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17581 (> (/ (truncate m) (* mo d h)) 0))
17582 (format fmt (/ m (* mo d (float h)))))
17583 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17584 (> (/ (truncate m) (* w d h)) 0))
17585 (format fmt (/ m (* w d (float h)))))
17586 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17587 (> (/ (truncate m) (* d h)) 0))
17588 (format fmt (/ m (* d (float h)))))
17589 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17590 (> (/ (truncate m) h) 0))
17591 (format fmt (/ m (float h))))
17592 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17593 (format fmt m))
17594 ;; fall back to smallest time unit with a format
17595 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17596 (format fmt (/ m (float h))))
17597 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17598 (format fmt (/ m (* d (float h)))))
17599 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17600 (format fmt (/ m (* w d (float h)))))
17601 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17602 (format fmt (/ m (* mo d (float h)))))
17603 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17604 (format fmt (/ m (* y d (float h))))))
17605 ;; standard (non-fractional) format, with single format string
17606 (if (stringp org-time-clocksum-format)
17607 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17608 ;; separate formats components
17609 (and (setq fmt (plist-get org-time-clocksum-format :years))
17610 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17611 (plist-get org-time-clocksum-format :require-years))
17612 (setq clocksum (concat clocksum (format fmt n))
17613 m (- m (* n y d h))))
17614 (and (setq fmt (plist-get org-time-clocksum-format :months))
17615 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17616 (plist-get org-time-clocksum-format :require-months))
17617 (setq clocksum (concat clocksum (format fmt n))
17618 m (- m (* n mo d h))))
17619 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17620 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17621 (plist-get org-time-clocksum-format :require-weeks))
17622 (setq clocksum (concat clocksum (format fmt n))
17623 m (- m (* n w d h))))
17624 (and (setq fmt (plist-get org-time-clocksum-format :days))
17625 (or (> (setq n (/ (truncate m) (* d h))) 0)
17626 (plist-get org-time-clocksum-format :require-days))
17627 (setq clocksum (concat clocksum (format fmt n))
17628 m (- m (* n d h))))
17629 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17630 (or (> (setq n (/ (truncate m) h)) 0)
17631 (plist-get org-time-clocksum-format :require-hours))
17632 (setq clocksum (concat clocksum (format fmt n))
17633 m (- m (* n h))))
17634 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17635 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17636 (setq clocksum (concat clocksum (format fmt m))))
17637 ;; return formatted time duration
17638 clocksum))))
17640 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17641 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17642 "Org mode version 8.0")
17644 (defun org-hours-to-clocksum-string (n)
17645 (org-minutes-to-clocksum-string (* n 60)))
17647 (defun org-hh:mm-string-to-minutes (s)
17648 "Convert a string H:MM to a number of minutes.
17649 If the string is just a number, interpret it as minutes.
17650 In fact, the first hh:mm or number in the string will be taken,
17651 there can be extra stuff in the string.
17652 If no number is found, the return value is 0."
17653 (cond
17654 ((integerp s) s)
17655 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17656 (+ (* (string-to-number (match-string 1 s)) 60)
17657 (string-to-number (match-string 2 s))))
17658 ((string-match "\\([0-9]+\\)" s)
17659 (string-to-number (match-string 1 s)))
17660 (t 0)))
17662 (defcustom org-image-actual-width t
17663 "Should we use the actual width of images when inlining them?
17665 When set to `t', always use the image width.
17667 When set to a number, use imagemagick (when available) to set
17668 the image's width to this value.
17670 When set to a number in a list, try to get the width from any
17671 #+ATTR.* keyword if it matches a width specification like
17673 #+ATTR_HTML: :width 300px
17675 and fall back on that number if none is found.
17677 When set to nil, try to get the width from an #+ATTR.* keyword
17678 and fall back on the original width if none is found.
17680 This requires Emacs >= 24.1, build with imagemagick support."
17681 :group 'org-appearance
17682 :version "24.4"
17683 :package-version '(Org . "8.0")
17684 :type '(choice
17685 (const :tag "Use the image width" t)
17686 (integer :tag "Use a number of pixels")
17687 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17688 (const :tag "Use #+ATTR* or don't resize" nil)))
17690 (defcustom org-agenda-inhibit-startup nil
17691 "Inhibit startup when preparing agenda buffers.
17692 When this variable is `t' (the default), the initialization of
17693 the Org agenda buffers is inhibited: e.g. the visibility state
17694 is not set, the tables are not re-aligned, etc."
17695 :type 'boolean
17696 :version "24.3"
17697 :group 'org-agenda)
17699 (defcustom org-agenda-ignore-drawer-properties nil
17700 "Avoid updating text properties when building the agenda.
17701 Properties are used to prepare buffers for effort estimates, appointments,
17702 and subtree-local categories.
17703 If you don't use these in the agenda, you can add them to this list and
17704 agenda building will be a bit faster.
17705 The value is a list, with zero or more of the symbols `effort', `appt',
17706 or `category'."
17707 :type '(set :greedy t
17708 (const effort)
17709 (const appt)
17710 (const category))
17711 :version "24.3"
17712 :group 'org-agenda)
17714 (defun org-duration-string-to-minutes (s &optional output-to-string)
17715 "Convert a duration string S to minutes.
17717 A bare number is interpreted as minutes, modifiers can be set by
17718 customizing `org-effort-durations' (which see).
17720 Entries containing a colon are interpreted as H:MM by
17721 `org-hh:mm-string-to-minutes'."
17722 (let ((result 0)
17723 (re (concat "\\([0-9.]+\\) *\\("
17724 (regexp-opt (mapcar 'car org-effort-durations))
17725 "\\)")))
17726 (while (string-match re s)
17727 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17728 (string-to-number (match-string 1 s))))
17729 (setq s (replace-match "" nil t s)))
17730 (setq result (floor result))
17731 (incf result (org-hh:mm-string-to-minutes s))
17732 (if output-to-string (number-to-string result) result)))
17734 ;;;; Files
17736 (defun org-save-all-org-buffers ()
17737 "Save all Org-mode buffers without user confirmation."
17738 (interactive)
17739 (message "Saving all Org-mode buffers...")
17740 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17741 (when (featurep 'org-id) (org-id-locations-save))
17742 (message "Saving all Org-mode buffers... done"))
17744 (defun org-revert-all-org-buffers ()
17745 "Revert all Org-mode buffers.
17746 Prompt for confirmation when there are unsaved changes.
17747 Be sure you know what you are doing before letting this function
17748 overwrite your changes.
17750 This function is useful in a setup where one tracks org files
17751 with a version control system, to revert on one machine after pulling
17752 changes from another. I believe the procedure must be like this:
17754 1. M-x org-save-all-org-buffers
17755 2. Pull changes from the other machine, resolve conflicts
17756 3. M-x org-revert-all-org-buffers"
17757 (interactive)
17758 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17759 (user-error "Abort"))
17760 (save-excursion
17761 (save-window-excursion
17762 (mapc
17763 (lambda (b)
17764 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17765 (with-current-buffer b buffer-file-name))
17766 (org-pop-to-buffer-same-window b)
17767 (revert-buffer t 'no-confirm)))
17768 (buffer-list))
17769 (when (and (featurep 'org-id) org-id-track-globally)
17770 (org-id-locations-load)))))
17772 ;;;; Agenda files
17774 ;;;###autoload
17775 (defun org-switchb (&optional arg)
17776 "Switch between Org buffers.
17777 With one prefix argument, restrict available buffers to files.
17778 With two prefix arguments, restrict available buffers to agenda files.
17780 Defaults to `iswitchb' for buffer name completion.
17781 Set `org-completion-use-ido' to make it use ido instead."
17782 (interactive "P")
17783 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17784 ((equal arg '(16)) (org-buffer-list 'agenda))
17785 (t (org-buffer-list))))
17786 (org-completion-use-iswitchb org-completion-use-iswitchb)
17787 (org-completion-use-ido org-completion-use-ido))
17788 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17789 (setq org-completion-use-iswitchb t))
17790 (org-pop-to-buffer-same-window
17791 (org-icompleting-read "Org buffer: "
17792 (mapcar 'list (mapcar 'buffer-name blist))
17793 nil t))))
17795 ;;; Define some older names previously used for this functionality
17796 ;;;###autoload
17797 (defalias 'org-ido-switchb 'org-switchb)
17798 ;;;###autoload
17799 (defalias 'org-iswitchb 'org-switchb)
17801 (defun org-buffer-list (&optional predicate exclude-tmp)
17802 "Return a list of Org buffers.
17803 PREDICATE can be `export', `files' or `agenda'.
17805 export restrict the list to Export buffers.
17806 files restrict the list to buffers visiting Org files.
17807 agenda restrict the list to buffers visiting agenda files.
17809 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17810 (let* ((bfn nil)
17811 (agenda-files (and (eq predicate 'agenda)
17812 (mapcar 'file-truename (org-agenda-files t))))
17813 (filter
17814 (cond
17815 ((eq predicate 'files)
17816 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17817 ((eq predicate 'export)
17818 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17819 ((eq predicate 'agenda)
17820 (lambda (b)
17821 (with-current-buffer b
17822 (and (derived-mode-p 'org-mode)
17823 (setq bfn (buffer-file-name b))
17824 (member (file-truename bfn) agenda-files)))))
17825 (t (lambda (b) (with-current-buffer b
17826 (or (derived-mode-p 'org-mode)
17827 (string-match "\*Org .*Export"
17828 (buffer-name b)))))))))
17829 (delq nil
17830 (mapcar
17831 (lambda(b)
17832 (if (and (funcall filter b)
17833 (or (not exclude-tmp)
17834 (not (string-match "tmp" (buffer-name b)))))
17836 nil))
17837 (buffer-list)))))
17839 (defun org-agenda-files (&optional unrestricted archives)
17840 "Get the list of agenda files.
17841 Optional UNRESTRICTED means return the full list even if a restriction
17842 is currently in place.
17843 When ARCHIVES is t, include all archive files that are really being
17844 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17845 `org-agenda-archives-mode' is t."
17846 (let ((files
17847 (cond
17848 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17849 ((stringp org-agenda-files) (org-read-agenda-file-list))
17850 ((listp org-agenda-files) org-agenda-files)
17851 (t (error "Invalid value of `org-agenda-files'")))))
17852 (setq files (apply 'append
17853 (mapcar (lambda (f)
17854 (if (file-directory-p f)
17855 (directory-files
17856 f t org-agenda-file-regexp)
17857 (list f)))
17858 files)))
17859 (when org-agenda-skip-unavailable-files
17860 (setq files (delq nil
17861 (mapcar (function
17862 (lambda (file)
17863 (and (file-readable-p file) file)))
17864 files))))
17865 (when (or (eq archives t)
17866 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17867 (setq files (org-add-archive-files files)))
17868 files))
17870 (defun org-agenda-file-p (&optional file)
17871 "Return non-nil, if FILE is an agenda file.
17872 If FILE is omitted, use the file associated with the current
17873 buffer."
17874 (member (or file (buffer-file-name))
17875 (org-agenda-files t)))
17877 (defun org-edit-agenda-file-list ()
17878 "Edit the list of agenda files.
17879 Depending on setup, this either uses customize to edit the variable
17880 `org-agenda-files', or it visits the file that is holding the list. In the
17881 latter case, the buffer is set up in a way that saving it automatically kills
17882 the buffer and restores the previous window configuration."
17883 (interactive)
17884 (if (stringp org-agenda-files)
17885 (let ((cw (current-window-configuration)))
17886 (find-file org-agenda-files)
17887 (org-set-local 'org-window-configuration cw)
17888 (org-add-hook 'after-save-hook
17889 (lambda ()
17890 (set-window-configuration
17891 (prog1 org-window-configuration
17892 (kill-buffer (current-buffer))))
17893 (org-install-agenda-files-menu)
17894 (message "New agenda file list installed"))
17895 nil 'local)
17896 (message "%s" (substitute-command-keys
17897 "Edit list and finish with \\[save-buffer]")))
17898 (customize-variable 'org-agenda-files)))
17900 (defun org-store-new-agenda-file-list (list)
17901 "Set new value for the agenda file list and save it correctly."
17902 (if (stringp org-agenda-files)
17903 (let ((fe (org-read-agenda-file-list t)) b u)
17904 (while (setq b (find-buffer-visiting org-agenda-files))
17905 (kill-buffer b))
17906 (with-temp-file org-agenda-files
17907 (insert
17908 (mapconcat
17909 (lambda (f) ;; Keep un-expanded entries.
17910 (if (setq u (assoc f fe))
17911 (cdr u)
17913 list "\n")
17914 "\n")))
17915 (let ((org-mode-hook nil) (org-inhibit-startup t)
17916 (org-insert-mode-line-in-empty-file nil))
17917 (setq org-agenda-files list)
17918 (customize-save-variable 'org-agenda-files org-agenda-files))))
17920 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17921 "Read the list of agenda files from a file.
17922 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17923 filenames, used by `org-store-new-agenda-file-list' to write back
17924 un-expanded file names."
17925 (when (file-directory-p org-agenda-files)
17926 (error "`org-agenda-files' cannot be a single directory"))
17927 (when (stringp org-agenda-files)
17928 (with-temp-buffer
17929 (insert-file-contents org-agenda-files)
17930 (mapcar
17931 (lambda (f)
17932 (let ((e (expand-file-name (substitute-in-file-name f)
17933 org-directory)))
17934 (if pair-with-expansion
17935 (cons e f)
17936 e)))
17937 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17939 ;;;###autoload
17940 (defun org-cycle-agenda-files ()
17941 "Cycle through the files in `org-agenda-files'.
17942 If the current buffer visits an agenda file, find the next one in the list.
17943 If the current buffer does not, find the first agenda file."
17944 (interactive)
17945 (let* ((fs (org-agenda-files t))
17946 (files (append fs (list (car fs))))
17947 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17948 file)
17949 (unless files (user-error "No agenda files"))
17950 (catch 'exit
17951 (while (setq file (pop files))
17952 (if (equal (file-truename file) tcf)
17953 (when (car files)
17954 (find-file (car files))
17955 (throw 'exit t))))
17956 (find-file (car fs)))
17957 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17959 (defun org-agenda-file-to-front (&optional to-end)
17960 "Move/add the current file to the top of the agenda file list.
17961 If the file is not present in the list, it is added to the front. If it is
17962 present, it is moved there. With optional argument TO-END, add/move to the
17963 end of the list."
17964 (interactive "P")
17965 (let ((org-agenda-skip-unavailable-files nil)
17966 (file-alist (mapcar (lambda (x)
17967 (cons (file-truename x) x))
17968 (org-agenda-files t)))
17969 (ctf (file-truename
17970 (or buffer-file-name
17971 (user-error "Please save the current buffer to a file"))))
17972 x had)
17973 (setq x (assoc ctf file-alist) had x)
17975 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17976 (if to-end
17977 (setq file-alist (append (delq x file-alist) (list x)))
17978 (setq file-alist (cons x (delq x file-alist))))
17979 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17980 (org-install-agenda-files-menu)
17981 (message "File %s to %s of agenda file list"
17982 (if had "moved" "added") (if to-end "end" "front"))))
17984 (defun org-remove-file (&optional file)
17985 "Remove current file from the list of files in variable `org-agenda-files'.
17986 These are the files which are being checked for agenda entries.
17987 Optional argument FILE means use this file instead of the current."
17988 (interactive)
17989 (let* ((org-agenda-skip-unavailable-files nil)
17990 (file (or file buffer-file-name
17991 (user-error "Current buffer does not visit a file")))
17992 (true-file (file-truename file))
17993 (afile (abbreviate-file-name file))
17994 (files (delq nil (mapcar
17995 (lambda (x)
17996 (if (equal true-file
17997 (file-truename x))
17998 nil x))
17999 (org-agenda-files t)))))
18000 (if (not (= (length files) (length (org-agenda-files t))))
18001 (progn
18002 (org-store-new-agenda-file-list files)
18003 (org-install-agenda-files-menu)
18004 (message "Removed file: %s" afile))
18005 (message "File was not in list: %s (not removed)" afile))))
18007 (defun org-file-menu-entry (file)
18008 (vector file (list 'find-file file) t))
18010 (defun org-check-agenda-file (file)
18011 "Make sure FILE exists. If not, ask user what to do."
18012 (when (not (file-exists-p file))
18013 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18014 (abbreviate-file-name file))
18015 (let ((r (downcase (read-char-exclusive))))
18016 (cond
18017 ((equal r ?r)
18018 (org-remove-file file)
18019 (throw 'nextfile t))
18020 (t (error "Abort"))))))
18022 (defun org-get-agenda-file-buffer (file)
18023 "Get a buffer visiting FILE. If the buffer needs to be created, add
18024 it to the list of buffers which might be released later."
18025 (let ((buf (org-find-base-buffer-visiting file)))
18026 (if buf
18027 buf ; just return it
18028 ;; Make a new buffer and remember it
18029 (setq buf (find-file-noselect file))
18030 (if buf (push buf org-agenda-new-buffers))
18031 buf)))
18033 (defun org-release-buffers (blist)
18034 "Release all buffers in list, asking the user for confirmation when needed.
18035 When a buffer is unmodified, it is just killed. When modified, it is saved
18036 \(if the user agrees) and then killed."
18037 (let (buf file)
18038 (while (setq buf (pop blist))
18039 (setq file (buffer-file-name buf))
18040 (when (and (buffer-modified-p buf)
18041 file
18042 (y-or-n-p (format "Save file %s? " file)))
18043 (with-current-buffer buf (save-buffer)))
18044 (kill-buffer buf))))
18046 (defun org-agenda-prepare-buffers (files)
18047 "Create buffers for all agenda files, protect archived trees and comments."
18048 (interactive)
18049 (let ((pa '(:org-archived t))
18050 (pc '(:org-comment t))
18051 (pall '(:org-archived t :org-comment t))
18052 (inhibit-read-only t)
18053 (org-inhibit-startup org-agenda-inhibit-startup)
18054 (rea (concat ":" org-archive-tag ":"))
18055 file re pos)
18056 (setq org-tag-alist-for-agenda nil
18057 org-tag-groups-alist-for-agenda nil)
18058 (save-window-excursion
18059 (save-restriction
18060 (while (setq file (pop files))
18061 (catch 'nextfile
18062 (if (bufferp file)
18063 (set-buffer file)
18064 (org-check-agenda-file file)
18065 (set-buffer (org-get-agenda-file-buffer file)))
18066 (widen)
18067 (org-set-regexps-and-options-for-tags)
18068 (setq pos (point))
18069 (goto-char (point-min))
18070 (let ((case-fold-search t))
18071 (when (search-forward "#+setupfile" nil t)
18072 ;; Don't set all regexps and options systematically as
18073 ;; this is only run for setting agenda tags from setup
18074 ;; file
18075 (org-set-regexps-and-options)))
18076 (or (memq 'category org-agenda-ignore-drawer-properties)
18077 (org-refresh-category-properties))
18078 (or (memq 'effort org-agenda-ignore-drawer-properties)
18079 (org-refresh-properties org-effort-property 'org-effort))
18080 (or (memq 'appt org-agenda-ignore-drawer-properties)
18081 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18082 (setq org-todo-keywords-for-agenda
18083 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18084 (setq org-done-keywords-for-agenda
18085 (append org-done-keywords-for-agenda org-done-keywords))
18086 (setq org-todo-keyword-alist-for-agenda
18087 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18088 (setq org-drawers-for-agenda
18089 (append org-drawers-for-agenda org-drawers))
18090 (setq org-tag-alist-for-agenda
18091 (org-uniquify
18092 (append org-tag-alist-for-agenda
18093 org-tag-alist
18094 org-tag-persistent-alist)))
18095 (if org-group-tags
18096 (setq org-tag-groups-alist-for-agenda
18097 (org-uniquify-alist
18098 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18099 (org-with-silent-modifications
18100 (save-excursion
18101 (remove-text-properties (point-min) (point-max) pall)
18102 (when org-agenda-skip-archived-trees
18103 (goto-char (point-min))
18104 (while (re-search-forward rea nil t)
18105 (if (org-at-heading-p t)
18106 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18107 (goto-char (point-min))
18108 (setq re (format org-heading-keyword-regexp-format
18109 org-comment-string))
18110 (while (re-search-forward re nil t)
18111 (add-text-properties
18112 (match-beginning 0) (org-end-of-subtree t) pc))))
18113 (goto-char pos)))))
18114 (setq org-todo-keywords-for-agenda
18115 (org-uniquify org-todo-keywords-for-agenda))
18116 (setq org-todo-keyword-alist-for-agenda
18117 (org-uniquify org-todo-keyword-alist-for-agenda))))
18120 ;;;; CDLaTeX minor mode
18122 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18123 "Keymap for the minor `org-cdlatex-mode'.")
18125 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18126 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18127 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18128 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18129 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18131 (defvar org-cdlatex-texmathp-advice-is-done nil
18132 "Flag remembering if we have applied the advice to texmathp already.")
18134 (define-minor-mode org-cdlatex-mode
18135 "Toggle the minor `org-cdlatex-mode'.
18136 This mode supports entering LaTeX environment and math in LaTeX fragments
18137 in Org-mode.
18138 \\{org-cdlatex-mode-map}"
18139 nil " OCDL" nil
18140 (when org-cdlatex-mode
18141 (require 'cdlatex)
18142 (run-hooks 'cdlatex-mode-hook)
18143 (cdlatex-compute-tables))
18144 (unless org-cdlatex-texmathp-advice-is-done
18145 (setq org-cdlatex-texmathp-advice-is-done t)
18146 (defadvice texmathp (around org-math-always-on activate)
18147 "Always return t in org-mode buffers.
18148 This is because we want to insert math symbols without dollars even outside
18149 the LaTeX math segments. If Orgmode thinks that point is actually inside
18150 an embedded LaTeX fragment, let texmathp do its job.
18151 \\[org-cdlatex-mode-map]"
18152 (interactive)
18153 (let (p)
18154 (cond
18155 ((not (derived-mode-p 'org-mode)) ad-do-it)
18156 ((eq this-command 'cdlatex-math-symbol)
18157 (setq ad-return-value t
18158 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18160 (let ((p (org-inside-LaTeX-fragment-p)))
18161 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18162 (setq ad-return-value t
18163 texmathp-why '("Org-mode embedded math" . 0))
18164 (if p ad-do-it)))))))))
18166 (defun turn-on-org-cdlatex ()
18167 "Unconditionally turn on `org-cdlatex-mode'."
18168 (org-cdlatex-mode 1))
18170 (defun org-try-cdlatex-tab ()
18171 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18172 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18173 - inside a LaTeX fragment, or
18174 - after the first word in a line, where an abbreviation expansion could
18175 insert a LaTeX environment."
18176 (when org-cdlatex-mode
18177 (cond
18178 ;; Before any word on the line: No expansion possible.
18179 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18180 ;; Just after first word on the line: Expand it. Make sure it
18181 ;; cannot happen on headlines, though.
18182 ((save-excursion
18183 (skip-chars-backward "a-zA-Z0-9*")
18184 (skip-chars-backward " \t")
18185 (and (bolp) (not (org-at-heading-p))))
18186 (cdlatex-tab) t)
18187 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18189 (defun org-cdlatex-underscore-caret (&optional arg)
18190 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18191 Revert to the normal definition outside of these fragments."
18192 (interactive "P")
18193 (if (org-inside-LaTeX-fragment-p)
18194 (call-interactively 'cdlatex-sub-superscript)
18195 (let (org-cdlatex-mode)
18196 (call-interactively (key-binding (vector last-input-event))))))
18198 (defun org-cdlatex-math-modify (&optional arg)
18199 "Execute `cdlatex-math-modify' in LaTeX fragments.
18200 Revert to the normal definition outside of these fragments."
18201 (interactive "P")
18202 (if (org-inside-LaTeX-fragment-p)
18203 (call-interactively 'cdlatex-math-modify)
18204 (let (org-cdlatex-mode)
18205 (call-interactively (key-binding (vector last-input-event))))))
18209 ;;;; LaTeX fragments
18211 (defvar org-latex-regexps
18212 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18213 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18214 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18215 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18216 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18217 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18218 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18219 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18220 "Regular expressions for matching embedded LaTeX.")
18222 (defun org-inside-LaTeX-fragment-p ()
18223 "Test if point is inside a LaTeX fragment.
18224 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18225 sequence appearing also before point.
18226 Even though the matchers for math are configurable, this function assumes
18227 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18228 delimiters are skipped when they have been removed by customization.
18229 The return value is nil, or a cons cell with the delimiter and the
18230 position of this delimiter.
18232 This function does a reasonably good job, but can locally be fooled by
18233 for example currency specifications. For example it will assume being in
18234 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18235 fragments that are properly closed, but during editing, we have to live
18236 with the uncertainty caused by missing closing delimiters. This function
18237 looks only before point, not after."
18238 (catch 'exit
18239 (let ((pos (point))
18240 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18241 (lim (progn
18242 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18243 (point)))
18244 dd-on str (start 0) m re)
18245 (goto-char pos)
18246 (when dodollar
18247 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18248 re (nth 1 (assoc "$" org-latex-regexps)))
18249 (while (string-match re str start)
18250 (cond
18251 ((= (match-end 0) (length str))
18252 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18253 ((= (match-end 0) (- (length str) 5))
18254 (throw 'exit nil))
18255 (t (setq start (match-end 0))))))
18256 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18257 (goto-char pos)
18258 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18259 (and (match-beginning 2) (throw 'exit nil))
18260 ;; count $$
18261 (while (re-search-backward "\\$\\$" lim t)
18262 (setq dd-on (not dd-on)))
18263 (goto-char pos)
18264 (if dd-on (cons "$$" m))))))
18266 (defun org-inside-latex-macro-p ()
18267 "Is point inside a LaTeX macro or its arguments?"
18268 (save-match-data
18269 (org-in-regexp
18270 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18272 (defvar org-latex-fragment-image-overlays nil
18273 "List of overlays carrying the images of latex fragments.")
18274 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18276 (defun org-remove-latex-fragment-image-overlays ()
18277 "Remove all overlays with LaTeX fragment images in current buffer."
18278 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18279 (setq org-latex-fragment-image-overlays nil))
18281 (defun org-preview-latex-fragment (&optional subtree)
18282 "Preview the LaTeX fragment at point, or all locally or globally.
18283 If the cursor is in a LaTeX fragment, create the image and overlay
18284 it over the source code. If there is no fragment at point, display
18285 all fragments in the current text, from one headline to the next. With
18286 prefix SUBTREE, display all fragments in the current subtree. With a
18287 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18288 the cursor is before the first headline,
18289 display all fragments in the buffer.
18290 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18291 (interactive "P")
18292 (unless buffer-file-name
18293 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18294 (when (display-graphic-p)
18295 (org-remove-latex-fragment-image-overlays)
18296 (save-excursion
18297 (save-restriction
18298 (let (beg end at msg)
18299 (cond
18300 ((or (equal subtree '(16))
18301 (not (save-excursion
18302 (re-search-backward org-outline-regexp-bol nil t))))
18303 (setq beg (point-min) end (point-max)
18304 msg "Creating images for buffer...%s"))
18305 ((equal subtree '(4))
18306 (org-back-to-heading)
18307 (setq beg (point) end (org-end-of-subtree t)
18308 msg "Creating images for subtree...%s"))
18310 (if (setq at (org-inside-LaTeX-fragment-p))
18311 (goto-char (max (point-min) (- (cdr at) 2)))
18312 (org-back-to-heading))
18313 (setq beg (point) end (progn (outline-next-heading) (point))
18314 msg (if at "Creating image...%s"
18315 "Creating images for entry...%s"))))
18316 (message msg "")
18317 (narrow-to-region beg end)
18318 (goto-char beg)
18319 (org-format-latex
18320 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18321 (file-name-nondirectory
18322 buffer-file-name)))
18323 default-directory 'overlays msg at 'forbuffer
18324 org-latex-create-formula-image-program)
18325 (message msg "done. Use `C-c C-c' to remove images."))))))
18327 (defun org-format-latex (prefix &optional dir overlays msg at
18328 forbuffer processing-type)
18329 "Replace LaTeX fragments with links to an image, and produce images.
18330 Some of the options can be changed using the variable
18331 `org-format-latex-options'."
18332 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18333 (let* ((prefixnodir (file-name-nondirectory prefix))
18334 (absprefix (expand-file-name prefix dir))
18335 (todir (file-name-directory absprefix))
18336 (opt org-format-latex-options)
18337 (optnew org-format-latex-options)
18338 (matchers (plist-get opt :matchers))
18339 (re-list org-latex-regexps)
18340 (cnt 0) txt hash link beg end re e checkdir
18341 string
18342 m n block-type block linkfile movefile ov)
18343 ;; Check the different regular expressions
18344 (while (setq e (pop re-list))
18345 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18346 block (if block-type "\n\n" ""))
18347 (when (member m matchers)
18348 (goto-char (point-min))
18349 (while (re-search-forward re nil t)
18350 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18351 (or (not overlays)
18352 (not (eq (get-char-property (match-beginning n)
18353 'org-overlay-type)
18354 'org-latex-overlay))))
18355 (cond
18356 ((eq processing-type 'verbatim))
18357 ((eq processing-type 'mathjax)
18358 ;; Prepare for MathJax processing.
18359 (setq string (match-string n))
18360 (when (member m '("$" "$1"))
18361 (save-excursion
18362 (delete-region (match-beginning n) (match-end n))
18363 (goto-char (match-beginning n))
18364 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18365 ((or (eq processing-type 'dvipng)
18366 (eq processing-type 'imagemagick))
18367 ;; Process to an image.
18368 (setq txt (match-string n)
18369 beg (match-beginning n) end (match-end n)
18370 cnt (1+ cnt))
18371 (let ((face (face-at-point))
18372 (fg (plist-get opt :foreground))
18373 (bg (plist-get opt :background))
18374 ;; Ensure full list is printed.
18375 print-length print-level)
18376 (when forbuffer
18377 ;; Get the colors from the face at point.
18378 (goto-char beg)
18379 (when (eq fg 'auto)
18380 (setq fg (face-attribute face :foreground nil 'default)))
18381 (when (eq bg 'auto)
18382 (setq bg (face-attribute face :background nil 'default)))
18383 (setq optnew (copy-sequence opt))
18384 (plist-put optnew :foreground fg)
18385 (plist-put optnew :background bg))
18386 (setq hash (sha1 (prin1-to-string
18387 (list org-format-latex-header
18388 org-latex-default-packages-alist
18389 org-latex-packages-alist
18390 org-format-latex-options
18391 forbuffer txt fg bg)))
18392 linkfile (format "%s_%s.png" prefix hash)
18393 movefile (format "%s_%s.png" absprefix hash)))
18394 (setq link (concat block "[[file:" linkfile "]]" block))
18395 (if msg (message msg cnt))
18396 (goto-char beg)
18397 (unless checkdir ; Ensure the directory exists.
18398 (setq checkdir t)
18399 (or (file-directory-p todir) (make-directory todir t)))
18400 (unless (file-exists-p movefile)
18401 (org-create-formula-image
18402 txt movefile optnew forbuffer processing-type))
18403 (if overlays
18404 (progn
18405 (mapc (lambda (o)
18406 (if (eq (overlay-get o 'org-overlay-type)
18407 'org-latex-overlay)
18408 (delete-overlay o)))
18409 (overlays-in beg end))
18410 (setq ov (make-overlay beg end))
18411 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18412 (if (featurep 'xemacs)
18413 (progn
18414 (overlay-put ov 'invisible t)
18415 (overlay-put
18416 ov 'end-glyph
18417 (make-glyph (vector 'png :file movefile))))
18418 (overlay-put
18419 ov 'display
18420 (list 'image :type 'png :file movefile :ascent 'center)))
18421 (push ov org-latex-fragment-image-overlays)
18422 (goto-char end))
18423 (delete-region beg end)
18424 (insert (org-add-props link
18425 (list 'org-latex-src
18426 (replace-regexp-in-string
18427 "\"" "" txt)
18428 'org-latex-src-embed-type
18429 (if block-type 'paragraph 'character))))))
18430 ((eq processing-type 'mathml)
18431 ;; Process to MathML
18432 (unless (save-match-data (org-format-latex-mathml-available-p))
18433 (user-error "LaTeX to MathML converter not configured"))
18434 (setq txt (match-string n)
18435 beg (match-beginning n) end (match-end n)
18436 cnt (1+ cnt))
18437 (if msg (message msg cnt))
18438 (goto-char beg)
18439 (delete-region beg end)
18440 (insert (org-format-latex-as-mathml
18441 txt block-type prefix dir)))
18443 (error "Unknown conversion type %s for LaTeX fragments"
18444 processing-type)))))))))
18446 (defun org-create-math-formula (latex-frag &optional mathml-file)
18447 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18448 Use `org-latex-to-mathml-convert-command'. If the conversion is
18449 sucessful, return the portion between \"<math...> </math>\"
18450 elements otherwise return nil. When MATHML-FILE is specified,
18451 write the results in to that file. When invoked as an
18452 interactive command, prompt for LATEX-FRAG, with initial value
18453 set to the current active region and echo the results for user
18454 inspection."
18455 (interactive (list (let ((frag (when (org-region-active-p)
18456 (buffer-substring-no-properties
18457 (region-beginning) (region-end)))))
18458 (read-string "LaTeX Fragment: " frag nil frag))))
18459 (unless latex-frag (error "Invalid LaTeX fragment"))
18460 (let* ((tmp-in-file (file-relative-name
18461 (make-temp-name (expand-file-name "ltxmathml-in"))))
18462 (ignore (write-region latex-frag nil tmp-in-file))
18463 (tmp-out-file (file-relative-name
18464 (make-temp-name (expand-file-name "ltxmathml-out"))))
18465 (cmd (format-spec
18466 org-latex-to-mathml-convert-command
18467 `((?j . ,(shell-quote-argument
18468 (expand-file-name org-latex-to-mathml-jar-file)))
18469 (?I . ,(shell-quote-argument tmp-in-file))
18470 (?o . ,(shell-quote-argument tmp-out-file)))))
18471 mathml shell-command-output)
18472 (when (org-called-interactively-p 'any)
18473 (unless (org-format-latex-mathml-available-p)
18474 (user-error "LaTeX to MathML converter not configured")))
18475 (message "Running %s" cmd)
18476 (setq shell-command-output (shell-command-to-string cmd))
18477 (setq mathml
18478 (when (file-readable-p tmp-out-file)
18479 (with-current-buffer (find-file-noselect tmp-out-file t)
18480 (goto-char (point-min))
18481 (when (re-search-forward
18482 (concat
18483 (regexp-quote
18484 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18485 "\\(.\\|\n\\)*"
18486 (regexp-quote "</math>")) nil t)
18487 (prog1 (match-string 0) (kill-buffer))))))
18488 (cond
18489 (mathml
18490 (setq mathml
18491 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18492 (when mathml-file
18493 (write-region mathml nil mathml-file))
18494 (when (org-called-interactively-p 'any)
18495 (message mathml)))
18496 ((message "LaTeX to MathML conversion failed")
18497 (message shell-command-output)))
18498 (delete-file tmp-in-file)
18499 (when (file-exists-p tmp-out-file)
18500 (delete-file tmp-out-file))
18501 mathml))
18503 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18504 prefix &optional dir)
18505 "Use `org-create-math-formula' but check local cache first."
18506 (let* ((absprefix (expand-file-name prefix dir))
18507 (print-length nil) (print-level nil)
18508 (formula-id (concat
18509 "formula-"
18510 (sha1
18511 (prin1-to-string
18512 (list latex-frag
18513 org-latex-to-mathml-convert-command)))))
18514 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18515 (formula-cache-dir (file-name-directory formula-cache)))
18517 (unless (file-directory-p formula-cache-dir)
18518 (make-directory formula-cache-dir t))
18520 (unless (file-exists-p formula-cache)
18521 (org-create-math-formula latex-frag formula-cache))
18523 (if (file-exists-p formula-cache)
18524 ;; Successful conversion. Return the link to MathML file.
18525 (org-add-props
18526 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18527 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18528 'org-latex-src-embed-type (if latex-frag-type
18529 'paragraph 'character)))
18530 ;; Failed conversion. Return the LaTeX fragment verbatim
18531 latex-frag)))
18533 (defun org-create-formula-image (string tofile options buffer &optional type)
18534 "Create an image from LaTeX source using dvipng or convert.
18535 This function calls either `org-create-formula-image-with-dvipng'
18536 or `org-create-formula-image-with-imagemagick' depending on the
18537 value of `org-latex-create-formula-image-program' or on the value
18538 of the optional TYPE variable.
18540 Note: ultimately these two function should be combined as they
18541 share a good deal of logic."
18542 (org-check-external-command
18543 "latex" "needed to convert LaTeX fragments to images")
18544 (funcall
18545 (case (or type org-latex-create-formula-image-program)
18546 ('dvipng
18547 (org-check-external-command
18548 "dvipng" "needed to convert LaTeX fragments to images")
18549 #'org-create-formula-image-with-dvipng)
18550 ('imagemagick
18551 (org-check-external-command
18552 "convert" "you need to install imagemagick")
18553 #'org-create-formula-image-with-imagemagick)
18554 (t (error
18555 "Invalid value of `org-latex-create-formula-image-program'")))
18556 string tofile options buffer))
18558 (declare-function org-export-get-backend "ox" (name))
18559 (declare-function org-export--get-global-options "ox" (&optional backend))
18560 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18561 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18562 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18563 (defun org-create-formula--latex-header ()
18564 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18565 (let ((info (org-combine-plists (org-export--get-global-options
18566 (org-export-get-backend 'latex))
18567 (org-export--get-inbuffer-options
18568 (org-export-get-backend 'latex)))))
18569 (org-latex-guess-babel-language
18570 (org-latex-guess-inputenc
18571 (org-splice-latex-header
18572 org-format-latex-header
18573 org-latex-default-packages-alist
18574 org-latex-packages-alist t
18575 (plist-get info :latex-header)))
18576 info)))
18578 ;; This function borrows from Ganesh Swami's latex2png.el
18579 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18580 "This calls dvipng."
18581 (require 'ox-latex)
18582 (let* ((tmpdir (if (featurep 'xemacs)
18583 (temp-directory)
18584 temporary-file-directory))
18585 (texfilebase (make-temp-name
18586 (expand-file-name "orgtex" tmpdir)))
18587 (texfile (concat texfilebase ".tex"))
18588 (dvifile (concat texfilebase ".dvi"))
18589 (pngfile (concat texfilebase ".png"))
18590 (fnh (if (featurep 'xemacs)
18591 (font-height (face-font 'default))
18592 (face-attribute 'default :height nil)))
18593 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18594 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18595 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18596 "Black"))
18597 (bg (or (plist-get options (if buffer :background :html-background))
18598 "Transparent")))
18599 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18600 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18601 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18602 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18603 (let ((latex-header (org-create-formula--latex-header)))
18604 (with-temp-file texfile
18605 (insert latex-header)
18606 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18607 (let ((dir default-directory))
18608 (condition-case nil
18609 (progn
18610 (cd tmpdir)
18611 (call-process "latex" nil nil nil texfile))
18612 (error nil))
18613 (cd dir))
18614 (if (not (file-exists-p dvifile))
18615 (progn (message "Failed to create dvi file from %s" texfile) nil)
18616 (condition-case nil
18617 (if (featurep 'xemacs)
18618 (call-process "dvipng" nil nil nil
18619 "-fg" fg "-bg" bg
18620 "-T" "tight"
18621 "-o" pngfile
18622 dvifile)
18623 (call-process "dvipng" nil nil nil
18624 "-fg" fg "-bg" bg
18625 "-D" dpi
18626 ;;"-x" scale "-y" scale
18627 "-T" "tight"
18628 "-o" pngfile
18629 dvifile))
18630 (error nil))
18631 (if (not (file-exists-p pngfile))
18632 (if org-format-latex-signal-error
18633 (error "Failed to create png file from %s" texfile)
18634 (message "Failed to create png file from %s" texfile)
18635 nil)
18636 ;; Use the requested file name and clean up
18637 (copy-file pngfile tofile 'replace)
18638 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18639 (if (file-exists-p (concat texfilebase e))
18640 (delete-file (concat texfilebase e))))
18641 pngfile))))
18643 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18644 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18645 "This calls convert, which is included into imagemagick."
18646 (require 'ox-latex)
18647 (let* ((tmpdir (if (featurep 'xemacs)
18648 (temp-directory)
18649 temporary-file-directory))
18650 (texfilebase (make-temp-name
18651 (expand-file-name "orgtex" tmpdir)))
18652 (texfile (concat texfilebase ".tex"))
18653 (pdffile (concat texfilebase ".pdf"))
18654 (pngfile (concat texfilebase ".png"))
18655 (fnh (if (featurep 'xemacs)
18656 (font-height (face-font 'default))
18657 (face-attribute 'default :height nil)))
18658 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18659 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18660 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18661 "black"))
18662 (bg (or (plist-get options (if buffer :background :html-background))
18663 "white")))
18664 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18665 (setq fg (org-latex-color-format fg)))
18666 (if (eq bg 'default) (setq bg (org-latex-color :background))
18667 (setq bg (org-latex-color-format
18668 (if (string= bg "Transparent") "white" bg))))
18669 (let ((latex-header (org-create-formula--latex-header)))
18670 (with-temp-file texfile
18671 (insert latex-header)
18672 (insert "\n\\begin{document}\n"
18673 "\\definecolor{fg}{rgb}{" fg "}\n"
18674 "\\definecolor{bg}{rgb}{" bg "}\n"
18675 "\n\\pagecolor{bg}\n"
18676 "\n{\\color{fg}\n"
18677 string
18678 "\n}\n"
18679 "\n\\end{document}\n")))
18680 (org-latex-compile texfile t)
18681 (if (not (file-exists-p pdffile))
18682 (progn (message "Failed to create pdf file from %s" texfile) nil)
18683 (condition-case nil
18684 (if (featurep 'xemacs)
18685 (call-process "convert" nil nil nil
18686 "-density" "96"
18687 "-trim"
18688 "-antialias"
18689 pdffile
18690 "-quality" "100"
18691 ;; "-sharpen" "0x1.0"
18692 pngfile)
18693 (call-process "convert" nil nil nil
18694 "-density" dpi
18695 "-trim"
18696 "-antialias"
18697 pdffile
18698 "-quality" "100"
18699 ;; "-sharpen" "0x1.0"
18700 pngfile))
18701 (error nil))
18702 (if (not (file-exists-p pngfile))
18703 (if org-format-latex-signal-error
18704 (error "Failed to create png file from %s" texfile)
18705 (message "Failed to create png file from %s" texfile)
18706 nil)
18707 ;; Use the requested file name and clean up
18708 (copy-file pngfile tofile 'replace)
18709 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18710 (if (file-exists-p (concat texfilebase e))
18711 (delete-file (concat texfilebase e))))
18712 pngfile))))
18714 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18715 "Fill a LaTeX header template TPL.
18716 In the template, the following place holders will be recognized:
18718 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18719 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18720 [PACKAGES] \\usepackage statements for PKG
18721 [NO-PACKAGES] do not include PKG
18722 [EXTRA] the string EXTRA
18723 [NO-EXTRA] do not include EXTRA
18725 For backward compatibility, if both the positive and the negative place
18726 holder is missing, the positive one (without the \"NO-\") will be
18727 assumed to be present at the end of the template.
18728 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18729 EXTRA is a string.
18730 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18731 (let (rpl (end ""))
18732 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18733 (setq rpl (if (or (match-end 1) (not def-pkg))
18734 "" (org-latex-packages-to-string def-pkg snippets-p t))
18735 tpl (replace-match rpl t t tpl))
18736 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18738 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18739 (setq rpl (if (or (match-end 1) (not pkg))
18740 "" (org-latex-packages-to-string pkg snippets-p t))
18741 tpl (replace-match rpl t t tpl))
18742 (if pkg (setq end
18743 (concat end "\n"
18744 (org-latex-packages-to-string pkg snippets-p)))))
18746 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18747 (setq rpl (if (or (match-end 1) (not extra))
18748 "" (concat extra "\n"))
18749 tpl (replace-match rpl t t tpl))
18750 (if (and extra (string-match "\\S-" extra))
18751 (setq end (concat end "\n" extra))))
18753 (if (string-match "\\S-" end)
18754 (concat tpl "\n" end)
18755 tpl)))
18757 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18758 "Turn an alist of packages into a string with the \\usepackage macros."
18759 (setq pkg (mapconcat (lambda(p)
18760 (cond
18761 ((stringp p) p)
18762 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18763 (format "%% Package %s omitted" (cadr p)))
18764 ((equal "" (car p))
18765 (format "\\usepackage{%s}" (cadr p)))
18767 (format "\\usepackage[%s]{%s}"
18768 (car p) (cadr p)))))
18770 "\n"))
18771 (if newline (concat pkg "\n") pkg))
18773 (defun org-dvipng-color (attr)
18774 "Return a RGB color specification for dvipng."
18775 (apply 'format "rgb %s %s %s"
18776 (mapcar 'org-normalize-color
18777 (if (featurep 'xemacs)
18778 (color-rgb-components
18779 (face-property 'default
18780 (cond ((eq attr :foreground) 'foreground)
18781 ((eq attr :background) 'background))))
18782 (color-values (face-attribute 'default attr nil))))))
18784 (defun org-dvipng-color-format (color-name)
18785 "Convert COLOR-NAME to a RGB color value for dvipng."
18786 (apply 'format "rgb %s %s %s"
18787 (mapcar 'org-normalize-color
18788 (color-values color-name))))
18790 (defun org-latex-color (attr)
18791 "Return a RGB color for the LaTeX color package."
18792 (apply 'format "%s,%s,%s"
18793 (mapcar 'org-normalize-color
18794 (if (featurep 'xemacs)
18795 (color-rgb-components
18796 (face-property 'default
18797 (cond ((eq attr :foreground) 'foreground)
18798 ((eq attr :background) 'background))))
18799 (color-values (face-attribute 'default attr nil))))))
18801 (defun org-latex-color-format (color-name)
18802 "Convert COLOR-NAME to a RGB color value."
18803 (apply 'format "%s,%s,%s"
18804 (mapcar 'org-normalize-color
18805 (color-values color-name))))
18807 (defun org-normalize-color (value)
18808 "Return string to be used as color value for an RGB component."
18809 (format "%g" (/ value 65535.0)))
18813 ;; Image display
18815 (defvar org-inline-image-overlays nil)
18816 (make-variable-buffer-local 'org-inline-image-overlays)
18818 (defun org-toggle-inline-images (&optional include-linked)
18819 "Toggle the display of inline images.
18820 INCLUDE-LINKED is passed to `org-display-inline-images'."
18821 (interactive "P")
18822 (if org-inline-image-overlays
18823 (progn
18824 (org-remove-inline-images)
18825 (message "Inline image display turned off"))
18826 (org-display-inline-images include-linked)
18827 (if (and (org-called-interactively-p)
18828 org-inline-image-overlays)
18829 (message "%d images displayed inline"
18830 (length org-inline-image-overlays))
18831 (message "No images to display inline"))))
18833 (defun org-redisplay-inline-images ()
18834 "Refresh the display of inline images."
18835 (interactive)
18836 (if (not org-inline-image-overlays)
18837 (org-toggle-inline-images)
18838 (org-toggle-inline-images)
18839 (org-toggle-inline-images)))
18841 (defun org-display-inline-images (&optional include-linked refresh beg end)
18842 "Display inline images.
18843 Normally only links without a description part are inlined, because this
18844 is how it will work for export. When INCLUDE-LINKED is set, also links
18845 with a description part will be inlined. This can be nice for a quick
18846 look at those images, but it does not reflect what exported files will look
18847 like.
18848 When REFRESH is set, refresh existing images between BEG and END.
18849 This will create new image displays only if necessary.
18850 BEG and END default to the buffer boundaries."
18851 (interactive "P")
18852 (when (display-graphic-p)
18853 (unless refresh
18854 (org-remove-inline-images)
18855 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18856 (save-excursion
18857 (save-restriction
18858 (widen)
18859 (setq beg (or beg (point-min)) end (or end (point-max)))
18860 (goto-char beg)
18861 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18862 (substring (org-image-file-name-regexp) 0 -2)
18863 "\\)\\]" (if include-linked "" "\\]")))
18864 (case-fold-search t)
18865 old file ov img type attrwidth width)
18866 (while (re-search-forward re end t)
18867 (setq old (get-char-property-and-overlay (match-beginning 1)
18868 'org-image-overlay)
18869 file (expand-file-name
18870 (concat (or (match-string 3) "") (match-string 4))))
18871 (when (image-type-available-p 'imagemagick)
18872 (setq attrwidth (if (or (listp org-image-actual-width)
18873 (null org-image-actual-width))
18874 (save-excursion
18875 (save-match-data
18876 (when (re-search-backward
18877 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18878 (save-excursion
18879 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18880 (string-to-number (match-string 1))))))
18881 width (cond ((eq org-image-actual-width t) nil)
18882 ((null org-image-actual-width) attrwidth)
18883 ((numberp org-image-actual-width)
18884 org-image-actual-width)
18885 ((listp org-image-actual-width)
18886 (or attrwidth (car org-image-actual-width))))
18887 type (if width 'imagemagick)))
18888 (when (file-exists-p file)
18889 (if (and (car-safe old) refresh)
18890 (image-refresh (overlay-get (cdr old) 'display))
18891 (setq img (save-match-data (create-image file type nil :width width)))
18892 (when img
18893 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18894 (overlay-put ov 'display img)
18895 (overlay-put ov 'face 'default)
18896 (overlay-put ov 'org-image-overlay t)
18897 (overlay-put ov 'modification-hooks
18898 (list 'org-display-inline-remove-overlay))
18899 (push ov org-inline-image-overlays))))))))))
18901 (define-obsolete-function-alias
18902 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18904 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18905 "Remove inline-display overlay if a corresponding region is modified."
18906 (let ((inhibit-modification-hooks t))
18907 (when (and ov after)
18908 (delete ov org-inline-image-overlays)
18909 (delete-overlay ov))))
18911 (defun org-remove-inline-images ()
18912 "Remove inline display of images."
18913 (interactive)
18914 (mapc 'delete-overlay org-inline-image-overlays)
18915 (setq org-inline-image-overlays nil))
18917 ;;;; Key bindings
18919 ;; Outline functions from `outline-mode-prefix-map'
18920 ;; that can be remapped in Org:
18921 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18922 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18923 (define-key org-mode-map [remap outline-forward-same-level]
18924 'org-forward-heading-same-level)
18925 (define-key org-mode-map [remap outline-backward-same-level]
18926 'org-backward-heading-same-level)
18927 (define-key org-mode-map [remap show-branches]
18928 'org-kill-note-or-show-branches)
18929 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18930 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18931 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18933 ;; Outline functions from `outline-mode-prefix-map' that can not
18934 ;; be remapped in Org:
18936 ;; - the column "key binding" shows whether the Outline function is still
18937 ;; available in Org mode on the same key that it has been bound to in
18938 ;; Outline mode:
18939 ;; - "overridden": key used for a different functionality in Org mode
18940 ;; - else: key still bound to the same Outline function in Org mode
18942 ;; | Outline function | key binding | Org replacement |
18943 ;; |------------------------------------+-------------+-----------------------|
18944 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18945 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18946 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18947 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18948 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18949 ;; | `show-entry' | overridden | no replacement |
18950 ;; | `show-children' | `C-c C-i' | visibility cycling |
18951 ;; | `show-branches' | `C-c C-k' | still same function |
18952 ;; | `show-subtree' | overridden | visibility cycling |
18953 ;; | `show-all' | overridden | no replacement |
18954 ;; | `hide-subtree' | overridden | visibility cycling |
18955 ;; | `hide-body' | overridden | no replacement |
18956 ;; | `hide-entry' | overridden | visibility cycling |
18957 ;; | `hide-leaves' | overridden | no replacement |
18958 ;; | `hide-sublevels' | overridden | no replacement |
18959 ;; | `hide-other' | overridden | no replacement |
18961 ;; Make `C-c C-x' a prefix key
18962 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18964 ;; TAB key with modifiers
18965 (org-defkey org-mode-map "\C-i" 'org-cycle)
18966 (org-defkey org-mode-map [(tab)] 'org-cycle)
18967 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18968 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18969 ;; The following line is necessary under Suse GNU/Linux
18970 (unless (featurep 'xemacs)
18971 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18972 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18973 (define-key org-mode-map [backtab] 'org-shifttab)
18975 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18976 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18977 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18979 ;; Cursor keys with modifiers
18980 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18981 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18982 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18983 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18985 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18986 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18987 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18988 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18990 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18991 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18992 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18993 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18995 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18996 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18997 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18998 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19000 ;; Babel keys
19001 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19002 (mapc (lambda (pair)
19003 (define-key org-babel-map (car pair) (cdr pair)))
19004 org-babel-key-bindings)
19006 ;;; Extra keys for tty access.
19007 ;; We only set them when really needed because otherwise the
19008 ;; menus don't show the simple keys
19010 (when (or org-use-extra-keys
19011 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19012 (not window-system))
19013 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19014 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19015 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19016 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19017 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19018 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19019 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19020 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19021 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19022 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19023 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19024 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19025 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19026 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19027 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19028 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19029 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19030 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19031 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19032 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19033 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19034 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19035 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19036 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19037 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19038 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19039 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19040 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19042 ;; All the other keys
19044 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19045 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19046 (if (boundp 'narrow-map)
19047 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19048 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19049 (if (boundp 'narrow-map)
19050 (org-defkey narrow-map "b" 'org-narrow-to-block)
19051 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19052 (if (boundp 'narrow-map)
19053 (org-defkey narrow-map "e" 'org-narrow-to-element)
19054 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19055 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19056 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19057 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19058 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19059 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19060 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19061 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19062 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19063 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19064 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19065 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19066 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19067 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19068 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19069 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19070 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19071 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19072 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19073 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19074 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19075 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19076 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19077 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19078 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19079 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19080 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19081 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19082 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19083 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19084 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19085 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19086 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19087 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19088 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19089 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19090 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19091 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19092 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19093 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19094 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19095 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19096 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19097 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19098 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19099 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19100 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19101 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19102 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19103 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19104 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19105 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19106 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19107 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19108 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19109 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19110 (org-defkey org-mode-map "\C-c^" 'org-sort)
19111 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19112 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19113 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19114 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19115 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19116 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19117 (org-defkey org-mode-map "\C-m" 'org-return)
19118 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19119 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19120 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19121 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19122 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19123 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19124 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19125 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19126 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19127 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19128 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19129 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19130 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19131 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19132 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19133 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19134 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19135 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19136 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19137 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19138 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19139 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19140 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19142 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19143 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19144 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19146 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19147 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19148 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19149 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19150 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19151 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19152 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19153 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19154 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19155 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19156 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19157 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19158 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19159 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19160 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19161 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19162 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19163 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19164 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19165 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19166 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19167 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19168 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19170 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19171 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19172 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19173 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19174 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19176 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19178 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19180 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19181 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19183 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19186 (when (featurep 'xemacs)
19187 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19190 (defconst org-speed-commands-default
19192 ("Outline Navigation")
19193 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19194 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19195 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19196 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19197 ("F" . org-next-block)
19198 ("B" . org-previous-block)
19199 ("u" . (org-speed-move-safe 'outline-up-heading))
19200 ("j" . org-goto)
19201 ("g" . (org-refile t))
19202 ("Outline Visibility")
19203 ("c" . org-cycle)
19204 ("C" . org-shifttab)
19205 (" " . org-display-outline-path)
19206 ("s" . org-narrow-to-subtree)
19207 ("=" . org-columns)
19208 ("Outline Structure Editing")
19209 ("U" . org-shiftmetaup)
19210 ("D" . org-shiftmetadown)
19211 ("r" . org-metaright)
19212 ("l" . org-metaleft)
19213 ("R" . org-shiftmetaright)
19214 ("L" . org-shiftmetaleft)
19215 ("i" . (progn (forward-char 1) (call-interactively
19216 'org-insert-heading-respect-content)))
19217 ("^" . org-sort)
19218 ("w" . org-refile)
19219 ("a" . org-archive-subtree-default-with-confirmation)
19220 ("@" . org-mark-subtree)
19221 ("#" . org-toggle-comment)
19222 ("Clock Commands")
19223 ("I" . org-clock-in)
19224 ("O" . org-clock-out)
19225 ("Meta Data Editing")
19226 ("t" . org-todo)
19227 ("," . (org-priority))
19228 ("0" . (org-priority ?\ ))
19229 ("1" . (org-priority ?A))
19230 ("2" . (org-priority ?B))
19231 ("3" . (org-priority ?C))
19232 (":" . org-set-tags-command)
19233 ("e" . org-set-effort)
19234 ("E" . org-inc-effort)
19235 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19236 (org-entry-put (point) "APPT_WARNTIME" m)))
19237 ("Agenda Views etc")
19238 ("v" . org-agenda)
19239 ("/" . org-sparse-tree)
19240 ("Misc")
19241 ("o" . org-open-at-point)
19242 ("?" . org-speed-command-help)
19243 ("<" . (org-agenda-set-restriction-lock 'subtree))
19244 (">" . (org-agenda-remove-restriction-lock))
19246 "The default speed commands.")
19248 (defun org-print-speed-command (e)
19249 (if (> (length (car e)) 1)
19250 (progn
19251 (princ "\n")
19252 (princ (car e))
19253 (princ "\n")
19254 (princ (make-string (length (car e)) ?-))
19255 (princ "\n"))
19256 (princ (car e))
19257 (princ " ")
19258 (if (symbolp (cdr e))
19259 (princ (symbol-name (cdr e)))
19260 (prin1 (cdr e)))
19261 (princ "\n")))
19263 (defun org-speed-command-help ()
19264 "Show the available speed commands."
19265 (interactive)
19266 (if (not org-use-speed-commands)
19267 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19268 (with-output-to-temp-buffer "*Help*"
19269 (princ "User-defined Speed commands\n===========================\n")
19270 (mapc 'org-print-speed-command org-speed-commands-user)
19271 (princ "\n")
19272 (princ "Built-in Speed commands\n=======================\n")
19273 (mapc 'org-print-speed-command org-speed-commands-default))
19274 (with-current-buffer "*Help*"
19275 (setq truncate-lines t))))
19277 (defun org-speed-move-safe (cmd)
19278 "Execute CMD, but make sure that the cursor always ends up in a headline.
19279 If not, return to the original position and throw an error."
19280 (interactive)
19281 (let ((pos (point)))
19282 (call-interactively cmd)
19283 (unless (and (bolp) (org-at-heading-p))
19284 (goto-char pos)
19285 (error "Boundary reached while executing %s" cmd))))
19287 (defvar org-self-insert-command-undo-counter 0)
19289 (defvar org-table-auto-blank-field) ; defined in org-table.el
19290 (defvar org-speed-command nil)
19292 (define-obsolete-function-alias
19293 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19295 (defun org-speed-command-activate (keys)
19296 "Hook for activating single-letter speed commands.
19297 `org-speed-commands-default' specifies a minimal command set.
19298 Use `org-speed-commands-user' for further customization."
19299 (when (or (and (bolp) (looking-at org-outline-regexp))
19300 (and (functionp org-use-speed-commands)
19301 (funcall org-use-speed-commands)))
19302 (cdr (assoc keys (append org-speed-commands-user
19303 org-speed-commands-default)))))
19305 (define-obsolete-function-alias
19306 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19308 (defun org-babel-speed-command-activate (keys)
19309 "Hook for activating single-letter code block commands."
19310 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19311 (cdr (assoc keys org-babel-key-bindings))))
19313 (defcustom org-speed-command-hook
19314 '(org-speed-command-default-hook org-babel-speed-command-hook)
19315 "Hook for activating speed commands at strategic locations.
19316 Hook functions are called in sequence until a valid handler is
19317 found.
19319 Each hook takes a single argument, a user-pressed command key
19320 which is also a `self-insert-command' from the global map.
19322 Within the hook, examine the cursor position and the command key
19323 and return nil or a valid handler as appropriate. Handler could
19324 be one of an interactive command, a function, or a form.
19326 Set `org-use-speed-commands' to non-nil value to enable this
19327 hook. The default setting is `org-speed-command-activate'."
19328 :group 'org-structure
19329 :version "24.1"
19330 :type 'hook)
19332 (defun org-self-insert-command (N)
19333 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19334 If the cursor is in a table looking at whitespace, the whitespace is
19335 overwritten, and the table is not marked as requiring realignment."
19336 (interactive "p")
19337 (org-check-before-invisible-edit 'insert)
19338 (cond
19339 ((and org-use-speed-commands
19340 (setq org-speed-command
19341 (run-hook-with-args-until-success
19342 'org-speed-command-hook (this-command-keys))))
19343 (cond
19344 ((commandp org-speed-command)
19345 (setq this-command org-speed-command)
19346 (call-interactively org-speed-command))
19347 ((functionp org-speed-command)
19348 (funcall org-speed-command))
19349 ((and org-speed-command (listp org-speed-command))
19350 (eval org-speed-command))
19351 (t (let (org-use-speed-commands)
19352 (call-interactively 'org-self-insert-command)))))
19353 ((and
19354 (org-table-p)
19355 (progn
19356 ;; check if we blank the field, and if that triggers align
19357 (and (featurep 'org-table) org-table-auto-blank-field
19358 (member last-command
19359 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19360 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19361 ;; got extra space, this field does not determine column width
19362 (let (org-table-may-need-update) (org-table-blank-field))
19363 ;; no extra space, this field may determine column width
19364 (org-table-blank-field)))
19366 (eq N 1)
19367 (looking-at "[^|\n]* |"))
19368 (let (org-table-may-need-update)
19369 (goto-char (1- (match-end 0)))
19370 (backward-delete-char 1)
19371 (goto-char (match-beginning 0))
19372 (self-insert-command N)))
19374 (setq org-table-may-need-update t)
19375 (self-insert-command N)
19376 (org-fix-tags-on-the-fly)
19377 (if org-self-insert-cluster-for-undo
19378 (if (not (eq last-command 'org-self-insert-command))
19379 (setq org-self-insert-command-undo-counter 1)
19380 (if (>= org-self-insert-command-undo-counter 20)
19381 (setq org-self-insert-command-undo-counter 1)
19382 (and (> org-self-insert-command-undo-counter 0)
19383 buffer-undo-list (listp buffer-undo-list)
19384 (not (cadr buffer-undo-list)) ; remove nil entry
19385 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19386 (setq org-self-insert-command-undo-counter
19387 (1+ org-self-insert-command-undo-counter))))))))
19389 (defun org-check-before-invisible-edit (kind)
19390 "Check is editing if kind KIND would be dangerous with invisible text around.
19391 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19392 ;; First, try to get out of here as quickly as possible, to reduce overhead
19393 (if (and org-catch-invisible-edits
19394 (or (not (boundp 'visible-mode)) (not visible-mode))
19395 (or (get-char-property (point) 'invisible)
19396 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19397 ;; OK, we need to take a closer look
19398 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19399 (invisible-before-point (if (bobp) nil (get-char-property
19400 (1- (point)) 'invisible)))
19401 (border-and-ok-direction
19403 ;; Check if we are acting predictably before invisible text
19404 (and invisible-at-point (not invisible-before-point)
19405 (memq kind '(insert delete-backward)))
19406 ;; Check if we are acting predictably after invisible text
19407 ;; This works not well, and I have turned it off. It seems
19408 ;; better to always show and stop after invisible text.
19409 ;; (and (not invisible-at-point) invisible-before-point
19410 ;; (memq kind '(insert delete)))
19412 (when (or (memq invisible-at-point '(outline org-hide-block t))
19413 (memq invisible-before-point '(outline org-hide-block t)))
19414 (if (eq org-catch-invisible-edits 'error)
19415 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19416 (if (and org-custom-properties-overlays
19417 (y-or-n-p "Display invisible properties in this buffer? "))
19418 (org-toggle-custom-properties-visibility)
19419 ;; Make the area visible
19420 (save-excursion
19421 (if invisible-before-point
19422 (goto-char (previous-single-char-property-change
19423 (point) 'invisible)))
19424 (org-cycle))
19425 (cond
19426 ((eq org-catch-invisible-edits 'show)
19427 ;; That's it, we do the edit after showing
19428 (message
19429 "Unfolding invisible region around point before editing")
19430 (sit-for 1))
19431 ((and (eq org-catch-invisible-edits 'smart)
19432 border-and-ok-direction)
19433 (message "Unfolding invisible region around point before editing"))
19435 ;; Don't do the edit, make the user repeat it in full visibility
19436 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19438 (defun org-fix-tags-on-the-fly ()
19439 (when (and (equal (char-after (point-at-bol)) ?*)
19440 (org-at-heading-p))
19441 (org-align-tags-here org-tags-column)))
19443 (defun org-delete-backward-char (N)
19444 "Like `delete-backward-char', insert whitespace at field end in tables.
19445 When deleting backwards, in tables this function will insert whitespace in
19446 front of the next \"|\" separator, to keep the table aligned. The table will
19447 still be marked for re-alignment if the field did fill the entire column,
19448 because, in this case the deletion might narrow the column."
19449 (interactive "p")
19450 (save-match-data
19451 (org-check-before-invisible-edit 'delete-backward)
19452 (if (and (org-table-p)
19453 (eq N 1)
19454 (string-match "|" (buffer-substring (point-at-bol) (point)))
19455 (looking-at ".*?|"))
19456 (let ((pos (point))
19457 (noalign (looking-at "[^|\n\r]* |"))
19458 (c org-table-may-need-update))
19459 (backward-delete-char N)
19460 (if (not overwrite-mode)
19461 (progn
19462 (skip-chars-forward "^|")
19463 (insert " ")
19464 (goto-char (1- pos))))
19465 ;; noalign: if there were two spaces at the end, this field
19466 ;; does not determine the width of the column.
19467 (if noalign (setq org-table-may-need-update c)))
19468 (backward-delete-char N)
19469 (org-fix-tags-on-the-fly))))
19471 (defun org-delete-char (N)
19472 "Like `delete-char', but insert whitespace at field end in tables.
19473 When deleting characters, in tables this function will insert whitespace in
19474 front of the next \"|\" separator, to keep the table aligned. The table will
19475 still be marked for re-alignment if the field did fill the entire column,
19476 because, in this case the deletion might narrow the column."
19477 (interactive "p")
19478 (save-match-data
19479 (org-check-before-invisible-edit 'delete)
19480 (if (and (org-table-p)
19481 (not (bolp))
19482 (not (= (char-after) ?|))
19483 (eq N 1))
19484 (if (looking-at ".*?|")
19485 (let ((pos (point))
19486 (noalign (looking-at "[^|\n\r]* |"))
19487 (c org-table-may-need-update))
19488 (replace-match
19489 (concat (substring (match-string 0) 1 -1) " |") nil t)
19490 (goto-char pos)
19491 ;; noalign: if there were two spaces at the end, this field
19492 ;; does not determine the width of the column.
19493 (if noalign (setq org-table-may-need-update c)))
19494 (delete-char N))
19495 (delete-char N)
19496 (org-fix-tags-on-the-fly))))
19498 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19499 (put 'org-self-insert-command 'delete-selection t)
19500 (put 'orgtbl-self-insert-command 'delete-selection t)
19501 (put 'org-delete-char 'delete-selection 'supersede)
19502 (put 'org-delete-backward-char 'delete-selection 'supersede)
19503 (put 'org-yank 'delete-selection 'yank)
19505 ;; Make `flyspell-mode' delay after some commands
19506 (put 'org-self-insert-command 'flyspell-delayed t)
19507 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19508 (put 'org-delete-char 'flyspell-delayed t)
19509 (put 'org-delete-backward-char 'flyspell-delayed t)
19511 ;; Make pabbrev-mode expand after org-mode commands
19512 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19513 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19515 ;; How to do this: Measure non-white length of current string
19516 ;; If equal to column width, we should realign.
19518 (defun org-remap (map &rest commands)
19519 "In MAP, remap the functions given in COMMANDS.
19520 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19521 (let (new old)
19522 (while commands
19523 (setq old (pop commands) new (pop commands))
19524 (if (fboundp 'command-remapping)
19525 (org-defkey map (vector 'remap old) new)
19526 (substitute-key-definition old new map global-map)))))
19528 (defun org-transpose-words ()
19529 "Transpose words for Org.
19530 This uses the `org-mode-transpose-word-syntax-table' syntax
19531 table, which interprets characters in `org-emphasis-alist' as
19532 word constituants."
19533 (interactive)
19534 (with-syntax-table org-mode-transpose-word-syntax-table
19535 (call-interactively 'transpose-words)))
19536 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19538 (when (eq org-enable-table-editor 'optimized)
19539 ;; If the user wants maximum table support, we need to hijack
19540 ;; some standard editing functions
19541 (org-remap org-mode-map
19542 'self-insert-command 'org-self-insert-command
19543 'delete-char 'org-delete-char
19544 'delete-backward-char 'org-delete-backward-char)
19545 (org-defkey org-mode-map "|" 'org-force-self-insert))
19547 (defvar org-ctrl-c-ctrl-c-hook nil
19548 "Hook for functions attaching themselves to `C-c C-c'.
19550 This can be used to add additional functionality to the C-c C-c
19551 key which executes context-dependent commands. This hook is run
19552 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19553 run after the last test.
19555 Each function will be called with no arguments. The function
19556 must check if the context is appropriate for it to act. If yes,
19557 it should do its thing and then return a non-nil value. If the
19558 context is wrong, just do nothing and return nil.")
19560 (defvar org-ctrl-c-ctrl-c-final-hook nil
19561 "Hook for functions attaching themselves to `C-c C-c'.
19563 This can be used to add additional functionality to the C-c C-c
19564 key which executes context-dependent commands. This hook is run
19565 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19566 before the first test.
19568 Each function will be called with no arguments. The function
19569 must check if the context is appropriate for it to act. If yes,
19570 it should do its thing and then return a non-nil value. If the
19571 context is wrong, just do nothing and return nil.")
19573 (defvar org-tab-first-hook nil
19574 "Hook for functions to attach themselves to TAB.
19575 See `org-ctrl-c-ctrl-c-hook' for more information.
19576 This hook runs as the first action when TAB is pressed, even before
19577 `org-cycle' messes around with the `outline-regexp' to cater for
19578 inline tasks and plain list item folding.
19579 If any function in this hook returns t, any other actions that
19580 would have been caused by TAB (such as table field motion or visibility
19581 cycling) will not occur.")
19583 (defvar org-tab-after-check-for-table-hook nil
19584 "Hook for functions to attach themselves to TAB.
19585 See `org-ctrl-c-ctrl-c-hook' for more information.
19586 This hook runs after it has been established that the cursor is not in a
19587 table, but before checking if the cursor is in a headline or if global cycling
19588 should be done.
19589 If any function in this hook returns t, not other actions like visibility
19590 cycling will be done.")
19592 (defvar org-tab-after-check-for-cycling-hook nil
19593 "Hook for functions to attach themselves to TAB.
19594 See `org-ctrl-c-ctrl-c-hook' for more information.
19595 This hook runs after it has been established that not table field motion and
19596 not visibility should be done because of current context. This is probably
19597 the place where a package like yasnippets can hook in.")
19599 (defvar org-tab-before-tab-emulation-hook nil
19600 "Hook for functions to attach themselves to TAB.
19601 See `org-ctrl-c-ctrl-c-hook' for more information.
19602 This hook runs after every other options for TAB have been exhausted, but
19603 before indentation and \t insertion takes place.")
19605 (defvar org-metaleft-hook nil
19606 "Hook for functions attaching themselves to `M-left'.
19607 See `org-ctrl-c-ctrl-c-hook' for more information.")
19608 (defvar org-metaright-hook nil
19609 "Hook for functions attaching themselves to `M-right'.
19610 See `org-ctrl-c-ctrl-c-hook' for more information.")
19611 (defvar org-metaup-hook nil
19612 "Hook for functions attaching themselves to `M-up'.
19613 See `org-ctrl-c-ctrl-c-hook' for more information.")
19614 (defvar org-metadown-hook nil
19615 "Hook for functions attaching themselves to `M-down'.
19616 See `org-ctrl-c-ctrl-c-hook' for more information.")
19617 (defvar org-shiftmetaleft-hook nil
19618 "Hook for functions attaching themselves to `M-S-left'.
19619 See `org-ctrl-c-ctrl-c-hook' for more information.")
19620 (defvar org-shiftmetaright-hook nil
19621 "Hook for functions attaching themselves to `M-S-right'.
19622 See `org-ctrl-c-ctrl-c-hook' for more information.")
19623 (defvar org-shiftmetaup-hook nil
19624 "Hook for functions attaching themselves to `M-S-up'.
19625 See `org-ctrl-c-ctrl-c-hook' for more information.")
19626 (defvar org-shiftmetadown-hook nil
19627 "Hook for functions attaching themselves to `M-S-down'.
19628 See `org-ctrl-c-ctrl-c-hook' for more information.")
19629 (defvar org-metareturn-hook nil
19630 "Hook for functions attaching themselves to `M-RET'.
19631 See `org-ctrl-c-ctrl-c-hook' for more information.")
19632 (defvar org-shiftup-hook nil
19633 "Hook for functions attaching themselves to `S-up'.
19634 See `org-ctrl-c-ctrl-c-hook' for more information.")
19635 (defvar org-shiftup-final-hook nil
19636 "Hook for functions attaching themselves to `S-up'.
19637 This one runs after all other options except shift-select have been excluded.
19638 See `org-ctrl-c-ctrl-c-hook' for more information.")
19639 (defvar org-shiftdown-hook nil
19640 "Hook for functions attaching themselves to `S-down'.
19641 See `org-ctrl-c-ctrl-c-hook' for more information.")
19642 (defvar org-shiftdown-final-hook nil
19643 "Hook for functions attaching themselves to `S-down'.
19644 This one runs after all other options except shift-select have been excluded.
19645 See `org-ctrl-c-ctrl-c-hook' for more information.")
19646 (defvar org-shiftleft-hook nil
19647 "Hook for functions attaching themselves to `S-left'.
19648 See `org-ctrl-c-ctrl-c-hook' for more information.")
19649 (defvar org-shiftleft-final-hook nil
19650 "Hook for functions attaching themselves to `S-left'.
19651 This one runs after all other options except shift-select have been excluded.
19652 See `org-ctrl-c-ctrl-c-hook' for more information.")
19653 (defvar org-shiftright-hook nil
19654 "Hook for functions attaching themselves to `S-right'.
19655 See `org-ctrl-c-ctrl-c-hook' for more information.")
19656 (defvar org-shiftright-final-hook nil
19657 "Hook for functions attaching themselves to `S-right'.
19658 This one runs after all other options except shift-select have been excluded.
19659 See `org-ctrl-c-ctrl-c-hook' for more information.")
19661 (defun org-modifier-cursor-error ()
19662 "Throw an error, a modified cursor command was applied in wrong context."
19663 (user-error "This command is active in special context like tables, headlines or items"))
19665 (defun org-shiftselect-error ()
19666 "Throw an error because Shift-Cursor command was applied in wrong context."
19667 (if (and (boundp 'shift-select-mode) shift-select-mode)
19668 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19669 (user-error "This command works only in special context like headlines or timestamps")))
19671 (defun org-call-for-shift-select (cmd)
19672 (let ((this-command-keys-shift-translated t))
19673 (call-interactively cmd)))
19675 (defun org-shifttab (&optional arg)
19676 "Global visibility cycling or move to previous table field.
19677 Call `org-table-previous-field' within a table.
19678 When ARG is nil, cycle globally through visibility states.
19679 When ARG is a numeric prefix, show contents of this level."
19680 (interactive "P")
19681 (cond
19682 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19683 ((integerp arg)
19684 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19685 (message "Content view to level: %d" arg)
19686 (org-content (prefix-numeric-value arg2))
19687 (org-cycle-show-empty-lines t)
19688 (setq org-cycle-global-status 'overview)))
19689 (t (call-interactively 'org-global-cycle))))
19691 (defun org-shiftmetaleft ()
19692 "Promote subtree or delete table column.
19693 Calls `org-promote-subtree', `org-outdent-item-tree', or
19694 `org-table-delete-column', depending on context. See the
19695 individual commands for more information."
19696 (interactive)
19697 (cond
19698 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19699 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19700 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19701 ((if (not (org-region-active-p)) (org-at-item-p)
19702 (save-excursion (goto-char (region-beginning))
19703 (org-at-item-p)))
19704 (call-interactively 'org-outdent-item-tree))
19705 (t (org-modifier-cursor-error))))
19707 (defun org-shiftmetaright ()
19708 "Demote subtree or insert table column.
19709 Calls `org-demote-subtree', `org-indent-item-tree', or
19710 `org-table-insert-column', depending on context. See the
19711 individual commands for more information."
19712 (interactive)
19713 (cond
19714 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19715 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19716 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19717 ((if (not (org-region-active-p)) (org-at-item-p)
19718 (save-excursion (goto-char (region-beginning))
19719 (org-at-item-p)))
19720 (call-interactively 'org-indent-item-tree))
19721 (t (org-modifier-cursor-error))))
19723 (defun org-shiftmetaup (&optional arg)
19724 "Move subtree up or kill table row.
19725 Calls `org-move-subtree-up' or `org-table-kill-row' or
19726 `org-move-item-up' or `org-timestamp-up', depending on context.
19727 See the individual commands for more information."
19728 (interactive "P")
19729 (cond
19730 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19731 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19732 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19733 ((org-at-item-p) (call-interactively 'org-move-item-up))
19734 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19735 (call-interactively 'org-timestamp-up)))
19736 (t (call-interactively 'org-drag-line-backward))))
19738 (defun org-shiftmetadown (&optional arg)
19739 "Move subtree down or insert table row.
19740 Calls `org-move-subtree-down' or `org-table-insert-row' or
19741 `org-move-item-down' or `org-timestamp-up', depending on context.
19742 See the individual commands for more information."
19743 (interactive "P")
19744 (cond
19745 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19746 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19747 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19748 ((org-at-item-p) (call-interactively 'org-move-item-down))
19749 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19750 (call-interactively 'org-timestamp-down)))
19751 (t (call-interactively 'org-drag-line-forward))))
19753 (defsubst org-hidden-tree-error ()
19754 (user-error
19755 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19757 (defun org-metaleft (&optional arg)
19758 "Promote heading or move table column to left.
19759 Calls `org-do-promote' or `org-table-move-column', depending on context.
19760 With no specific context, calls the Emacs default `backward-word'.
19761 See the individual commands for more information."
19762 (interactive "P")
19763 (cond
19764 ((run-hook-with-args-until-success 'org-metaleft-hook))
19765 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19766 ((org-with-limited-levels
19767 (or (org-at-heading-p)
19768 (and (org-region-active-p)
19769 (save-excursion
19770 (goto-char (region-beginning))
19771 (org-at-heading-p)))))
19772 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19773 (call-interactively 'org-do-promote))
19774 ;; At an inline task.
19775 ((org-at-heading-p)
19776 (call-interactively 'org-inlinetask-promote))
19777 ((or (org-at-item-p)
19778 (and (org-region-active-p)
19779 (save-excursion
19780 (goto-char (region-beginning))
19781 (org-at-item-p))))
19782 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19783 (call-interactively 'org-outdent-item))
19784 (t (call-interactively 'backward-word))))
19786 (defun org-metaright (&optional arg)
19787 "Demote a subtree, a list item or move table column to right.
19788 In front of a drawer or a block keyword, indent it correctly.
19789 With no specific context, calls the Emacs default `forward-word'.
19790 See the individual commands for more information."
19791 (interactive "P")
19792 (cond
19793 ((run-hook-with-args-until-success 'org-metaright-hook))
19794 ((org-at-table-p) (call-interactively 'org-table-move-column))
19795 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19796 ((org-at-block-p) (call-interactively 'org-indent-block))
19797 ((org-with-limited-levels
19798 (or (org-at-heading-p)
19799 (and (org-region-active-p)
19800 (save-excursion
19801 (goto-char (region-beginning))
19802 (org-at-heading-p)))))
19803 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19804 (call-interactively 'org-do-demote))
19805 ;; At an inline task.
19806 ((org-at-heading-p)
19807 (call-interactively 'org-inlinetask-demote))
19808 ((or (org-at-item-p)
19809 (and (org-region-active-p)
19810 (save-excursion
19811 (goto-char (region-beginning))
19812 (org-at-item-p))))
19813 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19814 (call-interactively 'org-indent-item))
19815 (t (call-interactively 'forward-word))))
19817 (defun org-check-for-hidden (what)
19818 "Check if there are hidden headlines/items in the current visual line.
19819 WHAT can be either `headlines' or `items'. If the current line is
19820 an outline or item heading and it has a folded subtree below it,
19821 this function returns t, nil otherwise."
19822 (let ((re (cond
19823 ((eq what 'headlines) org-outline-regexp-bol)
19824 ((eq what 'items) (org-item-beginning-re))
19825 (t (error "This should not happen"))))
19826 beg end)
19827 (save-excursion
19828 (catch 'exit
19829 (unless (org-region-active-p)
19830 (setq beg (point-at-bol))
19831 (beginning-of-line 2)
19832 (while (and (not (eobp)) ;; this is like `next-line'
19833 (get-char-property (1- (point)) 'invisible))
19834 (beginning-of-line 2))
19835 (setq end (point))
19836 (goto-char beg)
19837 (goto-char (point-at-eol))
19838 (setq end (max end (point)))
19839 (while (re-search-forward re end t)
19840 (if (get-char-property (match-beginning 0) 'invisible)
19841 (throw 'exit t))))
19842 nil))))
19844 (defun org-metaup (&optional arg)
19845 "Move subtree up or move table row up.
19846 Calls `org-move-subtree-up' or `org-table-move-row' or
19847 `org-move-item-up', depending on context. See the individual commands
19848 for more information."
19849 (interactive "P")
19850 (cond
19851 ((run-hook-with-args-until-success 'org-metaup-hook))
19852 ((org-region-active-p)
19853 (let* ((a (min (region-beginning) (region-end)))
19854 (b (1- (max (region-beginning) (region-end))))
19855 (c (save-excursion (goto-char a)
19856 (move-beginning-of-line 0)))
19857 (d (save-excursion (goto-char a)
19858 (move-end-of-line 0) (point))))
19859 (transpose-regions a b c d)
19860 (goto-char c)))
19861 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19862 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19863 ((org-at-item-p) (call-interactively 'org-move-item-up))
19864 (t (org-drag-element-backward))))
19866 (defun org-metadown (&optional arg)
19867 "Move subtree down or move table row down.
19868 Calls `org-move-subtree-down' or `org-table-move-row' or
19869 `org-move-item-down', depending on context. See the individual
19870 commands for more information."
19871 (interactive "P")
19872 (cond
19873 ((run-hook-with-args-until-success 'org-metadown-hook))
19874 ((org-region-active-p)
19875 (let* ((a (min (region-beginning) (region-end)))
19876 (b (max (region-beginning) (region-end)))
19877 (c (save-excursion (goto-char b)
19878 (move-beginning-of-line 1)))
19879 (d (save-excursion (goto-char b)
19880 (move-end-of-line 1) (1+ (point)))))
19881 (transpose-regions a b c d)
19882 (goto-char d)))
19883 ((org-at-table-p) (call-interactively 'org-table-move-row))
19884 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19885 ((org-at-item-p) (call-interactively 'org-move-item-down))
19886 (t (org-drag-element-forward))))
19888 (defun org-shiftup (&optional arg)
19889 "Increase item in timestamp or increase priority of current headline.
19890 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19891 depending on context. See the individual commands for more information."
19892 (interactive "P")
19893 (cond
19894 ((run-hook-with-args-until-success 'org-shiftup-hook))
19895 ((and org-support-shift-select (org-region-active-p))
19896 (org-call-for-shift-select 'previous-line))
19897 ((org-at-timestamp-p t)
19898 (call-interactively (if org-edit-timestamp-down-means-later
19899 'org-timestamp-down 'org-timestamp-up)))
19900 ((and (not (eq org-support-shift-select 'always))
19901 org-enable-priority-commands
19902 (org-at-heading-p))
19903 (call-interactively 'org-priority-up))
19904 ((and (not org-support-shift-select) (org-at-item-p))
19905 (call-interactively 'org-previous-item))
19906 ((org-clocktable-try-shift 'up arg))
19907 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19908 (org-support-shift-select
19909 (org-call-for-shift-select 'previous-line))
19910 (t (org-shiftselect-error))))
19912 (defun org-shiftdown (&optional arg)
19913 "Decrease item in timestamp or decrease priority of current headline.
19914 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19915 depending on context. See the individual commands for more information."
19916 (interactive "P")
19917 (cond
19918 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19919 ((and org-support-shift-select (org-region-active-p))
19920 (org-call-for-shift-select 'next-line))
19921 ((org-at-timestamp-p t)
19922 (call-interactively (if org-edit-timestamp-down-means-later
19923 'org-timestamp-up 'org-timestamp-down)))
19924 ((and (not (eq org-support-shift-select 'always))
19925 org-enable-priority-commands
19926 (org-at-heading-p))
19927 (call-interactively 'org-priority-down))
19928 ((and (not org-support-shift-select) (org-at-item-p))
19929 (call-interactively 'org-next-item))
19930 ((org-clocktable-try-shift 'down arg))
19931 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19932 (org-support-shift-select
19933 (org-call-for-shift-select 'next-line))
19934 (t (org-shiftselect-error))))
19936 (defun org-shiftright (&optional arg)
19937 "Cycle the thing at point or in the current line, depending on context.
19938 Depending on context, this does one of the following:
19940 - switch a timestamp at point one day into the future
19941 - on a headline, switch to the next TODO keyword.
19942 - on an item, switch entire list to the next bullet type
19943 - on a property line, switch to the next allowed value
19944 - on a clocktable definition line, move time block into the future"
19945 (interactive "P")
19946 (cond
19947 ((run-hook-with-args-until-success 'org-shiftright-hook))
19948 ((and org-support-shift-select (org-region-active-p))
19949 (org-call-for-shift-select 'forward-char))
19950 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19951 ((and (not (eq org-support-shift-select 'always))
19952 (org-at-heading-p))
19953 (let ((org-inhibit-logging
19954 (not org-treat-S-cursor-todo-selection-as-state-change))
19955 (org-inhibit-blocking
19956 (not org-treat-S-cursor-todo-selection-as-state-change)))
19957 (org-call-with-arg 'org-todo 'right)))
19958 ((or (and org-support-shift-select
19959 (not (eq org-support-shift-select 'always))
19960 (org-at-item-bullet-p))
19961 (and (not org-support-shift-select) (org-at-item-p)))
19962 (org-call-with-arg 'org-cycle-list-bullet nil))
19963 ((and (not (eq org-support-shift-select 'always))
19964 (org-at-property-p))
19965 (call-interactively 'org-property-next-allowed-value))
19966 ((org-clocktable-try-shift 'right arg))
19967 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19968 (org-support-shift-select
19969 (org-call-for-shift-select 'forward-char))
19970 (t (org-shiftselect-error))))
19972 (defun org-shiftleft (&optional arg)
19973 "Cycle the thing at point or in the current line, depending on context.
19974 Depending on context, this does one of the following:
19976 - switch a timestamp at point one day into the past
19977 - on a headline, switch to the previous TODO keyword.
19978 - on an item, switch entire list to the previous bullet type
19979 - on a property line, switch to the previous allowed value
19980 - on a clocktable definition line, move time block into the past"
19981 (interactive "P")
19982 (cond
19983 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19984 ((and org-support-shift-select (org-region-active-p))
19985 (org-call-for-shift-select 'backward-char))
19986 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19987 ((and (not (eq org-support-shift-select 'always))
19988 (org-at-heading-p))
19989 (let ((org-inhibit-logging
19990 (not org-treat-S-cursor-todo-selection-as-state-change))
19991 (org-inhibit-blocking
19992 (not org-treat-S-cursor-todo-selection-as-state-change)))
19993 (org-call-with-arg 'org-todo 'left)))
19994 ((or (and org-support-shift-select
19995 (not (eq org-support-shift-select 'always))
19996 (org-at-item-bullet-p))
19997 (and (not org-support-shift-select) (org-at-item-p)))
19998 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19999 ((and (not (eq org-support-shift-select 'always))
20000 (org-at-property-p))
20001 (call-interactively 'org-property-previous-allowed-value))
20002 ((org-clocktable-try-shift 'left arg))
20003 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20004 (org-support-shift-select
20005 (org-call-for-shift-select 'backward-char))
20006 (t (org-shiftselect-error))))
20008 (defun org-shiftcontrolright ()
20009 "Switch to next TODO set."
20010 (interactive)
20011 (cond
20012 ((and org-support-shift-select (org-region-active-p))
20013 (org-call-for-shift-select 'forward-word))
20014 ((and (not (eq org-support-shift-select 'always))
20015 (org-at-heading-p))
20016 (org-call-with-arg 'org-todo 'nextset))
20017 (org-support-shift-select
20018 (org-call-for-shift-select 'forward-word))
20019 (t (org-shiftselect-error))))
20021 (defun org-shiftcontrolleft ()
20022 "Switch to previous TODO set."
20023 (interactive)
20024 (cond
20025 ((and org-support-shift-select (org-region-active-p))
20026 (org-call-for-shift-select 'backward-word))
20027 ((and (not (eq org-support-shift-select 'always))
20028 (org-at-heading-p))
20029 (org-call-with-arg 'org-todo 'previousset))
20030 (org-support-shift-select
20031 (org-call-for-shift-select 'backward-word))
20032 (t (org-shiftselect-error))))
20034 (defun org-shiftcontrolup (&optional n)
20035 "Change timestamps synchronously up in CLOCK log lines.
20036 Optional argument N tells to change by that many units."
20037 (interactive "P")
20038 (cond ((and (not org-support-shift-select)
20039 (org-at-clock-log-p)
20040 (org-at-timestamp-p t))
20041 (org-clock-timestamps-up n))
20042 (t (org-shiftselect-error))))
20044 (defun org-shiftcontroldown (&optional n)
20045 "Change timestamps synchronously down in CLOCK log lines.
20046 Optional argument N tells to change by that many units."
20047 (interactive "P")
20048 (cond ((and (not org-support-shift-select)
20049 (org-at-clock-log-p)
20050 (org-at-timestamp-p t))
20051 (org-clock-timestamps-down n))
20052 (t (org-shiftselect-error))))
20054 (defun org-ctrl-c-ret ()
20055 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20056 (interactive)
20057 (cond
20058 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20059 (t (call-interactively 'org-insert-heading))))
20061 (defun org-find-visible ()
20062 (let ((s (point)))
20063 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20064 (get-char-property s 'invisible)))
20066 (defun org-find-invisible ()
20067 (let ((s (point)))
20068 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20069 (not (get-char-property s 'invisible))))
20072 (defun org-copy-visible (beg end)
20073 "Copy the visible parts of the region."
20074 (interactive "r")
20075 (let (snippets s)
20076 (save-excursion
20077 (save-restriction
20078 (narrow-to-region beg end)
20079 (setq s (goto-char (point-min)))
20080 (while (not (= (point) (point-max)))
20081 (goto-char (org-find-invisible))
20082 (push (buffer-substring s (point)) snippets)
20083 (setq s (goto-char (org-find-visible))))))
20084 (kill-new (apply 'concat (nreverse snippets)))))
20086 (defun org-copy-special ()
20087 "Copy region in table or copy current subtree.
20088 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20089 See the individual commands for more information."
20090 (interactive)
20091 (call-interactively
20092 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20094 (defun org-cut-special ()
20095 "Cut region in table or cut current subtree.
20096 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20097 See the individual commands for more information."
20098 (interactive)
20099 (call-interactively
20100 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20102 (defun org-paste-special (arg)
20103 "Paste rectangular region into table, or past subtree relative to level.
20104 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20105 See the individual commands for more information."
20106 (interactive "P")
20107 (if (org-at-table-p)
20108 (org-table-paste-rectangle)
20109 (org-paste-subtree arg)))
20111 (defsubst org-in-fixed-width-region-p ()
20112 "Is point in a fixed-width region?"
20113 (save-match-data
20114 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20116 (defun org-edit-special (&optional arg)
20117 "Call a special editor for the element at point.
20118 When at a table, call the formula editor with `org-table-edit-formulas'.
20119 When in a source code block, call `org-edit-src-code'.
20120 When in a fixed-width region, call `org-edit-fixed-width-region'.
20121 When at an #+INCLUDE keyword, visit the included file.
20122 On a link, call `ffap' to visit the link at point.
20123 Otherwise, return a user error."
20124 (interactive "P")
20125 (let ((element (org-element-at-point)))
20126 (assert (not buffer-read-only) nil
20127 "Buffer is read-only: %s" (buffer-name))
20128 (case (org-element-type element)
20129 (src-block
20130 (if (not arg) (org-edit-src-code)
20131 (let* ((info (org-babel-get-src-block-info))
20132 (lang (nth 0 info))
20133 (params (nth 2 info))
20134 (session (cdr (assq :session params))))
20135 (if (not session) (org-edit-src-code)
20136 ;; At a src-block with a session and function called with
20137 ;; an ARG: switch to the buffer related to the inferior
20138 ;; process.
20139 (switch-to-buffer
20140 (funcall (intern (concat "org-babel-prep-session:" lang))
20141 session params))))))
20142 (keyword
20143 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20144 (find-file
20145 (org-remove-double-quotes
20146 (car (org-split-string (org-element-property :value element)))))
20147 (user-error "No special environment to edit here")))
20148 (table
20149 (if (eq (org-element-property :type element) 'table.el)
20150 (org-edit-src-code)
20151 (call-interactively 'org-table-edit-formulas)))
20152 ;; Only Org tables contain `table-row' type elements.
20153 (table-row (call-interactively 'org-table-edit-formulas))
20154 ((example-block export-block) (org-edit-src-code))
20155 (fixed-width (org-edit-fixed-width-region))
20156 (otherwise
20157 ;; No notable element at point. Though, we may be at a link,
20158 ;; which is an object. Thus, scan deeper.
20159 (if (eq (org-element-type (org-element-context element)) 'link)
20160 (call-interactively 'ffap)
20161 (user-error "No special environment to edit here"))))))
20163 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20164 (defun org-ctrl-c-ctrl-c (&optional arg)
20165 "Set tags in headline, or update according to changed information at point.
20167 This command does many different things, depending on context:
20169 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20170 this is what we do.
20172 - If the cursor is on a statistics cookie, update it.
20174 - If the cursor is in a headline, prompt for tags and insert them
20175 into the current line, aligned to `org-tags-column'. When called
20176 with prefix arg, realign all tags in the current buffer.
20178 - If the cursor is in one of the special #+KEYWORD lines, this
20179 triggers scanning the buffer for these lines and updating the
20180 information.
20182 - If the cursor is inside a table, realign the table. This command
20183 works even if the automatic table editor has been turned off.
20185 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20186 the entire table.
20188 - If the cursor is at a footnote reference or definition, jump to
20189 the corresponding definition or references, respectively.
20191 - If the cursor is a the beginning of a dynamic block, update it.
20193 - If the current buffer is a capture buffer, close note and file it.
20195 - If the cursor is on a <<<target>>>, update radio targets and
20196 corresponding links in this buffer.
20198 - If the cursor is on a numbered item in a plain list, renumber the
20199 ordered list.
20201 - If the cursor is on a checkbox, toggle it.
20203 - If the cursor is on a code block, evaluate it. The variable
20204 `org-confirm-babel-evaluate' can be used to control prompting
20205 before code block evaluation, by default every code block
20206 evaluation requires confirmation. Code block evaluation can be
20207 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20208 (interactive "P")
20209 (cond
20210 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20211 org-occur-highlights
20212 org-latex-fragment-image-overlays)
20213 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20214 (org-remove-occur-highlights)
20215 (org-remove-latex-fragment-image-overlays)
20216 (message "Temporary highlights/overlays removed from current buffer"))
20217 ((and (local-variable-p 'org-finish-function (current-buffer))
20218 (fboundp org-finish-function))
20219 (funcall org-finish-function))
20220 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20222 (let* ((context (org-element-context)) (type (org-element-type context)))
20223 ;; Test if point is within a blank line.
20224 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20225 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20226 (user-error "C-c C-c can do nothing useful at this location"))
20227 ;; When at a link, act according to the parent instead.
20228 (when (eq type 'link)
20229 (setq context (org-element-property :parent context))
20230 (setq type (org-element-type context)))
20231 ;; For convenience: at the first line of a paragraph on the
20232 ;; same line as an item, apply function on that item instead.
20233 (when (eq type 'paragraph)
20234 (let ((parent (org-element-property :parent context)))
20235 (when (and (eq (org-element-type parent) 'item)
20236 (= (point-at-bol) (org-element-property :begin parent)))
20237 (setq context parent type 'item))))
20238 ;; Act according to type of element or object at point.
20239 (case type
20240 (clock (org-clock-update-time-maybe))
20241 (dynamic-block
20242 (save-excursion
20243 (goto-char (org-element-property :post-affiliated context))
20244 (org-update-dblock)))
20245 (footnote-definition
20246 (goto-char (org-element-property :post-affiliated context))
20247 (call-interactively 'org-footnote-action))
20248 (footnote-reference (call-interactively 'org-footnote-action))
20249 ((headline inlinetask)
20250 (save-excursion (goto-char (org-element-property :begin context))
20251 (call-interactively 'org-set-tags)))
20252 (item
20253 ;; At an item: a double C-u set checkbox to "[-]"
20254 ;; unconditionally, whereas a single one will toggle its
20255 ;; presence. Without an universal argument, if the item
20256 ;; has a checkbox, toggle it. Otherwise repair the list.
20257 (let* ((box (org-element-property :checkbox context))
20258 (struct (org-element-property :structure context))
20259 (old-struct (copy-tree struct))
20260 (parents (org-list-parents-alist struct))
20261 (prevs (org-list-prevs-alist struct))
20262 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20263 (org-list-set-checkbox
20264 (org-element-property :begin context) struct
20265 (cond ((equal arg '(16)) "[-]")
20266 ((and (not box) (equal arg '(4))) "[ ]")
20267 ((or (not box) (equal arg '(4))) nil)
20268 ((eq box 'on) "[ ]")
20269 (t "[X]")))
20270 ;; Mimic `org-list-write-struct' but with grabbing
20271 ;; a return value from `org-list-struct-fix-box'.
20272 (org-list-struct-fix-ind struct parents 2)
20273 (org-list-struct-fix-item-end struct)
20274 (org-list-struct-fix-bul struct prevs)
20275 (org-list-struct-fix-ind struct parents)
20276 (let ((block-item
20277 (org-list-struct-fix-box struct parents prevs orderedp)))
20278 (if (and box (equal struct old-struct))
20279 (if (equal arg '(16))
20280 (message "Checkboxes already reset")
20281 (user-error "Cannot toggle this checkbox: %s"
20282 (if (eq box 'on)
20283 "all subitems checked"
20284 "unchecked subitems")))
20285 (org-list-struct-apply-struct struct old-struct)
20286 (org-update-checkbox-count-maybe))
20287 (when block-item
20288 (message "Checkboxes were removed due to empty box at line %d"
20289 (org-current-line block-item))))))
20290 (keyword
20291 (let ((org-inhibit-startup-visibility-stuff t)
20292 (org-startup-align-all-tables nil))
20293 (when (boundp 'org-table-coordinate-overlays)
20294 (mapc 'delete-overlay org-table-coordinate-overlays)
20295 (setq org-table-coordinate-overlays nil))
20296 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20297 (message "Local setup has been refreshed"))
20298 (plain-list
20299 ;; At a plain list, with a double C-u argument, set
20300 ;; checkboxes of each item to "[-]", whereas a single one
20301 ;; will toggle their presence according to the state of the
20302 ;; first item in the list. Without an argument, repair the
20303 ;; list.
20304 (let* ((begin (org-element-property :contents-begin context))
20305 (beginm (move-marker (make-marker) begin))
20306 (struct (org-element-property :structure context))
20307 (old-struct (copy-tree struct))
20308 (first-box (save-excursion
20309 (goto-char begin)
20310 (looking-at org-list-full-item-re)
20311 (match-string-no-properties 3)))
20312 (new-box (cond ((equal arg '(16)) "[-]")
20313 ((equal arg '(4)) (unless first-box "[ ]"))
20314 ((equal first-box "[X]") "[ ]")
20315 (t "[X]"))))
20316 (cond
20317 (arg
20318 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20319 (org-list-get-all-items
20320 begin struct (org-list-prevs-alist struct))))
20321 ((and first-box (eq (point) begin))
20322 ;; For convenience, when point is at bol on the first
20323 ;; item of the list and no argument is provided, simply
20324 ;; toggle checkbox of that item, if any.
20325 (org-list-set-checkbox begin struct new-box)))
20326 (org-list-write-struct
20327 struct (org-list-parents-alist struct) old-struct)
20328 (org-update-checkbox-count-maybe)
20329 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20330 ((property-drawer node-property)
20331 (call-interactively 'org-property-action))
20332 ((radio-target target)
20333 (call-interactively 'org-update-radio-target-regexp))
20334 (statistics-cookie
20335 (call-interactively 'org-update-statistics-cookies))
20336 ((table table-cell table-row)
20337 ;; At a table, recalculate every field and align it. Also
20338 ;; send the table if necessary. If the table has
20339 ;; a `table.el' type, just give up. At a table row or
20340 ;; cell, maybe recalculate line but always align table.
20341 (if (eq (org-element-property :type context) 'table.el)
20342 (message "Use C-c ' to edit table.el tables")
20343 (let ((org-enable-table-editor t))
20344 (if (or (eq type 'table)
20345 ;; Check if point is at a TBLFM line.
20346 (and (eq type 'table-row)
20347 (= (point) (org-element-property :end context))))
20348 (save-excursion
20349 (if (org-at-TBLFM-p)
20350 (progn (require 'org-table)
20351 (org-table-calc-current-TBLFM))
20352 (goto-char (org-element-property :contents-begin context))
20353 (org-call-with-arg 'org-table-recalculate (or arg t))
20354 (orgtbl-send-table 'maybe)))
20355 (org-table-maybe-eval-formula)
20356 (cond (arg (call-interactively 'org-table-recalculate))
20357 ((org-table-maybe-recalculate-line))
20358 (t (org-table-align)))))))
20359 (timestamp (org-timestamp-change 0 'day))
20360 (otherwise
20361 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20362 (user-error
20363 "C-c C-c can do nothing useful at this location")))))))))
20365 (defun org-mode-restart ()
20366 "Restart Org-mode, to scan again for special lines.
20367 Also updates the keyword regular expressions."
20368 (interactive)
20369 (org-mode)
20370 (message "Org-mode restarted"))
20372 (defun org-kill-note-or-show-branches ()
20373 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20374 (interactive)
20375 (if (not org-finish-function)
20376 (progn
20377 (hide-subtree)
20378 (call-interactively 'show-branches))
20379 (let ((org-note-abort t))
20380 (funcall org-finish-function))))
20382 (defun org-open-line (n)
20383 "Insert a new row in tables, call `open-line' elsewhere.
20384 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20385 (interactive "*p")
20386 (cond
20387 ((not org-special-ctrl-o)
20388 (open-line n))
20389 ((org-at-table-p)
20390 (org-table-insert-row))
20392 (open-line n))))
20394 (defun org-return (&optional indent)
20395 "Goto next table row or insert a newline.
20396 Calls `org-table-next-row' or `newline', depending on context.
20397 See the individual commands for more information."
20398 (interactive)
20399 (let (org-ts-what)
20400 (cond
20401 ((or (bobp) (org-in-src-block-p))
20402 (if indent (newline-and-indent) (newline)))
20403 ((org-at-table-p)
20404 (org-table-justify-field-maybe)
20405 (call-interactively 'org-table-next-row))
20406 ;; when `newline-and-indent' is called within a list, make sure
20407 ;; text moved stays inside the item.
20408 ((and (org-in-item-p) indent)
20409 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20410 (progn
20411 (save-match-data (newline))
20412 (org-indent-line-to (length (match-string 0))))
20413 (let ((ind (org-get-indentation)))
20414 (newline)
20415 (if (org-looking-back org-list-end-re)
20416 (org-indent-line)
20417 (org-indent-line-to ind)))))
20418 ((and org-return-follows-link
20419 (org-at-timestamp-p t)
20420 (not (eq org-ts-what 'after)))
20421 (org-follow-timestamp-link))
20422 ((and org-return-follows-link
20423 (let ((tprop (get-text-property (point) 'face)))
20424 (or (eq tprop 'org-link)
20425 (and (listp tprop) (memq 'org-link tprop)))))
20426 (call-interactively 'org-open-at-point))
20427 ((and (org-at-heading-p)
20428 (looking-at
20429 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20430 (org-show-entry)
20431 (end-of-line 1)
20432 (newline))
20433 (t (if indent (newline-and-indent) (newline))))))
20435 (defun org-return-indent ()
20436 "Goto next table row or insert a newline and indent.
20437 Calls `org-table-next-row' or `newline-and-indent', depending on
20438 context. See the individual commands for more information."
20439 (interactive)
20440 (org-return t))
20442 (defun org-ctrl-c-star ()
20443 "Compute table, or change heading status of lines.
20444 Calls `org-table-recalculate' or `org-toggle-heading',
20445 depending on context."
20446 (interactive)
20447 (cond
20448 ((org-at-table-p)
20449 (call-interactively 'org-table-recalculate))
20451 ;; Convert all lines in region to list items
20452 (call-interactively 'org-toggle-heading))))
20454 (defun org-ctrl-c-minus ()
20455 "Insert separator line in table or modify bullet status of line.
20456 Also turns a plain line or a region of lines into list items.
20457 Calls `org-table-insert-hline', `org-toggle-item', or
20458 `org-cycle-list-bullet', depending on context."
20459 (interactive)
20460 (cond
20461 ((org-at-table-p)
20462 (call-interactively 'org-table-insert-hline))
20463 ((org-region-active-p)
20464 (call-interactively 'org-toggle-item))
20465 ((org-in-item-p)
20466 (call-interactively 'org-cycle-list-bullet))
20468 (call-interactively 'org-toggle-item))))
20470 (defun org-toggle-item (arg)
20471 "Convert headings or normal lines to items, items to normal lines.
20472 If there is no active region, only the current line is considered.
20474 If the first non blank line in the region is a headline, convert
20475 all headlines to items, shifting text accordingly.
20477 If it is an item, convert all items to normal lines.
20479 If it is normal text, change region into a list of items.
20480 With a prefix argument ARG, change the region in a single item."
20481 (interactive "P")
20482 (let ((shift-text
20483 (function
20484 ;; Shift text in current section to IND, from point to END.
20485 ;; The function leaves point to END line.
20486 (lambda (ind end)
20487 (let ((min-i 1000) (end (copy-marker end)))
20488 ;; First determine the minimum indentation (MIN-I) of
20489 ;; the text.
20490 (save-excursion
20491 (catch 'exit
20492 (while (< (point) end)
20493 (let ((i (org-get-indentation)))
20494 (cond
20495 ;; Skip blank lines and inline tasks.
20496 ((looking-at "^[ \t]*$"))
20497 ((looking-at org-outline-regexp-bol))
20498 ;; We can't find less than 0 indentation.
20499 ((zerop i) (throw 'exit (setq min-i 0)))
20500 ((< i min-i) (setq min-i i))))
20501 (forward-line))))
20502 ;; Then indent each line so that a line indented to
20503 ;; MIN-I becomes indented to IND. Ignore blank lines
20504 ;; and inline tasks in the process.
20505 (let ((delta (- ind min-i)))
20506 (while (< (point) end)
20507 (unless (or (looking-at "^[ \t]*$")
20508 (looking-at org-outline-regexp-bol))
20509 (org-indent-line-to (+ (org-get-indentation) delta)))
20510 (forward-line)))))))
20511 (skip-blanks
20512 (function
20513 ;; Return beginning of first non-blank line, starting from
20514 ;; line at POS.
20515 (lambda (pos)
20516 (save-excursion
20517 (goto-char pos)
20518 (skip-chars-forward " \r\t\n")
20519 (point-at-bol)))))
20520 beg end)
20521 ;; Determine boundaries of changes.
20522 (if (org-region-active-p)
20523 (setq beg (funcall skip-blanks (region-beginning))
20524 end (copy-marker (region-end)))
20525 (setq beg (funcall skip-blanks (point-at-bol))
20526 end (copy-marker (point-at-eol))))
20527 ;; Depending on the starting line, choose an action on the text
20528 ;; between BEG and END.
20529 (org-with-limited-levels
20530 (save-excursion
20531 (goto-char beg)
20532 (cond
20533 ;; Case 1. Start at an item: de-itemize. Note that it only
20534 ;; happens when a region is active: `org-ctrl-c-minus'
20535 ;; would call `org-cycle-list-bullet' otherwise.
20536 ((org-at-item-p)
20537 (while (< (point) end)
20538 (when (org-at-item-p)
20539 (skip-chars-forward " \t")
20540 (delete-region (point) (match-end 0)))
20541 (forward-line)))
20542 ;; Case 2. Start at an heading: convert to items.
20543 ((org-at-heading-p)
20544 (let* ((bul (org-list-bullet-string "-"))
20545 (bul-len (length bul))
20546 ;; Indentation of the first heading. It should be
20547 ;; relative to the indentation of its parent, if any.
20548 (start-ind (save-excursion
20549 (cond
20550 ((not org-adapt-indentation) 0)
20551 ((not (outline-previous-heading)) 0)
20552 (t (length (match-string 0))))))
20553 ;; Level of first heading. Further headings will be
20554 ;; compared to it to determine hierarchy in the list.
20555 (ref-level (org-reduced-level (org-outline-level))))
20556 (while (< (point) end)
20557 (let* ((level (org-reduced-level (org-outline-level)))
20558 (delta (max 0 (- level ref-level))))
20559 ;; If current headline is less indented than the first
20560 ;; one, set it as reference, in order to preserve
20561 ;; subtrees.
20562 (when (< level ref-level) (setq ref-level level))
20563 (replace-match bul t t)
20564 (org-indent-line-to (+ start-ind (* delta bul-len)))
20565 ;; Ensure all text down to END (or SECTION-END) belongs
20566 ;; to the newly created item.
20567 (let ((section-end (save-excursion
20568 (or (outline-next-heading) (point)))))
20569 (forward-line)
20570 (funcall shift-text
20571 (+ start-ind (* (1+ delta) bul-len))
20572 (min end section-end)))))))
20573 ;; Case 3. Normal line with ARG: make the first line of region
20574 ;; an item, and shift indentation of others lines to
20575 ;; set them as item's body.
20576 (arg (let* ((bul (org-list-bullet-string "-"))
20577 (bul-len (length bul))
20578 (ref-ind (org-get-indentation)))
20579 (skip-chars-forward " \t")
20580 (insert bul)
20581 (forward-line)
20582 (while (< (point) end)
20583 ;; Ensure that lines less indented than first one
20584 ;; still get included in item body.
20585 (funcall shift-text
20586 (+ ref-ind bul-len)
20587 (min end (save-excursion (or (outline-next-heading)
20588 (point)))))
20589 (forward-line))))
20590 ;; Case 4. Normal line without ARG: turn each non-item line
20591 ;; into an item.
20593 (while (< (point) end)
20594 (unless (or (org-at-heading-p) (org-at-item-p))
20595 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20596 (replace-match
20597 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20598 (forward-line))))))))
20600 (defun org-toggle-heading (&optional nstars)
20601 "Convert headings to normal text, or items or text to headings.
20602 If there is no active region, only convert the current line.
20604 With a \\[universal-argument] prefix, convert the whole list at
20605 point into heading.
20607 In a region:
20609 - If the first non blank line is a headline, remove the stars
20610 from all headlines in the region.
20612 - If it is a normal line, turn each and every normal line (i.e.,
20613 not an heading or an item) in the region into headings. If you
20614 want to convert only the first line of this region, use one
20615 universal prefix argument.
20617 - If it is a plain list item, turn all plain list items into headings.
20619 When converting a line into a heading, the number of stars is chosen
20620 such that the lines become children of the current entry. However,
20621 when a numeric prefix argument is given, its value determines the
20622 number of stars to add."
20623 (interactive "P")
20624 (let ((skip-blanks
20625 (function
20626 ;; Return beginning of first non-blank line, starting from
20627 ;; line at POS.
20628 (lambda (pos)
20629 (save-excursion
20630 (goto-char pos)
20631 (while (org-at-comment-p) (forward-line))
20632 (skip-chars-forward " \r\t\n")
20633 (point-at-bol)))))
20634 beg end toggled)
20635 ;; Determine boundaries of changes. If a universal prefix has
20636 ;; been given, put the list in a region. If region ends at a bol,
20637 ;; do not consider the last line to be in the region.
20639 (when (and current-prefix-arg (org-at-item-p))
20640 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20641 (org-mark-element))
20643 (if (org-region-active-p)
20644 (setq beg (funcall skip-blanks (region-beginning))
20645 end (copy-marker (save-excursion
20646 (goto-char (region-end))
20647 (if (bolp) (point) (point-at-eol)))))
20648 (setq beg (funcall skip-blanks (point-at-bol))
20649 end (copy-marker (point-at-eol))))
20650 ;; Ensure inline tasks don't count as headings.
20651 (org-with-limited-levels
20652 (save-excursion
20653 (goto-char beg)
20654 (cond
20655 ;; Case 1. Started at an heading: de-star headings.
20656 ((org-at-heading-p)
20657 (while (< (point) end)
20658 (when (org-at-heading-p t)
20659 (looking-at org-outline-regexp) (replace-match "")
20660 (setq toggled t))
20661 (forward-line)))
20662 ;; Case 2. Started at an item: change items into headlines.
20663 ;; One star will be added by `org-list-to-subtree'.
20664 ((org-at-item-p)
20665 (let* ((stars (make-string
20666 ;; subtract the star that will be added again by
20667 ;; `org-list-to-subtree'
20668 (if (numberp nstars) (1- nstars)
20669 (or (org-current-level) 0))
20670 ?*))
20671 (add-stars
20672 (cond (nstars "") ; stars from prefix only
20673 ((equal stars "") "") ; before first heading
20674 (org-odd-levels-only "*") ; inside heading, odd
20675 (t "")))) ; inside heading, oddeven
20676 (while (< (point) end)
20677 (when (org-at-item-p)
20678 ;; Pay attention to cases when region ends before list.
20679 (let* ((struct (org-list-struct))
20680 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20681 (save-restriction
20682 (narrow-to-region (point) list-end)
20683 (insert
20684 (org-list-to-subtree
20685 (org-list-parse-list t)
20686 '(:istart (concat stars add-stars (funcall get-stars depth))
20687 :icount (concat stars add-stars (funcall get-stars depth)))))))
20688 (setq toggled t))
20689 (forward-line))))
20690 ;; Case 3. Started at normal text: make every line an heading,
20691 ;; skipping headlines and items.
20692 (t (let* ((stars
20693 (make-string
20694 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20695 (add-stars
20696 (cond (nstars "") ; stars from prefix only
20697 ((equal stars "") "*") ; before first heading
20698 (org-odd-levels-only "**") ; inside heading, odd
20699 (t "*"))) ; inside heading, oddeven
20700 (rpl (concat stars add-stars " "))
20701 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20702 (while (< (point) (if (equal nstars '(4)) lend end))
20703 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20704 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20705 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20706 (forward-line)))))))
20707 (unless toggled (message "Cannot toggle heading from here"))))
20709 (defun org-meta-return (&optional arg)
20710 "Insert a new heading or wrap a region in a table.
20711 Calls `org-insert-heading' or `org-table-wrap-region', depending
20712 on context. See the individual commands for more information."
20713 (interactive "P")
20714 (org-check-before-invisible-edit 'insert)
20715 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20716 (let* ((element (org-element-at-point))
20717 (type (org-element-type element)))
20718 (when (eq type 'table-row)
20719 (setq element (org-element-property :parent element))
20720 (setq type 'table))
20721 (if (and (eq type 'table)
20722 (eq (org-element-property :type element) 'org)
20723 (>= (point) (org-element-property :contents-begin element))
20724 (< (point) (org-element-property :contents-end element)))
20725 (call-interactively 'org-table-wrap-region)
20726 (call-interactively 'org-insert-heading)))))
20728 ;;; Menu entries
20730 (defsubst org-in-subtree-not-table-p ()
20731 "Are we in a subtree and not in a table?"
20732 (and (not (org-before-first-heading-p))
20733 (not (org-at-table-p))))
20735 ;; Define the Org-mode menus
20736 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20737 '("Tbl"
20738 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20739 ["Next Field" org-cycle (org-at-table-p)]
20740 ["Previous Field" org-shifttab (org-at-table-p)]
20741 ["Next Row" org-return (org-at-table-p)]
20742 "--"
20743 ["Blank Field" org-table-blank-field (org-at-table-p)]
20744 ["Edit Field" org-table-edit-field (org-at-table-p)]
20745 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20746 "--"
20747 ("Column"
20748 ["Move Column Left" org-metaleft (org-at-table-p)]
20749 ["Move Column Right" org-metaright (org-at-table-p)]
20750 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20751 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20752 ("Row"
20753 ["Move Row Up" org-metaup (org-at-table-p)]
20754 ["Move Row Down" org-metadown (org-at-table-p)]
20755 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20756 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20757 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20758 "--"
20759 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20760 ("Rectangle"
20761 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20762 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20763 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20764 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20765 "--"
20766 ("Calculate"
20767 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20768 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20769 ["Edit Formulas" org-edit-special (org-at-table-p)]
20770 "--"
20771 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20772 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20773 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20774 "--"
20775 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20776 "--"
20777 ["Sum Column/Rectangle" org-table-sum
20778 (or (org-at-table-p) (org-region-active-p))]
20779 ["Which Column?" org-table-current-column (org-at-table-p)])
20780 ["Debug Formulas"
20781 org-table-toggle-formula-debugger
20782 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20783 ["Show Col/Row Numbers"
20784 org-table-toggle-coordinate-overlays
20785 :style toggle
20786 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20787 "--"
20788 ["Create" org-table-create (and (not (org-at-table-p))
20789 org-enable-table-editor)]
20790 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20791 ["Import from File" org-table-import (not (org-at-table-p))]
20792 ["Export to File" org-table-export (org-at-table-p)]
20793 "--"
20794 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20796 (easy-menu-define org-org-menu org-mode-map "Org menu"
20797 '("Org"
20798 ("Show/Hide"
20799 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20800 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20801 ["Sparse Tree..." org-sparse-tree t]
20802 ["Reveal Context" org-reveal t]
20803 ["Show All" show-all t]
20804 "--"
20805 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20806 "--"
20807 ["New Heading" org-insert-heading t]
20808 ("Navigate Headings"
20809 ["Up" outline-up-heading t]
20810 ["Next" outline-next-visible-heading t]
20811 ["Previous" outline-previous-visible-heading t]
20812 ["Next Same Level" outline-forward-same-level t]
20813 ["Previous Same Level" outline-backward-same-level t]
20814 "--"
20815 ["Jump" org-goto t])
20816 ("Edit Structure"
20817 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20818 "--"
20819 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20820 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20821 "--"
20822 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20823 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20824 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20825 "--"
20826 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20827 "--"
20828 ["Copy visible text" org-copy-visible t]
20829 "--"
20830 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20831 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20832 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20833 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20834 "--"
20835 ["Sort Region/Children" org-sort t]
20836 "--"
20837 ["Convert to odd levels" org-convert-to-odd-levels t]
20838 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20839 ("Editing"
20840 ["Emphasis..." org-emphasize t]
20841 ["Edit Source Example" org-edit-special t]
20842 "--"
20843 ["Footnote new/jump" org-footnote-action t]
20844 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20845 ("Archive"
20846 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20847 "--"
20848 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20849 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20850 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20852 "--"
20853 ("Hyperlinks"
20854 ["Store Link (Global)" org-store-link t]
20855 ["Find existing link to here" org-occur-link-in-agenda-files t]
20856 ["Insert Link" org-insert-link t]
20857 ["Follow Link" org-open-at-point t]
20858 "--"
20859 ["Next link" org-next-link t]
20860 ["Previous link" org-previous-link t]
20861 "--"
20862 ["Descriptive Links"
20863 org-toggle-link-display
20864 :style radio
20865 :selected org-descriptive-links
20867 ["Literal Links"
20868 org-toggle-link-display
20869 :style radio
20870 :selected (not org-descriptive-links)])
20871 "--"
20872 ("TODO Lists"
20873 ["TODO/DONE/-" org-todo t]
20874 ("Select keyword"
20875 ["Next keyword" org-shiftright (org-at-heading-p)]
20876 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20877 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20878 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20879 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20880 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20881 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20882 "--"
20883 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20884 :selected org-enforce-todo-dependencies :style toggle :active t]
20885 "Settings for tree at point"
20886 ["Do Children sequentially" org-toggle-ordered-property :style radio
20887 :selected (org-entry-get nil "ORDERED")
20888 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20889 ["Do Children parallel" org-toggle-ordered-property :style radio
20890 :selected (not (org-entry-get nil "ORDERED"))
20891 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20892 "--"
20893 ["Set Priority" org-priority t]
20894 ["Priority Up" org-shiftup t]
20895 ["Priority Down" org-shiftdown t]
20896 "--"
20897 ["Get news from all feeds" org-feed-update-all t]
20898 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20899 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20900 ("TAGS and Properties"
20901 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20902 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20903 "--"
20904 ["Set property" org-set-property (not (org-before-first-heading-p))]
20905 ["Column view of properties" org-columns t]
20906 ["Insert Column View DBlock" org-insert-columns-dblock t])
20907 ("Dates and Scheduling"
20908 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20909 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20910 ("Change Date"
20911 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20912 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20913 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20914 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20915 ["Compute Time Range" org-evaluate-time-range t]
20916 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20917 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20918 "--"
20919 ["Custom time format" org-toggle-time-stamp-overlays
20920 :style radio :selected org-display-custom-times]
20921 "--"
20922 ["Goto Calendar" org-goto-calendar t]
20923 ["Date from Calendar" org-date-from-calendar t]
20924 "--"
20925 ["Start/Restart Timer" org-timer-start t]
20926 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20927 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20928 ["Insert Timer String" org-timer t]
20929 ["Insert Timer Item" org-timer-item t])
20930 ("Logging work"
20931 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20932 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20933 ["Clock out" org-clock-out t]
20934 ["Clock cancel" org-clock-cancel t]
20935 "--"
20936 ["Mark as default task" org-clock-mark-default-task t]
20937 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20938 ["Goto running clock" org-clock-goto t]
20939 "--"
20940 ["Display times" org-clock-display t]
20941 ["Create clock table" org-clock-report t]
20942 "--"
20943 ["Record DONE time"
20944 (progn (setq org-log-done (not org-log-done))
20945 (message "Switching to %s will %s record a timestamp"
20946 (car org-done-keywords)
20947 (if org-log-done "automatically" "not")))
20948 :style toggle :selected org-log-done])
20949 "--"
20950 ["Agenda Command..." org-agenda t]
20951 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20952 ("File List for Agenda")
20953 ("Special views current file"
20954 ["TODO Tree" org-show-todo-tree t]
20955 ["Check Deadlines" org-check-deadlines t]
20956 ["Timeline" org-timeline t]
20957 ["Tags/Property tree" org-match-sparse-tree t])
20958 "--"
20959 ["Export/Publish..." org-export-dispatch t]
20960 ("LaTeX"
20961 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20962 :selected org-cdlatex-mode]
20963 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20964 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20965 ["Modify math symbol" org-cdlatex-math-modify
20966 (org-inside-LaTeX-fragment-p)]
20967 ["Insert citation" org-reftex-citation t]
20968 "--"
20969 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20970 "--"
20971 ("MobileOrg"
20972 ["Push Files and Views" org-mobile-push t]
20973 ["Get Captured and Flagged" org-mobile-pull t]
20974 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20975 "--"
20976 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20977 "--"
20978 ("Documentation"
20979 ["Show Version" org-version t]
20980 ["Info Documentation" org-info t])
20981 ("Customize"
20982 ["Browse Org Group" org-customize t]
20983 "--"
20984 ["Expand This Menu" org-create-customize-menu
20985 (fboundp 'customize-menu-create)])
20986 ["Send bug report" org-submit-bug-report t]
20987 "--"
20988 ("Refresh/Reload"
20989 ["Refresh setup current buffer" org-mode-restart t]
20990 ["Reload Org (after update)" org-reload t]
20991 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20994 (defun org-info (&optional node)
20995 "Read documentation for Org-mode in the info system.
20996 With optional NODE, go directly to that node."
20997 (interactive)
20998 (info (format "(org)%s" (or node ""))))
21000 ;;;###autoload
21001 (defun org-submit-bug-report ()
21002 "Submit a bug report on Org-mode via mail.
21004 Don't hesitate to report any problems or inaccurate documentation.
21006 If you don't have setup sending mail from (X)Emacs, please copy the
21007 output buffer into your mail program, as it gives us important
21008 information about your Org-mode version and configuration."
21009 (interactive)
21010 (require 'reporter)
21011 (org-load-modules-maybe)
21012 (org-require-autoloaded-modules)
21013 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21014 (reporter-submit-bug-report
21015 "emacs-orgmode@gnu.org"
21016 (org-version nil 'full)
21017 (let (list)
21018 (save-window-excursion
21019 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21020 (delete-other-windows)
21021 (erase-buffer)
21022 (insert "You are about to submit a bug report to the Org-mode mailing list.
21024 We would like to add your full Org-mode and Outline configuration to the
21025 bug report. This greatly simplifies the work of the maintainer and
21026 other experts on the mailing list.
21028 HOWEVER, some variables you have customized may contain private
21029 information. The names of customers, colleagues, or friends, might
21030 appear in the form of file names, tags, todo states, or search strings.
21031 If you answer yes to the prompt, you might want to check and remove
21032 such private information before sending the email.")
21033 (add-text-properties (point-min) (point-max) '(face org-warning))
21034 (when (yes-or-no-p "Include your Org-mode configuration ")
21035 (mapatoms
21036 (lambda (v)
21037 (and (boundp v)
21038 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21039 (or (and (symbol-value v)
21040 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21041 (and
21042 (get v 'custom-type) (get v 'standard-value)
21043 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21044 (push v list)))))
21045 (kill-buffer (get-buffer "*Warn about privacy*"))
21046 list))
21047 nil nil
21048 "Remember to cover the basics, that is, what you expected to happen and
21049 what in fact did happen. You don't know how to make a good report? See
21051 http://orgmode.org/manual/Feedback.html#Feedback
21053 Your bug report will be posted to the Org-mode mailing list.
21054 ------------------------------------------------------------------------")
21055 (save-excursion
21056 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21057 (replace-match "\\1Bug: \\3 [\\2]")))))
21060 (defun org-install-agenda-files-menu ()
21061 (let ((bl (buffer-list)))
21062 (save-excursion
21063 (while bl
21064 (set-buffer (pop bl))
21065 (if (derived-mode-p 'org-mode) (setq bl nil)))
21066 (when (derived-mode-p 'org-mode)
21067 (easy-menu-change
21068 '("Org") "File List for Agenda"
21069 (append
21070 (list
21071 ["Edit File List" (org-edit-agenda-file-list) t]
21072 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21073 ["Remove Current File from List" org-remove-file t]
21074 ["Cycle through agenda files" org-cycle-agenda-files t]
21075 ["Occur in all agenda files" org-occur-in-agenda-files t]
21076 "--")
21077 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21079 ;;;; Documentation
21081 (defun org-require-autoloaded-modules ()
21082 (interactive)
21083 (mapc 'require
21084 '(org-agenda org-archive org-attach org-clock org-colview org-id
21085 org-table org-timer)))
21087 ;;;###autoload
21088 (defun org-reload (&optional uncompiled)
21089 "Reload all org lisp files.
21090 With prefix arg UNCOMPILED, load the uncompiled versions."
21091 (interactive "P")
21092 (require 'loadhist)
21093 (let* ((org-dir (org-find-library-dir "org"))
21094 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21095 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21096 (remove-re (mapconcat 'identity
21097 (mapcar (lambda (f) (concat "^" f "$"))
21098 (list (if (featurep 'xemacs)
21099 "org-colview"
21100 "org-colview-xemacs")
21101 "org" "org-loaddefs" "org-version"))
21102 "\\|"))
21103 (feats (delete-dups
21104 (mapcar 'file-name-sans-extension
21105 (mapcar 'file-name-nondirectory
21106 (delq nil
21107 (mapcar 'feature-file
21108 features))))))
21109 (lfeat (append
21110 (sort
21111 (setq feats
21112 (delq nil (mapcar
21113 (lambda (f)
21114 (if (and (string-match feature-re f)
21115 (not (string-match remove-re f)))
21116 f nil))
21117 feats)))
21118 'string-lessp)
21119 (list "org-version" "org")))
21120 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21121 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21122 load-uncore load-misses)
21123 (setq load-misses
21124 (delq 't
21125 (mapcar (lambda (f)
21126 (or (org-load-noerror-mustsuffix (concat org-dir f))
21127 (and (string= org-dir contrib-dir)
21128 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21129 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21130 (add-to-list 'load-uncore f 'append)
21133 lfeat)))
21134 (if load-uncore
21135 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21136 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21137 (if load-misses
21138 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21139 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21140 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21142 ;;;###autoload
21143 (defun org-customize ()
21144 "Call the customize function with org as argument."
21145 (interactive)
21146 (org-load-modules-maybe)
21147 (org-require-autoloaded-modules)
21148 (customize-browse 'org))
21150 (defun org-create-customize-menu ()
21151 "Create a full customization menu for Org-mode, insert it into the menu."
21152 (interactive)
21153 (org-load-modules-maybe)
21154 (org-require-autoloaded-modules)
21155 (if (fboundp 'customize-menu-create)
21156 (progn
21157 (easy-menu-change
21158 '("Org") "Customize"
21159 `(["Browse Org group" org-customize t]
21160 "--"
21161 ,(customize-menu-create 'org)
21162 ["Set" Custom-set t]
21163 ["Save" Custom-save t]
21164 ["Reset to Current" Custom-reset-current t]
21165 ["Reset to Saved" Custom-reset-saved t]
21166 ["Reset to Standard Settings" Custom-reset-standard t]))
21167 (message "\"Org\"-menu now contains full customization menu"))
21168 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21170 ;;;; Miscellaneous stuff
21172 ;;; Generally useful functions
21174 (defun org-get-at-bol (property)
21175 "Get text property PROPERTY at beginning of line."
21176 (get-text-property (point-at-bol) property))
21178 (defun org-find-text-property-in-string (prop s)
21179 "Return the first non-nil value of property PROP in string S."
21180 (or (get-text-property 0 prop s)
21181 (get-text-property (or (next-single-property-change 0 prop s) 0)
21182 prop s)))
21184 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21185 "Display the given MESSAGE as a warning."
21186 (if (fboundp 'display-warning)
21187 (display-warning 'org message
21188 (if (featurep 'xemacs) 'warning :warning))
21189 (let ((buf (get-buffer-create "*Org warnings*")))
21190 (with-current-buffer buf
21191 (goto-char (point-max))
21192 (insert "Warning (Org): " message)
21193 (unless (bolp)
21194 (newline)))
21195 (display-buffer buf)
21196 (sit-for 0))))
21198 (defun org-eval (form)
21199 "Eval FORM and return result."
21200 (condition-case error
21201 (eval form)
21202 (error (format "%%![Error: %s]" error))))
21204 (defun org-in-clocktable-p ()
21205 "Check if the cursor is in a clocktable."
21206 (let ((pos (point)) start)
21207 (save-excursion
21208 (end-of-line 1)
21209 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21210 (setq start (match-beginning 0))
21211 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21212 (>= (match-end 0) pos)
21213 start))))
21215 (defun org-in-commented-line ()
21216 "Is point in a line starting with `#'?"
21217 (equal (char-after (point-at-bol)) ?#))
21219 (defun org-in-indented-comment-line ()
21220 "Is point in a line starting with `#' after some white space?"
21221 (save-excursion
21222 (save-match-data
21223 (goto-char (point-at-bol))
21224 (looking-at "[ \t]*#"))))
21226 (defun org-in-verbatim-emphasis ()
21227 (save-match-data
21228 (and (org-in-regexp org-emph-re 2)
21229 (>= (point) (match-beginning 3))
21230 (<= (point) (match-end 4))
21231 (member (match-string 3) '("=" "~")))))
21233 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21234 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21235 (if (and marker (marker-buffer marker)
21236 (buffer-live-p (marker-buffer marker)))
21237 (progn
21238 (org-pop-to-buffer-same-window (marker-buffer marker))
21239 (if (or (> marker (point-max)) (< marker (point-min)))
21240 (widen))
21241 (goto-char marker)
21242 (org-show-context 'org-goto))
21243 (if bookmark
21244 (bookmark-jump bookmark)
21245 (error "Cannot find location"))))
21247 (defun org-quote-csv-field (s)
21248 "Quote field for inclusion in CSV material."
21249 (if (string-match "[\",]" s)
21250 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21253 (defun org-force-self-insert (N)
21254 "Needed to enforce self-insert under remapping."
21255 (interactive "p")
21256 (self-insert-command N))
21258 (defun org-string-width (s)
21259 "Compute width of string, ignoring invisible characters.
21260 This ignores character with invisibility property `org-link', and also
21261 characters with property `org-cwidth', because these will become invisible
21262 upon the next fontification round."
21263 (let (b l)
21264 (when (or (eq t buffer-invisibility-spec)
21265 (assq 'org-link buffer-invisibility-spec))
21266 (while (setq b (text-property-any 0 (length s)
21267 'invisible 'org-link s))
21268 (setq s (concat (substring s 0 b)
21269 (substring s (or (next-single-property-change
21270 b 'invisible s) (length s)))))))
21271 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21272 (setq s (concat (substring s 0 b)
21273 (substring s (or (next-single-property-change
21274 b 'org-cwidth s) (length s))))))
21275 (setq l (string-width s) b -1)
21276 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21277 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21280 (defun org-shorten-string (s maxlength)
21281 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21282 If the string is shorter or has length MAXLENGTH, just return the
21283 original string. If it is longer, the functions finds a space in the
21284 string, breaks this string off at that locations and adds three dots
21285 as ellipsis. Including the ellipsis, the string will not be longer
21286 than MAXLENGTH. If finding a good breaking point in the string does
21287 not work, the string is just chopped off in the middle of a word
21288 if necessary."
21289 (if (<= (length s) maxlength)
21291 (let* ((n (max (- maxlength 4) 1))
21292 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21293 (if (string-match re s)
21294 (concat (match-string 1 s) "...")
21295 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21297 (defun org-get-indentation (&optional line)
21298 "Get the indentation of the current line, interpreting tabs.
21299 When LINE is given, assume it represents a line and compute its indentation."
21300 (if line
21301 (if (string-match "^ *" (org-remove-tabs line))
21302 (match-end 0))
21303 (save-excursion
21304 (beginning-of-line 1)
21305 (skip-chars-forward " \t")
21306 (current-column))))
21308 (defun org-get-string-indentation (s)
21309 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21310 (let ((n -1) (i 0) (w tab-width) c)
21311 (catch 'exit
21312 (while (< (setq n (1+ n)) (length s))
21313 (setq c (aref s n))
21314 (cond ((= c ?\ ) (setq i (1+ i)))
21315 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21316 (t (throw 'exit t)))))
21319 (defun org-remove-tabs (s &optional width)
21320 "Replace tabulators in S with spaces.
21321 Assumes that s is a single line, starting in column 0."
21322 (setq width (or width tab-width))
21323 (while (string-match "\t" s)
21324 (setq s (replace-match
21325 (make-string
21326 (- (* width (/ (+ (match-beginning 0) width) width))
21327 (match-beginning 0)) ?\ )
21328 t t s)))
21331 (defun org-fix-indentation (line ind)
21332 "Fix indentation in LINE.
21333 IND is a cons cell with target and minimum indentation.
21334 If the current indentation in LINE is smaller than the minimum,
21335 leave it alone. If it is larger than ind, set it to the target."
21336 (let* ((l (org-remove-tabs line))
21337 (i (org-get-indentation l))
21338 (i1 (car ind)) (i2 (cdr ind)))
21339 (if (>= i i2) (setq l (substring line i2)))
21340 (if (> i1 0)
21341 (concat (make-string i1 ?\ ) l)
21342 l)))
21344 (defun org-remove-indentation (code &optional n)
21345 "Remove the maximum common indentation from the lines in CODE.
21346 N may optionally be the number of spaces to remove."
21347 (with-temp-buffer
21348 (insert code)
21349 (org-do-remove-indentation n)
21350 (buffer-string)))
21352 (defun org-do-remove-indentation (&optional n)
21353 "Remove the maximum common indentation from the buffer."
21354 (untabify (point-min) (point-max))
21355 (let ((min 10000) re)
21356 (if n
21357 (setq min n)
21358 (goto-char (point-min))
21359 (while (re-search-forward "^ *[^ \n]" nil t)
21360 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21361 (unless (or (= min 0) (= min 10000))
21362 (setq re (format "^ \\{%d\\}" min))
21363 (goto-char (point-min))
21364 (while (re-search-forward re nil t)
21365 (replace-match "")
21366 (end-of-line 1))
21367 min)))
21369 (defun org-fill-template (template alist)
21370 "Find each %key of ALIST in TEMPLATE and replace it."
21371 (let ((case-fold-search nil)
21372 entry key value)
21373 (setq alist (sort (copy-sequence alist)
21374 (lambda (a b) (< (length (car a)) (length (car b))))))
21375 (while (setq entry (pop alist))
21376 (setq template
21377 (replace-regexp-in-string
21378 (concat "%" (regexp-quote (car entry)))
21379 (or (cdr entry) "") template t t)))
21380 template))
21382 (defun org-base-buffer (buffer)
21383 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21384 (if (not buffer)
21385 buffer
21386 (or (buffer-base-buffer buffer)
21387 buffer)))
21389 (defun org-trim (s)
21390 "Remove whitespace at beginning and end of string."
21391 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21392 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21395 (defun org-wrap (string &optional width lines)
21396 "Wrap string to either a number of lines, or a width in characters.
21397 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21398 that costs. If there is a word longer than WIDTH, the text is actually
21399 wrapped to the length of that word.
21400 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21401 many lines, whatever width that takes.
21402 The return value is a list of lines, without newlines at the end."
21403 (let* ((words (org-split-string string "[ \t\n]+"))
21404 (maxword (apply 'max (mapcar 'org-string-width words)))
21405 w ll)
21406 (cond (width
21407 (org-do-wrap words (max maxword width)))
21408 (lines
21409 (setq w maxword)
21410 (setq ll (org-do-wrap words maxword))
21411 (if (<= (length ll) lines)
21413 (setq ll words)
21414 (while (> (length ll) lines)
21415 (setq w (1+ w))
21416 (setq ll (org-do-wrap words w)))
21417 ll))
21418 (t (error "Cannot wrap this")))))
21420 (defun org-do-wrap (words width)
21421 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21422 (let (lines line)
21423 (while words
21424 (setq line (pop words))
21425 (while (and words (< (+ (length line) (length (car words))) width))
21426 (setq line (concat line " " (pop words))))
21427 (setq lines (push line lines)))
21428 (nreverse lines)))
21430 (defun org-split-string (string &optional separators)
21431 "Splits STRING into substrings at SEPARATORS.
21432 No empty strings are returned if there are matches at the beginning
21433 and end of string."
21434 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21435 (start 0)
21436 notfirst
21437 (list nil))
21438 (while (and (string-match rexp string
21439 (if (and notfirst
21440 (= start (match-beginning 0))
21441 (< start (length string)))
21442 (1+ start) start))
21443 (< (match-beginning 0) (length string)))
21444 (setq notfirst t)
21445 (or (eq (match-beginning 0) 0)
21446 (and (eq (match-beginning 0) (match-end 0))
21447 (eq (match-beginning 0) start))
21448 (setq list
21449 (cons (substring string start (match-beginning 0))
21450 list)))
21451 (setq start (match-end 0)))
21452 (or (eq start (length string))
21453 (setq list
21454 (cons (substring string start)
21455 list)))
21456 (nreverse list)))
21458 (defun org-quote-vert (s)
21459 "Replace \"|\" with \"\\vert\"."
21460 (while (string-match "|" s)
21461 (setq s (replace-match "\\vert" t t s)))
21464 (defun org-uuidgen-p (s)
21465 "Is S an ID created by UUIDGEN?"
21466 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21468 (defun org-in-src-block-p (&optional inside)
21469 "Whether point is in a code source block.
21470 When INSIDE is non-nil, don't consider we are within a src block
21471 when point is at #+BEGIN_SRC or #+END_SRC."
21472 (let ((case-fold-search t) ov)
21473 (or (and (setq ov (overlays-at (point)))
21474 (memq 'org-block-background
21475 (overlay-properties (car ov))))
21476 (and (not inside)
21477 (save-match-data
21478 (save-excursion
21479 (beginning-of-line)
21480 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21482 (defun org-context ()
21483 "Return a list of contexts of the current cursor position.
21484 If several contexts apply, all are returned.
21485 Each context entry is a list with a symbol naming the context, and
21486 two positions indicating start and end of the context. Possible
21487 contexts are:
21489 :headline anywhere in a headline
21490 :headline-stars on the leading stars in a headline
21491 :todo-keyword on a TODO keyword (including DONE) in a headline
21492 :tags on the TAGS in a headline
21493 :priority on the priority cookie in a headline
21494 :item on the first line of a plain list item
21495 :item-bullet on the bullet/number of a plain list item
21496 :checkbox on the checkbox in a plain list item
21497 :table in an org-mode table
21498 :table-special on a special filed in a table
21499 :table-table in a table.el table
21500 :clocktable in a clocktable
21501 :src-block in a source block
21502 :link on a hyperlink
21503 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21504 :target on a <<target>>
21505 :radio-target on a <<<radio-target>>>
21506 :latex-fragment on a LaTeX fragment
21507 :latex-preview on a LaTeX fragment with overlaid preview image
21509 This function expects the position to be visible because it uses font-lock
21510 faces as a help to recognize the following contexts: :table-special, :link,
21511 and :keyword."
21512 (let* ((f (get-text-property (point) 'face))
21513 (faces (if (listp f) f (list f)))
21514 (case-fold-search t)
21515 (p (point)) clist o)
21516 ;; First the large context
21517 (cond
21518 ((org-at-heading-p t)
21519 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21520 (when (progn
21521 (beginning-of-line 1)
21522 (looking-at org-todo-line-tags-regexp))
21523 (push (org-point-in-group p 1 :headline-stars) clist)
21524 (push (org-point-in-group p 2 :todo-keyword) clist)
21525 (push (org-point-in-group p 4 :tags) clist))
21526 (goto-char p)
21527 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21528 (if (looking-at "\\[#[A-Z0-9]\\]")
21529 (push (org-point-in-group p 0 :priority) clist)))
21531 ((org-at-item-p)
21532 (push (org-point-in-group p 2 :item-bullet) clist)
21533 (push (list :item (point-at-bol)
21534 (save-excursion (org-end-of-item) (point)))
21535 clist)
21536 (and (org-at-item-checkbox-p)
21537 (push (org-point-in-group p 0 :checkbox) clist)))
21539 ((org-at-table-p)
21540 (push (list :table (org-table-begin) (org-table-end)) clist)
21541 (if (memq 'org-formula faces)
21542 (push (list :table-special
21543 (previous-single-property-change p 'face)
21544 (next-single-property-change p 'face)) clist)))
21545 ((org-at-table-p 'any)
21546 (push (list :table-table) clist)))
21547 (goto-char p)
21549 (let ((case-fold-search t))
21550 ;; New the "medium" contexts: clocktables, source blocks
21551 (cond ((org-in-clocktable-p)
21552 (push (list :clocktable
21553 (and (or (looking-at "#\\+BEGIN: clocktable")
21554 (search-backward "#+BEGIN: clocktable" nil t))
21555 (match-beginning 0))
21556 (and (re-search-forward "#\\+END:?" nil t)
21557 (match-end 0))) clist))
21558 ((org-in-src-block-p)
21559 (push (list :src-block
21560 (and (or (looking-at "#\\+BEGIN_SRC")
21561 (search-backward "#+BEGIN_SRC" nil t))
21562 (match-beginning 0))
21563 (and (search-forward "#+END_SRC" nil t)
21564 (match-beginning 0))) clist))))
21565 (goto-char p)
21567 ;; Now the small context
21568 (cond
21569 ((org-at-timestamp-p)
21570 (push (org-point-in-group p 0 :timestamp) clist))
21571 ((memq 'org-link faces)
21572 (push (list :link
21573 (previous-single-property-change p 'face)
21574 (next-single-property-change p 'face)) clist))
21575 ((memq 'org-special-keyword faces)
21576 (push (list :keyword
21577 (previous-single-property-change p 'face)
21578 (next-single-property-change p 'face)) clist))
21579 ((org-at-target-p)
21580 (push (org-point-in-group p 0 :target) clist)
21581 (goto-char (1- (match-beginning 0)))
21582 (if (looking-at org-radio-target-regexp)
21583 (push (org-point-in-group p 0 :radio-target) clist))
21584 (goto-char p))
21585 ((setq o (car (delq nil
21586 (mapcar
21587 (lambda (x)
21588 (if (memq x org-latex-fragment-image-overlays) x))
21589 (overlays-at (point))))))
21590 (push (list :latex-fragment
21591 (overlay-start o) (overlay-end o)) clist)
21592 (push (list :latex-preview
21593 (overlay-start o) (overlay-end o)) clist))
21594 ((org-inside-LaTeX-fragment-p)
21595 ;; FIXME: positions wrong.
21596 (push (list :latex-fragment (point) (point)) clist)))
21598 (setq clist (nreverse (delq nil clist)))
21599 clist))
21601 ;; FIXME: Compare with at-regexp-p Do we need both?
21602 (defun org-in-regexp (re &optional nlines visually)
21603 "Check if point is inside a match of regexp.
21604 Normally only the current line is checked, but you can include NLINES extra
21605 lines both before and after point into the search.
21606 If VISUALLY is set, require that the cursor is not after the match but
21607 really on, so that the block visually is on the match."
21608 (catch 'exit
21609 (let ((pos (point))
21610 (eol (point-at-eol (+ 1 (or nlines 0))))
21611 (inc (if visually 1 0)))
21612 (save-excursion
21613 (beginning-of-line (- 1 (or nlines 0)))
21614 (while (re-search-forward re eol t)
21615 (if (and (<= (match-beginning 0) pos)
21616 (>= (+ inc (match-end 0)) pos))
21617 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21619 (defun org-at-regexp-p (regexp)
21620 "Is point inside a match of REGEXP in the current line?"
21621 (catch 'exit
21622 (save-excursion
21623 (let ((pos (point)) (end (point-at-eol)))
21624 (beginning-of-line 1)
21625 (while (re-search-forward regexp end t)
21626 (if (and (<= (match-beginning 0) pos)
21627 (>= (match-end 0) pos))
21628 (throw 'exit t)))
21629 nil))))
21631 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21632 "Non-nil when point is between matches of START-RE and END-RE.
21634 Also return a non-nil value when point is on one of the matches.
21636 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21637 buffer positions. Default values are the positions of headlines
21638 surrounding the point.
21640 The functions returns a cons cell whose car (resp. cdr) is the
21641 position before START-RE (resp. after END-RE)."
21642 (save-match-data
21643 (let ((pos (point))
21644 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21645 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21646 beg end)
21647 (save-excursion
21648 ;; Point is on a block when on START-RE or if START-RE can be
21649 ;; found before it...
21650 (and (or (org-at-regexp-p start-re)
21651 (re-search-backward start-re limit-up t))
21652 (setq beg (match-beginning 0))
21653 ;; ... and END-RE after it...
21654 (goto-char (match-end 0))
21655 (re-search-forward end-re limit-down t)
21656 (> (setq end (match-end 0)) pos)
21657 ;; ... without another START-RE in-between.
21658 (goto-char (match-beginning 0))
21659 (not (re-search-backward start-re (1+ beg) t))
21660 ;; Return value.
21661 (cons beg end))))))
21663 (defun org-in-block-p (names)
21664 "Non-nil when point belongs to a block whose name belongs to NAMES.
21666 NAMES is a list of strings containing names of blocks.
21668 Return first block name matched, or nil. Beware that in case of
21669 nested blocks, the returned name may not belong to the closest
21670 block from point."
21671 (save-match-data
21672 (catch 'exit
21673 (let ((case-fold-search t)
21674 (lim-up (save-excursion (outline-previous-heading)))
21675 (lim-down (save-excursion (outline-next-heading))))
21676 (mapc (lambda (name)
21677 (let ((n (regexp-quote name)))
21678 (when (org-between-regexps-p
21679 (concat "^[ \t]*#\\+begin_" n)
21680 (concat "^[ \t]*#\\+end_" n)
21681 lim-up lim-down)
21682 (throw 'exit n))))
21683 names))
21684 nil)))
21686 (defun org-in-drawer-p ()
21687 "Is point within a drawer?"
21688 (save-match-data
21689 (let ((case-fold-search t)
21690 (lim-up (save-excursion (outline-previous-heading)))
21691 (lim-down (save-excursion (outline-next-heading))))
21692 (org-between-regexps-p
21693 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21694 "^[ \t]*:end:.*$"
21695 lim-up lim-down))))
21697 (defun org-occur-in-agenda-files (regexp &optional nlines)
21698 "Call `multi-occur' with buffers for all agenda files."
21699 (interactive "sOrg-files matching: \np")
21700 (let* ((files (org-agenda-files))
21701 (tnames (mapcar 'file-truename files))
21702 (extra org-agenda-text-search-extra-files)
21704 (when (eq (car extra) 'agenda-archives)
21705 (setq extra (cdr extra))
21706 (setq files (org-add-archive-files files)))
21707 (while (setq f (pop extra))
21708 (unless (member (file-truename f) tnames)
21709 (add-to-list 'files f 'append)
21710 (add-to-list 'tnames (file-truename f) 'append)))
21711 (multi-occur
21712 (mapcar (lambda (x)
21713 (with-current-buffer
21714 (or (get-file-buffer x) (find-file-noselect x))
21715 (widen)
21716 (current-buffer)))
21717 files)
21718 regexp)))
21720 (if (boundp 'occur-mode-find-occurrence-hook)
21721 ;; Emacs 23
21722 (add-hook 'occur-mode-find-occurrence-hook
21723 (lambda ()
21724 (when (derived-mode-p 'org-mode)
21725 (org-reveal))))
21726 ;; Emacs 22
21727 (defadvice occur-mode-goto-occurrence
21728 (after org-occur-reveal activate)
21729 (and (derived-mode-p 'org-mode) (org-reveal)))
21730 (defadvice occur-mode-goto-occurrence-other-window
21731 (after org-occur-reveal activate)
21732 (and (derived-mode-p 'org-mode) (org-reveal)))
21733 (defadvice occur-mode-display-occurrence
21734 (after org-occur-reveal activate)
21735 (when (derived-mode-p 'org-mode)
21736 (let ((pos (occur-mode-find-occurrence)))
21737 (with-current-buffer (marker-buffer pos)
21738 (save-excursion
21739 (goto-char pos)
21740 (org-reveal)))))))
21742 (defun org-occur-link-in-agenda-files ()
21743 "Create a link and search for it in the agendas.
21744 The link is not stored in `org-stored-links', it is just created
21745 for the search purpose."
21746 (interactive)
21747 (let ((link (condition-case nil
21748 (org-store-link nil)
21749 (error "Unable to create a link to here"))))
21750 (org-occur-in-agenda-files (regexp-quote link))))
21752 (defun org-reverse-string (string)
21753 "Return the reverse of STRING."
21754 (apply 'string (reverse (string-to-list string))))
21756 (defsubst org-uniquify (list)
21757 "Non-destructively remove duplicate elements from LIST."
21758 (let ((res (copy-sequence list))) (delete-dups res)))
21760 (defun org-uniquify-alist (alist)
21761 "Merge elements of ALIST with the same key.
21763 For example, in this alist:
21765 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21766 => '((a 1 3) (b 2))
21768 merge (a 1) and (a 3) into (a 1 3).
21770 The function returns the new ALIST."
21771 (let (rtn)
21772 (mapc
21773 (lambda (e)
21774 (let (n)
21775 (if (not (assoc (car e) rtn))
21776 (push e rtn)
21777 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21778 (setq rtn (assq-delete-all (car e) rtn))
21779 (push n rtn))))
21780 alist)
21781 rtn))
21783 (defun org-delete-all (elts list)
21784 "Remove all elements in ELTS from LIST."
21785 (while elts
21786 (setq list (delete (pop elts) list)))
21787 list)
21789 (defun org-count (cl-item cl-seq)
21790 "Count the number of occurrences of ITEM in SEQ.
21791 Taken from `count' in cl-seq.el with all keyword arguments removed."
21792 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21793 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21794 (while (< cl-start cl-end)
21795 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21796 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21797 (setq cl-start (1+ cl-start)))
21798 cl-count))
21800 (defun org-remove-if (predicate seq)
21801 "Remove everything from SEQ that fulfills PREDICATE."
21802 (let (res e)
21803 (while seq
21804 (setq e (pop seq))
21805 (if (not (funcall predicate e)) (push e res)))
21806 (nreverse res)))
21808 (defun org-remove-if-not (predicate seq)
21809 "Remove everything from SEQ that does not fulfill PREDICATE."
21810 (let (res e)
21811 (while seq
21812 (setq e (pop seq))
21813 (if (funcall predicate e) (push e res)))
21814 (nreverse res)))
21816 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21817 "Reduce two-argument FUNCTION across SEQ.
21818 Taken from `reduce' in cl-seq.el with all keyword arguments but
21819 \":initial-value\" removed."
21820 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21821 (cadr (memq :initial-value cl-keys)))
21822 (cl-seq (pop cl-seq))
21823 (t (funcall cl-func)))))
21824 (while cl-seq
21825 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21826 cl-accum))
21828 (defun org-every (pred seq)
21829 "Return true if PREDICATE is true of every element of SEQ.
21830 Adapted from `every' in cl.el."
21831 (catch 'org-every
21832 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21835 (defun org-some (pred seq)
21836 "Return true if PREDICATE is true of any element of SEQ.
21837 Adapted from `some' in cl.el."
21838 (catch 'org-some
21839 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21840 nil))
21842 (defun org-back-over-empty-lines ()
21843 "Move backwards over whitespace, to the beginning of the first empty line.
21844 Returns the number of empty lines passed."
21845 (let ((pos (point)))
21846 (if (cdr (assoc 'heading org-blank-before-new-entry))
21847 (skip-chars-backward " \t\n\r")
21848 (unless (eobp)
21849 (forward-line -1)))
21850 (beginning-of-line 2)
21851 (goto-char (min (point) pos))
21852 (count-lines (point) pos)))
21854 (defun org-skip-whitespace ()
21855 (skip-chars-forward " \t\n\r"))
21857 (defun org-point-in-group (point group &optional context)
21858 "Check if POINT is in match-group GROUP.
21859 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21860 match. If the match group does not exist or point is not inside it,
21861 return nil."
21862 (and (match-beginning group)
21863 (>= point (match-beginning group))
21864 (<= point (match-end group))
21865 (if context
21866 (list context (match-beginning group) (match-end group))
21867 t)))
21869 (defun org-switch-to-buffer-other-window (&rest args)
21870 "Switch to buffer in a second window on the current frame.
21871 In particular, do not allow pop-up frames.
21872 Returns the newly created buffer."
21873 (org-no-popups
21874 (apply 'switch-to-buffer-other-window args)))
21876 (defun org-combine-plists (&rest plists)
21877 "Create a single property list from all plists in PLISTS.
21878 The process starts by copying the first list, and then setting properties
21879 from the other lists. Settings in the last list are the most significant
21880 ones and overrule settings in the other lists."
21881 (let ((rtn (copy-sequence (pop plists)))
21882 p v ls)
21883 (while plists
21884 (setq ls (pop plists))
21885 (while ls
21886 (setq p (pop ls) v (pop ls))
21887 (setq rtn (plist-put rtn p v))))
21888 rtn))
21890 (defun org-replace-escapes (string table)
21891 "Replace %-escapes in STRING with values in TABLE.
21892 TABLE is an association list with keys like \"%a\" and string values.
21893 The sequences in STRING may contain normal field width and padding information,
21894 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21895 so values can contain further %-escapes if they are define later in TABLE."
21896 (let ((tbl (copy-alist table))
21897 (case-fold-search nil)
21898 (pchg 0)
21899 e re rpl)
21900 (while (setq e (pop tbl))
21901 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21902 (when (and (cdr e) (string-match re (cdr e)))
21903 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21904 (safe "SREF"))
21905 (add-text-properties 0 3 (list 'sref sref) safe)
21906 (setcdr e (replace-match safe t t (cdr e)))))
21907 (while (string-match re string)
21908 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21909 (cdr e)))
21910 (setq string (replace-match rpl t t string))))
21911 (while (setq pchg (next-property-change pchg string))
21912 (let ((sref (get-text-property pchg 'sref string)))
21913 (when (and sref (string-match "SREF" string pchg))
21914 (setq string (replace-match sref t t string)))))
21915 string))
21917 (defun org-sublist (list start end)
21918 "Return a section of LIST, from START to END.
21919 Counting starts at 1."
21920 (let (rtn (c start))
21921 (setq list (nthcdr (1- start) list))
21922 (while (and list (<= c end))
21923 (push (pop list) rtn)
21924 (setq c (1+ c)))
21925 (nreverse rtn)))
21927 (defun org-find-base-buffer-visiting (file)
21928 "Like `find-buffer-visiting' but always return the base buffer and
21929 not an indirect buffer."
21930 (let ((buf (or (get-file-buffer file)
21931 (find-buffer-visiting file))))
21932 (if buf
21933 (or (buffer-base-buffer buf) buf)
21934 nil)))
21936 (defun org-image-file-name-regexp (&optional extensions)
21937 "Return regexp matching the file names of images.
21938 If EXTENSIONS is given, only match these."
21939 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21940 (image-file-name-regexp)
21941 (let ((image-file-name-extensions
21942 (or extensions
21943 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21944 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21945 (concat "\\."
21946 (regexp-opt (nconc (mapcar 'upcase
21947 image-file-name-extensions)
21948 image-file-name-extensions)
21950 "\\'"))))
21952 (defun org-file-image-p (file &optional extensions)
21953 "Return non-nil if FILE is an image."
21954 (save-match-data
21955 (string-match (org-image-file-name-regexp extensions) file)))
21957 (defun org-get-cursor-date (&optional with-time)
21958 "Return the date at cursor in as a time.
21959 This works in the calendar and in the agenda, anywhere else it just
21960 returns the current time.
21961 If WITH-TIME is non-nil, returns the time of the event at point (in
21962 the agenda) or the current time of the day."
21963 (let (date day defd tp tm hod mod)
21964 (when with-time
21965 (setq tp (get-text-property (point) 'time))
21966 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21967 (setq hod (string-to-number (match-string 1 tp))
21968 mod (string-to-number (match-string 2 tp))))
21969 (or tp (setq hod (nth 2 (decode-time (current-time)))
21970 mod (nth 1 (decode-time (current-time))))))
21971 (cond
21972 ((eq major-mode 'calendar-mode)
21973 (setq date (calendar-cursor-to-date)
21974 defd (encode-time 0 (or mod 0) (or hod 0)
21975 (nth 1 date) (nth 0 date) (nth 2 date))))
21976 ((eq major-mode 'org-agenda-mode)
21977 (setq day (get-text-property (point) 'day))
21978 (if day
21979 (setq date (calendar-gregorian-from-absolute day)
21980 defd (encode-time 0 (or mod 0) (or hod 0)
21981 (nth 1 date) (nth 0 date) (nth 2 date))))))
21982 (or defd (current-time))))
21984 (defun org-mark-subtree (&optional up)
21985 "Mark the current subtree.
21986 This puts point at the start of the current subtree, and mark at
21987 the end. If a numeric prefix UP is given, move up into the
21988 hierarchy of headlines by UP levels before marking the subtree."
21989 (interactive "P")
21990 (org-with-limited-levels
21991 (cond ((org-at-heading-p) (beginning-of-line))
21992 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21993 (t (outline-previous-visible-heading 1))))
21994 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21995 (if (org-called-interactively-p 'any)
21996 (call-interactively 'org-mark-element)
21997 (org-mark-element)))
22000 ;;; Indentation
22002 (defun org-indent-line ()
22003 "Indent line depending on context."
22004 (interactive)
22005 (let* ((pos (point))
22006 (itemp (org-at-item-p))
22007 (case-fold-search t)
22008 (org-drawer-regexp (or org-drawer-regexp "\000"))
22009 (inline-task-p (and (featurep 'org-inlinetask)
22010 (org-inlinetask-in-task-p)))
22011 (inline-re (and inline-task-p
22012 (org-inlinetask-outline-regexp)))
22013 column)
22014 (if (and orgstruct-is-++ (eq pos (point)))
22015 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22016 (indent-according-to-mode))
22017 (beginning-of-line 1)
22018 (cond
22019 ;; Headings
22020 ((looking-at org-outline-regexp) (setq column 0))
22021 ;; Footnote definition
22022 ((looking-at org-footnote-definition-re) (setq column 0))
22023 ;; Literal examples
22024 ((looking-at "[ \t]*:\\( \\|$\\)")
22025 (setq column (org-get-indentation))) ; do nothing
22026 ;; Lists
22027 ((ignore-errors (goto-char (org-in-item-p)))
22028 (setq column (if itemp
22029 (org-get-indentation)
22030 (org-list-item-body-column (point))))
22031 (goto-char pos))
22032 ;; Drawers
22033 ((and (looking-at "[ \t]*:END:")
22034 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22035 (save-excursion
22036 (goto-char (1- (match-beginning 1)))
22037 (setq column (current-column))))
22038 ;; Special blocks
22039 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22040 (save-excursion
22041 (re-search-backward
22042 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22043 (setq column (org-get-indentation (match-string 0))))
22044 ((and (not (looking-at "[ \t]*#\\+begin_"))
22045 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22046 (save-excursion
22047 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22048 (setq column
22049 (cond ((equal (downcase (match-string 1)) "src")
22050 ;; src blocks: let `org-edit-src-exit' handle them
22051 (org-get-indentation))
22052 ((equal (downcase (match-string 1)) "example")
22053 (max (org-get-indentation)
22054 (org-get-indentation (match-string 0))))
22056 (org-get-indentation (match-string 0))))))
22057 ;; This line has nothing special, look at the previous relevant
22058 ;; line to compute indentation
22060 (beginning-of-line 0)
22061 (while (and (not (bobp))
22062 (not (looking-at org-table-line-regexp))
22063 (not (looking-at org-drawer-regexp))
22064 ;; When point started in an inline task, do not move
22065 ;; above task starting line.
22066 (not (and inline-task-p (looking-at inline-re)))
22067 ;; Skip drawers, blocks, empty lines, verbatim,
22068 ;; comments, tables, footnotes definitions, lists,
22069 ;; inline tasks.
22070 (or (and (looking-at "[ \t]*:END:")
22071 (re-search-backward org-drawer-regexp nil t))
22072 (and (looking-at "[ \t]*#\\+end_")
22073 (re-search-backward "[ \t]*#\\+begin_"nil t))
22074 (looking-at "[ \t]*[\n:#|]")
22075 (looking-at org-footnote-definition-re)
22076 (and (not inline-task-p)
22077 (featurep 'org-inlinetask)
22078 (org-inlinetask-in-task-p)
22079 (or (org-inlinetask-goto-beginning) t))))
22080 (beginning-of-line 0))
22081 (cond
22082 ;; There was a list item above.
22083 ((ignore-errors (goto-char (org-in-item-p)))
22084 (goto-char (org-list-get-top-point (org-list-struct)))
22085 (setq column (org-get-indentation)))
22086 ;; There was an heading above.
22087 ((looking-at "\\*+[ \t]+")
22088 (if (not org-adapt-indentation)
22089 (setq column 0)
22090 (goto-char (match-end 0))
22091 (setq column (current-column))))
22092 ;; A drawer had started and is unfinished
22093 ((looking-at org-drawer-regexp)
22094 (goto-char (1- (match-beginning 1)))
22095 (setq column (current-column)))
22096 ;; Else, nothing noticeable found: get indentation and go on.
22097 (t (setq column (org-get-indentation))))))
22098 ;; Now apply indentation and move cursor accordingly
22099 (goto-char pos)
22100 (if (<= (current-column) (current-indentation))
22101 (org-indent-line-to column)
22102 (save-excursion (org-indent-line-to column)))
22103 ;; Special polishing for properties, see `org-property-format'
22104 (setq column (current-column))
22105 (beginning-of-line 1)
22106 (if (looking-at org-property-re)
22107 (replace-match (concat (match-string 4)
22108 (format org-property-format
22109 (match-string 1) (match-string 3)))
22110 t t))
22111 (org-move-to-column column))))
22113 (defun org-indent-drawer ()
22114 "Indent the drawer at point."
22115 (interactive)
22116 (let ((p (point))
22117 (e (and (save-excursion (re-search-forward ":END:" nil t))
22118 (match-end 0)))
22119 (folded
22120 (save-excursion
22121 (end-of-line)
22122 (when (overlays-at (point))
22123 (member 'invisible (overlay-properties
22124 (car (overlays-at (point)))))))))
22125 (when folded (org-cycle))
22126 (indent-for-tab-command)
22127 (while (and (move-beginning-of-line 2) (< (point) e))
22128 (indent-for-tab-command))
22129 (goto-char p)
22130 (when folded (org-cycle)))
22131 (message "Drawer at point indented"))
22133 (defun org-indent-block ()
22134 "Indent the block at point."
22135 (interactive)
22136 (let ((p (point))
22137 (case-fold-search t)
22138 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22139 (match-end 0)))
22140 (folded
22141 (save-excursion
22142 (end-of-line)
22143 (when (overlays-at (point))
22144 (member 'invisible (overlay-properties
22145 (car (overlays-at (point)))))))))
22146 (when folded (org-cycle))
22147 (indent-for-tab-command)
22148 (while (and (move-beginning-of-line 2) (< (point) e))
22149 (indent-for-tab-command))
22150 (goto-char p)
22151 (when folded (org-cycle)))
22152 (message "Block at point indented"))
22154 (defun org-indent-region (start end)
22155 "Indent region."
22156 (interactive "r")
22157 (save-excursion
22158 (let ((line-end (org-current-line end)))
22159 (goto-char start)
22160 (while (< (org-current-line) line-end)
22161 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22162 (t (call-interactively 'org-indent-line)))
22163 (move-beginning-of-line 2)))))
22166 ;;; Filling
22168 ;; We use our own fill-paragraph and auto-fill functions.
22170 ;; `org-fill-paragraph' relies on adaptive filling and context
22171 ;; checking. Appropriate `fill-prefix' is computed with
22172 ;; `org-adaptive-fill-function'.
22174 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22175 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22176 ;; `org-adaptive-fill-function' value. Internally,
22177 ;; `org-comment-line-break-function' breaks the line.
22179 ;; `org-setup-filling' installs filling and auto-filling related
22180 ;; variables during `org-mode' initialization.
22182 (defvar org-element-paragraph-separate) ; org-element.el
22183 (defun org-setup-filling ()
22184 (require 'org-element)
22185 ;; Prevent auto-fill from inserting unwanted new items.
22186 (when (boundp 'fill-nobreak-predicate)
22187 (org-set-local
22188 'fill-nobreak-predicate
22189 (org-uniquify
22190 (append fill-nobreak-predicate
22191 '(org-fill-line-break-nobreak-p
22192 org-fill-paragraph-with-timestamp-nobreak-p)))))
22193 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22194 (org-set-local 'paragraph-start paragraph-ending)
22195 (org-set-local 'paragraph-separate paragraph-ending))
22196 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22197 (org-set-local 'auto-fill-inhibit-regexp nil)
22198 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22199 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22200 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22202 (defun org-fill-line-break-nobreak-p ()
22203 "Non-nil when a new line at point would create an Org line break."
22204 (save-excursion
22205 (skip-chars-backward "[ \t]")
22206 (skip-chars-backward "\\\\")
22207 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22209 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22210 "Non-nil when a new line at point would split a timestamp."
22211 (and (org-at-timestamp-p t)
22212 (not (looking-at org-ts-regexp-both))))
22214 (declare-function message-in-body-p "message" ())
22215 (defvar orgtbl-line-start-regexp) ; From org-table.el
22216 (defun org-adaptive-fill-function ()
22217 "Compute a fill prefix for the current line.
22218 Return fill prefix, as a string, or nil if current line isn't
22219 meant to be filled. For convenience, if `adaptive-fill-regexp'
22220 matches in paragraphs or comments, use it."
22221 (catch 'exit
22222 (when (derived-mode-p 'message-mode)
22223 (save-excursion
22224 (beginning-of-line)
22225 (cond ((or (not (message-in-body-p))
22226 (looking-at orgtbl-line-start-regexp))
22227 (throw 'exit nil))
22228 ((looking-at message-cite-prefix-regexp)
22229 (throw 'exit (match-string-no-properties 0)))
22230 ((looking-at org-outline-regexp)
22231 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22232 (org-with-wide-buffer
22233 (let* ((p (line-beginning-position))
22234 (element (save-excursion
22235 (beginning-of-line)
22236 (or (ignore-errors (org-element-at-point))
22237 (user-error "An element cannot be parsed line %d"
22238 (line-number-at-pos (point))))))
22239 (type (org-element-type element))
22240 (post-affiliated (org-element-property :post-affiliated element)))
22241 (unless (and post-affiliated (< p post-affiliated))
22242 (case type
22243 (comment
22244 (save-excursion
22245 (beginning-of-line)
22246 (looking-at "[ \t]*")
22247 (concat (match-string 0) "# ")))
22248 (footnote-definition "")
22249 ((item plain-list)
22250 (make-string (org-list-item-body-column
22251 (or post-affiliated
22252 (org-element-property :begin element)))
22253 ? ))
22254 (paragraph
22255 ;; Fill prefix is usually the same as the current line,
22256 ;; unless the paragraph is at the beginning of an item.
22257 (let ((parent (org-element-property :parent element)))
22258 (save-excursion
22259 (beginning-of-line)
22260 (cond ((eq (org-element-type parent) 'item)
22261 (make-string (org-list-item-body-column
22262 (org-element-property :begin parent))
22263 ? ))
22264 ((and adaptive-fill-regexp
22265 ;; Locally disable
22266 ;; `adaptive-fill-function' to let
22267 ;; `fill-context-prefix' handle
22268 ;; `adaptive-fill-regexp' variable.
22269 (let (adaptive-fill-function)
22270 (fill-context-prefix
22271 post-affiliated
22272 (org-element-property :end element)))))
22273 ((looking-at "[ \t]+") (match-string 0))
22274 (t "")))))
22275 (comment-block
22276 ;; Only fill contents if P is within block boundaries.
22277 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22278 (forward-line)
22279 (point)))
22280 (cend (save-excursion
22281 (goto-char (org-element-property :end element))
22282 (skip-chars-backward " \r\t\n")
22283 (line-beginning-position))))
22284 (when (and (>= p cbeg) (< p cend))
22285 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22286 (match-string 0)
22287 ""))))))))))
22289 (declare-function message-goto-body "message" ())
22290 (defvar message-cite-prefix-regexp) ; From message.el
22291 (defun org-fill-paragraph (&optional justify)
22292 "Fill element at point, when applicable.
22294 This function only applies to comment blocks, comments, example
22295 blocks and paragraphs. Also, as a special case, re-align table
22296 when point is at one.
22298 If JUSTIFY is non-nil (interactively, with prefix argument),
22299 justify as well. If `sentence-end-double-space' is non-nil, then
22300 period followed by one space does not end a sentence, so don't
22301 break a line there. The variable `fill-column' controls the
22302 width for filling.
22304 For convenience, when point is at a plain list, an item or
22305 a footnote definition, try to fill the first paragraph within."
22306 (interactive)
22307 (if (and (derived-mode-p 'message-mode)
22308 (or (not (message-in-body-p))
22309 (save-excursion (move-beginning-of-line 1)
22310 (looking-at message-cite-prefix-regexp))))
22311 ;; First ensure filling is correct in message-mode.
22312 (let ((fill-paragraph-function
22313 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22314 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22315 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22316 (paragraph-separate
22317 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22318 (fill-paragraph nil))
22319 (with-syntax-table org-mode-transpose-word-syntax-table
22320 ;; Move to end of line in order to get the first paragraph
22321 ;; within a plain list or a footnote definition.
22322 (let ((element (save-excursion
22323 (end-of-line)
22324 (or (ignore-errors (org-element-at-point))
22325 (user-error "An element cannot be parsed line %d"
22326 (line-number-at-pos (point)))))))
22327 ;; First check if point is in a blank line at the beginning of
22328 ;; the buffer. In that case, ignore filling.
22329 (case (org-element-type element)
22330 ;; Use major mode filling function is src blocks.
22331 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22332 ;; Align Org tables, leave table.el tables as-is.
22333 (table-row (org-table-align) t)
22334 (table
22335 (when (eq (org-element-property :type element) 'org)
22336 (save-excursion
22337 (goto-char (org-element-property :post-affiliated element))
22338 (org-table-align)))
22340 (paragraph
22341 ;; Paragraphs may contain `line-break' type objects.
22342 (let ((beg (max (point-min)
22343 (org-element-property :contents-begin element)))
22344 (end (min (point-max)
22345 (org-element-property :contents-end element))))
22346 ;; Do nothing if point is at an affiliated keyword.
22347 (if (< (line-end-position) beg) t
22348 (when (derived-mode-p 'message-mode)
22349 ;; In `message-mode', do not fill following citation
22350 ;; in current paragraph nor text before message body.
22351 (let ((body-start (save-excursion (message-goto-body))))
22352 (when body-start (setq beg (max body-start beg))))
22353 (when (save-excursion
22354 (re-search-forward
22355 (concat "^" message-cite-prefix-regexp) end t))
22356 (setq end (match-beginning 0))))
22357 ;; Fill paragraph, taking line breaks into account.
22358 ;; For that, slice the paragraph using line breaks as
22359 ;; separators, and fill the parts in reverse order to
22360 ;; avoid messing with markers.
22361 (save-excursion
22362 (goto-char end)
22363 (mapc
22364 (lambda (pos)
22365 (fill-region-as-paragraph pos (point) justify)
22366 (goto-char pos))
22367 ;; Find the list of ending positions for line breaks
22368 ;; in the current paragraph. Add paragraph
22369 ;; beginning to include first slice.
22370 (nreverse
22371 (cons beg
22372 (org-element-map
22373 (org-element--parse-objects
22374 beg end nil (org-element-restriction 'paragraph))
22375 'line-break
22376 (lambda (lb) (org-element-property :end lb)))))))
22377 t)))
22378 ;; Contents of `comment-block' type elements should be
22379 ;; filled as plain text, but only if point is within block
22380 ;; markers.
22381 (comment-block
22382 (let* ((case-fold-search t)
22383 (beg (save-excursion
22384 (goto-char (org-element-property :begin element))
22385 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22386 (forward-line)
22387 (point)))
22388 (end (save-excursion
22389 (goto-char (org-element-property :end element))
22390 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22391 (line-beginning-position))))
22392 (if (or (< (point) beg) (> (point) end)) t
22393 (fill-region-as-paragraph
22394 (save-excursion (end-of-line)
22395 (re-search-backward "^[ \t]*$" beg 'move)
22396 (line-beginning-position))
22397 (save-excursion (beginning-of-line)
22398 (re-search-forward "^[ \t]*$" end 'move)
22399 (line-beginning-position))
22400 justify))))
22401 ;; Fill comments.
22402 (comment
22403 (let ((begin (org-element-property :post-affiliated element))
22404 (end (org-element-property :end element)))
22405 (when (and (>= (point) begin) (<= (point) end))
22406 (let ((begin (save-excursion
22407 (end-of-line)
22408 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22409 (progn (forward-line) (point))
22410 begin)))
22411 (end (save-excursion
22412 (end-of-line)
22413 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22414 (1- (line-beginning-position))
22415 (skip-chars-backward " \r\t\n")
22416 (line-end-position)))))
22417 ;; Do not fill comments when at a blank line.
22418 (when (> end begin)
22419 (let ((fill-prefix
22420 (save-excursion
22421 (beginning-of-line)
22422 (looking-at "[ \t]*#")
22423 (let ((comment-prefix (match-string 0)))
22424 (goto-char (match-end 0))
22425 (if (looking-at adaptive-fill-regexp)
22426 (concat comment-prefix (match-string 0))
22427 (concat comment-prefix " "))))))
22428 (save-excursion
22429 (fill-region-as-paragraph begin end justify))))))
22431 ;; Ignore every other element.
22432 (otherwise t))))))
22434 (defun org-auto-fill-function ()
22435 "Auto-fill function."
22436 ;; Check if auto-filling is meaningful.
22437 (let ((fc (current-fill-column)))
22438 (when (and fc (> (current-column) fc))
22439 (let* ((fill-prefix (org-adaptive-fill-function))
22440 ;; Enforce empty fill prefix, if required. Otherwise, it
22441 ;; will be computed again.
22442 (adaptive-fill-mode (not (equal fill-prefix ""))))
22443 (when fill-prefix (do-auto-fill))))))
22445 (defun org-comment-line-break-function (&optional soft)
22446 "Break line at point and indent, continuing comment if within one.
22447 The inserted newline is marked hard if variable
22448 `use-hard-newlines' is true, unless optional argument SOFT is
22449 non-nil."
22450 (if soft (insert-and-inherit ?\n) (newline 1))
22451 (save-excursion (forward-char -1) (delete-horizontal-space))
22452 (delete-horizontal-space)
22453 (indent-to-left-margin)
22454 (insert-before-markers-and-inherit fill-prefix))
22457 ;;; Comments
22459 ;; Org comments syntax is quite complex. It requires the entire line
22460 ;; to be just a comment. Also, even with the right syntax at the
22461 ;; beginning of line, some some elements (i.e. verse-block or
22462 ;; example-block) don't accept comments. Usual Emacs comment commands
22463 ;; cannot cope with those requirements. Therefore, Org replaces them.
22465 ;; Org still relies on `comment-dwim', but cannot trust
22466 ;; `comment-only-p'. So, `comment-region-function' and
22467 ;; `uncomment-region-function' both point
22468 ;; to`org-comment-or-uncomment-region'. Eventually,
22469 ;; `org-insert-comment' takes care of insertion of comments at the
22470 ;; beginning of line.
22472 ;; `org-setup-comments-handling' install comments related variables
22473 ;; during `org-mode' initialization.
22475 (defun org-setup-comments-handling ()
22476 (interactive)
22477 (org-set-local 'comment-use-syntax nil)
22478 (org-set-local 'comment-start "# ")
22479 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22480 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22481 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22482 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22484 (defun org-insert-comment ()
22485 "Insert an empty comment above current line.
22486 If the line is empty, insert comment at its beginning."
22487 (beginning-of-line)
22488 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22489 (org-indent-line)
22490 (insert "# "))
22492 (defvar comment-empty-lines) ; From newcomment.el.
22493 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22494 "Comment or uncomment each non-blank line in the region.
22495 Uncomment each non-blank line between BEG and END if it only
22496 contains commented lines. Otherwise, comment them."
22497 (save-restriction
22498 ;; Restrict region
22499 (narrow-to-region (save-excursion (goto-char beg)
22500 (skip-chars-forward " \r\t\n" end)
22501 (line-beginning-position))
22502 (save-excursion (goto-char end)
22503 (skip-chars-backward " \r\t\n" beg)
22504 (line-end-position)))
22505 (let ((uncommentp
22506 ;; UNCOMMENTP is non-nil when every non blank line between
22507 ;; BEG and END is a comment.
22508 (save-excursion
22509 (goto-char (point-min))
22510 (while (and (not (eobp))
22511 (let ((element (org-element-at-point)))
22512 (and (eq (org-element-type element) 'comment)
22513 (goto-char (min (point-max)
22514 (org-element-property
22515 :end element)))))))
22516 (eobp))))
22517 (if uncommentp
22518 ;; Only blank lines and comments in region: uncomment it.
22519 (save-excursion
22520 (goto-char (point-min))
22521 (while (not (eobp))
22522 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22523 (replace-match "" nil nil nil 1))
22524 (forward-line)))
22525 ;; Comment each line in region.
22526 (let ((min-indent (point-max)))
22527 ;; First find the minimum indentation across all lines.
22528 (save-excursion
22529 (goto-char (point-min))
22530 (while (and (not (eobp)) (not (zerop min-indent)))
22531 (unless (looking-at "[ \t]*$")
22532 (setq min-indent (min min-indent (current-indentation))))
22533 (forward-line)))
22534 ;; Then loop over all lines.
22535 (save-excursion
22536 (goto-char (point-min))
22537 (while (not (eobp))
22538 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22539 ;; Don't get fooled by invisible text (e.g. link path)
22540 ;; when moving to column MIN-INDENT.
22541 (let ((buffer-invisibility-spec nil))
22542 (org-move-to-column min-indent t))
22543 (insert comment-start))
22544 (forward-line))))))))
22547 ;;; Planning
22549 ;; This section contains tools to operate on timestamp objects, as
22550 ;; returned by, e.g. `org-element-context'.
22552 (defun org-timestamp-has-time-p (timestamp)
22553 "Non-nil when TIMESTAMP has a time specified."
22554 (org-element-property :hour-start timestamp))
22556 (defun org-timestamp-format (timestamp format &optional end utc)
22557 "Format a TIMESTAMP element into a string.
22559 FORMAT is a format specifier to be passed to
22560 `format-time-string'.
22562 When optional argument END is non-nil, use end of date-range or
22563 time-range, if possible.
22565 When optional argument UTC is non-nil, time will be expressed as
22566 Universal Time."
22567 (format-time-string
22568 format
22569 (apply 'encode-time
22570 (cons 0
22571 (mapcar
22572 (lambda (prop) (or (org-element-property prop timestamp) 0))
22573 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22574 '(:minute-start :hour-start :day-start :month-start
22575 :year-start)))))
22576 utc))
22578 (defun org-timestamp-split-range (timestamp &optional end)
22579 "Extract a timestamp object from a date or time range.
22581 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22582 the end of the range. Otherwise, extract its start.
22584 Return a new timestamp object sharing the same parent as
22585 TIMESTAMP."
22586 (let ((type (org-element-property :type timestamp)))
22587 (if (memq type '(active inactive diary)) timestamp
22588 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22589 ;; Set new type.
22590 (org-element-put-property
22591 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22592 ;; Copy start properties over end properties if END is
22593 ;; non-nil. Otherwise, copy end properties over `start' ones.
22594 (let ((p-alist '((:minute-start . :minute-end)
22595 (:hour-start . :hour-end)
22596 (:day-start . :day-end)
22597 (:month-start . :month-end)
22598 (:year-start . :year-end))))
22599 (dolist (p-cell p-alist)
22600 (org-element-put-property
22601 split-ts
22602 (funcall (if end 'car 'cdr) p-cell)
22603 (org-element-property
22604 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22605 ;; Eventually refresh `:raw-value'.
22606 (org-element-put-property split-ts :raw-value nil)
22607 (org-element-put-property
22608 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22610 (defun org-timestamp-translate (timestamp &optional boundary)
22611 "Apply `org-translate-time' on a TIMESTAMP object.
22612 When optional argument BOUNDARY is non-nil, it is either the
22613 symbol `start' or `end'. In this case, only translate the
22614 starting or ending part of TIMESTAMP if it is a date or time
22615 range. Otherwise, translate both parts."
22616 (if (and (not boundary)
22617 (memq (org-element-property :type timestamp)
22618 '(active-range inactive-range)))
22619 (concat
22620 (org-translate-time
22621 (org-element-property :raw-value
22622 (org-timestamp-split-range timestamp)))
22623 "--"
22624 (org-translate-time
22625 (org-element-property :raw-value
22626 (org-timestamp-split-range timestamp t))))
22627 (org-translate-time
22628 (org-element-property
22629 :raw-value
22630 (if (not boundary) timestamp
22631 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22635 ;;; Other stuff.
22637 (defun org-toggle-fixed-width-section (arg)
22638 "Toggle the fixed-width export.
22639 If there is no active region, the QUOTE keyword at the current headline is
22640 inserted or removed. When present, it causes the text between this headline
22641 and the next to be exported as fixed-width text, and unmodified.
22642 If there is an active region, this command adds or removes a colon as the
22643 first character of this line. If the first character of a line is a colon,
22644 this line is also exported in fixed-width font."
22645 (interactive "P")
22646 (let* ((cc 0)
22647 (regionp (org-region-active-p))
22648 (beg (if regionp (region-beginning) (point)))
22649 (end (if regionp (region-end)))
22650 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22651 (case-fold-search nil)
22652 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22653 off)
22654 (if regionp
22655 (save-excursion
22656 (goto-char beg)
22657 (setq cc (current-column))
22658 (beginning-of-line 1)
22659 (setq off (looking-at re))
22660 (while (> nlines 0)
22661 (setq nlines (1- nlines))
22662 (beginning-of-line 1)
22663 (cond
22664 (arg
22665 (org-move-to-column cc t)
22666 (insert ": \n")
22667 (forward-line -1))
22668 ((and off (looking-at re))
22669 (replace-match "" t t nil 1))
22670 ((not off) (org-move-to-column cc t) (insert ": ")))
22671 (forward-line 1)))
22672 (save-excursion
22673 (org-back-to-heading)
22674 (cond
22675 ((looking-at (format org-heading-keyword-regexp-format
22676 org-quote-string))
22677 (goto-char (match-end 1))
22678 (looking-at (concat " +" org-quote-string))
22679 (replace-match "" t t)
22680 (when (eolp) (insert " ")))
22681 ((looking-at org-outline-regexp)
22682 (goto-char (match-end 0))
22683 (insert org-quote-string " ")))))))
22685 (defun org-reftex-citation ()
22686 "Use reftex-citation to insert a citation into the buffer.
22687 This looks for a line like
22689 #+BIBLIOGRAPHY: foo plain option:-d
22691 and derives from it that foo.bib is the bibliography file relevant
22692 for this document. It then installs the necessary environment for RefTeX
22693 to work in this buffer and calls `reftex-citation' to insert a citation
22694 into the buffer.
22696 Export of such citations to both LaTeX and HTML is handled by the contributed
22697 package ox-bibtex by Taru Karttunen."
22698 (interactive)
22699 (let ((reftex-docstruct-symbol 'rds)
22700 (reftex-cite-format "\\cite{%l}")
22701 rds bib)
22702 (save-excursion
22703 (save-restriction
22704 (widen)
22705 (let ((case-fold-search t)
22706 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22707 (if (not (save-excursion
22708 (or (re-search-forward re nil t)
22709 (re-search-backward re nil t))))
22710 (error "No bibliography defined in file")
22711 (setq bib (concat (match-string 1) ".bib")
22712 rds (list (list 'bib bib)))))))
22713 (call-interactively 'reftex-citation)))
22715 ;;;; Functions extending outline functionality
22717 (defun org-beginning-of-line (&optional arg)
22718 "Go to the beginning of the current line. If that is invisible, continue
22719 to a visible line beginning. This makes the function of C-a more intuitive.
22720 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22721 first attempt, and only move to after the tags when the cursor is already
22722 beyond the end of the headline."
22723 (interactive "P")
22724 (let ((pos (point))
22725 (special (if (consp org-special-ctrl-a/e)
22726 (car org-special-ctrl-a/e)
22727 org-special-ctrl-a/e))
22728 deactivate-mark refpos)
22729 (if (org-bound-and-true-p visual-line-mode)
22730 (beginning-of-visual-line 1)
22731 (beginning-of-line 1))
22732 (if (and arg (fboundp 'move-beginning-of-line))
22733 (call-interactively 'move-beginning-of-line)
22734 (if (bobp)
22736 (backward-char 1)
22737 (if (org-truely-invisible-p)
22738 (while (and (not (bobp)) (org-truely-invisible-p))
22739 (backward-char 1)
22740 (beginning-of-line 1))
22741 (forward-char 1))))
22742 (when special
22743 (cond
22744 ((and (looking-at org-complex-heading-regexp)
22745 (= (char-after (match-end 1)) ?\ ))
22746 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22747 (point-at-eol)))
22748 (goto-char
22749 (if (eq special t)
22750 (cond ((> pos refpos) refpos)
22751 ((= pos (point)) refpos)
22752 (t (point)))
22753 (cond ((> pos (point)) (point))
22754 ((not (eq last-command this-command)) (point))
22755 (t refpos)))))
22756 ((org-at-item-p)
22757 ;; Being at an item and not looking at an the item means point
22758 ;; was previously moved to beginning of a visual line, which
22759 ;; doesn't contain the item. Therefore, do nothing special,
22760 ;; just stay here.
22761 (when (looking-at org-list-full-item-re)
22762 ;; Set special position at first white space character after
22763 ;; bullet, and check-box, if any.
22764 (let ((after-bullet
22765 (let ((box (match-end 3)))
22766 (if (not box) (match-end 1)
22767 (let ((after (char-after box)))
22768 (if (and after (= after ? )) (1+ box) box))))))
22769 ;; Special case: Move point to special position when
22770 ;; currently after it or at beginning of line.
22771 (if (eq special t)
22772 (when (or (> pos after-bullet) (= (point) pos))
22773 (goto-char after-bullet))
22774 ;; Reversed case: Move point to special position when
22775 ;; point was already at beginning of line and command is
22776 ;; repeated.
22777 (when (and (= (point) pos) (eq last-command this-command))
22778 (goto-char after-bullet))))))))
22779 (org-no-warnings
22780 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22781 (setq disable-point-adjustment
22782 (or (not (invisible-p (point)))
22783 (not (invisible-p (max (point-min) (1- (point))))))))
22785 (defun org-end-of-line (&optional arg)
22786 "Go to the end of the line.
22787 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22788 tags on the first attempt, and only move to after the tags when
22789 the cursor is already beyond the end of the headline."
22790 (interactive "P")
22791 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22792 org-special-ctrl-a/e))
22793 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22794 'end-of-visual-line)
22795 ((fboundp 'move-end-of-line) 'move-end-of-line)
22796 (t 'end-of-line)))
22797 deactivate-mark)
22798 (if (or (not special) arg) (call-interactively move-fun)
22799 (let* ((element (save-excursion (beginning-of-line)
22800 (org-element-at-point)))
22801 (type (org-element-type element)))
22802 (cond
22803 ((memq type '(headline inlinetask))
22804 (let ((pos (point)))
22805 (beginning-of-line 1)
22806 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22807 (if (eq special t)
22808 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22809 (goto-char (match-beginning 1))
22810 (goto-char (match-end 0)))
22811 (if (or (< pos (match-end 0))
22812 (not (eq this-command last-command)))
22813 (goto-char (match-end 0))
22814 (goto-char (match-beginning 1))))
22815 (call-interactively move-fun))))
22816 ((org-element-property :hiddenp element)
22817 ;; If element is hidden, `move-end-of-line' would put point
22818 ;; after it. Use `end-of-line' to stay on current line.
22819 (call-interactively 'end-of-line))
22820 (t (call-interactively move-fun)))))
22821 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22822 (setq disable-point-adjustment
22823 (or (not (invisible-p (point)))
22824 (not (invisible-p (max (point-min) (1- (point))))))))
22826 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22827 (define-key org-mode-map "\C-e" 'org-end-of-line)
22829 (defun org-backward-sentence (&optional arg)
22830 "Go to beginning of sentence, or beginning of table field.
22831 This will call `backward-sentence' or `org-table-beginning-of-field',
22832 depending on context."
22833 (interactive "P")
22834 (cond
22835 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22836 (t (call-interactively 'backward-sentence))))
22838 (defun org-forward-sentence (&optional arg)
22839 "Go to end of sentence, or end of table field.
22840 This will call `forward-sentence' or `org-table-end-of-field',
22841 depending on context."
22842 (interactive "P")
22843 (cond
22844 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22845 (t (call-interactively 'forward-sentence))))
22847 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22848 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22850 (defun org-kill-line (&optional arg)
22851 "Kill line, to tags or end of line."
22852 (interactive "P")
22853 (cond
22854 ((or (not org-special-ctrl-k)
22855 (bolp)
22856 (not (org-at-heading-p)))
22857 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22858 org-ctrl-k-protect-subtree)
22859 (if (or (eq org-ctrl-k-protect-subtree 'error)
22860 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22861 (user-error "C-k aborted as it would kill a hidden subtree")))
22862 (call-interactively
22863 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22864 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22865 (kill-region (point) (match-beginning 1))
22866 (org-set-tags nil t))
22867 (t (kill-region (point) (point-at-eol)))))
22869 (define-key org-mode-map "\C-k" 'org-kill-line)
22871 (defun org-yank (&optional arg)
22872 "Yank. If the kill is a subtree, treat it specially.
22873 This command will look at the current kill and check if is a single
22874 subtree, or a series of subtrees[1]. If it passes the test, and if the
22875 cursor is at the beginning of a line or after the stars of a currently
22876 empty headline, then the yank is handled specially. How exactly depends
22877 on the value of the following variables, both set by default.
22879 org-yank-folded-subtrees
22880 When set, the subtree(s) will be folded after insertion, but only
22881 if doing so would now swallow text after the yanked text.
22883 org-yank-adjusted-subtrees
22884 When set, the subtree will be promoted or demoted in order to
22885 fit into the local outline tree structure, which means that the level
22886 will be adjusted so that it becomes the smaller one of the two
22887 *visible* surrounding headings.
22889 Any prefix to this command will cause `yank' to be called directly with
22890 no special treatment. In particular, a simple \\[universal-argument] prefix \
22891 will just
22892 plainly yank the text as it is.
22894 \[1] The test checks if the first non-white line is a heading
22895 and if there are no other headings with fewer stars."
22896 (interactive "P")
22897 (org-yank-generic 'yank arg))
22899 (defun org-yank-generic (command arg)
22900 "Perform some yank-like command.
22902 This function implements the behavior described in the `org-yank'
22903 documentation. However, it has been generalized to work for any
22904 interactive command with similar behavior."
22906 ;; pretend to be command COMMAND
22907 (setq this-command command)
22909 (if arg
22910 (call-interactively command)
22912 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22913 (and (org-kill-is-subtree-p)
22914 (or (bolp)
22915 (and (looking-at "[ \t]*$")
22916 (string-match
22917 "\\`\\*+\\'"
22918 (buffer-substring (point-at-bol) (point)))))))
22919 swallowp)
22920 (cond
22921 ((and subtreep org-yank-folded-subtrees)
22922 (let ((beg (point))
22923 end)
22924 (if (and subtreep org-yank-adjusted-subtrees)
22925 (org-paste-subtree nil nil 'for-yank)
22926 (call-interactively command))
22928 (setq end (point))
22929 (goto-char beg)
22930 (when (and (bolp) subtreep
22931 (not (setq swallowp
22932 (org-yank-folding-would-swallow-text beg end))))
22933 (org-with-limited-levels
22934 (or (looking-at org-outline-regexp)
22935 (re-search-forward org-outline-regexp-bol end t))
22936 (while (and (< (point) end) (looking-at org-outline-regexp))
22937 (hide-subtree)
22938 (org-cycle-show-empty-lines 'folded)
22939 (condition-case nil
22940 (outline-forward-same-level 1)
22941 (error (goto-char end))))))
22942 (when swallowp
22943 (message
22944 "Inserted text not folded because that would swallow text"))
22946 (goto-char end)
22947 (skip-chars-forward " \t\n\r")
22948 (beginning-of-line 1)
22949 (push-mark beg 'nomsg)))
22950 ((and subtreep org-yank-adjusted-subtrees)
22951 (let ((beg (point-at-bol)))
22952 (org-paste-subtree nil nil 'for-yank)
22953 (push-mark beg 'nomsg)))
22955 (call-interactively command))))))
22957 (defun org-yank-folding-would-swallow-text (beg end)
22958 "Would hide-subtree at BEG swallow any text after END?"
22959 (let (level)
22960 (org-with-limited-levels
22961 (save-excursion
22962 (goto-char beg)
22963 (when (or (looking-at org-outline-regexp)
22964 (re-search-forward org-outline-regexp-bol end t))
22965 (setq level (org-outline-level)))
22966 (goto-char end)
22967 (skip-chars-forward " \t\r\n\v\f")
22968 (if (or (eobp)
22969 (and (bolp) (looking-at org-outline-regexp)
22970 (<= (org-outline-level) level)))
22971 nil ; Nothing would be swallowed
22972 t))))) ; something would swallow
22974 (define-key org-mode-map "\C-y" 'org-yank)
22976 (defun org-truely-invisible-p ()
22977 "Check if point is at a character currently not visible.
22978 This version does not only check the character property, but also
22979 `visible-mode'."
22980 ;; Early versions of noutline don't have `outline-invisible-p'.
22981 (if (org-bound-and-true-p visible-mode)
22983 (outline-invisible-p)))
22985 (defun org-invisible-p2 ()
22986 "Check if point is at a character currently not visible."
22987 (save-excursion
22988 (if (and (eolp) (not (bobp))) (backward-char 1))
22989 ;; Early versions of noutline don't have `outline-invisible-p'.
22990 (outline-invisible-p)))
22992 (defun org-back-to-heading (&optional invisible-ok)
22993 "Call `outline-back-to-heading', but provide a better error message."
22994 (condition-case nil
22995 (outline-back-to-heading invisible-ok)
22996 (error (error "Before first headline at position %d in buffer %s"
22997 (point) (current-buffer)))))
22999 (defun org-before-first-heading-p ()
23000 "Before first heading?"
23001 (save-excursion
23002 (end-of-line)
23003 (null (re-search-backward org-outline-regexp-bol nil t))))
23005 (defun org-at-heading-p (&optional ignored)
23006 (outline-on-heading-p t))
23007 ;; Compatibility alias with Org versions < 7.8.03
23008 (defalias 'org-on-heading-p 'org-at-heading-p)
23010 (defun org-at-comment-p nil
23011 "Is cursor in a line starting with a # character?"
23012 (save-excursion
23013 (beginning-of-line)
23014 (looking-at "^#")))
23016 (defun org-at-drawer-p nil
23017 "Is cursor at a drawer keyword?"
23018 (save-excursion
23019 (move-beginning-of-line 1)
23020 (looking-at org-drawer-regexp)))
23022 (defun org-at-block-p nil
23023 "Is cursor at a block keyword?"
23024 (save-excursion
23025 (move-beginning-of-line 1)
23026 (looking-at org-block-regexp)))
23028 (defun org-point-at-end-of-empty-headline ()
23029 "If point is at the end of an empty headline, return t, else nil.
23030 If the heading only contains a TODO keyword, it is still still considered
23031 empty."
23032 (and (looking-at "[ \t]*$")
23033 (when org-todo-line-regexp
23034 (save-excursion
23035 (beginning-of-line 1)
23036 (let ((case-fold-search nil))
23037 (looking-at org-todo-line-regexp)
23038 (string= (match-string 3) ""))))))
23040 (defun org-at-heading-or-item-p ()
23041 (or (org-at-heading-p) (org-at-item-p)))
23043 (defun org-at-target-p ()
23044 (or (org-in-regexp org-radio-target-regexp)
23045 (org-in-regexp org-target-regexp)))
23046 ;; Compatibility alias with Org versions < 7.8.03
23047 (defalias 'org-on-target-p 'org-at-target-p)
23049 (defun org-up-heading-all (arg)
23050 "Move to the heading line of which the present line is a subheading.
23051 This function considers both visible and invisible heading lines.
23052 With argument, move up ARG levels."
23053 (if (fboundp 'outline-up-heading-all)
23054 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23055 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23057 (defun org-up-heading-safe ()
23058 "Move to the heading line of which the present line is a subheading.
23059 This version will not throw an error. It will return the level of the
23060 headline found, or nil if no higher level is found.
23062 Also, this function will be a lot faster than `outline-up-heading',
23063 because it relies on stars being the outline starters. This can really
23064 make a significant difference in outlines with very many siblings."
23065 (let (start-level re)
23066 (org-back-to-heading t)
23067 (setq start-level (funcall outline-level))
23068 (if (equal start-level 1)
23070 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23071 (if (re-search-backward re nil t)
23072 (funcall outline-level)))))
23074 (defun org-first-sibling-p ()
23075 "Is this heading the first child of its parents?"
23076 (interactive)
23077 (let ((re org-outline-regexp-bol)
23078 level l)
23079 (unless (org-at-heading-p t)
23080 (user-error "Not at a heading"))
23081 (setq level (funcall outline-level))
23082 (save-excursion
23083 (if (not (re-search-backward re nil t))
23085 (setq l (funcall outline-level))
23086 (< l level)))))
23088 (defun org-goto-sibling (&optional previous)
23089 "Goto the next sibling, even if it is invisible.
23090 When PREVIOUS is set, go to the previous sibling instead. Returns t
23091 when a sibling was found. When none is found, return nil and don't
23092 move point."
23093 (let ((fun (if previous 're-search-backward 're-search-forward))
23094 (pos (point))
23095 (re org-outline-regexp-bol)
23096 level l)
23097 (when (condition-case nil (org-back-to-heading t) (error nil))
23098 (setq level (funcall outline-level))
23099 (catch 'exit
23100 (or previous (forward-char 1))
23101 (while (funcall fun re nil t)
23102 (setq l (funcall outline-level))
23103 (when (< l level) (goto-char pos) (throw 'exit nil))
23104 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23105 (goto-char pos)
23106 nil))))
23108 (defun org-show-siblings ()
23109 "Show all siblings of the current headline."
23110 (save-excursion
23111 (while (org-goto-sibling) (org-flag-heading nil)))
23112 (save-excursion
23113 (while (org-goto-sibling 'previous)
23114 (org-flag-heading nil))))
23116 (defun org-goto-first-child ()
23117 "Goto the first child, even if it is invisible.
23118 Return t when a child was found. Otherwise don't move point and
23119 return nil."
23120 (let (level (pos (point)) (re org-outline-regexp-bol))
23121 (when (condition-case nil (org-back-to-heading t) (error nil))
23122 (setq level (outline-level))
23123 (forward-char 1)
23124 (if (and (re-search-forward re nil t) (> (outline-level) level))
23125 (progn (goto-char (match-beginning 0)) t)
23126 (goto-char pos) nil))))
23128 (defun org-show-hidden-entry ()
23129 "Show an entry where even the heading is hidden."
23130 (save-excursion
23131 (org-show-entry)))
23133 (defun org-flag-heading (flag &optional entry)
23134 "Flag the current heading. FLAG non-nil means make invisible.
23135 When ENTRY is non-nil, show the entire entry."
23136 (save-excursion
23137 (org-back-to-heading t)
23138 ;; Check if we should show the entire entry
23139 (if entry
23140 (progn
23141 (org-show-entry)
23142 (save-excursion
23143 (and (outline-next-heading)
23144 (org-flag-heading nil))))
23145 (outline-flag-region (max (point-min) (1- (point)))
23146 (save-excursion (outline-end-of-heading) (point))
23147 flag))))
23149 (defun org-get-next-sibling ()
23150 "Move to next heading of the same level, and return point.
23151 If there is no such heading, return nil.
23152 This is like outline-next-sibling, but invisible headings are ok."
23153 (let ((level (funcall outline-level)))
23154 (outline-next-heading)
23155 (while (and (not (eobp)) (> (funcall outline-level) level))
23156 (outline-next-heading))
23157 (if (or (eobp) (< (funcall outline-level) level))
23159 (point))))
23161 (defun org-get-last-sibling ()
23162 "Move to previous heading of the same level, and return point.
23163 If there is no such heading, return nil."
23164 (let ((opoint (point))
23165 (level (funcall outline-level)))
23166 (outline-previous-heading)
23167 (when (and (/= (point) opoint) (outline-on-heading-p t))
23168 (while (and (> (funcall outline-level) level)
23169 (not (bobp)))
23170 (outline-previous-heading))
23171 (if (< (funcall outline-level) level)
23173 (point)))))
23175 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23176 "Goto to the end of a subtree."
23177 ;; This contains an exact copy of the original function, but it uses
23178 ;; `org-back-to-heading', to make it work also in invisible
23179 ;; trees. And is uses an invisible-ok argument.
23180 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23181 ;; Furthermore, when used inside Org, finding the end of a large subtree
23182 ;; with many children and grandchildren etc, this can be much faster
23183 ;; than the outline version.
23184 (org-back-to-heading invisible-ok)
23185 (let ((first t)
23186 (level (funcall outline-level)))
23187 (if (and (derived-mode-p 'org-mode) (< level 1000))
23188 ;; A true heading (not a plain list item), in Org-mode
23189 ;; This means we can easily find the end by looking
23190 ;; only for the right number of stars. Using a regexp to do
23191 ;; this is so much faster than using a Lisp loop.
23192 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23193 (forward-char 1)
23194 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23195 ;; something else, do it the slow way
23196 (while (and (not (eobp))
23197 (or first (> (funcall outline-level) level)))
23198 (setq first nil)
23199 (outline-next-heading)))
23200 (unless to-heading
23201 (if (memq (preceding-char) '(?\n ?\^M))
23202 (progn
23203 ;; Go to end of line before heading
23204 (forward-char -1)
23205 (if (memq (preceding-char) '(?\n ?\^M))
23206 ;; leave blank line before heading
23207 (forward-char -1))))))
23208 (point))
23210 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23211 "Use Org version in org-mode, for dramatic speed-up."
23212 (if (derived-mode-p 'org-mode)
23213 (progn
23214 (org-end-of-subtree nil t)
23215 (unless (eobp) (backward-char 1)))
23216 ad-do-it))
23218 (defun org-end-of-meta-data-and-drawers ()
23219 "Jump to the first text after meta data and drawers in the current entry.
23220 This will move over empty lines, lines with planning time stamps,
23221 clocking lines, and drawers."
23222 (org-back-to-heading t)
23223 (let ((end (save-excursion (outline-next-heading) (point)))
23224 (re (concat "\\(" org-drawer-regexp "\\)"
23225 "\\|" "[ \t]*" org-keyword-time-regexp)))
23226 (forward-line 1)
23227 (while (re-search-forward re end t)
23228 (if (not (match-end 1))
23229 ;; empty or planning line
23230 (forward-line 1)
23231 ;; a drawer, find the end
23232 (re-search-forward "^[ \t]*:END:" end 'move)
23233 (forward-line 1)))
23234 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23235 (point)))
23237 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23238 "Move forward to the ARG'th subheading at same level as this one.
23239 Stop at the first and last subheadings of a superior heading.
23240 Normally this only looks at visible headings, but when INVISIBLE-OK is
23241 non-nil it will also look at invisible ones."
23242 (interactive "p")
23243 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23244 (if (and arg (< arg 0))
23245 (goto-char (point-min))
23246 (outline-next-heading))
23247 (org-at-heading-p)
23248 (let ((level (- (match-end 0) (match-beginning 0) 1))
23249 (f (if (and arg (< arg 0))
23250 're-search-backward
23251 're-search-forward))
23252 (count (if arg (abs arg) 1))
23253 (result (point)))
23254 (while (and (prog1 (> count 0)
23255 (forward-char (if (and arg (< arg 0)) -1 1)))
23256 (funcall f org-outline-regexp-bol nil 'move))
23257 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23258 (cond ((< l level) (setq count 0))
23259 ((and (= l level)
23260 (or invisible-ok
23261 (progn
23262 (goto-char (line-beginning-position))
23263 (not (outline-invisible-p)))))
23264 (setq count (1- count))
23265 (when (eq l level)
23266 (setq result (point)))))))
23267 (goto-char result))
23268 (beginning-of-line 1)))
23270 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23271 "Move backward to the ARG'th subheading at same level as this one.
23272 Stop at the first and last subheadings of a superior heading."
23273 (interactive "p")
23274 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23276 (defun org-next-block (arg &optional backward block-regexp)
23277 "Jump to the next block.
23278 With a prefix argument ARG, jump forward ARG many source blocks.
23279 When BACKWARD is non-nil, jump to the previous block.
23280 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23281 (interactive "p")
23282 (let ((re (or block-regexp org-block-regexp))
23283 (re-search-fn (or (and backward 're-search-backward)
23284 're-search-forward)))
23285 (if (looking-at re) (forward-char 1))
23286 (condition-case nil
23287 (funcall re-search-fn re nil nil arg)
23288 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23289 (goto-char (match-beginning 0)) (org-show-context)))
23291 (defun org-previous-block (arg &optional block-regexp)
23292 "Jump to the previous block.
23293 With a prefix argument ARG, jump backward ARG many source blocks.
23294 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23295 (interactive "p")
23296 (org-next-block arg t block-regexp))
23298 (defun org-forward-paragraph ()
23299 "Move forward to beginning of next paragraph or equivalent.
23301 The function moves point to the beginning of the next visible
23302 structural element, which can be a paragraph, a table, a list
23303 item, etc. It also provides some special moves for convenience:
23305 - On an affiliated keyword, jump to the beginning of the
23306 relative element.
23307 - On an item or a footnote definition, move to the second
23308 element inside, if any.
23309 - On a table or a property drawer, jump after it.
23310 - On a verse or source block, stop after blank lines."
23311 (interactive)
23312 (when (eobp) (user-error "Cannot move further down"))
23313 (let* ((deactivate-mark nil)
23314 (element (org-element-at-point))
23315 (type (org-element-type element))
23316 (post-affiliated (org-element-property :post-affiliated element))
23317 (contents-begin (org-element-property :contents-begin element))
23318 (contents-end (org-element-property :contents-end element))
23319 (end (let ((end (org-element-property :end element)) (parent element))
23320 (while (and (setq parent (org-element-property :parent parent))
23321 (= (org-element-property :contents-end parent) end))
23322 (setq end (org-element-property :end parent)))
23323 end)))
23324 (cond ((not element)
23325 (skip-chars-forward " \r\t\n")
23326 (or (eobp) (beginning-of-line)))
23327 ;; On affiliated keywords, move to element's beginning.
23328 ((and post-affiliated (< (point) post-affiliated))
23329 (goto-char post-affiliated))
23330 ;; At a table row, move to the end of the table. Similarly,
23331 ;; at a node property, move to the end of the property
23332 ;; drawer.
23333 ((memq type '(node-property table-row))
23334 (goto-char (org-element-property
23335 :end (org-element-property :parent element))))
23336 ((memq type '(property-drawer table)) (goto-char end))
23337 ;; Consider blank lines as separators in verse and source
23338 ;; blocks to ease editing.
23339 ((memq type '(src-block verse-block))
23340 (when (eq type 'src-block)
23341 (setq contents-end
23342 (save-excursion (goto-char end)
23343 (skip-chars-backward " \r\t\n")
23344 (line-beginning-position))))
23345 (beginning-of-line)
23346 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23347 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23348 (goto-char end)
23349 (skip-chars-forward " \r\t\n")
23350 (if (= (point) contents-end) (goto-char end)
23351 (beginning-of-line))))
23352 ;; With no contents, just skip element.
23353 ((not contents-begin) (goto-char end))
23354 ;; If contents are invisible, skip the element altogether.
23355 ((outline-invisible-p (line-end-position))
23356 (case type
23357 (headline
23358 (org-with-limited-levels (outline-next-visible-heading 1)))
23359 ;; At a plain list, make sure we move to the next item
23360 ;; instead of skipping the whole list.
23361 (plain-list (forward-char)
23362 (org-forward-paragraph))
23363 (otherwise (goto-char end))))
23364 ((>= (point) contents-end) (goto-char end))
23365 ((>= (point) contents-begin)
23366 ;; This can only happen on paragraphs and plain lists.
23367 (case type
23368 (paragraph (goto-char end))
23369 ;; At a plain list, try to move to second element in
23370 ;; first item, if possible.
23371 (plain-list (end-of-line)
23372 (org-forward-paragraph))))
23373 ;; When contents start on the middle of a line (e.g. in
23374 ;; items and footnote definitions), try to reach first
23375 ;; element starting after current line.
23376 ((> (line-end-position) contents-begin)
23377 (end-of-line)
23378 (org-forward-paragraph))
23379 (t (goto-char contents-begin)))))
23381 (defun org-backward-paragraph ()
23382 "Move backward to start of previous paragraph or equivalent.
23384 The function moves point to the beginning of the current
23385 structural element, which can be a paragraph, a table, a list
23386 item, etc., or to the beginning of the previous visible one if
23387 point is already there. It also provides some special moves for
23388 convenience:
23390 - On an affiliated keyword, jump to the first one.
23391 - On a table or a property drawer, move to its beginning.
23392 - On a verse or source block, stop before blank lines."
23393 (interactive)
23394 (when (bobp) (user-error "Cannot move further up"))
23395 (let* ((deactivate-mark nil)
23396 (element (org-element-at-point))
23397 (type (org-element-type element))
23398 (contents-begin (org-element-property :contents-begin element))
23399 (contents-end (org-element-property :contents-end element))
23400 (post-affiliated (org-element-property :post-affiliated element))
23401 (begin (org-element-property :begin element)))
23402 (cond
23403 ((not element) (goto-char (point-min)))
23404 ((= (point) begin)
23405 (backward-char)
23406 (org-backward-paragraph))
23407 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23408 ((memq type '(node-property table-row))
23409 (goto-char (org-element-property
23410 :post-affiliated (org-element-property :parent element))))
23411 ((memq type '(property-drawer table)) (goto-char begin))
23412 ((memq type '(src-block verse-block))
23413 (when (eq type 'src-block)
23414 (setq contents-begin
23415 (save-excursion (goto-char begin) (forward-line) (point))))
23416 (if (= (point) contents-begin) (goto-char post-affiliated)
23417 ;; Inside a verse block, see blank lines as paragraph
23418 ;; separators.
23419 (let ((origin (point)))
23420 (skip-chars-backward " \r\t\n" contents-begin)
23421 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23422 (skip-chars-forward " \r\t\n" origin)
23423 (if (= (point) origin) (goto-char contents-begin)
23424 (beginning-of-line))))))
23425 ((not contents-begin) (goto-char (or post-affiliated begin)))
23426 ((eq type 'paragraph)
23427 (goto-char contents-begin)
23428 ;; When at first paragraph in an item or a footnote definition,
23429 ;; move directly to beginning of line.
23430 (let ((parent-contents
23431 (org-element-property
23432 :contents-begin (org-element-property :parent element))))
23433 (when (and parent-contents (= parent-contents contents-begin))
23434 (beginning-of-line))))
23435 ;; At the end of a greater element, move to the beginning of the
23436 ;; last element within.
23437 ((>= (point) contents-end)
23438 (goto-char (1- contents-end))
23439 (org-backward-paragraph))
23440 (t (goto-char (or post-affiliated begin))))
23441 ;; Ensure we never leave point invisible.
23442 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23444 (defun org-forward-element ()
23445 "Move forward by one element.
23446 Move to the next element at the same level, when possible."
23447 (interactive)
23448 (cond ((eobp) (user-error "Cannot move further down"))
23449 ((org-with-limited-levels (org-at-heading-p))
23450 (let ((origin (point)))
23451 (goto-char (org-end-of-subtree nil t))
23452 (unless (org-with-limited-levels (org-at-heading-p))
23453 (goto-char origin)
23454 (user-error "Cannot move further down"))))
23456 (let* ((elem (org-element-at-point))
23457 (end (org-element-property :end elem))
23458 (parent (org-element-property :parent elem)))
23459 (cond ((and parent (= (org-element-property :contents-end parent) end))
23460 (goto-char (org-element-property :end parent)))
23461 ((integer-or-marker-p end) (goto-char end))
23462 (t (message "No element at point")))))))
23464 (defun org-backward-element ()
23465 "Move backward by one element.
23466 Move to the previous element at the same level, when possible."
23467 (interactive)
23468 (cond ((bobp) (user-error "Cannot move further up"))
23469 ((org-with-limited-levels (org-at-heading-p))
23470 ;; At a headline, move to the previous one, if any, or stay
23471 ;; here.
23472 (let ((origin (point)))
23473 (org-with-limited-levels (org-backward-heading-same-level 1))
23474 ;; When current headline has no sibling above, move to its
23475 ;; parent.
23476 (when (= (point) origin)
23477 (or (org-with-limited-levels (org-up-heading-safe))
23478 (progn (goto-char origin)
23479 (user-error "Cannot move further up"))))))
23481 (let* ((trail (org-element-at-point 'keep-trail))
23482 (elem (car trail))
23483 (prev-elem (nth 1 trail))
23484 (beg (org-element-property :begin elem)))
23485 (cond
23486 ;; Move to beginning of current element if point isn't
23487 ;; there already.
23488 ((null beg) (message "No element at point"))
23489 ((/= (point) beg) (goto-char beg))
23490 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23491 ((org-before-first-heading-p) (goto-char (point-min)))
23492 (t (org-back-to-heading)))))))
23494 (defun org-up-element ()
23495 "Move to upper element."
23496 (interactive)
23497 (if (org-with-limited-levels (org-at-heading-p))
23498 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23499 (let* ((elem (org-element-at-point))
23500 (parent (org-element-property :parent elem)))
23501 (if parent (goto-char (org-element-property :begin parent))
23502 (if (org-with-limited-levels (org-before-first-heading-p))
23503 (user-error "No surrounding element")
23504 (org-with-limited-levels (org-back-to-heading)))))))
23506 (defvar org-element-greater-elements)
23507 (defun org-down-element ()
23508 "Move to inner element."
23509 (interactive)
23510 (let ((element (org-element-at-point)))
23511 (cond
23512 ((memq (org-element-type element) '(plain-list table))
23513 (goto-char (org-element-property :contents-begin element))
23514 (forward-char))
23515 ((memq (org-element-type element) org-element-greater-elements)
23516 ;; If contents are hidden, first disclose them.
23517 (when (org-element-property :hiddenp element) (org-cycle))
23518 (goto-char (or (org-element-property :contents-begin element)
23519 (user-error "No content for this element"))))
23520 (t (user-error "No inner element")))))
23522 (defun org-drag-element-backward ()
23523 "Move backward element at point."
23524 (interactive)
23525 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23526 (let* ((trail (org-element-at-point 'keep-trail))
23527 (elem (car trail))
23528 (prev-elem (nth 1 trail)))
23529 ;; Error out if no previous element or previous element is
23530 ;; a parent of the current one.
23531 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23532 (user-error "Cannot drag element backward")
23533 (let ((pos (point)))
23534 (org-element-swap-A-B prev-elem elem)
23535 (goto-char (+ (org-element-property :begin prev-elem)
23536 (- pos (org-element-property :begin elem)))))))))
23538 (defun org-drag-element-forward ()
23539 "Move forward element at point."
23540 (interactive)
23541 (let* ((pos (point))
23542 (elem (org-element-at-point)))
23543 (when (= (point-max) (org-element-property :end elem))
23544 (user-error "Cannot drag element forward"))
23545 (goto-char (org-element-property :end elem))
23546 (let ((next-elem (org-element-at-point)))
23547 (when (or (org-element-nested-p elem next-elem)
23548 (and (eq (org-element-type next-elem) 'headline)
23549 (not (eq (org-element-type elem) 'headline))))
23550 (goto-char pos)
23551 (user-error "Cannot drag element forward"))
23552 ;; Compute new position of point: it's shifted by NEXT-ELEM
23553 ;; body's length (without final blanks) and by the length of
23554 ;; blanks between ELEM and NEXT-ELEM.
23555 (let ((size-next (- (save-excursion
23556 (goto-char (org-element-property :end next-elem))
23557 (skip-chars-backward " \r\t\n")
23558 (forward-line)
23559 ;; Small correction if buffer doesn't end
23560 ;; with a newline character.
23561 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23562 (org-element-property :begin next-elem)))
23563 (size-blank (- (org-element-property :end elem)
23564 (save-excursion
23565 (goto-char (org-element-property :end elem))
23566 (skip-chars-backward " \r\t\n")
23567 (forward-line)
23568 (point)))))
23569 (org-element-swap-A-B elem next-elem)
23570 (goto-char (+ pos size-next size-blank))))))
23572 (defun org-drag-line-forward (arg)
23573 "Drag the line at point ARG lines forward."
23574 (interactive "p")
23575 (dotimes (n (abs arg))
23576 (let ((c (current-column)))
23577 (if (< 0 arg)
23578 (progn
23579 (beginning-of-line 2)
23580 (transpose-lines 1)
23581 (beginning-of-line 0))
23582 (transpose-lines 1)
23583 (beginning-of-line -1))
23584 (org-move-to-column c))))
23586 (defun org-drag-line-backward (arg)
23587 "Drag the line at point ARG lines backward."
23588 (interactive "p")
23589 (org-drag-line-forward (- arg)))
23591 (defun org-mark-element ()
23592 "Put point at beginning of this element, mark at end.
23594 Interactively, if this command is repeated or (in Transient Mark
23595 mode) if the mark is active, it marks the next element after the
23596 ones already marked."
23597 (interactive)
23598 (let (deactivate-mark)
23599 (if (and (org-called-interactively-p 'any)
23600 (or (and (eq last-command this-command) (mark t))
23601 (and transient-mark-mode mark-active)))
23602 (set-mark
23603 (save-excursion
23604 (goto-char (mark))
23605 (goto-char (org-element-property :end (org-element-at-point)))))
23606 (let ((element (org-element-at-point)))
23607 (end-of-line)
23608 (push-mark (org-element-property :end element) t t)
23609 (goto-char (org-element-property :begin element))))))
23611 (defun org-narrow-to-element ()
23612 "Narrow buffer to current element."
23613 (interactive)
23614 (let ((elem (org-element-at-point)))
23615 (cond
23616 ((eq (car elem) 'headline)
23617 (narrow-to-region
23618 (org-element-property :begin elem)
23619 (org-element-property :end elem)))
23620 ((memq (car elem) org-element-greater-elements)
23621 (narrow-to-region
23622 (org-element-property :contents-begin elem)
23623 (org-element-property :contents-end elem)))
23625 (narrow-to-region
23626 (org-element-property :begin elem)
23627 (org-element-property :end elem))))))
23629 (defun org-transpose-element ()
23630 "Transpose current and previous elements, keeping blank lines between.
23631 Point is moved after both elements."
23632 (interactive)
23633 (org-skip-whitespace)
23634 (let ((end (org-element-property :end (org-element-at-point))))
23635 (org-drag-element-backward)
23636 (goto-char end)))
23638 (defun org-unindent-buffer ()
23639 "Un-indent the visible part of the buffer.
23640 Relative indentation (between items, inside blocks, etc.) isn't
23641 modified."
23642 (interactive)
23643 (unless (eq major-mode 'org-mode)
23644 (user-error "Cannot un-indent a buffer not in Org mode"))
23645 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23646 unindent-tree ; For byte-compiler.
23647 (unindent-tree
23648 (function
23649 (lambda (contents)
23650 (mapc
23651 (lambda (element)
23652 (if (memq (org-element-type element) '(headline section))
23653 (funcall unindent-tree (org-element-contents element))
23654 (save-excursion
23655 (save-restriction
23656 (narrow-to-region
23657 (org-element-property :begin element)
23658 (org-element-property :end element))
23659 (org-do-remove-indentation)))))
23660 (reverse contents))))))
23661 (funcall unindent-tree (org-element-contents parse-tree))))
23663 (defun org-show-subtree ()
23664 "Show everything after this heading at deeper levels."
23665 (interactive)
23666 (outline-flag-region
23667 (point)
23668 (save-excursion
23669 (org-end-of-subtree t t))
23670 nil))
23672 (defun org-show-entry ()
23673 "Show the body directly following this heading.
23674 Show the heading too, if it is currently invisible."
23675 (interactive)
23676 (save-excursion
23677 (condition-case nil
23678 (progn
23679 (org-back-to-heading t)
23680 (outline-flag-region
23681 (max (point-min) (1- (point)))
23682 (save-excursion
23683 (if (re-search-forward
23684 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23685 (match-beginning 1)
23686 (point-max)))
23687 nil)
23688 (org-cycle-hide-drawers 'children))
23689 (error nil))))
23691 (defun org-make-options-regexp (kwds &optional extra)
23692 "Make a regular expression for keyword lines."
23693 (concat
23694 "^#\\+\\("
23695 (mapconcat 'regexp-quote kwds "\\|")
23696 (if extra (concat "\\|" extra))
23697 "\\):[ \t]*\\(.*\\)"))
23699 ;; Make isearch reveal the necessary context
23700 (defun org-isearch-end ()
23701 "Reveal context after isearch exits."
23702 (when isearch-success ; only if search was successful
23703 (if (featurep 'xemacs)
23704 ;; Under XEmacs, the hook is run in the correct place,
23705 ;; we directly show the context.
23706 (org-show-context 'isearch)
23707 ;; In Emacs the hook runs *before* restoring the overlays.
23708 ;; So we have to use a one-time post-command-hook to do this.
23709 ;; (Emacs 22 has a special variable, see function `org-mode')
23710 (unless (and (boundp 'isearch-mode-end-hook-quit)
23711 isearch-mode-end-hook-quit)
23712 ;; Only when the isearch was not quitted.
23713 (org-add-hook 'post-command-hook 'org-isearch-post-command
23714 'append 'local)))
23715 (org-fix-ellipsis-at-bol)))
23717 (defun org-isearch-post-command ()
23718 "Remove self from hook, and show context."
23719 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23720 (org-show-context 'isearch))
23723 ;;;; Integration with and fixes for other packages
23725 ;;; Imenu support
23727 (defvar org-imenu-markers nil
23728 "All markers currently used by Imenu.")
23729 (make-variable-buffer-local 'org-imenu-markers)
23731 (defun org-imenu-new-marker (&optional pos)
23732 "Return a new marker for use by Imenu, and remember the marker."
23733 (let ((m (make-marker)))
23734 (move-marker m (or pos (point)))
23735 (push m org-imenu-markers)
23738 (defun org-imenu-get-tree ()
23739 "Produce the index for Imenu."
23740 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23741 (setq org-imenu-markers nil)
23742 (let* ((n org-imenu-depth)
23743 (re (concat "^" (org-get-limited-outline-regexp)))
23744 (subs (make-vector (1+ n) nil))
23745 (last-level 0)
23746 m level head0 head)
23747 (save-excursion
23748 (save-restriction
23749 (widen)
23750 (goto-char (point-max))
23751 (while (re-search-backward re nil t)
23752 (setq level (org-reduced-level (funcall outline-level)))
23753 (when (and (<= level n)
23754 (looking-at org-complex-heading-regexp)
23755 (setq head0 (org-match-string-no-properties 4)))
23756 (setq head (org-link-display-format head0)
23757 m (org-imenu-new-marker))
23758 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23759 (if (>= level last-level)
23760 (push (cons head m) (aref subs level))
23761 (push (cons head (aref subs (1+ level))) (aref subs level))
23762 (loop for i from (1+ level) to n do (aset subs i nil)))
23763 (setq last-level level)))))
23764 (aref subs 1)))
23766 (eval-after-load "imenu"
23767 '(progn
23768 (add-hook 'imenu-after-jump-hook
23769 (lambda ()
23770 (if (derived-mode-p 'org-mode)
23771 (org-show-context 'org-goto))))))
23773 (defun org-link-display-format (link)
23774 "Replace a link with its the description.
23775 If there is no description, use the link target."
23776 (save-match-data
23777 (if (string-match org-bracket-link-analytic-regexp link)
23778 (replace-match (if (match-end 5)
23779 (match-string 5 link)
23780 (concat (match-string 1 link)
23781 (match-string 3 link)))
23782 nil t link)
23783 link)))
23785 (defun org-toggle-link-display ()
23786 "Toggle the literal or descriptive display of links."
23787 (interactive)
23788 (if org-descriptive-links
23789 (progn (org-remove-from-invisibility-spec '(org-link))
23790 (org-restart-font-lock)
23791 (setq org-descriptive-links nil))
23792 (progn (add-to-invisibility-spec '(org-link))
23793 (org-restart-font-lock)
23794 (setq org-descriptive-links t))))
23796 ;; Speedbar support
23798 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23799 "Overlay marking the agenda restriction line in speedbar.")
23800 (overlay-put org-speedbar-restriction-lock-overlay
23801 'face 'org-agenda-restriction-lock)
23802 (overlay-put org-speedbar-restriction-lock-overlay
23803 'help-echo "Agendas are currently limited to this item.")
23804 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23806 (defun org-speedbar-set-agenda-restriction ()
23807 "Restrict future agenda commands to the location at point in speedbar.
23808 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23809 (interactive)
23810 (require 'org-agenda)
23811 (let (p m tp np dir txt)
23812 (cond
23813 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23814 'org-imenu t))
23815 (setq m (get-text-property p 'org-imenu-marker))
23816 (with-current-buffer (marker-buffer m)
23817 (goto-char m)
23818 (org-agenda-set-restriction-lock 'subtree)))
23819 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23820 'speedbar-function 'speedbar-find-file))
23821 (setq tp (previous-single-property-change
23822 (1+ p) 'speedbar-function)
23823 np (next-single-property-change
23824 tp 'speedbar-function)
23825 dir (speedbar-line-directory)
23826 txt (buffer-substring-no-properties (or tp (point-min))
23827 (or np (point-max))))
23828 (with-current-buffer (find-file-noselect
23829 (let ((default-directory dir))
23830 (expand-file-name txt)))
23831 (unless (derived-mode-p 'org-mode)
23832 (user-error "Cannot restrict to non-Org-mode file"))
23833 (org-agenda-set-restriction-lock 'file)))
23834 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23835 (move-overlay org-speedbar-restriction-lock-overlay
23836 (point-at-bol) (point-at-eol))
23837 (setq current-prefix-arg nil)
23838 (org-agenda-maybe-redo)))
23840 (defvar speedbar-file-key-map)
23841 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23842 (eval-after-load "speedbar"
23843 '(progn
23844 (speedbar-add-supported-extension ".org")
23845 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23846 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23847 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23848 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23849 (add-hook 'speedbar-visiting-tag-hook
23850 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23852 ;;; Fixes and Hacks for problems with other packages
23854 ;; Make flyspell not check words in links, to not mess up our keymap
23855 (defvar org-element-affiliated-keywords) ; From org-element.el
23856 (defvar org-element-block-name-alist) ; From org-element.el
23857 (defun org-mode-flyspell-verify ()
23858 "Don't let flyspell put overlays at active buttons, or on
23859 {todo,all-time,additional-option-like}-keywords."
23860 (require 'org-element) ; For `org-element-affiliated-keywords'
23861 (let ((pos (max (1- (point)) (point-min)))
23862 (word (thing-at-point 'word)))
23863 (and (not (get-text-property pos 'keymap))
23864 (not (get-text-property pos 'org-no-flyspell))
23865 (not (member word org-todo-keywords-1))
23866 (not (member word org-all-time-keywords))
23867 (not (member word org-options-keywords))
23868 (not (member word (mapcar 'car org-startup-options)))
23869 (not (member-ignore-case word org-element-affiliated-keywords))
23870 (not (member-ignore-case word (org-get-export-keywords)))
23871 (not (member-ignore-case
23872 word (mapcar 'car org-element-block-name-alist)))
23873 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23874 (not (org-in-src-block-p)))))
23876 (defun org-remove-flyspell-overlays-in (beg end)
23877 "Remove flyspell overlays in region."
23878 (and (org-bound-and-true-p flyspell-mode)
23879 (fboundp 'flyspell-delete-region-overlays)
23880 (flyspell-delete-region-overlays beg end))
23881 (add-text-properties beg end '(org-no-flyspell t)))
23883 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23884 (eval-after-load "bookmark"
23885 '(if (boundp 'bookmark-after-jump-hook)
23886 ;; We can use the hook
23887 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23888 ;; Hook not available, use advice
23889 (defadvice bookmark-jump (after org-make-visible activate)
23890 "Make the position visible."
23891 (org-bookmark-jump-unhide))))
23893 ;; Make sure saveplace shows the location if it was hidden
23894 (eval-after-load "saveplace"
23895 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23896 "Make the position visible."
23897 (org-bookmark-jump-unhide)))
23899 ;; Make sure ecb shows the location if it was hidden
23900 (eval-after-load "ecb"
23901 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23902 "Make hierarchy visible when jumping into location from ECB tree buffer."
23903 (if (derived-mode-p 'org-mode)
23904 (org-show-context))))
23906 (defun org-bookmark-jump-unhide ()
23907 "Unhide the current position, to show the bookmark location."
23908 (and (derived-mode-p 'org-mode)
23909 (or (outline-invisible-p)
23910 (save-excursion (goto-char (max (point-min) (1- (point))))
23911 (outline-invisible-p)))
23912 (org-show-context 'bookmark-jump)))
23914 ;; Make session.el ignore our circular variable
23915 (defvar session-globals-exclude)
23916 (eval-after-load "session"
23917 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23919 ;;;; Finish up
23921 (provide 'org)
23923 (run-hooks 'org-load-hook)
23925 ;;; org.el ends here