Remove spurious defvar
[org-mode/org-tableheadings.git] / lisp / org.el
blob4dd62364afbcd6b11db2e3deade7c74be7f35faa
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 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-bound 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 (version1 (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 version1))
313 version1)))
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.
658 If you want to control how Org exports those characters, see
659 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
660 used to be an alias for `org-export-with-sub-superscripts' in
661 Org <8.0, it is not anymore.
663 When this option is turned on, you can use TeX-like syntax for
664 sub- and superscripts within the buffer. Several characters after
665 \"_\" or \"^\" will be considered as a single item - so grouping
666 with {} is normally not needed. For example, the following things
667 will be parsed as single sub- or superscripts:
669 10^24 or 10^tau several digits will be considered 1 item.
670 10^-12 or 10^-tau a leading sign with digits or a word
671 x^2-y^3 will be read as x^2 - y^3, because items are
672 terminated by almost any nonword/nondigit char.
673 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
675 Still, ambiguity is possible. So when in doubt, use {} to enclose
676 the sub/superscript. If you set this variable to the symbol `{}',
677 the braces are *required* in order to trigger interpretations as
678 sub/superscript. This can be helpful in documents that need \"_\"
679 frequently in plain text."
680 :group 'org-startup
681 :version "24.4"
682 :package-version '(Org . "8.0")
683 :type '(choice
684 (const :tag "Always interpret" t)
685 (const :tag "Only with braces" {})
686 (const :tag "Never interpret" nil)))
688 (defcustom org-startup-with-beamer-mode nil
689 "Non-nil means turn on `org-beamer-mode' on startup.
690 This can also be configured on a per-file basis by adding one of
691 the following lines anywhere in the buffer:
693 #+STARTUP: beamer"
694 :group 'org-startup
695 :version "24.1"
696 :type 'boolean)
698 (defcustom org-startup-align-all-tables nil
699 "Non-nil means align all tables when visiting a file.
700 This is useful when the column width in tables is forced with <N> cookies
701 in table fields. Such tables will look correct only after the first re-align.
702 This can also be configured on a per-file basis by adding one of
703 the following lines anywhere in the buffer:
704 #+STARTUP: align
705 #+STARTUP: noalign"
706 :group 'org-startup
707 :type 'boolean)
709 (defcustom org-startup-with-inline-images nil
710 "Non-nil means show inline images when loading a new Org file.
711 This can also be configured on a per-file basis by adding one of
712 the following lines anywhere in the buffer:
713 #+STARTUP: inlineimages
714 #+STARTUP: noinlineimages"
715 :group 'org-startup
716 :version "24.1"
717 :type 'boolean)
719 (defcustom org-startup-with-latex-preview nil
720 "Non-nil means preview LaTeX fragments when loading a new Org file.
722 This can also be configured on a per-file basis by adding one of
723 the following lines anywhere in the buffer:
724 #+STARTUP: latexpreview
725 #+STARTUP: nolatexpreview"
726 :group 'org-startup
727 :version "24.4"
728 :package-version '(Org . "8.0")
729 :type 'boolean)
731 (defcustom org-insert-mode-line-in-empty-file nil
732 "Non-nil means insert the first line setting Org-mode in empty files.
733 When the function `org-mode' is called interactively in an empty file, this
734 normally means that the file name does not automatically trigger Org-mode.
735 To ensure that the file will always be in Org-mode in the future, a
736 line enforcing Org-mode will be inserted into the buffer, if this option
737 has been set."
738 :group 'org-startup
739 :type 'boolean)
741 (defcustom org-replace-disputed-keys nil
742 "Non-nil means use alternative key bindings for some keys.
743 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
744 These keys are also used by other packages like shift-selection-mode'
745 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
746 If you want to use Org-mode together with one of these other modes,
747 or more generally if you would like to move some Org-mode commands to
748 other keys, set this variable and configure the keys with the variable
749 `org-disputed-keys'.
751 This option is only relevant at load-time of Org-mode, and must be set
752 *before* org.el is loaded. Changing it requires a restart of Emacs to
753 become effective."
754 :group 'org-startup
755 :type 'boolean)
757 (defcustom org-use-extra-keys nil
758 "Non-nil means use extra key sequence definitions for certain commands.
759 This happens automatically if you run XEmacs or if `window-system'
760 is nil. This variable lets you do the same manually. You must
761 set it before loading org.
763 Example: on Carbon Emacs 22 running graphically, with an external
764 keyboard on a Powerbook, the default way of setting M-left might
765 not work for either Alt or ESC. Setting this variable will make
766 it work for ESC."
767 :group 'org-startup
768 :type 'boolean)
770 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
772 (defcustom org-disputed-keys
773 '(([(shift up)] . [(meta p)])
774 ([(shift down)] . [(meta n)])
775 ([(shift left)] . [(meta -)])
776 ([(shift right)] . [(meta +)])
777 ([(control shift right)] . [(meta shift +)])
778 ([(control shift left)] . [(meta shift -)]))
779 "Keys for which Org-mode and other modes compete.
780 This is an alist, cars are the default keys, second element specifies
781 the alternative to use when `org-replace-disputed-keys' is t.
783 Keys can be specified in any syntax supported by `define-key'.
784 The value of this option takes effect only at Org-mode's startup,
785 therefore you'll have to restart Emacs to apply it after changing."
786 :group 'org-startup
787 :type 'alist)
789 (defun org-key (key)
790 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
791 Or return the original if not disputed.
792 Also apply the translations defined in `org-xemacs-key-equivalents'."
793 (when org-replace-disputed-keys
794 (let* ((nkey (key-description key))
795 (x (org-find-if (lambda (x)
796 (equal (key-description (car x)) nkey))
797 org-disputed-keys)))
798 (setq key (if x (cdr x) key))))
799 (when (featurep 'xemacs)
800 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
801 key)
803 (defun org-find-if (predicate seq)
804 (catch 'exit
805 (while seq
806 (if (funcall predicate (car seq))
807 (throw 'exit (car seq))
808 (pop seq)))))
810 (defun org-defkey (keymap key def)
811 "Define a key, possibly translated, as returned by `org-key'."
812 (define-key keymap (org-key key) def))
814 (defcustom org-ellipsis nil
815 "The ellipsis to use in the Org-mode outline.
816 When nil, just use the standard three dots.
817 When a string, use that string instead.
818 When a face, use the standard 3 dots, but with the specified face.
819 The change affects only Org-mode (which will then use its own display table).
820 Changing this requires executing `M-x org-mode RET' in a buffer to become
821 effective."
822 :group 'org-startup
823 :type '(choice (const :tag "Default" nil)
824 (face :tag "Face" :value org-warning)
825 (string :tag "String" :value "...#")))
827 (defvar org-display-table nil
828 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
830 (defgroup org-keywords nil
831 "Keywords in Org-mode."
832 :tag "Org Keywords"
833 :group 'org)
835 (defcustom org-deadline-string "DEADLINE:"
836 "String to mark deadline entries.
837 A deadline is this string, followed by a time stamp. Should be a word,
838 terminated by a colon. You can insert a schedule keyword and
839 a timestamp with \\[org-deadline].
840 Changes become only effective after restarting Emacs."
841 :group 'org-keywords
842 :type 'string)
844 (defcustom org-scheduled-string "SCHEDULED:"
845 "String to mark scheduled TODO entries.
846 A schedule is this string, followed by a time stamp. Should be a word,
847 terminated by a colon. You can insert a schedule keyword and
848 a timestamp with \\[org-schedule].
849 Changes become only effective after restarting Emacs."
850 :group 'org-keywords
851 :type 'string)
853 (defcustom org-closed-string "CLOSED:"
854 "String used as the prefix for timestamps logging closing a TODO entry."
855 :group 'org-keywords
856 :type 'string)
858 (defcustom org-clock-string "CLOCK:"
859 "String used as prefix for timestamps clocking work hours on an item."
860 :group 'org-keywords
861 :type 'string)
863 (defcustom org-closed-keep-when-no-todo nil
864 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
865 :group 'org-todo
866 :group 'org-keywords
867 :version "24.4"
868 :package-version '(Org . "8.0")
869 :type 'boolean)
871 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
872 org-scheduled-string "\\|"
873 org-deadline-string "\\|"
874 org-closed-string "\\|"
875 org-clock-string "\\)")
876 "Matches a line with planning or clock info.")
878 (defcustom org-comment-string "COMMENT"
879 "Entries starting with this keyword will never be exported.
880 An entry can be toggled between COMMENT and normal with
881 \\[org-toggle-comment].
882 Changes become only effective after restarting Emacs."
883 :group 'org-keywords
884 :type 'string)
886 (defcustom org-quote-string "QUOTE"
887 "Entries starting with this keyword will be exported in fixed-width font.
888 Quoting applies only to the text in the entry following the headline, and does
889 not extend beyond the next headline, even if that is lower level.
890 An entry can be toggled between QUOTE and normal with
891 \\[org-toggle-fixed-width-section]."
892 :group 'org-keywords
893 :type 'string)
895 (defconst org-repeat-re
896 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
897 "Regular expression for specifying repeated events.
898 After a match, group 1 contains the repeat expression.")
900 (defgroup org-structure nil
901 "Options concerning the general structure of Org-mode files."
902 :tag "Org Structure"
903 :group 'org)
905 (defgroup org-reveal-location nil
906 "Options about how to make context of a location visible."
907 :tag "Org Reveal Location"
908 :group 'org-structure)
910 (defconst org-context-choice
911 '(choice
912 (const :tag "Always" t)
913 (const :tag "Never" nil)
914 (repeat :greedy t :tag "Individual contexts"
915 (cons
916 (choice :tag "Context"
917 (const agenda)
918 (const org-goto)
919 (const occur-tree)
920 (const tags-tree)
921 (const link-search)
922 (const mark-goto)
923 (const bookmark-jump)
924 (const isearch)
925 (const default))
926 (boolean))))
927 "Contexts for the reveal options.")
929 (defcustom org-show-hierarchy-above '((default . t))
930 "Non-nil means show full hierarchy when revealing a location.
931 Org-mode often shows locations in an org-mode file which might have
932 been invisible before. When this is set, the hierarchy of headings
933 above the exposed location is shown.
934 Turning this off for example for sparse trees makes them very compact.
935 Instead of t, this can also be an alist specifying this option for different
936 contexts. Valid contexts are
937 agenda when exposing an entry from the agenda
938 org-goto when using the command `org-goto' on key C-c C-j
939 occur-tree when using the command `org-occur' on key C-c /
940 tags-tree when constructing a sparse tree based on tags matches
941 link-search when exposing search matches associated with a link
942 mark-goto when exposing the jump goal of a mark
943 bookmark-jump when exposing a bookmark location
944 isearch when exiting from an incremental search
945 default default for all contexts not set explicitly"
946 :group 'org-reveal-location
947 :type org-context-choice)
949 (defcustom org-show-following-heading '((default . nil))
950 "Non-nil means show following heading when revealing a location.
951 Org-mode often shows locations in an org-mode file which might have
952 been invisible before. When this is set, the heading following the
953 match is shown.
954 Turning this off for example for sparse trees makes them very compact,
955 but makes it harder to edit the location of the match. In such a case,
956 use the command \\[org-reveal] to show more context.
957 Instead of t, this can also be an alist specifying this option for different
958 contexts. See `org-show-hierarchy-above' for valid contexts."
959 :group 'org-reveal-location
960 :type org-context-choice)
962 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
963 "Non-nil means show all sibling heading when revealing a location.
964 Org-mode often shows locations in an org-mode file which might have
965 been invisible before. When this is set, the sibling of the current entry
966 heading are all made visible. If `org-show-hierarchy-above' is t,
967 the same happens on each level of the hierarchy above the current entry.
969 By default this is on for the isearch context, off for all other contexts.
970 Turning this off for example for sparse trees makes them very compact,
971 but makes it harder to edit the location of the match. In such a case,
972 use the command \\[org-reveal] to show more context.
973 Instead of t, this can also be an alist specifying this option for different
974 contexts. See `org-show-hierarchy-above' for valid contexts."
975 :group 'org-reveal-location
976 :type org-context-choice
977 :version "24.4"
978 :package-version '(Org . "8.0"))
980 (defcustom org-show-entry-below '((default . nil))
981 "Non-nil means show the entry below a headline when revealing a location.
982 Org-mode often shows locations in an org-mode file which might have
983 been invisible before. When this is set, the text below the headline that is
984 exposed is also shown.
986 By default this is off for all contexts.
987 Instead of t, this can also be an alist specifying this option for different
988 contexts. See `org-show-hierarchy-above' for valid contexts."
989 :group 'org-reveal-location
990 :type org-context-choice)
992 (defcustom org-indirect-buffer-display 'other-window
993 "How should indirect tree buffers be displayed?
994 This applies to indirect buffers created with the commands
995 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
996 Valid values are:
997 current-window Display in the current window
998 other-window Just display in another window.
999 dedicated-frame Create one new frame, and re-use it each time.
1000 new-frame Make a new frame each time. Note that in this case
1001 previously-made indirect buffers are kept, and you need to
1002 kill these buffers yourself."
1003 :group 'org-structure
1004 :group 'org-agenda-windows
1005 :type '(choice
1006 (const :tag "In current window" current-window)
1007 (const :tag "In current frame, other window" other-window)
1008 (const :tag "Each time a new frame" new-frame)
1009 (const :tag "One dedicated frame" dedicated-frame)))
1011 (defcustom org-use-speed-commands nil
1012 "Non-nil means activate single letter commands at beginning of a headline.
1013 This may also be a function to test for appropriate locations where speed
1014 commands should be active."
1015 :group 'org-structure
1016 :type '(choice
1017 (const :tag "Never" nil)
1018 (const :tag "At beginning of headline stars" t)
1019 (function)))
1021 (defcustom org-speed-commands-user nil
1022 "Alist of additional speed commands.
1023 This list will be checked before `org-speed-commands-default'
1024 when the variable `org-use-speed-commands' is non-nil
1025 and when the cursor is at the beginning of a headline.
1026 The car if each entry is a string with a single letter, which must
1027 be assigned to `self-insert-command' in the global map.
1028 The cdr is either a command to be called interactively, a function
1029 to be called, or a form to be evaluated.
1030 An entry that is just a list with a single string will be interpreted
1031 as a descriptive headline that will be added when listing the speed
1032 commands in the Help buffer using the `?' speed command."
1033 :group 'org-structure
1034 :type '(repeat :value ("k" . ignore)
1035 (choice :value ("k" . ignore)
1036 (list :tag "Descriptive Headline" (string :tag "Headline"))
1037 (cons :tag "Letter and Command"
1038 (string :tag "Command letter")
1039 (choice
1040 (function)
1041 (sexp))))))
1043 (defcustom org-bookmark-names-plist
1044 '(:last-capture "org-capture-last-stored"
1045 :last-refile "org-refile-last-stored"
1046 :last-capture-marker "org-capture-last-stored-marker")
1047 "Names for bookmarks automatically set by some Org commands.
1048 This can provide strings as names for a number of bookmarks Org sets
1049 automatically. The following keys are currently implemented:
1050 :last-capture
1051 :last-capture-marker
1052 :last-refile
1053 When a key does not show up in the property list, the corresponding bookmark
1054 is not set."
1055 :group 'org-structure
1056 :type 'plist)
1058 (defgroup org-cycle nil
1059 "Options concerning visibility cycling in Org-mode."
1060 :tag "Org Cycle"
1061 :group 'org-structure)
1063 (defcustom org-cycle-skip-children-state-if-no-children t
1064 "Non-nil means skip CHILDREN state in entries that don't have any."
1065 :group 'org-cycle
1066 :type 'boolean)
1068 (defcustom org-cycle-max-level nil
1069 "Maximum level which should still be subject to visibility cycling.
1070 Levels higher than this will, for cycling, be treated as text, not a headline.
1071 When `org-odd-levels-only' is set, a value of N in this variable actually
1072 means 2N-1 stars as the limiting headline.
1073 When nil, cycle all levels.
1074 Note that the limiting level of cycling is also influenced by
1075 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1076 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1077 than its value."
1078 :group 'org-cycle
1079 :type '(choice
1080 (const :tag "No limit" nil)
1081 (integer :tag "Maximum level")))
1083 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1084 "Names of drawers. Drawers are not opened by cycling on the headline above.
1085 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1086 this:
1087 :DRAWERNAME:
1088 .....
1089 :END:
1090 The drawer \"PROPERTIES\" is special for capturing properties through
1091 the property API.
1093 Drawers can be defined on the per-file basis with a line like:
1095 #+DRAWERS: HIDDEN STATE PROPERTIES"
1096 :group 'org-structure
1097 :group 'org-cycle
1098 :type '(repeat (string :tag "Drawer Name")))
1100 (defcustom org-hide-block-startup nil
1101 "Non-nil means entering Org-mode will fold all blocks.
1102 This can also be set in on a per-file basis with
1104 #+STARTUP: hideblocks
1105 #+STARTUP: showblocks"
1106 :group 'org-startup
1107 :group 'org-cycle
1108 :type 'boolean)
1110 (defcustom org-cycle-global-at-bob nil
1111 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1112 This makes it possible to do global cycling without having to use S-TAB or
1113 \\[universal-argument] TAB. For this special case to work, the first line
1114 of the buffer must not be a headline -- it may be empty or some other text.
1115 When used in this way, `org-cycle-hook' is disabled temporarily to make
1116 sure the cursor stays at the beginning of the buffer. When this option is
1117 nil, don't do anything special at the beginning of the buffer."
1118 :group 'org-cycle
1119 :type 'boolean)
1121 (defcustom org-cycle-level-after-item/entry-creation t
1122 "Non-nil means cycle entry level or item indentation in new empty entries.
1124 When the cursor is at the end of an empty headline, i.e., with only stars
1125 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1126 and then all possible ancestor states, before returning to the original state.
1127 This makes data entry extremely fast: M-RET to create a new headline,
1128 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1130 When the cursor is at the end of an empty plain list item, one TAB will
1131 make it a subitem, two or more tabs will back up to make this an item
1132 higher up in the item hierarchy."
1133 :group 'org-cycle
1134 :type 'boolean)
1136 (defcustom org-cycle-emulate-tab t
1137 "Where should `org-cycle' emulate TAB.
1138 nil Never
1139 white Only in completely white lines
1140 whitestart Only at the beginning of lines, before the first non-white char
1141 t Everywhere except in headlines
1142 exc-hl-bol Everywhere except at the start of a headline
1143 If TAB is used in a place where it does not emulate TAB, the current subtree
1144 visibility is cycled."
1145 :group 'org-cycle
1146 :type '(choice (const :tag "Never" nil)
1147 (const :tag "Only in completely white lines" white)
1148 (const :tag "Before first char in a line" whitestart)
1149 (const :tag "Everywhere except in headlines" t)
1150 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1152 (defcustom org-cycle-separator-lines 2
1153 "Number of empty lines needed to keep an empty line between collapsed trees.
1154 If you leave an empty line between the end of a subtree and the following
1155 headline, this empty line is hidden when the subtree is folded.
1156 Org-mode will leave (exactly) one empty line visible if the number of
1157 empty lines is equal or larger to the number given in this variable.
1158 So the default 2 means at least 2 empty lines after the end of a subtree
1159 are needed to produce free space between a collapsed subtree and the
1160 following headline.
1162 If the number is negative, and the number of empty lines is at least -N,
1163 all empty lines are shown.
1165 Special case: when 0, never leave empty lines in collapsed view."
1166 :group 'org-cycle
1167 :type 'integer)
1168 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1170 (defcustom org-pre-cycle-hook nil
1171 "Hook that is run before visibility cycling is happening.
1172 The function(s) in this hook must accept a single argument which indicates
1173 the new state that will be set right after running this hook. The
1174 argument is a symbol. Before a global state change, it can have the values
1175 `overview', `content', or `all'. Before a local state change, it can have
1176 the values `folded', `children', or `subtree'."
1177 :group 'org-cycle
1178 :type 'hook)
1180 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1181 org-cycle-hide-drawers
1182 org-cycle-hide-inline-tasks
1183 org-cycle-show-empty-lines
1184 org-optimize-window-after-visibility-change)
1185 "Hook that is run after `org-cycle' has changed the buffer visibility.
1186 The function(s) in this hook must accept a single argument which indicates
1187 the new state that was set by the most recent `org-cycle' command. The
1188 argument is a symbol. After a global state change, it can have the values
1189 `overview', `contents', or `all'. After a local state change, it can have
1190 the values `folded', `children', or `subtree'."
1191 :group 'org-cycle
1192 :type 'hook)
1194 (defgroup org-edit-structure nil
1195 "Options concerning structure editing in Org-mode."
1196 :tag "Org Edit Structure"
1197 :group 'org-structure)
1199 (defcustom org-odd-levels-only nil
1200 "Non-nil means skip even levels and only use odd levels for the outline.
1201 This has the effect that two stars are being added/taken away in
1202 promotion/demotion commands. It also influences how levels are
1203 handled by the exporters.
1204 Changing it requires restart of `font-lock-mode' to become effective
1205 for fontification also in regions already fontified.
1206 You may also set this on a per-file basis by adding one of the following
1207 lines to the buffer:
1209 #+STARTUP: odd
1210 #+STARTUP: oddeven"
1211 :group 'org-edit-structure
1212 :group 'org-appearance
1213 :type 'boolean)
1215 (defcustom org-adapt-indentation t
1216 "Non-nil means adapt indentation to outline node level.
1218 When this variable is set, Org assumes that you write outlines by
1219 indenting text in each node to align with the headline (after the stars).
1220 The following issues are influenced by this variable:
1222 - When this is set and the *entire* text in an entry is indented, the
1223 indentation is increased by one space in a demotion command, and
1224 decreased by one in a promotion command. If any line in the entry
1225 body starts with text at column 0, indentation is not changed at all.
1227 - Property drawers and planning information is inserted indented when
1228 this variable s set. When nil, they will not be indented.
1230 - TAB indents a line relative to context. The lines below a headline
1231 will be indented when this variable is set.
1233 Note that this is all about true indentation, by adding and removing
1234 space characters. See also `org-indent.el' which does level-dependent
1235 indentation in a virtual way, i.e. at display time in Emacs."
1236 :group 'org-edit-structure
1237 :type 'boolean)
1239 (defcustom org-special-ctrl-a/e nil
1240 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1242 When t, `C-a' will bring back the cursor to the beginning of the
1243 headline text, i.e. after the stars and after a possible TODO
1244 keyword. In an item, this will be the position after bullet and
1245 check-box, if any. When the cursor is already at that position,
1246 another `C-a' will bring it to the beginning of the line.
1248 `C-e' will jump to the end of the headline, ignoring the presence
1249 of tags in the headline. A second `C-e' will then jump to the
1250 true end of the line, after any tags. This also means that, when
1251 this variable is non-nil, `C-e' also will never jump beyond the
1252 end of the heading of a folded section, i.e. not after the
1253 ellipses.
1255 When set to the symbol `reversed', the first `C-a' or `C-e' works
1256 normally, going to the true line boundary first. Only a directly
1257 following, identical keypress will bring the cursor to the
1258 special positions.
1260 This may also be a cons cell where the behavior for `C-a' and
1261 `C-e' is set separately."
1262 :group 'org-edit-structure
1263 :type '(choice
1264 (const :tag "off" nil)
1265 (const :tag "on: after stars/bullet and before tags first" t)
1266 (const :tag "reversed: true line boundary first" reversed)
1267 (cons :tag "Set C-a and C-e separately"
1268 (choice :tag "Special C-a"
1269 (const :tag "off" nil)
1270 (const :tag "on: after stars/bullet first" t)
1271 (const :tag "reversed: before stars/bullet first" reversed))
1272 (choice :tag "Special C-e"
1273 (const :tag "off" nil)
1274 (const :tag "on: before tags first" t)
1275 (const :tag "reversed: after tags first" reversed)))))
1276 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1278 (defcustom org-special-ctrl-k nil
1279 "Non-nil means `C-k' will behave specially in headlines.
1280 When nil, `C-k' will call the default `kill-line' command.
1281 When t, the following will happen while the cursor is in the headline:
1283 - When the cursor is at the beginning of a headline, kill the entire
1284 line and possible the folded subtree below the line.
1285 - When in the middle of the headline text, kill the headline up to the tags.
1286 - When after the headline text, kill the tags."
1287 :group 'org-edit-structure
1288 :type 'boolean)
1290 (defcustom org-ctrl-k-protect-subtree nil
1291 "Non-nil means, do not delete a hidden subtree with C-k.
1292 When set to the symbol `error', simply throw an error when C-k is
1293 used to kill (part-of) a headline that has hidden text behind it.
1294 Any other non-nil value will result in a query to the user, if it is
1295 OK to kill that hidden subtree. When nil, kill without remorse."
1296 :group 'org-edit-structure
1297 :version "24.1"
1298 :type '(choice
1299 (const :tag "Do not protect hidden subtrees" nil)
1300 (const :tag "Protect hidden subtrees with a security query" t)
1301 (const :tag "Never kill a hidden subtree with C-k" error)))
1303 (defcustom org-special-ctrl-o t
1304 "Non-nil means, make `C-o' insert a row in tables."
1305 :group 'org-edit-structure
1306 :type 'boolean)
1308 (defcustom org-catch-invisible-edits nil
1309 "Check if in invisible region before inserting or deleting a character.
1310 Valid values are:
1312 nil Do not check, so just do invisible edits.
1313 error Throw an error and do nothing.
1314 show Make point visible, and do the requested edit.
1315 show-and-error Make point visible, then throw an error and abort the edit.
1316 smart Make point visible, and do insertion/deletion if it is
1317 adjacent to visible text and the change feels predictable.
1318 Never delete a previously invisible character or add in the
1319 middle or right after an invisible region. Basically, this
1320 allows insertion and backward-delete right before ellipses.
1321 FIXME: maybe in this case we should not even show?"
1322 :group 'org-edit-structure
1323 :version "24.1"
1324 :type '(choice
1325 (const :tag "Do not check" nil)
1326 (const :tag "Throw error when trying to edit" error)
1327 (const :tag "Unhide, but do not do the edit" show-and-error)
1328 (const :tag "Show invisible part and do the edit" show)
1329 (const :tag "Be smart and do the right thing" smart)))
1331 (defcustom org-yank-folded-subtrees t
1332 "Non-nil means when yanking subtrees, fold them.
1333 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1334 it starts with a heading and all other headings in it are either children
1335 or siblings, then fold all the subtrees. However, do this only if no
1336 text after the yank would be swallowed into a folded tree by this action."
1337 :group 'org-edit-structure
1338 :type 'boolean)
1340 (defcustom org-yank-adjusted-subtrees nil
1341 "Non-nil means when yanking subtrees, adjust the level.
1342 With this setting, `org-paste-subtree' is used to insert the subtree, see
1343 this function for details."
1344 :group 'org-edit-structure
1345 :type 'boolean)
1347 (defcustom org-M-RET-may-split-line '((default . t))
1348 "Non-nil means M-RET will split the line at the cursor position.
1349 When nil, it will go to the end of the line before making a
1350 new line.
1351 You may also set this option in a different way for different
1352 contexts. Valid contexts are:
1354 headline when creating a new headline
1355 item when creating a new item
1356 table in a table field
1357 default the value to be used for all contexts not explicitly
1358 customized"
1359 :group 'org-structure
1360 :group 'org-table
1361 :type '(choice
1362 (const :tag "Always" t)
1363 (const :tag "Never" nil)
1364 (repeat :greedy t :tag "Individual contexts"
1365 (cons
1366 (choice :tag "Context"
1367 (const headline)
1368 (const item)
1369 (const table)
1370 (const default))
1371 (boolean)))))
1374 (defcustom org-insert-heading-respect-content nil
1375 "Non-nil means insert new headings after the current subtree.
1376 When nil, the new heading is created directly after the current line.
1377 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1378 this variable on for the duration of the command."
1379 :group 'org-structure
1380 :type 'boolean)
1382 (defcustom org-blank-before-new-entry '((heading . auto)
1383 (plain-list-item . auto))
1384 "Should `org-insert-heading' leave a blank line before new heading/item?
1385 The value is an alist, with `heading' and `plain-list-item' as CAR,
1386 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1387 which case Org will look at the surrounding headings/items and try to
1388 make an intelligent decision whether to insert a blank line or not.
1390 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1391 the setting here is ignored and no empty line is inserted to avoid breaking
1392 the list structure."
1393 :group 'org-edit-structure
1394 :type '(list
1395 (cons (const heading)
1396 (choice (const :tag "Never" nil)
1397 (const :tag "Always" t)
1398 (const :tag "Auto" auto)))
1399 (cons (const plain-list-item)
1400 (choice (const :tag "Never" nil)
1401 (const :tag "Always" t)
1402 (const :tag "Auto" auto)))))
1404 (defcustom org-insert-heading-hook nil
1405 "Hook being run after inserting a new heading."
1406 :group 'org-edit-structure
1407 :type 'hook)
1409 (defcustom org-enable-fixed-width-editor t
1410 "Non-nil means lines starting with \":\" are treated as fixed-width.
1411 This currently only means they are never auto-wrapped.
1412 When nil, such lines will be treated like ordinary lines.
1413 See also the QUOTE keyword."
1414 :group 'org-edit-structure
1415 :type 'boolean)
1417 (defcustom org-goto-auto-isearch t
1418 "Non-nil means typing characters in `org-goto' starts incremental search.
1419 When nil, you can use these keybindings to navigate the buffer:
1421 q Quit the org-goto interface
1422 n Go to the next visible heading
1423 p Go to the previous visible heading
1424 f Go one heading forward on same level
1425 b Go one heading backward on same level
1426 u Go one heading up"
1427 :group 'org-edit-structure
1428 :type 'boolean)
1430 (defgroup org-sparse-trees nil
1431 "Options concerning sparse trees in Org-mode."
1432 :tag "Org Sparse Trees"
1433 :group 'org-structure)
1435 (defcustom org-highlight-sparse-tree-matches t
1436 "Non-nil means highlight all matches that define a sparse tree.
1437 The highlights will automatically disappear the next time the buffer is
1438 changed by an edit command."
1439 :group 'org-sparse-trees
1440 :type 'boolean)
1442 (defcustom org-remove-highlights-with-change t
1443 "Non-nil means any change to the buffer will remove temporary highlights.
1444 Such highlights are created by `org-occur' and `org-clock-display'.
1445 When nil, `C-c C-c needs to be used to get rid of the highlights.
1446 The highlights created by `org-preview-latex-fragment' always need
1447 `C-c C-c' to be removed."
1448 :group 'org-sparse-trees
1449 :group 'org-time
1450 :type 'boolean)
1453 (defcustom org-occur-hook '(org-first-headline-recenter)
1454 "Hook that is run after `org-occur' has constructed a sparse tree.
1455 This can be used to recenter the window to show as much of the structure
1456 as possible."
1457 :group 'org-sparse-trees
1458 :type 'hook)
1460 (defgroup org-imenu-and-speedbar nil
1461 "Options concerning imenu and speedbar in Org-mode."
1462 :tag "Org Imenu and Speedbar"
1463 :group 'org-structure)
1465 (defcustom org-imenu-depth 2
1466 "The maximum level for Imenu access to Org-mode headlines.
1467 This also applied for speedbar access."
1468 :group 'org-imenu-and-speedbar
1469 :type 'integer)
1471 (defgroup org-table nil
1472 "Options concerning tables in Org-mode."
1473 :tag "Org Table"
1474 :group 'org)
1476 (defcustom org-enable-table-editor 'optimized
1477 "Non-nil means lines starting with \"|\" are handled by the table editor.
1478 When nil, such lines will be treated like ordinary lines.
1480 When equal to the symbol `optimized', the table editor will be optimized to
1481 do the following:
1482 - Automatic overwrite mode in front of whitespace in table fields.
1483 This makes the structure of the table stay in tact as long as the edited
1484 field does not exceed the column width.
1485 - Minimize the number of realigns. Normally, the table is aligned each time
1486 TAB or RET are pressed to move to another field. With optimization this
1487 happens only if changes to a field might have changed the column width.
1488 Optimization requires replacing the functions `self-insert-command',
1489 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1490 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1491 very good at guessing when a re-align will be necessary, but you can always
1492 force one with \\[org-ctrl-c-ctrl-c].
1494 If you would like to use the optimized version in Org-mode, but the
1495 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1497 This variable can be used to turn on and off the table editor during a session,
1498 but in order to toggle optimization, a restart is required.
1500 See also the variable `org-table-auto-blank-field'."
1501 :group 'org-table
1502 :type '(choice
1503 (const :tag "off" nil)
1504 (const :tag "on" t)
1505 (const :tag "on, optimized" optimized)))
1507 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1508 (version<= emacs-version "24.1"))
1509 "Non-nil means cluster self-insert commands for undo when possible.
1510 If this is set, then, like in the Emacs command loop, 20 consecutive
1511 characters will be undone together.
1512 This is configurable, because there is some impact on typing performance."
1513 :group 'org-table
1514 :type 'boolean)
1516 (defcustom org-table-tab-recognizes-table.el t
1517 "Non-nil means TAB will automatically notice a table.el table.
1518 When it sees such a table, it moves point into it and - if necessary -
1519 calls `table-recognize-table'."
1520 :group 'org-table-editing
1521 :type 'boolean)
1523 (defgroup org-link nil
1524 "Options concerning links in Org-mode."
1525 :tag "Org Link"
1526 :group 'org)
1528 (defvar org-link-abbrev-alist-local nil
1529 "Buffer-local version of `org-link-abbrev-alist', which see.
1530 The value of this is taken from the #+LINK lines.")
1531 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1533 (defcustom org-link-abbrev-alist nil
1534 "Alist of link abbreviations.
1535 The car of each element is a string, to be replaced at the start of a link.
1536 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1537 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1539 [[linkkey:tag][description]]
1541 The 'linkkey' must be a word word, starting with a letter, followed
1542 by letters, numbers, '-' or '_'.
1544 If REPLACE is a string, the tag will simply be appended to create the link.
1545 If the string contains \"%s\", the tag will be inserted there. If the string
1546 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1547 at that point (see the function `url-hexify-string'). If the string contains
1548 the specifier \"%(my-function)\", then the custom function `my-function' will
1549 be invoked: this function takes the tag as its only argument and must return
1550 a string.
1552 REPLACE may also be a function that will be called with the tag as the
1553 only argument to create the link, which should be returned as a string.
1555 See the manual for examples."
1556 :group 'org-link
1557 :type '(repeat
1558 (cons
1559 (string :tag "Protocol")
1560 (choice
1561 (string :tag "Format")
1562 (function)))))
1564 (defcustom org-descriptive-links t
1565 "Non-nil means Org will display descriptive links.
1566 E.g. [[http://orgmode.org][Org website]] will be displayed as
1567 \"Org Website\", hiding the link itself and just displaying its
1568 description. When set to `nil', Org will display the full links
1569 literally.
1571 You can interactively set the value of this variable by calling
1572 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1573 :group 'org-link
1574 :type 'boolean)
1576 (defcustom org-link-file-path-type 'adaptive
1577 "How the path name in file links should be stored.
1578 Valid values are:
1580 relative Relative to the current directory, i.e. the directory of the file
1581 into which the link is being inserted.
1582 absolute Absolute path, if possible with ~ for home directory.
1583 noabbrev Absolute path, no abbreviation of home directory.
1584 adaptive Use relative path for files in the current directory and sub-
1585 directories of it. For other files, use an absolute path."
1586 :group 'org-link
1587 :type '(choice
1588 (const relative)
1589 (const absolute)
1590 (const noabbrev)
1591 (const adaptive)))
1593 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1594 "Types of links that should be activated in Org-mode files.
1595 This is a list of symbols, each leading to the activation of a certain link
1596 type. In principle, it does not hurt to turn on most link types - there may
1597 be a small gain when turning off unused link types. The types are:
1599 bracket The recommended [[link][description]] or [[link]] links with hiding.
1600 angle Links in angular brackets that may contain whitespace like
1601 <bbdb:Carsten Dominik>.
1602 plain Plain links in normal text, no whitespace, like http://google.com.
1603 radio Text that is matched by a radio target, see manual for details.
1604 tag Tag settings in a headline (link to tag search).
1605 date Time stamps (link to calendar).
1606 footnote Footnote labels.
1608 Changing this variable requires a restart of Emacs to become effective."
1609 :group 'org-link
1610 :type '(set :greedy t
1611 (const :tag "Double bracket links" bracket)
1612 (const :tag "Angular bracket links" angle)
1613 (const :tag "Plain text links" plain)
1614 (const :tag "Radio target matches" radio)
1615 (const :tag "Tags" tag)
1616 (const :tag "Timestamps" date)
1617 (const :tag "Footnotes" footnote)))
1619 (defcustom org-make-link-description-function nil
1620 "Function to use for generating link descriptions from links.
1621 When nil, the link location will be used. This function must take
1622 two parameters: the first one is the link, the second one is the
1623 description generated by `org-insert-link'. The function should
1624 return the description to use."
1625 :group 'org-link
1626 :type '(choice (const nil) (function)))
1628 (defgroup org-link-store nil
1629 "Options concerning storing links in Org-mode."
1630 :tag "Org Store Link"
1631 :group 'org-link)
1633 (defcustom org-url-hexify-p t
1634 "When non-nil, hexify URL when creating a link."
1635 :type 'boolean
1636 :version "24.3"
1637 :group 'org-link-store)
1639 (defcustom org-email-link-description-format "Email %c: %.30s"
1640 "Format of the description part of a link to an email or usenet message.
1641 The following %-escapes will be replaced by corresponding information:
1643 %F full \"From\" field
1644 %f name, taken from \"From\" field, address if no name
1645 %T full \"To\" field
1646 %t first name in \"To\" field, address if no name
1647 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1648 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1649 %s subject
1650 %d date
1651 %m message-id.
1653 You may use normal field width specification between the % and the letter.
1654 This is for example useful to limit the length of the subject.
1656 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1657 :group 'org-link-store
1658 :type 'string)
1660 (defcustom org-from-is-user-regexp
1661 (let (r1 r2)
1662 (when (and user-mail-address (not (string= user-mail-address "")))
1663 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1664 (when (and user-full-name (not (string= user-full-name "")))
1665 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1666 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1667 "Regexp matched against the \"From:\" header of an email or usenet message.
1668 It should match if the message is from the user him/herself."
1669 :group 'org-link-store
1670 :type 'regexp)
1672 (defcustom org-context-in-file-links t
1673 "Non-nil means file links from `org-store-link' contain context.
1674 A search string will be added to the file name with :: as separator and
1675 used to find the context when the link is activated by the command
1676 `org-open-at-point'. When this option is t, the entire active region
1677 will be placed in the search string of the file link. If set to a
1678 positive integer, only the first n lines of context will be stored.
1680 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1681 negates this setting for the duration of the command."
1682 :group 'org-link-store
1683 :type '(choice boolean integer))
1685 (defcustom org-keep-stored-link-after-insertion nil
1686 "Non-nil means keep link in list for entire session.
1688 The command `org-store-link' adds a link pointing to the current
1689 location to an internal list. These links accumulate during a session.
1690 The command `org-insert-link' can be used to insert links into any
1691 Org-mode file (offering completion for all stored links). When this
1692 option is nil, every link which has been inserted once using \\[org-insert-link]
1693 will be removed from the list, to make completing the unused links
1694 more efficient."
1695 :group 'org-link-store
1696 :type 'boolean)
1698 (defgroup org-link-follow nil
1699 "Options concerning following links in Org-mode."
1700 :tag "Org Follow Link"
1701 :group 'org-link)
1703 (defcustom org-link-translation-function nil
1704 "Function to translate links with different syntax to Org syntax.
1705 This can be used to translate links created for example by the Planner
1706 or emacs-wiki packages to Org syntax.
1707 The function must accept two parameters, a TYPE containing the link
1708 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1709 which is everything after the link protocol. It should return a cons
1710 with possibly modified values of type and path.
1711 Org contains a function for this, so if you set this variable to
1712 `org-translate-link-from-planner', you should be able follow many
1713 links created by planner."
1714 :group 'org-link-follow
1715 :type '(choice (const nil) (function)))
1717 (defcustom org-follow-link-hook nil
1718 "Hook that is run after a link has been followed."
1719 :group 'org-link-follow
1720 :type 'hook)
1722 (defcustom org-tab-follows-link nil
1723 "Non-nil means on links TAB will follow the link.
1724 Needs to be set before org.el is loaded.
1725 This really should not be used, it does not make sense, and the
1726 implementation is bad."
1727 :group 'org-link-follow
1728 :type 'boolean)
1730 (defcustom org-return-follows-link nil
1731 "Non-nil means on links RET will follow the link.
1732 In tables, the special behavior of RET has precedence."
1733 :group 'org-link-follow
1734 :type 'boolean)
1736 (defcustom org-mouse-1-follows-link
1737 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1738 "Non-nil means mouse-1 on a link will follow the link.
1739 A longer mouse click will still set point. Does not work on XEmacs.
1740 Needs to be set before org.el is loaded."
1741 :group 'org-link-follow
1742 :version "24.4"
1743 :package-version '(Org . "8.3")
1744 :type '(choice
1745 (const :tag "A double click follows the link" double)
1746 (const :tag "Unconditionally follow the link with mouse-1" t)
1747 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1749 (defcustom org-mark-ring-length 4
1750 "Number of different positions to be recorded in the ring.
1751 Changing this requires a restart of Emacs to work correctly."
1752 :group 'org-link-follow
1753 :type 'integer)
1755 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1756 "Non-nil means internal links in Org files must exactly match a headline.
1757 When nil, the link search tries to match a phrase with all words
1758 in the search text."
1759 :group 'org-link-follow
1760 :version "24.1"
1761 :type '(choice
1762 (const :tag "Use fuzzy text search" nil)
1763 (const :tag "Match only exact headline" t)
1764 (const :tag "Match exact headline or query to create it"
1765 query-to-create)))
1767 (defcustom org-link-frame-setup
1768 '((vm . vm-visit-folder-other-frame)
1769 (vm-imap . vm-visit-imap-folder-other-frame)
1770 (gnus . org-gnus-no-new-news)
1771 (file . find-file-other-window)
1772 (wl . wl-other-frame))
1773 "Setup the frame configuration for following links.
1774 When following a link with Emacs, it may often be useful to display
1775 this link in another window or frame. This variable can be used to
1776 set this up for the different types of links.
1777 For VM, use any of
1778 `vm-visit-folder'
1779 `vm-visit-folder-other-window'
1780 `vm-visit-folder-other-frame'
1781 For Gnus, use any of
1782 `gnus'
1783 `gnus-other-frame'
1784 `org-gnus-no-new-news'
1785 For FILE, use any of
1786 `find-file'
1787 `find-file-other-window'
1788 `find-file-other-frame'
1789 For Wanderlust use any of
1790 `wl'
1791 `wl-other-frame'
1792 For the calendar, use the variable `calendar-setup'.
1793 For BBDB, it is currently only possible to display the matches in
1794 another window."
1795 :group 'org-link-follow
1796 :type '(list
1797 (cons (const vm)
1798 (choice
1799 (const vm-visit-folder)
1800 (const vm-visit-folder-other-window)
1801 (const vm-visit-folder-other-frame)))
1802 (cons (const vm-imap)
1803 (choice
1804 (const vm-visit-imap-folder)
1805 (const vm-visit-imap-folder-other-window)
1806 (const vm-visit-imap-folder-other-frame)))
1807 (cons (const gnus)
1808 (choice
1809 (const gnus)
1810 (const gnus-other-frame)
1811 (const org-gnus-no-new-news)))
1812 (cons (const file)
1813 (choice
1814 (const find-file)
1815 (const find-file-other-window)
1816 (const find-file-other-frame)))
1817 (cons (const wl)
1818 (choice
1819 (const wl)
1820 (const wl-other-frame)))))
1822 (defcustom org-display-internal-link-with-indirect-buffer nil
1823 "Non-nil means use indirect buffer to display infile links.
1824 Activating internal links (from one location in a file to another location
1825 in the same file) normally just jumps to the location. When the link is
1826 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1827 is displayed in
1828 another window. When this option is set, the other window actually displays
1829 an indirect buffer clone of the current buffer, to avoid any visibility
1830 changes to the current buffer."
1831 :group 'org-link-follow
1832 :type 'boolean)
1834 (defcustom org-open-non-existing-files nil
1835 "Non-nil means `org-open-file' will open non-existing files.
1836 When nil, an error will be generated.
1837 This variable applies only to external applications because they
1838 might choke on non-existing files. If the link is to a file that
1839 will be opened in Emacs, the variable is ignored."
1840 :group 'org-link-follow
1841 :type 'boolean)
1843 (defcustom org-open-directory-means-index-dot-org nil
1844 "Non-nil means a link to a directory really means to index.org.
1845 When nil, following a directory link will run dired or open a finder/explorer
1846 window on that directory."
1847 :group 'org-link-follow
1848 :type 'boolean)
1850 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1851 "Function and arguments to call for following mailto links.
1852 This is a list with the first element being a Lisp function, and the
1853 remaining elements being arguments to the function. In string arguments,
1854 %a will be replaced by the address, and %s will be replaced by the subject
1855 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1856 :group 'org-link-follow
1857 :type '(choice
1858 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1859 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1860 (const :tag "message-mail" (message-mail "%a" "%s"))
1861 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1863 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1864 "Non-nil means ask for confirmation before executing shell links.
1865 Shell links can be dangerous: just think about a link
1867 [[shell:rm -rf ~/*][Google Search]]
1869 This link would show up in your Org-mode document as \"Google Search\",
1870 but really it would remove your entire home directory.
1871 Therefore we advise against setting this variable to nil.
1872 Just change it to `y-or-n-p' if you want to confirm with a
1873 single keystroke rather than having to type \"yes\"."
1874 :group 'org-link-follow
1875 :type '(choice
1876 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1877 (const :tag "with y-or-n (faster)" y-or-n-p)
1878 (const :tag "no confirmation (dangerous)" nil)))
1879 (put 'org-confirm-shell-link-function
1880 'safe-local-variable
1881 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1883 (defcustom org-confirm-shell-link-not-regexp ""
1884 "A regexp to skip confirmation for shell links."
1885 :group 'org-link-follow
1886 :version "24.1"
1887 :type 'regexp)
1889 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1890 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1891 Elisp links can be dangerous: just think about a link
1893 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1895 This link would show up in your Org-mode document as \"Google Search\",
1896 but really it would remove your entire home directory.
1897 Therefore we advise against setting this variable to nil.
1898 Just change it to `y-or-n-p' if you want to confirm with a
1899 single keystroke rather than having to type \"yes\"."
1900 :group 'org-link-follow
1901 :type '(choice
1902 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1903 (const :tag "with y-or-n (faster)" y-or-n-p)
1904 (const :tag "no confirmation (dangerous)" nil)))
1905 (put 'org-confirm-shell-link-function
1906 'safe-local-variable
1907 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1909 (defcustom org-confirm-elisp-link-not-regexp ""
1910 "A regexp to skip confirmation for Elisp links."
1911 :group 'org-link-follow
1912 :version "24.1"
1913 :type 'regexp)
1915 (defconst org-file-apps-defaults-gnu
1916 '((remote . emacs)
1917 (system . mailcap)
1918 (t . mailcap))
1919 "Default file applications on a UNIX or GNU/Linux system.
1920 See `org-file-apps'.")
1922 (defconst org-file-apps-defaults-macosx
1923 '((remote . emacs)
1924 (t . "open %s")
1925 (system . "open %s")
1926 ("ps.gz" . "gv %s")
1927 ("eps.gz" . "gv %s")
1928 ("dvi" . "xdvi %s")
1929 ("fig" . "xfig %s"))
1930 "Default file applications on a MacOS X system.
1931 The system \"open\" is known as a default, but we use X11 applications
1932 for some files for which the OS does not have a good default.
1933 See `org-file-apps'.")
1935 (defconst org-file-apps-defaults-windowsnt
1936 (list
1937 '(remote . emacs)
1938 (cons t
1939 (list (if (featurep 'xemacs)
1940 'mswindows-shell-execute
1941 'w32-shell-execute)
1942 "open" 'file))
1943 (cons 'system
1944 (list (if (featurep 'xemacs)
1945 'mswindows-shell-execute
1946 'w32-shell-execute)
1947 "open" 'file)))
1948 "Default file applications on a Windows NT system.
1949 The system \"open\" is used for most files.
1950 See `org-file-apps'.")
1952 (defcustom org-file-apps
1953 '((auto-mode . emacs)
1954 ("\\.mm\\'" . default)
1955 ("\\.x?html?\\'" . default)
1956 ("\\.pdf\\'" . default))
1957 "External applications for opening `file:path' items in a document.
1958 Org-mode uses system defaults for different file types, but
1959 you can use this variable to set the application for a given file
1960 extension. The entries in this list are cons cells where the car identifies
1961 files and the cdr the corresponding command. Possible values for the
1962 file identifier are
1963 \"string\" A string as a file identifier can be interpreted in different
1964 ways, depending on its contents:
1966 - Alphanumeric characters only:
1967 Match links with this file extension.
1968 Example: (\"pdf\" . \"evince %s\")
1969 to open PDFs with evince.
1971 - Regular expression: Match links where the
1972 filename matches the regexp. If you want to
1973 use groups here, use shy groups.
1975 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1976 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1977 to open *.html and *.xhtml with firefox.
1979 - Regular expression which contains (non-shy) groups:
1980 Match links where the whole link, including \"::\", and
1981 anything after that, matches the regexp.
1982 In a custom command string, %1, %2, etc. are replaced with
1983 the parts of the link that were matched by the groups.
1984 For backwards compatibility, if a command string is given
1985 that does not use any of the group matches, this case is
1986 handled identically to the second one (i.e. match against
1987 file name only).
1988 In a custom lisp form, you can access the group matches with
1989 (match-string n link).
1991 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1992 to open [[file:document.pdf::5]] with evince at page 5.
1994 `directory' Matches a directory
1995 `remote' Matches a remote file, accessible through tramp or efs.
1996 Remote files most likely should be visited through Emacs
1997 because external applications cannot handle such paths.
1998 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1999 so all files Emacs knows how to handle. Using this with
2000 command `emacs' will open most files in Emacs. Beware that this
2001 will also open html files inside Emacs, unless you add
2002 (\"html\" . default) to the list as well.
2003 t Default for files not matched by any of the other options.
2004 `system' The system command to open files, like `open' on Windows
2005 and Mac OS X, and mailcap under GNU/Linux. This is the command
2006 that will be selected if you call `C-c C-o' with a double
2007 \\[universal-argument] \\[universal-argument] prefix.
2009 Possible values for the command are:
2010 `emacs' The file will be visited by the current Emacs process.
2011 `default' Use the default application for this file type, which is the
2012 association for t in the list, most likely in the system-specific
2013 part.
2014 This can be used to overrule an unwanted setting in the
2015 system-specific variable.
2016 `system' Use the system command for opening files, like \"open\".
2017 This command is specified by the entry whose car is `system'.
2018 Most likely, the system-specific version of this variable
2019 does define this command, but you can overrule/replace it
2020 here.
2021 string A command to be executed by a shell; %s will be replaced
2022 by the path to the file.
2023 sexp A Lisp form which will be evaluated. The file path will
2024 be available in the Lisp variable `file'.
2025 For more examples, see the system specific constants
2026 `org-file-apps-defaults-macosx'
2027 `org-file-apps-defaults-windowsnt'
2028 `org-file-apps-defaults-gnu'."
2029 :group 'org-link-follow
2030 :type '(repeat
2031 (cons (choice :value ""
2032 (string :tag "Extension")
2033 (const :tag "System command to open files" system)
2034 (const :tag "Default for unrecognized files" t)
2035 (const :tag "Remote file" remote)
2036 (const :tag "Links to a directory" directory)
2037 (const :tag "Any files that have Emacs modes"
2038 auto-mode))
2039 (choice :value ""
2040 (const :tag "Visit with Emacs" emacs)
2041 (const :tag "Use default" default)
2042 (const :tag "Use the system command" system)
2043 (string :tag "Command")
2044 (sexp :tag "Lisp form")))))
2046 (defcustom org-doi-server-url "http://dx.doi.org/"
2047 "The URL of the DOI server."
2048 :type 'string
2049 :version "24.3"
2050 :group 'org-link-follow)
2052 (defgroup org-refile nil
2053 "Options concerning refiling entries in Org-mode."
2054 :tag "Org Refile"
2055 :group 'org)
2057 (defcustom org-directory "~/org"
2058 "Directory with org files.
2059 This is just a default location to look for Org files. There is no need
2060 at all to put your files into this directory. It is only used in the
2061 following situations:
2063 1. When a capture template specifies a target file that is not an
2064 absolute path. The path will then be interpreted relative to
2065 `org-directory'
2066 2. When a capture note is filed away in an interactive way (when exiting the
2067 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2068 with `org-directory' as the default path."
2069 :group 'org-refile
2070 :group 'org-capture
2071 :type 'directory)
2073 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2074 "Default target for storing notes.
2075 Used as a fall back file for org-capture.el, for templates that
2076 do not specify a target file."
2077 :group 'org-refile
2078 :group 'org-capture
2079 :type '(choice
2080 (const :tag "Default from remember-data-file" nil)
2081 file))
2083 (defcustom org-goto-interface 'outline
2084 "The default interface to be used for `org-goto'.
2085 Allowed values are:
2086 outline The interface shows an outline of the relevant file
2087 and the correct heading is found by moving through
2088 the outline or by searching with incremental search.
2089 outline-path-completion Headlines in the current buffer are offered via
2090 completion. This is the interface also used by
2091 the refile command."
2092 :group 'org-refile
2093 :type '(choice
2094 (const :tag "Outline" outline)
2095 (const :tag "Outline-path-completion" outline-path-completion)))
2097 (defcustom org-goto-max-level 5
2098 "Maximum target level when running `org-goto' with refile interface."
2099 :group 'org-refile
2100 :type 'integer)
2102 (defcustom org-reverse-note-order nil
2103 "Non-nil means store new notes at the beginning of a file or entry.
2104 When nil, new notes will be filed to the end of a file or entry.
2105 This can also be a list with cons cells of regular expressions that
2106 are matched against file names, and values."
2107 :group 'org-capture
2108 :group 'org-refile
2109 :type '(choice
2110 (const :tag "Reverse always" t)
2111 (const :tag "Reverse never" nil)
2112 (repeat :tag "By file name regexp"
2113 (cons regexp boolean))))
2115 (defcustom org-log-refile nil
2116 "Information to record when a task is refiled.
2118 Possible values are:
2120 nil Don't add anything
2121 time Add a time stamp to the task
2122 note Prompt for a note and add it with template `org-log-note-headings'
2124 This option can also be set with on a per-file-basis with
2126 #+STARTUP: nologrefile
2127 #+STARTUP: logrefile
2128 #+STARTUP: lognoterefile
2130 You can have local logging settings for a subtree by setting the LOGGING
2131 property to one or more of these keywords.
2133 When bulk-refiling from the agenda, the value `note' is forbidden and
2134 will temporarily be changed to `time'."
2135 :group 'org-refile
2136 :group 'org-progress
2137 :version "24.1"
2138 :type '(choice
2139 (const :tag "No logging" nil)
2140 (const :tag "Record timestamp" time)
2141 (const :tag "Record timestamp with note." note)))
2143 (defcustom org-refile-targets nil
2144 "Targets for refiling entries with \\[org-refile].
2145 This is a list of cons cells. Each cell contains:
2146 - a specification of the files to be considered, either a list of files,
2147 or a symbol whose function or variable value will be used to retrieve
2148 a file name or a list of file names. If you use `org-agenda-files' for
2149 that, all agenda files will be scanned for targets. Nil means consider
2150 headings in the current buffer.
2151 - A specification of how to find candidate refile targets. This may be
2152 any of:
2153 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2154 This tag has to be present in all target headlines, inheritance will
2155 not be considered.
2156 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2157 todo keyword.
2158 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2159 headlines that are refiling targets.
2160 - a cons cell (:level . N). Any headline of level N is considered a target.
2161 Note that, when `org-odd-levels-only' is set, level corresponds to
2162 order in hierarchy, not to the number of stars.
2163 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2164 Note that, when `org-odd-levels-only' is set, level corresponds to
2165 order in hierarchy, not to the number of stars.
2167 Each element of this list generates a set of possible targets.
2168 The union of these sets is presented (with completion) to
2169 the user by `org-refile'.
2171 You can set the variable `org-refile-target-verify-function' to a function
2172 to verify each headline found by the simple criteria above.
2174 When this variable is nil, all top-level headlines in the current buffer
2175 are used, equivalent to the value `((nil . (:level . 1))'."
2176 :group 'org-refile
2177 :type '(repeat
2178 (cons
2179 (choice :value org-agenda-files
2180 (const :tag "All agenda files" org-agenda-files)
2181 (const :tag "Current buffer" nil)
2182 (function) (variable) (file))
2183 (choice :tag "Identify target headline by"
2184 (cons :tag "Specific tag" (const :value :tag) (string))
2185 (cons :tag "TODO keyword" (const :value :todo) (string))
2186 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2187 (cons :tag "Level number" (const :value :level) (integer))
2188 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2190 (defcustom org-refile-target-verify-function nil
2191 "Function to verify if the headline at point should be a refile target.
2192 The function will be called without arguments, with point at the
2193 beginning of the headline. It should return t and leave point
2194 where it is if the headline is a valid target for refiling.
2196 If the target should not be selected, the function must return nil.
2197 In addition to this, it may move point to a place from where the search
2198 should be continued. For example, the function may decide that the entire
2199 subtree of the current entry should be excluded and move point to the end
2200 of the subtree."
2201 :group 'org-refile
2202 :type '(choice
2203 (const nil)
2204 (function)))
2206 (defcustom org-refile-use-cache nil
2207 "Non-nil means cache refile targets to speed up the process.
2208 The cache for a particular file will be updated automatically when
2209 the buffer has been killed, or when any of the marker used for flagging
2210 refile targets no longer points at a live buffer.
2211 If you have added new entries to a buffer that might themselves be targets,
2212 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2213 find that easier, `C-u C-u C-u C-c C-w'."
2214 :group 'org-refile
2215 :version "24.1"
2216 :type 'boolean)
2218 (defcustom org-refile-use-outline-path nil
2219 "Non-nil means provide refile targets as paths.
2220 So a level 3 headline will be available as level1/level2/level3.
2222 When the value is `file', also include the file name (without directory)
2223 into the path. In this case, you can also stop the completion after
2224 the file name, to get entries inserted as top level in the file.
2226 When `full-file-path', include the full file path."
2227 :group 'org-refile
2228 :type '(choice
2229 (const :tag "Not" nil)
2230 (const :tag "Yes" t)
2231 (const :tag "Start with file name" file)
2232 (const :tag "Start with full file path" full-file-path)))
2234 (defcustom org-outline-path-complete-in-steps t
2235 "Non-nil means complete the outline path in hierarchical steps.
2236 When Org-mode uses the refile interface to select an outline path
2237 \(see variable `org-refile-use-outline-path'), the completion of
2238 the path can be done is a single go, or if can be done in steps down
2239 the headline hierarchy. Going in steps is probably the best if you
2240 do not use a special completion package like `ido' or `icicles'.
2241 However, when using these packages, going in one step can be very
2242 fast, while still showing the whole path to the entry."
2243 :group 'org-refile
2244 :type 'boolean)
2246 (defcustom org-refile-allow-creating-parent-nodes nil
2247 "Non-nil means allow to create new nodes as refile targets.
2248 New nodes are then created by adding \"/new node name\" to the completion
2249 of an existing node. When the value of this variable is `confirm',
2250 new node creation must be confirmed by the user (recommended).
2251 When nil, the completion must match an existing entry.
2253 Note that, if the new heading is not seen by the criteria
2254 listed in `org-refile-targets', multiple instances of the same
2255 heading would be created by trying again to file under the new
2256 heading."
2257 :group 'org-refile
2258 :type '(choice
2259 (const :tag "Never" nil)
2260 (const :tag "Always" t)
2261 (const :tag "Prompt for confirmation" confirm)))
2263 (defcustom org-refile-active-region-within-subtree nil
2264 "Non-nil means also refile active region within a subtree.
2266 By default `org-refile' doesn't allow refiling regions if they
2267 don't contain a set of subtrees, but it might be convenient to
2268 do so sometimes: in that case, the first line of the region is
2269 converted to a headline before refiling."
2270 :group 'org-refile
2271 :version "24.1"
2272 :type 'boolean)
2274 (defgroup org-todo nil
2275 "Options concerning TODO items in Org-mode."
2276 :tag "Org TODO"
2277 :group 'org)
2279 (defgroup org-progress nil
2280 "Options concerning Progress logging in Org-mode."
2281 :tag "Org Progress"
2282 :group 'org-time)
2284 (defvar org-todo-interpretation-widgets
2285 '((:tag "Sequence (cycling hits every state)" sequence)
2286 (:tag "Type (cycling directly to DONE)" type))
2287 "The available interpretation symbols for customizing `org-todo-keywords'.
2288 Interested libraries should add to this list.")
2290 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2291 "List of TODO entry keyword sequences and their interpretation.
2292 \\<org-mode-map>This is a list of sequences.
2294 Each sequence starts with a symbol, either `sequence' or `type',
2295 indicating if the keywords should be interpreted as a sequence of
2296 action steps, or as different types of TODO items. The first
2297 keywords are states requiring action - these states will select a headline
2298 for inclusion into the global TODO list Org-mode produces. If one of
2299 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2300 signify that no further action is necessary. If \"|\" is not found,
2301 the last keyword is treated as the only DONE state of the sequence.
2303 The command \\[org-todo] cycles an entry through these states, and one
2304 additional state where no keyword is present. For details about this
2305 cycling, see the manual.
2307 TODO keywords and interpretation can also be set on a per-file basis with
2308 the special #+SEQ_TODO and #+TYP_TODO lines.
2310 Each keyword can optionally specify a character for fast state selection
2311 \(in combination with the variable `org-use-fast-todo-selection')
2312 and specifiers for state change logging, using the same syntax that
2313 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2314 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2315 indicates to record a time stamp each time this state is selected.
2317 Each keyword may also specify if a timestamp or a note should be
2318 recorded when entering or leaving the state, by adding additional
2319 characters in the parenthesis after the keyword. This looks like this:
2320 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2321 record only the time of the state change. With X and Y being either
2322 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2323 Y when leaving the state if and only if the *target* state does not
2324 define X. You may omit any of the fast-selection key or X or /Y,
2325 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2327 For backward compatibility, this variable may also be just a list
2328 of keywords. In this case the interpretation (sequence or type) will be
2329 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2330 :group 'org-todo
2331 :group 'org-keywords
2332 :type '(choice
2333 (repeat :tag "Old syntax, just keywords"
2334 (string :tag "Keyword"))
2335 (repeat :tag "New syntax"
2336 (cons
2337 (choice
2338 :tag "Interpretation"
2339 ;;Quick and dirty way to see
2340 ;;`org-todo-interpretations'. This takes the
2341 ;;place of item arguments
2342 :convert-widget
2343 (lambda (widget)
2344 (widget-put widget
2345 :args (mapcar
2346 #'(lambda (x)
2347 (widget-convert
2348 (cons 'const x)))
2349 org-todo-interpretation-widgets))
2350 widget))
2351 (repeat
2352 (string :tag "Keyword"))))))
2354 (defvar org-todo-keywords-1 nil
2355 "All TODO and DONE keywords active in a buffer.")
2356 (make-variable-buffer-local 'org-todo-keywords-1)
2357 (defvar org-todo-keywords-for-agenda nil)
2358 (defvar org-done-keywords-for-agenda nil)
2359 (defvar org-drawers-for-agenda nil)
2360 (defvar org-todo-keyword-alist-for-agenda nil)
2361 (defvar org-tag-alist-for-agenda nil
2362 "Alist of all tags from all agenda files.")
2363 (defvar org-tag-groups-alist-for-agenda nil
2364 "Alist of all groups tags from all current agenda files.")
2365 (defvar org-tag-groups-alist nil)
2366 (make-variable-buffer-local 'org-tag-groups-alist)
2367 (defvar org-agenda-contributing-files nil)
2368 (defvar org-not-done-keywords nil)
2369 (make-variable-buffer-local 'org-not-done-keywords)
2370 (defvar org-done-keywords nil)
2371 (make-variable-buffer-local 'org-done-keywords)
2372 (defvar org-todo-heads nil)
2373 (make-variable-buffer-local 'org-todo-heads)
2374 (defvar org-todo-sets nil)
2375 (make-variable-buffer-local 'org-todo-sets)
2376 (defvar org-todo-log-states nil)
2377 (make-variable-buffer-local 'org-todo-log-states)
2378 (defvar org-todo-kwd-alist nil)
2379 (make-variable-buffer-local 'org-todo-kwd-alist)
2380 (defvar org-todo-key-alist nil)
2381 (make-variable-buffer-local 'org-todo-key-alist)
2382 (defvar org-todo-key-trigger nil)
2383 (make-variable-buffer-local 'org-todo-key-trigger)
2385 (defcustom org-todo-interpretation 'sequence
2386 "Controls how TODO keywords are interpreted.
2387 This variable is in principle obsolete and is only used for
2388 backward compatibility, if the interpretation of todo keywords is
2389 not given already in `org-todo-keywords'. See that variable for
2390 more information."
2391 :group 'org-todo
2392 :group 'org-keywords
2393 :type '(choice (const sequence)
2394 (const type)))
2396 (defcustom org-use-fast-todo-selection t
2397 "Non-nil means use the fast todo selection scheme with C-c C-t.
2398 This variable describes if and under what circumstances the cycling
2399 mechanism for TODO keywords will be replaced by a single-key, direct
2400 selection scheme.
2402 When nil, fast selection is never used.
2404 When the symbol `prefix', it will be used when `org-todo' is called
2405 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2406 `C-u t' in an agenda buffer.
2408 When t, fast selection is used by default. In this case, the prefix
2409 argument forces cycling instead.
2411 In all cases, the special interface is only used if access keys have
2412 actually been assigned by the user, i.e. if keywords in the configuration
2413 are followed by a letter in parenthesis, like TODO(t)."
2414 :group 'org-todo
2415 :type '(choice
2416 (const :tag "Never" nil)
2417 (const :tag "By default" t)
2418 (const :tag "Only with C-u C-c C-t" prefix)))
2420 (defcustom org-provide-todo-statistics t
2421 "Non-nil means update todo statistics after insert and toggle.
2422 ALL-HEADLINES means update todo statistics by including headlines
2423 with no TODO keyword as well, counting them as not done.
2424 A list of TODO keywords means the same, but skip keywords that are
2425 not in this list.
2427 When this is set, todo statistics is updated in the parent of the
2428 current entry each time a todo state is changed."
2429 :group 'org-todo
2430 :type '(choice
2431 (const :tag "Yes, only for TODO entries" t)
2432 (const :tag "Yes, including all entries" all-headlines)
2433 (repeat :tag "Yes, for TODOs in this list"
2434 (string :tag "TODO keyword"))
2435 (other :tag "No TODO statistics" nil)))
2437 (defcustom org-hierarchical-todo-statistics t
2438 "Non-nil means TODO statistics covers just direct children.
2439 When nil, all entries in the subtree are considered.
2440 This has only an effect if `org-provide-todo-statistics' is set.
2441 To set this to nil for only a single subtree, use a COOKIE_DATA
2442 property and include the word \"recursive\" into the value."
2443 :group 'org-todo
2444 :type 'boolean)
2446 (defcustom org-after-todo-state-change-hook nil
2447 "Hook which is run after the state of a TODO item was changed.
2448 The new state (a string with a TODO keyword, or nil) is available in the
2449 Lisp variable `org-state'."
2450 :group 'org-todo
2451 :type 'hook)
2453 (defvar org-blocker-hook nil
2454 "Hook for functions that are allowed to block a state change.
2456 Functions in this hook should not modify the buffer.
2457 Each function gets as its single argument a property list,
2458 see `org-trigger-hook' for more information about this list.
2460 If any of the functions in this hook returns nil, the state change
2461 is blocked.")
2463 (defvar org-trigger-hook nil
2464 "Hook for functions that are triggered by a state change.
2466 Each function gets as its single argument a property list with at
2467 least the following elements:
2469 (:type type-of-change :position pos-at-entry-start
2470 :from old-state :to new-state)
2472 Depending on the type, more properties may be present.
2474 This mechanism is currently implemented for:
2476 TODO state changes
2477 ------------------
2478 :type todo-state-change
2479 :from previous state (keyword as a string), or nil, or a symbol
2480 'todo' or 'done', to indicate the general type of state.
2481 :to new state, like in :from")
2483 (defcustom org-enforce-todo-dependencies nil
2484 "Non-nil means undone TODO entries will block switching the parent to DONE.
2485 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2486 be blocked if any prior sibling is not yet done.
2487 Finally, if the parent is blocked because of ordered siblings of its own,
2488 the child will also be blocked."
2489 :set (lambda (var val)
2490 (set var val)
2491 (if val
2492 (add-hook 'org-blocker-hook
2493 'org-block-todo-from-children-or-siblings-or-parent)
2494 (remove-hook 'org-blocker-hook
2495 'org-block-todo-from-children-or-siblings-or-parent)))
2496 :group 'org-todo
2497 :type 'boolean)
2499 (defcustom org-enforce-todo-checkbox-dependencies nil
2500 "Non-nil means unchecked boxes will block switching the parent to DONE.
2501 When this is nil, checkboxes have no influence on switching TODO states.
2502 When non-nil, you first need to check off all check boxes before the TODO
2503 entry can be switched to DONE.
2504 This variable needs to be set before org.el is loaded, and you need to
2505 restart Emacs after a change to make the change effective. The only way
2506 to change is while Emacs is running is through the customize interface."
2507 :set (lambda (var val)
2508 (set var val)
2509 (if val
2510 (add-hook 'org-blocker-hook
2511 'org-block-todo-from-checkboxes)
2512 (remove-hook 'org-blocker-hook
2513 'org-block-todo-from-checkboxes)))
2514 :group 'org-todo
2515 :type 'boolean)
2517 (defcustom org-treat-insert-todo-heading-as-state-change nil
2518 "Non-nil means inserting a TODO heading is treated as state change.
2519 So when the command \\[org-insert-todo-heading] is used, state change
2520 logging will apply if appropriate. When nil, the new TODO item will
2521 be inserted directly, and no logging will take place."
2522 :group 'org-todo
2523 :type 'boolean)
2525 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2526 "Non-nil means switching TODO states with S-cursor counts as state change.
2527 This is the default behavior. However, setting this to nil allows a
2528 convenient way to select a TODO state and bypass any logging associated
2529 with that."
2530 :group 'org-todo
2531 :type 'boolean)
2533 (defcustom org-todo-state-tags-triggers nil
2534 "Tag changes that should be triggered by TODO state changes.
2535 This is a list. Each entry is
2537 (state-change (tag . flag) .......)
2539 State-change can be a string with a state, and empty string to indicate the
2540 state that has no TODO keyword, or it can be one of the symbols `todo'
2541 or `done', meaning any not-done or done state, respectively."
2542 :group 'org-todo
2543 :group 'org-tags
2544 :type '(repeat
2545 (cons (choice :tag "When changing to"
2546 (const :tag "Not-done state" todo)
2547 (const :tag "Done state" done)
2548 (string :tag "State"))
2549 (repeat
2550 (cons :tag "Tag action"
2551 (string :tag "Tag")
2552 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2554 (defcustom org-log-done nil
2555 "Information to record when a task moves to the DONE state.
2557 Possible values are:
2559 nil Don't add anything, just change the keyword
2560 time Add a time stamp to the task
2561 note Prompt for a note and add it with template `org-log-note-headings'
2563 This option can also be set with on a per-file-basis with
2565 #+STARTUP: nologdone
2566 #+STARTUP: logdone
2567 #+STARTUP: lognotedone
2569 You can have local logging settings for a subtree by setting the LOGGING
2570 property to one or more of these keywords."
2571 :group 'org-todo
2572 :group 'org-progress
2573 :type '(choice
2574 (const :tag "No logging" nil)
2575 (const :tag "Record CLOSED timestamp" time)
2576 (const :tag "Record CLOSED timestamp with note." note)))
2578 ;; Normalize old uses of org-log-done.
2579 (cond
2580 ((eq org-log-done t) (setq org-log-done 'time))
2581 ((and (listp org-log-done) (memq 'done org-log-done))
2582 (setq org-log-done 'note)))
2584 (defcustom org-log-reschedule nil
2585 "Information to record when the scheduling date of a tasks is modified.
2587 Possible values are:
2589 nil Don't add anything, just change the date
2590 time Add a time stamp to the task
2591 note Prompt for a note and add it with template `org-log-note-headings'
2593 This option can also be set with on a per-file-basis with
2595 #+STARTUP: nologreschedule
2596 #+STARTUP: logreschedule
2597 #+STARTUP: lognotereschedule"
2598 :group 'org-todo
2599 :group 'org-progress
2600 :type '(choice
2601 (const :tag "No logging" nil)
2602 (const :tag "Record timestamp" time)
2603 (const :tag "Record timestamp with note." note)))
2605 (defcustom org-log-redeadline nil
2606 "Information to record when the deadline date of a tasks is modified.
2608 Possible values are:
2610 nil Don't add anything, just change the date
2611 time Add a time stamp to the task
2612 note Prompt for a note and add it with template `org-log-note-headings'
2614 This option can also be set with on a per-file-basis with
2616 #+STARTUP: nologredeadline
2617 #+STARTUP: logredeadline
2618 #+STARTUP: lognoteredeadline
2620 You can have local logging settings for a subtree by setting the LOGGING
2621 property to one or more of these keywords."
2622 :group 'org-todo
2623 :group 'org-progress
2624 :type '(choice
2625 (const :tag "No logging" nil)
2626 (const :tag "Record timestamp" time)
2627 (const :tag "Record timestamp with note." note)))
2629 (defcustom org-log-note-clock-out nil
2630 "Non-nil means record a note when clocking out of an item.
2631 This can also be configured on a per-file basis by adding one of
2632 the following lines anywhere in the buffer:
2634 #+STARTUP: lognoteclock-out
2635 #+STARTUP: nolognoteclock-out"
2636 :group 'org-todo
2637 :group 'org-progress
2638 :type 'boolean)
2640 (defcustom org-log-done-with-time t
2641 "Non-nil means the CLOSED time stamp will contain date and time.
2642 When nil, only the date will be recorded."
2643 :group 'org-progress
2644 :type 'boolean)
2646 (defcustom org-log-note-headings
2647 '((done . "CLOSING NOTE %t")
2648 (state . "State %-12s from %-12S %t")
2649 (note . "Note taken on %t")
2650 (reschedule . "Rescheduled from %S on %t")
2651 (delschedule . "Not scheduled, was %S on %t")
2652 (redeadline . "New deadline from %S on %t")
2653 (deldeadline . "Removed deadline, was %S on %t")
2654 (refile . "Refiled on %t")
2655 (clock-out . ""))
2656 "Headings for notes added to entries.
2657 The value is an alist, with the car being a symbol indicating the note
2658 context, and the cdr is the heading to be used. The heading may also be the
2659 empty string.
2660 %t in the heading will be replaced by a time stamp.
2661 %T will be an active time stamp instead the default inactive one
2662 %d will be replaced by a short-format time stamp.
2663 %D will be replaced by an active short-format time stamp.
2664 %s will be replaced by the new TODO state, in double quotes.
2665 %S will be replaced by the old TODO state, in double quotes.
2666 %u will be replaced by the user name.
2667 %U will be replaced by the full user name.
2669 In fact, it is not a good idea to change the `state' entry, because
2670 agenda log mode depends on the format of these entries."
2671 :group 'org-todo
2672 :group 'org-progress
2673 :type '(list :greedy t
2674 (cons (const :tag "Heading when closing an item" done) string)
2675 (cons (const :tag
2676 "Heading when changing todo state (todo sequence only)"
2677 state) string)
2678 (cons (const :tag "Heading when just taking a note" note) string)
2679 (cons (const :tag "Heading when rescheduling" reschedule) string)
2680 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2681 (cons (const :tag "Heading when changing deadline" redeadline) string)
2682 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2683 (cons (const :tag "Heading when refiling" refile) string)
2684 (cons (const :tag "Heading when clocking out" clock-out) string)))
2686 (unless (assq 'note org-log-note-headings)
2687 (push '(note . "%t") org-log-note-headings))
2689 (defcustom org-log-into-drawer nil
2690 "Non-nil means insert state change notes and time stamps into a drawer.
2691 When nil, state changes notes will be inserted after the headline and
2692 any scheduling and clock lines, but not inside a drawer.
2694 The value of this variable should be the name of the drawer to use.
2695 LOGBOOK is proposed as the default drawer for this purpose, you can
2696 also set this to a string to define the drawer of your choice.
2698 A value of t is also allowed, representing \"LOGBOOK\".
2700 A value of t or nil can also be set with on a per-file-basis with
2702 #+STARTUP: logdrawer
2703 #+STARTUP: nologdrawer
2705 If this variable is set, `org-log-state-notes-insert-after-drawers'
2706 will be ignored.
2708 You can set the property LOG_INTO_DRAWER to overrule this setting for
2709 a subtree."
2710 :group 'org-todo
2711 :group 'org-progress
2712 :type '(choice
2713 (const :tag "Not into a drawer" nil)
2714 (const :tag "LOGBOOK" t)
2715 (string :tag "Other")))
2717 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2719 (defun org-log-into-drawer ()
2720 "Return the value of `org-log-into-drawer', but let properties overrule.
2721 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2722 used instead of the default value."
2723 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2724 (cond
2725 ((not p) org-log-into-drawer)
2726 ((equal p "nil") nil)
2727 ((equal p "t") "LOGBOOK")
2728 (t p))))
2730 (defcustom org-log-state-notes-insert-after-drawers nil
2731 "Non-nil means insert state change notes after any drawers in entry.
2732 Only the drawers that *immediately* follow the headline and the
2733 deadline/scheduled line are skipped.
2734 When nil, insert notes right after the heading and perhaps the line
2735 with deadline/scheduling if present.
2737 This variable will have no effect if `org-log-into-drawer' is
2738 set."
2739 :group 'org-todo
2740 :group 'org-progress
2741 :type 'boolean)
2743 (defcustom org-log-states-order-reversed t
2744 "Non-nil means the latest state note will be directly after heading.
2745 When nil, the state change notes will be ordered according to time.
2747 This option can also be set with on a per-file-basis with
2749 #+STARTUP: logstatesreversed
2750 #+STARTUP: nologstatesreversed"
2751 :group 'org-todo
2752 :group 'org-progress
2753 :type 'boolean)
2755 (defcustom org-todo-repeat-to-state nil
2756 "The TODO state to which a repeater should return the repeating task.
2757 By default this is the first task in a TODO sequence, or the previous state
2758 in a TODO_TYP set. But you can specify another task here.
2759 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2760 :group 'org-todo
2761 :version "24.1"
2762 :type '(choice (const :tag "Head of sequence" nil)
2763 (string :tag "Specific state")))
2765 (defcustom org-log-repeat 'time
2766 "Non-nil means record moving through the DONE state when triggering repeat.
2767 An auto-repeating task is immediately switched back to TODO when
2768 marked DONE. If you are not logging state changes (by adding \"@\"
2769 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2770 record a closing note, there will be no record of the task moving
2771 through DONE. This variable forces taking a note anyway.
2773 nil Don't force a record
2774 time Record a time stamp
2775 note Prompt for a note and add it with template `org-log-note-headings'
2777 This option can also be set with on a per-file-basis with
2779 #+STARTUP: nologrepeat
2780 #+STARTUP: logrepeat
2781 #+STARTUP: lognoterepeat
2783 You can have local logging settings for a subtree by setting the LOGGING
2784 property to one or more of these keywords."
2785 :group 'org-todo
2786 :group 'org-progress
2787 :type '(choice
2788 (const :tag "Don't force a record" nil)
2789 (const :tag "Force recording the DONE state" time)
2790 (const :tag "Force recording a note with the DONE state" note)))
2793 (defgroup org-priorities nil
2794 "Priorities in Org-mode."
2795 :tag "Org Priorities"
2796 :group 'org-todo)
2798 (defcustom org-enable-priority-commands t
2799 "Non-nil means priority commands are active.
2800 When nil, these commands will be disabled, so that you never accidentally
2801 set a priority."
2802 :group 'org-priorities
2803 :type 'boolean)
2805 (defcustom org-highest-priority ?A
2806 "The highest priority of TODO items. A character like ?A, ?B etc.
2807 Must have a smaller ASCII number than `org-lowest-priority'."
2808 :group 'org-priorities
2809 :type 'character)
2811 (defcustom org-lowest-priority ?C
2812 "The lowest priority of TODO items. A character like ?A, ?B etc.
2813 Must have a larger ASCII number than `org-highest-priority'."
2814 :group 'org-priorities
2815 :type 'character)
2817 (defcustom org-default-priority ?B
2818 "The default priority of TODO items.
2819 This is the priority an item gets if no explicit priority is given.
2820 When starting to cycle on an empty priority the first step in the cycle
2821 depends on `org-priority-start-cycle-with-default'. The resulting first
2822 step priority must not exceed the range from `org-highest-priority' to
2823 `org-lowest-priority' which means that `org-default-priority' has to be
2824 in this range exclusive or inclusive the range boundaries. Else the
2825 first step refuses to set the default and the second will fall back
2826 to (depending on the command used) the highest or lowest priority."
2827 :group 'org-priorities
2828 :type 'character)
2830 (defcustom org-priority-start-cycle-with-default t
2831 "Non-nil means start with default priority when starting to cycle.
2832 When this is nil, the first step in the cycle will be (depending on the
2833 command used) one higher or lower than the default priority.
2834 See also `org-default-priority'."
2835 :group 'org-priorities
2836 :type 'boolean)
2838 (defcustom org-get-priority-function nil
2839 "Function to extract the priority from a string.
2840 The string is normally the headline. If this is nil Org computes the
2841 priority from the priority cookie like [#A] in the headline. It returns
2842 an integer, increasing by 1000 for each priority level.
2843 The user can set a different function here, which should take a string
2844 as an argument and return the numeric priority."
2845 :group 'org-priorities
2846 :version "24.1"
2847 :type '(choice
2848 (const nil)
2849 (function)))
2851 (defgroup org-time nil
2852 "Options concerning time stamps and deadlines in Org-mode."
2853 :tag "Org Time"
2854 :group 'org)
2856 (defcustom org-insert-labeled-timestamps-at-point nil
2857 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2858 When nil, these labeled time stamps are forces into the second line of an
2859 entry, just after the headline. When scheduling from the global TODO list,
2860 the time stamp will always be forced into the second line."
2861 :group 'org-time
2862 :type 'boolean)
2864 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2865 "Formats for `format-time-string' which are used for time stamps.
2866 It is not recommended to change this constant.")
2868 (defcustom org-time-stamp-rounding-minutes '(0 5)
2869 "Number of minutes to round time stamps to.
2870 These are two values, the first applies when first creating a time stamp.
2871 The second applies when changing it with the commands `S-up' and `S-down'.
2872 When changing the time stamp, this means that it will change in steps
2873 of N minutes, as given by the second value.
2875 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2876 numbers should be factors of 60, so for example 5, 10, 15.
2878 When this is larger than 1, you can still force an exact time stamp by using
2879 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2880 and by using a prefix arg to `S-up/down' to specify the exact number
2881 of minutes to shift."
2882 :group 'org-time
2883 :get #'(lambda (var) ; Make sure both elements are there
2884 (if (integerp (default-value var))
2885 (list (default-value var) 5)
2886 (default-value var)))
2887 :type '(list
2888 (integer :tag "when inserting times")
2889 (integer :tag "when modifying times")))
2891 ;; Normalize old customizations of this variable.
2892 (when (integerp org-time-stamp-rounding-minutes)
2893 (setq org-time-stamp-rounding-minutes
2894 (list org-time-stamp-rounding-minutes
2895 org-time-stamp-rounding-minutes)))
2897 (defcustom org-display-custom-times nil
2898 "Non-nil means overlay custom formats over all time stamps.
2899 The formats are defined through the variable `org-time-stamp-custom-formats'.
2900 To turn this on on a per-file basis, insert anywhere in the file:
2901 #+STARTUP: customtime"
2902 :group 'org-time
2903 :set 'set-default
2904 :type 'sexp)
2905 (make-variable-buffer-local 'org-display-custom-times)
2907 (defcustom org-time-stamp-custom-formats
2908 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2909 "Custom formats for time stamps. See `format-time-string' for the syntax.
2910 These are overlaid over the default ISO format if the variable
2911 `org-display-custom-times' is set. Time like %H:%M should be at the
2912 end of the second format. The custom formats are also honored by export
2913 commands, if custom time display is turned on at the time of export."
2914 :group 'org-time
2915 :type 'sexp)
2917 (defun org-time-stamp-format (&optional long inactive)
2918 "Get the right format for a time string."
2919 (let ((f (if long (cdr org-time-stamp-formats)
2920 (car org-time-stamp-formats))))
2921 (if inactive
2922 (concat "[" (substring f 1 -1) "]")
2923 f)))
2925 (defcustom org-time-clocksum-format
2926 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2927 "The format string used when creating CLOCKSUM lines.
2928 This is also used when Org mode generates a time duration.
2930 The value can be a single format string containing two
2931 %-sequences, which will be filled with the number of hours and
2932 minutes in that order.
2934 Alternatively, the value can be a plist associating any of the
2935 keys :years, :months, :weeks, :days, :hours or :minutes with
2936 format strings. The time duration is formatted using only the
2937 time components that are needed and concatenating the results.
2938 If a time unit in absent, it falls back to the next smallest
2939 unit.
2941 The keys :require-years, :require-months, :require-days,
2942 :require-weeks, :require-hours, :require-minutes are also
2943 meaningful. A non-nil value for these keys indicates that the
2944 corresponding time component should always be included, even if
2945 its value is 0.
2948 For example,
2950 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2951 :require-minutes t)
2953 means durations longer than a day will be expressed in days,
2954 hours and minutes, and durations less than a day will always be
2955 expressed in hours and minutes (even for durations less than an
2956 hour).
2958 The value
2960 \(:days \"%dd\" :minutes \"%dm\")
2962 means durations longer than a day will be expressed in days and
2963 minutes, and durations less than a day will be expressed entirely
2964 in minutes (even for durations longer than an hour)."
2965 :group 'org-time
2966 :group 'org-clock
2967 :version "24.4"
2968 :package-version '(Org . "8.0")
2969 :type '(choice (string :tag "Format string")
2970 (set :tag "Plist"
2971 (group :inline t (const :tag "Years" :years)
2972 (string :tag "Format string"))
2973 (group :inline t
2974 (const :tag "Always show years" :require-years)
2975 (const t))
2976 (group :inline t (const :tag "Months" :months)
2977 (string :tag "Format string"))
2978 (group :inline t
2979 (const :tag "Always show months" :require-months)
2980 (const t))
2981 (group :inline t (const :tag "Weeks" :weeks)
2982 (string :tag "Format string"))
2983 (group :inline t
2984 (const :tag "Always show weeks" :require-weeks)
2985 (const t))
2986 (group :inline t (const :tag "Days" :days)
2987 (string :tag "Format string"))
2988 (group :inline t
2989 (const :tag "Always show days" :require-days)
2990 (const t))
2991 (group :inline t (const :tag "Hours" :hours)
2992 (string :tag "Format string"))
2993 (group :inline t
2994 (const :tag "Always show hours" :require-hours)
2995 (const t))
2996 (group :inline t (const :tag "Minutes" :minutes)
2997 (string :tag "Format string"))
2998 (group :inline t
2999 (const :tag "Always show minutes" :require-minutes)
3000 (const t)))))
3002 (defcustom org-time-clocksum-use-fractional nil
3003 "When non-nil, \\[org-clock-display] uses fractional times.
3004 See `org-time-clocksum-format' for more on time clock formats."
3005 :group 'org-time
3006 :group 'org-clock
3007 :version "24.3"
3008 :type 'boolean)
3010 (defcustom org-time-clocksum-use-effort-durations nil
3011 "When non-nil, \\[org-clock-display] uses effort durations.
3012 E.g. by default, one day is considered to be a 8 hours effort,
3013 so a task that has been clocked for 16 hours will be displayed
3014 as during 2 days in the clock display or in the clocktable.
3016 See `org-effort-durations' on how to set effort durations
3017 and `org-time-clocksum-format' for more on time clock formats."
3018 :group 'org-time
3019 :group 'org-clock
3020 :version "24.4"
3021 :package-version '(Org . "8.0")
3022 :type 'boolean)
3024 (defcustom org-time-clocksum-fractional-format "%.2f"
3025 "The format string used when creating CLOCKSUM lines,
3026 or when Org mode generates a time duration, if
3027 `org-time-clocksum-use-fractional' is enabled.
3029 The value can be a single format string containing one
3030 %-sequence, which will be filled with the number of hours as
3031 a float.
3033 Alternatively, the value can be a plist associating any of the
3034 keys :years, :months, :weeks, :days, :hours or :minutes with
3035 a format string. The time duration is formatted using the
3036 largest time unit which gives a non-zero integer part. If all
3037 specified formats have zero integer part, the smallest time unit
3038 is used."
3039 :group 'org-time
3040 :type '(choice (string :tag "Format string")
3041 (set (group :inline t (const :tag "Years" :years)
3042 (string :tag "Format string"))
3043 (group :inline t (const :tag "Months" :months)
3044 (string :tag "Format string"))
3045 (group :inline t (const :tag "Weeks" :weeks)
3046 (string :tag "Format string"))
3047 (group :inline t (const :tag "Days" :days)
3048 (string :tag "Format string"))
3049 (group :inline t (const :tag "Hours" :hours)
3050 (string :tag "Format string"))
3051 (group :inline t (const :tag "Minutes" :minutes)
3052 (string :tag "Format string")))))
3054 (defcustom org-deadline-warning-days 14
3055 "Number of days before expiration during which a deadline becomes active.
3056 This variable governs the display in sparse trees and in the agenda.
3057 When 0 or negative, it means use this number (the absolute value of it)
3058 even if a deadline has a different individual lead time specified.
3060 Custom commands can set this variable in the options section."
3061 :group 'org-time
3062 :group 'org-agenda-daily/weekly
3063 :type 'integer)
3065 (defcustom org-scheduled-delay-days 0
3066 "Number of days before a scheduled item becomes active.
3067 This variable governs the display in sparse trees and in the agenda.
3068 The default value (i.e. 0) means: don't delay scheduled item.
3069 When negative, it means use this number (the absolute value of it)
3070 even if a scheduled item has a different individual delay time
3071 specified.
3073 Custom commands can set this variable in the options section."
3074 :group 'org-time
3075 :group 'org-agenda-daily/weekly
3076 :version "24.4"
3077 :package-version '(Org . "8.0")
3078 :type 'integer)
3080 (defcustom org-read-date-prefer-future t
3081 "Non-nil means assume future for incomplete date input from user.
3082 This affects the following situations:
3083 1. The user gives a month but not a year.
3084 For example, if it is April and you enter \"feb 2\", this will be read
3085 as Feb 2, *next* year. \"May 5\", however, will be this year.
3086 2. The user gives a day, but no month.
3087 For example, if today is the 15th, and you enter \"3\", Org-mode will
3088 read this as the third of *next* month. However, if you enter \"17\",
3089 it will be considered as *this* month.
3091 If you set this variable to the symbol `time', then also the following
3092 will work:
3094 3. If the user gives a time.
3095 If the time is before now, it will be interpreted as tomorrow.
3097 Currently none of this works for ISO week specifications.
3099 When this option is nil, the current day, month and year will always be
3100 used as defaults.
3102 See also `org-agenda-jump-prefer-future'."
3103 :group 'org-time
3104 :type '(choice
3105 (const :tag "Never" nil)
3106 (const :tag "Check month and day" t)
3107 (const :tag "Check month, day, and time" time)))
3109 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3110 "Should the agenda jump command prefer the future for incomplete dates?
3111 The default is to do the same as configured in `org-read-date-prefer-future'.
3112 But you can also set a deviating value here.
3113 This may t or nil, or the symbol `org-read-date-prefer-future'."
3114 :group 'org-agenda
3115 :group 'org-time
3116 :version "24.1"
3117 :type '(choice
3118 (const :tag "Use org-read-date-prefer-future"
3119 org-read-date-prefer-future)
3120 (const :tag "Never" nil)
3121 (const :tag "Always" t)))
3123 (defcustom org-read-date-force-compatible-dates t
3124 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3126 Depending on the system Emacs is running on, certain dates cannot
3127 be represented with the type used internally to represent time.
3128 Dates between 1970-1-1 and 2038-1-1 can always be represented
3129 correctly. Some systems allow for earlier dates, some for later,
3130 some for both. One way to find out it to insert any date into an
3131 Org buffer, putting the cursor on the year and hitting S-up and
3132 S-down to test the range.
3134 When this variable is set to t, the date/time prompt will not let
3135 you specify dates outside the 1970-2037 range, so it is certain that
3136 these dates will work in whatever version of Emacs you are
3137 running, and also that you can move a file from one Emacs implementation
3138 to another. WHenever Org is forcing the year for you, it will display
3139 a message and beep.
3141 When this variable is nil, Org will check if the date is
3142 representable in the specific Emacs implementation you are using.
3143 If not, it will force a year, usually the current year, and beep
3144 to remind you. Currently this setting is not recommended because
3145 the likelihood that you will open your Org files in an Emacs that
3146 has limited date range is not negligible.
3148 A workaround for this problem is to use diary sexp dates for time
3149 stamps outside of this range."
3150 :group 'org-time
3151 :version "24.1"
3152 :type 'boolean)
3154 (defcustom org-read-date-display-live t
3155 "Non-nil means display current interpretation of date prompt live.
3156 This display will be in an overlay, in the minibuffer."
3157 :group 'org-time
3158 :type 'boolean)
3160 (defcustom org-read-date-popup-calendar t
3161 "Non-nil means pop up a calendar when prompting for a date.
3162 In the calendar, the date can be selected with mouse-1. However, the
3163 minibuffer will also be active, and you can simply enter the date as well.
3164 When nil, only the minibuffer will be available."
3165 :group 'org-time
3166 :type 'boolean)
3167 (org-defvaralias 'org-popup-calendar-for-date-prompt
3168 'org-read-date-popup-calendar)
3170 (make-obsolete-variable
3171 'org-read-date-minibuffer-setup-hook
3172 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3173 (defcustom org-read-date-minibuffer-setup-hook nil
3174 "Hook to be used to set up keys for the date/time interface.
3175 Add key definitions to `minibuffer-local-map', which will be a
3176 temporary copy.
3178 WARNING: This option is obsolete, you should use
3179 `org-read-date-minibuffer-local-map' to set up keys."
3180 :group 'org-time
3181 :type 'hook)
3183 (defcustom org-extend-today-until 0
3184 "The hour when your day really ends. Must be an integer.
3185 This has influence for the following applications:
3186 - When switching the agenda to \"today\". It it is still earlier than
3187 the time given here, the day recognized as TODAY is actually yesterday.
3188 - When a date is read from the user and it is still before the time given
3189 here, the current date and time will be assumed to be yesterday, 23:59.
3190 Also, timestamps inserted in capture templates follow this rule.
3192 IMPORTANT: This is a feature whose implementation is and likely will
3193 remain incomplete. Really, it is only here because past midnight seems to
3194 be the favorite working time of John Wiegley :-)"
3195 :group 'org-time
3196 :type 'integer)
3198 (defcustom org-use-effective-time nil
3199 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3200 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3201 \"effective time\" of any timestamps between midnight and 8am will be
3202 23:59 of the previous day."
3203 :group 'org-time
3204 :version "24.1"
3205 :type 'boolean)
3207 (defcustom org-use-last-clock-out-time-as-effective-time nil
3208 "When non-nil, use the last clock out time for `org-todo'.
3209 Note that this option has precedence over the combined use of
3210 `org-use-effective-time' and `org-extend-today-until'."
3211 :group 'org-time
3212 :version "24.4"
3213 :package-version '(Org . "8.0")
3214 :type 'boolean)
3216 (defcustom org-edit-timestamp-down-means-later nil
3217 "Non-nil means S-down will increase the time in a time stamp.
3218 When nil, S-up will increase."
3219 :group 'org-time
3220 :type 'boolean)
3222 (defcustom org-calendar-follow-timestamp-change t
3223 "Non-nil means make the calendar window follow timestamp changes.
3224 When a timestamp is modified and the calendar window is visible, it will be
3225 moved to the new date."
3226 :group 'org-time
3227 :type 'boolean)
3229 (defgroup org-tags nil
3230 "Options concerning tags in Org-mode."
3231 :tag "Org Tags"
3232 :group 'org)
3234 (defcustom org-tag-alist nil
3235 "List of tags allowed in Org-mode files.
3236 When this list is nil, Org-mode will base TAG input on what is already in the
3237 buffer.
3238 The value of this variable is an alist, the car of each entry must be a
3239 keyword as a string, the cdr may be a character that is used to select
3240 that tag through the fast-tag-selection interface.
3241 See the manual for details."
3242 :group 'org-tags
3243 :type '(repeat
3244 (choice
3245 (cons (string :tag "Tag name")
3246 (character :tag "Access char"))
3247 (list :tag "Start radio group"
3248 (const :startgroup)
3249 (option (string :tag "Group description")))
3250 (list :tag "Group tags delimiter"
3251 (const :grouptags))
3252 (list :tag "End radio group"
3253 (const :endgroup)
3254 (option (string :tag "Group description")))
3255 (const :tag "New line" (:newline)))))
3257 (defcustom org-tag-persistent-alist nil
3258 "List of tags that will always appear in all Org-mode files.
3259 This is in addition to any in buffer settings or customizations
3260 of `org-tag-alist'.
3261 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3262 The value of this variable is an alist, the car of each entry must be a
3263 keyword as a string, the cdr may be a character that is used to select
3264 that tag through the fast-tag-selection interface.
3265 See the manual for details.
3266 To disable these tags on a per-file basis, insert anywhere in the file:
3267 #+STARTUP: noptag"
3268 :group 'org-tags
3269 :type '(repeat
3270 (choice
3271 (cons (string :tag "Tag name")
3272 (character :tag "Access char"))
3273 (const :tag "Start radio group" (:startgroup))
3274 (const :tag "Group tags delimiter" (:grouptags))
3275 (const :tag "End radio group" (:endgroup))
3276 (const :tag "New line" (:newline)))))
3278 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3279 "If non-nil, always offer completion for all tags of all agenda files.
3280 Instead of customizing this variable directly, you might want to
3281 set it locally for capture buffers, because there no list of
3282 tags in that file can be created dynamically (there are none).
3284 (add-hook 'org-capture-mode-hook
3285 (lambda ()
3286 (set (make-local-variable
3287 'org-complete-tags-always-offer-all-agenda-tags)
3288 t)))"
3289 :group 'org-tags
3290 :version "24.1"
3291 :type 'boolean)
3293 (defvar org-file-tags nil
3294 "List of tags that can be inherited by all entries in the file.
3295 The tags will be inherited if the variable `org-use-tag-inheritance'
3296 says they should be.
3297 This variable is populated from #+FILETAGS lines.")
3299 (defcustom org-use-fast-tag-selection 'auto
3300 "Non-nil means use fast tag selection scheme.
3301 This is a special interface to select and deselect tags with single keys.
3302 When nil, fast selection is never used.
3303 When the symbol `auto', fast selection is used if and only if selection
3304 characters for tags have been configured, either through the variable
3305 `org-tag-alist' or through a #+TAGS line in the buffer.
3306 When t, fast selection is always used and selection keys are assigned
3307 automatically if necessary."
3308 :group 'org-tags
3309 :type '(choice
3310 (const :tag "Always" t)
3311 (const :tag "Never" nil)
3312 (const :tag "When selection characters are configured" auto)))
3314 (defcustom org-fast-tag-selection-single-key nil
3315 "Non-nil means fast tag selection exits after first change.
3316 When nil, you have to press RET to exit it.
3317 During fast tag selection, you can toggle this flag with `C-c'.
3318 This variable can also have the value `expert'. In this case, the window
3319 displaying the tags menu is not even shown, until you press C-c again."
3320 :group 'org-tags
3321 :type '(choice
3322 (const :tag "No" nil)
3323 (const :tag "Yes" t)
3324 (const :tag "Expert" expert)))
3326 (defvar org-fast-tag-selection-include-todo nil
3327 "Non-nil means fast tags selection interface will also offer TODO states.
3328 This is an undocumented feature, you should not rely on it.")
3330 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3331 "The column to which tags should be indented in a headline.
3332 If this number is positive, it specifies the column. If it is negative,
3333 it means that the tags should be flushright to that column. For example,
3334 -80 works well for a normal 80 character screen.
3335 When 0, place tags directly after headline text, with only one space in
3336 between."
3337 :group 'org-tags
3338 :type 'integer)
3340 (defcustom org-auto-align-tags t
3341 "Non-nil keeps tags aligned when modifying headlines.
3342 Some operations (i.e. demoting) change the length of a headline and
3343 therefore shift the tags around. With this option turned on, after
3344 each such operation the tags are again aligned to `org-tags-column'."
3345 :group 'org-tags
3346 :type 'boolean)
3348 (defcustom org-use-tag-inheritance t
3349 "Non-nil means tags in levels apply also for sublevels.
3350 When nil, only the tags directly given in a specific line apply there.
3351 This may also be a list of tags that should be inherited, or a regexp that
3352 matches tags that should be inherited. Additional control is possible
3353 with the variable `org-tags-exclude-from-inheritance' which gives an
3354 explicit list of tags to be excluded from inheritance, even if the value of
3355 `org-use-tag-inheritance' would select it for inheritance.
3357 If this option is t, a match early-on in a tree can lead to a large
3358 number of matches in the subtree when constructing the agenda or creating
3359 a sparse tree. If you only want to see the first match in a tree during
3360 a search, check out the variable `org-tags-match-list-sublevels'."
3361 :group 'org-tags
3362 :type '(choice
3363 (const :tag "Not" nil)
3364 (const :tag "Always" t)
3365 (repeat :tag "Specific tags" (string :tag "Tag"))
3366 (regexp :tag "Tags matched by regexp")))
3368 (defcustom org-tags-exclude-from-inheritance nil
3369 "List of tags that should never be inherited.
3370 This is a way to exclude a few tags from inheritance. For way to do
3371 the opposite, to actively allow inheritance for selected tags,
3372 see the variable `org-use-tag-inheritance'."
3373 :group 'org-tags
3374 :type '(repeat (string :tag "Tag")))
3376 (defun org-tag-inherit-p (tag)
3377 "Check if TAG is one that should be inherited."
3378 (cond
3379 ((member tag org-tags-exclude-from-inheritance) nil)
3380 ((eq org-use-tag-inheritance t) t)
3381 ((not org-use-tag-inheritance) nil)
3382 ((stringp org-use-tag-inheritance)
3383 (string-match org-use-tag-inheritance tag))
3384 ((listp org-use-tag-inheritance)
3385 (member tag org-use-tag-inheritance))
3386 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3388 (defcustom org-tags-match-list-sublevels t
3389 "Non-nil means list also sublevels of headlines matching a search.
3390 This variable applies to tags/property searches, and also to stuck
3391 projects because this search is based on a tags match as well.
3393 When set to the symbol `indented', sublevels are indented with
3394 leading dots.
3396 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3397 the sublevels of a headline matching a tag search often also match
3398 the same search. Listing all of them can create very long lists.
3399 Setting this variable to nil causes subtrees of a match to be skipped.
3401 This variable is semi-obsolete and probably should always be true. It
3402 is better to limit inheritance to certain tags using the variables
3403 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3404 :group 'org-tags
3405 :type '(choice
3406 (const :tag "No, don't list them" nil)
3407 (const :tag "Yes, do list them" t)
3408 (const :tag "List them, indented with leading dots" indented)))
3410 (defcustom org-tags-sort-function nil
3411 "When set, tags are sorted using this function as a comparator."
3412 :group 'org-tags
3413 :type '(choice
3414 (const :tag "No sorting" nil)
3415 (const :tag "Alphabetical" string<)
3416 (const :tag "Reverse alphabetical" string>)
3417 (function :tag "Custom function" nil)))
3419 (defvar org-tags-history nil
3420 "History of minibuffer reads for tags.")
3421 (defvar org-last-tags-completion-table nil
3422 "The last used completion table for tags.")
3423 (defvar org-after-tags-change-hook nil
3424 "Hook that is run after the tags in a line have changed.")
3426 (defgroup org-properties nil
3427 "Options concerning properties in Org-mode."
3428 :tag "Org Properties"
3429 :group 'org)
3431 (defcustom org-property-format "%-10s %s"
3432 "How property key/value pairs should be formatted by `indent-line'.
3433 When `indent-line' hits a property definition, it will format the line
3434 according to this format, mainly to make sure that the values are
3435 lined-up with respect to each other."
3436 :group 'org-properties
3437 :type 'string)
3439 (defcustom org-properties-postprocess-alist nil
3440 "Alist of properties and functions to adjust inserted values.
3441 Elements of this alist must be of the form
3443 ([string] [function])
3445 where [string] must be a property name and [function] must be a
3446 lambda expression: this lambda expression must take one argument,
3447 the value to adjust, and return the new value as a string.
3449 For example, this element will allow the property \"Remaining\"
3450 to be updated wrt the relation between the \"Effort\" property
3451 and the clock summary:
3453 ((\"Remaining\" (lambda(value)
3454 (let ((clocksum (org-clock-sum-current-item))
3455 (effort (org-duration-string-to-minutes
3456 (org-entry-get (point) \"Effort\"))))
3457 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3458 :group 'org-properties
3459 :version "24.1"
3460 :type '(alist :key-type (string :tag "Property")
3461 :value-type (function :tag "Function")))
3463 (defcustom org-use-property-inheritance nil
3464 "Non-nil means properties apply also for sublevels.
3466 This setting is chiefly used during property searches. Turning it on can
3467 cause significant overhead when doing a search, which is why it is not
3468 on by default.
3470 When nil, only the properties directly given in the current entry count.
3471 When t, every property is inherited. The value may also be a list of
3472 properties that should have inheritance, or a regular expression matching
3473 properties that should be inherited.
3475 However, note that some special properties use inheritance under special
3476 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3477 and the properties ending in \"_ALL\" when they are used as descriptor
3478 for valid values of a property.
3480 Note for programmers:
3481 When querying an entry with `org-entry-get', you can control if inheritance
3482 should be used. By default, `org-entry-get' looks only at the local
3483 properties. You can request inheritance by setting the inherit argument
3484 to t (to force inheritance) or to `selective' (to respect the setting
3485 in this variable)."
3486 :group 'org-properties
3487 :type '(choice
3488 (const :tag "Not" nil)
3489 (const :tag "Always" t)
3490 (repeat :tag "Specific properties" (string :tag "Property"))
3491 (regexp :tag "Properties matched by regexp")))
3493 (defun org-property-inherit-p (property)
3494 "Check if PROPERTY is one that should be inherited."
3495 (cond
3496 ((eq org-use-property-inheritance t) t)
3497 ((not org-use-property-inheritance) nil)
3498 ((stringp org-use-property-inheritance)
3499 (string-match org-use-property-inheritance property))
3500 ((listp org-use-property-inheritance)
3501 (member property org-use-property-inheritance))
3502 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3504 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3505 "The default column format, if no other format has been defined.
3506 This variable can be set on the per-file basis by inserting a line
3508 #+COLUMNS: %25ITEM ....."
3509 :group 'org-properties
3510 :type 'string)
3512 (defcustom org-columns-ellipses ".."
3513 "The ellipses to be used when a field in column view is truncated.
3514 When this is the empty string, as many characters as possible are shown,
3515 but then there will be no visual indication that the field has been truncated.
3516 When this is a string of length N, the last N characters of a truncated
3517 field are replaced by this string. If the column is narrower than the
3518 ellipses string, only part of the ellipses string will be shown."
3519 :group 'org-properties
3520 :type 'string)
3522 (defcustom org-columns-modify-value-for-display-function nil
3523 "Function that modifies values for display in column view.
3524 For example, it can be used to cut out a certain part from a time stamp.
3525 The function must take 2 arguments:
3527 column-title The title of the column (*not* the property name)
3528 value The value that should be modified.
3530 The function should return the value that should be displayed,
3531 or nil if the normal value should be used."
3532 :group 'org-properties
3533 :type '(choice (const nil) (function)))
3535 (defcustom org-effort-property "Effort"
3536 "The property that is being used to keep track of effort estimates.
3537 Effort estimates given in this property need to have the format H:MM."
3538 :group 'org-properties
3539 :group 'org-progress
3540 :type '(string :tag "Property"))
3542 (defconst org-global-properties-fixed
3543 '(("VISIBILITY_ALL" . "folded children content all")
3544 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3545 "List of property/value pairs that can be inherited by any entry.
3547 These are fixed values, for the preset properties. The user variable
3548 that can be used to add to this list is `org-global-properties'.
3550 The entries in this list are cons cells where the car is a property
3551 name and cdr is a string with the value. If the value represents
3552 multiple items like an \"_ALL\" property, separate the items by
3553 spaces.")
3555 (defcustom org-global-properties nil
3556 "List of property/value pairs that can be inherited by any entry.
3558 This list will be combined with the constant `org-global-properties-fixed'.
3560 The entries in this list are cons cells where the car is a property
3561 name and cdr is a string with the value.
3563 You can set buffer-local values for the same purpose in the variable
3564 `org-file-properties' this by adding lines like
3566 #+PROPERTY: NAME VALUE"
3567 :group 'org-properties
3568 :type '(repeat
3569 (cons (string :tag "Property")
3570 (string :tag "Value"))))
3572 (defvar org-file-properties nil
3573 "List of property/value pairs that can be inherited by any entry.
3574 Valid for the current buffer.
3575 This variable is populated from #+PROPERTY lines.")
3576 (make-variable-buffer-local 'org-file-properties)
3578 (defgroup org-agenda nil
3579 "Options concerning agenda views in Org-mode."
3580 :tag "Org Agenda"
3581 :group 'org)
3583 (defvar org-category nil
3584 "Variable used by org files to set a category for agenda display.
3585 Such files should use a file variable to set it, for example
3587 # -*- mode: org; org-category: \"ELisp\"
3589 or contain a special line
3591 #+CATEGORY: ELisp
3593 If the file does not specify a category, then file's base name
3594 is used instead.")
3595 (make-variable-buffer-local 'org-category)
3596 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3598 (defcustom org-agenda-files nil
3599 "The files to be used for agenda display.
3600 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3601 \\[org-remove-file]. You can also use customize to edit the list.
3603 If an entry is a directory, all files in that directory that are matched by
3604 `org-agenda-file-regexp' will be part of the file list.
3606 If the value of the variable is not a list but a single file name, then
3607 the list of agenda files is actually stored and maintained in that file, one
3608 agenda file per line. In this file paths can be given relative to
3609 `org-directory'. Tilde expansion and environment variable substitution
3610 are also made."
3611 :group 'org-agenda
3612 :type '(choice
3613 (repeat :tag "List of files and directories" file)
3614 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3616 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3617 "Regular expression to match files for `org-agenda-files'.
3618 If any element in the list in that variable contains a directory instead
3619 of a normal file, all files in that directory that are matched by this
3620 regular expression will be included."
3621 :group 'org-agenda
3622 :type 'regexp)
3624 (defcustom org-agenda-text-search-extra-files nil
3625 "List of extra files to be searched by text search commands.
3626 These files will be searched in addition to the agenda files by the
3627 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3628 Note that these files will only be searched for text search commands,
3629 not for the other agenda views like todo lists, tag searches or the weekly
3630 agenda. This variable is intended to list notes and possibly archive files
3631 that should also be searched by these two commands.
3632 In fact, if the first element in the list is the symbol `agenda-archives',
3633 then all archive files of all agenda files will be added to the search
3634 scope."
3635 :group 'org-agenda
3636 :type '(set :greedy t
3637 (const :tag "Agenda Archives" agenda-archives)
3638 (repeat :inline t (file))))
3640 (org-defvaralias 'org-agenda-multi-occur-extra-files
3641 'org-agenda-text-search-extra-files)
3643 (defcustom org-agenda-skip-unavailable-files nil
3644 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3645 A nil value means to remove them, after a query, from the list."
3646 :group 'org-agenda
3647 :type 'boolean)
3649 (defcustom org-calendar-to-agenda-key [?c]
3650 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3651 The command `org-calendar-goto-agenda' will be bound to this key. The
3652 default is the character `c' because then `c' can be used to switch back and
3653 forth between agenda and calendar."
3654 :group 'org-agenda
3655 :type 'sexp)
3657 (defcustom org-calendar-insert-diary-entry-key [?i]
3658 "The key to be installed in `calendar-mode-map' for adding diary entries.
3659 This option is irrelevant until `org-agenda-diary-file' has been configured
3660 to point to an Org-mode file. When that is the case, the command
3661 `org-agenda-diary-entry' will be bound to the key given here, by default
3662 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3663 if you want to continue doing this, you need to change this to a different
3664 key."
3665 :group 'org-agenda
3666 :type 'sexp)
3668 (defcustom org-agenda-diary-file 'diary-file
3669 "File to which to add new entries with the `i' key in agenda and calendar.
3670 When this is the symbol `diary-file', the functionality in the Emacs
3671 calendar will be used to add entries to the `diary-file'. But when this
3672 points to a file, `org-agenda-diary-entry' will be used instead."
3673 :group 'org-agenda
3674 :type '(choice
3675 (const :tag "The standard Emacs diary file" diary-file)
3676 (file :tag "Special Org file diary entries")))
3678 (eval-after-load "calendar"
3679 '(progn
3680 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3681 'org-calendar-goto-agenda)
3682 (add-hook 'calendar-mode-hook
3683 (lambda ()
3684 (unless (eq org-agenda-diary-file 'diary-file)
3685 (define-key calendar-mode-map
3686 org-calendar-insert-diary-entry-key
3687 'org-agenda-diary-entry))))))
3689 (defgroup org-latex nil
3690 "Options for embedding LaTeX code into Org-mode."
3691 :tag "Org LaTeX"
3692 :group 'org)
3694 (defcustom org-format-latex-options
3695 '(:foreground default :background default :scale 1.0
3696 :html-foreground "Black" :html-background "Transparent"
3697 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3698 "Options for creating images from LaTeX fragments.
3699 This is a property list with the following properties:
3700 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3701 `default' means use the foreground of the default face.
3702 `auto' means use the foreground from the text face.
3703 :background the background color, or \"Transparent\".
3704 `default' means use the background of the default face.
3705 `auto' means use the background from the text face.
3706 :scale a scaling factor for the size of the images, to get more pixels
3707 :html-foreground, :html-background, :html-scale
3708 the same numbers for HTML export.
3709 :matchers a list indicating which matchers should be used to
3710 find LaTeX fragments. Valid members of this list are:
3711 \"begin\" find environments
3712 \"$1\" find single characters surrounded by $.$
3713 \"$\" find math expressions surrounded by $...$
3714 \"$$\" find math expressions surrounded by $$....$$
3715 \"\\(\" find math expressions surrounded by \\(...\\)
3716 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3717 :group 'org-latex
3718 :type 'plist)
3720 (defcustom org-format-latex-signal-error t
3721 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3722 When nil, just push out a message."
3723 :group 'org-latex
3724 :version "24.1"
3725 :type 'boolean)
3727 (defcustom org-latex-to-mathml-jar-file nil
3728 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3729 Use this to specify additional executable file say a jar file.
3731 When using MathToWeb as the converter, specify the full-path to
3732 your mathtoweb.jar file."
3733 :group 'org-latex
3734 :version "24.1"
3735 :type '(choice
3736 (const :tag "None" nil)
3737 (file :tag "JAR file" :must-match t)))
3739 (defcustom org-latex-to-mathml-convert-command nil
3740 "Command to convert LaTeX fragments to MathML.
3741 Replace format-specifiers in the command as noted below and use
3742 `shell-command' to convert LaTeX to MathML.
3743 %j: Executable file in fully expanded form as specified by
3744 `org-latex-to-mathml-jar-file'.
3745 %I: Input LaTeX file in fully expanded form
3746 %o: Output MathML file
3747 This command is used by `org-create-math-formula'.
3749 When using MathToWeb as the converter, set this to
3750 \"java -jar %j -unicode -force -df %o %I\"."
3751 :group 'org-latex
3752 :version "24.1"
3753 :type '(choice
3754 (const :tag "None" nil)
3755 (string :tag "\nShell command")))
3757 (defcustom org-latex-create-formula-image-program 'dvipng
3758 "Program to convert LaTeX fragments with.
3760 dvipng Process the LaTeX fragments to dvi file, then convert
3761 dvi files to png files using dvipng.
3762 This will also include processing of non-math environments.
3763 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3764 to convert pdf files to png files"
3765 :group 'org-latex
3766 :version "24.1"
3767 :type '(choice
3768 (const :tag "dvipng" dvipng)
3769 (const :tag "imagemagick" imagemagick)))
3771 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3772 "Path to store latex preview images.
3773 A relative path here creates many directories relative to the
3774 processed org files paths. An absolute path puts all preview
3775 images at the same place."
3776 :group 'org-latex
3777 :version "24.3"
3778 :type 'string)
3780 (defun org-format-latex-mathml-available-p ()
3781 "Return t if `org-latex-to-mathml-convert-command' is usable."
3782 (save-match-data
3783 (when (and (boundp 'org-latex-to-mathml-convert-command)
3784 org-latex-to-mathml-convert-command)
3785 (let ((executable (car (split-string
3786 org-latex-to-mathml-convert-command))))
3787 (when (executable-find executable)
3788 (if (string-match
3789 "%j" org-latex-to-mathml-convert-command)
3790 (file-readable-p org-latex-to-mathml-jar-file)
3791 t))))))
3793 (defcustom org-format-latex-header "\\documentclass{article}
3794 \\usepackage[usenames]{color}
3795 \[PACKAGES]
3796 \[DEFAULT-PACKAGES]
3797 \\pagestyle{empty} % do not remove
3798 % The settings below are copied from fullpage.sty
3799 \\setlength{\\textwidth}{\\paperwidth}
3800 \\addtolength{\\textwidth}{-3cm}
3801 \\setlength{\\oddsidemargin}{1.5cm}
3802 \\addtolength{\\oddsidemargin}{-2.54cm}
3803 \\setlength{\\evensidemargin}{\\oddsidemargin}
3804 \\setlength{\\textheight}{\\paperheight}
3805 \\addtolength{\\textheight}{-\\headheight}
3806 \\addtolength{\\textheight}{-\\headsep}
3807 \\addtolength{\\textheight}{-\\footskip}
3808 \\addtolength{\\textheight}{-3cm}
3809 \\setlength{\\topmargin}{1.5cm}
3810 \\addtolength{\\topmargin}{-2.54cm}"
3811 "The document header used for processing LaTeX fragments.
3812 It is imperative that this header make sure that no page number
3813 appears on the page. The package defined in the variables
3814 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3815 will either replace the placeholder \"[PACKAGES]\" in this
3816 header, or they will be appended."
3817 :group 'org-latex
3818 :type 'string)
3820 (defun org-set-packages-alist (var val)
3821 "Set the packages alist and make sure it has 3 elements per entry."
3822 (set var (mapcar (lambda (x)
3823 (if (and (consp x) (= (length x) 2))
3824 (list (car x) (nth 1 x) t)
3826 val)))
3828 (defun org-get-packages-alist (var)
3829 "Get the packages alist and make sure it has 3 elements per entry."
3830 (mapcar (lambda (x)
3831 (if (and (consp x) (= (length x) 2))
3832 (list (car x) (nth 1 x) t)
3834 (default-value var)))
3836 (defcustom org-latex-default-packages-alist
3837 '(("AUTO" "inputenc" t)
3838 ("T1" "fontenc" t)
3839 ("" "fixltx2e" nil)
3840 ("" "graphicx" t)
3841 ("" "longtable" nil)
3842 ("" "float" nil)
3843 ("" "wrapfig" nil)
3844 ("" "rotating" nil)
3845 ("normalem" "ulem" t)
3846 ("" "amsmath" t)
3847 ("" "textcomp" t)
3848 ("" "marvosym" t)
3849 ("" "wasysym" t)
3850 ("" "amssymb" t)
3851 ("" "hyperref" nil)
3852 "\\tolerance=1000")
3853 "Alist of default packages to be inserted in the header.
3855 Change this only if one of the packages here causes an
3856 incompatibility with another package you are using.
3858 The packages in this list are needed by one part or another of
3859 Org mode to function properly:
3861 - inputenc, fontenc: for basic font and character selection
3862 - fixltx2e: Important patches of LaTeX itself
3863 - graphicx: for including images
3864 - longtable: For multipage tables
3865 - float, wrapfig: for figure placement
3866 - rotating: for sideways figures and tables
3867 - ulem: for underline and strike-through
3868 - amsmath: for subscript and superscript and math environments
3869 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3870 for interpreting the entities in `org-entities'. You can skip
3871 some of these packages if you don't use any of their symbols.
3872 - hyperref: for cross references
3874 Therefore you should not modify this variable unless you know
3875 what you are doing. The one reason to change it anyway is that
3876 you might be loading some other package that conflicts with one
3877 of the default packages. Each cell is of the format
3878 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3879 the package also needs to be included when compiling LaTeX
3880 snippets into images for inclusion into non-LaTeX output."
3881 :group 'org-latex
3882 :group 'org-export-latex
3883 :set 'org-set-packages-alist
3884 :get 'org-get-packages-alist
3885 :version "24.1"
3886 :type '(repeat
3887 (choice
3888 (list :tag "options/package pair"
3889 (string :tag "options")
3890 (string :tag "package")
3891 (boolean :tag "Snippet"))
3892 (string :tag "A line of LaTeX"))))
3894 (defcustom org-latex-packages-alist nil
3895 "Alist of packages to be inserted in every LaTeX header.
3897 These will be inserted after `org-latex-default-packages-alist'.
3898 Each cell is of the format:
3900 \(\"options\" \"package\" snippet-flag)
3902 SNIPPET-FLAG, when t, indicates that this package is also needed
3903 when turning LaTeX snippets into images for inclusion into
3904 non-LaTeX output.
3906 Make sure that you only list packages here which:
3908 - you want in every file
3909 - do not conflict with the setup in `org-format-latex-header'.
3910 - do not conflict with the default packages in
3911 `org-latex-default-packages-alist'."
3912 :group 'org-latex
3913 :group 'org-export-latex
3914 :set 'org-set-packages-alist
3915 :get 'org-get-packages-alist
3916 :type '(repeat
3917 (choice
3918 (list :tag "options/package pair"
3919 (string :tag "options")
3920 (string :tag "package")
3921 (boolean :tag "Snippet"))
3922 (string :tag "A line of LaTeX"))))
3924 (defgroup org-appearance nil
3925 "Settings for Org-mode appearance."
3926 :tag "Org Appearance"
3927 :group 'org)
3929 (defcustom org-level-color-stars-only nil
3930 "Non-nil means fontify only the stars in each headline.
3931 When nil, the entire headline is fontified.
3932 Changing it requires restart of `font-lock-mode' to become effective
3933 also in regions already fontified."
3934 :group 'org-appearance
3935 :type 'boolean)
3937 (defcustom org-hide-leading-stars nil
3938 "Non-nil means hide the first N-1 stars in a headline.
3939 This works by using the face `org-hide' for these stars. This
3940 face is white for a light background, and black for a dark
3941 background. You may have to customize the face `org-hide' to
3942 make this work.
3943 Changing it requires restart of `font-lock-mode' to become effective
3944 also in regions already fontified.
3945 You may also set this on a per-file basis by adding one of the following
3946 lines to the buffer:
3948 #+STARTUP: hidestars
3949 #+STARTUP: showstars"
3950 :group 'org-appearance
3951 :type 'boolean)
3953 (defcustom org-hidden-keywords nil
3954 "List of symbols corresponding to keywords to be hidden the org buffer.
3955 For example, a value '(title) for this list will make the document's title
3956 appear in the buffer without the initial #+TITLE: keyword."
3957 :group 'org-appearance
3958 :version "24.1"
3959 :type '(set (const :tag "#+AUTHOR" author)
3960 (const :tag "#+DATE" date)
3961 (const :tag "#+EMAIL" email)
3962 (const :tag "#+TITLE" title)))
3964 (defcustom org-custom-properties nil
3965 "List of properties (as strings) with a special meaning.
3966 The default use of these custom properties is to let the user
3967 hide them with `org-toggle-custom-properties-visibility'."
3968 :group 'org-properties
3969 :group 'org-appearance
3970 :version "24.3"
3971 :type '(repeat (string :tag "Property Name")))
3973 (defcustom org-fontify-done-headline nil
3974 "Non-nil means change the face of a headline if it is marked DONE.
3975 Normally, only the TODO/DONE keyword indicates the state of a headline.
3976 When this is non-nil, the headline after the keyword is set to the
3977 `org-headline-done' as an additional indication."
3978 :group 'org-appearance
3979 :type 'boolean)
3981 (defcustom org-fontify-emphasized-text t
3982 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3983 Changing this variable requires a restart of Emacs to take effect."
3984 :group 'org-appearance
3985 :type 'boolean)
3987 (defcustom org-fontify-whole-heading-line nil
3988 "Non-nil means fontify the whole line for headings.
3989 This is useful when setting a background color for the
3990 org-level-* faces."
3991 :group 'org-appearance
3992 :type 'boolean)
3994 (defcustom org-highlight-latex-and-related nil
3995 "Non-nil means highlight LaTeX related syntax in the buffer.
3996 When non nil, the value should be a list containing any of the
3997 following symbols:
3998 `latex' Highlight LaTeX snippets and environments.
3999 `script' Highlight subscript and superscript.
4000 `entities' Highlight entities."
4001 :group 'org-appearance
4002 :version "24.4"
4003 :package-version '(Org . "8.0")
4004 :type '(choice
4005 (const :tag "No highlighting" nil)
4006 (set :greedy t :tag "Highlight"
4007 (const :tag "LaTeX snippets and environments" latex)
4008 (const :tag "Subscript and superscript" script)
4009 (const :tag "Entities" entities))))
4011 (defcustom org-hide-emphasis-markers nil
4012 "Non-nil mean font-lock should hide the emphasis marker characters."
4013 :group 'org-appearance
4014 :type 'boolean)
4016 (defcustom org-pretty-entities nil
4017 "Non-nil means show entities as UTF8 characters.
4018 When nil, the \\name form remains in the buffer."
4019 :group 'org-appearance
4020 :version "24.1"
4021 :type 'boolean)
4023 (defcustom org-pretty-entities-include-sub-superscripts t
4024 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4025 :group 'org-appearance
4026 :version "24.1"
4027 :type 'boolean)
4029 (defvar org-emph-re nil
4030 "Regular expression for matching emphasis.
4031 After a match, the match groups contain these elements:
4032 0 The match of the full regular expression, including the characters
4033 before and after the proper match
4034 1 The character before the proper match, or empty at beginning of line
4035 2 The proper match, including the leading and trailing markers
4036 3 The leading marker like * or /, indicating the type of highlighting
4037 4 The text between the emphasis markers, not including the markers
4038 5 The character after the match, empty at the end of a line")
4039 (defvar org-verbatim-re nil
4040 "Regular expression for matching verbatim text.")
4041 (defvar org-emphasis-regexp-components) ; defined just below
4042 (defvar org-emphasis-alist) ; defined just below
4043 (defun org-set-emph-re (var val)
4044 "Set variable and compute the emphasis regular expression."
4045 (set var val)
4046 (when (and (boundp 'org-emphasis-alist)
4047 (boundp 'org-emphasis-regexp-components)
4048 org-emphasis-alist org-emphasis-regexp-components)
4049 (let* ((e org-emphasis-regexp-components)
4050 (pre (car e))
4051 (post (nth 1 e))
4052 (border (nth 2 e))
4053 (body (nth 3 e))
4054 (nl (nth 4 e))
4055 (body1 (concat body "*?"))
4056 (markers (mapconcat 'car org-emphasis-alist ""))
4057 (vmarkers (mapconcat
4058 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4059 org-emphasis-alist "")))
4060 ;; make sure special characters appear at the right position in the class
4061 (if (string-match "\\^" markers)
4062 (setq markers (concat (replace-match "" t t markers) "^")))
4063 (if (string-match "-" markers)
4064 (setq markers (concat (replace-match "" t t markers) "-")))
4065 (if (string-match "\\^" vmarkers)
4066 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4067 (if (string-match "-" vmarkers)
4068 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4069 (if (> nl 0)
4070 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4071 (int-to-string nl) "\\}")))
4072 ;; Make the regexp
4073 (setq org-emph-re
4074 (concat "\\([" pre "]\\|^\\)"
4075 "\\("
4076 "\\([" markers "]\\)"
4077 "\\("
4078 "[^" border "]\\|"
4079 "[^" border "]"
4080 body1
4081 "[^" border "]"
4082 "\\)"
4083 "\\3\\)"
4084 "\\([" post "]\\|$\\)"))
4085 (setq org-verbatim-re
4086 (concat "\\([" pre "]\\|^\\)"
4087 "\\("
4088 "\\([" vmarkers "]\\)"
4089 "\\("
4090 "[^" border "]\\|"
4091 "[^" border "]"
4092 body1
4093 "[^" border "]"
4094 "\\)"
4095 "\\3\\)"
4096 "\\([" post "]\\|$\\)")))))
4098 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4099 ;; set this option proved cumbersome. See this message/thread:
4100 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4101 (defvar org-emphasis-regexp-components
4102 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4103 "Components used to build the regular expression for emphasis.
4104 This is a list with five entries. Terminology: In an emphasis string
4105 like \" *strong word* \", we call the initial space PREMATCH, the final
4106 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4107 and \"trong wor\" is the body. The different components in this variable
4108 specify what is allowed/forbidden in each part:
4110 pre Chars allowed as prematch. Beginning of line will be allowed too.
4111 post Chars allowed as postmatch. End of line will be allowed too.
4112 border The chars *forbidden* as border characters.
4113 body-regexp A regexp like \".\" to match a body character. Don't use
4114 non-shy groups here, and don't allow newline here.
4115 newline The maximum number of newlines allowed in an emphasis exp.
4117 You need to reload Org or to restart Emacs after customizing this.")
4119 (defcustom org-emphasis-alist
4120 `(("*" bold)
4121 ("/" italic)
4122 ("_" underline)
4123 ("=" org-code verbatim)
4124 ("~" org-verbatim verbatim)
4125 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4126 "Alist of characters and faces to emphasize text.
4127 Text starting and ending with a special character will be emphasized,
4128 for example *bold*, _underlined_ and /italic/. This variable sets the
4129 marker characters and the face to be used by font-lock for highlighting
4130 in Org-mode Emacs buffers.
4132 You need to reload Org or to restart Emacs after customizing this."
4133 :group 'org-appearance
4134 :set 'org-set-emph-re
4135 :version "24.4"
4136 :package-version '(Org . "8.0")
4137 :type '(repeat
4138 (list
4139 (string :tag "Marker character")
4140 (choice
4141 (face :tag "Font-lock-face")
4142 (plist :tag "Face property list"))
4143 (option (const verbatim)))))
4145 (defvar org-protecting-blocks
4146 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4147 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4148 This is needed for font-lock setup.")
4150 ;;; Miscellaneous options
4152 (defgroup org-completion nil
4153 "Completion in Org-mode."
4154 :tag "Org Completion"
4155 :group 'org)
4157 (defcustom org-completion-use-ido nil
4158 "Non-nil means use ido completion wherever possible.
4159 Note that `ido-mode' must be active for this variable to be relevant.
4160 If you decide to turn this variable on, you might well want to turn off
4161 `org-outline-path-complete-in-steps'.
4162 See also `org-completion-use-iswitchb'."
4163 :group 'org-completion
4164 :type 'boolean)
4166 (defcustom org-completion-use-iswitchb nil
4167 "Non-nil means use iswitchb completion wherever possible.
4168 Note that `iswitchb-mode' must be active for this variable to be relevant.
4169 If you decide to turn this variable on, you might well want to turn off
4170 `org-outline-path-complete-in-steps'.
4171 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4172 :group 'org-completion
4173 :type 'boolean)
4175 (defcustom org-completion-fallback-command 'hippie-expand
4176 "The expansion command called by \\[pcomplete] in normal context.
4177 Normal means, no org-mode-specific context."
4178 :group 'org-completion
4179 :type 'function)
4181 ;;; Functions and variables from their packages
4182 ;; Declared here to avoid compiler warnings
4184 ;; XEmacs only
4185 (defvar outline-mode-menu-heading)
4186 (defvar outline-mode-menu-show)
4187 (defvar outline-mode-menu-hide)
4188 (defvar zmacs-regions) ; XEmacs regions
4190 ;; Emacs only
4191 (defvar mark-active)
4193 ;; Various packages
4194 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4195 (declare-function calendar-forward-day "cal-move" (arg))
4196 (declare-function calendar-goto-date "cal-move" (date))
4197 (declare-function calendar-goto-today "cal-move" ())
4198 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4199 (defvar calc-embedded-close-formula)
4200 (defvar calc-embedded-open-formula)
4201 (declare-function cdlatex-tab "ext:cdlatex" ())
4202 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4203 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4204 (defvar font-lock-unfontify-region-function)
4205 (declare-function iswitchb-read-buffer "iswitchb"
4206 (prompt &optional default require-match start matches-set))
4207 (defvar iswitchb-temp-buflist)
4208 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4209 (defvar org-agenda-tags-todo-honor-ignore-options)
4210 (declare-function org-agenda-skip "org-agenda" ())
4211 (declare-function
4212 org-agenda-format-item "org-agenda"
4213 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4214 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4215 (declare-function org-agenda-change-all-lines "org-agenda"
4216 (newhead hdmarker &optional fixface just-this))
4217 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4218 (declare-function org-agenda-maybe-redo "org-agenda" ())
4219 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4220 (beg end))
4221 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4222 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4223 "org-agenda" (&optional end))
4224 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4225 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4226 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4227 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4228 (declare-function org-indent-mode "org-indent" (&optional arg))
4229 (declare-function parse-time-string "parse-time" (string))
4230 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4231 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4232 (defvar remember-data-file)
4233 (defvar texmathp-why)
4234 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4235 (declare-function table--at-cell-p "table" (position &optional object at-column))
4237 (defvar org-latex-regexps)
4239 ;;; Autoload and prepare some org modules
4241 ;; Some table stuff that needs to be defined here, because it is used
4242 ;; by the functions setting up org-mode or checking for table context.
4244 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4245 "Detect an org-type or table-type table.")
4246 (defconst org-table-line-regexp "^[ \t]*|"
4247 "Detect an org-type table line.")
4248 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4249 "Detect an org-type table line.")
4250 (defconst org-table-hline-regexp "^[ \t]*|-"
4251 "Detect an org-type table hline.")
4252 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4253 "Detect a table-type table hline.")
4254 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4255 "Detect the first line outside a table when searching from within it.
4256 This works for both table types.")
4258 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4259 "Detect a #+TBLFM line.")
4261 ;;;###autoload
4262 (defun turn-on-orgtbl ()
4263 "Unconditionally turn on `orgtbl-mode'."
4264 (require 'org-table)
4265 (orgtbl-mode 1))
4267 (defun org-at-table-p (&optional table-type)
4268 "Return t if the cursor is inside an org-type table.
4269 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4270 (if org-enable-table-editor
4271 (save-excursion
4272 (beginning-of-line 1)
4273 (looking-at (if table-type org-table-any-line-regexp
4274 org-table-line-regexp)))
4275 nil))
4276 (defsubst org-table-p () (org-at-table-p))
4278 (defun org-at-table.el-p ()
4279 "Return t if and only if we are at a table.el table."
4280 (and (org-at-table-p 'any)
4281 (save-excursion
4282 (goto-char (org-table-begin 'any))
4283 (looking-at org-table1-hline-regexp))))
4285 (defun org-table-recognize-table.el ()
4286 "If there is a table.el table nearby, recognize it and move into it."
4287 (if org-table-tab-recognizes-table.el
4288 (if (org-at-table.el-p)
4289 (progn
4290 (beginning-of-line 1)
4291 (if (looking-at org-table-dataline-regexp)
4293 (if (looking-at org-table1-hline-regexp)
4294 (progn
4295 (beginning-of-line 2)
4296 (if (looking-at org-table-any-border-regexp)
4297 (beginning-of-line -1)))))
4298 (if (re-search-forward "|" (org-table-end t) t)
4299 (progn
4300 (require 'table)
4301 (if (table--at-cell-p (point))
4303 (message "recognizing table.el table...")
4304 (table-recognize-table)
4305 (message "recognizing table.el table...done")))
4306 (error "This should not happen"))
4308 nil)
4309 nil))
4311 (defun org-at-table-hline-p ()
4312 "Return t if the cursor is inside a hline in a table."
4313 (if org-enable-table-editor
4314 (save-excursion
4315 (beginning-of-line 1)
4316 (looking-at org-table-hline-regexp))
4317 nil))
4319 (defun org-table-map-tables (function &optional quietly)
4320 "Apply FUNCTION to the start of all tables in the buffer."
4321 (save-excursion
4322 (save-restriction
4323 (widen)
4324 (goto-char (point-min))
4325 (while (re-search-forward org-table-any-line-regexp nil t)
4326 (unless quietly
4327 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4328 (beginning-of-line 1)
4329 (when (and (looking-at org-table-line-regexp)
4330 ;; Exclude tables in src/example/verbatim/clocktable blocks
4331 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4332 (save-excursion (funcall function))
4333 (or (looking-at org-table-line-regexp)
4334 (forward-char 1)))
4335 (re-search-forward org-table-any-border-regexp nil 1))))
4336 (unless quietly (message "Mapping tables: done")))
4338 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4339 (declare-function org-clock-update-mode-line "org-clock" ())
4340 (declare-function org-resolve-clocks "org-clock"
4341 (&optional also-non-dangling-p prompt last-valid))
4343 (defun org-at-TBLFM-p (&optional pos)
4344 "Return t when point (or POS) is in #+TBLFM line."
4345 (save-excursion
4346 (let ((pos pos)))
4347 (goto-char (or pos (point)))
4348 (beginning-of-line 1)
4349 (looking-at org-TBLFM-regexp)))
4351 (defvar org-clock-start-time)
4352 (defvar org-clock-marker (make-marker)
4353 "Marker recording the last clock-in.")
4354 (defvar org-clock-hd-marker (make-marker)
4355 "Marker recording the last clock-in, but the headline position.")
4356 (defvar org-clock-heading ""
4357 "The heading of the current clock entry.")
4358 (defun org-clock-is-active ()
4359 "Return the buffer where the clock is currently running.
4360 Return nil if no clock is running."
4361 (marker-buffer org-clock-marker))
4363 (defun org-check-running-clock ()
4364 "Check if the current buffer contains the running clock.
4365 If yes, offer to stop it and to save the buffer with the changes."
4366 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4367 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4368 (buffer-name))))
4369 (org-clock-out)
4370 (when (y-or-n-p "Save changed buffer?")
4371 (save-buffer))))
4373 (defun org-clocktable-try-shift (dir n)
4374 "Check if this line starts a clock table, if yes, shift the time block."
4375 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4376 (org-clocktable-shift dir n)))
4378 ;;;###autoload
4379 (defun org-clock-persistence-insinuate ()
4380 "Set up hooks for clock persistence."
4381 (require 'org-clock)
4382 (add-hook 'org-mode-hook 'org-clock-load)
4383 (add-hook 'kill-emacs-hook 'org-clock-save))
4385 (defgroup org-archive nil
4386 "Options concerning archiving in Org-mode."
4387 :tag "Org Archive"
4388 :group 'org-structure)
4390 (defcustom org-archive-location "%s_archive::"
4391 "The location where subtrees should be archived.
4393 The value of this variable is a string, consisting of two parts,
4394 separated by a double-colon. The first part is a filename and
4395 the second part is a headline.
4397 When the filename is omitted, archiving happens in the same file.
4398 %s in the filename will be replaced by the current file
4399 name (without the directory part). Archiving to a different file
4400 is useful to keep archived entries from contributing to the
4401 Org-mode Agenda.
4403 The archived entries will be filed as subtrees of the specified
4404 headline. When the headline is omitted, the subtrees are simply
4405 filed away at the end of the file, as top-level entries. Also in
4406 the heading you can use %s to represent the file name, this can be
4407 useful when using the same archive for a number of different files.
4409 Here are a few examples:
4410 \"%s_archive::\"
4411 If the current file is Projects.org, archive in file
4412 Projects.org_archive, as top-level trees. This is the default.
4414 \"::* Archived Tasks\"
4415 Archive in the current file, under the top-level headline
4416 \"* Archived Tasks\".
4418 \"~/org/archive.org::\"
4419 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4421 \"~/org/archive.org::* From %s\"
4422 Archive in file ~/org/archive.org (absolute path), under headlines
4423 \"From FILENAME\" where file name is the current file name.
4425 \"~/org/datetree.org::datetree/* Finished Tasks\"
4426 The \"datetree/\" string is special, signifying to archive
4427 items to the datetree. Items are placed in either the CLOSED
4428 date of the item, or the current date if there is no CLOSED date.
4429 The heading will be a subentry to the current date. There doesn't
4430 need to be a heading, but there always needs to be a slash after
4431 datetree. For example, to store archived items directly in the
4432 datetree, use \"~/org/datetree.org::datetree/\".
4434 \"basement::** Finished Tasks\"
4435 Archive in file ./basement (relative path), as level 3 trees
4436 below the level 2 heading \"** Finished Tasks\".
4438 You may set this option on a per-file basis by adding to the buffer a
4439 line like
4441 #+ARCHIVE: basement::** Finished Tasks
4443 You may also define it locally for a subtree by setting an ARCHIVE property
4444 in the entry. If such a property is found in an entry, or anywhere up
4445 the hierarchy, it will be used."
4446 :group 'org-archive
4447 :type 'string)
4449 (defcustom org-archive-tag "ARCHIVE"
4450 "The tag that marks a subtree as archived.
4451 An archived subtree does not open during visibility cycling, and does
4452 not contribute to the agenda listings.
4453 After changing this, font-lock must be restarted in the relevant buffers to
4454 get the proper fontification."
4455 :group 'org-archive
4456 :group 'org-keywords
4457 :type 'string)
4459 (defcustom org-agenda-skip-archived-trees t
4460 "Non-nil means the agenda will skip any items located in archived trees.
4461 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4462 variable is no longer recommended, you should leave it at the value t.
4463 Instead, use the key `v' to cycle the archives-mode in the agenda."
4464 :group 'org-archive
4465 :group 'org-agenda-skip
4466 :type 'boolean)
4468 (defcustom org-columns-skip-archived-trees t
4469 "Non-nil means ignore archived trees when creating column view."
4470 :group 'org-archive
4471 :group 'org-properties
4472 :type 'boolean)
4474 (defcustom org-cycle-open-archived-trees nil
4475 "Non-nil means `org-cycle' will open archived trees.
4476 An archived tree is a tree marked with the tag ARCHIVE.
4477 When nil, archived trees will stay folded. You can still open them with
4478 normal outline commands like `show-all', but not with the cycling commands."
4479 :group 'org-archive
4480 :group 'org-cycle
4481 :type 'boolean)
4483 (defcustom org-sparse-tree-open-archived-trees nil
4484 "Non-nil means sparse tree construction shows matches in archived trees.
4485 When nil, matches in these trees are highlighted, but the trees are kept in
4486 collapsed state."
4487 :group 'org-archive
4488 :group 'org-sparse-trees
4489 :type 'boolean)
4491 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4492 "The default date type when building a sparse tree.
4493 When this is nil, a date is a scheduled or a deadline timestamp.
4494 Otherwise, these types are allowed:
4496 all: all timestamps
4497 active: only active timestamps (<...>)
4498 inactive: only inactive timestamps (<...)
4499 scheduled: only scheduled timestamps
4500 deadline: only deadline timestamps"
4501 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4502 (const :tag "All timestamps" all)
4503 (const :tag "Only active timestamps" active)
4504 (const :tag "Only inactive timestamps" inactive)
4505 (const :tag "Only scheduled timestamps" scheduled)
4506 (const :tag "Only deadline timestamps" deadline)
4507 (const :tag "Only closed timestamps" closed))
4508 :version "24.3"
4509 :group 'org-sparse-trees)
4511 (defun org-cycle-hide-archived-subtrees (state)
4512 "Re-hide all archived subtrees after a visibility state change."
4513 (when (and (not org-cycle-open-archived-trees)
4514 (not (memq state '(overview folded))))
4515 (save-excursion
4516 (let* ((globalp (memq state '(contents all)))
4517 (beg (if globalp (point-min) (point)))
4518 (end (if globalp (point-max) (org-end-of-subtree t))))
4519 (org-hide-archived-subtrees beg end)
4520 (goto-char beg)
4521 (if (looking-at (concat ".*:" org-archive-tag ":"))
4522 (message "%s" (substitute-command-keys
4523 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4525 (defun org-force-cycle-archived ()
4526 "Cycle subtree even if it is archived."
4527 (interactive)
4528 (setq this-command 'org-cycle)
4529 (let ((org-cycle-open-archived-trees t))
4530 (call-interactively 'org-cycle)))
4532 (defun org-hide-archived-subtrees (beg end)
4533 "Re-hide all archived subtrees after a visibility state change."
4534 (save-excursion
4535 (let* ((re (concat ":" org-archive-tag ":")))
4536 (goto-char beg)
4537 (while (re-search-forward re end t)
4538 (when (org-at-heading-p)
4539 (org-flag-subtree t)
4540 (org-end-of-subtree t))))))
4542 (declare-function outline-end-of-heading "outline" ())
4543 (declare-function outline-flag-region "outline" (from to flag))
4544 (defun org-flag-subtree (flag)
4545 (save-excursion
4546 (org-back-to-heading t)
4547 (outline-end-of-heading)
4548 (outline-flag-region (point)
4549 (progn (org-end-of-subtree t) (point))
4550 flag)))
4552 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4554 ;; Declare Column View Code
4556 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4557 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4558 (declare-function org-columns-compute "org-colview" (property))
4560 ;; Declare ID code
4562 (declare-function org-id-store-link "org-id")
4563 (declare-function org-id-locations-load "org-id")
4564 (declare-function org-id-locations-save "org-id")
4565 (defvar org-id-track-globally)
4567 ;;; Variables for pre-computed regular expressions, all buffer local
4569 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4570 "Matches first line of a hidden block.")
4571 (make-variable-buffer-local 'org-drawer-regexp)
4572 (defvar org-todo-regexp nil
4573 "Matches any of the TODO state keywords.")
4574 (make-variable-buffer-local 'org-todo-regexp)
4575 (defvar org-not-done-regexp nil
4576 "Matches any of the TODO state keywords except the last one.")
4577 (make-variable-buffer-local 'org-not-done-regexp)
4578 (defvar org-not-done-heading-regexp nil
4579 "Matches a TODO headline that is not done.")
4580 (make-variable-buffer-local 'org-not-done-regexp)
4581 (defvar org-todo-line-regexp nil
4582 "Matches a headline and puts TODO state into group 2 if present.")
4583 (make-variable-buffer-local 'org-todo-line-regexp)
4584 (defvar org-complex-heading-regexp nil
4585 "Matches a headline and puts everything into groups:
4586 group 1: the stars
4587 group 2: The todo keyword, maybe
4588 group 3: Priority cookie
4589 group 4: True headline
4590 group 5: Tags")
4591 (make-variable-buffer-local 'org-complex-heading-regexp)
4592 (defvar org-complex-heading-regexp-format nil
4593 "Printf format to make regexp to match an exact headline.
4594 This regexp will match the headline of any node which has the
4595 exact headline text that is put into the format, but may have any
4596 TODO state, priority and tags.")
4597 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4598 (defvar org-todo-line-tags-regexp nil
4599 "Matches a headline and puts TODO state into group 2 if present.
4600 Also put tags into group 4 if tags are present.")
4601 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4602 (defvar org-ds-keyword-length 12
4603 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4604 (make-variable-buffer-local 'org-ds-keyword-length)
4605 (defvar org-deadline-regexp nil
4606 "Matches the DEADLINE keyword.")
4607 (make-variable-buffer-local 'org-deadline-regexp)
4608 (defvar org-deadline-time-regexp nil
4609 "Matches the DEADLINE keyword together with a time stamp.")
4610 (make-variable-buffer-local 'org-deadline-time-regexp)
4611 (defvar org-deadline-time-hour-regexp nil
4612 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4613 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4614 (defvar org-deadline-line-regexp nil
4615 "Matches the DEADLINE keyword and the rest of the line.")
4616 (make-variable-buffer-local 'org-deadline-line-regexp)
4617 (defvar org-scheduled-regexp nil
4618 "Matches the SCHEDULED keyword.")
4619 (make-variable-buffer-local 'org-scheduled-regexp)
4620 (defvar org-scheduled-time-regexp nil
4621 "Matches the SCHEDULED keyword together with a time stamp.")
4622 (make-variable-buffer-local 'org-scheduled-time-regexp)
4623 (defvar org-scheduled-time-hour-regexp nil
4624 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4625 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4626 (defvar org-closed-time-regexp nil
4627 "Matches the CLOSED keyword together with a time stamp.")
4628 (make-variable-buffer-local 'org-closed-time-regexp)
4630 (defvar org-keyword-time-regexp nil
4631 "Matches any of the 4 keywords, together with the time stamp.")
4632 (make-variable-buffer-local 'org-keyword-time-regexp)
4633 (defvar org-keyword-time-not-clock-regexp nil
4634 "Matches any of the 3 keywords, together with the time stamp.")
4635 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4636 (defvar org-maybe-keyword-time-regexp nil
4637 "Matches a timestamp, possibly preceded by a keyword.")
4638 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4639 (defvar org-all-time-keywords nil
4640 "List of time keywords.")
4641 (make-variable-buffer-local 'org-all-time-keywords)
4643 (defconst org-plain-time-of-day-regexp
4644 (concat
4645 "\\(\\<[012]?[0-9]"
4646 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4647 "\\(--?"
4648 "\\(\\<[012]?[0-9]"
4649 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4650 "\\)?")
4651 "Regular expression to match a plain time or time range.
4652 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4653 groups carry important information:
4654 0 the full match
4655 1 the first time, range or not
4656 8 the second time, if it is a range.")
4658 (defconst org-plain-time-extension-regexp
4659 (concat
4660 "\\(\\<[012]?[0-9]"
4661 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4662 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4663 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4664 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4665 groups carry important information:
4666 0 the full match
4667 7 hours of duration
4668 9 minutes of duration")
4670 (defconst org-stamp-time-of-day-regexp
4671 (concat
4672 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4673 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4674 "\\(--?"
4675 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4676 "Regular expression to match a timestamp time or time range.
4677 After a match, the following groups carry important information:
4678 0 the full match
4679 1 date plus weekday, for back referencing to make sure both times are on the same day
4680 2 the first time, range or not
4681 4 the second time, if it is a range.")
4683 (defconst org-startup-options
4684 '(("fold" org-startup-folded t)
4685 ("overview" org-startup-folded t)
4686 ("nofold" org-startup-folded nil)
4687 ("showall" org-startup-folded nil)
4688 ("showeverything" org-startup-folded showeverything)
4689 ("content" org-startup-folded content)
4690 ("indent" org-startup-indented t)
4691 ("noindent" org-startup-indented nil)
4692 ("hidestars" org-hide-leading-stars t)
4693 ("showstars" org-hide-leading-stars nil)
4694 ("odd" org-odd-levels-only t)
4695 ("oddeven" org-odd-levels-only nil)
4696 ("align" org-startup-align-all-tables t)
4697 ("noalign" org-startup-align-all-tables nil)
4698 ("inlineimages" org-startup-with-inline-images t)
4699 ("noinlineimages" org-startup-with-inline-images nil)
4700 ("latexpreview" org-startup-with-latex-preview t)
4701 ("nolatexpreview" org-startup-with-latex-preview nil)
4702 ("customtime" org-display-custom-times t)
4703 ("logdone" org-log-done time)
4704 ("lognotedone" org-log-done note)
4705 ("nologdone" org-log-done nil)
4706 ("lognoteclock-out" org-log-note-clock-out t)
4707 ("nolognoteclock-out" org-log-note-clock-out nil)
4708 ("logrepeat" org-log-repeat state)
4709 ("lognoterepeat" org-log-repeat note)
4710 ("logdrawer" org-log-into-drawer t)
4711 ("nologdrawer" org-log-into-drawer nil)
4712 ("logstatesreversed" org-log-states-order-reversed t)
4713 ("nologstatesreversed" org-log-states-order-reversed nil)
4714 ("nologrepeat" org-log-repeat nil)
4715 ("logreschedule" org-log-reschedule time)
4716 ("lognotereschedule" org-log-reschedule note)
4717 ("nologreschedule" org-log-reschedule nil)
4718 ("logredeadline" org-log-redeadline time)
4719 ("lognoteredeadline" org-log-redeadline note)
4720 ("nologredeadline" org-log-redeadline nil)
4721 ("logrefile" org-log-refile time)
4722 ("lognoterefile" org-log-refile note)
4723 ("nologrefile" org-log-refile nil)
4724 ("fninline" org-footnote-define-inline t)
4725 ("nofninline" org-footnote-define-inline nil)
4726 ("fnlocal" org-footnote-section nil)
4727 ("fnauto" org-footnote-auto-label t)
4728 ("fnprompt" org-footnote-auto-label nil)
4729 ("fnconfirm" org-footnote-auto-label confirm)
4730 ("fnplain" org-footnote-auto-label plain)
4731 ("fnadjust" org-footnote-auto-adjust t)
4732 ("nofnadjust" org-footnote-auto-adjust nil)
4733 ("constcgs" constants-unit-system cgs)
4734 ("constSI" constants-unit-system SI)
4735 ("noptag" org-tag-persistent-alist nil)
4736 ("hideblocks" org-hide-block-startup t)
4737 ("nohideblocks" org-hide-block-startup nil)
4738 ("beamer" org-startup-with-beamer-mode t)
4739 ("entitiespretty" org-pretty-entities t)
4740 ("entitiesplain" org-pretty-entities nil))
4741 "Variable associated with STARTUP options for org-mode.
4742 Each element is a list of three items: the startup options (as written
4743 in the #+STARTUP line), the corresponding variable, and the value to set
4744 this variable to if the option is found. An optional forth element PUSH
4745 means to push this value onto the list in the variable.")
4747 (defun org-update-property-plist (key val props)
4748 "Update PROPS with KEY and VAL."
4749 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4750 (key (if appending (substring key 0 (- (length key) 1)) key))
4751 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4752 (previous (cdr (assoc key props))))
4753 (if appending
4754 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4755 (cons (cons key val) remainder))))
4757 (defconst org-block-regexp
4758 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4759 "Regular expression for hiding blocks.")
4760 (defconst org-heading-keyword-regexp-format
4761 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4762 "Printf format for a regexp matching a headline with some keyword.
4763 This regexp will match the headline of any node which has the
4764 exact keyword that is put into the format. The keyword isn't in
4765 any group by default, but the stars and the body are.")
4766 (defconst org-heading-keyword-maybe-regexp-format
4767 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4768 "Printf format for a regexp matching a headline, possibly with some keyword.
4769 This regexp can match any headline with the specified keyword, or
4770 without a keyword. The keyword isn't in any group by default,
4771 but the stars and the body are.")
4773 (defcustom org-group-tags t
4774 "When non-nil (the default), use group tags.
4775 This can be turned on/off through `org-toggle-tags-groups'."
4776 :group 'org-tags
4777 :group 'org-startup
4778 :type 'boolean)
4780 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4782 (defun org-toggle-tags-groups ()
4783 "Toggle support for group tags.
4784 Support for group tags is controlled by the option
4785 `org-group-tags', which is non-nil by default."
4786 (interactive)
4787 (setq org-group-tags (not org-group-tags))
4788 (cond ((and (derived-mode-p 'org-agenda-mode)
4789 org-group-tags)
4790 (org-agenda-redo))
4791 ((derived-mode-p 'org-mode)
4792 (let ((org-inhibit-startup t)) (org-mode))))
4793 (message "Groups tags support has been turned %s"
4794 (if org-group-tags "on" "off")))
4796 (defun org-set-regexps-and-options-for-tags ()
4797 "Precompute variables used for tags."
4798 (when (derived-mode-p 'org-mode)
4799 (org-set-local 'org-file-tags nil)
4800 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4801 (splitre "[ \t]+")
4802 (start 0)
4803 tags ftags key value)
4804 (save-excursion
4805 (save-restriction
4806 (widen)
4807 (goto-char (point-min))
4808 (while (re-search-forward re nil t)
4809 (setq key (upcase (org-match-string-no-properties 1))
4810 value (org-match-string-no-properties 2))
4811 (if (stringp value) (setq value (org-trim value)))
4812 (cond
4813 ((equal key "TAGS")
4814 (setq tags (append tags (if tags '("\\n") nil)
4815 (org-split-string value splitre))))
4816 ((equal key "FILETAGS")
4817 (when (string-match "\\S-" value)
4818 (setq ftags
4819 (append
4820 ftags
4821 (apply 'append
4822 (mapcar (lambda (x) (org-split-string x ":"))
4823 (org-split-string value)))))))))))
4824 ;; Process the file tags.
4825 (and ftags (org-set-local 'org-file-tags
4826 (mapcar 'org-add-prop-inherited ftags)))
4827 (org-set-local 'org-tag-groups-alist nil)
4828 ;; Process the tags.
4829 (when (and (not tags) org-tag-alist)
4830 (setq tags
4831 (mapcar
4832 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4833 ((eq (car tg) :endgroup) "}")
4834 ((eq (car tg) :grouptags) ":")
4835 ((eq (car tg) :newline) "\n")
4836 (t (concat (car tg)
4837 (if (characterp (cdr tg))
4838 (format "(%s)" (char-to-string (cdr tg))) "")))))
4839 org-tag-alist)))
4840 (let (e tgs g)
4841 (while (setq e (pop tags))
4842 (cond
4843 ((equal e "{")
4844 (progn (push '(:startgroup) tgs)
4845 (when (equal (nth 1 tags) ":")
4846 (push (list (replace-regexp-in-string
4847 "(.+)$" "" (nth 0 tags)))
4848 org-tag-groups-alist)
4849 (setq g 0))))
4850 ((equal e ":") (push '(:grouptags) tgs))
4851 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4852 ((equal e "\\n") (push '(:newline) tgs))
4853 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4854 (push (cons (match-string 1 e)
4855 (string-to-char (match-string 2 e))) tgs)
4856 (if (and g (> g 0))
4857 (setcar org-tag-groups-alist
4858 (append (car org-tag-groups-alist)
4859 (list (match-string 1 e)))))
4860 (if g (setq g (1+ g))))
4861 (t (push (list e) tgs)
4862 (if (and g (> g 0))
4863 (setcar org-tag-groups-alist
4864 (append (car org-tag-groups-alist) (list e))))
4865 (if g (setq g (1+ g))))))
4866 (org-set-local 'org-tag-alist nil)
4867 (while (setq e (pop tgs))
4868 (or (and (stringp (car e))
4869 (assoc (car e) org-tag-alist))
4870 (push e org-tag-alist)))
4871 ;; Return a list with tag variables
4872 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4874 (defvar org-ota nil)
4875 (defun org-set-regexps-and-options ()
4876 "Precompute regular expressions used in the current buffer."
4877 (when (derived-mode-p 'org-mode)
4878 (org-set-local 'org-todo-kwd-alist nil)
4879 (org-set-local 'org-todo-key-alist nil)
4880 (org-set-local 'org-todo-key-trigger nil)
4881 (org-set-local 'org-todo-keywords-1 nil)
4882 (org-set-local 'org-done-keywords nil)
4883 (org-set-local 'org-todo-heads nil)
4884 (org-set-local 'org-todo-sets nil)
4885 (org-set-local 'org-todo-log-states nil)
4886 (org-set-local 'org-file-properties nil)
4887 (let ((re (org-make-options-regexp
4888 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4889 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4890 "SETUPFILE" "OPTIONS")
4891 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4892 (splitre "[ \t]+")
4893 (scripts org-use-sub-superscripts)
4894 kwds kws0 kwsa key log value cat arch const links hw dws
4895 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4896 (start 0))
4897 (save-excursion
4898 (save-restriction
4899 (widen)
4900 (goto-char (point-min))
4901 (while
4902 (or (and
4903 ext-setup-or-nil
4904 (not org-ota)
4905 (let (ret)
4906 (with-temp-buffer
4907 (insert ext-setup-or-nil)
4908 (let ((major-mode 'org-mode) org-ota)
4909 (setq ret (save-match-data
4910 (org-set-regexps-and-options-for-tags)))))
4911 ;; Append setupfile tags to existing tags
4912 (setq org-ota t)
4913 (setq org-file-tags
4914 (delq nil (append org-file-tags (nth 0 ret)))
4915 org-tag-alist
4916 (delq nil (append org-tag-alist (nth 1 ret)))
4917 org-tag-groups-alist
4918 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4919 (and ext-setup-or-nil
4920 (string-match re ext-setup-or-nil start)
4921 (setq start (match-end 0)))
4922 (and (setq ext-setup-or-nil nil start 0)
4923 (re-search-forward re nil t)))
4924 (setq key (upcase (match-string 1 ext-setup-or-nil))
4925 value (org-match-string-no-properties 2 ext-setup-or-nil))
4926 (if (stringp value) (setq value (org-trim value)))
4927 (cond
4928 ((equal key "CATEGORY")
4929 (setq cat value))
4930 ((member key '("SEQ_TODO" "TODO"))
4931 (push (cons 'sequence (org-split-string value splitre)) kwds))
4932 ((equal key "TYP_TODO")
4933 (push (cons 'type (org-split-string value splitre)) kwds))
4934 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4935 ;; general TODO-like setup
4936 (push (cons (intern (downcase (match-string 1 key)))
4937 (org-split-string value splitre)) kwds))
4938 ((equal key "COLUMNS")
4939 (org-set-local 'org-columns-default-format value))
4940 ((equal key "LINK")
4941 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4942 (push (cons (match-string 1 value)
4943 (org-trim (match-string 2 value)))
4944 links)))
4945 ((equal key "PRIORITIES")
4946 (setq prio (org-split-string value " +")))
4947 ((equal key "PROPERTY")
4948 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4949 (setq props (org-update-property-plist (match-string 1 value)
4950 (match-string 2 value)
4951 props))))
4952 ((equal key "DRAWERS")
4953 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4954 ((equal key "CONSTANTS")
4955 (org-table-set-constants))
4956 ((equal key "STARTUP")
4957 (let ((opts (org-split-string value splitre))
4958 l var val)
4959 (while (setq l (pop opts))
4960 (when (setq l (assoc l org-startup-options))
4961 (setq var (nth 1 l) val (nth 2 l))
4962 (if (not (nth 3 l))
4963 (set (make-local-variable var) val)
4964 (if (not (listp (symbol-value var)))
4965 (set (make-local-variable var) nil))
4966 (set (make-local-variable var) (symbol-value var))
4967 (add-to-list var val))))))
4968 ((equal key "ARCHIVE")
4969 (setq arch value)
4970 (remove-text-properties 0 (length arch)
4971 '(face t fontified t) arch))
4972 ((equal key "OPTIONS")
4973 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4974 (setq scripts (read (match-string 2 value)))))
4975 ((and (equal key "SETUPFILE")
4976 ;; Prevent checking in Gnus messages
4977 (not buffer-read-only))
4978 (setq setup-contents (org-file-contents
4979 (expand-file-name
4980 (org-remove-double-quotes value))
4981 'noerror))
4982 (if (not ext-setup-or-nil)
4983 (setq ext-setup-or-nil setup-contents start 0)
4984 (setq ext-setup-or-nil
4985 (concat (substring ext-setup-or-nil 0 start)
4986 "\n" setup-contents "\n"
4987 (substring ext-setup-or-nil start)))))))
4988 ;; search for property blocks
4989 (goto-char (point-min))
4990 (while (re-search-forward org-block-regexp nil t)
4991 (when (equal "PROPERTY" (upcase (match-string 1)))
4992 (setq value (replace-regexp-in-string
4993 "[\n\r]" " " (match-string 4)))
4994 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4995 (setq props (org-update-property-plist (match-string 1 value)
4996 (match-string 2 value)
4997 props)))))))
4998 (org-set-local 'org-use-sub-superscripts scripts)
4999 (when cat
5000 (org-set-local 'org-category (intern cat))
5001 (push (cons "CATEGORY" cat) props))
5002 (when prio
5003 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5004 (setq prio (mapcar 'string-to-char prio))
5005 (org-set-local 'org-highest-priority (nth 0 prio))
5006 (org-set-local 'org-lowest-priority (nth 1 prio))
5007 (org-set-local 'org-default-priority (nth 2 prio)))
5008 (and props (org-set-local 'org-file-properties (nreverse props)))
5009 (and drawers (org-set-local 'org-drawers drawers))
5010 (and arch (org-set-local 'org-archive-location arch))
5011 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5012 ;; Process the TODO keywords
5013 (unless kwds
5014 ;; Use the global values as if they had been given locally.
5015 (setq kwds (default-value 'org-todo-keywords))
5016 (if (stringp (car kwds))
5017 (setq kwds (list (cons org-todo-interpretation
5018 (default-value 'org-todo-keywords)))))
5019 (setq kwds (reverse kwds)))
5020 (setq kwds (nreverse kwds))
5021 (let (inter kws kw)
5022 (while (setq kws (pop kwds))
5023 (let ((kws (or
5024 (run-hook-with-args-until-success
5025 'org-todo-setup-filter-hook kws)
5026 kws)))
5027 (setq inter (pop kws) sep (member "|" kws)
5028 kws0 (delete "|" (copy-sequence kws))
5029 kwsa nil
5030 kws1 (mapcar
5031 (lambda (x)
5032 ;; 1 2
5033 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5034 (progn
5035 (setq kw (match-string 1 x)
5036 key (and (match-end 2) (match-string 2 x))
5037 log (org-extract-log-state-settings x))
5038 (push (cons kw (and key (string-to-char key))) kwsa)
5039 (and log (push log org-todo-log-states))
5041 (error "Invalid TODO keyword %s" x)))
5042 kws0)
5043 kwsa (if kwsa (append '((:startgroup))
5044 (nreverse kwsa)
5045 '((:endgroup))))
5046 hw (car kws1)
5047 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5048 tail (list inter hw (car dws) (org-last dws))))
5049 (add-to-list 'org-todo-heads hw 'append)
5050 (push kws1 org-todo-sets)
5051 (setq org-done-keywords (append org-done-keywords dws nil))
5052 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5053 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5054 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5055 (setq org-todo-sets (nreverse org-todo-sets)
5056 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5057 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5058 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5059 ;; Compute the regular expressions and other local variables.
5060 ;; Using `org-outline-regexp-bol' would complicate them much,
5061 ;; because of the fixed white space at the end of that string.
5062 (if (not org-done-keywords)
5063 (setq org-done-keywords (and org-todo-keywords-1
5064 (list (org-last org-todo-keywords-1)))))
5065 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5066 (length org-scheduled-string)
5067 (length org-clock-string)
5068 (length org-closed-string)))
5069 org-drawer-regexp
5070 (concat "^[ \t]*:\\("
5071 (mapconcat 'regexp-quote org-drawers "\\|")
5072 "\\):[ \t]*$")
5073 org-not-done-keywords
5074 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5075 org-todo-regexp
5076 (concat "\\("
5077 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5078 "\\)")
5079 org-not-done-regexp
5080 (concat "\\("
5081 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5082 "\\)")
5083 org-not-done-heading-regexp
5084 (format org-heading-keyword-regexp-format org-not-done-regexp)
5085 org-todo-line-regexp
5086 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5087 org-complex-heading-regexp
5088 (concat "^\\(\\*+\\)"
5089 "\\(?: +" org-todo-regexp "\\)?"
5090 "\\(?: +\\(\\[#.\\]\\)\\)?"
5091 "\\(?: +\\(.*?\\)\\)??"
5092 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5093 "[ \t]*$")
5094 org-complex-heading-regexp-format
5095 (concat "^\\(\\*+\\)"
5096 "\\(?: +" org-todo-regexp "\\)?"
5097 "\\(?: +\\(\\[#.\\]\\)\\)?"
5098 "\\(?: +"
5099 ;; Stats cookies can be stuck to body.
5100 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5101 "\\(%s\\)"
5102 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5103 "\\)"
5104 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5105 "[ \t]*$")
5106 org-todo-line-tags-regexp
5107 (concat "^\\(\\*+\\)"
5108 "\\(?: +" org-todo-regexp "\\)?"
5109 "\\(?: +\\(.*?\\)\\)??"
5110 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5111 "[ \t]*$")
5112 org-deadline-regexp (concat "\\<" org-deadline-string)
5113 org-deadline-time-regexp
5114 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5115 org-deadline-time-hour-regexp
5116 (concat "\\<" org-deadline-string
5117 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5118 org-deadline-line-regexp
5119 (concat "\\<\\(" org-deadline-string "\\).*")
5120 org-scheduled-regexp
5121 (concat "\\<" org-scheduled-string)
5122 org-scheduled-time-regexp
5123 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5124 org-scheduled-time-hour-regexp
5125 (concat "\\<" org-scheduled-string
5126 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5127 org-closed-time-regexp
5128 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5129 org-keyword-time-regexp
5130 (concat "\\<\\(" org-scheduled-string
5131 "\\|" org-deadline-string
5132 "\\|" org-closed-string
5133 "\\|" org-clock-string "\\)"
5134 " *[[<]\\([^]>]+\\)[]>]")
5135 org-keyword-time-not-clock-regexp
5136 (concat "\\<\\(" org-scheduled-string
5137 "\\|" org-deadline-string
5138 "\\|" org-closed-string
5139 "\\)"
5140 " *[[<]\\([^]>]+\\)[]>]")
5141 org-maybe-keyword-time-regexp
5142 (concat "\\(\\<\\(" org-scheduled-string
5143 "\\|" org-deadline-string
5144 "\\|" org-closed-string
5145 "\\|" org-clock-string "\\)\\)?"
5146 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5147 org-all-time-keywords
5148 (mapcar (lambda (w) (substring w 0 -1))
5149 (list org-scheduled-string org-deadline-string
5150 org-clock-string org-closed-string)))
5151 (setq org-ota nil)
5152 (org-compute-latex-and-related-regexp))))
5154 (defun org-file-contents (file &optional noerror)
5155 "Return the contents of FILE, as a string."
5156 (if (or (not file)
5157 (not (file-readable-p file)))
5158 (if noerror
5159 (message "Cannot read file \"%s\"" file)
5160 (error "Cannot read file \"%s\"" file))
5161 (with-temp-buffer
5162 (insert-file-contents file)
5163 (buffer-string))))
5165 (defun org-extract-log-state-settings (x)
5166 "Extract the log state setting from a TODO keyword string.
5167 This will extract info from a string like \"WAIT(w@/!)\"."
5168 (let (kw key log1 log2)
5169 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5170 (setq kw (match-string 1 x)
5171 key (and (match-end 2) (match-string 2 x))
5172 log1 (and (match-end 3) (match-string 3 x))
5173 log2 (and (match-end 4) (match-string 4 x)))
5174 (and (or log1 log2)
5175 (list kw
5176 (and log1 (if (equal log1 "!") 'time 'note))
5177 (and log2 (if (equal log2 "!") 'time 'note)))))))
5179 (defun org-remove-keyword-keys (list)
5180 "Remove a pair of parenthesis at the end of each string in LIST."
5181 (mapcar (lambda (x)
5182 (if (string-match "(.*)$" x)
5183 (substring x 0 (match-beginning 0))
5185 list))
5187 (defun org-assign-fast-keys (alist)
5188 "Assign fast keys to a keyword-key alist.
5189 Respect keys that are already there."
5190 (let (new e (alt ?0))
5191 (while (setq e (pop alist))
5192 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5193 (cdr e)) ;; Key already assigned.
5194 (push e new)
5195 (let ((clist (string-to-list (downcase (car e))))
5196 (used (append new alist)))
5197 (when (= (car clist) ?@)
5198 (pop clist))
5199 (while (and clist (rassoc (car clist) used))
5200 (pop clist))
5201 (unless clist
5202 (while (rassoc alt used)
5203 (incf alt)))
5204 (push (cons (car e) (or (car clist) alt)) new))))
5205 (nreverse new)))
5207 ;;; Some variables used in various places
5209 (defvar org-window-configuration nil
5210 "Used in various places to store a window configuration.")
5211 (defvar org-selected-window nil
5212 "Used in various places to store a window configuration.")
5213 (defvar org-finish-function nil
5214 "Function to be called when `C-c C-c' is used.
5215 This is for getting out of special buffers like capture.")
5218 ;; FIXME: Occasionally check by commenting these, to make sure
5219 ;; no other functions uses these, forgetting to let-bind them.
5220 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5221 (defvar org-last-state)
5222 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5224 ;; Defined somewhere in this file, but used before definition.
5225 (defvar org-entities) ;; defined in org-entities.el
5226 (defvar org-struct-menu)
5227 (defvar org-org-menu)
5228 (defvar org-tbl-menu)
5230 ;;;; Define the Org-mode
5232 ;; We use a before-change function to check if a table might need
5233 ;; an update.
5234 (defvar org-table-may-need-update t
5235 "Indicates that a table might need an update.
5236 This variable is set by `org-before-change-function'.
5237 `org-table-align' sets it back to nil.")
5238 (defun org-before-change-function (beg end)
5239 "Every change indicates that a table might need an update."
5240 (setq org-table-may-need-update t))
5241 (defvar org-mode-map)
5242 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5243 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5244 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5245 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5246 (defvar org-table-buffer-is-an nil)
5248 (defvar bidi-paragraph-direction)
5249 (defvar buffer-face-mode-face)
5251 (require 'outline)
5252 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5253 (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"))
5254 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5256 ;; Other stuff we need.
5257 (require 'time-date)
5258 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5259 (require 'easymenu)
5260 (require 'overlay)
5262 ;; (require 'org-macs) moved higher up in the file before it is first used
5263 (require 'org-entities)
5264 ;; (require 'org-compat) moved higher up in the file before it is first used
5265 (require 'org-faces)
5266 (require 'org-list)
5267 (require 'org-pcomplete)
5268 (require 'org-src)
5269 (require 'org-footnote)
5270 (require 'org-macro)
5272 ;; babel
5273 (require 'ob)
5275 ;;;###autoload
5276 (define-derived-mode org-mode outline-mode "Org"
5277 "Outline-based notes management and organizer, alias
5278 \"Carsten's outline-mode for keeping track of everything.\"
5280 Org-mode develops organizational tasks around a NOTES file which
5281 contains information about projects as plain text. Org-mode is
5282 implemented on top of outline-mode, which is ideal to keep the content
5283 of large files well structured. It supports ToDo items, deadlines and
5284 time stamps, which magically appear in the diary listing of the Emacs
5285 calendar. Tables are easily created with a built-in table editor.
5286 Plain text URL-like links connect to websites, emails (VM), Usenet
5287 messages (Gnus), BBDB entries, and any files related to the project.
5288 For printing and sharing of notes, an Org-mode file (or a part of it)
5289 can be exported as a structured ASCII or HTML file.
5291 The following commands are available:
5293 \\{org-mode-map}"
5295 ;; Get rid of Outline menus, they are not needed
5296 ;; Need to do this here because define-derived-mode sets up
5297 ;; the keymap so late. Still, it is a waste to call this each time
5298 ;; we switch another buffer into org-mode.
5299 (if (featurep 'xemacs)
5300 (when (boundp 'outline-mode-menu-heading)
5301 ;; Assume this is Greg's port, it uses easymenu
5302 (easy-menu-remove outline-mode-menu-heading)
5303 (easy-menu-remove outline-mode-menu-show)
5304 (easy-menu-remove outline-mode-menu-hide))
5305 (define-key org-mode-map [menu-bar headings] 'undefined)
5306 (define-key org-mode-map [menu-bar hide] 'undefined)
5307 (define-key org-mode-map [menu-bar show] 'undefined))
5309 (org-load-modules-maybe)
5310 (easy-menu-add org-org-menu)
5311 (easy-menu-add org-tbl-menu)
5312 (org-install-agenda-files-menu)
5313 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5314 (add-to-invisibility-spec '(org-cwidth))
5315 (add-to-invisibility-spec '(org-hide-block . t))
5316 (when (featurep 'xemacs)
5317 (org-set-local 'line-move-ignore-invisible t))
5318 (org-set-local 'outline-regexp org-outline-regexp)
5319 (org-set-local 'outline-level 'org-outline-level)
5320 (setq bidi-paragraph-direction 'left-to-right)
5321 (when (and org-ellipsis
5322 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5323 (fboundp 'make-glyph-code))
5324 (unless org-display-table
5325 (setq org-display-table (make-display-table)))
5326 (set-display-table-slot
5327 org-display-table 4
5328 (vconcat (mapcar
5329 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5330 org-ellipsis)))
5331 (if (stringp org-ellipsis) org-ellipsis "..."))))
5332 (setq buffer-display-table org-display-table))
5333 (org-set-regexps-and-options-for-tags)
5334 (org-set-regexps-and-options)
5335 (org-set-font-lock-defaults)
5336 (when (and org-tag-faces (not org-tags-special-faces-re))
5337 ;; tag faces set outside customize.... force initialization.
5338 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5339 ;; Calc embedded
5340 (org-set-local 'calc-embedded-open-mode "# ")
5341 ;; Modify a few syntax entries
5342 (modify-syntax-entry ?@ "w")
5343 (modify-syntax-entry ?\" "\"")
5344 (if org-startup-truncated (setq truncate-lines t))
5345 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5346 (org-set-local 'font-lock-unfontify-region-function
5347 'org-unfontify-region)
5348 ;; Activate before-change-function
5349 (org-set-local 'org-table-may-need-update t)
5350 (org-add-hook 'before-change-functions 'org-before-change-function nil
5351 'local)
5352 ;; Check for running clock before killing a buffer
5353 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5354 ;; Initialize macros templates.
5355 (org-macro-initialize-templates)
5356 ;; Initialize radio targets.
5357 (org-update-radio-target-regexp)
5358 ;; Indentation.
5359 (org-set-local 'indent-line-function 'org-indent-line)
5360 (org-set-local 'indent-region-function 'org-indent-region)
5361 ;; Filling and auto-filling.
5362 (org-setup-filling)
5363 ;; Comments.
5364 (org-setup-comments-handling)
5365 ;; Beginning/end of defun
5366 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5367 (org-set-local 'end-of-defun-function 'org-forward-element)
5368 ;; Next error for sparse trees
5369 (org-set-local 'next-error-function 'org-occur-next-match)
5370 ;; Make sure dependence stuff works reliably, even for users who set it
5371 ;; too late :-(
5372 (if org-enforce-todo-dependencies
5373 (add-hook 'org-blocker-hook
5374 'org-block-todo-from-children-or-siblings-or-parent)
5375 (remove-hook 'org-blocker-hook
5376 'org-block-todo-from-children-or-siblings-or-parent))
5377 (if org-enforce-todo-checkbox-dependencies
5378 (add-hook 'org-blocker-hook
5379 'org-block-todo-from-checkboxes)
5380 (remove-hook 'org-blocker-hook
5381 'org-block-todo-from-checkboxes))
5383 ;; Align options lines
5384 (org-set-local
5385 'align-mode-rules-list
5386 '((org-in-buffer-settings
5387 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5388 (modes . '(org-mode)))))
5390 ;; Imenu
5391 (org-set-local 'imenu-create-index-function
5392 'org-imenu-get-tree)
5394 ;; Make isearch reveal context
5395 (if (or (featurep 'xemacs)
5396 (not (boundp 'outline-isearch-open-invisible-function)))
5397 ;; Emacs 21 and XEmacs make use of the hook
5398 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5399 ;; Emacs 22 deals with this through a special variable
5400 (org-set-local 'outline-isearch-open-invisible-function
5401 (lambda (&rest ignore) (org-show-context 'isearch)))
5402 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5404 ;; Setup the pcomplete hooks
5405 (set (make-local-variable 'pcomplete-command-completion-function)
5406 'org-pcomplete-initial)
5407 (set (make-local-variable 'pcomplete-command-name-function)
5408 'org-command-at-point)
5409 (set (make-local-variable 'pcomplete-default-completion-function)
5410 'ignore)
5411 (set (make-local-variable 'pcomplete-parse-arguments-function)
5412 'org-parse-arguments)
5413 (set (make-local-variable 'pcomplete-termination-string) "")
5414 (when (>= emacs-major-version 23)
5415 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5417 ;; If empty file that did not turn on org-mode automatically, make it to.
5418 (if (and org-insert-mode-line-in-empty-file
5419 (org-called-interactively-p 'any)
5420 (= (point-min) (point-max)))
5421 (insert "# -*- mode: org -*-\n\n"))
5422 (unless org-inhibit-startup
5423 (org-unmodified
5424 (and org-startup-with-beamer-mode (org-beamer-mode))
5425 (when org-startup-align-all-tables
5426 (org-table-map-tables 'org-table-align 'quietly))
5427 (when org-startup-with-inline-images
5428 (org-display-inline-images))
5429 (when org-startup-with-latex-preview
5430 (org-preview-latex-fragment))
5431 (unless org-inhibit-startup-visibility-stuff
5432 (org-set-startup-visibility))))
5433 ;; Try to set org-hide correctly
5434 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5436 ;; Update `customize-package-emacs-version-alist'
5437 (add-to-list 'customize-package-emacs-version-alist
5438 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5439 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5440 ("8.0" . "24.4")))
5442 (defvar org-mode-transpose-word-syntax-table
5443 (let ((st (make-syntax-table)))
5444 (mapc (lambda(c) (modify-syntax-entry
5445 (string-to-char (car c)) "w p" st))
5446 org-emphasis-alist)
5447 st))
5449 (when (fboundp 'abbrev-table-put)
5450 (abbrev-table-put org-mode-abbrev-table
5451 :parents (list text-mode-abbrev-table)))
5453 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5455 (defsubst org-fix-ellipsis-at-bol ()
5456 (save-excursion (goto-char (window-start)) (recenter 0)))
5458 (defun org-find-invisible-foreground ()
5459 (let ((candidates (remove
5460 "unspecified-bg"
5461 (nconc
5462 (list (face-background 'default)
5463 (face-background 'org-default))
5464 (mapcar
5465 (lambda (alist)
5466 (when (boundp alist)
5467 (cdr (assoc 'background-color (symbol-value alist)))))
5468 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5469 (list (face-foreground 'org-hide))))))
5470 (car (remove nil candidates))))
5472 (defun org-current-time (&optional rounding-minutes past)
5473 "Current time, possibly rounded to ROUNDING-MINUTES.
5474 When ROUNDING-MINUTES is not an integer, fall back on the car of
5475 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5476 the rounding returns a past time."
5477 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5478 (car org-time-stamp-rounding-minutes)))
5479 (time (decode-time)) res)
5480 (if (< r 1)
5481 (current-time)
5482 (setq res
5483 (apply 'encode-time
5484 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5485 (nthcdr 2 time))))
5486 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5487 (seconds-to-time (- (org-float-time res) (* r 60)))
5488 res))))
5490 (defun org-today ()
5491 "Return today date, considering `org-extend-today-until'."
5492 (time-to-days
5493 (time-subtract (current-time)
5494 (list 0 (* 3600 org-extend-today-until) 0))))
5496 ;;;; Font-Lock stuff, including the activators
5498 (defvar org-mouse-map (make-sparse-keymap))
5499 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5500 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5501 (when org-mouse-1-follows-link
5502 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5503 (when org-tab-follows-link
5504 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5505 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5507 (require 'font-lock)
5509 (defconst org-non-link-chars "]\t\n\r<>")
5510 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5511 "shell" "elisp" "doi" "message"))
5512 (defvar org-link-types-re nil
5513 "Matches a link that has a url-like prefix like \"http:\"")
5514 (defvar org-link-re-with-space nil
5515 "Matches a link with spaces, optional angular brackets around it.")
5516 (defvar org-link-re-with-space2 nil
5517 "Matches a link with spaces, optional angular brackets around it.")
5518 (defvar org-link-re-with-space3 nil
5519 "Matches a link with spaces, only for internal part in bracket links.")
5520 (defvar org-angle-link-re nil
5521 "Matches link with angular brackets, spaces are allowed.")
5522 (defvar org-plain-link-re nil
5523 "Matches plain link, without spaces.")
5524 (defvar org-bracket-link-regexp nil
5525 "Matches a link in double brackets.")
5526 (defvar org-bracket-link-analytic-regexp nil
5527 "Regular expression used to analyze links.
5528 Here is what the match groups contain after a match:
5529 1: http:
5530 2: http
5531 3: path
5532 4: [desc]
5533 5: desc")
5534 (defvar org-bracket-link-analytic-regexp++ nil
5535 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5536 (defvar org-any-link-re nil
5537 "Regular expression matching any link.")
5539 (defconst org-match-sexp-depth 3
5540 "Number of stacked braces for sub/superscript matching.")
5542 (defun org-create-multibrace-regexp (left right n)
5543 "Create a regular expression which will match a balanced sexp.
5544 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5545 as single character strings.
5546 The regexp returned will match the entire expression including the
5547 delimiters. It will also define a single group which contains the
5548 match except for the outermost delimiters. The maximum depth of
5549 stacked delimiters is N. Escaping delimiters is not possible."
5550 (let* ((nothing (concat "[^" left right "]*?"))
5551 (or "\\|")
5552 (re nothing)
5553 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5554 (while (> n 1)
5555 (setq n (1- n)
5556 re (concat re or next)
5557 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5558 (concat left "\\(" re "\\)" right)))
5560 (defvar org-match-substring-regexp
5561 (concat
5562 "\\(\\S-\\)\\([_^]\\)\\("
5563 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5564 "\\|"
5565 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5566 "\\|"
5567 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5568 "The regular expression matching a sub- or superscript.")
5570 (defvar org-match-substring-with-braces-regexp
5571 (concat
5572 "\\(\\S-\\)\\([_^]\\)\\("
5573 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5574 "\\)")
5575 "The regular expression matching a sub- or superscript, forcing braces.")
5577 (defun org-make-link-regexps ()
5578 "Update the link regular expressions.
5579 This should be called after the variable `org-link-types' has changed."
5580 (setq org-link-types-re
5581 (concat
5582 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5583 org-link-re-with-space
5584 (concat
5585 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5586 "\\([^" org-non-link-chars " ]"
5587 "[^" org-non-link-chars "]*"
5588 "[^" org-non-link-chars " ]\\)>?")
5589 org-link-re-with-space2
5590 (concat
5591 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5592 "\\([^" org-non-link-chars " ]"
5593 "[^\t\n\r]*"
5594 "[^" org-non-link-chars " ]\\)>?")
5595 org-link-re-with-space3
5596 (concat
5597 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5598 "\\([^" org-non-link-chars " ]"
5599 "[^\t\n\r]*\\)")
5600 org-angle-link-re
5601 (concat
5602 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5603 "\\([^" org-non-link-chars " ]"
5604 "[^" org-non-link-chars "]*"
5605 "\\)>")
5606 org-plain-link-re
5607 (concat
5608 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5609 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5610 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5611 org-bracket-link-regexp
5612 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5613 org-bracket-link-analytic-regexp
5614 (concat
5615 "\\[\\["
5616 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5617 "\\([^]]+\\)"
5618 "\\]"
5619 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5620 "\\]")
5621 org-bracket-link-analytic-regexp++
5622 (concat
5623 "\\[\\["
5624 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5625 "\\([^]]+\\)"
5626 "\\]"
5627 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5628 "\\]")
5629 org-any-link-re
5630 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5631 org-angle-link-re "\\)\\|\\("
5632 org-plain-link-re "\\)")))
5634 (org-make-link-regexps)
5636 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5637 "Regular expression for fast time stamp matching.")
5638 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5639 "Regular expression for fast time stamp matching.")
5640 (defconst org-ts-regexp0
5641 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5642 "Regular expression matching time strings for analysis.
5643 This one does not require the space after the date, so it can be used
5644 on a string that terminates immediately after the date.")
5645 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5646 "Regular expression matching time strings for analysis.")
5647 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5648 "Regular expression matching time stamps, with groups.")
5649 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5650 "Regular expression matching time stamps (also [..]), with groups.")
5651 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5652 "Regular expression matching a time stamp range.")
5653 (defconst org-tr-regexp-both
5654 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5655 "Regular expression matching a time stamp range.")
5656 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5657 org-ts-regexp "\\)?")
5658 "Regular expression matching a time stamp or time stamp range.")
5659 (defconst org-tsr-regexp-both
5660 (concat org-ts-regexp-both "\\(--?-?"
5661 org-ts-regexp-both "\\)?")
5662 "Regular expression matching a time stamp or time stamp range.
5663 The time stamps may be either active or inactive.")
5665 (defvar org-emph-face nil)
5667 (defun org-do-emphasis-faces (limit)
5668 "Run through the buffer and add overlays to emphasized strings."
5669 (let (rtn a)
5670 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5671 (if (not (= (char-after (match-beginning 3))
5672 (char-after (match-beginning 4))))
5673 (progn
5674 (setq rtn t)
5675 (setq a (assoc (match-string 3) org-emphasis-alist))
5676 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5677 'face
5678 (nth 1 a))
5679 (and (nth 2 a)
5680 (org-remove-flyspell-overlays-in
5681 (match-beginning 0) (match-end 0)))
5682 (add-text-properties (match-beginning 2) (match-end 2)
5683 '(font-lock-multiline t org-emphasis t))
5684 (when org-hide-emphasis-markers
5685 (add-text-properties (match-end 4) (match-beginning 5)
5686 '(invisible org-link))
5687 (add-text-properties (match-beginning 3) (match-end 3)
5688 '(invisible org-link)))))
5689 (goto-char (1+ (match-beginning 0))))
5690 rtn))
5692 (defun org-emphasize (&optional char)
5693 "Insert or change an emphasis, i.e. a font like bold or italic.
5694 If there is an active region, change that region to a new emphasis.
5695 If there is no region, just insert the marker characters and position
5696 the cursor between them.
5697 CHAR should be the marker character. If it is a space, it means to
5698 remove the emphasis of the selected region.
5699 If CHAR is not given (for example in an interactive call) it will be
5700 prompted for."
5701 (interactive)
5702 (let ((erc org-emphasis-regexp-components)
5703 (prompt "")
5704 (string "") beg end move c s)
5705 (if (org-region-active-p)
5706 (setq beg (region-beginning) end (region-end)
5707 string (buffer-substring beg end))
5708 (setq move t))
5710 (unless char
5711 (message "Emphasis marker or tag: [%s]"
5712 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5713 (setq char (read-char-exclusive)))
5714 (if (equal char ?\ )
5715 (setq s "" move nil)
5716 (unless (assoc (char-to-string char) org-emphasis-alist)
5717 (user-error "No such emphasis marker: \"%c\"" char))
5718 (setq s (char-to-string char)))
5719 (while (and (> (length string) 1)
5720 (equal (substring string 0 1) (substring string -1))
5721 (assoc (substring string 0 1) org-emphasis-alist))
5722 (setq string (substring string 1 -1)))
5723 (setq string (concat s string s))
5724 (if beg (delete-region beg end))
5725 (unless (or (bolp)
5726 (string-match (concat "[" (nth 0 erc) "\n]")
5727 (char-to-string (char-before (point)))))
5728 (insert " "))
5729 (unless (or (eobp)
5730 (string-match (concat "[" (nth 1 erc) "\n]")
5731 (char-to-string (char-after (point)))))
5732 (insert " ") (backward-char 1))
5733 (insert string)
5734 (and move (backward-char 1))))
5736 (defconst org-nonsticky-props
5737 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5739 (defsubst org-rear-nonsticky-at (pos)
5740 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5742 (defun org-activate-plain-links (limit)
5743 "Run through the buffer and add overlays to links."
5744 (let (f hl)
5745 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5746 (not (org-in-src-block-p)))
5747 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5748 (setq f (get-text-property (match-beginning 0) 'face))
5749 (setq hl (org-match-string-no-properties 0))
5750 (if (or (eq f 'org-tag)
5751 (and (listp f) (memq 'org-tag f)))
5753 (add-text-properties (match-beginning 0) (match-end 0)
5754 (list 'mouse-face 'highlight
5755 'face 'org-link
5756 'htmlize-link `(:uri ,hl)
5757 'keymap org-mouse-map))
5758 (org-rear-nonsticky-at (match-end 0)))
5759 t)))
5761 (defun org-activate-code (limit)
5762 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5763 (progn
5764 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5765 (remove-text-properties (match-beginning 0) (match-end 0)
5766 '(display t invisible t intangible t))
5767 t)))
5769 (defcustom org-src-fontify-natively nil
5770 "When non-nil, fontify code in code blocks."
5771 :type 'boolean
5772 :version "24.1"
5773 :group 'org-appearance
5774 :group 'org-babel)
5776 (defcustom org-allow-promoting-top-level-subtree nil
5777 "When non-nil, allow promoting a top level subtree.
5778 The leading star of the top level headline will be replaced
5779 by a #."
5780 :type 'boolean
5781 :version "24.1"
5782 :group 'org-appearance)
5784 (defun org-fontify-meta-lines-and-blocks (limit)
5785 (condition-case nil
5786 (org-fontify-meta-lines-and-blocks-1 limit)
5787 (error (message "org-mode fontification error"))))
5789 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5790 "Fontify #+ lines and blocks."
5791 (let ((case-fold-search t))
5792 (if (re-search-forward
5793 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5794 limit t)
5795 (let ((beg (match-beginning 0))
5796 (block-start (match-end 0))
5797 (block-end nil)
5798 (lang (match-string 7))
5799 (beg1 (line-beginning-position 2))
5800 (dc1 (downcase (match-string 2)))
5801 (dc3 (downcase (match-string 3)))
5802 end end1 quoting block-type ovl)
5803 (cond
5804 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5805 ;; a single line of backend-specific content
5806 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5807 (remove-text-properties (match-beginning 0) (match-end 0)
5808 '(display t invisible t intangible t))
5809 (add-text-properties (match-beginning 1) (match-end 3)
5810 '(font-lock-fontified t face org-meta-line))
5811 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5812 '(font-lock-fontified t face org-block))
5813 ; for backend-specific code
5815 ((and (match-end 4) (equal dc3 "+begin"))
5816 ;; Truly a block
5817 (setq block-type (downcase (match-string 5))
5818 quoting (member block-type org-protecting-blocks))
5819 (when (re-search-forward
5820 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5821 nil t) ;; on purpose, we look further than LIMIT
5822 (setq end (min (point-max) (match-end 0))
5823 end1 (min (point-max) (1- (match-beginning 0))))
5824 (setq block-end (match-beginning 0))
5825 (when quoting
5826 (remove-text-properties beg end
5827 '(display t invisible t intangible t)))
5828 (add-text-properties
5829 beg end
5830 '(font-lock-fontified t font-lock-multiline t))
5831 (add-text-properties beg beg1 '(face org-meta-line))
5832 (add-text-properties end1 (min (point-max) (1+ end))
5833 '(face org-meta-line)) ; for end_src
5834 (cond
5835 ((and lang (not (string= lang "")) org-src-fontify-natively)
5836 (org-src-font-lock-fontify-block lang block-start block-end)
5837 ;; remove old background overlays
5838 (mapc (lambda (ov)
5839 (if (eq (overlay-get ov 'face) 'org-block-background)
5840 (delete-overlay ov)))
5841 (overlays-at (/ (+ beg1 block-end) 2)))
5842 ;; add a background overlay
5843 (setq ovl (make-overlay beg1 block-end))
5844 (overlay-put ovl 'face 'org-block-background)
5845 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5846 (quoting
5847 (add-text-properties beg1 (min (point-max) (1+ end1))
5848 '(face org-block))) ; end of source block
5849 ((not org-fontify-quote-and-verse-blocks))
5850 ((string= block-type "quote")
5851 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5852 ((string= block-type "verse")
5853 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5854 (add-text-properties beg beg1 '(face org-block-begin-line))
5855 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5856 '(face org-block-end-line))
5858 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5859 (add-text-properties
5860 beg (match-end 3)
5861 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5862 '(font-lock-fontified t invisible t)
5863 '(font-lock-fontified t face org-document-info-keyword)))
5864 (add-text-properties
5865 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5866 (if (string-equal dc1 "+title:")
5867 '(font-lock-fontified t face org-document-title)
5868 '(font-lock-fontified t face org-document-info))))
5869 ((or (equal dc1 "+results")
5870 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5871 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5872 "+call:" "+header:" "+headers:" "+name:"))
5873 (and (match-end 4) (equal dc3 "+attr")))
5874 (add-text-properties
5875 beg (match-end 0)
5876 '(font-lock-fontified t face org-meta-line))
5878 ((member dc3 '(" " ""))
5879 (add-text-properties
5880 beg (match-end 0)
5881 '(font-lock-fontified t face font-lock-comment-face)))
5882 ((not (member (char-after beg) '(?\ ?\t)))
5883 ;; just any other in-buffer setting, but not indented
5884 (add-text-properties
5885 beg (match-end 0)
5886 '(font-lock-fontified t face org-meta-line))
5888 (t nil))))))
5890 (defun org-activate-angle-links (limit)
5891 "Run through the buffer and add overlays to links."
5892 (if (and (re-search-forward org-angle-link-re limit t)
5893 (not (org-in-src-block-p)))
5894 (progn
5895 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5896 (add-text-properties (match-beginning 0) (match-end 0)
5897 (list 'mouse-face 'highlight
5898 'keymap org-mouse-map))
5899 (org-rear-nonsticky-at (match-end 0))
5900 t)))
5902 (defun org-activate-footnote-links (limit)
5903 "Run through the buffer and add overlays to footnotes."
5904 (let ((fn (org-footnote-next-reference-or-definition limit)))
5905 (when fn
5906 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5907 (org-remove-flyspell-overlays-in beg end)
5908 (add-text-properties beg end
5909 (list 'mouse-face 'highlight
5910 'keymap org-mouse-map
5911 'help-echo
5912 (if (= (point-at-bol) beg)
5913 "Footnote definition"
5914 "Footnote reference")
5915 'font-lock-fontified t
5916 'font-lock-multiline t
5917 'face 'org-footnote))))))
5919 (defun org-activate-bracket-links (limit)
5920 "Run through the buffer and add overlays to bracketed links."
5921 (if (and (re-search-forward org-bracket-link-regexp limit t)
5922 (not (org-in-src-block-p)))
5923 (let* ((hl (org-match-string-no-properties 1))
5924 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5925 (ip (org-maybe-intangible
5926 (list 'invisible 'org-link
5927 'keymap org-mouse-map 'mouse-face 'highlight
5928 'font-lock-multiline t 'help-echo help
5929 'htmlize-link `(:uri ,hl))))
5930 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5931 'font-lock-multiline t 'help-echo help
5932 'htmlize-link `(:uri ,hl))))
5933 ;; We need to remove the invisible property here. Table narrowing
5934 ;; may have made some of this invisible.
5935 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5936 (remove-text-properties (match-beginning 0) (match-end 0)
5937 '(invisible nil))
5938 (if (match-end 3)
5939 (progn
5940 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5941 (org-rear-nonsticky-at (match-beginning 3))
5942 (add-text-properties (match-beginning 3) (match-end 3) vp)
5943 (org-rear-nonsticky-at (match-end 3))
5944 (add-text-properties (match-end 3) (match-end 0) ip)
5945 (org-rear-nonsticky-at (match-end 0)))
5946 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5947 (org-rear-nonsticky-at (match-beginning 1))
5948 (add-text-properties (match-beginning 1) (match-end 1) vp)
5949 (org-rear-nonsticky-at (match-end 1))
5950 (add-text-properties (match-end 1) (match-end 0) ip)
5951 (org-rear-nonsticky-at (match-end 0)))
5952 t)))
5954 (defun org-activate-dates (limit)
5955 "Run through the buffer and add overlays to dates."
5956 (if (and (re-search-forward org-tsr-regexp-both limit t)
5957 (not (equal (char-before (match-beginning 0)) 91)))
5958 (progn
5959 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5960 (add-text-properties (match-beginning 0) (match-end 0)
5961 (list 'mouse-face 'highlight
5962 'keymap org-mouse-map))
5963 (org-rear-nonsticky-at (match-end 0))
5964 (when org-display-custom-times
5965 (if (match-end 3)
5966 (org-display-custom-time (match-beginning 3) (match-end 3)))
5967 (org-display-custom-time (match-beginning 1) (match-end 1)))
5968 t)))
5970 (defvar org-target-link-regexp nil
5971 "Regular expression matching radio targets in plain text.")
5972 (make-variable-buffer-local 'org-target-link-regexp)
5973 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5974 "Regular expression matching a link target.")
5975 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5976 "Regular expression matching a radio target.")
5977 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5978 "Regular expression matching any target.")
5980 (defun org-activate-target-links (limit)
5981 "Run through the buffer and add overlays to target matches."
5982 (when org-target-link-regexp
5983 (let ((case-fold-search t))
5984 (if (re-search-forward org-target-link-regexp limit t)
5985 (progn
5986 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5987 (add-text-properties (match-beginning 0) (match-end 0)
5988 (list 'mouse-face 'highlight
5989 'keymap org-mouse-map
5990 'help-echo "Radio target link"
5991 'org-linked-text t))
5992 (org-rear-nonsticky-at (match-end 0))
5993 t)))))
5995 (defun org-update-radio-target-regexp ()
5996 "Find all radio targets in this file and update the regular expression."
5997 (interactive)
5998 (when (memq 'radio org-activate-links)
5999 (setq org-target-link-regexp
6000 (org-make-target-link-regexp (org-all-targets 'radio)))
6001 (org-restart-font-lock)))
6003 (defun org-hide-wide-columns (limit)
6004 (let (s e)
6005 (setq s (text-property-any (point) (or limit (point-max))
6006 'org-cwidth t))
6007 (when s
6008 (setq e (next-single-property-change s 'org-cwidth))
6009 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6010 (goto-char e)
6011 t)))
6013 (defvar org-latex-and-related-regexp nil
6014 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6015 (defvar org-match-substring-regexp)
6016 (defvar org-match-substring-with-braces-regexp)
6018 (defun org-compute-latex-and-related-regexp ()
6019 "Compute regular expression for LaTeX, entities and sub/superscript.
6020 Result depends on variable `org-highlight-latex-and-related'."
6021 (org-set-local
6022 'org-latex-and-related-regexp
6023 (let* ((re-sub
6024 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6025 ((eq org-use-sub-superscripts '{})
6026 (list org-match-substring-with-braces-regexp))
6027 (org-use-sub-superscripts (list org-match-substring-regexp))))
6028 (re-latex
6029 (when (memq 'latex org-highlight-latex-and-related)
6030 (let ((matchers (plist-get org-format-latex-options :matchers)))
6031 (delq nil
6032 (mapcar (lambda (x)
6033 (and (member (car x) matchers) (nth 1 x)))
6034 org-latex-regexps)))))
6035 (re-entities
6036 (when (memq 'entities org-highlight-latex-and-related)
6037 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6038 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6040 (defun org-do-latex-and-related (limit)
6041 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6042 LIMIT bounds the search for syntax to highlight. Stop at first
6043 highlighted object, if any. Return t if some highlighting was
6044 done, nil otherwise."
6045 (when (org-string-nw-p org-latex-and-related-regexp)
6046 (catch 'found
6047 (while (re-search-forward org-latex-and-related-regexp limit t)
6048 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6049 'face))
6050 '(org-code org-verbatim underline))
6051 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6052 '(?_ ?^))
6054 0)))
6055 (font-lock-prepend-text-property
6056 (+ offset (match-beginning 0)) (match-end 0)
6057 'face 'org-latex-and-related)
6058 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6059 '(font-lock-multiline t)))
6060 (throw 'found t)))
6061 nil)))
6063 (defun org-restart-font-lock ()
6064 "Restart `font-lock-mode', to force refontification."
6065 (when (and (boundp 'font-lock-mode) font-lock-mode)
6066 (font-lock-mode -1)
6067 (font-lock-mode 1)))
6069 (defun org-all-targets (&optional radio)
6070 "Return a list of all targets in this file.
6071 When optional argument RADIO is non-nil, only find radio
6072 targets."
6073 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6074 (save-excursion
6075 (goto-char (point-min))
6076 (while (re-search-forward re nil t)
6077 ;; Make sure point is really within the object.
6078 (backward-char)
6079 (let ((obj (org-element-context)))
6080 (when (memq (org-element-type obj) '(radio-target target))
6081 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6082 rtn)))
6084 (defun org-make-target-link-regexp (targets)
6085 "Make regular expression matching all strings in TARGETS.
6086 The regular expression finds the targets also if there is a line break
6087 between words."
6088 (and targets
6089 (concat
6090 "\\<\\("
6091 (mapconcat
6092 (lambda (x)
6093 (setq x (regexp-quote x))
6094 (while (string-match " +" x)
6095 (setq x (replace-match "\\s-+" t t x)))
6097 targets
6098 "\\|")
6099 "\\)\\>")))
6101 (defun org-activate-tags (limit)
6102 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6103 (progn
6104 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6105 (add-text-properties (match-beginning 1) (match-end 1)
6106 (list 'mouse-face 'highlight
6107 'keymap org-mouse-map))
6108 (org-rear-nonsticky-at (match-end 1))
6109 t)))
6111 (defun org-outline-level ()
6112 "Compute the outline level of the heading at point.
6113 If this is called at a normal headline, the level is the number of stars.
6114 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6115 (save-excursion
6116 (if (not (condition-case nil
6117 (org-back-to-heading t)
6118 (error nil)))
6120 (looking-at org-outline-regexp)
6121 (1- (- (match-end 0) (match-beginning 0))))))
6123 (defvar org-font-lock-keywords nil)
6125 (defsubst org-re-property (property &optional literal)
6126 "Return a regexp matching a PROPERTY line.
6127 Match group 3 will be set to the value if it exists."
6128 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6129 (if literal property (regexp-quote property))
6130 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6132 (defconst org-property-re
6133 (org-re-property ".*?" 'literal)
6134 "Regular expression matching a property line.
6135 There are four matching groups:
6136 1: :PROPKEY: including the leading and trailing colon,
6137 2: PROPKEY without the leading and trailing colon,
6138 3: PROPVAL without leading or trailing spaces,
6139 4: the indentation of the current line,
6140 5: trailing whitespace.")
6142 (defvar org-font-lock-hook nil
6143 "Functions to be called for special font lock stuff.")
6145 (defvar org-font-lock-set-keywords-hook nil
6146 "Functions that can manipulate `org-font-lock-extra-keywords'.
6147 This is called after `org-font-lock-extra-keywords' is defined, but before
6148 it is installed to be used by font lock. This can be useful if something
6149 needs to be inserted at a specific position in the font-lock sequence.")
6151 (defun org-font-lock-hook (limit)
6152 "Run `org-font-lock-hook' within LIMIT."
6153 (run-hook-with-args 'org-font-lock-hook limit))
6155 (defun org-set-font-lock-defaults ()
6156 "Set font lock defaults for the current buffer."
6157 (let* ((em org-fontify-emphasized-text)
6158 (lk org-activate-links)
6159 (org-font-lock-extra-keywords
6160 (list
6161 ;; Call the hook
6162 '(org-font-lock-hook)
6163 ;; Headlines
6164 `(,(if org-fontify-whole-heading-line
6165 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6166 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6167 (1 (org-get-level-face 1))
6168 (2 (org-get-level-face 2))
6169 (3 (org-get-level-face 3)))
6170 ;; Table lines
6171 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6172 (1 'org-table t))
6173 ;; Table internals
6174 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6175 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6176 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6177 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6178 ;; Drawers
6179 (list org-drawer-regexp '(0 'org-special-keyword t))
6180 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6181 ;; Properties
6182 (list org-property-re
6183 '(1 'org-special-keyword t)
6184 '(3 'org-property-value t))
6185 ;; Links
6186 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6187 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6188 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6189 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6190 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6191 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6192 (if (memq 'footnote lk) '(org-activate-footnote-links))
6193 ;; Targets.
6194 (list org-any-target-regexp '(0 'org-target t))
6195 ;; Diary sexps.
6196 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6197 ;; Macro
6198 '("{{{.+}}}" (0 'org-macro t))
6199 '(org-hide-wide-columns (0 nil append))
6200 ;; TODO keyword
6201 (list (format org-heading-keyword-regexp-format
6202 org-todo-regexp)
6203 '(2 (org-get-todo-face 2) t))
6204 ;; DONE
6205 (if org-fontify-done-headline
6206 (list (format org-heading-keyword-regexp-format
6207 (concat
6208 "\\(?:"
6209 (mapconcat 'regexp-quote org-done-keywords "\\|")
6210 "\\)"))
6211 '(2 'org-headline-done t))
6212 nil)
6213 ;; Priorities
6214 '(org-font-lock-add-priority-faces)
6215 ;; Tags
6216 '(org-font-lock-add-tag-faces)
6217 ;; Tags groups
6218 (if (and org-group-tags org-tag-groups-alist)
6219 (list (concat org-outline-regexp-bol ".+\\(:"
6220 (regexp-opt (mapcar 'car org-tag-groups-alist))
6221 ":\\).*$")
6222 '(1 'org-tag-group prepend)))
6223 ;; Special keywords
6224 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6225 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6226 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6227 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6228 ;; Emphasis
6229 (if em
6230 (if (featurep 'xemacs)
6231 '(org-do-emphasis-faces (0 nil append))
6232 '(org-do-emphasis-faces)))
6233 ;; Checkboxes
6234 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6235 1 'org-checkbox prepend)
6236 (if (cdr (assq 'checkbox org-list-automatic-rules))
6237 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6238 (0 (org-get-checkbox-statistics-face) t)))
6239 ;; Description list items
6240 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6241 1 'org-list-dt prepend)
6242 ;; ARCHIVEd headings
6243 (list (concat
6244 org-outline-regexp-bol
6245 "\\(.*:" org-archive-tag ":.*\\)")
6246 '(1 'org-archived prepend))
6247 ;; Specials
6248 '(org-do-latex-and-related)
6249 '(org-fontify-entities)
6250 '(org-raise-scripts)
6251 ;; Code
6252 '(org-activate-code (1 'org-code t))
6253 ;; COMMENT
6254 (list (format org-heading-keyword-regexp-format
6255 (concat "\\("
6256 org-comment-string "\\|" org-quote-string
6257 "\\)"))
6258 '(2 'org-special-keyword t))
6259 ;; Blocks and meta lines
6260 '(org-fontify-meta-lines-and-blocks))))
6261 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6262 (run-hooks 'org-font-lock-set-keywords-hook)
6263 ;; Now set the full font-lock-keywords
6264 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6265 (org-set-local 'font-lock-defaults
6266 '(org-font-lock-keywords t nil nil backward-paragraph))
6267 (kill-local-variable 'font-lock-keywords) nil))
6269 (defun org-toggle-pretty-entities ()
6270 "Toggle the composition display of entities as UTF8 characters."
6271 (interactive)
6272 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6273 (org-restart-font-lock)
6274 (if org-pretty-entities
6275 (message "Entities are now displayed as UTF8 characters")
6276 (save-restriction
6277 (widen)
6278 (org-decompose-region (point-min) (point-max))
6279 (message "Entities are now displayed as plain text"))))
6281 (defvar org-custom-properties-overlays nil
6282 "List of overlays used for custom properties.")
6283 (make-variable-buffer-local 'org-custom-properties-overlays)
6285 (defun org-toggle-custom-properties-visibility ()
6286 "Display or hide properties in `org-custom-properties'."
6287 (interactive)
6288 (if org-custom-properties-overlays
6289 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6290 (setq org-custom-properties-overlays nil))
6291 (unless (not org-custom-properties)
6292 (save-excursion
6293 (save-restriction
6294 (widen)
6295 (goto-char (point-min))
6296 (while (re-search-forward org-property-re nil t)
6297 (mapc (lambda(p)
6298 (when (equal p (substring (match-string 1) 1 -1))
6299 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6300 (overlay-put o 'invisible t)
6301 (overlay-put o 'org-custom-property t)
6302 (push o org-custom-properties-overlays))))
6303 org-custom-properties)))))))
6305 (defun org-fontify-entities (limit)
6306 "Find an entity to fontify."
6307 (let (ee)
6308 (when org-pretty-entities
6309 (catch 'match
6310 (while (re-search-forward
6311 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6312 limit t)
6313 (if (and (not (org-in-indented-comment-line))
6314 (setq ee (org-entity-get (match-string 1)))
6315 (= (length (nth 6 ee)) 1))
6316 (let*
6317 ((end (if (equal (match-string 2) "{}")
6318 (match-end 2)
6319 (match-end 1))))
6320 (add-text-properties
6321 (match-beginning 0) end
6322 (list 'font-lock-fontified t))
6323 (compose-region (match-beginning 0) end
6324 (nth 6 ee) nil)
6325 (backward-char 1)
6326 (throw 'match t))))
6327 nil))))
6329 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6330 "Fontify string S like in Org-mode."
6331 (with-temp-buffer
6332 (insert s)
6333 (let ((org-odd-levels-only odd-levels))
6334 (org-mode)
6335 (font-lock-fontify-buffer)
6336 (buffer-string))))
6338 (defvar org-m nil)
6339 (defvar org-l nil)
6340 (defvar org-f nil)
6341 (defun org-get-level-face (n)
6342 "Get the right face for match N in font-lock matching of headlines."
6343 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6344 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6345 (if org-cycle-level-faces
6346 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6347 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6348 (cond
6349 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6350 ((eq n 2) org-f)
6351 (t (if org-level-color-stars-only nil org-f))))
6354 (defun org-get-todo-face (kwd)
6355 "Get the right face for a TODO keyword KWD.
6356 If KWD is a number, get the corresponding match group."
6357 (if (numberp kwd) (setq kwd (match-string kwd)))
6358 (or (org-face-from-face-or-color
6359 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6360 (and (member kwd org-done-keywords) 'org-done)
6361 'org-todo))
6363 (defun org-face-from-face-or-color (context inherit face-or-color)
6364 "Create a face list that inherits INHERIT, but sets the foreground color.
6365 When FACE-OR-COLOR is not a string, just return it."
6366 (if (stringp face-or-color)
6367 (list :inherit inherit
6368 (cdr (assoc context org-faces-easy-properties))
6369 face-or-color)
6370 face-or-color))
6372 (defun org-font-lock-add-tag-faces (limit)
6373 "Add the special tag faces."
6374 (when (and org-tag-faces org-tags-special-faces-re)
6375 (while (re-search-forward org-tags-special-faces-re limit t)
6376 (add-text-properties (match-beginning 1) (match-end 1)
6377 (list 'face (org-get-tag-face 1)
6378 'font-lock-fontified t))
6379 (backward-char 1))))
6381 (defun org-font-lock-add-priority-faces (limit)
6382 "Add the special priority faces."
6383 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6384 (when (save-match-data (org-at-heading-p))
6385 (add-text-properties
6386 (match-beginning 0) (match-end 0)
6387 (list 'face (or (org-face-from-face-or-color
6388 'priority 'org-priority
6389 (cdr (assoc (char-after (match-beginning 1))
6390 org-priority-faces)))
6391 'org-priority)
6392 'font-lock-fontified t)))))
6394 (defun org-get-tag-face (kwd)
6395 "Get the right face for a TODO keyword KWD.
6396 If KWD is a number, get the corresponding match group."
6397 (if (numberp kwd) (setq kwd (match-string kwd)))
6398 (or (org-face-from-face-or-color
6399 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6400 'org-tag))
6402 (defun org-unfontify-region (beg end &optional maybe_loudly)
6403 "Remove fontification and activation overlays from links."
6404 (font-lock-default-unfontify-region beg end)
6405 (let* ((buffer-undo-list t)
6406 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6407 (inhibit-modification-hooks t)
6408 deactivate-mark buffer-file-name buffer-file-truename)
6409 (org-decompose-region beg end)
6410 (remove-text-properties beg end
6411 '(mouse-face t keymap t org-linked-text t
6412 invisible t intangible t
6413 org-no-flyspell t org-emphasis t))
6414 (org-remove-font-lock-display-properties beg end)))
6416 (defconst org-script-display '(((raise -0.3) (height 0.7))
6417 ((raise 0.3) (height 0.7))
6418 ((raise -0.5))
6419 ((raise 0.5)))
6420 "Display properties for showing superscripts and subscripts.")
6422 (defun org-remove-font-lock-display-properties (beg end)
6423 "Remove specific display properties that have been added by font lock.
6424 The will remove the raise properties that are used to show superscripts
6425 and subscripts."
6426 (let (next prop)
6427 (while (< beg end)
6428 (setq next (next-single-property-change beg 'display nil end)
6429 prop (get-text-property beg 'display))
6430 (if (member prop org-script-display)
6431 (put-text-property beg next 'display nil))
6432 (setq beg next))))
6434 (defun org-raise-scripts (limit)
6435 "Add raise properties to sub/superscripts."
6436 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6437 (if (re-search-forward
6438 (if (eq org-use-sub-superscripts t)
6439 org-match-substring-regexp
6440 org-match-substring-with-braces-regexp)
6441 limit t)
6442 (let* ((pos (point)) table-p comment-p
6443 (mpos (match-beginning 3))
6444 (emph-p (get-text-property mpos 'org-emphasis))
6445 (link-p (get-text-property mpos 'mouse-face))
6446 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6447 (goto-char (point-at-bol))
6448 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6449 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6450 (goto-char pos)
6451 ;; Handle a_b^c
6452 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6453 (if (or comment-p emph-p link-p keyw-p)
6455 (put-text-property (match-beginning 3) (match-end 0)
6456 'display
6457 (if (equal (char-after (match-beginning 2)) ?^)
6458 (nth (if table-p 3 1) org-script-display)
6459 (nth (if table-p 2 0) org-script-display)))
6460 (add-text-properties (match-beginning 2) (match-end 2)
6461 (list 'invisible t
6462 'org-dwidth t 'org-dwidth-n 1))
6463 (if (and (eq (char-after (match-beginning 3)) ?{)
6464 (eq (char-before (match-end 3)) ?}))
6465 (progn
6466 (add-text-properties
6467 (match-beginning 3) (1+ (match-beginning 3))
6468 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6469 (add-text-properties
6470 (1- (match-end 3)) (match-end 3)
6471 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6472 t)))))
6474 ;;;; Visibility cycling, including org-goto and indirect buffer
6476 ;;; Cycling
6478 (defvar org-cycle-global-status nil)
6479 (make-variable-buffer-local 'org-cycle-global-status)
6480 (put 'org-cycle-global-status 'org-state t)
6481 (defvar org-cycle-subtree-status nil)
6482 (make-variable-buffer-local 'org-cycle-subtree-status)
6483 (put 'org-cycle-subtree-status 'org-state t)
6485 (defvar org-inlinetask-min-level)
6487 (defun org-unlogged-message (&rest args)
6488 "Display a message, but avoid logging it in the *Messages* buffer."
6489 (let ((message-log-max nil))
6490 (apply 'message args)))
6492 ;;;###autoload
6493 (defun org-cycle (&optional arg)
6494 "TAB-action and visibility cycling for Org-mode.
6496 This is the command invoked in Org-mode by the TAB key. Its main purpose
6497 is outline visibility cycling, but it also invokes other actions
6498 in special contexts.
6500 - When this function is called with a prefix argument, rotate the entire
6501 buffer through 3 states (global cycling)
6502 1. OVERVIEW: Show only top-level headlines.
6503 2. CONTENTS: Show all headlines of all levels, but no body text.
6504 3. SHOW ALL: Show everything.
6505 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6506 determined by the variable `org-startup-folded', and by any VISIBILITY
6507 properties in the buffer.
6508 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6509 including any drawers.
6511 - When inside a table, re-align the table and move to the next field.
6513 - When point is at the beginning of a headline, rotate the subtree started
6514 by this line through 3 different states (local cycling)
6515 1. FOLDED: Only the main headline is shown.
6516 2. CHILDREN: The main headline and the direct children are shown.
6517 From this state, you can move to one of the children
6518 and zoom in further.
6519 3. SUBTREE: Show the entire subtree, including body text.
6520 If there is no subtree, switch directly from CHILDREN to FOLDED.
6522 - When point is at the beginning of an empty headline and the variable
6523 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6524 of the headline by demoting and promoting it to likely levels. This
6525 speeds up creation document structure by pressing TAB once or several
6526 times right after creating a new headline.
6528 - When there is a numeric prefix, go up to a heading with level ARG, do
6529 a `show-subtree' and return to the previous cursor position. If ARG
6530 is negative, go up that many levels.
6532 - When point is not at the beginning of a headline, execute the global
6533 binding for TAB, which is re-indenting the line. See the option
6534 `org-cycle-emulate-tab' for details.
6536 - Special case: if point is at the beginning of the buffer and there is
6537 no headline in line 1, this function will act as if called with prefix arg
6538 (C-u TAB, same as S-TAB) also when called without prefix arg.
6539 But only if also the variable `org-cycle-global-at-bob' is t."
6540 (interactive "P")
6541 (org-load-modules-maybe)
6542 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6543 (and org-cycle-level-after-item/entry-creation
6544 (or (org-cycle-level)
6545 (org-cycle-item-indentation))))
6546 (let* ((limit-level
6547 (or org-cycle-max-level
6548 (and (boundp 'org-inlinetask-min-level)
6549 org-inlinetask-min-level
6550 (1- org-inlinetask-min-level))))
6551 (nstars (and limit-level
6552 (if org-odd-levels-only
6553 (and limit-level (1- (* limit-level 2)))
6554 limit-level)))
6555 (org-outline-regexp
6556 (if (not (derived-mode-p 'org-mode))
6557 outline-regexp
6558 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6559 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6560 (not (looking-at org-outline-regexp))))
6561 (org-cycle-hook
6562 (if bob-special
6563 (delq 'org-optimize-window-after-visibility-change
6564 (copy-sequence org-cycle-hook))
6565 org-cycle-hook))
6566 (pos (point)))
6568 (if (or bob-special (equal arg '(4)))
6569 ;; special case: use global cycling
6570 (setq arg t))
6572 (cond
6574 ((equal arg '(16))
6575 (setq last-command 'dummy)
6576 (org-set-startup-visibility)
6577 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6579 ((equal arg '(64))
6580 (show-all)
6581 (org-unlogged-message "Entire buffer visible, including drawers"))
6583 ;; Table: enter it or move to the next field.
6584 ((org-at-table-p 'any)
6585 (if (org-at-table.el-p)
6586 (message "Use C-c ' to edit table.el tables")
6587 (if arg (org-table-edit-field t)
6588 (org-table-justify-field-maybe)
6589 (call-interactively 'org-table-next-field))))
6591 ((run-hook-with-args-until-success
6592 'org-tab-after-check-for-table-hook))
6594 ;; Global cycling: delegate to `org-cycle-internal-global'.
6595 ((eq arg t) (org-cycle-internal-global))
6597 ;; Drawers: delegate to `org-flag-drawer'.
6598 ((and org-drawers org-drawer-regexp
6599 (save-excursion
6600 (beginning-of-line 1)
6601 (looking-at org-drawer-regexp)))
6602 (org-flag-drawer ; toggle block visibility
6603 (not (get-char-property (match-end 0) 'invisible))))
6605 ;; Show-subtree, ARG levels up from here.
6606 ((integerp arg)
6607 (save-excursion
6608 (org-back-to-heading)
6609 (outline-up-heading (if (< arg 0) (- arg)
6610 (- (funcall outline-level) arg)))
6611 (org-show-subtree)))
6613 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6614 ((and (featurep 'org-inlinetask)
6615 (org-inlinetask-at-task-p)
6616 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6617 (org-inlinetask-toggle-visibility))
6619 ((org-try-cdlatex-tab))
6621 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6622 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6623 (save-excursion (beginning-of-line 1)
6624 (looking-at org-outline-regexp)))
6625 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6626 (org-cycle-internal-local))
6628 ;; From there: TAB emulation and template completion.
6629 (buffer-read-only (org-back-to-heading))
6631 ((run-hook-with-args-until-success
6632 'org-tab-after-check-for-cycling-hook))
6634 ((org-try-structure-completion))
6636 ((run-hook-with-args-until-success
6637 'org-tab-before-tab-emulation-hook))
6639 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6640 (or (not (bolp))
6641 (not (looking-at org-outline-regexp))))
6642 (call-interactively (global-key-binding "\t")))
6644 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6645 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6646 (or (and (eq org-cycle-emulate-tab 'white)
6647 (= (match-end 0) (point-at-eol)))
6648 (and (eq org-cycle-emulate-tab 'whitestart)
6649 (>= (match-end 0) pos))))
6651 (eq org-cycle-emulate-tab t))
6652 (call-interactively (global-key-binding "\t")))
6654 (t (save-excursion
6655 (org-back-to-heading)
6656 (org-cycle)))))))
6658 (defun org-cycle-internal-global ()
6659 "Do the global cycling action."
6660 ;; Hack to avoid display of messages for .org attachments in Gnus
6661 (let ((ga (string-match "\\*fontification" (buffer-name))))
6662 (cond
6663 ((and (eq last-command this-command)
6664 (eq org-cycle-global-status 'overview))
6665 ;; We just created the overview - now do table of contents
6666 ;; This can be slow in very large buffers, so indicate action
6667 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6668 (unless ga (org-unlogged-message "CONTENTS..."))
6669 (org-content)
6670 (unless ga (org-unlogged-message "CONTENTS...done"))
6671 (setq org-cycle-global-status 'contents)
6672 (run-hook-with-args 'org-cycle-hook 'contents))
6674 ((and (eq last-command this-command)
6675 (eq org-cycle-global-status 'contents))
6676 ;; We just showed the table of contents - now show everything
6677 (run-hook-with-args 'org-pre-cycle-hook 'all)
6678 (show-all)
6679 (unless ga (org-unlogged-message "SHOW ALL"))
6680 (setq org-cycle-global-status 'all)
6681 (run-hook-with-args 'org-cycle-hook 'all))
6684 ;; Default action: go to overview
6685 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6686 (org-overview)
6687 (unless ga (org-unlogged-message "OVERVIEW"))
6688 (setq org-cycle-global-status 'overview)
6689 (run-hook-with-args 'org-cycle-hook 'overview)))))
6691 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6693 (defun org-cycle-internal-local ()
6694 "Do the local cycling action."
6695 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6696 ;; First, determine end of headline (EOH), end of subtree or item
6697 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6698 (save-excursion
6699 (if (org-at-item-p)
6700 (progn
6701 (beginning-of-line)
6702 (setq struct (org-list-struct))
6703 (setq eoh (point-at-eol))
6704 (setq eos (org-list-get-item-end-before-blank (point) struct))
6705 (setq has-children (org-list-has-child-p (point) struct)))
6706 (org-back-to-heading)
6707 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6708 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6709 (setq has-children
6710 (or (save-excursion
6711 (let ((level (funcall outline-level)))
6712 (outline-next-heading)
6713 (and (org-at-heading-p t)
6714 (> (funcall outline-level) level))))
6715 (save-excursion
6716 (org-list-search-forward (org-item-beginning-re) eos t)))))
6717 ;; Determine end invisible part of buffer (EOL)
6718 (beginning-of-line 2)
6719 ;; XEmacs doesn't have `next-single-char-property-change'
6720 (if (featurep 'xemacs)
6721 (while (and (not (eobp)) ;; this is like `next-line'
6722 (get-char-property (1- (point)) 'invisible))
6723 (beginning-of-line 2))
6724 (while (and (not (eobp)) ;; this is like `next-line'
6725 (get-char-property (1- (point)) 'invisible))
6726 (goto-char (next-single-char-property-change (point) 'invisible))
6727 (and (eolp) (beginning-of-line 2))))
6728 (setq eol (point)))
6729 ;; Find out what to do next and set `this-command'
6730 (cond
6731 ((= eos eoh)
6732 ;; Nothing is hidden behind this heading
6733 (unless (org-before-first-heading-p)
6734 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6735 (org-unlogged-message "EMPTY ENTRY")
6736 (setq org-cycle-subtree-status nil)
6737 (save-excursion
6738 (goto-char eos)
6739 (outline-next-heading)
6740 (if (outline-invisible-p) (org-flag-heading nil))))
6741 ((and (or (>= eol eos)
6742 (not (string-match "\\S-" (buffer-substring eol eos))))
6743 (or has-children
6744 (not (setq children-skipped
6745 org-cycle-skip-children-state-if-no-children))))
6746 ;; Entire subtree is hidden in one line: children view
6747 (unless (org-before-first-heading-p)
6748 (run-hook-with-args 'org-pre-cycle-hook 'children))
6749 (if (org-at-item-p)
6750 (org-list-set-item-visibility (point-at-bol) struct 'children)
6751 (org-show-entry)
6752 (org-with-limited-levels (show-children))
6753 ;; FIXME: This slows down the func way too much.
6754 ;; How keep drawers hidden in subtree anyway?
6755 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6756 ;; (org-cycle-hide-drawers 'subtree))
6758 ;; Fold every list in subtree to top-level items.
6759 (when (eq org-cycle-include-plain-lists 'integrate)
6760 (save-excursion
6761 (org-back-to-heading)
6762 (while (org-list-search-forward (org-item-beginning-re) eos t)
6763 (beginning-of-line 1)
6764 (let* ((struct (org-list-struct))
6765 (prevs (org-list-prevs-alist struct))
6766 (end (org-list-get-bottom-point struct)))
6767 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6768 (org-list-get-all-items (point) struct prevs))
6769 (goto-char (if (< end eos) end eos)))))))
6770 (org-unlogged-message "CHILDREN")
6771 (save-excursion
6772 (goto-char eos)
6773 (outline-next-heading)
6774 (if (outline-invisible-p) (org-flag-heading nil)))
6775 (setq org-cycle-subtree-status 'children)
6776 (unless (org-before-first-heading-p)
6777 (run-hook-with-args 'org-cycle-hook 'children)))
6778 ((or children-skipped
6779 (and (eq last-command this-command)
6780 (eq org-cycle-subtree-status 'children)))
6781 ;; We just showed the children, or no children are there,
6782 ;; now show everything.
6783 (unless (org-before-first-heading-p)
6784 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6785 (outline-flag-region eoh eos nil)
6786 (org-unlogged-message
6787 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6788 (setq org-cycle-subtree-status 'subtree)
6789 (unless (org-before-first-heading-p)
6790 (run-hook-with-args 'org-cycle-hook 'subtree)))
6792 ;; Default action: hide the subtree.
6793 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6794 (outline-flag-region eoh eos t)
6795 (org-unlogged-message "FOLDED")
6796 (setq org-cycle-subtree-status 'folded)
6797 (unless (org-before-first-heading-p)
6798 (run-hook-with-args 'org-cycle-hook 'folded))))))
6800 ;;;###autoload
6801 (defun org-global-cycle (&optional arg)
6802 "Cycle the global visibility. For details see `org-cycle'.
6803 With \\[universal-argument] prefix arg, switch to startup visibility.
6804 With a numeric prefix, show all headlines up to that level."
6805 (interactive "P")
6806 (let ((org-cycle-include-plain-lists
6807 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6808 (cond
6809 ((integerp arg)
6810 (show-all)
6811 (hide-sublevels arg)
6812 (setq org-cycle-global-status 'contents))
6813 ((equal arg '(4))
6814 (org-set-startup-visibility)
6815 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6817 (org-cycle '(4))))))
6819 (defun org-set-startup-visibility ()
6820 "Set the visibility required by startup options and properties."
6821 (cond
6822 ((eq org-startup-folded t)
6823 (org-overview))
6824 ((eq org-startup-folded 'content)
6825 (org-content))
6826 ((or (eq org-startup-folded 'showeverything)
6827 (eq org-startup-folded nil))
6828 (show-all)))
6829 (unless (eq org-startup-folded 'showeverything)
6830 (if org-hide-block-startup (org-hide-block-all))
6831 (org-set-visibility-according-to-property 'no-cleanup)
6832 (org-cycle-hide-archived-subtrees 'all)
6833 (org-cycle-hide-drawers 'all)
6834 (org-cycle-show-empty-lines t)))
6836 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6837 "Switch subtree visibilities according to :VISIBILITY: property."
6838 (interactive)
6839 (let (org-show-entry-below state)
6840 (save-excursion
6841 (goto-char (point-min))
6842 (while (re-search-forward
6843 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6844 nil t)
6845 (setq state (match-string 1))
6846 (save-excursion
6847 (org-back-to-heading t)
6848 (hide-subtree)
6849 (org-reveal)
6850 (cond
6851 ((equal state '("fold" "folded"))
6852 (hide-subtree))
6853 ((equal state "children")
6854 (org-show-hidden-entry)
6855 (show-children))
6856 ((equal state "content")
6857 (save-excursion
6858 (save-restriction
6859 (org-narrow-to-subtree)
6860 (org-content))))
6861 ((member state '("all" "showall"))
6862 (show-subtree)))))
6863 (unless no-cleanup
6864 (org-cycle-hide-archived-subtrees 'all)
6865 (org-cycle-hide-drawers 'all)
6866 (org-cycle-show-empty-lines 'all)))))
6868 ;; This function uses outline-regexp instead of the more fundamental
6869 ;; org-outline-regexp so that org-cycle-global works outside of Org
6870 ;; buffers, where outline-regexp is needed.
6871 (defun org-overview ()
6872 "Switch to overview mode, showing only top-level headlines.
6873 Really, this shows all headlines with level equal or greater than the level
6874 of the first headline in the buffer. This is important, because if the
6875 first headline is not level one, then (hide-sublevels 1) gives confusing
6876 results."
6877 (interactive)
6878 (let ((pos (point))
6879 (level (save-excursion
6880 (goto-char (point-min))
6881 (if (re-search-forward (concat "^" outline-regexp) nil t)
6882 (progn
6883 (goto-char (match-beginning 0))
6884 (funcall outline-level))))))
6885 (and level (hide-sublevels level))
6886 (recenter '(4))
6887 (goto-char pos)))
6889 (defun org-content (&optional arg)
6890 "Show all headlines in the buffer, like a table of contents.
6891 With numerical argument N, show content up to level N."
6892 (interactive "P")
6893 (save-excursion
6894 ;; Visit all headings and show their offspring
6895 (and (integerp arg) (org-overview))
6896 (goto-char (point-max))
6897 (catch 'exit
6898 (while (and (progn (condition-case nil
6899 (outline-previous-visible-heading 1)
6900 (error (goto-char (point-min))))
6902 (looking-at org-outline-regexp))
6903 (if (integerp arg)
6904 (show-children (1- arg))
6905 (show-branches))
6906 (if (bobp) (throw 'exit nil))))))
6908 (defun org-optimize-window-after-visibility-change (state)
6909 "Adjust the window after a change in outline visibility.
6910 This function is the default value of the hook `org-cycle-hook'."
6911 (when (get-buffer-window (current-buffer))
6912 (cond
6913 ((eq state 'content) nil)
6914 ((eq state 'all) nil)
6915 ((eq state 'folded) nil)
6916 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6917 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6919 (defun org-remove-empty-overlays-at (pos)
6920 "Remove outline overlays that do not contain non-white stuff."
6921 (mapc
6922 (lambda (o)
6923 (and (eq 'outline (overlay-get o 'invisible))
6924 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6925 (overlay-end o))))
6926 (delete-overlay o)))
6927 (overlays-at pos)))
6929 (defun org-clean-visibility-after-subtree-move ()
6930 "Fix visibility issues after moving a subtree."
6931 ;; First, find a reasonable region to look at:
6932 ;; Start two siblings above, end three below
6933 (let* ((beg (save-excursion
6934 (and (org-get-last-sibling)
6935 (org-get-last-sibling))
6936 (point)))
6937 (end (save-excursion
6938 (and (org-get-next-sibling)
6939 (org-get-next-sibling)
6940 (org-get-next-sibling))
6941 (if (org-at-heading-p)
6942 (point-at-eol)
6943 (point))))
6944 (level (looking-at "\\*+"))
6945 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6946 (save-excursion
6947 (save-restriction
6948 (narrow-to-region beg end)
6949 (when re
6950 ;; Properly fold already folded siblings
6951 (goto-char (point-min))
6952 (while (re-search-forward re nil t)
6953 (if (and (not (outline-invisible-p))
6954 (save-excursion
6955 (goto-char (point-at-eol)) (outline-invisible-p)))
6956 (hide-entry))))
6957 (org-cycle-show-empty-lines 'overview)
6958 (org-cycle-hide-drawers 'overview)))))
6960 (defun org-cycle-show-empty-lines (state)
6961 "Show empty lines above all visible headlines.
6962 The region to be covered depends on STATE when called through
6963 `org-cycle-hook'. Lisp program can use t for STATE to get the
6964 entire buffer covered. Note that an empty line is only shown if there
6965 are at least `org-cycle-separator-lines' empty lines before the headline."
6966 (when (not (= org-cycle-separator-lines 0))
6967 (save-excursion
6968 (let* ((n (abs org-cycle-separator-lines))
6969 (re (cond
6970 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6971 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6972 (t (let ((ns (number-to-string (- n 2))))
6973 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6974 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6975 beg end b e)
6976 (cond
6977 ((memq state '(overview contents t))
6978 (setq beg (point-min) end (point-max)))
6979 ((memq state '(children folded))
6980 (setq beg (point) end (progn (org-end-of-subtree t t)
6981 (beginning-of-line 2)
6982 (point)))))
6983 (when beg
6984 (goto-char beg)
6985 (while (re-search-forward re end t)
6986 (unless (get-char-property (match-end 1) 'invisible)
6987 (setq e (match-end 1))
6988 (if (< org-cycle-separator-lines 0)
6989 (setq b (save-excursion
6990 (goto-char (match-beginning 0))
6991 (org-back-over-empty-lines)
6992 (if (save-excursion
6993 (goto-char (max (point-min) (1- (point))))
6994 (org-at-heading-p))
6995 (1- (point))
6996 (point))))
6997 (setq b (match-beginning 1)))
6998 (outline-flag-region b e nil)))))))
6999 ;; Never hide empty lines at the end of the file.
7000 (save-excursion
7001 (goto-char (point-max))
7002 (outline-previous-heading)
7003 (outline-end-of-heading)
7004 (if (and (looking-at "[ \t\n]+")
7005 (= (match-end 0) (point-max)))
7006 (outline-flag-region (point) (match-end 0) nil))))
7008 (defun org-show-empty-lines-in-parent ()
7009 "Move to the parent and re-show empty lines before visible headlines."
7010 (save-excursion
7011 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7012 (org-cycle-show-empty-lines context))))
7014 (defun org-files-list ()
7015 "Return `org-agenda-files' list, plus all open org-mode files.
7016 This is useful for operations that need to scan all of a user's
7017 open and agenda-wise Org files."
7018 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7019 (dolist (buf (buffer-list))
7020 (with-current-buffer buf
7021 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7022 (let ((file (expand-file-name (buffer-file-name))))
7023 (unless (member file files)
7024 (push file files))))))
7025 files))
7027 (defsubst org-entry-beginning-position ()
7028 "Return the beginning position of the current entry."
7029 (save-excursion (outline-back-to-heading t) (point)))
7031 (defsubst org-entry-end-position ()
7032 "Return the end position of the current entry."
7033 (save-excursion (outline-next-heading) (point)))
7035 (defun org-cycle-hide-drawers (state)
7036 "Re-hide all drawers after a visibility state change."
7037 (when (and (derived-mode-p 'org-mode)
7038 (not (memq state '(overview folded contents))))
7039 (save-excursion
7040 (let* ((globalp (memq state '(contents all)))
7041 (beg (if globalp (point-min) (point)))
7042 (end (if globalp (point-max)
7043 (if (eq state 'children)
7044 (save-excursion (outline-next-heading) (point))
7045 (org-end-of-subtree t)))))
7046 (goto-char beg)
7047 (while (re-search-forward org-drawer-regexp end t)
7048 (org-flag-drawer t))))))
7050 (defun org-cycle-hide-inline-tasks (state)
7051 "Re-hide inline tasks when switching to 'contents or 'children
7052 visibility state."
7053 (case state
7054 (contents
7055 (when (org-bound-and-true-p org-inlinetask-min-level)
7056 (hide-sublevels (1- org-inlinetask-min-level))))
7057 (children
7058 (when (featurep 'org-inlinetask)
7059 (save-excursion
7060 (while (and (outline-next-heading)
7061 (org-inlinetask-at-task-p))
7062 (org-inlinetask-toggle-visibility)
7063 (org-inlinetask-goto-end)))))))
7065 (defun org-flag-drawer (flag)
7066 "When FLAG is non-nil, hide the drawer we are within.
7067 Otherwise make it visible."
7068 (save-excursion
7069 (beginning-of-line 1)
7070 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7071 (let ((b (match-end 0)))
7072 (if (re-search-forward
7073 "^[ \t]*:END:"
7074 (save-excursion (outline-next-heading) (point)) t)
7075 (outline-flag-region b (point-at-eol) flag)
7076 (user-error ":END: line missing at position %s" b))))))
7078 (defun org-subtree-end-visible-p ()
7079 "Is the end of the current subtree visible?"
7080 (pos-visible-in-window-p
7081 (save-excursion (org-end-of-subtree t) (point))))
7083 (defun org-first-headline-recenter (&optional N)
7084 "Move cursor to the first headline and recenter the headline.
7085 Optional argument N means put the headline into the Nth line of the window."
7086 (goto-char (point-min))
7087 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7088 (beginning-of-line)
7089 (recenter (prefix-numeric-value N))))
7091 ;;; Saving and restoring visibility
7093 (defun org-outline-overlay-data (&optional use-markers)
7094 "Return a list of the locations of all outline overlays.
7095 These are overlays with the `invisible' property value `outline'.
7096 The return value is a list of cons cells, with start and stop
7097 positions for each overlay.
7098 If USE-MARKERS is set, return the positions as markers."
7099 (let (beg end)
7100 (save-excursion
7101 (save-restriction
7102 (widen)
7103 (delq nil
7104 (mapcar (lambda (o)
7105 (when (eq (overlay-get o 'invisible) 'outline)
7106 (setq beg (overlay-start o)
7107 end (overlay-end o))
7108 (and beg end (> end beg)
7109 (if use-markers
7110 (cons (move-marker (make-marker) beg)
7111 (move-marker (make-marker) end))
7112 (cons beg end)))))
7113 (overlays-in (point-min) (point-max))))))))
7115 (defun org-set-outline-overlay-data (data)
7116 "Create visibility overlays for all positions in DATA.
7117 DATA should have been made by `org-outline-overlay-data'."
7118 (let (o)
7119 (save-excursion
7120 (save-restriction
7121 (widen)
7122 (show-all)
7123 (mapc (lambda (c)
7124 (outline-flag-region (car c) (cdr c) t))
7125 data)))))
7127 ;;; Folding of blocks
7129 (defvar org-hide-block-overlays nil
7130 "Overlays hiding blocks.")
7131 (make-variable-buffer-local 'org-hide-block-overlays)
7133 (defun org-block-map (function &optional start end)
7134 "Call FUNCTION at the head of all source blocks in the current buffer.
7135 Optional arguments START and END can be used to limit the range."
7136 (let ((start (or start (point-min)))
7137 (end (or end (point-max))))
7138 (save-excursion
7139 (goto-char start)
7140 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7141 (save-excursion
7142 (save-match-data
7143 (goto-char (match-beginning 0))
7144 (funcall function)))))))
7146 (defun org-hide-block-toggle-all ()
7147 "Toggle the visibility of all blocks in the current buffer."
7148 (org-block-map #'org-hide-block-toggle))
7150 (defun org-hide-block-all ()
7151 "Fold all blocks in the current buffer."
7152 (interactive)
7153 (org-show-block-all)
7154 (org-block-map #'org-hide-block-toggle-maybe))
7156 (defun org-show-block-all ()
7157 "Unfold all blocks in the current buffer."
7158 (interactive)
7159 (mapc 'delete-overlay org-hide-block-overlays)
7160 (setq org-hide-block-overlays nil))
7162 (defun org-hide-block-toggle-maybe ()
7163 "Toggle visibility of block at point."
7164 (interactive)
7165 (let ((case-fold-search t))
7166 (if (save-excursion
7167 (beginning-of-line 1)
7168 (looking-at org-block-regexp))
7169 (progn (org-hide-block-toggle)
7170 t) ;; to signal that we took action
7171 nil))) ;; to signal that we did not
7173 (defun org-hide-block-toggle (&optional force)
7174 "Toggle the visibility of the current block."
7175 (interactive)
7176 (save-excursion
7177 (beginning-of-line)
7178 (if (re-search-forward org-block-regexp nil t)
7179 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7180 (end (match-end 0)) ;; end of entire body
7182 (if (memq t (mapcar (lambda (overlay)
7183 (eq (overlay-get overlay 'invisible)
7184 'org-hide-block))
7185 (overlays-at start)))
7186 (if (or (not force) (eq force 'off))
7187 (mapc (lambda (ov)
7188 (when (member ov org-hide-block-overlays)
7189 (setq org-hide-block-overlays
7190 (delq ov org-hide-block-overlays)))
7191 (when (eq (overlay-get ov 'invisible)
7192 'org-hide-block)
7193 (delete-overlay ov)))
7194 (overlays-at start)))
7195 (setq ov (make-overlay start end))
7196 (overlay-put ov 'invisible 'org-hide-block)
7197 ;; make the block accessible to isearch
7198 (overlay-put
7199 ov 'isearch-open-invisible
7200 (lambda (ov)
7201 (when (member ov org-hide-block-overlays)
7202 (setq org-hide-block-overlays
7203 (delq ov org-hide-block-overlays)))
7204 (when (eq (overlay-get ov 'invisible)
7205 'org-hide-block)
7206 (delete-overlay ov))))
7207 (push ov org-hide-block-overlays)))
7208 (user-error "Not looking at a source block"))))
7210 ;; org-tab-after-check-for-cycling-hook
7211 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7212 ;; Remove overlays when changing major mode
7213 (add-hook 'org-mode-hook
7214 (lambda () (org-add-hook 'change-major-mode-hook
7215 'org-show-block-all 'append 'local)))
7217 ;;; Org-goto
7219 (defvar org-goto-window-configuration nil)
7220 (defvar org-goto-marker nil)
7221 (defvar org-goto-map)
7222 (defun org-goto-map ()
7223 "Set the keymap `org-goto'."
7224 (setq org-goto-map
7225 (let ((map (make-sparse-keymap)))
7226 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7227 mouse-drag-region universal-argument org-occur))
7228 cmd)
7229 (while (setq cmd (pop cmds))
7230 (substitute-key-definition cmd cmd map global-map)))
7231 (suppress-keymap map)
7232 (org-defkey map "\C-m" 'org-goto-ret)
7233 (org-defkey map [(return)] 'org-goto-ret)
7234 (org-defkey map [(left)] 'org-goto-left)
7235 (org-defkey map [(right)] 'org-goto-right)
7236 (org-defkey map [(control ?g)] 'org-goto-quit)
7237 (org-defkey map "\C-i" 'org-cycle)
7238 (org-defkey map [(tab)] 'org-cycle)
7239 (org-defkey map [(down)] 'outline-next-visible-heading)
7240 (org-defkey map [(up)] 'outline-previous-visible-heading)
7241 (if org-goto-auto-isearch
7242 (if (fboundp 'define-key-after)
7243 (define-key-after map [t] 'org-goto-local-auto-isearch)
7244 nil)
7245 (org-defkey map "q" 'org-goto-quit)
7246 (org-defkey map "n" 'outline-next-visible-heading)
7247 (org-defkey map "p" 'outline-previous-visible-heading)
7248 (org-defkey map "f" 'outline-forward-same-level)
7249 (org-defkey map "b" 'outline-backward-same-level)
7250 (org-defkey map "u" 'outline-up-heading))
7251 (org-defkey map "/" 'org-occur)
7252 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7253 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7254 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7255 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7256 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7257 map)))
7259 (defconst org-goto-help
7260 "Browse buffer copy, to find location or copy text.%s
7261 RET=jump to location C-g=quit and return to previous location
7262 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7264 (defvar org-goto-start-pos) ; dynamically scoped parameter
7266 (defun org-goto (&optional alternative-interface)
7267 "Look up a different location in the current file, keeping current visibility.
7269 When you want look-up or go to a different location in a
7270 document, the fastest way is often to fold the entire buffer and
7271 then dive into the tree. This method has the disadvantage, that
7272 the previous location will be folded, which may not be what you
7273 want.
7275 This command works around this by showing a copy of the current
7276 buffer in an indirect buffer, in overview mode. You can dive
7277 into the tree in that copy, use org-occur and incremental search
7278 to find a location. When pressing RET or `Q', the command
7279 returns to the original buffer in which the visibility is still
7280 unchanged. After RET it will also jump to the location selected
7281 in the indirect buffer and expose the headline hierarchy above.
7283 With a prefix argument, use the alternative interface: e.g. if
7284 `org-goto-interface' is 'outline use 'outline-path-completion."
7285 (interactive "P")
7286 (org-goto-map)
7287 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7288 (org-refile-use-outline-path t)
7289 (org-refile-target-verify-function nil)
7290 (interface
7291 (if (not alternative-interface)
7292 org-goto-interface
7293 (if (eq org-goto-interface 'outline)
7294 'outline-path-completion
7295 'outline)))
7296 (org-goto-start-pos (point))
7297 (selected-point
7298 (if (eq interface 'outline)
7299 (car (org-get-location (current-buffer) org-goto-help))
7300 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7301 (org-refile-check-position pa)
7302 (nth 3 pa)))))
7303 (if selected-point
7304 (progn
7305 (org-mark-ring-push org-goto-start-pos)
7306 (goto-char selected-point)
7307 (if (or (outline-invisible-p) (org-invisible-p2))
7308 (org-show-context 'org-goto)))
7309 (message "Quit"))))
7311 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7312 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7313 (defvar org-goto-local-auto-isearch-map) ; defined below
7315 (defun org-get-location (buf help)
7316 "Let the user select a location in the Org-mode buffer BUF.
7317 This function uses a recursive edit. It returns the selected position
7318 or nil."
7319 (org-no-popups
7320 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7321 (isearch-hide-immediately nil)
7322 (isearch-search-fun-function
7323 (lambda () 'org-goto-local-search-headings))
7324 (org-goto-selected-point org-goto-exit-command))
7325 (save-excursion
7326 (save-window-excursion
7327 (delete-other-windows)
7328 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7329 (org-pop-to-buffer-same-window
7330 (condition-case nil
7331 (make-indirect-buffer (current-buffer) "*org-goto*")
7332 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7333 (with-output-to-temp-buffer "*Org Help*"
7334 (princ (format help (if org-goto-auto-isearch
7335 " Just type for auto-isearch."
7336 " n/p/f/b/u to navigate, q to quit."))))
7337 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7338 (setq buffer-read-only nil)
7339 (let ((org-startup-truncated t)
7340 (org-startup-folded nil)
7341 (org-startup-align-all-tables nil))
7342 (org-mode)
7343 (org-overview))
7344 (setq buffer-read-only t)
7345 (if (and (boundp 'org-goto-start-pos)
7346 (integer-or-marker-p org-goto-start-pos))
7347 (let ((org-show-hierarchy-above t)
7348 (org-show-siblings t)
7349 (org-show-following-heading t))
7350 (goto-char org-goto-start-pos)
7351 (and (outline-invisible-p) (org-show-context)))
7352 (goto-char (point-min)))
7353 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7354 (message "Select location and press RET")
7355 (use-local-map org-goto-map)
7356 (recursive-edit)))
7357 (kill-buffer "*org-goto*")
7358 (cons org-goto-selected-point org-goto-exit-command))))
7360 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7361 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7362 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7363 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7365 (defun org-goto-local-search-headings (string bound noerror)
7366 "Search and make sure that any matches are in headlines."
7367 (catch 'return
7368 (while (if isearch-forward
7369 (search-forward string bound noerror)
7370 (search-backward string bound noerror))
7371 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7372 (and (member :headline context)
7373 (not (member :tags context))))
7374 (throw 'return (point))))))
7376 (defun org-goto-local-auto-isearch ()
7377 "Start isearch."
7378 (interactive)
7379 (goto-char (point-min))
7380 (let ((keys (this-command-keys)))
7381 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7382 (isearch-mode t)
7383 (isearch-process-search-char (string-to-char keys)))))
7385 (defun org-goto-ret (&optional arg)
7386 "Finish `org-goto' by going to the new location."
7387 (interactive "P")
7388 (setq org-goto-selected-point (point)
7389 org-goto-exit-command 'return)
7390 (throw 'exit nil))
7392 (defun org-goto-left ()
7393 "Finish `org-goto' by going to the new location."
7394 (interactive)
7395 (if (org-at-heading-p)
7396 (progn
7397 (beginning-of-line 1)
7398 (setq org-goto-selected-point (point)
7399 org-goto-exit-command 'left)
7400 (throw 'exit nil))
7401 (user-error "Not on a heading")))
7403 (defun org-goto-right ()
7404 "Finish `org-goto' by going to the new location."
7405 (interactive)
7406 (if (org-at-heading-p)
7407 (progn
7408 (setq org-goto-selected-point (point)
7409 org-goto-exit-command 'right)
7410 (throw 'exit nil))
7411 (user-error "Not on a heading")))
7413 (defun org-goto-quit ()
7414 "Finish `org-goto' without cursor motion."
7415 (interactive)
7416 (setq org-goto-selected-point nil)
7417 (setq org-goto-exit-command 'quit)
7418 (throw 'exit nil))
7420 ;;; Indirect buffer display of subtrees
7422 (defvar org-indirect-dedicated-frame nil
7423 "This is the frame being used for indirect tree display.")
7424 (defvar org-last-indirect-buffer nil)
7426 (defun org-tree-to-indirect-buffer (&optional arg)
7427 "Create indirect buffer and narrow it to current subtree.
7428 With a numerical prefix ARG, go up to this level and then take that tree.
7429 If ARG is negative, go up that many levels.
7431 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7432 indirect buffer previously made with this command, to avoid proliferation of
7433 indirect buffers. However, when you call the command with a \
7434 \\[universal-argument] prefix, or
7435 when `org-indirect-buffer-display' is `new-frame', the last buffer
7436 is kept so that you can work with several indirect buffers at the same time.
7437 If `org-indirect-buffer-display' is `dedicated-frame', the \
7438 \\[universal-argument] prefix also
7439 requests that a new frame be made for the new buffer, so that the dedicated
7440 frame is not changed."
7441 (interactive "P")
7442 (let ((cbuf (current-buffer))
7443 (cwin (selected-window))
7444 (pos (point))
7445 beg end level heading ibuf)
7446 (save-excursion
7447 (org-back-to-heading t)
7448 (when (numberp arg)
7449 (setq level (org-outline-level))
7450 (if (< arg 0) (setq arg (+ level arg)))
7451 (while (> (setq level (org-outline-level)) arg)
7452 (org-up-heading-safe)))
7453 (setq beg (point)
7454 heading (org-get-heading))
7455 (org-end-of-subtree t t)
7456 (if (org-at-heading-p) (backward-char 1))
7457 (setq end (point)))
7458 (if (and (buffer-live-p org-last-indirect-buffer)
7459 (not (eq org-indirect-buffer-display 'new-frame))
7460 (not arg))
7461 (kill-buffer org-last-indirect-buffer))
7462 (setq ibuf (org-get-indirect-buffer cbuf)
7463 org-last-indirect-buffer ibuf)
7464 (cond
7465 ((or (eq org-indirect-buffer-display 'new-frame)
7466 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7467 (select-frame (make-frame))
7468 (delete-other-windows)
7469 (org-pop-to-buffer-same-window ibuf)
7470 (org-set-frame-title heading))
7471 ((eq org-indirect-buffer-display 'dedicated-frame)
7472 (raise-frame
7473 (select-frame (or (and org-indirect-dedicated-frame
7474 (frame-live-p org-indirect-dedicated-frame)
7475 org-indirect-dedicated-frame)
7476 (setq org-indirect-dedicated-frame (make-frame)))))
7477 (delete-other-windows)
7478 (org-pop-to-buffer-same-window ibuf)
7479 (org-set-frame-title (concat "Indirect: " heading)))
7480 ((eq org-indirect-buffer-display 'current-window)
7481 (org-pop-to-buffer-same-window ibuf))
7482 ((eq org-indirect-buffer-display 'other-window)
7483 (pop-to-buffer ibuf))
7484 (t (error "Invalid value")))
7485 (if (featurep 'xemacs)
7486 (save-excursion (org-mode) (turn-on-font-lock)))
7487 (narrow-to-region beg end)
7488 (show-all)
7489 (goto-char pos)
7490 (run-hook-with-args 'org-cycle-hook 'all)
7491 (and (window-live-p cwin) (select-window cwin))))
7493 (defun org-get-indirect-buffer (&optional buffer)
7494 (setq buffer (or buffer (current-buffer)))
7495 (let ((n 1) (base (buffer-name buffer)) bname)
7496 (while (buffer-live-p
7497 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7498 (setq n (1+ n)))
7499 (condition-case nil
7500 (make-indirect-buffer buffer bname 'clone)
7501 (error (make-indirect-buffer buffer bname)))))
7503 (defun org-set-frame-title (title)
7504 "Set the title of the current frame to the string TITLE."
7505 ;; FIXME: how to name a single frame in XEmacs???
7506 (unless (featurep 'xemacs)
7507 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7509 ;;;; Structure editing
7511 ;;; Inserting headlines
7513 (defun org-previous-line-empty-p (&optional next)
7514 "Is the previous line a blank line?
7515 When NEXT is non-nil, check the next line instead."
7516 (save-excursion
7517 (and (not (bobp))
7518 (or (beginning-of-line (if next 2 0)) t)
7519 (save-match-data
7520 (looking-at "[ \t]*$")))))
7522 (defun org-insert-heading (&optional arg invisible-ok)
7523 "Insert a new heading or item with same depth at point.
7524 If point is in a plain list and ARG is nil, create a new list item.
7525 With one universal prefix argument, insert a heading even in lists.
7526 With two universal prefix arguments, insert the heading at the end
7527 of the parent subtree.
7529 If point is at the beginning of a headline, insert a sibling before
7530 the current headline. If point is not at the beginning, split the line
7531 and create a new headline with the text in the current line after point
7532 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7534 If point is at the beginning of a normal line, turn this line into
7535 a heading.
7537 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7538 This is important for non-interactive uses of the command."
7539 (interactive "P")
7540 (if (org-called-interactively-p 'any) (org-reveal))
7541 (let ((itemp (org-in-item-p))
7542 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7543 (respect-content (or org-insert-heading-respect-content
7544 (equal arg '(16))))
7545 (initial-content "")
7546 (adjust-empty-lines t))
7548 (cond
7550 ((or (= (buffer-size) 0)
7551 (and (not (save-excursion
7552 (and (ignore-errors (org-back-to-heading invisible-ok))
7553 (org-at-heading-p))))
7554 (or arg (not itemp))))
7555 ;; At beginning of buffer or so high up that only a heading
7556 ;; makes sense.
7557 (insert
7558 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7559 (if (org-in-src-block-p) ",* " "* "))
7560 (run-hooks 'org-insert-heading-hook))
7562 ((and itemp (not (equal arg '(4))))
7563 ;; Insert an item
7564 (org-insert-item))
7567 ;; Insert a heading
7568 (save-restriction
7569 (widen)
7570 (let* ((level nil)
7571 (on-heading (org-at-heading-p))
7572 (empty-line-p (if on-heading
7573 (org-previous-line-empty-p)
7574 ;; We will decide later
7575 nil))
7576 ;; Get a level string to fall back on
7577 (fix-level
7578 (save-excursion
7579 (org-back-to-heading t)
7580 (if (org-previous-line-empty-p) (setq empty-line-p t))
7581 (looking-at org-outline-regexp)
7582 (make-string (1- (length (match-string 0))) ?*)))
7583 (stars
7584 (save-excursion
7585 (condition-case nil
7586 (progn
7587 (org-back-to-heading invisible-ok)
7588 (when (and (not on-heading)
7589 (featurep 'org-inlinetask)
7590 (integerp org-inlinetask-min-level)
7591 (>= (length (match-string 0))
7592 org-inlinetask-min-level))
7593 ;; Find a heading level before the inline task
7594 (while (and (setq level (org-up-heading-safe))
7595 (>= level org-inlinetask-min-level)))
7596 (if (org-at-heading-p)
7597 (org-back-to-heading invisible-ok)
7598 (error "This should not happen")))
7599 (unless (and (save-excursion
7600 (save-match-data
7601 (org-backward-heading-same-level
7602 1 invisible-ok))
7603 (= (point) (match-beginning 0)))
7604 (not (org-previous-line-empty-p t)))
7605 (setq empty-line-p (or empty-line-p
7606 (org-previous-line-empty-p))))
7607 (match-string 0))
7608 (error (or fix-level "* ")))))
7609 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7610 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7611 pos hide-previous previous-pos)
7613 ;; If we insert after content, move there and clean up whitespace
7614 (when respect-content
7615 (org-end-of-subtree nil t)
7616 (skip-chars-backward " \r\n")
7617 (and (looking-at "[ \t]+") (replace-match ""))
7618 (unless (eobp) (forward-char 1))
7619 (when (looking-at "^\\*")
7620 (unless (bobp) (backward-char 1))
7621 (insert "\n")))
7623 ;; If we are splitting, grab the text that should be moved to the new headline
7624 (when may-split
7625 (if (org-on-heading-p)
7626 ;; This is a heading, we split intelligently (keeping tags)
7627 (let ((pos (point)))
7628 (goto-char (point-at-bol))
7629 (unless (looking-at org-complex-heading-regexp)
7630 (error "This should not happen"))
7631 (when (and (match-beginning 4)
7632 (> pos (match-beginning 4))
7633 (< pos (match-end 4)))
7634 (setq initial-content (buffer-substring pos (match-end 4)))
7635 (goto-char pos)
7636 (delete-region (point) (match-end 4))
7637 (if (looking-at "[ \t]*$")
7638 (replace-match "")
7639 (insert (make-string (length initial-content) ?\ )))
7640 (setq initial-content (org-trim initial-content)))
7641 (goto-char pos))
7642 ;; a normal line
7643 (unless (bolp)
7644 (setq initial-content (buffer-substring (point) (point-at-eol)))
7645 (delete-region (point) (point-at-eol))
7646 (setq initial-content (org-trim initial-content)))))
7648 ;; If we are at the beginning of the line, insert before it. Else after
7649 (cond
7650 ((and (bolp) (looking-at "[ \t]*$")))
7651 ((and (bolp) (not (looking-at "[ \t]*$")))
7652 (open-line 1))
7654 (goto-char (point-at-eol))
7655 (insert "\n")))
7657 ;; Insert the new heading
7658 (insert stars)
7659 (just-one-space)
7660 (insert initial-content)
7661 (when adjust-empty-lines
7662 (if (or (not blank)
7663 (and blank (not (org-previous-line-empty-p))))
7664 (org-N-empty-lines-before-current (if blank 1 0))))
7665 (run-hooks 'org-insert-heading-hook)))))))
7667 (defun org-N-empty-lines-before-current (N)
7668 "Make the number of empty lines before current exactly N.
7669 So this will delete or add empty lines."
7670 (save-excursion
7671 (goto-char (point-at-bol))
7672 (if (looking-back "\\s-+" nil 'greedy)
7673 (replace-match ""))
7674 (or (bobp) (insert "\n"))
7675 (while (> N 0)
7676 (insert "\n")
7677 (setq N (1- N)))))
7679 (defun org-get-heading (&optional no-tags no-todo)
7680 "Return the heading of the current entry, without the stars.
7681 When NO-TAGS is non-nil, don't include tags.
7682 When NO-TODO is non-nil, don't include TODO keywords."
7683 (save-excursion
7684 (org-back-to-heading t)
7685 (cond
7686 ((and no-tags no-todo)
7687 (looking-at org-complex-heading-regexp)
7688 (match-string 4))
7689 (no-tags
7690 (looking-at (concat org-outline-regexp
7691 "\\(.*?\\)"
7692 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7693 (match-string 1))
7694 (no-todo
7695 (looking-at org-todo-line-regexp)
7696 (match-string 3))
7697 (t (looking-at org-heading-regexp)
7698 (match-string 2)))))
7700 (defvar orgstruct-mode) ; defined below
7702 (defun org-heading-components ()
7703 "Return the components of the current heading.
7704 This is a list with the following elements:
7705 - the level as an integer
7706 - the reduced level, different if `org-odd-levels-only' is set.
7707 - the TODO keyword, or nil
7708 - the priority character, like ?A, or nil if no priority is given
7709 - the headline text itself, or the tags string if no headline text
7710 - the tags string, or nil."
7711 (save-excursion
7712 (org-back-to-heading t)
7713 (if (let (case-fold-search)
7714 (looking-at
7715 (if orgstruct-mode
7716 org-heading-regexp
7717 org-complex-heading-regexp)))
7718 (if orgstruct-mode
7719 (list (length (match-string 1))
7720 (org-reduced-level (length (match-string 1)))
7723 (match-string 2)
7724 nil)
7725 (list (length (match-string 1))
7726 (org-reduced-level (length (match-string 1)))
7727 (org-match-string-no-properties 2)
7728 (and (match-end 3) (aref (match-string 3) 2))
7729 (org-match-string-no-properties 4)
7730 (org-match-string-no-properties 5))))))
7732 (defun org-get-entry ()
7733 "Get the entry text, after heading, entire subtree."
7734 (save-excursion
7735 (org-back-to-heading t)
7736 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7738 (defun org-insert-heading-after-current ()
7739 "Insert a new heading with same level as current, after current subtree."
7740 (interactive)
7741 (org-back-to-heading)
7742 (org-insert-heading)
7743 (org-move-subtree-down)
7744 (end-of-line 1))
7746 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7747 "Insert heading with `org-insert-heading-respect-content' set to t."
7748 (interactive "P")
7749 (let ((org-insert-heading-respect-content t))
7750 (org-insert-heading '(4) invisible-ok)))
7752 (defun org-insert-todo-heading-respect-content (&optional force-state)
7753 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7754 (interactive "P")
7755 (let ((org-insert-heading-respect-content t))
7756 (org-insert-todo-heading force-state '(4))))
7758 (defun org-insert-todo-heading (arg &optional force-heading)
7759 "Insert a new heading with the same level and TODO state as current heading.
7760 If the heading has no TODO state, or if the state is DONE, use the first
7761 state (TODO by default). Also one prefix arg, force first state. With two
7762 prefix args, force inserting at the end of the parent subtree."
7763 (interactive "P")
7764 (when (or force-heading (not (org-insert-item 'checkbox)))
7765 (org-insert-heading (or (and (equal arg '(16)) '(16))
7766 force-heading))
7767 (save-excursion
7768 (org-back-to-heading)
7769 (outline-previous-heading)
7770 (looking-at org-todo-line-regexp))
7771 (let*
7772 ((new-mark-x
7773 (if (or arg
7774 (not (match-beginning 2))
7775 (member (match-string 2) org-done-keywords))
7776 (car org-todo-keywords-1)
7777 (match-string 2)))
7778 (new-mark
7780 (run-hook-with-args-until-success
7781 'org-todo-get-default-hook new-mark-x nil)
7782 new-mark-x)))
7783 (beginning-of-line 1)
7784 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7785 (if org-treat-insert-todo-heading-as-state-change
7786 (org-todo new-mark)
7787 (insert new-mark " "))))
7788 (when org-provide-todo-statistics
7789 (org-update-parent-todo-statistics))))
7791 (defun org-insert-subheading (arg)
7792 "Insert a new subheading and demote it.
7793 Works for outline headings and for plain lists alike."
7794 (interactive "P")
7795 (org-insert-heading arg)
7796 (cond
7797 ((org-at-heading-p) (org-do-demote))
7798 ((org-at-item-p) (org-indent-item))))
7800 (defun org-insert-todo-subheading (arg)
7801 "Insert a new subheading with TODO keyword or checkbox and demote it.
7802 Works for outline headings and for plain lists alike."
7803 (interactive "P")
7804 (org-insert-todo-heading arg)
7805 (cond
7806 ((org-at-heading-p) (org-do-demote))
7807 ((org-at-item-p) (org-indent-item))))
7809 ;;; Promotion and Demotion
7811 (defvar org-after-demote-entry-hook nil
7812 "Hook run after an entry has been demoted.
7813 The cursor will be at the beginning of the entry.
7814 When a subtree is being demoted, the hook will be called for each node.")
7816 (defvar org-after-promote-entry-hook nil
7817 "Hook run after an entry has been promoted.
7818 The cursor will be at the beginning of the entry.
7819 When a subtree is being promoted, the hook will be called for each node.")
7821 (defun org-promote-subtree ()
7822 "Promote the entire subtree.
7823 See also `org-promote'."
7824 (interactive)
7825 (save-excursion
7826 (org-with-limited-levels (org-map-tree 'org-promote)))
7827 (org-fix-position-after-promote))
7829 (defun org-demote-subtree ()
7830 "Demote the entire subtree. See `org-demote'.
7831 See also `org-promote'."
7832 (interactive)
7833 (save-excursion
7834 (org-with-limited-levels (org-map-tree 'org-demote)))
7835 (org-fix-position-after-promote))
7838 (defun org-do-promote ()
7839 "Promote the current heading higher up the tree.
7840 If the region is active in `transient-mark-mode', promote all headings
7841 in the region."
7842 (interactive)
7843 (save-excursion
7844 (if (org-region-active-p)
7845 (org-map-region 'org-promote (region-beginning) (region-end))
7846 (org-promote)))
7847 (org-fix-position-after-promote))
7849 (defun org-do-demote ()
7850 "Demote the current heading lower down the tree.
7851 If the region is active in `transient-mark-mode', demote all headings
7852 in the region."
7853 (interactive)
7854 (save-excursion
7855 (if (org-region-active-p)
7856 (org-map-region 'org-demote (region-beginning) (region-end))
7857 (org-demote)))
7858 (org-fix-position-after-promote))
7860 (defun org-fix-position-after-promote ()
7861 "Make sure that after pro/demotion cursor position is right."
7862 (let ((pos (point)))
7863 (when (save-excursion
7864 (beginning-of-line 1)
7865 (looking-at org-todo-line-regexp)
7866 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7867 (cond ((eobp) (insert " "))
7868 ((eolp) (insert " "))
7869 ((equal (char-after) ?\ ) (forward-char 1))))))
7871 (defun org-current-level ()
7872 "Return the level of the current entry, or nil if before the first headline.
7873 The level is the number of stars at the beginning of the headline."
7874 (save-excursion
7875 (org-with-limited-levels
7876 (if (ignore-errors (org-back-to-heading t))
7877 (funcall outline-level)))))
7879 (defun org-get-previous-line-level ()
7880 "Return the outline depth of the last headline before the current line.
7881 Returns 0 for the first headline in the buffer, and nil if before the
7882 first headline."
7883 (and (org-current-level)
7884 (or (and (/= (line-beginning-position) (point-min))
7885 (save-excursion (beginning-of-line 0) (org-current-level)))
7886 0)))
7888 (defun org-reduced-level (l)
7889 "Compute the effective level of a heading.
7890 This takes into account the setting of `org-odd-levels-only'."
7891 (cond
7892 ((zerop l) 0)
7893 (org-odd-levels-only (1+ (floor (/ l 2))))
7894 (t l)))
7896 (defun org-level-increment ()
7897 "Return the number of stars that will be added or removed at a
7898 time to headlines when structure editing, based on the value of
7899 `org-odd-levels-only'."
7900 (if org-odd-levels-only 2 1))
7902 (defun org-get-valid-level (level &optional change)
7903 "Rectify a level change under the influence of `org-odd-levels-only'
7904 LEVEL is a current level, CHANGE is by how much the level should be
7905 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7906 even level numbers will become the next higher odd number."
7907 (if org-odd-levels-only
7908 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7909 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7910 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7911 (max 1 (+ level (or change 0)))))
7913 (if (boundp 'define-obsolete-function-alias)
7914 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7915 (define-obsolete-function-alias 'org-get-legal-level
7916 'org-get-valid-level)
7917 (define-obsolete-function-alias 'org-get-legal-level
7918 'org-get-valid-level "23.1")))
7920 (defun org-promote ()
7921 "Promote the current heading higher up the tree.
7922 If the region is active in `transient-mark-mode', promote all headings
7923 in the region."
7924 (org-back-to-heading t)
7925 (let* ((level (save-match-data (funcall outline-level)))
7926 (after-change-functions (remove 'flyspell-after-change-function
7927 after-change-functions))
7928 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7929 (diff (abs (- level (length up-head) -1))))
7930 (cond ((and (= level 1) org-called-with-limited-levels
7931 org-allow-promoting-top-level-subtree)
7932 (replace-match "# " nil t))
7933 ((= level 1)
7934 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7935 (t (replace-match up-head nil t)))
7936 ;; Fixup tag positioning
7937 (unless (= level 1)
7938 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7939 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7940 (run-hooks 'org-after-promote-entry-hook)))
7942 (defun org-demote ()
7943 "Demote the current heading lower down the tree.
7944 If the region is active in `transient-mark-mode', demote all headings
7945 in the region."
7946 (org-back-to-heading t)
7947 (let* ((level (save-match-data (funcall outline-level)))
7948 (after-change-functions (remove 'flyspell-after-change-function
7949 after-change-functions))
7950 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7951 (diff (abs (- level (length down-head) -1))))
7952 (replace-match down-head nil t)
7953 ;; Fixup tag positioning
7954 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7955 (if org-adapt-indentation (org-fixup-indentation diff))
7956 (run-hooks 'org-after-demote-entry-hook)))
7958 (defun org-cycle-level ()
7959 "Cycle the level of an empty headline through possible states.
7960 This goes first to child, then to parent, level, then up the hierarchy.
7961 After top level, it switches back to sibling level."
7962 (interactive)
7963 (let ((org-adapt-indentation nil))
7964 (when (org-point-at-end-of-empty-headline)
7965 (setq this-command 'org-cycle-level) ; Only needed for caching
7966 (let ((cur-level (org-current-level))
7967 (prev-level (org-get-previous-line-level)))
7968 (cond
7969 ;; If first headline in file, promote to top-level.
7970 ((= prev-level 0)
7971 (loop repeat (/ (- cur-level 1) (org-level-increment))
7972 do (org-do-promote)))
7973 ;; If same level as prev, demote one.
7974 ((= prev-level cur-level)
7975 (org-do-demote))
7976 ;; If parent is top-level, promote to top level if not already.
7977 ((= prev-level 1)
7978 (loop repeat (/ (- cur-level 1) (org-level-increment))
7979 do (org-do-promote)))
7980 ;; If top-level, return to prev-level.
7981 ((= cur-level 1)
7982 (loop repeat (/ (- prev-level 1) (org-level-increment))
7983 do (org-do-demote)))
7984 ;; If less than prev-level, promote one.
7985 ((< cur-level prev-level)
7986 (org-do-promote))
7987 ;; If deeper than prev-level, promote until higher than
7988 ;; prev-level.
7989 ((> cur-level prev-level)
7990 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7991 do (org-do-promote))))
7992 t))))
7994 (defun org-map-tree (fun)
7995 "Call FUN for every heading underneath the current one."
7996 (org-back-to-heading)
7997 (let ((level (funcall outline-level)))
7998 (save-excursion
7999 (funcall fun)
8000 (while (and (progn
8001 (outline-next-heading)
8002 (> (funcall outline-level) level))
8003 (not (eobp)))
8004 (funcall fun)))))
8006 (defun org-map-region (fun beg end)
8007 "Call FUN for every heading between BEG and END."
8008 (let ((org-ignore-region t))
8009 (save-excursion
8010 (setq end (copy-marker end))
8011 (goto-char beg)
8012 (if (and (re-search-forward org-outline-regexp-bol nil t)
8013 (< (point) end))
8014 (funcall fun))
8015 (while (and (progn
8016 (outline-next-heading)
8017 (< (point) end))
8018 (not (eobp)))
8019 (funcall fun)))))
8021 (defvar org-property-end-re) ; silence byte-compiler
8022 (defun org-fixup-indentation (diff)
8023 "Change the indentation in the current entry by DIFF.
8024 However, if any line in the current entry has no indentation, or if it
8025 would end up with no indentation after the change, nothing at all is done."
8026 (save-excursion
8027 (let ((end (save-excursion (outline-next-heading)
8028 (point-marker)))
8029 (prohibit (if (> diff 0)
8030 "^\\S-"
8031 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8032 col)
8033 (unless (save-excursion (end-of-line 1)
8034 (re-search-forward prohibit end t))
8035 (while (and (< (point) end)
8036 (re-search-forward "^[ \t]+" end t))
8037 (goto-char (match-end 0))
8038 (setq col (current-column))
8039 (if (< diff 0) (replace-match ""))
8040 (org-indent-to-column (+ diff col))))
8041 (move-marker end nil))))
8043 (defun org-convert-to-odd-levels ()
8044 "Convert an org-mode file with all levels allowed to one with odd levels.
8045 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8046 level 5 etc."
8047 (interactive)
8048 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8049 (let ((outline-level 'org-outline-level)
8050 (org-odd-levels-only nil) n)
8051 (save-excursion
8052 (goto-char (point-min))
8053 (while (re-search-forward "^\\*\\*+ " nil t)
8054 (setq n (- (length (match-string 0)) 2))
8055 (while (>= (setq n (1- n)) 0)
8056 (org-demote))
8057 (end-of-line 1))))))
8059 (defun org-convert-to-oddeven-levels ()
8060 "Convert an org-mode file with only odd levels to one with odd/even levels.
8061 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8062 file contains a section with an even level, conversion would
8063 destroy the structure of the file. An error is signaled in this
8064 case."
8065 (interactive)
8066 (goto-char (point-min))
8067 ;; First check if there are no even levels
8068 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8069 (org-show-context t)
8070 (error "Not all levels are odd in this file. Conversion not possible"))
8071 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8072 (let ((outline-regexp org-outline-regexp)
8073 (outline-level 'org-outline-level)
8074 (org-odd-levels-only nil) n)
8075 (save-excursion
8076 (goto-char (point-min))
8077 (while (re-search-forward "^\\*\\*+ " nil t)
8078 (setq n (/ (1- (length (match-string 0))) 2))
8079 (while (>= (setq n (1- n)) 0)
8080 (org-promote))
8081 (end-of-line 1))))))
8083 (defun org-tr-level (n)
8084 "Make N odd if required."
8085 (if org-odd-levels-only (1+ (/ n 2)) n))
8087 ;;; Vertical tree motion, cutting and pasting of subtrees
8089 (defun org-move-subtree-up (&optional arg)
8090 "Move the current subtree up past ARG headlines of the same level."
8091 (interactive "p")
8092 (org-move-subtree-down (- (prefix-numeric-value arg))))
8094 (defun org-move-subtree-down (&optional arg)
8095 "Move the current subtree down past ARG headlines of the same level."
8096 (interactive "p")
8097 (setq arg (prefix-numeric-value arg))
8098 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8099 'org-get-last-sibling))
8100 (ins-point (make-marker))
8101 (cnt (abs arg))
8102 (col (current-column))
8103 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8104 ;; Select the tree
8105 (org-back-to-heading)
8106 (setq beg0 (point))
8107 (save-excursion
8108 (setq ne-beg (org-back-over-empty-lines))
8109 (setq beg (point)))
8110 (save-match-data
8111 (save-excursion (outline-end-of-heading)
8112 (setq folded (outline-invisible-p)))
8113 (outline-end-of-subtree))
8114 (outline-next-heading)
8115 (setq ne-end (org-back-over-empty-lines))
8116 (setq end (point))
8117 (goto-char beg0)
8118 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8119 ;; include less whitespace
8120 (save-excursion
8121 (goto-char beg)
8122 (forward-line (- ne-beg ne-end))
8123 (setq beg (point))))
8124 ;; Find insertion point, with error handling
8125 (while (> cnt 0)
8126 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8127 (progn (goto-char beg0)
8128 (user-error "Cannot move past superior level or buffer limit")))
8129 (setq cnt (1- cnt)))
8130 (if (> arg 0)
8131 ;; Moving forward - still need to move over subtree
8132 (progn (org-end-of-subtree t t)
8133 (save-excursion
8134 (org-back-over-empty-lines)
8135 (or (bolp) (newline)))))
8136 (setq ne-ins (org-back-over-empty-lines))
8137 (move-marker ins-point (point))
8138 (setq txt (buffer-substring beg end))
8139 (org-save-markers-in-region beg end)
8140 (delete-region beg end)
8141 (org-remove-empty-overlays-at beg)
8142 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8143 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8144 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8145 (let ((bbb (point)))
8146 (insert-before-markers txt)
8147 (org-reinstall-markers-in-region bbb)
8148 (move-marker ins-point bbb))
8149 (or (bolp) (insert "\n"))
8150 (setq ins-end (point))
8151 (goto-char ins-point)
8152 (org-skip-whitespace)
8153 (when (and (< arg 0)
8154 (org-first-sibling-p)
8155 (> ne-ins ne-beg))
8156 ;; Move whitespace back to beginning
8157 (save-excursion
8158 (goto-char ins-end)
8159 (let ((kill-whole-line t))
8160 (kill-line (- ne-ins ne-beg)) (point)))
8161 (insert (make-string (- ne-ins ne-beg) ?\n)))
8162 (move-marker ins-point nil)
8163 (if folded
8164 (hide-subtree)
8165 (org-show-entry)
8166 (show-children)
8167 (org-cycle-hide-drawers 'children))
8168 (org-clean-visibility-after-subtree-move)
8169 ;; move back to the initial column we were at
8170 (move-to-column col)))
8172 (defvar org-subtree-clip ""
8173 "Clipboard for cut and paste of subtrees.
8174 This is actually only a copy of the kill, because we use the normal kill
8175 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8177 (defvar org-subtree-clip-folded nil
8178 "Was the last copied subtree folded?
8179 This is used to fold the tree back after pasting.")
8181 (defun org-cut-subtree (&optional n)
8182 "Cut the current subtree into the clipboard.
8183 With prefix arg N, cut this many sequential subtrees.
8184 This is a short-hand for marking the subtree and then cutting it."
8185 (interactive "p")
8186 (org-copy-subtree n 'cut))
8188 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8189 "Copy the current subtree it in the clipboard.
8190 With prefix arg N, copy this many sequential subtrees.
8191 This is a short-hand for marking the subtree and then copying it.
8192 If CUT is non-nil, actually cut the subtree.
8193 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8194 of some markers in the region, even if CUT is non-nil. This is
8195 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8196 (interactive "p")
8197 (let (beg end folded (beg0 (point)))
8198 (if (org-called-interactively-p 'any)
8199 (org-back-to-heading nil) ; take what looks like a subtree
8200 (org-back-to-heading t)) ; take what is really there
8201 (setq beg (point))
8202 (skip-chars-forward " \t\r\n")
8203 (save-match-data
8204 (if nosubtrees
8205 (outline-next-heading)
8206 (save-excursion (outline-end-of-heading)
8207 (setq folded (outline-invisible-p)))
8208 (condition-case nil
8209 (org-forward-heading-same-level (1- n) t)
8210 (error nil))
8211 (org-end-of-subtree t t)))
8212 (setq end (point))
8213 (goto-char beg0)
8214 (when (> end beg)
8215 (setq org-subtree-clip-folded folded)
8216 (when (or cut force-store-markers)
8217 (org-save-markers-in-region beg end))
8218 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8219 (setq org-subtree-clip (current-kill 0))
8220 (message "%s: Subtree(s) with %d characters"
8221 (if cut "Cut" "Copied")
8222 (length org-subtree-clip)))))
8224 (defun org-paste-subtree (&optional level tree for-yank)
8225 "Paste the clipboard as a subtree, with modification of headline level.
8226 The entire subtree is promoted or demoted in order to match a new headline
8227 level.
8229 If the cursor is at the beginning of a headline, the same level as
8230 that headline is used to paste the tree.
8232 If not, the new level is derived from the *visible* headings
8233 before and after the insertion point, and taken to be the inferior headline
8234 level of the two. So if the previous visible heading is level 3 and the
8235 next is level 4 (or vice versa), level 4 will be used for insertion.
8236 This makes sure that the subtree remains an independent subtree and does
8237 not swallow low level entries.
8239 You can also force a different level, either by using a numeric prefix
8240 argument, or by inserting the heading marker by hand. For example, if the
8241 cursor is after \"*****\", then the tree will be shifted to level 5.
8243 If optional TREE is given, use this text instead of the kill ring.
8245 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8246 move back over whitespace before inserting, and move point to the end of
8247 the inserted text when done."
8248 (interactive "P")
8249 (setq tree (or tree (and kill-ring (current-kill 0))))
8250 (unless (org-kill-is-subtree-p tree)
8251 (user-error "%s"
8252 (substitute-command-keys
8253 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8254 (org-with-limited-levels
8255 (let* ((visp (not (outline-invisible-p)))
8256 (txt tree)
8257 (^re_ "\\(\\*+\\)[ \t]*")
8258 (old-level (if (string-match org-outline-regexp-bol txt)
8259 (- (match-end 0) (match-beginning 0) 1)
8260 -1))
8261 (force-level (cond (level (prefix-numeric-value level))
8262 ((and (looking-at "[ \t]*$")
8263 (string-match
8264 "^\\*+$" (buffer-substring
8265 (point-at-bol) (point))))
8266 (- (match-end 1) (match-beginning 1)))
8267 ((and (bolp)
8268 (looking-at org-outline-regexp))
8269 (- (match-end 0) (point) 1))))
8270 (previous-level (save-excursion
8271 (condition-case nil
8272 (progn
8273 (outline-previous-visible-heading 1)
8274 (if (looking-at ^re_)
8275 (- (match-end 0) (match-beginning 0) 1)
8277 (error 1))))
8278 (next-level (save-excursion
8279 (condition-case nil
8280 (progn
8281 (or (looking-at org-outline-regexp)
8282 (outline-next-visible-heading 1))
8283 (if (looking-at ^re_)
8284 (- (match-end 0) (match-beginning 0) 1)
8286 (error 1))))
8287 (new-level (or force-level (max previous-level next-level)))
8288 (shift (if (or (= old-level -1)
8289 (= new-level -1)
8290 (= old-level new-level))
8292 (- new-level old-level)))
8293 (delta (if (> shift 0) -1 1))
8294 (func (if (> shift 0) 'org-demote 'org-promote))
8295 (org-odd-levels-only nil)
8296 beg end newend)
8297 ;; Remove the forced level indicator
8298 (if force-level
8299 (delete-region (point-at-bol) (point)))
8300 ;; Paste
8301 (beginning-of-line (if (bolp) 1 2))
8302 (setq beg (point))
8303 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8304 (insert-before-markers txt)
8305 (unless (string-match "\n\\'" txt) (insert "\n"))
8306 (setq newend (point))
8307 (org-reinstall-markers-in-region beg)
8308 (setq end (point))
8309 (goto-char beg)
8310 (skip-chars-forward " \t\n\r")
8311 (setq beg (point))
8312 (if (and (outline-invisible-p) visp)
8313 (save-excursion (outline-show-heading)))
8314 ;; Shift if necessary
8315 (unless (= shift 0)
8316 (save-restriction
8317 (narrow-to-region beg end)
8318 (while (not (= shift 0))
8319 (org-map-region func (point-min) (point-max))
8320 (setq shift (+ delta shift)))
8321 (goto-char (point-min))
8322 (setq newend (point-max))))
8323 (when (or (org-called-interactively-p 'interactive) for-yank)
8324 (message "Clipboard pasted as level %d subtree" new-level))
8325 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8326 kill-ring
8327 (eq org-subtree-clip (current-kill 0))
8328 org-subtree-clip-folded)
8329 ;; The tree was folded before it was killed/copied
8330 (hide-subtree))
8331 (and for-yank (goto-char newend)))))
8333 (defun org-kill-is-subtree-p (&optional txt)
8334 "Check if the current kill is an outline subtree, or a set of trees.
8335 Returns nil if kill does not start with a headline, or if the first
8336 headline level is not the largest headline level in the tree.
8337 So this will actually accept several entries of equal levels as well,
8338 which is OK for `org-paste-subtree'.
8339 If optional TXT is given, check this string instead of the current kill."
8340 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8341 (re (org-get-limited-outline-regexp))
8342 (^re (concat "^" re))
8343 (start-level (and kill
8344 (string-match
8345 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8346 kill)
8347 (- (match-end 2) (match-beginning 2) 1)))
8348 (start (1+ (or (match-beginning 2) -1))))
8349 (if (not start-level)
8350 (progn
8351 nil) ;; does not even start with a heading
8352 (catch 'exit
8353 (while (setq start (string-match ^re kill (1+ start)))
8354 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8355 (throw 'exit nil)))
8356 t))))
8358 (defvar org-markers-to-move nil
8359 "Markers that should be moved with a cut-and-paste operation.
8360 Those markers are stored together with their positions relative to
8361 the start of the region.")
8363 (defun org-save-markers-in-region (beg end)
8364 "Check markers in region.
8365 If these markers are between BEG and END, record their position relative
8366 to BEG, so that after moving the block of text, we can put the markers back
8367 into place.
8368 This function gets called just before an entry or tree gets cut from the
8369 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8370 called immediately, to move the markers with the entries."
8371 (setq org-markers-to-move nil)
8372 (when (featurep 'org-clock)
8373 (org-clock-save-markers-for-cut-and-paste beg end))
8374 (when (featurep 'org-agenda)
8375 (org-agenda-save-markers-for-cut-and-paste beg end)))
8377 (defun org-check-and-save-marker (marker beg end)
8378 "Check if MARKER is between BEG and END.
8379 If yes, remember the marker and the distance to BEG."
8380 (when (and (marker-buffer marker)
8381 (equal (marker-buffer marker) (current-buffer)))
8382 (if (and (>= marker beg) (< marker end))
8383 (push (cons marker (- marker beg)) org-markers-to-move))))
8385 (defun org-reinstall-markers-in-region (beg)
8386 "Move all remembered markers to their position relative to BEG."
8387 (mapc (lambda (x)
8388 (move-marker (car x) (+ beg (cdr x))))
8389 org-markers-to-move)
8390 (setq org-markers-to-move nil))
8392 (defun org-narrow-to-subtree ()
8393 "Narrow buffer to the current subtree."
8394 (interactive)
8395 (save-excursion
8396 (save-match-data
8397 (org-with-limited-levels
8398 (narrow-to-region
8399 (progn (org-back-to-heading t) (point))
8400 (progn (org-end-of-subtree t t)
8401 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8402 (point)))))))
8404 (defun org-narrow-to-block ()
8405 "Narrow buffer to the current block."
8406 (interactive)
8407 (let* ((case-fold-search t)
8408 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8409 "^[ \t]*#\\+end_.*")))
8410 (if blockp
8411 (narrow-to-region (car blockp) (cdr blockp))
8412 (user-error "Not in a block"))))
8414 (eval-when-compile
8415 (defvar org-property-drawer-re))
8417 (defvar org-property-start-re) ;; defined below
8418 (defun org-clone-subtree-with-time-shift (n &optional shift)
8419 "Clone the task (subtree) at point N times.
8420 The clones will be inserted as siblings.
8422 In interactive use, the user will be prompted for the number of
8423 clones to be produced. If the entry has a timestamp, the user
8424 will also be prompted for a time shift, which may be a repeater
8425 as used in time stamps, for example `+3d'. To disable this,
8426 you can call the function with a universal prefix argument.
8428 When a valid repeater is given and the entry contains any time
8429 stamps, the clones will become a sequence in time, with time
8430 stamps in the subtree shifted for each clone produced. If SHIFT
8431 is nil or the empty string, time stamps will be left alone. The
8432 ID property of the original subtree is removed.
8434 If the original subtree did contain time stamps with a repeater,
8435 the following will happen:
8436 - the repeater will be removed in each clone
8437 - an additional clone will be produced, with the current, unshifted
8438 date(s) in the entry.
8439 - the original entry will be placed *after* all the clones, with
8440 repeater intact.
8441 - the start days in the repeater in the original entry will be shifted
8442 to past the last clone.
8443 In this way you can spell out a number of instances of a repeating task,
8444 and still retain the repeater to cover future instances of the task."
8445 (interactive "nNumber of clones to produce: ")
8446 (let ((shift
8447 (or shift
8448 (if (and (not (equal current-prefix-arg '(4)))
8449 (save-excursion
8450 (re-search-forward org-ts-regexp-both
8451 (save-excursion
8452 (org-end-of-subtree t)
8453 (point)) t)))
8454 (read-from-minibuffer
8455 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8456 ""))) ;; No time shift
8457 (n-no-remove -1)
8458 (drawer-re org-drawer-regexp)
8459 beg end template task idprop
8460 shift-n shift-what doshift nmin nmax)
8461 (if (not (and (integerp n) (> n 0)))
8462 (error "Invalid number of replications %s" n))
8463 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8464 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8465 shift)))
8466 (error "Invalid shift specification %s" shift))
8467 (when doshift
8468 (setq shift-n (string-to-number (match-string 1 shift))
8469 shift-what (cdr (assoc (match-string 2 shift)
8470 '(("d" . day) ("w" . week)
8471 ("m" . month) ("y" . year))))))
8472 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8473 (setq nmin 1 nmax n)
8474 (org-back-to-heading t)
8475 (setq beg (point))
8476 (setq idprop (org-entry-get nil "ID"))
8477 (org-end-of-subtree t t)
8478 (or (bolp) (insert "\n"))
8479 (setq end (point))
8480 (setq template (buffer-substring beg end))
8481 (when (and doshift
8482 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8483 (delete-region beg end)
8484 (setq end beg)
8485 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8486 (goto-char end)
8487 (loop for n from nmin to nmax do
8488 ;; prepare clone
8489 (with-temp-buffer
8490 (insert template)
8491 (org-mode)
8492 (goto-char (point-min))
8493 (org-show-subtree)
8494 (and idprop (if org-clone-delete-id
8495 (org-entry-delete nil "ID")
8496 (org-id-get-create t)))
8497 (unless (= n 0)
8498 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8499 (kill-whole-line))
8500 (goto-char (point-min))
8501 (while (re-search-forward drawer-re nil t)
8502 (mapc (lambda (d)
8503 (org-remove-empty-drawer-at d (point))) org-drawers)))
8504 (goto-char (point-min))
8505 (when doshift
8506 (while (re-search-forward org-ts-regexp-both nil t)
8507 (org-timestamp-change (* n shift-n) shift-what))
8508 (unless (= n n-no-remove)
8509 (goto-char (point-min))
8510 (while (re-search-forward org-ts-regexp nil t)
8511 (save-excursion
8512 (goto-char (match-beginning 0))
8513 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8514 (delete-region (match-beginning 1) (match-end 1)))))))
8515 (setq task (buffer-string)))
8516 (insert task))
8517 (goto-char beg)))
8519 ;;; Outline Sorting
8521 (defun org-sort (with-case)
8522 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8523 Optional argument WITH-CASE means sort case-sensitively."
8524 (interactive "P")
8525 (cond
8526 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8527 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8529 (org-call-with-arg 'org-sort-entries with-case))))
8531 (defun org-sort-remove-invisible (s)
8532 "Remove invisible links from string S."
8533 (remove-text-properties 0 (length s) org-rm-props s)
8534 (while (string-match org-bracket-link-regexp s)
8535 (setq s (replace-match (if (match-end 2)
8536 (match-string 3 s)
8537 (match-string 1 s)) t t s)))
8538 (let ((st (format " %s " s)))
8539 (while (string-match org-emph-re st)
8540 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8541 (setq s (substring st 1 -1)))
8544 (defvar org-priority-regexp) ; defined later in the file
8546 (defvar org-after-sorting-entries-or-items-hook nil
8547 "Hook that is run after a bunch of entries or items have been sorted.
8548 When children are sorted, the cursor is in the parent line when this
8549 hook gets called. When a region or a plain list is sorted, the cursor
8550 will be in the first entry of the sorted region/list.")
8552 (defun org-sort-entries
8553 (&optional with-case sorting-type getkey-func compare-func property)
8554 "Sort entries on a certain level of an outline tree.
8555 If there is an active region, the entries in the region are sorted.
8556 Else, if the cursor is before the first entry, sort the top-level items.
8557 Else, the children of the entry at point are sorted.
8559 Sorting can be alphabetically, numerically, by date/time as given by
8560 a time stamp, by a property, by priority order, or by a custom function.
8562 The command prompts for the sorting type unless it has been given to the
8563 function through the SORTING-TYPE argument, which needs to be a character,
8564 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8565 precise meaning of each character:
8567 n Numerically, by converting the beginning of the entry/item to a number.
8568 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8569 o By order of TODO keywords.
8570 t By date/time, either the first active time stamp in the entry, or, if
8571 none exist, by the first inactive one.
8572 s By the scheduled date/time.
8573 d By deadline date/time.
8574 c By creation time, which is assumed to be the first inactive time stamp
8575 at the beginning of a line.
8576 p By priority according to the cookie.
8577 r By the value of a property.
8579 Capital letters will reverse the sort order.
8581 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8582 called with point at the beginning of the record. It must return either
8583 a string or a number that should serve as the sorting key for that record.
8585 Comparing entries ignores case by default. However, with an optional argument
8586 WITH-CASE, the sorting considers case as well.
8588 Sorting is done against the visible part of the headlines, it ignores hidden
8589 links."
8590 (interactive "P")
8591 (let ((case-func (if with-case 'identity 'downcase))
8592 (cmstr
8593 ;; The clock marker is lost when using `sort-subr', let's
8594 ;; store the clocking string.
8595 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8596 (save-excursion
8597 (goto-char org-clock-marker)
8598 (looking-back "^.*") (match-string-no-properties 0))))
8599 start beg end stars re re2
8600 txt what tmp)
8601 ;; Find beginning and end of region to sort
8602 (cond
8603 ((org-region-active-p)
8604 ;; we will sort the region
8605 (setq end (region-end)
8606 what "region")
8607 (goto-char (region-beginning))
8608 (if (not (org-at-heading-p)) (outline-next-heading))
8609 (setq start (point)))
8610 ((or (org-at-heading-p)
8611 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8612 ;; we will sort the children of the current headline
8613 (org-back-to-heading)
8614 (setq start (point)
8615 end (progn (org-end-of-subtree t t)
8616 (or (bolp) (insert "\n"))
8617 (org-back-over-empty-lines)
8618 (point))
8619 what "children")
8620 (goto-char start)
8621 (show-subtree)
8622 (outline-next-heading))
8624 ;; we will sort the top-level entries in this file
8625 (goto-char (point-min))
8626 (or (org-at-heading-p) (outline-next-heading))
8627 (setq start (point))
8628 (goto-char (point-max))
8629 (beginning-of-line 1)
8630 (when (looking-at ".*?\\S-")
8631 ;; File ends in a non-white line
8632 (end-of-line 1)
8633 (insert "\n"))
8634 (setq end (point-max))
8635 (setq what "top-level")
8636 (goto-char start)
8637 (show-all)))
8639 (setq beg (point))
8640 (if (>= beg end) (user-error "Nothing to sort"))
8642 (looking-at "\\(\\*+\\)")
8643 (setq stars (match-string 1)
8644 re (concat "^" (regexp-quote stars) " +")
8645 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8646 txt (buffer-substring beg end))
8647 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8648 (if (and (not (equal stars "*")) (string-match re2 txt))
8649 (user-error "Region to sort contains a level above the first entry"))
8651 (unless sorting-type
8652 (message
8653 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8654 [t]ime [s]cheduled [d]eadline [c]reated
8655 A/N/P/R/O/F/T/S/D/C means reversed:"
8656 what)
8657 (setq sorting-type (read-char-exclusive))
8659 (unless getkey-func
8660 (and (= (downcase sorting-type) ?f)
8661 (setq getkey-func
8662 (org-icompleting-read "Sort using function: "
8663 obarray 'fboundp t nil nil))
8664 (setq getkey-func (intern getkey-func))))
8666 (and (= (downcase sorting-type) ?r)
8667 (not property)
8668 (setq property
8669 (org-icompleting-read "Property: "
8670 (mapcar 'list (org-buffer-property-keys t))
8671 nil t))))
8673 (message "Sorting entries...")
8675 (save-restriction
8676 (narrow-to-region start end)
8677 (let ((dcst (downcase sorting-type))
8678 (case-fold-search nil)
8679 (now (current-time)))
8680 (sort-subr
8681 (/= dcst sorting-type)
8682 ;; This function moves to the beginning character of the "record" to
8683 ;; be sorted.
8684 (lambda nil
8685 (if (re-search-forward re nil t)
8686 (goto-char (match-beginning 0))
8687 (goto-char (point-max))))
8688 ;; This function moves to the last character of the "record" being
8689 ;; sorted.
8690 (lambda nil
8691 (save-match-data
8692 (condition-case nil
8693 (outline-forward-same-level 1)
8694 (error
8695 (goto-char (point-max))))))
8696 ;; This function returns the value that gets sorted against.
8697 (lambda nil
8698 (cond
8699 ((= dcst ?n)
8700 (if (looking-at org-complex-heading-regexp)
8701 (string-to-number (org-sort-remove-invisible (match-string 4)))
8702 nil))
8703 ((= dcst ?a)
8704 (if (looking-at org-complex-heading-regexp)
8705 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8706 nil))
8707 ((= dcst ?t)
8708 (let ((end (save-excursion (outline-next-heading) (point))))
8709 (if (or (re-search-forward org-ts-regexp end t)
8710 (re-search-forward org-ts-regexp-both end t))
8711 (org-time-string-to-seconds (match-string 0))
8712 (org-float-time now))))
8713 ((= dcst ?c)
8714 (let ((end (save-excursion (outline-next-heading) (point))))
8715 (if (re-search-forward
8716 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8717 end t)
8718 (org-time-string-to-seconds (match-string 0))
8719 (org-float-time now))))
8720 ((= dcst ?s)
8721 (let ((end (save-excursion (outline-next-heading) (point))))
8722 (if (re-search-forward org-scheduled-time-regexp end t)
8723 (org-time-string-to-seconds (match-string 1))
8724 (org-float-time now))))
8725 ((= dcst ?d)
8726 (let ((end (save-excursion (outline-next-heading) (point))))
8727 (if (re-search-forward org-deadline-time-regexp end t)
8728 (org-time-string-to-seconds (match-string 1))
8729 (org-float-time now))))
8730 ((= dcst ?p)
8731 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8732 (string-to-char (match-string 2))
8733 org-default-priority))
8734 ((= dcst ?r)
8735 (or (org-entry-get nil property) ""))
8736 ((= dcst ?o)
8737 (if (looking-at org-complex-heading-regexp)
8738 (- 9999 (length (member (match-string 2)
8739 org-todo-keywords-1)))))
8740 ((= dcst ?f)
8741 (if getkey-func
8742 (progn
8743 (setq tmp (funcall getkey-func))
8744 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8745 tmp)
8746 (error "Invalid key function `%s'" getkey-func)))
8747 (t (error "Invalid sorting type `%c'" sorting-type))))
8749 (cond
8750 ((= dcst ?a) 'string<)
8751 ((= dcst ?f) compare-func)
8752 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8753 (run-hooks 'org-after-sorting-entries-or-items-hook)
8754 ;; Reset the clock marker if needed
8755 (when cmstr
8756 (save-excursion
8757 (goto-char start)
8758 (search-forward cmstr nil t)
8759 (move-marker org-clock-marker (point))))
8760 (message "Sorting entries...done")))
8762 (defun org-do-sort (table what &optional with-case sorting-type)
8763 "Sort TABLE of WHAT according to SORTING-TYPE.
8764 The user will be prompted for the SORTING-TYPE if the call to this
8765 function does not specify it. WHAT is only for the prompt, to indicate
8766 what is being sorted. The sorting key will be extracted from
8767 the car of the elements of the table.
8768 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8769 (unless sorting-type
8770 (message
8771 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8772 what)
8773 (setq sorting-type (read-char-exclusive)))
8774 (let ((dcst (downcase sorting-type))
8775 extractfun comparefun)
8776 ;; Define the appropriate functions
8777 (cond
8778 ((= dcst ?n)
8779 (setq extractfun 'string-to-number
8780 comparefun (if (= dcst sorting-type) '< '>)))
8781 ((= dcst ?a)
8782 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8783 (lambda(x) (downcase (org-sort-remove-invisible x))))
8784 comparefun (if (= dcst sorting-type)
8785 'string<
8786 (lambda (a b) (and (not (string< a b))
8787 (not (string= a b)))))))
8788 ((= dcst ?t)
8789 (setq extractfun
8790 (lambda (x)
8791 (if (or (string-match org-ts-regexp x)
8792 (string-match org-ts-regexp-both x))
8793 (org-float-time
8794 (org-time-string-to-time (match-string 0 x)))
8796 comparefun (if (= dcst sorting-type) '< '>)))
8797 (t (error "Invalid sorting type `%c'" sorting-type)))
8799 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8800 table)
8801 (lambda (a b) (funcall comparefun (car a) (car b))))))
8804 ;;; The orgstruct minor mode
8806 ;; Define a minor mode which can be used in other modes in order to
8807 ;; integrate the org-mode structure editing commands.
8809 ;; This is really a hack, because the org-mode structure commands use
8810 ;; keys which normally belong to the major mode. Here is how it
8811 ;; works: The minor mode defines all the keys necessary to operate the
8812 ;; structure commands, but wraps the commands into a function which
8813 ;; tests if the cursor is currently at a headline or a plain list
8814 ;; item. If that is the case, the structure command is used,
8815 ;; temporarily setting many Org-mode variables like regular
8816 ;; expressions for filling etc. However, when any of those keys is
8817 ;; used at a different location, function uses `key-binding' to look
8818 ;; up if the key has an associated command in another currently active
8819 ;; keymap (minor modes, major mode, global), and executes that
8820 ;; command. There might be problems if any of the keys is otherwise
8821 ;; used as a prefix key.
8823 (defcustom orgstruct-heading-prefix-regexp ""
8824 "Regexp that matches the custom prefix of Org headlines in
8825 orgstruct(++)-mode."
8826 :group 'org
8827 :version "24.4"
8828 :package-version '(Org . "8.3")
8829 :type 'regexp)
8830 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8832 (defcustom orgstruct-setup-hook nil
8833 "Hook run after orgstruct-mode-map is filled."
8834 :group 'org
8835 :version "24.4"
8836 :package-version '(Org . "8.0")
8837 :type 'hook)
8839 (defvar orgstruct-initialized nil)
8841 (defvar org-local-vars nil
8842 "List of local variables, for use by `orgstruct-mode'.")
8844 ;;;###autoload
8845 (define-minor-mode orgstruct-mode
8846 "Toggle the minor mode `orgstruct-mode'.
8847 This mode is for using Org-mode structure commands in other
8848 modes. The following keys behave as if Org-mode were active, if
8849 the cursor is on a headline, or on a plain list item (both as
8850 defined by Org-mode)."
8851 nil " OrgStruct" (make-sparse-keymap)
8852 (funcall (if orgstruct-mode
8853 'add-to-invisibility-spec
8854 'remove-from-invisibility-spec)
8855 '(outline . t))
8856 (when orgstruct-mode
8857 (org-load-modules-maybe)
8858 (unless orgstruct-initialized
8859 (orgstruct-setup)
8860 (setq orgstruct-initialized t))))
8862 ;;;###autoload
8863 (defun turn-on-orgstruct ()
8864 "Unconditionally turn on `orgstruct-mode'."
8865 (orgstruct-mode 1))
8867 (defvar org-fb-vars nil)
8868 (make-variable-buffer-local 'org-fb-vars)
8869 (defun orgstruct++-mode (&optional arg)
8870 "Toggle `orgstruct-mode', the enhanced version of it.
8871 In addition to setting orgstruct-mode, this also exports all
8872 indentation and autofilling variables from org-mode into the
8873 buffer. It will also recognize item context in multiline items."
8874 (interactive "P")
8875 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8876 (if (< arg 1)
8877 (progn (orgstruct-mode -1)
8878 (mapc (lambda(v)
8879 (org-set-local (car v)
8880 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8881 org-fb-vars))
8882 (orgstruct-mode 1)
8883 (setq org-fb-vars nil)
8884 (unless org-local-vars
8885 (setq org-local-vars (org-get-local-variables)))
8886 (let (var val)
8887 (mapc
8888 (lambda (x)
8889 (when (string-match
8890 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8891 (symbol-name (car x)))
8892 (setq var (car x) val (nth 1 x))
8893 (push (list var `(quote ,(eval var))) org-fb-vars)
8894 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8895 org-local-vars)
8896 (org-set-local 'orgstruct-is-++ t))))
8898 (defvar orgstruct-is-++ nil
8899 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8900 (make-variable-buffer-local 'orgstruct-is-++)
8902 ;;;###autoload
8903 (defun turn-on-orgstruct++ ()
8904 "Unconditionally turn on `orgstruct++-mode'."
8905 (orgstruct++-mode 1))
8907 (defun orgstruct-error ()
8908 "Error when there is no default binding for a structure key."
8909 (interactive)
8910 (funcall (if (fboundp 'user-error)
8911 'user-error
8912 'error)
8913 "This key has no function outside structure elements"))
8915 (defun orgstruct-setup ()
8916 "Setup orgstruct keymap."
8917 (dolist (cell '((org-demote . t)
8918 (org-metaleft . t)
8919 (org-metaright . t)
8920 (org-promote . t)
8921 (org-shiftmetaleft . t)
8922 (org-shiftmetaright . t)
8923 org-backward-element
8924 org-backward-heading-same-level
8925 org-ctrl-c-ret
8926 org-ctrl-c-minus
8927 org-ctrl-c-star
8928 org-cycle
8929 org-forward-heading-same-level
8930 org-insert-heading
8931 org-insert-heading-respect-content
8932 org-kill-note-or-show-branches
8933 org-mark-subtree
8934 org-meta-return
8935 org-metadown
8936 org-metaup
8937 org-narrow-to-subtree
8938 org-promote-subtree
8939 org-reveal
8940 org-shiftdown
8941 org-shiftleft
8942 org-shiftmetadown
8943 org-shiftmetaup
8944 org-shiftright
8945 org-shifttab
8946 org-shifttab
8947 org-shiftup
8948 org-show-subtree
8949 org-sort
8950 org-up-element
8951 outline-demote
8952 outline-next-visible-heading
8953 outline-previous-visible-heading
8954 outline-promote
8955 outline-up-heading
8956 show-children))
8957 (let ((f (or (car-safe cell) cell))
8958 (disable-when-heading-prefix (cdr-safe cell)))
8959 (when (fboundp f)
8960 (let ((new-bindings))
8961 (dolist (binding (nconc (where-is-internal f org-mode-map)
8962 (where-is-internal f outline-mode-map)))
8963 (push binding new-bindings)
8964 ;; TODO use local-function-key-map
8965 (dolist (rep '(("<tab>" . "TAB")
8966 ("<return>" . "RET")
8967 ("<escape>" . "ESC")
8968 ("<delete>" . "DEL")))
8969 (setq binding (read-kbd-macro
8970 (let ((case-fold-search))
8971 (replace-regexp-in-string
8972 (regexp-quote (cdr rep))
8973 (car rep)
8974 (key-description binding)))))
8975 (pushnew binding new-bindings :test 'equal)))
8976 (dolist (binding new-bindings)
8977 (let ((key (lookup-key orgstruct-mode-map binding)))
8978 (when (or (not key) (numberp key))
8979 (condition-case nil
8980 (org-defkey orgstruct-mode-map
8981 binding
8982 (orgstruct-make-binding f binding disable-when-heading-prefix))
8983 (error nil)))))))))
8984 (run-hooks 'orgstruct-setup-hook))
8986 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8987 "Create a function for binding in the structure minor mode.
8988 FUN is the command to call inside a table. KEY is the key that
8989 should be checked in for a command to execute outside of tables.
8990 Non-nil `disable-when-heading-prefix' means to disable the command
8991 if `orgstruct-heading-prefix-regexp' is not empty."
8992 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8993 (let ((nname name)
8994 (i 0))
8995 (while (fboundp (intern nname))
8996 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8997 (setq name (intern nname)))
8998 (eval
8999 (let ((bindings '((org-heading-regexp
9000 (concat "^"
9001 orgstruct-heading-prefix-regexp
9002 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9003 (org-outline-regexp
9004 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9005 (org-outline-regexp-bol
9006 (concat "^" org-outline-regexp))
9007 (outline-regexp org-outline-regexp)
9008 (outline-heading-end-regexp "\n")
9009 (outline-level 'org-outline-level)
9010 (outline-heading-alist))))
9011 `(defun ,name (arg)
9012 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9013 "Outside of structure, run the binding of `"
9014 (key-description key) "'."
9015 (when disable-when-heading-prefix
9016 (concat
9017 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9018 "back to the default binding due to limitations of Org's implementation of\n"
9019 "`" (symbol-name fun) "'.")))
9020 (interactive "p")
9021 (let* ((disable
9022 ,(and disable-when-heading-prefix
9023 '(not (string= orgstruct-heading-prefix-regexp ""))))
9024 (fallback
9025 (or disable
9026 (not
9027 (let* ,bindings
9028 (org-context-p 'headline 'item
9029 ,(when (memq fun
9030 '(org-insert-heading
9031 org-insert-heading-respect-content
9032 org-meta-return))
9033 '(when orgstruct-is-++
9034 'item-body))))))))
9035 (if fallback
9036 (let* ((orgstruct-mode)
9037 (binding
9038 (loop with key = ,key
9039 for rep in
9040 '(nil
9041 ("<\\([^>]*\\)tab>" . "\\1TAB")
9042 ("<\\([^>]*\\)return>" . "\\1RET")
9043 ("<\\([^>]*\\)escape>" . "\\1ESC")
9044 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9046 (when rep
9047 (setq key (read-kbd-macro
9048 (let ((case-fold-search))
9049 (replace-regexp-in-string
9050 (car rep)
9051 (cdr rep)
9052 (key-description key))))))
9053 thereis (key-binding key))))
9054 (if (keymapp binding)
9055 (set-transient-map binding)
9056 (let ((func (or binding
9057 (unless disable
9058 'orgstruct-error))))
9059 (when func
9060 (call-interactively func)))))
9061 (org-run-like-in-org-mode
9062 (lambda ()
9063 (interactive)
9064 (let* ,bindings
9065 (call-interactively ',fun)))))))))
9066 name))
9068 (defun org-contextualize-keys (alist contexts)
9069 "Return valid elements in ALIST depending on CONTEXTS.
9071 `org-agenda-custom-commands' or `org-capture-templates' are the
9072 values used for ALIST, and `org-agenda-custom-commands-contexts'
9073 or `org-capture-templates-contexts' are the associated contexts
9074 definitions."
9075 (let ((contexts
9076 ;; normalize contexts
9077 (mapcar
9078 (lambda(c) (cond ((listp (cadr c))
9079 (list (car c) (car c) (cadr c)))
9080 ((string= "" (cadr c))
9081 (list (car c) (car c) (caddr c)))
9082 (t c))) contexts))
9083 (a alist) c r s)
9084 ;; loop over all commands or templates
9085 (while (setq c (pop a))
9086 (let (vrules repl)
9087 (cond
9088 ((not (assoc (car c) contexts))
9089 (push c r))
9090 ((and (assoc (car c) contexts)
9091 (setq vrules (org-contextualize-validate-key
9092 (car c) contexts)))
9093 (mapc (lambda (vr)
9094 (when (not (equal (car vr) (cadr vr)))
9095 (setq repl vr))) vrules)
9096 (if (not repl) (push c r)
9097 (push (cadr repl) s)
9098 (push
9099 (cons (car c)
9100 (cdr (or (assoc (cadr repl) alist)
9101 (error "Undefined key `%s' as contextual replacement for `%s'"
9102 (cadr repl) (car c)))))
9103 r))))))
9104 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9105 (delq
9107 (delete-dups
9108 (mapcar (lambda (x)
9109 (let ((tpl (car x)))
9110 (when (not (delq
9112 (mapcar (lambda(y)
9113 (equal y tpl)) s))) x)))
9114 (reverse r))))))
9116 (defun org-contextualize-validate-key (key contexts)
9117 "Check CONTEXTS for agenda or capture KEY."
9118 (let (r rr res)
9119 (while (setq r (pop contexts))
9120 (mapc
9121 (lambda (rr)
9122 (when
9123 (and (equal key (car r))
9124 (if (functionp rr) (funcall rr)
9125 (or (and (eq (car rr) 'in-file)
9126 (buffer-file-name)
9127 (string-match (cdr rr) (buffer-file-name)))
9128 (and (eq (car rr) 'in-mode)
9129 (string-match (cdr rr) (symbol-name major-mode)))
9130 (and (eq (car rr) 'in-buffer)
9131 (string-match (cdr rr) (buffer-name)))
9132 (when (and (eq (car rr) 'not-in-file)
9133 (buffer-file-name))
9134 (not (string-match (cdr rr) (buffer-file-name))))
9135 (when (eq (car rr) 'not-in-mode)
9136 (not (string-match (cdr rr) (symbol-name major-mode))))
9137 (when (eq (car rr) 'not-in-buffer)
9138 (not (string-match (cdr rr) (buffer-name)))))))
9139 (push r res)))
9140 (car (last r))))
9141 (delete-dups (delq nil res))))
9143 (defun org-context-p (&rest contexts)
9144 "Check if local context is any of CONTEXTS.
9145 Possible values in the list of contexts are `table', `headline', and `item'."
9146 (let ((pos (point)))
9147 (goto-char (point-at-bol))
9148 (prog1 (or (and (memq 'table contexts)
9149 (looking-at "[ \t]*|"))
9150 (and (memq 'headline contexts)
9151 (looking-at org-outline-regexp))
9152 (and (memq 'item contexts)
9153 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9154 (and (memq 'item-body contexts)
9155 (org-in-item-p)))
9156 (goto-char pos))))
9158 (defun org-get-local-variables ()
9159 "Return a list of all local variables in an Org mode buffer."
9160 (let (varlist)
9161 (with-current-buffer (get-buffer-create "*Org tmp*")
9162 (erase-buffer)
9163 (org-mode)
9164 (setq varlist (buffer-local-variables)))
9165 (kill-buffer "*Org tmp*")
9166 (delq nil
9167 (mapcar
9168 (lambda (x)
9169 (setq x
9170 (if (symbolp x)
9171 (list x)
9172 (list (car x) (cdr x))))
9173 (if (and (not (get (car x) 'org-state))
9174 (string-match
9175 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9176 (symbol-name (car x))))
9177 x nil))
9178 varlist))))
9180 (defun org-clone-local-variables (from-buffer &optional regexp)
9181 "Clone local variables from FROM-BUFFER.
9182 Optional argument REGEXP selects variables to clone."
9183 (mapc
9184 (lambda (pair)
9185 (and (symbolp (car pair))
9186 (or (null regexp)
9187 (string-match regexp (symbol-name (car pair))))
9188 (set (make-local-variable (car pair))
9189 (cdr pair))))
9190 (buffer-local-variables from-buffer)))
9192 ;;;###autoload
9193 (defun org-run-like-in-org-mode (cmd)
9194 "Run a command, pretending that the current buffer is in Org-mode.
9195 This will temporarily bind local variables that are typically bound in
9196 Org-mode to the values they have in Org-mode, and then interactively
9197 call CMD."
9198 (org-load-modules-maybe)
9199 (unless org-local-vars
9200 (setq org-local-vars (org-get-local-variables)))
9201 (let (binds)
9202 (dolist (var org-local-vars)
9203 (when (or (not (boundp (car var)))
9204 (eq (symbol-value (car var))
9205 (default-value (car var))))
9206 (push (list (car var) `(quote ,(cadr var))) binds)))
9207 (eval `(let ,binds
9208 (call-interactively (quote ,cmd))))))
9210 ;;;; Archiving
9212 (defun org-get-category (&optional pos force-refresh)
9213 "Get the category applying to position POS."
9214 (save-match-data
9215 (if force-refresh (org-refresh-category-properties))
9216 (let ((pos (or pos (point))))
9217 (or (get-text-property pos 'org-category)
9218 (progn (org-refresh-category-properties)
9219 (get-text-property pos 'org-category))))))
9221 (defun org-refresh-category-properties ()
9222 "Refresh category text properties in the buffer."
9223 (let ((case-fold-search t)
9224 (inhibit-read-only t)
9225 (def-cat (cond
9226 ((null org-category)
9227 (if buffer-file-name
9228 (file-name-sans-extension
9229 (file-name-nondirectory buffer-file-name))
9230 "???"))
9231 ((symbolp org-category) (symbol-name org-category))
9232 (t org-category)))
9233 beg end cat pos optionp)
9234 (org-with-silent-modifications
9235 (save-excursion
9236 (save-restriction
9237 (widen)
9238 (goto-char (point-min))
9239 (put-text-property (point) (point-max) 'org-category def-cat)
9240 (while (re-search-forward
9241 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9242 (setq pos (match-end 0)
9243 optionp (equal (char-after (match-beginning 0)) ?#)
9244 cat (org-trim (match-string 2)))
9245 (if optionp
9246 (setq beg (point-at-bol) end (point-max))
9247 (org-back-to-heading t)
9248 (setq beg (point) end (org-end-of-subtree t t)))
9249 (put-text-property beg end 'org-category cat)
9250 (put-text-property beg end 'org-category-position beg)
9251 (goto-char pos)))))))
9253 (defun org-refresh-properties (dprop tprop)
9254 "Refresh buffer text properties.
9255 DPROP is the drawer property and TPROP is the corresponding text
9256 property to set."
9257 (let ((case-fold-search t)
9258 (inhibit-read-only t) p)
9259 (org-with-silent-modifications
9260 (save-excursion
9261 (save-restriction
9262 (widen)
9263 (goto-char (point-min))
9264 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9265 (setq p (org-match-string-no-properties 1))
9266 (save-excursion
9267 (org-back-to-heading t)
9268 (put-text-property
9269 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9272 ;;;; Link Stuff
9274 ;;; Link abbreviations
9276 (defun org-link-expand-abbrev (link)
9277 "Apply replacements as defined in `org-link-abbrev-alist'."
9278 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9279 (let* ((key (match-string 1 link))
9280 (as (or (assoc key org-link-abbrev-alist-local)
9281 (assoc key org-link-abbrev-alist)))
9282 (tag (and (match-end 2) (match-string 3 link)))
9283 rpl)
9284 (if (not as)
9285 link
9286 (setq rpl (cdr as))
9287 (cond
9288 ((symbolp rpl) (funcall rpl tag))
9289 ((string-match "%(\\([^)]+\\))" rpl)
9290 (replace-match
9291 (save-match-data
9292 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9293 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9294 ((string-match "%h" rpl)
9295 (replace-match (url-hexify-string (or tag "")) t t rpl))
9296 (t (concat rpl tag)))))
9297 link))
9299 ;;; Storing and inserting links
9301 (defvar org-insert-link-history nil
9302 "Minibuffer history for links inserted with `org-insert-link'.")
9304 (defvar org-stored-links nil
9305 "Contains the links stored with `org-store-link'.")
9307 (defvar org-store-link-plist nil
9308 "Plist with info about the most recently link created with `org-store-link'.")
9310 (defvar org-link-protocols nil
9311 "Link protocols added to Org-mode using `org-add-link-type'.")
9313 (defvar org-store-link-functions nil
9314 "List of functions that are called to create and store a link.
9315 Each function will be called in turn until one returns a non-nil
9316 value. Each function should check if it is responsible for creating
9317 this link (for example by looking at the major mode).
9318 If not, it must exit and return nil.
9319 If yes, it should return a non-nil value after a calling
9320 `org-store-link-props' with a list of properties and values.
9321 Special properties are:
9323 :type The link prefix, like \"http\". This must be given.
9324 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9325 This is obligatory as well.
9326 :description Optional default description for the second pair
9327 of brackets in an Org-mode link. The user can still change
9328 this when inserting this link into an Org-mode buffer.
9330 In addition to these, any additional properties can be specified
9331 and then used in capture templates.")
9333 (defun org-add-link-type (type &optional follow export)
9334 "Add TYPE to the list of `org-link-types'.
9335 Re-compute all regular expressions depending on `org-link-types'
9337 FOLLOW and EXPORT are two functions.
9339 FOLLOW should take the link path as the single argument and do whatever
9340 is necessary to follow the link, for example find a file or display
9341 a mail message.
9343 EXPORT should format the link path for export to one of the export formats.
9344 It should be a function accepting three arguments:
9346 path the path of the link, the text after the prefix (like \"http:\")
9347 desc the description of the link, if any, or a description added by
9348 org-export-normalize-links if there is none
9349 format the export format, a symbol like `html' or `latex' or `ascii'..
9351 The function may use the FORMAT information to return different values
9352 depending on the format. The return value will be put literally into
9353 the exported file. If the return value is nil, this means Org should
9354 do what it normally does with links which do not have EXPORT defined.
9356 Org-mode has a built-in default for exporting links. If you are happy with
9357 this default, there is no need to define an export function for the link
9358 type. For a simple example of an export function, see `org-bbdb.el'."
9359 (add-to-list 'org-link-types type t)
9360 (org-make-link-regexps)
9361 (if (assoc type org-link-protocols)
9362 (setcdr (assoc type org-link-protocols) (list follow export))
9363 (push (list type follow export) org-link-protocols)))
9365 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9366 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9368 ;;;###autoload
9369 (defun org-store-link (arg)
9370 "\\<org-mode-map>Store an org-link to the current location.
9371 This link is added to `org-stored-links' and can later be inserted
9372 into an org-buffer with \\[org-insert-link].
9374 For some link types, a prefix arg is interpreted.
9375 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9376 For file links, arg negates `org-context-in-file-links'.
9378 A double prefix arg force skipping storing functions that are not
9379 part of Org's core.
9381 A triple prefix arg force storing a link for each line in the
9382 active region."
9383 (interactive "P")
9384 (org-load-modules-maybe)
9385 (if (and (equal arg '(64)) (org-region-active-p))
9386 (save-excursion
9387 (let ((end (region-end)))
9388 (goto-char (region-beginning))
9389 (set-mark (point))
9390 (while (< (point-at-eol) end)
9391 (move-end-of-line 1) (activate-mark)
9392 (let (current-prefix-arg)
9393 (call-interactively 'org-store-link))
9394 (move-beginning-of-line 2)
9395 (set-mark (point)))))
9396 (org-with-limited-levels
9397 (setq org-store-link-plist nil)
9398 (let (link cpltxt desc description search
9399 txt custom-id agenda-link sfuns sfunsn)
9400 (cond
9402 ;; Store a link using an external link type
9403 ((and (not (equal arg '(16)))
9404 (setq sfuns
9405 (delq
9406 nil (mapcar (lambda (f)
9407 (let (fs) (if (funcall f) (push f fs))))
9408 org-store-link-functions))
9409 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9410 (or (and (cdr sfuns)
9411 (funcall (intern
9412 (completing-read
9413 "Which function for creating the link? "
9414 sfunsn t (car sfunsn)))))
9415 (funcall (caar sfuns)))
9416 (setq link (plist-get org-store-link-plist :link)
9417 desc (or (plist-get org-store-link-plist
9418 :description) link))))
9420 ;; Store a link from a source code buffer
9421 ((org-src-edit-buffer-p)
9422 (let (label gc)
9423 (while (or (not label)
9424 (save-excursion
9425 (save-restriction
9426 (widen)
9427 (goto-char (point-min))
9428 (re-search-forward
9429 (regexp-quote (format org-coderef-label-format label))
9430 nil t))))
9431 (when label (message "Label exists already") (sit-for 2))
9432 (setq label (read-string "Code line label: " label)))
9433 (end-of-line 1)
9434 (setq link (format org-coderef-label-format label))
9435 (setq gc (- 79 (length link)))
9436 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9437 (insert link)
9438 (setq link (concat "(" label ")") desc nil)))
9440 ;; We are in the agenda, link to referenced location
9441 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9442 (let ((m (or (get-text-property (point) 'org-hd-marker)
9443 (get-text-property (point) 'org-marker))))
9444 (when m
9445 (org-with-point-at m
9446 (setq agenda-link
9447 (if (org-called-interactively-p 'any)
9448 (call-interactively 'org-store-link)
9449 (org-store-link nil)))))))
9451 ((eq major-mode 'calendar-mode)
9452 (let ((cd (calendar-cursor-to-date)))
9453 (setq link
9454 (format-time-string
9455 (car org-time-stamp-formats)
9456 (apply 'encode-time
9457 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9458 nil nil nil))))
9459 (org-store-link-props :type "calendar" :date cd)))
9461 ((eq major-mode 'help-mode)
9462 (setq link (concat "help:" (save-excursion
9463 (goto-char (point-min))
9464 (looking-at "^[^ ]+")
9465 (match-string 0))))
9466 (org-store-link-props :type "help"))
9468 ((eq major-mode 'w3-mode)
9469 (setq cpltxt (if (and (buffer-name)
9470 (not (string-match "Untitled" (buffer-name))))
9471 (buffer-name)
9472 (url-view-url t))
9473 link (url-view-url t))
9474 (org-store-link-props :type "w3" :url (url-view-url t)))
9476 ((eq major-mode 'image-mode)
9477 (setq cpltxt (concat "file:"
9478 (abbreviate-file-name buffer-file-name))
9479 link cpltxt)
9480 (org-store-link-props :type "image" :file buffer-file-name))
9482 ;; In dired, store a link to the file of the current line
9483 ((eq major-mode 'dired-mode)
9484 (let ((file (dired-get-filename nil t)))
9485 (setq file (if file
9486 (abbreviate-file-name
9487 (expand-file-name (dired-get-filename nil t)))
9488 ;; otherwise, no file so use current directory.
9489 default-directory))
9490 (setq cpltxt (concat "file:" file)
9491 link cpltxt)))
9493 ((setq search (run-hook-with-args-until-success
9494 'org-create-file-search-functions))
9495 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9496 "::" search))
9497 (setq cpltxt (or description link)))
9499 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9500 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9501 (cond
9502 ;; Store a link using the target at point
9503 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9504 (setq cpltxt
9505 (concat "file:"
9506 (abbreviate-file-name
9507 (buffer-file-name (buffer-base-buffer)))
9508 "::" (match-string 1))
9509 link cpltxt))
9510 ((and (featurep 'org-id)
9511 (or (eq org-id-link-to-org-use-id t)
9512 (and (org-called-interactively-p 'any)
9513 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9514 (and (eq org-id-link-to-org-use-id
9515 'create-if-interactive-and-no-custom-id)
9516 (not custom-id))))
9517 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9518 ;; Store a link using the ID at point
9519 (setq link (condition-case nil
9520 (prog1 (org-id-store-link)
9521 (setq desc (plist-get org-store-link-plist
9522 :description)))
9523 (error
9524 ;; Probably before first headline, link only to file
9525 (concat "file:"
9526 (abbreviate-file-name
9527 (buffer-file-name (buffer-base-buffer))))))))
9529 ;; Just link to current headline
9530 (setq cpltxt (concat "file:"
9531 (abbreviate-file-name
9532 (buffer-file-name (buffer-base-buffer)))))
9533 ;; Add a context search string
9534 (when (org-xor org-context-in-file-links arg)
9535 (let* ((ee (org-element-at-point))
9536 (et (org-element-type ee))
9537 (ev (plist-get (cadr ee) :value))
9538 (ek (plist-get (cadr ee) :key))
9539 (eok (and (stringp ek) (string-match "name" ek))))
9540 (setq txt (cond
9541 ((org-at-heading-p) nil)
9542 ((and (eq et 'keyword) eok) ev)
9543 ((org-region-active-p)
9544 (buffer-substring (region-beginning) (region-end)))))
9545 (when (or (null txt) (string-match "\\S-" txt))
9546 (setq cpltxt
9547 (concat cpltxt "::"
9548 (condition-case nil
9549 (org-make-org-heading-search-string txt)
9550 (error "")))
9551 desc (or (and (eq et 'keyword) eok ev)
9552 (nth 4 (ignore-errors (org-heading-components)))
9553 "NONE")))))
9554 (if (string-match "::\\'" cpltxt)
9555 (setq cpltxt (substring cpltxt 0 -2)))
9556 (setq link cpltxt))))
9558 ((buffer-file-name (buffer-base-buffer))
9559 ;; Just link to this file here.
9560 (setq cpltxt (concat "file:"
9561 (abbreviate-file-name
9562 (buffer-file-name (buffer-base-buffer)))))
9563 ;; Add a context string.
9564 (when (org-xor org-context-in-file-links arg)
9565 (setq txt (if (org-region-active-p)
9566 (buffer-substring (region-beginning) (region-end))
9567 (buffer-substring (point-at-bol) (point-at-eol))))
9568 ;; Only use search option if there is some text.
9569 (when (string-match "\\S-" txt)
9570 (setq cpltxt
9571 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9572 desc "NONE")))
9573 (setq link cpltxt))
9575 ((org-called-interactively-p 'interactive)
9576 (user-error "No method for storing a link from this buffer"))
9578 (t (setq link nil)))
9580 ;; We're done setting link and desc, clean up
9581 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9582 (setq link (or link cpltxt)
9583 desc (or desc cpltxt))
9584 (cond ((equal desc "NONE") (setq desc nil))
9585 ((string-match org-bracket-link-analytic-regexp desc)
9586 (let ((d0 (match-string 3 desc))
9587 (p0 (match-string 5 desc)))
9588 (setq desc
9589 (replace-regexp-in-string
9590 org-bracket-link-regexp
9591 (concat (or p0 d0)
9592 (if (equal (length (match-string 0 desc))
9593 (length desc)) "*" "")) desc)))))
9595 ;; Return the link
9596 (if (not (and (or (org-called-interactively-p 'any)
9597 executing-kbd-macro) link))
9598 (or agenda-link (and link (org-make-link-string link desc)))
9599 (push (list link desc) org-stored-links)
9600 (message "Stored: %s" (or desc link))
9601 (when custom-id
9602 (setq link (concat "file:" (abbreviate-file-name
9603 (buffer-file-name)) "::#" custom-id))
9604 (push (list link desc) org-stored-links))
9605 (car org-stored-links))))))
9607 (defun org-store-link-props (&rest plist)
9608 "Store link properties, extract names and addresses."
9609 (let (x adr)
9610 (when (setq x (plist-get plist :from))
9611 (setq adr (mail-extract-address-components x))
9612 (setq plist (plist-put plist :fromname (car adr)))
9613 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9614 (when (setq x (plist-get plist :to))
9615 (setq adr (mail-extract-address-components x))
9616 (setq plist (plist-put plist :toname (car adr)))
9617 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9618 (let ((from (plist-get plist :from))
9619 (to (plist-get plist :to)))
9620 (when (and from to org-from-is-user-regexp)
9621 (setq plist
9622 (plist-put plist :fromto
9623 (if (string-match org-from-is-user-regexp from)
9624 (concat "to %t")
9625 (concat "from %f"))))))
9626 (setq org-store-link-plist plist))
9628 (defun org-add-link-props (&rest plist)
9629 "Add these properties to the link property list."
9630 (let (key value)
9631 (while plist
9632 (setq key (pop plist) value (pop plist))
9633 (setq org-store-link-plist
9634 (plist-put org-store-link-plist key value)))))
9636 (defun org-email-link-description (&optional fmt)
9637 "Return the description part of an email link.
9638 This takes information from `org-store-link-plist' and formats it
9639 according to FMT (default from `org-email-link-description-format')."
9640 (setq fmt (or fmt org-email-link-description-format))
9641 (let* ((p org-store-link-plist)
9642 (to (plist-get p :toaddress))
9643 (from (plist-get p :fromaddress))
9644 (table
9645 (list
9646 (cons "%c" (plist-get p :fromto))
9647 (cons "%F" (plist-get p :from))
9648 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9649 (cons "%T" (plist-get p :to))
9650 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9651 (cons "%s" (plist-get p :subject))
9652 (cons "%d" (plist-get p :date))
9653 (cons "%m" (plist-get p :message-id)))))
9654 (when (string-match "%c" fmt)
9655 ;; Check if the user wrote this message
9656 (if (and org-from-is-user-regexp from to
9657 (save-match-data (string-match org-from-is-user-regexp from)))
9658 (setq fmt (replace-match "to %t" t t fmt))
9659 (setq fmt (replace-match "from %f" t t fmt))))
9660 (org-replace-escapes fmt table)))
9662 (defun org-make-org-heading-search-string (&optional string)
9663 "Make search string for the current headline or STRING."
9664 (let ((s (or string
9665 (and (derived-mode-p 'org-mode)
9666 (save-excursion
9667 (org-back-to-heading t)
9668 (org-element-property :raw-value (org-element-at-point))))))
9669 (lines org-context-in-file-links))
9670 (or string (setq s (concat "*" s))) ; Add * for headlines
9671 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9672 (when (and string (integerp lines) (> lines 0))
9673 (let ((slines (org-split-string s "\n")))
9674 (when (< lines (length slines))
9675 (setq s (mapconcat
9676 'identity
9677 (reverse (nthcdr (- (length slines) lines)
9678 (reverse slines))) "\n")))))
9679 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9681 (defun org-make-link-string (link &optional description)
9682 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9683 (unless (string-match "\\S-" link)
9684 (error "Empty link"))
9685 (when (and description
9686 (stringp description)
9687 (not (string-match "\\S-" description)))
9688 (setq description nil))
9689 (when (stringp description)
9690 ;; Remove brackets from the description, they are fatal.
9691 (while (string-match "\\[" description)
9692 (setq description (replace-match "{" t t description)))
9693 (while (string-match "\\]" description)
9694 (setq description (replace-match "}" t t description))))
9695 (when (equal link description)
9696 ;; No description needed, it is identical
9697 (setq description nil))
9698 (when (and (not description)
9699 (not (string-match (org-image-file-name-regexp) link))
9700 (not (equal link (org-link-escape link))))
9701 (setq description (org-extract-attributes link)))
9702 (setq link
9703 (cond ((string-match (org-image-file-name-regexp) link) link)
9704 ((string-match org-link-types-re link)
9705 (concat (match-string 1 link)
9706 (org-link-escape (substring link (match-end 1)))))
9707 (t (org-link-escape link))))
9708 (concat "[[" link "]"
9709 (if description (concat "[" description "]") "")
9710 "]"))
9712 (defconst org-link-escape-chars
9713 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9714 "List of characters that should be escaped in link.
9715 This is the list that is used for internal purposes.")
9717 (defconst org-link-escape-chars-browser
9718 '(?\ ?\")
9719 "List of escapes for characters that are problematic in links.
9720 This is the list that is used before handing over to the browser.")
9722 (defun org-link-escape (text &optional table merge)
9723 "Return percent escaped representation of TEXT.
9724 TEXT is a string with the text to escape.
9725 Optional argument TABLE is a list with characters that should be
9726 escaped. When nil, `org-link-escape-chars' is used.
9727 If optional argument MERGE is set, merge TABLE into
9728 `org-link-escape-chars'."
9729 (cond
9730 ((and table merge)
9731 (mapc (lambda (defchr)
9732 (unless (member defchr table)
9733 (setq table (cons defchr table)))) org-link-escape-chars))
9734 ((null table)
9735 (setq table org-link-escape-chars)))
9736 (mapconcat
9737 (lambda (char)
9738 (if (or (member char table)
9739 (and (or (< char 32) (= char 37) (> char 126))
9740 org-url-hexify-p))
9741 (mapconcat (lambda (sequence-element)
9742 (format "%%%.2X" sequence-element))
9743 (or (encode-coding-char char 'utf-8)
9744 (error "Unable to percent escape character: %s"
9745 (char-to-string char))) "")
9746 (char-to-string char))) text ""))
9748 (defun org-link-unescape (str)
9749 "Unhex hexified Unicode strings as returned from the JavaScript function
9750 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9751 (unless (and (null str) (string= "" str))
9752 (let ((pos 0) (case-fold-search t) unhexed)
9753 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9754 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9755 (setq str (replace-match unhexed t t str))
9756 (setq pos (+ pos (length unhexed))))))
9757 str)
9759 (defun org-link-unescape-compound (hex)
9760 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9761 Note: this function also decodes single byte encodings like
9762 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9763 (save-match-data
9764 (let* ((bytes (cdr (split-string hex "%")))
9765 (ret "")
9766 (eat 0)
9767 (sum 0))
9768 (while bytes
9769 (let* ((val (string-to-number (pop bytes) 16))
9770 (shift-xor
9771 (if (= 0 eat)
9772 (cond
9773 ((>= val 252) (cons 6 252))
9774 ((>= val 248) (cons 5 248))
9775 ((>= val 240) (cons 4 240))
9776 ((>= val 224) (cons 3 224))
9777 ((>= val 192) (cons 2 192))
9778 (t (cons 0 0)))
9779 (cons 6 128))))
9780 (if (>= val 192) (setq eat (car shift-xor)))
9781 (setq val (logxor val (cdr shift-xor)))
9782 (setq sum (+ (lsh sum (car shift-xor)) val))
9783 (if (> eat 0) (setq eat (- eat 1)))
9784 (cond
9785 ((= 0 eat) ;multi byte
9786 (setq ret (concat ret (org-char-to-string sum)))
9787 (setq sum 0))
9788 ((not bytes) ; single byte(s)
9789 (setq ret (org-link-unescape-single-byte-sequence hex))))
9790 )) ;; end (while bytes
9791 ret )))
9793 (defun org-link-unescape-single-byte-sequence (hex)
9794 "Unhexify hex-encoded single byte character sequences."
9795 (mapconcat (lambda (byte)
9796 (char-to-string (string-to-number byte 16)))
9797 (cdr (split-string hex "%")) ""))
9799 (defun org-xor (a b)
9800 "Exclusive or."
9801 (if a (not b) b))
9803 (defun org-fixup-message-id-for-http (s)
9804 "Replace special characters in a message id, so it can be used in an http query."
9805 (when (string-match "%" s)
9806 (setq s (mapconcat (lambda (c)
9807 (if (eq c ?%)
9808 "%25"
9809 (char-to-string c)))
9810 s "")))
9811 (while (string-match "<" s)
9812 (setq s (replace-match "%3C" t t s)))
9813 (while (string-match ">" s)
9814 (setq s (replace-match "%3E" t t s)))
9815 (while (string-match "@" s)
9816 (setq s (replace-match "%40" t t s)))
9819 (defun org-link-prettify (link)
9820 "Return a human-readable representation of LINK.
9821 The car of LINK must be a raw link the cdr of LINK must be either
9822 a link description or nil."
9823 (let ((desc (or (cadr link) "<no description>")))
9824 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9825 "<" (car link) ">")))
9827 ;;;###autoload
9828 (defun org-insert-link-global ()
9829 "Insert a link like Org-mode does.
9830 This command can be called in any mode to insert a link in Org-mode syntax."
9831 (interactive)
9832 (org-load-modules-maybe)
9833 (org-run-like-in-org-mode 'org-insert-link))
9835 (defun org-insert-all-links (&optional keep)
9836 "Insert all links in `org-stored-links'."
9837 (interactive "P")
9838 (let ((links (copy-sequence org-stored-links)) l)
9839 (while (setq l (if keep (pop links) (pop org-stored-links)))
9840 (insert "- ")
9841 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9842 (insert "\n"))))
9844 (defun org-link-fontify-links-to-this-file ()
9845 "Fontify links to the current file in `org-stored-links'."
9846 (let ((f (buffer-file-name)) a b)
9847 (setq a (mapcar (lambda(l)
9848 (let ((ll (car l)))
9849 (when (and (string-match "^file:\\(.+\\)::" ll)
9850 (equal f (expand-file-name (match-string 1 ll))))
9851 ll)))
9852 org-stored-links))
9853 (when (featurep 'org-id)
9854 (setq b (mapcar (lambda(l)
9855 (let ((ll (car l)))
9856 (when (and (string-match "^id:\\(.+\\)$" ll)
9857 (equal f (expand-file-name
9858 (or (org-id-find-id-file
9859 (match-string 1 ll)) ""))))
9860 ll)))
9861 org-stored-links)))
9862 (mapcar (lambda(l)
9863 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9864 (delq nil (append a b)))))
9866 (defvar org-link-links-in-this-file nil)
9867 (defun org-insert-link (&optional complete-file link-location default-description)
9868 "Insert a link. At the prompt, enter the link.
9870 Completion can be used to insert any of the link protocol prefixes like
9871 http or ftp in use.
9873 The history can be used to select a link previously stored with
9874 `org-store-link'. When the empty string is entered (i.e. if you just
9875 press RET at the prompt), the link defaults to the most recently
9876 stored link. As SPC triggers completion in the minibuffer, you need to
9877 use M-SPC or C-q SPC to force the insertion of a space character.
9879 You will also be prompted for a description, and if one is given, it will
9880 be displayed in the buffer instead of the link.
9882 If there is already a link at point, this command will allow you to edit link
9883 and description parts.
9885 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9886 be selected using completion. The path to the file will be relative to the
9887 current directory if the file is in the current directory or a subdirectory.
9888 Otherwise, the link will be the absolute path as completed in the minibuffer
9889 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9890 option `org-link-file-path-type'.
9892 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9893 the current directory or below.
9895 With three \\[universal-argument] prefixes, negate the meaning of
9896 `org-keep-stored-link-after-insertion'.
9898 If `org-make-link-description-function' is non-nil, this function will be
9899 called with the link target, and the result will be the default
9900 link description.
9902 If the LINK-LOCATION parameter is non-nil, this value will be
9903 used as the link location instead of reading one interactively.
9905 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9906 be used as the default description."
9907 (interactive "P")
9908 (let* ((wcf (current-window-configuration))
9909 (origbuf (current-buffer))
9910 (region (if (org-region-active-p)
9911 (buffer-substring (region-beginning) (region-end))))
9912 (remove (and region (list (region-beginning) (region-end))))
9913 (desc region)
9914 tmphist ; byte-compile incorrectly complains about this
9915 (link link-location)
9916 (abbrevs org-link-abbrev-alist-local)
9917 entry file all-prefixes auto-desc)
9918 (cond
9919 (link-location) ; specified by arg, just use it.
9920 ((org-in-regexp org-bracket-link-regexp 1)
9921 ;; We do have a link at point, and we are going to edit it.
9922 (setq remove (list (match-beginning 0) (match-end 0)))
9923 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9924 (setq link (read-string "Link: "
9925 (org-link-unescape
9926 (org-match-string-no-properties 1)))))
9927 ((or (org-in-regexp org-angle-link-re)
9928 (org-in-regexp org-plain-link-re))
9929 ;; Convert to bracket link
9930 (setq remove (list (match-beginning 0) (match-end 0))
9931 link (read-string "Link: "
9932 (org-remove-angle-brackets (match-string 0)))))
9933 ((member complete-file '((4) (16)))
9934 ;; Completing read for file names.
9935 (setq link (org-file-complete-link complete-file)))
9937 ;; Read link, with completion for stored links.
9938 (org-link-fontify-links-to-this-file)
9939 (org-switch-to-buffer-other-window "*Org Links*")
9940 (with-current-buffer "*Org Links*"
9941 (erase-buffer)
9942 (insert "Insert a link.
9943 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9944 (when org-stored-links
9945 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9946 (insert (mapconcat 'org-link-prettify
9947 (reverse org-stored-links) "\n")))
9948 (goto-char (point-min)))
9949 (let ((cw (selected-window)))
9950 (select-window (get-buffer-window "*Org Links*" 'visible))
9951 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9952 (unless (pos-visible-in-window-p (point-max))
9953 (org-fit-window-to-buffer))
9954 (and (window-live-p cw) (select-window cw)))
9955 ;; Fake a link history, containing the stored links.
9956 (setq tmphist (append (mapcar 'car org-stored-links)
9957 org-insert-link-history))
9958 (setq all-prefixes (append (mapcar 'car abbrevs)
9959 (mapcar 'car org-link-abbrev-alist)
9960 org-link-types))
9961 (unwind-protect
9962 (progn
9963 (setq link
9964 (org-completing-read
9965 "Link: "
9966 (append
9967 (mapcar (lambda (x) (concat x ":"))
9968 all-prefixes)
9969 (mapcar 'car org-stored-links))
9970 nil nil nil
9971 'tmphist
9972 (caar org-stored-links)))
9973 (if (not (string-match "\\S-" link))
9974 (user-error "No link selected"))
9975 (mapc (lambda(l)
9976 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9977 org-stored-links)
9978 (if (or (member link all-prefixes)
9979 (and (equal ":" (substring link -1))
9980 (member (substring link 0 -1) all-prefixes)
9981 (setq link (substring link 0 -1))))
9982 (setq link (with-current-buffer origbuf
9983 (org-link-try-special-completion link)))))
9984 (set-window-configuration wcf)
9985 (kill-buffer "*Org Links*"))
9986 (setq entry (assoc link org-stored-links))
9987 (or entry (push link org-insert-link-history))
9988 (setq desc (or desc (nth 1 entry)))))
9990 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9991 (not org-keep-stored-link-after-insertion))
9992 (setq org-stored-links (delq (assoc link org-stored-links)
9993 org-stored-links)))
9995 (if (and (string-match org-plain-link-re link)
9996 (not (string-match org-ts-regexp link)))
9997 ;; URL-like link, normalize the use of angular brackets.
9998 (setq link (org-remove-angle-brackets link)))
10000 ;; Check if we are linking to the current file with a search
10001 ;; option If yes, simplify the link by using only the search
10002 ;; option.
10003 (when (and buffer-file-name
10004 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10005 (let* ((path (match-string 1 link))
10006 (case-fold-search nil)
10007 (search (match-string 2 link)))
10008 (save-match-data
10009 (if (equal (file-truename buffer-file-name) (file-truename path))
10010 ;; We are linking to this same file, with a search option
10011 (setq link search)))))
10013 ;; Check if we can/should use a relative path. If yes, simplify the link
10014 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10015 (let* ((type (match-string 1 link))
10016 (path (match-string 2 link))
10017 (origpath path)
10018 (case-fold-search nil))
10019 (cond
10020 ((or (eq org-link-file-path-type 'absolute)
10021 (equal complete-file '(16)))
10022 (setq path (abbreviate-file-name (expand-file-name path))))
10023 ((eq org-link-file-path-type 'noabbrev)
10024 (setq path (expand-file-name path)))
10025 ((eq org-link-file-path-type 'relative)
10026 (setq path (file-relative-name path)))
10028 (save-match-data
10029 (if (string-match (concat "^" (regexp-quote
10030 (expand-file-name
10031 (file-name-as-directory
10032 default-directory))))
10033 (expand-file-name path))
10034 ;; We are linking a file with relative path name.
10035 (setq path (substring (expand-file-name path)
10036 (match-end 0)))
10037 (setq path (abbreviate-file-name (expand-file-name path)))))))
10038 (setq link (concat type path))
10039 (if (equal desc origpath)
10040 (setq desc path))))
10042 (if org-make-link-description-function
10043 (setq desc
10044 (or (condition-case nil
10045 (funcall org-make-link-description-function link desc)
10046 (error (progn (message "Can't get link description from `%s'"
10047 (symbol-name org-make-link-description-function))
10048 (sit-for 2) nil)))
10049 (read-string "Description: " default-description)))
10050 (if default-description (setq desc default-description)
10051 (setq desc (or (and auto-desc desc)
10052 (read-string "Description: " desc)))))
10054 (unless (string-match "\\S-" desc) (setq desc nil))
10055 (if remove (apply 'delete-region remove))
10056 (insert (org-make-link-string link desc))))
10058 (defun org-link-try-special-completion (type)
10059 "If there is completion support for link type TYPE, offer it."
10060 (let ((fun (intern (concat "org-" type "-complete-link"))))
10061 (if (functionp fun)
10062 (funcall fun)
10063 (read-string "Link (no completion support): " (concat type ":")))))
10065 (defun org-file-complete-link (&optional arg)
10066 "Create a file link using completion."
10067 (let (file link)
10068 (setq file (org-iread-file-name "File: "))
10069 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10070 (pwd1 (file-name-as-directory (abbreviate-file-name
10071 (expand-file-name ".")))))
10072 (cond
10073 ((equal arg '(16))
10074 (setq link (concat
10075 "file:"
10076 (abbreviate-file-name (expand-file-name file)))))
10077 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10078 (setq link (concat "file:" (match-string 1 file))))
10079 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10080 (expand-file-name file))
10081 (setq link (concat
10082 "file:" (match-string 1 (expand-file-name file)))))
10083 (t (setq link (concat "file:" file)))))
10084 link))
10086 (defun org-iread-file-name (&rest args)
10087 "Read-file-name using `ido-mode' speedup if available.
10088 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10089 See `read-file-name' for a description of parameters."
10090 (org-without-partial-completion
10091 (if (and org-completion-use-ido
10092 (fboundp 'ido-read-file-name)
10093 (boundp 'ido-mode) ido-mode
10094 (listp (second args)))
10095 (let ((ido-enter-matching-directory nil))
10096 (apply 'ido-read-file-name args))
10097 (apply 'read-file-name args))))
10099 (defun org-completing-read (&rest args)
10100 "Completing-read with SPACE being a normal character."
10101 (let ((enable-recursive-minibuffers t)
10102 (minibuffer-local-completion-map
10103 (copy-keymap minibuffer-local-completion-map)))
10104 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10105 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10106 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10107 (apply 'org-icompleting-read args)))
10109 (defun org-completing-read-no-i (&rest args)
10110 (let (org-completion-use-ido org-completion-use-iswitchb)
10111 (apply 'org-completing-read args)))
10113 (defun org-iswitchb-completing-read (prompt choices &rest args)
10114 "Use iswitch as a completing-read replacement to choose from choices.
10115 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10116 from."
10117 (let* ((iswitchb-use-virtual-buffers nil)
10118 (iswitchb-make-buflist-hook
10119 (lambda ()
10120 (setq iswitchb-temp-buflist choices))))
10121 (iswitchb-read-buffer prompt)))
10123 (defun org-icompleting-read (&rest args)
10124 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10125 (org-without-partial-completion
10126 (if (and org-completion-use-ido
10127 (fboundp 'ido-completing-read)
10128 (boundp 'ido-mode) ido-mode
10129 (listp (second args)))
10130 (let ((ido-enter-matching-directory nil))
10131 (apply 'ido-completing-read (concat (car args))
10132 (if (consp (car (nth 1 args)))
10133 (mapcar 'car (nth 1 args))
10134 (nth 1 args))
10135 (cddr args)))
10136 (if (and org-completion-use-iswitchb
10137 (boundp 'iswitchb-mode) iswitchb-mode
10138 (listp (second args)))
10139 (apply 'org-iswitchb-completing-read (concat (car args))
10140 (if (consp (car (nth 1 args)))
10141 (mapcar 'car (nth 1 args))
10142 (nth 1 args))
10143 (cddr args))
10144 (apply 'completing-read args)))))
10146 (defun org-extract-attributes (s)
10147 "Extract the attributes cookie from a string and set as text property."
10148 (let (a attr (start 0) key value)
10149 (save-match-data
10150 (when (string-match "{{\\([^}]+\\)}}$" s)
10151 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10152 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10153 (setq key (match-string 1 a) value (match-string 2 a)
10154 start (match-end 0)
10155 attr (plist-put attr (intern key) value))))
10156 (org-add-props s nil 'org-attr attr))
10159 ;;; Opening/following a link
10161 (defvar org-link-search-failed nil)
10163 (defvar org-open-link-functions nil
10164 "Hook for functions finding a plain text link.
10165 These functions must take a single argument, the link content.
10166 They will be called for links that look like [[link text][description]]
10167 when LINK TEXT does not have a protocol like \"http:\" and does not look
10168 like a filename (e.g. \"./blue.png\").
10170 These functions will be called *before* Org attempts to resolve the
10171 link by doing text searches in the current buffer - so if you want a
10172 link \"[[target]]\" to still find \"<<target>>\", your function should
10173 handle this as a special case.
10175 When the function does handle the link, it must return a non-nil value.
10176 If it decides that it is not responsible for this link, it must return
10177 nil to indicate that that Org-mode can continue with other options
10178 like exact and fuzzy text search.")
10180 (defun org-next-link (&optional search-backward)
10181 "Move forward to the next link.
10182 If the link is in hidden text, expose it."
10183 (interactive "P")
10184 (when (and org-link-search-failed (eq this-command last-command))
10185 (goto-char (point-min))
10186 (message "Link search wrapped back to beginning of buffer"))
10187 (setq org-link-search-failed nil)
10188 (let* ((pos (point))
10189 (ct (org-context))
10190 (a (assoc :link ct))
10191 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10192 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10193 ((looking-at org-any-link-re)
10194 ;; Don't stay stuck at link without an org-link face
10195 (forward-char (if search-backward -1 1))))
10196 (if (funcall srch-fun org-any-link-re nil t)
10197 (progn
10198 (goto-char (match-beginning 0))
10199 (if (outline-invisible-p) (org-show-context)))
10200 (goto-char pos)
10201 (setq org-link-search-failed t)
10202 (message "No further link found"))))
10204 (defun org-previous-link ()
10205 "Move backward to the previous link.
10206 If the link is in hidden text, expose it."
10207 (interactive)
10208 (funcall 'org-next-link t))
10210 (defun org-translate-link (s)
10211 "Translate a link string if a translation function has been defined."
10212 (if (and org-link-translation-function
10213 (fboundp org-link-translation-function)
10214 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10215 (progn
10216 (setq s (funcall org-link-translation-function
10217 (match-string 1 s) (match-string 2 s)))
10218 (concat (car s) ":" (cdr s)))
10221 (defun org-translate-link-from-planner (type path)
10222 "Translate a link from Emacs Planner syntax so that Org can follow it.
10223 This is still an experimental function, your mileage may vary."
10224 (cond
10225 ((member type '("http" "https" "news" "ftp"))
10226 ;; standard Internet links are the same.
10227 nil)
10228 ((and (equal type "irc") (string-match "^//" path))
10229 ;; Planner has two / at the beginning of an irc link, we have 1.
10230 ;; We should have zero, actually....
10231 (setq path (substring path 1)))
10232 ((and (equal type "lisp") (string-match "^/" path))
10233 ;; Planner has a slash, we do not.
10234 (setq type "elisp" path (substring path 1)))
10235 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10236 ;; A typical message link. Planner has the id after the final slash,
10237 ;; we separate it with a hash mark
10238 (setq path (concat (match-string 1 path) "#"
10239 (org-remove-angle-brackets (match-string 2 path))))))
10240 (cons type path))
10242 (defun org-find-file-at-mouse (ev)
10243 "Open file link or URL at mouse."
10244 (interactive "e")
10245 (mouse-set-point ev)
10246 (org-open-at-point 'in-emacs))
10248 (defun org-open-at-mouse (ev)
10249 "Open file link or URL at mouse.
10250 See the docstring of `org-open-file' for details."
10251 (interactive "e")
10252 (mouse-set-point ev)
10253 (if (eq major-mode 'org-agenda-mode)
10254 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10255 (org-open-at-point))
10257 (defvar org-window-config-before-follow-link nil
10258 "The window configuration before following a link.
10259 This is saved in case the need arises to restore it.")
10261 (defvar org-open-link-marker (make-marker)
10262 "Marker pointing to the location where `org-open-at-point; was called.")
10264 ;;;###autoload
10265 (defun org-open-at-point-global ()
10266 "Follow a link like Org-mode does.
10267 This command can be called in any mode to follow a link that has
10268 Org-mode syntax."
10269 (interactive)
10270 (org-run-like-in-org-mode 'org-open-at-point))
10272 ;;;###autoload
10273 (defun org-open-link-from-string (s &optional arg reference-buffer)
10274 "Open a link in the string S, as if it was in Org-mode."
10275 (interactive "sLink: \nP")
10276 (let ((reference-buffer (or reference-buffer (current-buffer))))
10277 (with-temp-buffer
10278 (let ((org-inhibit-startup (not reference-buffer)))
10279 (org-mode)
10280 (insert s)
10281 (goto-char (point-min))
10282 (when reference-buffer
10283 (setq org-link-abbrev-alist-local
10284 (with-current-buffer reference-buffer
10285 org-link-abbrev-alist-local)))
10286 (org-open-at-point arg reference-buffer)))))
10288 (defvar org-open-at-point-functions nil
10289 "Hook that is run when following a link at point.
10291 Functions in this hook must return t if they identify and follow
10292 a link at point. If they don't find anything interesting at point,
10293 they must return nil.")
10295 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10296 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10297 (defun org-open-at-point (&optional arg reference-buffer)
10298 "Open link at or after point.
10299 If there is no link at point, this function will search forward up to
10300 the end of the current line.
10301 Normally, files will be opened by an appropriate application. If the
10302 optional prefix argument ARG is non-nil, Emacs will visit the file.
10303 With a double prefix argument, try to open outside of Emacs, in the
10304 application the system uses for this file type."
10305 (interactive "P")
10306 ;; if in a code block, then open the block's results
10307 (unless (call-interactively #'org-babel-open-src-block-result)
10308 (org-load-modules-maybe)
10309 (move-marker org-open-link-marker (point))
10310 (setq org-window-config-before-follow-link (current-window-configuration))
10311 (org-remove-occur-highlights nil nil t)
10312 (cond
10313 ((and (org-at-heading-p)
10314 (not (org-at-timestamp-p t))
10315 (not (org-in-regexp
10316 (concat org-plain-link-re "\\|"
10317 org-bracket-link-regexp "\\|"
10318 org-angle-link-re "\\|"
10319 "[ \t]:[^ \t\n]+:[ \t]*$")))
10320 (not (get-text-property (point) 'org-linked-text)))
10321 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10322 (lk0 (car lkall))
10323 (lk (if (stringp lk0) (list lk0) lk0))
10324 (lkend (cdr lkall)))
10325 (mapcar (lambda(l)
10326 (search-forward l nil lkend)
10327 (goto-char (match-beginning 0))
10328 (org-open-at-point))
10329 lk))
10330 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10331 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10332 ((and (org-at-timestamp-p t)
10333 (not (org-in-regexp org-bracket-link-regexp)))
10334 (org-follow-timestamp-link))
10335 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10336 (not (org-in-regexp org-any-link-re)))
10337 (org-footnote-action))
10339 (let (type path link line search (pos (point)))
10340 (catch 'match
10341 (save-excursion
10342 (skip-chars-forward "^]\n\r")
10343 (when (org-in-regexp org-bracket-link-regexp 1)
10344 (setq link (org-extract-attributes
10345 (org-link-unescape (org-match-string-no-properties 1))))
10346 (while (string-match " *\n *" link)
10347 (setq link (replace-match " " t t link)))
10348 (setq link (org-link-expand-abbrev link))
10349 (cond
10350 ((or (file-name-absolute-p link)
10351 (string-match "^\\.\\.?/" link))
10352 (setq type "file" path link))
10353 ((string-match org-link-re-with-space3 link)
10354 (setq type (match-string 1 link) path (match-string 2 link)))
10355 ((string-match "^help:+\\(.+\\)" link)
10356 (setq type "help" path (match-string 1 link)))
10357 (t (setq type "thisfile" path link)))
10358 (throw 'match t)))
10360 (when (get-text-property (point) 'org-linked-text)
10361 (setq type "thisfile"
10362 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10363 (1+ (point)) (point))
10364 path (buffer-substring
10365 (or (previous-single-property-change pos 'org-linked-text)
10366 (point-min))
10367 (or (next-single-property-change pos 'org-linked-text)
10368 (point-max)))
10369 ;; Ensure we will search for a <<<radio>>> link, not
10370 ;; a simple reference like <<ref>>
10371 path (concat "<" path))
10372 (throw 'match t))
10374 (save-excursion
10375 (when (or (org-in-regexp org-angle-link-re)
10376 (let ((match (org-in-regexp org-plain-link-re)))
10377 ;; Check a plain link is not within a bracket link
10378 (and match
10379 (save-excursion
10380 (progn
10381 (goto-char (car match))
10382 (not (org-in-regexp org-bracket-link-regexp))))))
10383 (let ((line_ending (save-excursion (end-of-line) (point))))
10384 ;; We are in a line before a plain or bracket link
10385 (or (re-search-forward org-plain-link-re line_ending t)
10386 (re-search-forward org-bracket-link-regexp line_ending t))))
10387 (setq type (match-string 1)
10388 path (org-link-unescape (match-string 2)))
10389 (throw 'match t)))
10390 (save-excursion
10391 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10392 (setq type "tags"
10393 path (match-string 1))
10394 (while (string-match ":" path)
10395 (setq path (replace-match "+" t t path)))
10396 (throw 'match t)))
10397 (when (org-in-regexp "<\\([^><\n]+\\)>")
10398 (setq type "tree-match"
10399 path (match-string 1))
10400 (throw 'match t)))
10401 (unless path
10402 (user-error "No link found"))
10404 ;; switch back to reference buffer
10405 ;; needed when if called in a temporary buffer through
10406 ;; org-open-link-from-string
10407 (with-current-buffer (or reference-buffer (current-buffer))
10409 ;; Remove any trailing spaces in path
10410 (if (string-match " +\\'" path)
10411 (setq path (replace-match "" t t path)))
10412 (if (and org-link-translation-function
10413 (fboundp org-link-translation-function))
10414 ;; Check if we need to translate the link
10415 (let ((tmp (funcall org-link-translation-function type path)))
10416 (setq type (car tmp) path (cdr tmp))))
10418 (cond
10420 ((assoc type org-link-protocols)
10421 (funcall (nth 1 (assoc type org-link-protocols)) path))
10423 ((equal type "help")
10424 (let ((f-or-v (intern path)))
10425 (cond ((fboundp f-or-v)
10426 (describe-function f-or-v))
10427 ((boundp f-or-v)
10428 (describe-variable f-or-v))
10429 (t (error "Not a known function or variable")))))
10431 ((equal type "mailto")
10432 (let ((cmd (car org-link-mailto-program))
10433 (args (cdr org-link-mailto-program)) args1
10434 (address path) (subject "") a)
10435 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10436 (setq address (match-string 1 path)
10437 subject (org-link-escape (match-string 2 path))))
10438 (while args
10439 (cond
10440 ((not (stringp (car args))) (push (pop args) args1))
10441 (t (setq a (pop args))
10442 (if (string-match "%a" a)
10443 (setq a (replace-match address t t a)))
10444 (if (string-match "%s" a)
10445 (setq a (replace-match subject t t a)))
10446 (push a args1))))
10447 (apply cmd (nreverse args1))))
10449 ((member type '("http" "https" "ftp" "news"))
10450 (browse-url
10451 (concat type ":"
10452 (if (org-string-match-p
10453 (concat "[[:nonascii:]"
10454 org-link-escape-chars-browser "]")
10455 path)
10456 (org-link-escape path org-link-escape-chars-browser)
10457 path))))
10459 ((string= type "doi")
10460 (browse-url
10461 (concat org-doi-server-url
10462 (if (org-string-match-p
10463 (concat "[[:nonascii:]"
10464 org-link-escape-chars-browser "]")
10465 path)
10466 (org-link-escape path org-link-escape-chars-browser)
10467 path))))
10469 ((member type '("message"))
10470 (browse-url (concat type ":" path)))
10472 ((string= type "tags")
10473 (org-tags-view arg path))
10475 ((string= type "tree-match")
10476 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10478 ((string= type "file")
10479 (if (string-match "::\\([0-9]+\\)\\'" path)
10480 (setq line (string-to-number (match-string 1 path))
10481 path (substring path 0 (match-beginning 0)))
10482 (if (string-match "::\\(.+\\)\\'" path)
10483 (setq search (match-string 1 path)
10484 path (substring path 0 (match-beginning 0)))))
10485 (if (string-match "[*?{]" (file-name-nondirectory path))
10486 (dired path)
10487 (org-open-file path arg line search)))
10489 ((string= type "shell")
10490 (let ((buf (generate-new-buffer "*Org Shell Output"))
10491 (cmd path))
10492 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10493 (string-match org-confirm-shell-link-not-regexp cmd))
10494 (not org-confirm-shell-link-function)
10495 (funcall org-confirm-shell-link-function
10496 (format "Execute \"%s\" in shell? "
10497 (org-add-props cmd nil
10498 'face 'org-warning))))
10499 (progn
10500 (message "Executing %s" cmd)
10501 (shell-command cmd buf)
10502 (if (featurep 'midnight)
10503 (setq clean-buffer-list-kill-buffer-names
10504 (cons buf clean-buffer-list-kill-buffer-names))))
10505 (error "Abort"))))
10507 ((string= type "elisp")
10508 (let ((cmd path))
10509 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10510 (string-match org-confirm-elisp-link-not-regexp cmd))
10511 (not org-confirm-elisp-link-function)
10512 (funcall org-confirm-elisp-link-function
10513 (format "Execute \"%s\" as elisp? "
10514 (org-add-props cmd nil
10515 'face 'org-warning))))
10516 (message "%s => %s" cmd
10517 (if (equal (string-to-char cmd) ?\()
10518 (eval (read cmd))
10519 (call-interactively (read cmd))))
10520 (error "Abort"))))
10522 ((and (string= type "thisfile")
10523 (or (run-hook-with-args-until-success
10524 'org-open-link-functions path)
10525 (and link
10526 (string-match "^id:" link)
10527 (or (featurep 'org-id) (require 'org-id))
10528 (progn
10529 (funcall (nth 1 (assoc "id" org-link-protocols))
10530 (substring path 3))
10531 t)))))
10533 ((string= type "thisfile")
10534 (if arg
10535 (switch-to-buffer-other-window
10536 (org-get-buffer-for-internal-link (current-buffer)))
10537 (org-mark-ring-push))
10538 (let ((cmd `(org-link-search
10539 ,path
10540 ,(cond ((equal arg '(4)) ''occur)
10541 ((equal arg '(16)) ''org-occur))
10542 ,pos)))
10543 (condition-case nil (let ((org-link-search-inhibit-query t))
10544 (eval cmd))
10545 (error (progn (widen) (eval cmd))))))
10547 (t (browse-url-at-point)))))))
10548 (move-marker org-open-link-marker nil)
10549 (run-hook-with-args 'org-follow-link-hook)))
10551 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10552 "Offer links in the current entry and return the selected link.
10553 If there is only one link, return it.
10554 If NTH is an integer, return the NTH link found.
10555 If ZERO is a string, check also this string for a link, and if
10556 there is one, return it."
10557 (with-current-buffer buffer
10558 (save-excursion
10559 (save-restriction
10560 (widen)
10561 (goto-char marker)
10562 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10563 "\\(" org-angle-link-re "\\)\\|"
10564 "\\(" org-plain-link-re "\\)"))
10565 (cnt ?0)
10566 (in-emacs (if (integerp nth) nil nth))
10567 have-zero end links link c)
10568 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10569 (push (match-string 0 zero) links)
10570 (setq cnt (1- cnt) have-zero t))
10571 (save-excursion
10572 (org-back-to-heading t)
10573 (setq end (save-excursion (outline-next-heading) (point)))
10574 (while (re-search-forward re end t)
10575 (push (match-string 0) links))
10576 (setq links (org-uniquify (reverse links))))
10577 (cond
10578 ((null links)
10579 (message "No links"))
10580 ((equal (length links) 1)
10581 (setq link (car links)))
10582 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10583 (setq link (nth (if have-zero nth (1- nth)) links)))
10584 (t ; we have to select a link
10585 (save-excursion
10586 (save-window-excursion
10587 (delete-other-windows)
10588 (with-output-to-temp-buffer "*Select Link*"
10589 (mapc (lambda (l)
10590 (if (not (string-match org-bracket-link-regexp l))
10591 (princ (format "[%c] %s\n" (incf cnt)
10592 (org-remove-angle-brackets l)))
10593 (if (match-end 3)
10594 (princ (format "[%c] %s (%s)\n" (incf cnt)
10595 (match-string 3 l) (match-string 1 l)))
10596 (princ (format "[%c] %s\n" (incf cnt)
10597 (match-string 1 l))))))
10598 links))
10599 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10600 (message "Select link to open, RET to open all:")
10601 (setq c (read-char-exclusive))
10602 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10603 (when (equal c ?q) (error "Abort"))
10604 (if (equal c ?\C-m)
10605 (setq link links)
10606 (setq nth (- c ?0))
10607 (if have-zero (setq nth (1+ nth)))
10608 (unless (and (integerp nth) (>= (length links) nth))
10609 (user-error "Invalid link selection"))
10610 (setq link (nth (1- nth) links)))))
10611 (cons link end))))))
10613 ;; Add special file links that specify the way of opening
10615 (org-add-link-type "file+sys" 'org-open-file-with-system)
10616 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10617 (defun org-open-file-with-system (path)
10618 "Open file at PATH using the system way of opening it."
10619 (org-open-file path 'system))
10620 (defun org-open-file-with-emacs (path)
10621 "Open file at PATH in Emacs."
10622 (org-open-file path 'emacs))
10625 ;;; File search
10627 (defvar org-create-file-search-functions nil
10628 "List of functions to construct the right search string for a file link.
10629 These functions are called in turn with point at the location to
10630 which the link should point.
10632 A function in the hook should first test if it would like to
10633 handle this file type, for example by checking the `major-mode'
10634 or the file extension. If it decides not to handle this file, it
10635 should just return nil to give other functions a chance. If it
10636 does handle the file, it must return the search string to be used
10637 when following the link. The search string will be part of the
10638 file link, given after a double colon, and `org-open-at-point'
10639 will automatically search for it. If special measures must be
10640 taken to make the search successful, another function should be
10641 added to the companion hook `org-execute-file-search-functions',
10642 which see.
10644 A function in this hook may also use `setq' to set the variable
10645 `description' to provide a suggestion for the descriptive text to
10646 be used for this link when it gets inserted into an Org-mode
10647 buffer with \\[org-insert-link].")
10649 (defvar org-execute-file-search-functions nil
10650 "List of functions to execute a file search triggered by a link.
10652 Functions added to this hook must accept a single argument, the
10653 search string that was part of the file link, the part after the
10654 double colon. The function must first check if it would like to
10655 handle this search, for example by checking the `major-mode' or
10656 the file extension. If it decides not to handle this search, it
10657 should just return nil to give other functions a chance. If it
10658 does handle the search, it must return a non-nil value to keep
10659 other functions from trying.
10661 Each function can access the current prefix argument through the
10662 variable `current-prefix-arg'. Note that a single prefix is used
10663 to force opening a link in Emacs, so it may be good to only use a
10664 numeric or double prefix to guide the search function.
10666 In case this is needed, a function in this hook can also restore
10667 the window configuration before `org-open-at-point' was called using:
10669 (set-window-configuration org-window-config-before-follow-link)")
10671 (defun org-link-search (s &optional type avoid-pos stealth)
10672 "Search for a link search option.
10673 If S is surrounded by forward slashes, it is interpreted as a
10674 regular expression. In org-mode files, this will create an `org-occur'
10675 sparse tree. In ordinary files, `occur' will be used to list matches.
10676 If the current buffer is in `dired-mode', grep will be used to search
10677 in all files. If AVOID-POS is given, ignore matches near that position.
10679 When optional argument STEALTH is non-nil, do not modify
10680 visibility around point, thus ignoring
10681 `org-show-hierarchy-above', `org-show-following-heading' and
10682 `org-show-siblings' variables."
10683 (let ((case-fold-search t)
10684 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10685 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10686 (append '(("") (" ") ("\t") ("\n"))
10687 org-emphasis-alist)
10688 "\\|") "\\)"))
10689 (pos (point))
10690 (pre nil) (post nil)
10691 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10692 (cond
10693 ;; First check if there are any special search functions
10694 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10695 ;; Now try the builtin stuff
10696 ((and (equal (string-to-char s0) ?#)
10697 (> (length s0) 1)
10698 (save-excursion
10699 (goto-char (point-min))
10700 (and
10701 (re-search-forward
10702 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10703 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10704 (setq type 'dedicated
10705 pos (match-beginning 0))))
10706 ;; There is an exact target for this
10707 (goto-char pos)
10708 (org-back-to-heading t)))
10709 ((save-excursion
10710 (goto-char (point-min))
10711 (and
10712 (re-search-forward
10713 (concat "<<" (regexp-quote s0) ">>") nil t)
10714 (setq type 'dedicated
10715 pos (match-beginning 0))))
10716 ;; There is an exact target for this
10717 (goto-char pos))
10718 ((save-excursion
10719 (goto-char (point-min))
10720 (and
10721 (re-search-forward
10722 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10723 (setq type 'dedicated pos (match-beginning 0))))
10724 ;; Found an element with a matching #+name affiliated keyword.
10725 (goto-char pos))
10726 ((and (string-match "^(\\(.*\\))$" s0)
10727 (save-excursion
10728 (goto-char (point-min))
10729 (and
10730 (re-search-forward
10731 (concat "[^[]" (regexp-quote
10732 (format org-coderef-label-format
10733 (match-string 1 s0))))
10734 nil t)
10735 (setq type 'dedicated
10736 pos (1+ (match-beginning 0))))))
10737 ;; There is a coderef target for this
10738 (goto-char pos))
10739 ((string-match "^/\\(.*\\)/$" s)
10740 ;; A regular expression
10741 (cond
10742 ((derived-mode-p 'org-mode)
10743 (org-occur (match-string 1 s)))
10744 (t (org-do-occur (match-string 1 s)))))
10745 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10746 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10747 (goto-char (point-min))
10748 (cond
10749 ((let (case-fold-search)
10750 (re-search-forward (format org-complex-heading-regexp-format
10751 (regexp-quote s))
10752 nil t))
10753 ;; OK, found a match
10754 (setq type 'dedicated)
10755 (goto-char (match-beginning 0)))
10756 ((and (not org-link-search-inhibit-query)
10757 (eq org-link-search-must-match-exact-headline 'query-to-create)
10758 (y-or-n-p "No match - create this as a new heading? "))
10759 (goto-char (point-max))
10760 (or (bolp) (newline))
10761 (insert "* " s "\n")
10762 (beginning-of-line 0))
10764 (goto-char pos)
10765 (error "No match"))))
10767 ;; A normal search string
10768 (when (equal (string-to-char s) ?*)
10769 ;; Anchor on headlines, post may include tags.
10770 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10771 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10772 s (substring s 1)))
10773 (remove-text-properties
10774 0 (length s)
10775 '(face nil mouse-face nil keymap nil fontified nil) s)
10776 ;; Make a series of regular expressions to find a match
10777 (setq words (org-split-string s "[ \n\r\t]+")
10779 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10780 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10781 "\\)" markers)
10782 re2a_ (concat "\\(" (mapconcat 'downcase words
10783 "[ \t\r\n]+") "\\)[ \t\r\n]")
10784 re2a (concat "[ \t\r\n]" re2a_)
10785 re4_ (concat "\\(" (mapconcat 'downcase words
10786 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10787 re4 (concat "[^a-zA-Z_]" re4_)
10789 re1 (concat pre re2 post)
10790 re3 (concat pre (if pre re4_ re4) post)
10791 re5 (concat pre ".*" re4)
10792 re2 (concat pre re2)
10793 re2a (concat pre (if pre re2a_ re2a))
10794 re4 (concat pre (if pre re4_ re4))
10795 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10796 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10797 re5 "\\)"))
10798 (cond
10799 ((eq type 'org-occur) (org-occur reall))
10800 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10801 (t (goto-char (point-min))
10802 (setq type 'fuzzy)
10803 (if (or (and (org-search-not-self 1 re0 nil t)
10804 (setq type 'dedicated))
10805 (org-search-not-self 1 re1 nil t)
10806 (org-search-not-self 1 re2 nil t)
10807 (org-search-not-self 1 re2a nil t)
10808 (org-search-not-self 1 re3 nil t)
10809 (org-search-not-self 1 re4 nil t)
10810 (org-search-not-self 1 re5 nil t))
10811 (goto-char (match-beginning 1))
10812 (goto-char pos)
10813 (error "No match"))))))
10814 (and (derived-mode-p 'org-mode)
10815 (not stealth)
10816 (org-show-context 'link-search))
10817 type))
10819 (defun org-search-not-self (group &rest args)
10820 "Execute `re-search-forward', but only accept matches that do not
10821 enclose the position of `org-open-link-marker'."
10822 (let ((m org-open-link-marker))
10823 (catch 'exit
10824 (while (apply 're-search-forward args)
10825 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10826 (goto-char (match-end group))
10827 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10828 (> (match-beginning 0) (marker-position m))
10829 (< (match-end 0) (marker-position m)))
10830 (save-match-data
10831 (or (not (org-in-regexp
10832 org-bracket-link-analytic-regexp 1))
10833 (not (match-end 4)) ; no description
10834 (and (<= (match-beginning 4) (point))
10835 (>= (match-end 4) (point))))))
10836 (throw 'exit (point))))))))
10838 (defun org-get-buffer-for-internal-link (buffer)
10839 "Return a buffer to be used for displaying the link target of internal links."
10840 (cond
10841 ((not org-display-internal-link-with-indirect-buffer)
10842 buffer)
10843 ((string-match "(Clone)$" (buffer-name buffer))
10844 (message "Buffer is already a clone, not making another one")
10845 ;; we also do not modify visibility in this case
10846 buffer)
10847 (t ; make a new indirect buffer for displaying the link
10848 (let* ((bn (buffer-name buffer))
10849 (ibn (concat bn "(Clone)"))
10850 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10851 (with-current-buffer ib (org-overview))
10852 ib))))
10854 (defun org-do-occur (regexp &optional cleanup)
10855 "Call the Emacs command `occur'.
10856 If CLEANUP is non-nil, remove the printout of the regular expression
10857 in the *Occur* buffer. This is useful if the regex is long and not useful
10858 to read."
10859 (occur regexp)
10860 (when cleanup
10861 (let ((cwin (selected-window)) win beg end)
10862 (when (setq win (get-buffer-window "*Occur*"))
10863 (select-window win))
10864 (goto-char (point-min))
10865 (when (re-search-forward "match[a-z]+" nil t)
10866 (setq beg (match-end 0))
10867 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10868 (setq end (1- (match-beginning 0)))))
10869 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10870 (goto-char (point-min))
10871 (select-window cwin))))
10873 ;;; The mark ring for links jumps
10875 (defvar org-mark-ring nil
10876 "Mark ring for positions before jumps in Org-mode.")
10877 (defvar org-mark-ring-last-goto nil
10878 "Last position in the mark ring used to go back.")
10879 ;; Fill and close the ring
10880 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10881 (loop for i from 1 to org-mark-ring-length do
10882 (push (make-marker) org-mark-ring))
10883 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10884 org-mark-ring)
10886 (defun org-mark-ring-push (&optional pos buffer)
10887 "Put the current position or POS into the mark ring and rotate it."
10888 (interactive)
10889 (setq pos (or pos (point)))
10890 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10891 (move-marker (car org-mark-ring)
10892 (or pos (point))
10893 (or buffer (current-buffer)))
10894 (message "%s"
10895 (substitute-command-keys
10896 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10898 (defun org-mark-ring-goto (&optional n)
10899 "Jump to the previous position in the mark ring.
10900 With prefix arg N, jump back that many stored positions. When
10901 called several times in succession, walk through the entire ring.
10902 Org-mode commands jumping to a different position in the current file,
10903 or to another Org-mode file, automatically push the old position
10904 onto the ring."
10905 (interactive "p")
10906 (let (p m)
10907 (if (eq last-command this-command)
10908 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10909 (setq p org-mark-ring))
10910 (setq org-mark-ring-last-goto p)
10911 (setq m (car p))
10912 (org-pop-to-buffer-same-window (marker-buffer m))
10913 (goto-char m)
10914 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10916 (defun org-remove-angle-brackets (s)
10917 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10918 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10920 (defun org-add-angle-brackets (s)
10921 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10922 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10924 (defun org-remove-double-quotes (s)
10925 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10926 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10929 ;;; Following specific links
10931 (defun org-follow-timestamp-link ()
10932 "Open an agenda view for the time-stamp date/range at point."
10933 (cond
10934 ((org-at-date-range-p t)
10935 (let ((org-agenda-start-on-weekday)
10936 (t1 (match-string 1))
10937 (t2 (match-string 2)) tt1 tt2)
10938 (setq tt1 (time-to-days (org-time-string-to-time t1))
10939 tt2 (time-to-days (org-time-string-to-time t2)))
10940 (let ((org-agenda-buffer-tmp-name
10941 (format "*Org Agenda(a:%s)"
10942 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10943 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10944 ((org-at-timestamp-p t)
10945 (let ((org-agenda-buffer-tmp-name
10946 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10947 (org-agenda-list nil (time-to-days (org-time-string-to-time
10948 (substring (match-string 1) 0 10)))
10949 1)))
10950 (t (error "This should not happen"))))
10953 ;;; Following file links
10954 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10955 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10956 (declare-function mailcap-mime-info
10957 "mailcap" (string &optional request no-decode))
10958 (defvar org-wait nil)
10959 (defun org-open-file (path &optional in-emacs line search)
10960 "Open the file at PATH.
10961 First, this expands any special file name abbreviations. Then the
10962 configuration variable `org-file-apps' is checked if it contains an
10963 entry for this file type, and if yes, the corresponding command is launched.
10965 If no application is found, Emacs simply visits the file.
10967 With optional prefix argument IN-EMACS, Emacs will visit the file.
10968 With a double \\[universal-argument] \\[universal-argument] \
10969 prefix arg, Org tries to avoid opening in Emacs
10970 and to use an external application to visit the file.
10972 Optional LINE specifies a line to go to, optional SEARCH a string
10973 to search for. If LINE or SEARCH is given, the file will be
10974 opened in Emacs, unless an entry from org-file-apps that makes
10975 use of groups in a regexp matches.
10977 If you want to change the way frames are used when following a
10978 link, please customize `org-link-frame-setup'.
10980 If the file does not exist, an error is thrown."
10981 (let* ((file (if (equal path "")
10982 buffer-file-name
10983 (substitute-in-file-name (expand-file-name path))))
10984 (file-apps (append org-file-apps (org-default-apps)))
10985 (apps (org-remove-if
10986 'org-file-apps-entry-match-against-dlink-p file-apps))
10987 (apps-dlink (org-remove-if-not
10988 'org-file-apps-entry-match-against-dlink-p file-apps))
10989 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10990 (dirp (if remp nil (file-directory-p file)))
10991 (file (if (and dirp org-open-directory-means-index-dot-org)
10992 (concat (file-name-as-directory file) "index.org")
10993 file))
10994 (a-m-a-p (assq 'auto-mode apps))
10995 (dfile (downcase file))
10996 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10997 (link (cond ((and (eq line nil)
10998 (eq search nil))
10999 file)
11000 (line
11001 (concat file "::" (number-to-string line)))
11002 (search
11003 (concat file "::" search))))
11004 (dlink (downcase link))
11005 (old-buffer (current-buffer))
11006 (old-pos (point))
11007 (old-mode major-mode)
11008 ext cmd link-match-data)
11009 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11010 (setq ext (match-string 1 dfile))
11011 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11012 (setq ext (match-string 1 dfile))))
11013 (cond
11014 ((member in-emacs '((16) system))
11015 (setq cmd (cdr (assoc 'system apps))))
11016 (in-emacs (setq cmd 'emacs))
11018 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11019 (and dirp (cdr (assoc 'directory apps)))
11020 ; first, try matching against apps-dlink
11021 ; if we get a match here, store the match data for later
11022 (let ((match (assoc-default dlink apps-dlink
11023 'string-match)))
11024 (if match
11025 (progn (setq link-match-data (match-data))
11026 match)
11027 (progn (setq in-emacs (or in-emacs line search))
11028 nil))) ; if we have no match in apps-dlink,
11029 ; always open the file in emacs if line or search
11030 ; is given (for backwards compatibility)
11031 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11032 'string-match)
11033 (cdr (assoc ext apps))
11034 (cdr (assoc t apps))))))
11035 (when (eq cmd 'system)
11036 (setq cmd (cdr (assoc 'system apps))))
11037 (when (eq cmd 'default)
11038 (setq cmd (cdr (assoc t apps))))
11039 (when (eq cmd 'mailcap)
11040 (require 'mailcap)
11041 (mailcap-parse-mailcaps)
11042 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11043 (command (mailcap-mime-info mime-type)))
11044 (if (stringp command)
11045 (setq cmd command)
11046 (setq cmd 'emacs))))
11047 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11048 (not (file-exists-p file))
11049 (not org-open-non-existing-files))
11050 (user-error "No such file: %s" file))
11051 (cond
11052 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11053 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11054 (while (string-match "['\"]%s['\"]" cmd)
11055 (setq cmd (replace-match "%s" t t cmd)))
11056 (while (string-match "%s" cmd)
11057 (setq cmd (replace-match
11058 (save-match-data
11059 (shell-quote-argument
11060 (convert-standard-filename file)))
11061 t t cmd)))
11063 ;; Replace "%1", "%2" etc. in command with group matches from regex
11064 (save-match-data
11065 (let ((match-index 1)
11066 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11067 (set-match-data link-match-data)
11068 (while (<= match-index number-of-groups)
11069 (let ((regex (concat "%" (number-to-string match-index)))
11070 (replace-with (match-string match-index dlink)))
11071 (while (string-match regex cmd)
11072 (setq cmd (replace-match replace-with t t cmd))))
11073 (setq match-index (+ match-index 1)))))
11075 (save-window-excursion
11076 (message "Running %s...done" cmd)
11077 (start-process-shell-command cmd nil cmd)
11078 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11079 ((or (stringp cmd)
11080 (eq cmd 'emacs))
11081 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11082 (widen)
11083 (if line (org-goto-line line)
11084 (if search (org-link-search search))))
11085 ((consp cmd)
11086 (let ((file (convert-standard-filename file)))
11087 (save-match-data
11088 (set-match-data link-match-data)
11089 (eval cmd))))
11090 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11091 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11092 (or (not (equal old-buffer (current-buffer)))
11093 (not (equal old-pos (point))))
11094 (org-mark-ring-push old-pos old-buffer))))
11096 (defun org-file-apps-entry-match-against-dlink-p (entry)
11097 "This function returns non-nil if `entry' uses a regular
11098 expression which should be matched against the whole link by
11099 org-open-file.
11101 It assumes that is the case when the entry uses a regular
11102 expression which has at least one grouping construct and the
11103 action is either a lisp form or a command string containing
11104 '%1', i.e. using at least one subexpression match as a
11105 parameter."
11106 (let ((selector (car entry))
11107 (action (cdr entry)))
11108 (if (stringp selector)
11109 (and (> (regexp-opt-depth selector) 0)
11110 (or (and (stringp action)
11111 (string-match "%[0-9]" action))
11112 (consp action)))
11113 nil)))
11115 (defun org-default-apps ()
11116 "Return the default applications for this operating system."
11117 (cond
11118 ((eq system-type 'darwin)
11119 org-file-apps-defaults-macosx)
11120 ((eq system-type 'windows-nt)
11121 org-file-apps-defaults-windowsnt)
11122 (t org-file-apps-defaults-gnu)))
11124 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11125 "Convert extensions to regular expressions in the cars of LIST.
11126 Also, weed out any non-string entries, because the return value is used
11127 only for regexp matching.
11128 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11129 point to the symbol `emacs', indicating that the file should
11130 be opened in Emacs."
11131 (append
11132 (delq nil
11133 (mapcar (lambda (x)
11134 (if (not (stringp (car x)))
11136 (if (string-match "\\W" (car x))
11138 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11139 list))
11140 (if add-auto-mode
11141 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11143 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11144 (defun org-file-remote-p (file)
11145 "Test whether FILE specifies a location on a remote system.
11146 Return non-nil if the location is indeed remote.
11148 For example, the filename \"/user@host:/foo\" specifies a location
11149 on the system \"/user@host:\"."
11150 (cond ((fboundp 'file-remote-p)
11151 (file-remote-p file))
11152 ((fboundp 'tramp-handle-file-remote-p)
11153 (tramp-handle-file-remote-p file))
11154 ((and (boundp 'ange-ftp-name-format)
11155 (string-match (car ange-ftp-name-format) file))
11156 t)))
11159 ;;;; Refiling
11161 (defun org-get-org-file ()
11162 "Read a filename, with default directory `org-directory'."
11163 (let ((default (or org-default-notes-file remember-data-file)))
11164 (read-file-name (format "File name [%s]: " default)
11165 (file-name-as-directory org-directory)
11166 default)))
11168 (defun org-notes-order-reversed-p ()
11169 "Check if the current file should receive notes in reversed order."
11170 (cond
11171 ((not org-reverse-note-order) nil)
11172 ((eq t org-reverse-note-order) t)
11173 ((not (listp org-reverse-note-order)) nil)
11174 (t (catch 'exit
11175 (let ((all org-reverse-note-order)
11176 entry)
11177 (while (setq entry (pop all))
11178 (if (string-match (car entry) buffer-file-name)
11179 (throw 'exit (cdr entry))))
11180 nil)))))
11182 (defvar org-refile-target-table nil
11183 "The list of refile targets, created by `org-refile'.")
11185 (defvar org-agenda-new-buffers nil
11186 "Buffers created to visit agenda files.")
11188 (defvar org-refile-cache nil
11189 "Cache for refile targets.")
11191 (defvar org-refile-markers nil
11192 "All the markers used for caching refile locations.")
11194 (defun org-refile-marker (pos)
11195 "Get a new refile marker, but only if caching is in use."
11196 (if (not org-refile-use-cache)
11198 (let ((m (make-marker)))
11199 (move-marker m pos)
11200 (push m org-refile-markers)
11201 m)))
11203 (defun org-refile-cache-clear ()
11204 "Clear the refile cache and disable all the markers."
11205 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11206 (setq org-refile-markers nil)
11207 (setq org-refile-cache nil)
11208 (message "Refile cache has been cleared"))
11210 (defun org-refile-cache-check-set (set)
11211 "Check if all the markers in the cache still have live buffers."
11212 (let (marker)
11213 (catch 'exit
11214 (while (and set (setq marker (nth 3 (pop set))))
11215 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11216 (when (and marker (null (marker-buffer marker)))
11217 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11218 (sit-for 3)
11219 (throw 'exit nil)))
11220 t)))
11222 (defun org-refile-cache-put (set &rest identifiers)
11223 "Push the refile targets SET into the cache, under IDENTIFIERS."
11224 (let* ((key (sha1 (prin1-to-string identifiers)))
11225 (entry (assoc key org-refile-cache)))
11226 (if entry
11227 (setcdr entry set)
11228 (push (cons key set) org-refile-cache))))
11230 (defun org-refile-cache-get (&rest identifiers)
11231 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11232 (cond
11233 ((not org-refile-cache) nil)
11234 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11236 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11237 org-refile-cache))))
11238 (and set (org-refile-cache-check-set set) set)))))
11240 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11241 "Produce a table with refile targets."
11242 (let ((case-fold-search nil)
11243 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11244 (entries (or org-refile-targets '((nil . (:level . 1)))))
11245 targets tgs txt re files f desc descre fast-path-p level pos0)
11246 (message "Getting targets...")
11247 (with-current-buffer (or default-buffer (current-buffer))
11248 (while (setq entry (pop entries))
11249 (setq files (car entry) desc (cdr entry))
11250 (setq fast-path-p nil)
11251 (cond
11252 ((null files) (setq files (list (current-buffer))))
11253 ((eq files 'org-agenda-files)
11254 (setq files (org-agenda-files 'unrestricted)))
11255 ((and (symbolp files) (fboundp files))
11256 (setq files (funcall files)))
11257 ((and (symbolp files) (boundp files))
11258 (setq files (symbol-value files))))
11259 (if (stringp files) (setq files (list files)))
11260 (cond
11261 ((eq (car desc) :tag)
11262 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11263 ((eq (car desc) :todo)
11264 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11265 ((eq (car desc) :regexp)
11266 (setq descre (cdr desc)))
11267 ((eq (car desc) :level)
11268 (setq descre (concat "^\\*\\{" (number-to-string
11269 (if org-odd-levels-only
11270 (1- (* 2 (cdr desc)))
11271 (cdr desc)))
11272 "\\}[ \t]")))
11273 ((eq (car desc) :maxlevel)
11274 (setq fast-path-p t)
11275 (setq descre (concat "^\\*\\{1," (number-to-string
11276 (if org-odd-levels-only
11277 (1- (* 2 (cdr desc)))
11278 (cdr desc)))
11279 "\\}[ \t]")))
11280 (t (error "Bad refiling target description %s" desc)))
11281 (while (setq f (pop files))
11282 (with-current-buffer
11283 (if (bufferp f) f (org-get-agenda-file-buffer f))
11285 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11286 (progn
11287 (if (bufferp f) (setq f (buffer-file-name
11288 (buffer-base-buffer f))))
11289 (setq f (and f (expand-file-name f)))
11290 (if (eq org-refile-use-outline-path 'file)
11291 (push (list (file-name-nondirectory f) f nil nil) tgs))
11292 (save-excursion
11293 (save-restriction
11294 (widen)
11295 (goto-char (point-min))
11296 (while (re-search-forward descre nil t)
11297 (goto-char (setq pos0 (point-at-bol)))
11298 (catch 'next
11299 (when org-refile-target-verify-function
11300 (save-match-data
11301 (or (funcall org-refile-target-verify-function)
11302 (throw 'next t))))
11303 (when (and (looking-at org-complex-heading-regexp)
11304 (not (member (match-string 4) excluded-entries))
11305 (match-string 4))
11306 (setq level (org-reduced-level
11307 (- (match-end 1) (match-beginning 1)))
11308 txt (org-link-display-format (match-string 4))
11309 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11310 re (format org-complex-heading-regexp-format
11311 (regexp-quote (match-string 4))))
11312 (when org-refile-use-outline-path
11313 (setq txt (mapconcat
11314 'org-protect-slash
11315 (append
11316 (if (eq org-refile-use-outline-path
11317 'file)
11318 (list (file-name-nondirectory
11319 (buffer-file-name
11320 (buffer-base-buffer))))
11321 (if (eq org-refile-use-outline-path
11322 'full-file-path)
11323 (list (buffer-file-name
11324 (buffer-base-buffer)))))
11325 (org-get-outline-path fast-path-p
11326 level txt)
11327 (list txt))
11328 "/")))
11329 (push (list txt f re (org-refile-marker (point)))
11330 tgs)))
11331 (when (= (point) pos0)
11332 ;; verification function has not moved point
11333 (goto-char (point-at-eol))))))))
11334 (when org-refile-use-cache
11335 (org-refile-cache-put tgs (buffer-file-name) descre))
11336 (setq targets (append tgs targets))))))
11337 (message "Getting targets...done")
11338 (nreverse targets)))
11340 (defun org-protect-slash (s)
11341 (while (string-match "/" s)
11342 (setq s (replace-match "\\" t t s)))
11345 (defvar org-olpa (make-vector 20 nil))
11347 (defun org-get-outline-path (&optional fastp level heading)
11348 "Return the outline path to the current entry, as a list.
11350 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11351 routine which makes outline path derivations for an entire file,
11352 avoiding backtracing. Refile target collection makes use of that."
11353 (if fastp
11354 (progn
11355 (if (> level 19)
11356 (error "Outline path failure, more than 19 levels"))
11357 (loop for i from level upto 19 do
11358 (aset org-olpa i nil))
11359 (prog1
11360 (delq nil (append org-olpa nil))
11361 (aset org-olpa level heading)))
11362 (let (rtn case-fold-search)
11363 (save-excursion
11364 (save-restriction
11365 (widen)
11366 (while (org-up-heading-safe)
11367 (when (looking-at org-complex-heading-regexp)
11368 (push (org-trim
11369 (replace-regexp-in-string
11370 ;; Remove statistical/checkboxes cookies
11371 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11372 (org-match-string-no-properties 4)))
11373 rtn)))
11374 rtn)))))
11376 (defun org-format-outline-path (path &optional width prefix separator)
11377 "Format the outline path PATH for display.
11378 WIDTH is the maximum number of characters that is available.
11379 PREFIX is a prefix to be included in the returned string,
11380 such as the file name.
11381 SEPARATOR is inserted between the different parts of the path,
11382 the default is \"/\"."
11383 (setq width (or width 79))
11384 (if prefix (setq width (- width (length prefix))))
11385 (if (not path)
11386 (or prefix "")
11387 (let* ((nsteps (length path))
11388 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11389 (maxwidth (if (<= total-width width)
11390 10000 ;; everything fits
11391 ;; we need to shorten the level headings
11392 (/ (- width nsteps) nsteps)))
11393 (org-odd-levels-only nil)
11394 (n 0)
11395 (total (1+ (length prefix))))
11396 (setq maxwidth (max maxwidth 10))
11397 (concat prefix
11398 (if prefix (or separator "/"))
11399 (mapconcat
11400 (lambda (h)
11401 (setq n (1+ n))
11402 (if (and (= n nsteps) (< maxwidth 10000))
11403 (setq maxwidth (- total-width total)))
11404 (if (< (length h) maxwidth)
11405 (progn (setq total (+ total (length h) 1)) h)
11406 (setq h (substring h 0 (- maxwidth 2))
11407 total (+ total maxwidth 1))
11408 (if (string-match "[ \t]+\\'" h)
11409 (setq h (substring h 0 (match-beginning 0))))
11410 (setq h (concat h "..")))
11411 (org-add-props h nil 'face
11412 (nth (% (1- n) org-n-level-faces)
11413 org-level-faces))
11415 path (or separator "/"))))))
11417 (defun org-display-outline-path (&optional file current separator just-return-string)
11418 "Display the current outline path in the echo area.
11420 If FILE is non-nil, prepend the output with the file name.
11421 If CURRENT is non-nil, append the current heading to the output.
11422 SEPARATOR is passed through to `org-format-outline-path'. It separates
11423 the different parts of the path and defaults to \"/\".
11424 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11425 (interactive "P")
11426 (let* (case-fold-search
11427 (bfn (buffer-file-name (buffer-base-buffer)))
11428 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11429 res)
11430 (if current (setq path (append path
11431 (save-excursion
11432 (org-back-to-heading t)
11433 (if (looking-at org-complex-heading-regexp)
11434 (list (match-string 4)))))))
11435 (setq res
11436 (org-format-outline-path
11437 path
11438 (1- (frame-width))
11439 (and file bfn (concat (file-name-nondirectory bfn) separator))
11440 separator))
11441 (if just-return-string
11442 (org-no-properties res)
11443 (org-unlogged-message "%s" res))))
11445 (defvar org-refile-history nil
11446 "History for refiling operations.")
11448 (defvar org-after-refile-insert-hook nil
11449 "Hook run after `org-refile' has inserted its stuff at the new location.
11450 Note that this is still *before* the stuff will be removed from
11451 the *old* location.")
11453 (defvar org-capture-last-stored-marker)
11454 (defvar org-refile-keep nil
11455 "Non-nil means `org-refile' will copy instead of refile.")
11457 (defun org-copy ()
11458 "Like `org-refile', but copy."
11459 (interactive)
11460 (let ((org-refile-keep t))
11461 (funcall 'org-refile nil nil nil "Copy")))
11463 (defun org-refile (&optional goto default-buffer rfloc msg)
11464 "Move the entry or entries at point to another heading.
11465 The list of target headings is compiled using the information in
11466 `org-refile-targets', which see.
11468 At the target location, the entry is filed as a subitem of the target
11469 heading. Depending on `org-reverse-note-order', the new subitem will
11470 either be the first or the last subitem.
11472 If there is an active region, all entries in that region will be moved.
11473 However, the region must fulfill the requirement that the first heading
11474 is the first one sets the top-level of the moved text - at most siblings
11475 below it are allowed.
11477 With prefix arg GOTO, the command will only visit the target location
11478 and not actually move anything.
11480 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11481 go to the location where the last refiling operation has put the subtree.
11483 With a numeric prefix argument of `2', refile to the running clock.
11485 With a numeric prefix argument of `3', emulate `org-refile-keep'
11486 being set to `t' and copy to the target location, don't move it.
11487 Beware that keeping refiled entries may result in duplicated ID
11488 properties.
11490 RFLOC can be a refile location obtained in a different way.
11492 MSG is a string to replace \"Refile\" in the default prompt with
11493 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11495 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11497 If you are using target caching (see `org-refile-use-cache'),
11498 you have to clear the target cache in order to find new targets.
11499 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11500 prefix argument (`C-u C-u C-u C-c C-w')."
11502 (interactive "P")
11503 (if (member goto '(0 (64)))
11504 (org-refile-cache-clear)
11505 (let* ((actionmsg (or msg "Refile"))
11506 (cbuf (current-buffer))
11507 (regionp (org-region-active-p))
11508 (region-start (and regionp (region-beginning)))
11509 (region-end (and regionp (region-end)))
11510 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11511 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11512 pos it nbuf file re level reversed)
11513 (setq last-command nil)
11514 (when regionp
11515 (goto-char region-start)
11516 (or (bolp) (goto-char (point-at-bol)))
11517 (setq region-start (point))
11518 (unless (or (org-kill-is-subtree-p
11519 (buffer-substring region-start region-end))
11520 (prog1 org-refile-active-region-within-subtree
11521 (let ((s (point-at-eol)))
11522 (org-toggle-heading)
11523 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11524 (user-error "The region is not a (sequence of) subtree(s)")))
11525 (if (equal goto '(16))
11526 (org-refile-goto-last-stored)
11527 (when (or
11528 (and (equal goto 2)
11529 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11530 (prog1
11531 (setq it (list (or org-clock-heading "running clock")
11532 (buffer-file-name
11533 (marker-buffer org-clock-hd-marker))
11535 (marker-position org-clock-hd-marker)))
11536 (setq goto nil)))
11537 (setq it (or rfloc
11538 (let (heading-text)
11539 (save-excursion
11540 (unless goto
11541 (org-back-to-heading t)
11542 (setq heading-text
11543 (nth 4 (org-heading-components))))
11545 (org-refile-get-location
11546 (cond (goto "Goto")
11547 (regionp (concat actionmsg " region to"))
11548 (t (concat actionmsg " subtree \""
11549 heading-text "\" to")))
11550 default-buffer
11551 (and (not (equal '(4) goto))
11552 org-refile-allow-creating-parent-nodes)
11553 goto))))))
11554 (setq file (nth 1 it)
11555 re (nth 2 it)
11556 pos (nth 3 it))
11557 (if (and (not goto)
11559 (equal (buffer-file-name) file)
11560 (if regionp
11561 (and (>= pos region-start)
11562 (<= pos region-end))
11563 (and (>= pos (point))
11564 (< pos (save-excursion
11565 (org-end-of-subtree t t))))))
11566 (error "Cannot refile to position inside the tree or region"))
11568 (setq nbuf (or (find-buffer-visiting file)
11569 (find-file-noselect file)))
11570 (if (and goto (not (equal goto 3)))
11571 (progn
11572 (org-pop-to-buffer-same-window nbuf)
11573 (goto-char pos)
11574 (org-show-context 'org-goto))
11575 (if regionp
11576 (progn
11577 (org-kill-new (buffer-substring region-start region-end))
11578 (org-save-markers-in-region region-start region-end))
11579 (org-copy-subtree 1 nil t))
11580 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11581 (find-file-noselect file)))
11582 (setq reversed (org-notes-order-reversed-p))
11583 (save-excursion
11584 (save-restriction
11585 (widen)
11586 (if pos
11587 (progn
11588 (goto-char pos)
11589 (looking-at org-outline-regexp)
11590 (setq level (org-get-valid-level (funcall outline-level) 1))
11591 (goto-char
11592 (if reversed
11593 (or (outline-next-heading) (point-max))
11594 (or (save-excursion (org-get-next-sibling))
11595 (org-end-of-subtree t t)
11596 (point-max)))))
11597 (setq level 1)
11598 (if (not reversed)
11599 (goto-char (point-max))
11600 (goto-char (point-min))
11601 (or (outline-next-heading) (goto-char (point-max)))))
11602 (if (not (bolp)) (newline))
11603 (org-paste-subtree level)
11604 (when org-log-refile
11605 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11606 (unless (eq org-log-refile 'note)
11607 (save-excursion (org-add-log-note))))
11608 (and org-auto-align-tags
11609 (let ((org-loop-over-headlines-in-active-region nil))
11610 (org-set-tags nil t)))
11611 (let ((bookmark-name (plist-get org-bookmark-names-plist
11612 :last-refile)))
11613 (when bookmark-name
11614 (with-demoted-errors
11615 (bookmark-set bookmark-name))))
11616 ;; If we are refiling for capture, make sure that the
11617 ;; last-capture pointers point here
11618 (when (org-bound-and-true-p org-refile-for-capture)
11619 (let ((bookmark-name (plist-get org-bookmark-names-plist
11620 :last-capture-marker)))
11621 (when bookmark-name
11622 (with-demoted-errors
11623 (bookmark-set bookmark-name))))
11624 (move-marker org-capture-last-stored-marker (point)))
11625 (if (fboundp 'deactivate-mark) (deactivate-mark))
11626 (run-hooks 'org-after-refile-insert-hook))))
11627 (unless org-refile-keep
11628 (if regionp
11629 (delete-region (point) (+ (point) (- region-end region-start)))
11630 (delete-region
11631 (and (org-back-to-heading t) (point))
11632 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11633 (when (featurep 'org-inlinetask)
11634 (org-inlinetask-remove-END-maybe))
11635 (setq org-markers-to-move nil)
11636 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11638 (defun org-refile-goto-last-stored ()
11639 "Go to the location where the last refile was stored."
11640 (interactive)
11641 (bookmark-jump "org-refile-last-stored")
11642 (message "This is the location of the last refile"))
11644 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11645 no-exclude)
11646 "Prompt the user for a refile location, using PROMPT.
11647 PROMPT should not be suffixed with a colon and a space, because
11648 this function appends the default value from
11649 `org-refile-history' automatically, if that is not empty.
11650 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11651 this is used for the GOTO interface."
11652 (let ((org-refile-targets org-refile-targets)
11653 (org-refile-use-outline-path org-refile-use-outline-path)
11654 excluded-entries)
11655 (when (and (derived-mode-p 'org-mode)
11656 (not org-refile-use-cache)
11657 (not no-exclude))
11658 (org-map-tree
11659 (lambda()
11660 (setq excluded-entries
11661 (append excluded-entries (list (org-get-heading t t)))))))
11662 (setq org-refile-target-table
11663 (org-refile-get-targets default-buffer excluded-entries)))
11664 (unless org-refile-target-table
11665 (user-error "No refile targets"))
11666 (let* ((cbuf (current-buffer))
11667 (partial-completion-mode nil)
11668 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11669 (cfunc (if (and org-refile-use-outline-path
11670 org-outline-path-complete-in-steps)
11671 'org-olpath-completing-read
11672 'org-icompleting-read))
11673 (extra (if org-refile-use-outline-path "/" ""))
11674 (cbnex (concat (buffer-name) extra))
11675 (filename (and cfn (expand-file-name cfn)))
11676 (tbl (mapcar
11677 (lambda (x)
11678 (if (and (not (member org-refile-use-outline-path
11679 '(file full-file-path)))
11680 (not (equal filename (nth 1 x))))
11681 (cons (concat (car x) extra " ("
11682 (file-name-nondirectory (nth 1 x)) ")")
11683 (cdr x))
11684 (cons (concat (car x) extra) (cdr x))))
11685 org-refile-target-table))
11686 (completion-ignore-case t)
11687 cdef
11688 (prompt (concat prompt
11689 (or (and (car org-refile-history)
11690 (concat " (default " (car org-refile-history) ")"))
11691 (and (assoc cbnex tbl) (setq cdef cbnex)
11692 (concat " (default " cbnex ")"))) ": "))
11693 pa answ parent-target child parent old-hist)
11694 (setq old-hist org-refile-history)
11695 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11696 nil 'org-refile-history (or cdef (car org-refile-history))))
11697 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11698 (if pa
11699 (progn
11700 (org-refile-check-position pa)
11701 (when (or (not org-refile-history)
11702 (not (eq old-hist org-refile-history))
11703 (not (equal (car pa) (car org-refile-history))))
11704 (setq org-refile-history
11705 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11706 org-refile-history
11707 (cdr org-refile-history))))
11708 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11709 (pop org-refile-history)))
11711 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11712 (progn
11713 (setq parent (match-string 1 answ)
11714 child (match-string 2 answ))
11715 (setq parent-target (or (assoc parent tbl)
11716 (assoc (concat parent "/") tbl)))
11717 (when (and parent-target
11718 (or (eq new-nodes t)
11719 (and (eq new-nodes 'confirm)
11720 (y-or-n-p (format "Create new node \"%s\"? "
11721 child)))))
11722 (org-refile-new-child parent-target child)))
11723 (user-error "Invalid target location")))))
11725 (declare-function org-string-nw-p "org-macs" (s))
11726 (defun org-refile-check-position (refile-pointer)
11727 "Check if the refile pointer matches the headline to which it points."
11728 (let* ((file (nth 1 refile-pointer))
11729 (re (nth 2 refile-pointer))
11730 (pos (nth 3 refile-pointer))
11731 buffer)
11732 (if (and (not (markerp pos)) (not file))
11733 (user-error "Please save the buffer to a file before refiling")
11734 (when (org-string-nw-p re)
11735 (setq buffer (if (markerp pos)
11736 (marker-buffer pos)
11737 (or (find-buffer-visiting file)
11738 (find-file-noselect file))))
11739 (with-current-buffer buffer
11740 (save-excursion
11741 (save-restriction
11742 (widen)
11743 (goto-char pos)
11744 (beginning-of-line 1)
11745 (unless (org-looking-at-p re)
11746 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11748 (defun org-refile-new-child (parent-target child)
11749 "Use refile target PARENT-TARGET to add new CHILD below it."
11750 (unless parent-target
11751 (error "Cannot find parent for new node"))
11752 (let ((file (nth 1 parent-target))
11753 (pos (nth 3 parent-target))
11754 level)
11755 (with-current-buffer (or (find-buffer-visiting file)
11756 (find-file-noselect file))
11757 (save-excursion
11758 (save-restriction
11759 (widen)
11760 (if pos
11761 (goto-char pos)
11762 (goto-char (point-max))
11763 (if (not (bolp)) (newline)))
11764 (when (looking-at org-outline-regexp)
11765 (setq level (funcall outline-level))
11766 (org-end-of-subtree t t))
11767 (org-back-over-empty-lines)
11768 (insert "\n" (make-string
11769 (if pos (org-get-valid-level level 1) 1) ?*)
11770 " " child "\n")
11771 (beginning-of-line 0)
11772 (list (concat (car parent-target) "/" child) file "" (point)))))))
11774 (defun org-olpath-completing-read (prompt collection &rest args)
11775 "Read an outline path like a file name."
11776 (let ((thetable collection)
11777 (org-completion-use-ido nil) ; does not work with ido.
11778 (org-completion-use-iswitchb nil)) ; or iswitchb
11779 (apply
11780 'org-icompleting-read prompt
11781 (lambda (string predicate &optional flag)
11782 (let (rtn r f (l (length string)))
11783 (cond
11784 ((eq flag nil)
11785 ;; try completion
11786 (try-completion string thetable))
11787 ((eq flag t)
11788 ;; all-completions
11789 (setq rtn (all-completions string thetable predicate))
11790 (mapcar
11791 (lambda (x)
11792 (setq r (substring x l))
11793 (if (string-match " ([^)]*)$" x)
11794 (setq f (match-string 0 x))
11795 (setq f ""))
11796 (if (string-match "/" r)
11797 (concat string (substring r 0 (match-end 0)) f)
11799 rtn))
11800 ((eq flag 'lambda)
11801 ;; exact match?
11802 (assoc string thetable)))))
11803 args)))
11805 ;;;; Dynamic blocks
11807 (defun org-find-dblock (name)
11808 "Find the first dynamic block with name NAME in the buffer.
11809 If not found, stay at current position and return nil."
11810 (let ((case-fold-search t) pos)
11811 (save-excursion
11812 (goto-char (point-min))
11813 (setq pos (and (re-search-forward
11814 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11815 (match-beginning 0))))
11816 (if pos (goto-char pos))
11817 pos))
11819 (defconst org-dblock-start-re
11820 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11821 "Matches the start line of a dynamic block, with parameters.")
11823 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11824 "Matches the end of a dynamic block.")
11826 (defun org-create-dblock (plist)
11827 "Create a dynamic block section, with parameters taken from PLIST.
11828 PLIST must contain a :name entry which is used as name of the block."
11829 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11830 (end-of-line 1)
11831 (newline))
11832 (let ((col (current-column))
11833 (name (plist-get plist :name)))
11834 (insert "#+BEGIN: " name)
11835 (while plist
11836 (if (eq (car plist) :name)
11837 (setq plist (cddr plist))
11838 (insert " " (prin1-to-string (pop plist)))))
11839 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11840 (beginning-of-line -2)))
11842 (defun org-prepare-dblock ()
11843 "Prepare dynamic block for refresh.
11844 This empties the block, puts the cursor at the insert position and returns
11845 the property list including an extra property :name with the block name."
11846 (unless (looking-at org-dblock-start-re)
11847 (user-error "Not at a dynamic block"))
11848 (let* ((begdel (1+ (match-end 0)))
11849 (name (org-no-properties (match-string 1)))
11850 (params (append (list :name name)
11851 (read (concat "(" (match-string 3) ")")))))
11852 (save-excursion
11853 (beginning-of-line 1)
11854 (skip-chars-forward " \t")
11855 (setq params (plist-put params :indentation-column (current-column))))
11856 (unless (re-search-forward org-dblock-end-re nil t)
11857 (error "Dynamic block not terminated"))
11858 (setq params
11859 (append params
11860 (list :content (buffer-substring
11861 begdel (match-beginning 0)))))
11862 (delete-region begdel (match-beginning 0))
11863 (goto-char begdel)
11864 (open-line 1)
11865 params))
11867 (defun org-map-dblocks (&optional command)
11868 "Apply COMMAND to all dynamic blocks in the current buffer.
11869 If COMMAND is not given, use `org-update-dblock'."
11870 (let ((cmd (or command 'org-update-dblock)))
11871 (save-excursion
11872 (goto-char (point-min))
11873 (while (re-search-forward org-dblock-start-re nil t)
11874 (goto-char (match-beginning 0))
11875 (save-excursion
11876 (condition-case nil
11877 (funcall cmd)
11878 (error (message "Error during update of dynamic block"))))
11879 (unless (re-search-forward org-dblock-end-re nil t)
11880 (error "Dynamic block not terminated"))))))
11882 (defun org-dblock-update (&optional arg)
11883 "User command for updating dynamic blocks.
11884 Update the dynamic block at point. With prefix ARG, update all dynamic
11885 blocks in the buffer."
11886 (interactive "P")
11887 (if arg
11888 (org-update-all-dblocks)
11889 (or (looking-at org-dblock-start-re)
11890 (org-beginning-of-dblock))
11891 (org-update-dblock)))
11893 (defun org-update-dblock ()
11894 "Update the dynamic block at point.
11895 This means to empty the block, parse for parameters and then call
11896 the correct writing function."
11897 (interactive)
11898 (save-window-excursion
11899 (let* ((pos (point))
11900 (line (org-current-line))
11901 (params (org-prepare-dblock))
11902 (name (plist-get params :name))
11903 (indent (plist-get params :indentation-column))
11904 (cmd (intern (concat "org-dblock-write:" name))))
11905 (message "Updating dynamic block `%s' at line %d..." name line)
11906 (funcall cmd params)
11907 (message "Updating dynamic block `%s' at line %d...done" name line)
11908 (goto-char pos)
11909 (when (and indent (> indent 0))
11910 (setq indent (make-string indent ?\ ))
11911 (save-excursion
11912 (org-beginning-of-dblock)
11913 (forward-line 1)
11914 (while (not (looking-at org-dblock-end-re))
11915 (insert indent)
11916 (beginning-of-line 2))
11917 (when (looking-at org-dblock-end-re)
11918 (and (looking-at "[ \t]+")
11919 (replace-match ""))
11920 (insert indent)))))))
11922 (defun org-beginning-of-dblock ()
11923 "Find the beginning of the dynamic block at point.
11924 Error if there is no such block at point."
11925 (let ((pos (point))
11926 beg)
11927 (end-of-line 1)
11928 (if (and (re-search-backward org-dblock-start-re nil t)
11929 (setq beg (match-beginning 0))
11930 (re-search-forward org-dblock-end-re nil t)
11931 (> (match-end 0) pos))
11932 (goto-char beg)
11933 (goto-char pos)
11934 (error "Not in a dynamic block"))))
11936 (defun org-update-all-dblocks ()
11937 "Update all dynamic blocks in the buffer.
11938 This function can be used in a hook."
11939 (interactive)
11940 (when (derived-mode-p 'org-mode)
11941 (org-map-dblocks 'org-update-dblock)))
11944 ;;;; Completion
11946 (declare-function org-export-backend-name "org-export" (cl-x))
11947 (declare-function org-export-backend-options "org-export" (cl-x))
11948 (defun org-get-export-keywords ()
11949 "Return a list of all currently understood export keywords.
11950 Export keywords include options, block names, attributes and
11951 keywords relative to each registered export back-end."
11952 (let (keywords)
11953 (dolist (backend
11954 (org-bound-and-true-p org-export--registered-backends)
11955 (delq nil keywords))
11956 ;; Back-end name (for keywords, like #+LATEX:)
11957 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11958 (dolist (option-entry (org-export-backend-options backend))
11959 ;; Back-end options.
11960 (push (nth 1 option-entry) keywords)))))
11962 (defconst org-options-keywords
11963 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11964 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11965 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11966 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11967 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11969 (defcustom org-structure-template-alist
11970 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11971 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11972 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11973 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11974 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11975 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11976 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11977 "<literal style=\"latex\">\n?\n</literal>")
11978 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11979 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11980 "<literal style=\"html\">\n?\n</literal>")
11981 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11982 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11983 ("A" "#+ASCII: " "")
11984 ("i" "#+INDEX: ?" "#+INDEX: ?")
11985 ("I" "#+INCLUDE: %file ?"
11986 "<include file=%file markup=\"?\">"))
11987 "Structure completion elements.
11988 This is a list of abbreviation keys and values. The value gets inserted
11989 if you type `<' followed by the key and then press the completion key,
11990 usually `M-TAB'. %file will be replaced by a file name after prompting
11991 for the file using completion. The cursor will be placed at the position
11992 of the `?` in the template.
11993 There are two templates for each key, the first uses the original Org syntax,
11994 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11995 the default when the /org-mtags.el/ module has been loaded. See also the
11996 variable `org-mtags-prefer-muse-templates'."
11997 :group 'org-completion
11998 :type '(repeat
11999 (list
12000 (string :tag "Key")
12001 (string :tag "Template")
12002 (string :tag "Muse Template"))))
12004 (defun org-try-structure-completion ()
12005 "Try to complete a structure template before point.
12006 This looks for strings like \"<e\" on an otherwise empty line and
12007 expands them."
12008 (let ((l (buffer-substring (point-at-bol) (point)))
12010 (when (and (looking-at "[ \t]*$")
12011 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12012 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12013 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12014 (match-beginning 1)) a)
12015 t)))
12017 (defun org-complete-expand-structure-template (start cell)
12018 "Expand a structure template."
12019 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12020 (rpl (nth (if musep 2 1) cell))
12021 (ind ""))
12022 (delete-region start (point))
12023 (when (string-match "\\`#\\+" rpl)
12024 (cond
12025 ((bolp))
12026 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12027 (setq ind (buffer-substring (point-at-bol) (point))))
12028 (t (newline))))
12029 (setq start (point))
12030 (if (string-match "%file" rpl)
12031 (setq rpl (replace-match
12032 (concat
12033 "\""
12034 (save-match-data
12035 (abbreviate-file-name (read-file-name "Include file: ")))
12036 "\"")
12037 t t rpl)))
12038 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12039 (concat "\n" ind)))
12040 (insert rpl)
12041 (if (re-search-backward "\\?" start t) (delete-char 1))))
12043 ;;;; TODO, DEADLINE, Comments
12045 (defun org-toggle-comment ()
12046 "Change the COMMENT state of an entry."
12047 (interactive)
12048 (save-excursion
12049 (org-back-to-heading)
12050 (let (case-fold-search)
12051 (cond
12052 ((looking-at (format org-heading-keyword-regexp-format
12053 org-comment-string))
12054 (goto-char (match-end 1))
12055 (looking-at (concat " +" org-comment-string))
12056 (replace-match "" t t)
12057 (when (eolp) (insert " ")))
12058 ((looking-at org-outline-regexp)
12059 (goto-char (match-end 0))
12060 (insert org-comment-string " "))))))
12062 (defvar org-last-todo-state-is-todo nil
12063 "This is non-nil when the last TODO state change led to a TODO state.
12064 If the last change removed the TODO tag or switched to DONE, then
12065 this is nil.")
12067 (defvar org-setting-tags nil) ; dynamically skipped
12069 (defvar org-todo-setup-filter-hook nil
12070 "Hook for functions that pre-filter todo specs.
12071 Each function takes a todo spec and returns either nil or the spec
12072 transformed into canonical form." )
12074 (defvar org-todo-get-default-hook nil
12075 "Hook for functions that get a default item for todo.
12076 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12077 nil or a string to be used for the todo mark." )
12079 (defvar org-agenda-headline-snapshot-before-repeat)
12081 (defun org-current-effective-time ()
12082 "Return current time adjusted for `org-extend-today-until' variable."
12083 (let* ((ct (org-current-time))
12084 (dct (decode-time ct))
12085 (ct1
12086 (cond
12087 (org-use-last-clock-out-time-as-effective-time
12088 (or (org-clock-get-last-clock-out-time) ct))
12089 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12090 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12091 (t ct))))
12092 ct1))
12094 (defun org-todo-yesterday (&optional arg)
12095 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12096 (interactive "P")
12097 (if (eq major-mode 'org-agenda-mode)
12098 (apply 'org-agenda-todo-yesterday arg)
12099 (let* ((hour (third (decode-time
12100 (org-current-time))))
12101 (org-extend-today-until (1+ hour)))
12102 (org-todo arg))))
12104 (defvar org-block-entry-blocking ""
12105 "First entry preventing the TODO state change.")
12107 (defun org-todo (&optional arg)
12108 "Change the TODO state of an item.
12109 The state of an item is given by a keyword at the start of the heading,
12110 like
12111 *** TODO Write paper
12112 *** DONE Call mom
12114 The different keywords are specified in the variable `org-todo-keywords'.
12115 By default the available states are \"TODO\" and \"DONE\".
12116 So for this example: when the item starts with TODO, it is changed to DONE.
12117 When it starts with DONE, the DONE is removed. And when neither TODO nor
12118 DONE are present, add TODO at the beginning of the heading.
12120 With \\[universal-argument] prefix arg, use completion to determine the new \
12121 state.
12122 With numeric prefix arg, switch to that state.
12123 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12124 keywords (nextset).
12125 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12126 With a numeric prefix arg of 0, inhibit note taking for the change.
12128 For calling through lisp, arg is also interpreted in the following way:
12129 'none -> empty state
12130 \"\"(empty string) -> switch to empty state
12131 'done -> switch to DONE
12132 'nextset -> switch to the next set of keywords
12133 'previousset -> switch to the previous set of keywords
12134 \"WAITING\" -> switch to the specified keyword, but only if it
12135 really is a member of `org-todo-keywords'."
12136 (interactive "P")
12137 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12138 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12139 'region-start-level 'region))
12140 org-loop-over-headlines-in-active-region)
12141 (org-map-entries
12142 `(org-todo ,arg)
12143 org-loop-over-headlines-in-active-region
12144 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12145 (if (equal arg '(16)) (setq arg 'nextset))
12146 (let ((org-blocker-hook org-blocker-hook)
12147 commentp
12148 case-fold-search)
12149 (when (equal arg '(64))
12150 (setq arg nil org-blocker-hook nil))
12151 (when (and org-blocker-hook
12152 (or org-inhibit-blocking
12153 (org-entry-get nil "NOBLOCKING")))
12154 (setq org-blocker-hook nil))
12155 (save-excursion
12156 (catch 'exit
12157 (org-back-to-heading t)
12158 (when (looking-at (concat "^\\*+ " org-comment-string))
12159 (org-toggle-comment)
12160 (setq commentp t))
12161 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12162 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12163 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12164 (let* ((match-data (match-data))
12165 (startpos (point-at-bol))
12166 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12167 (org-log-done org-log-done)
12168 (org-log-repeat org-log-repeat)
12169 (org-todo-log-states org-todo-log-states)
12170 (org-inhibit-logging
12171 (if (equal arg 0)
12172 (progn (setq arg nil) 'note) org-inhibit-logging))
12173 (this (match-string 1))
12174 (hl-pos (match-beginning 0))
12175 (head (org-get-todo-sequence-head this))
12176 (ass (assoc head org-todo-kwd-alist))
12177 (interpret (nth 1 ass))
12178 (done-word (nth 3 ass))
12179 (final-done-word (nth 4 ass))
12180 (org-last-state (or this ""))
12181 (completion-ignore-case t)
12182 (member (member this org-todo-keywords-1))
12183 (tail (cdr member))
12184 (org-state (cond
12185 ((and org-todo-key-trigger
12186 (or (and (equal arg '(4))
12187 (eq org-use-fast-todo-selection 'prefix))
12188 (and (not arg) org-use-fast-todo-selection
12189 (not (eq org-use-fast-todo-selection
12190 'prefix)))))
12191 ;; Use fast selection
12192 (org-fast-todo-selection))
12193 ((and (equal arg '(4))
12194 (or (not org-use-fast-todo-selection)
12195 (not org-todo-key-trigger)))
12196 ;; Read a state with completion
12197 (org-icompleting-read
12198 "State: " (mapcar 'list org-todo-keywords-1)
12199 nil t))
12200 ((eq arg 'right)
12201 (if this
12202 (if tail (car tail) nil)
12203 (car org-todo-keywords-1)))
12204 ((eq arg 'left)
12205 (if (equal member org-todo-keywords-1)
12207 (if this
12208 (nth (- (length org-todo-keywords-1)
12209 (length tail) 2)
12210 org-todo-keywords-1)
12211 (org-last org-todo-keywords-1))))
12212 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12213 (setq arg nil))) ; hack to fall back to cycling
12214 (arg
12215 ;; user or caller requests a specific state
12216 (cond
12217 ((equal arg "") nil)
12218 ((eq arg 'none) nil)
12219 ((eq arg 'done) (or done-word (car org-done-keywords)))
12220 ((eq arg 'nextset)
12221 (or (car (cdr (member head org-todo-heads)))
12222 (car org-todo-heads)))
12223 ((eq arg 'previousset)
12224 (let ((org-todo-heads (reverse org-todo-heads)))
12225 (or (car (cdr (member head org-todo-heads)))
12226 (car org-todo-heads))))
12227 ((car (member arg org-todo-keywords-1)))
12228 ((stringp arg)
12229 (user-error "State `%s' not valid in this file" arg))
12230 ((nth (1- (prefix-numeric-value arg))
12231 org-todo-keywords-1))))
12232 ((null member) (or head (car org-todo-keywords-1)))
12233 ((equal this final-done-word) nil) ;; -> make empty
12234 ((null tail) nil) ;; -> first entry
12235 ((memq interpret '(type priority))
12236 (if (eq this-command last-command)
12237 (car tail)
12238 (if (> (length tail) 0)
12239 (or done-word (car org-done-keywords))
12240 nil)))
12242 (car tail))))
12243 (org-state (or
12244 (run-hook-with-args-until-success
12245 'org-todo-get-default-hook org-state org-last-state)
12246 org-state))
12247 (next (if org-state (concat " " org-state " ") " "))
12248 (change-plist (list :type 'todo-state-change :from this :to org-state
12249 :position startpos))
12250 dolog now-done-p)
12251 (when org-blocker-hook
12252 (setq org-last-todo-state-is-todo
12253 (not (member this org-done-keywords)))
12254 (unless (save-excursion
12255 (save-match-data
12256 (org-with-wide-buffer
12257 (run-hook-with-args-until-failure
12258 'org-blocker-hook change-plist))))
12259 (if (org-called-interactively-p 'interactive)
12260 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12261 this org-state org-block-entry-blocking)
12262 ;; fail silently
12263 (message "TODO state change from %s to %s blocked (by \"%s\")"
12264 this org-state org-block-entry-blocking)
12265 (throw 'exit nil))))
12266 (store-match-data match-data)
12267 (replace-match next t t)
12268 (unless (pos-visible-in-window-p hl-pos)
12269 (message "TODO state changed to %s" (org-trim next)))
12270 (unless head
12271 (setq head (org-get-todo-sequence-head org-state)
12272 ass (assoc head org-todo-kwd-alist)
12273 interpret (nth 1 ass)
12274 done-word (nth 3 ass)
12275 final-done-word (nth 4 ass)))
12276 (when (memq arg '(nextset previousset))
12277 (message "Keyword-Set %d/%d: %s"
12278 (- (length org-todo-sets) -1
12279 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12280 (length org-todo-sets)
12281 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12282 (setq org-last-todo-state-is-todo
12283 (not (member org-state org-done-keywords)))
12284 (setq now-done-p (and (member org-state org-done-keywords)
12285 (not (member this org-done-keywords))))
12286 (and logging (org-local-logging logging))
12287 (when (and (or org-todo-log-states org-log-done)
12288 (not (eq org-inhibit-logging t))
12289 (not (memq arg '(nextset previousset))))
12290 ;; we need to look at recording a time and note
12291 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12292 (nth 2 (assoc this org-todo-log-states))))
12293 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12294 (setq dolog 'time))
12295 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12296 (and org-state
12297 (member org-state org-not-done-keywords)
12298 (not (member this org-not-done-keywords))))
12299 ;; This is now a todo state and was not one before
12300 ;; If there was a CLOSED time stamp, get rid of it.
12301 (org-add-planning-info nil nil 'closed))
12302 (when (and now-done-p org-log-done)
12303 ;; It is now done, and it was not done before
12304 (org-add-planning-info 'closed (org-current-effective-time))
12305 (if (and (not dolog) (eq 'note org-log-done))
12306 (org-add-log-setup 'done org-state this 'findpos 'note)))
12307 (when (and org-state dolog)
12308 ;; This is a non-nil state, and we need to log it
12309 (org-add-log-setup 'state org-state this 'findpos dolog)))
12310 ;; Fixup tag positioning
12311 (org-todo-trigger-tag-changes org-state)
12312 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12313 (when org-provide-todo-statistics
12314 (org-update-parent-todo-statistics))
12315 (run-hooks 'org-after-todo-state-change-hook)
12316 (if (and arg (not (member org-state org-done-keywords)))
12317 (setq head (org-get-todo-sequence-head org-state)))
12318 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12319 ;; Do we need to trigger a repeat?
12320 (when now-done-p
12321 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12322 ;; This is for the agenda, take a snapshot of the headline.
12323 (save-match-data
12324 (setq org-agenda-headline-snapshot-before-repeat
12325 (org-get-heading))))
12326 (org-auto-repeat-maybe org-state))
12327 ;; Fixup cursor location if close to the keyword
12328 (if (and (outline-on-heading-p)
12329 (not (bolp))
12330 (save-excursion (beginning-of-line 1)
12331 (looking-at org-todo-line-regexp))
12332 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12333 (progn
12334 (goto-char (or (match-end 2) (match-end 1)))
12335 (and (looking-at " ") (just-one-space))))
12336 (when org-trigger-hook
12337 (save-excursion
12338 (run-hook-with-args 'org-trigger-hook change-plist)))
12339 (when commentp (org-toggle-comment))))))))
12341 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12342 "Block turning an entry into a TODO, using the hierarchy.
12343 This checks whether the current task should be blocked from state
12344 changes. Such blocking occurs when:
12346 1. The task has children which are not all in a completed state.
12348 2. A task has a parent with the property :ORDERED:, and there
12349 are siblings prior to the current task with incomplete
12350 status.
12352 3. The parent of the task is blocked because it has siblings that should
12353 be done first, or is child of a block grandparent TODO entry."
12355 (if (not org-enforce-todo-dependencies)
12356 t ; if locally turned off don't block
12357 (catch 'dont-block
12358 ;; If this is not a todo state change, or if this entry is already DONE,
12359 ;; do not block
12360 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12361 (member (plist-get change-plist :from)
12362 (cons 'done org-done-keywords))
12363 (member (plist-get change-plist :to)
12364 (cons 'todo org-not-done-keywords))
12365 (not (plist-get change-plist :to)))
12366 (throw 'dont-block t))
12367 ;; If this task has children, and any are undone, it's blocked
12368 (save-excursion
12369 (org-back-to-heading t)
12370 (let ((this-level (funcall outline-level)))
12371 (outline-next-heading)
12372 (let ((child-level (funcall outline-level)))
12373 (while (and (not (eobp))
12374 (> child-level this-level))
12375 ;; this todo has children, check whether they are all
12376 ;; completed
12377 (if (and (not (org-entry-is-done-p))
12378 (org-entry-is-todo-p))
12379 (progn (setq org-block-entry-blocking (org-get-heading))
12380 (throw 'dont-block nil)))
12381 (outline-next-heading)
12382 (setq child-level (funcall outline-level))))))
12383 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12384 ;; any previous siblings are undone, it's blocked
12385 (save-excursion
12386 (org-back-to-heading t)
12387 (let* ((pos (point))
12388 (parent-pos (and (org-up-heading-safe) (point))))
12389 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12390 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12391 (forward-line 1)
12392 (re-search-forward org-not-done-heading-regexp pos t))
12393 (setq org-block-entry-blocking (match-string 0))
12394 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12395 ;; Search further up the hierarchy, to see if an ancestor is blocked
12396 (while t
12397 (goto-char parent-pos)
12398 (if (not (looking-at org-not-done-heading-regexp))
12399 (throw 'dont-block t)) ; do not block, parent is not a TODO
12400 (setq pos (point))
12401 (setq parent-pos (and (org-up-heading-safe) (point)))
12402 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12403 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12404 (forward-line 1)
12405 (re-search-forward org-not-done-heading-regexp pos t)
12406 (setq org-block-entry-blocking (org-get-heading)))
12407 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12409 (defcustom org-track-ordered-property-with-tag nil
12410 "Should the ORDERED property also be shown as a tag?
12411 The ORDERED property decides if an entry should require subtasks to be
12412 completed in sequence. Since a property is not very visible, setting
12413 this option means that toggling the ORDERED property with the command
12414 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12415 not relevant for the behavior, but it makes things more visible.
12417 Note that toggling the tag with tags commands will not change the property
12418 and therefore not influence behavior!
12420 This can be t, meaning the tag ORDERED should be used, It can also be a
12421 string to select a different tag for this task."
12422 :group 'org-todo
12423 :type '(choice
12424 (const :tag "No tracking" nil)
12425 (const :tag "Track with ORDERED tag" t)
12426 (string :tag "Use other tag")))
12428 (defun org-toggle-ordered-property ()
12429 "Toggle the ORDERED property of the current entry.
12430 For better visibility, you can track the value of this property with a tag.
12431 See variable `org-track-ordered-property-with-tag'."
12432 (interactive)
12433 (let* ((t1 org-track-ordered-property-with-tag)
12434 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12435 (save-excursion
12436 (org-back-to-heading)
12437 (if (org-entry-get nil "ORDERED")
12438 (progn
12439 (org-delete-property "ORDERED" "PROPERTIES")
12440 (and tag (org-toggle-tag tag 'off))
12441 (message "Subtasks can be completed in arbitrary order"))
12442 (org-entry-put nil "ORDERED" "t")
12443 (and tag (org-toggle-tag tag 'on))
12444 (message "Subtasks must be completed in sequence")))))
12446 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12447 (defun org-block-todo-from-checkboxes (change-plist)
12448 "Block turning an entry into a TODO, using checkboxes.
12449 This checks whether the current task should be blocked from state
12450 changes because there are unchecked boxes in this entry."
12451 (if (not org-enforce-todo-checkbox-dependencies)
12452 t ; if locally turned off don't block
12453 (catch 'dont-block
12454 ;; If this is not a todo state change, or if this entry is already DONE,
12455 ;; do not block
12456 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12457 (member (plist-get change-plist :from)
12458 (cons 'done org-done-keywords))
12459 (member (plist-get change-plist :to)
12460 (cons 'todo org-not-done-keywords))
12461 (not (plist-get change-plist :to)))
12462 (throw 'dont-block t))
12463 ;; If this task has checkboxes that are not checked, it's blocked
12464 (save-excursion
12465 (org-back-to-heading t)
12466 (let ((beg (point)) end)
12467 (outline-next-heading)
12468 (setq end (point))
12469 (goto-char beg)
12470 (if (org-list-search-forward
12471 (concat (org-item-beginning-re)
12472 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12473 "\\[[- ]\\]")
12474 end t)
12475 (progn
12476 (if (boundp 'org-blocked-by-checkboxes)
12477 (setq org-blocked-by-checkboxes t))
12478 (throw 'dont-block nil)))))
12479 t))) ; do not block
12481 (defun org-entry-blocked-p ()
12482 "Is the current entry blocked?"
12483 (org-with-silent-modifications
12484 (if (org-entry-get nil "NOBLOCKING")
12485 nil ;; Never block this entry
12486 (not (run-hook-with-args-until-failure
12487 'org-blocker-hook
12488 (list :type 'todo-state-change
12489 :position (point)
12490 :from 'todo
12491 :to 'done))))))
12493 (defun org-update-statistics-cookies (all)
12494 "Update the statistics cookie, either from TODO or from checkboxes.
12495 This should be called with the cursor in a line with a statistics cookie."
12496 (interactive "P")
12497 (if all
12498 (progn
12499 (org-update-checkbox-count 'all)
12500 (org-map-entries 'org-update-parent-todo-statistics))
12501 (if (not (org-at-heading-p))
12502 (org-update-checkbox-count)
12503 (let ((pos (point-marker))
12504 end l1 l2)
12505 (ignore-errors (org-back-to-heading t))
12506 (if (not (org-at-heading-p))
12507 (org-update-checkbox-count)
12508 (setq l1 (org-outline-level))
12509 (setq end (save-excursion
12510 (outline-next-heading)
12511 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12512 (point)))
12513 (if (and (save-excursion
12514 (re-search-forward
12515 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12516 (not (save-excursion (re-search-forward
12517 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12518 (org-update-checkbox-count)
12519 (if (and l2 (> l2 l1))
12520 (progn
12521 (goto-char end)
12522 (org-update-parent-todo-statistics))
12523 (goto-char pos)
12524 (beginning-of-line 1)
12525 (while (re-search-forward
12526 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12527 (point-at-eol) t)
12528 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12529 (goto-char pos)
12530 (move-marker pos nil)))))
12532 (defvar org-entry-property-inherited-from) ;; defined below
12533 (defun org-update-parent-todo-statistics ()
12534 "Update any statistics cookie in the parent of the current headline.
12535 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12536 the entire subtree and this will travel up the hierarchy and update
12537 statistics everywhere."
12538 (let* ((prop (save-excursion (org-up-heading-safe)
12539 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12540 (recursive (or (not org-hierarchical-todo-statistics)
12541 (and prop (string-match "\\<recursive\\>" prop))))
12542 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12544 (first t)
12545 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12546 level ltoggle l1 new ndel
12547 (cnt-all 0) (cnt-done 0) is-percent kwd
12548 checkbox-beg ov ovs ove cookie-present)
12549 (catch 'exit
12550 (save-excursion
12551 (beginning-of-line 1)
12552 (setq ltoggle (funcall outline-level))
12553 ;; Three situations are to consider:
12555 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12556 ;; to the top-level ancestor on the headline;
12558 ;; 2. If parent has "recursive" property, repeat up to the
12559 ;; headline setting that property, taking inheritance into
12560 ;; account;
12562 ;; 3. Else, move up to direct parent and proceed only once.
12563 (while (and (setq level (org-up-heading-safe))
12564 (or recursive first)
12565 (>= (point) lim))
12566 (setq first nil cookie-present nil)
12567 (unless (and level
12568 (not (string-match
12569 "\\<checkbox\\>"
12570 (downcase (or (org-entry-get nil "COOKIE_DATA")
12571 "")))))
12572 (throw 'exit nil))
12573 (while (re-search-forward box-re (point-at-eol) t)
12574 (setq cnt-all 0 cnt-done 0 cookie-present t)
12575 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12576 (save-match-data
12577 (unless (outline-next-heading) (throw 'exit nil))
12578 (while (and (looking-at org-complex-heading-regexp)
12579 (> (setq l1 (length (match-string 1))) level))
12580 (setq kwd (and (or recursive (= l1 ltoggle))
12581 (match-string 2)))
12582 (if (or (eq org-provide-todo-statistics 'all-headlines)
12583 (and (listp org-provide-todo-statistics)
12584 (or (member kwd org-provide-todo-statistics)
12585 (member kwd org-done-keywords))))
12586 (setq cnt-all (1+ cnt-all))
12587 (if (eq org-provide-todo-statistics t)
12588 (and kwd (setq cnt-all (1+ cnt-all)))))
12589 (and (member kwd org-done-keywords)
12590 (setq cnt-done (1+ cnt-done)))
12591 (outline-next-heading)))
12592 (setq new
12593 (if is-percent
12594 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12595 (format "[%d/%d]" cnt-done cnt-all))
12596 ndel (- (match-end 0) checkbox-beg))
12597 ;; handle overlays when updating cookie from column view
12598 (when (setq ov (car (overlays-at checkbox-beg)))
12599 (setq ovs (overlay-start ov) ove (overlay-end ov))
12600 (delete-overlay ov))
12601 (goto-char checkbox-beg)
12602 (insert new)
12603 (delete-region (point) (+ (point) ndel))
12604 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12605 (when ov (move-overlay ov ovs ove)))
12606 (when cookie-present
12607 (run-hook-with-args 'org-after-todo-statistics-hook
12608 cnt-done (- cnt-all cnt-done))))))
12609 (run-hooks 'org-todo-statistics-hook)))
12611 (defvar org-after-todo-statistics-hook nil
12612 "Hook that is called after a TODO statistics cookie has been updated.
12613 Each function is called with two arguments: the number of not-done entries
12614 and the number of done entries.
12616 For example, the following function, when added to this hook, will switch
12617 an entry to DONE when all children are done, and back to TODO when new
12618 entries are set to a TODO status. Note that this hook is only called
12619 when there is a statistics cookie in the headline!
12621 (defun org-summary-todo (n-done n-not-done)
12622 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12623 (let (org-log-done org-log-states) ; turn off logging
12624 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12627 (defvar org-todo-statistics-hook nil
12628 "Hook that is run whenever Org thinks TODO statistics should be updated.
12629 This hook runs even if there is no statistics cookie present, in which case
12630 `org-after-todo-statistics-hook' would not run.")
12632 (defun org-todo-trigger-tag-changes (state)
12633 "Apply the changes defined in `org-todo-state-tags-triggers'."
12634 (let ((l org-todo-state-tags-triggers)
12635 changes)
12636 (when (or (not state) (equal state ""))
12637 (setq changes (append changes (cdr (assoc "" l)))))
12638 (when (and (stringp state) (> (length state) 0))
12639 (setq changes (append changes (cdr (assoc state l)))))
12640 (when (member state org-not-done-keywords)
12641 (setq changes (append changes (cdr (assoc 'todo l)))))
12642 (when (member state org-done-keywords)
12643 (setq changes (append changes (cdr (assoc 'done l)))))
12644 (dolist (c changes)
12645 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12647 (defun org-local-logging (value)
12648 "Get logging settings from a property VALUE."
12649 (let* (words w a)
12650 ;; directly set the variables, they are already local.
12651 (setq org-log-done nil
12652 org-log-repeat nil
12653 org-todo-log-states nil)
12654 (setq words (org-split-string value))
12655 (while (setq w (pop words))
12656 (cond
12657 ((setq a (assoc w org-startup-options))
12658 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12659 (set (nth 1 a) (nth 2 a))))
12660 ((setq a (org-extract-log-state-settings w))
12661 (and (member (car a) org-todo-keywords-1)
12662 (push a org-todo-log-states)))))))
12664 (defun org-get-todo-sequence-head (kwd)
12665 "Return the head of the TODO sequence to which KWD belongs.
12666 If KWD is not set, check if there is a text property remembering the
12667 right sequence."
12668 (let (p)
12669 (cond
12670 ((not kwd)
12671 (or (get-text-property (point-at-bol) 'org-todo-head)
12672 (progn
12673 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12674 nil (point-at-eol)))
12675 (get-text-property p 'org-todo-head))))
12676 ((not (member kwd org-todo-keywords-1))
12677 (car org-todo-keywords-1))
12678 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12680 (defun org-fast-todo-selection ()
12681 "Fast TODO keyword selection with single keys.
12682 Returns the new TODO keyword, or nil if no state change should occur."
12683 (let* ((fulltable org-todo-key-alist)
12684 (done-keywords org-done-keywords) ;; needed for the faces.
12685 (maxlen (apply 'max (mapcar
12686 (lambda (x)
12687 (if (stringp (car x)) (string-width (car x)) 0))
12688 fulltable)))
12689 (expert nil)
12690 (fwidth (+ maxlen 3 1 3))
12691 (ncol (/ (- (window-width) 4) fwidth))
12692 tg cnt e c tbl
12693 groups ingroup)
12694 (save-excursion
12695 (save-window-excursion
12696 (if expert
12697 (set-buffer (get-buffer-create " *Org todo*"))
12698 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12699 (erase-buffer)
12700 (org-set-local 'org-done-keywords done-keywords)
12701 (setq tbl fulltable cnt 0)
12702 (while (setq e (pop tbl))
12703 (cond
12704 ((equal e '(:startgroup))
12705 (push '() groups) (setq ingroup t)
12706 (when (not (= cnt 0))
12707 (setq cnt 0)
12708 (insert "\n"))
12709 (insert "{ "))
12710 ((equal e '(:endgroup))
12711 (setq ingroup nil cnt 0)
12712 (insert "}\n"))
12713 ((equal e '(:newline))
12714 (when (not (= cnt 0))
12715 (setq cnt 0)
12716 (insert "\n")
12717 (setq e (car tbl))
12718 (while (equal (car tbl) '(:newline))
12719 (insert "\n")
12720 (setq tbl (cdr tbl)))))
12722 (setq tg (car e) c (cdr e))
12723 (if ingroup (push tg (car groups)))
12724 (setq tg (org-add-props tg nil 'face
12725 (org-get-todo-face tg)))
12726 (if (and (= cnt 0) (not ingroup)) (insert " "))
12727 (insert "[" c "] " tg (make-string
12728 (- fwidth 4 (length tg)) ?\ ))
12729 (when (= (setq cnt (1+ cnt)) ncol)
12730 (insert "\n")
12731 (if ingroup (insert " "))
12732 (setq cnt 0)))))
12733 (insert "\n")
12734 (goto-char (point-min))
12735 (if (not expert) (org-fit-window-to-buffer))
12736 (message "[a-z..]:Set [SPC]:clear")
12737 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12738 (cond
12739 ((or (= c ?\C-g)
12740 (and (= c ?q) (not (rassoc c fulltable))))
12741 (setq quit-flag t))
12742 ((= c ?\ ) nil)
12743 ((setq e (rassoc c fulltable) tg (car e))
12745 (t (setq quit-flag t)))))))
12747 (defun org-entry-is-todo-p ()
12748 (member (org-get-todo-state) org-not-done-keywords))
12750 (defun org-entry-is-done-p ()
12751 (member (org-get-todo-state) org-done-keywords))
12753 (defun org-get-todo-state ()
12754 "Return the TODO keyword of the current subtree."
12755 (save-excursion
12756 (org-back-to-heading t)
12757 (and (looking-at org-todo-line-regexp)
12758 (match-end 2)
12759 (match-string 2))))
12761 (defun org-at-date-range-p (&optional inactive-ok)
12762 "Is the cursor inside a date range?"
12763 (interactive)
12764 (save-excursion
12765 (catch 'exit
12766 (let ((pos (point)))
12767 (skip-chars-backward "^[<\r\n")
12768 (skip-chars-backward "<[")
12769 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12770 (>= (match-end 0) pos)
12771 (throw 'exit t))
12772 (skip-chars-backward "^<[\r\n")
12773 (skip-chars-backward "<[")
12774 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12775 (>= (match-end 0) pos)
12776 (throw 'exit t)))
12777 nil)))
12779 (defun org-get-repeat (&optional tagline)
12780 "Check if there is a deadline/schedule with repeater in this entry."
12781 (save-match-data
12782 (save-excursion
12783 (org-back-to-heading t)
12784 (and (re-search-forward (if tagline
12785 (concat tagline "\\s-*" org-repeat-re)
12786 org-repeat-re)
12787 (org-entry-end-position) t)
12788 (match-string-no-properties 1)))))
12790 (defvar org-last-changed-timestamp)
12791 (defvar org-last-inserted-timestamp)
12792 (defvar org-log-post-message)
12793 (defvar org-log-note-purpose)
12794 (defvar org-log-note-how)
12795 (defvar org-log-note-extra)
12796 (defun org-auto-repeat-maybe (done-word)
12797 "Check if the current headline contains a repeated deadline/schedule.
12798 If yes, set TODO state back to what it was and change the base date
12799 of repeating deadline/scheduled time stamps to new date.
12800 This function is run automatically after each state change to a DONE state."
12801 ;; last-state is dynamically scoped into this function
12802 (let* ((repeat (org-get-repeat))
12803 (aa (assoc org-last-state org-todo-kwd-alist))
12804 (interpret (nth 1 aa))
12805 (head (nth 2 aa))
12806 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12807 (msg "Entry repeats: ")
12808 (org-log-done nil)
12809 (org-todo-log-states nil)
12810 re type n what ts time to-state)
12811 (when repeat
12812 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12813 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12814 org-todo-repeat-to-state))
12815 (unless (and to-state (member to-state org-todo-keywords-1))
12816 (setq to-state (if (eq interpret 'type) org-last-state head)))
12817 (org-todo to-state)
12818 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12819 (org-entry-put nil "LAST_REPEAT" (format-time-string
12820 (org-time-stamp-format t t))))
12821 (when org-log-repeat
12822 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12823 (memq 'org-add-log-note post-command-hook))
12824 ;; OK, we are already setup for some record
12825 (if (eq org-log-repeat 'note)
12826 ;; make sure we take a note, not only a time stamp
12827 (setq org-log-note-how 'note))
12828 ;; Set up for taking a record
12829 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12830 org-last-state
12831 'findpos org-log-repeat)))
12832 (org-back-to-heading t)
12833 (org-add-planning-info nil nil 'closed)
12834 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12835 org-deadline-time-regexp "\\)\\|\\("
12836 org-ts-regexp "\\)"))
12837 (while (re-search-forward
12838 re (save-excursion (outline-next-heading) (point)) t)
12839 (setq type (if (match-end 1) org-scheduled-string
12840 (if (match-end 3) org-deadline-string "Plain:"))
12841 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12842 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12843 (setq n (string-to-number (match-string 2 ts))
12844 what (match-string 3 ts))
12845 (if (equal what "w") (setq n (* n 7) what "d"))
12846 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12847 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12848 ;; Preparation, see if we need to modify the start date for the change
12849 (when (match-end 1)
12850 (setq time (save-match-data (org-time-string-to-time ts)))
12851 (cond
12852 ((equal (match-string 1 ts) ".")
12853 ;; Shift starting date to today
12854 (org-timestamp-change
12855 (- (org-today) (time-to-days time))
12856 'day))
12857 ((equal (match-string 1 ts) "+")
12858 (let ((nshiftmax 10) (nshift 0))
12859 (while (or (= nshift 0)
12860 (<= (time-to-days time)
12861 (time-to-days (current-time))))
12862 (when (= (incf nshift) nshiftmax)
12863 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12864 (error "Abort")))
12865 (org-timestamp-change n (cdr (assoc what whata)))
12866 (org-at-timestamp-p t)
12867 (setq ts (match-string 1))
12868 (setq time (save-match-data (org-time-string-to-time ts)))))
12869 (org-timestamp-change (- n) (cdr (assoc what whata)))
12870 ;; rematch, so that we have everything in place for the real shift
12871 (org-at-timestamp-p t)
12872 (setq ts (match-string 1))
12873 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12874 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12875 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12876 (setq org-log-post-message msg)
12877 (message "%s" msg))))
12879 (defun org-show-todo-tree (arg)
12880 "Make a compact tree which shows all headlines marked with TODO.
12881 The tree will show the lines where the regexp matches, and all higher
12882 headlines above the match.
12883 With a \\[universal-argument] prefix, prompt for a regexp to match.
12884 With a numeric prefix N, construct a sparse tree for the Nth element
12885 of `org-todo-keywords-1'."
12886 (interactive "P")
12887 (let ((case-fold-search nil)
12888 (kwd-re
12889 (cond ((null arg) org-not-done-regexp)
12890 ((equal arg '(4))
12891 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12892 (mapcar 'list org-todo-keywords-1))))
12893 (concat "\\("
12894 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12895 "\\)\\>")))
12896 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12897 (regexp-quote (nth (1- (prefix-numeric-value arg))
12898 org-todo-keywords-1)))
12899 (t (user-error "Invalid prefix argument: %s" arg)))))
12900 (message "%d TODO entries found"
12901 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12903 (defun org-deadline (arg &optional time)
12904 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12905 With one universal prefix argument, remove any deadline from the item.
12906 With two universal prefix arguments, prompt for a warning delay.
12907 With argument TIME, set the deadline at the corresponding date. TIME
12908 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12909 (interactive "P")
12910 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12911 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12912 'region-start-level 'region))
12913 org-loop-over-headlines-in-active-region)
12914 (org-map-entries
12915 `(org-deadline ',arg ,time)
12916 org-loop-over-headlines-in-active-region
12917 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12918 (let* ((old-date (org-entry-get nil "DEADLINE"))
12919 (old-date-time (if old-date (org-time-string-to-time old-date)))
12920 (repeater (and old-date
12921 (string-match
12922 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12923 old-date)
12924 (match-string 1 old-date))))
12925 (cond
12926 ((equal arg '(4))
12927 (when (and old-date org-log-redeadline)
12928 (org-add-log-setup 'deldeadline nil old-date 'findpos
12929 org-log-redeadline))
12930 (org-remove-timestamp-with-keyword org-deadline-string)
12931 (message "Item no longer has a deadline."))
12932 ((equal arg '(16))
12933 (save-excursion
12934 (org-back-to-heading t)
12935 (if (re-search-forward
12936 org-deadline-time-regexp
12937 (save-excursion (outline-next-heading) (point)) t)
12938 (let* ((rpl0 (match-string 1))
12939 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12940 (replace-match
12941 (concat org-deadline-string
12942 " <" rpl
12943 (format " -%dd"
12944 (abs
12945 (- (time-to-days
12946 (save-match-data
12947 (org-read-date nil t nil "Warn starting from" old-date-time)))
12948 (time-to-days old-date-time))))
12949 ">") t t))
12950 (user-error "No deadline information to update"))))
12952 (org-add-planning-info 'deadline time 'closed)
12953 (when (and old-date org-log-redeadline
12954 (not (equal old-date
12955 (substring org-last-inserted-timestamp 1 -1))))
12956 (org-add-log-setup 'redeadline nil old-date 'findpos
12957 org-log-redeadline))
12958 (when repeater
12959 (save-excursion
12960 (org-back-to-heading t)
12961 (when (re-search-forward (concat org-deadline-string " "
12962 org-last-inserted-timestamp)
12963 (save-excursion
12964 (outline-next-heading) (point)) t)
12965 (goto-char (1- (match-end 0)))
12966 (insert " " repeater)
12967 (setq org-last-inserted-timestamp
12968 (concat (substring org-last-inserted-timestamp 0 -1)
12969 " " repeater
12970 (substring org-last-inserted-timestamp -1))))))
12971 (message "Deadline on %s" org-last-inserted-timestamp))))))
12973 (defun org-schedule (arg &optional time)
12974 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12975 With one universal prefix argument, remove any scheduling date from the item.
12976 With two universal prefix arguments, prompt for a delay cookie.
12977 With argument TIME, scheduled at the corresponding date. TIME can
12978 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12979 (interactive "P")
12980 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12981 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12982 'region-start-level 'region))
12983 org-loop-over-headlines-in-active-region)
12984 (org-map-entries
12985 `(org-schedule ',arg ,time)
12986 org-loop-over-headlines-in-active-region
12987 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12988 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12989 (old-date-time (if old-date (org-time-string-to-time old-date)))
12990 (repeater (and old-date
12991 (string-match
12992 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12993 old-date)
12994 (match-string 1 old-date))))
12995 (cond
12996 ((equal arg '(4))
12997 (progn
12998 (when (and old-date org-log-reschedule)
12999 (org-add-log-setup 'delschedule nil old-date 'findpos
13000 org-log-reschedule))
13001 (org-remove-timestamp-with-keyword org-scheduled-string)
13002 (message "Item is no longer scheduled.")))
13003 ((equal arg '(16))
13004 (save-excursion
13005 (org-back-to-heading t)
13006 (if (re-search-forward
13007 org-scheduled-time-regexp
13008 (save-excursion (outline-next-heading) (point)) t)
13009 (let* ((rpl0 (match-string 1))
13010 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13011 (replace-match
13012 (concat org-scheduled-string
13013 " <" rpl
13014 (format " -%dd"
13015 (abs
13016 (- (time-to-days
13017 (save-match-data
13018 (org-read-date nil t nil "Delay until" old-date-time)))
13019 (time-to-days old-date-time))))
13020 ">") t t))
13021 (user-error "No scheduled information to update"))))
13023 (org-add-planning-info 'scheduled time 'closed)
13024 (when (and old-date org-log-reschedule
13025 (not (equal old-date
13026 (substring org-last-inserted-timestamp 1 -1))))
13027 (org-add-log-setup 'reschedule nil old-date 'findpos
13028 org-log-reschedule))
13029 (when repeater
13030 (save-excursion
13031 (org-back-to-heading t)
13032 (when (re-search-forward (concat org-scheduled-string " "
13033 org-last-inserted-timestamp)
13034 (save-excursion
13035 (outline-next-heading) (point)) t)
13036 (goto-char (1- (match-end 0)))
13037 (insert " " repeater)
13038 (setq org-last-inserted-timestamp
13039 (concat (substring org-last-inserted-timestamp 0 -1)
13040 " " repeater
13041 (substring org-last-inserted-timestamp -1))))))
13042 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13044 (defun org-get-scheduled-time (pom &optional inherit)
13045 "Get the scheduled time as a time tuple, of a format suitable
13046 for calling org-schedule with, or if there is no scheduling,
13047 returns nil."
13048 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13049 (when time
13050 (apply 'encode-time (org-parse-time-string time)))))
13052 (defun org-get-deadline-time (pom &optional inherit)
13053 "Get the deadline as a time tuple, of a format suitable for
13054 calling org-deadline with, or if there is no scheduling, returns
13055 nil."
13056 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13057 (when time
13058 (apply 'encode-time (org-parse-time-string time)))))
13060 (defun org-remove-timestamp-with-keyword (keyword)
13061 "Remove all time stamps with KEYWORD in the current entry."
13062 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13063 beg)
13064 (save-excursion
13065 (org-back-to-heading t)
13066 (setq beg (point))
13067 (outline-next-heading)
13068 (while (re-search-backward re beg t)
13069 (replace-match "")
13070 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13071 (equal (char-before) ?\ ))
13072 (backward-delete-char 1)
13073 (if (string-match "^[ \t]*$" (buffer-substring
13074 (point-at-bol) (point-at-eol)))
13075 (delete-region (point-at-bol)
13076 (min (point-max) (1+ (point-at-eol))))))))))
13078 (defvar org-time-was-given) ; dynamically scoped parameter
13079 (defvar org-end-time-was-given) ; dynamically scoped parameter
13081 (defun org-add-planning-info (what &optional time &rest remove)
13082 "Insert new timestamp with keyword in the line directly after the headline.
13083 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13084 If non is given, the user is prompted for a date.
13085 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13086 be removed."
13087 (interactive)
13088 (let (org-time-was-given org-end-time-was-given ts
13089 end default-time default-input)
13091 (catch 'exit
13092 (when (and (memq what '(scheduled deadline))
13093 (or (not time)
13094 (and (stringp time)
13095 (string-match "^[-+]+[0-9]" time))))
13096 ;; Try to get a default date/time from existing timestamp
13097 (save-excursion
13098 (org-back-to-heading t)
13099 (setq end (save-excursion (outline-next-heading) (point)))
13100 (when (re-search-forward (if (eq what 'scheduled)
13101 org-scheduled-time-regexp
13102 org-deadline-time-regexp)
13103 end t)
13104 (setq ts (match-string 1)
13105 default-time
13106 (apply 'encode-time (org-parse-time-string ts))
13107 default-input (and ts (org-get-compact-tod ts))))))
13108 (when what
13109 (setq time
13110 (if (stringp time)
13111 ;; This is a string (relative or absolute), set proper date
13112 (apply 'encode-time
13113 (org-read-date-analyze
13114 time default-time (decode-time default-time)))
13115 ;; If necessary, get the time from the user
13116 (or time (org-read-date nil 'to-time nil nil
13117 default-time default-input)))))
13119 (when (and org-insert-labeled-timestamps-at-point
13120 (member what '(scheduled deadline)))
13121 (insert
13122 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13123 (org-insert-time-stamp time org-time-was-given
13124 nil nil nil (list org-end-time-was-given))
13125 (setq what nil))
13126 (save-excursion
13127 (save-restriction
13128 (let (col list elt ts buffer-invisibility-spec)
13129 (org-back-to-heading t)
13130 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13131 (goto-char (match-end 1))
13132 (setq col (current-column))
13133 (goto-char (match-end 0))
13134 (if (eobp) (insert "\n") (forward-char 1))
13135 (when (and (not what)
13136 (not (looking-at
13137 (concat "[ \t]*"
13138 org-keyword-time-not-clock-regexp))))
13139 ;; Nothing to add, nothing to remove...... :-)
13140 (throw 'exit nil))
13141 (if (and (not (looking-at org-outline-regexp))
13142 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13143 "[^\r\n]*"))
13144 (not (equal (match-string 1) org-clock-string)))
13145 (narrow-to-region (match-beginning 0) (match-end 0))
13146 (insert-before-markers "\n")
13147 (backward-char 1)
13148 (narrow-to-region (point) (point))
13149 (and org-adapt-indentation (org-indent-to-column col)))
13150 ;; Check if we have to remove something.
13151 (setq list (cons what remove))
13152 (while list
13153 (setq elt (pop list))
13154 (when (or (and (eq elt 'scheduled)
13155 (re-search-forward org-scheduled-time-regexp nil t))
13156 (and (eq elt 'deadline)
13157 (re-search-forward org-deadline-time-regexp nil t))
13158 (and (eq elt 'closed)
13159 (re-search-forward org-closed-time-regexp nil t)))
13160 (replace-match "")
13161 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13162 (and (looking-at "[ \t]+") (replace-match ""))
13163 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13164 (when what
13165 (insert
13166 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13167 (cond ((eq what 'scheduled) org-scheduled-string)
13168 ((eq what 'deadline) org-deadline-string)
13169 ((eq what 'closed) org-closed-string))
13170 " ")
13171 (setq ts (org-insert-time-stamp
13172 time
13173 (or org-time-was-given
13174 (and (eq what 'closed) org-log-done-with-time))
13175 (eq what 'closed)
13176 nil nil (list org-end-time-was-given)))
13177 (insert
13178 (if (not (or (bolp) (eq (char-before) ?\ )
13179 (memq (char-after) '(32 10))
13180 (eobp))) " " ""))
13181 (end-of-line 1))
13182 (goto-char (point-min))
13183 (widen)
13184 (if (and (looking-at "[ \t]*\n")
13185 (equal (char-before) ?\n))
13186 (delete-region (1- (point)) (point-at-eol)))
13187 ts))))))
13189 (defvar org-log-note-marker (make-marker))
13190 (defvar org-log-note-purpose nil)
13191 (defvar org-log-note-state nil)
13192 (defvar org-log-note-previous-state nil)
13193 (defvar org-log-note-how nil)
13194 (defvar org-log-note-extra nil)
13195 (defvar org-log-note-window-configuration nil)
13196 (defvar org-log-note-return-to (make-marker))
13197 (defvar org-log-note-effective-time nil
13198 "Remembered current time so that dynamically scoped
13199 `org-extend-today-until' affects tha timestamps in state change
13200 log")
13202 (defvar org-log-post-message nil
13203 "Message to be displayed after a log note has been stored.
13204 The auto-repeater uses this.")
13206 (defun org-add-note ()
13207 "Add a note to the current entry.
13208 This is done in the same way as adding a state change note."
13209 (interactive)
13210 (org-add-log-setup 'note nil nil 'findpos nil))
13212 (defvar org-property-end-re)
13213 (defun org-add-log-setup (&optional purpose state prev-state
13214 findpos how extra)
13215 "Set up the post command hook to take a note.
13216 If this is about to TODO state change, the new state is expected in STATE.
13217 When FINDPOS is non-nil, find the correct position for the note in
13218 the current entry. If not, assume that it can be inserted at point.
13219 HOW is an indicator what kind of note should be created.
13220 EXTRA is additional text that will be inserted into the notes buffer."
13221 (let* ((org-log-into-drawer (org-log-into-drawer))
13222 (drawer (cond ((stringp org-log-into-drawer)
13223 org-log-into-drawer)
13224 (org-log-into-drawer "LOGBOOK"))))
13225 (save-restriction
13226 (save-excursion
13227 (when findpos
13228 (org-back-to-heading t)
13229 (narrow-to-region (point) (save-excursion
13230 (outline-next-heading) (point)))
13231 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13232 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13233 "[^\r\n]*\\)?"))
13234 (goto-char (match-end 0))
13235 (cond
13236 (drawer
13237 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13238 nil t)
13239 (progn
13240 (goto-char (match-end 0))
13241 (or org-log-states-order-reversed
13242 (and (re-search-forward org-property-end-re nil t)
13243 (goto-char (1- (match-beginning 0))))))
13244 (insert "\n:" drawer ":\n:END:")
13245 (beginning-of-line 0)
13246 (org-indent-line)
13247 (beginning-of-line 2)
13248 (org-indent-line)
13249 (end-of-line 0)))
13250 ((and org-log-state-notes-insert-after-drawers
13251 (save-excursion
13252 (forward-line) (looking-at org-drawer-regexp)))
13253 (forward-line)
13254 (while (looking-at org-drawer-regexp)
13255 (goto-char (match-end 0))
13256 (re-search-forward org-property-end-re (point-max) t)
13257 (forward-line))
13258 (forward-line -1)))
13259 (unless org-log-states-order-reversed
13260 (and (= (char-after) ?\n) (forward-char 1))
13261 (org-skip-over-state-notes)
13262 (skip-chars-backward " \t\n\r")))
13263 (move-marker org-log-note-marker (point))
13264 (setq org-log-note-purpose purpose
13265 org-log-note-state state
13266 org-log-note-previous-state prev-state
13267 org-log-note-how how
13268 org-log-note-extra extra
13269 org-log-note-effective-time (org-current-effective-time))
13270 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13272 (defun org-skip-over-state-notes ()
13273 "Skip past the list of State notes in an entry."
13274 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13275 (when (ignore-errors (goto-char (org-in-item-p)))
13276 (let* ((struct (org-list-struct))
13277 (prevs (org-list-prevs-alist struct)))
13278 (while (looking-at "[ \t]*- State")
13279 (goto-char (or (org-list-get-next-item (point) struct prevs)
13280 (org-list-get-item-end (point) struct)))))))
13282 (defun org-add-log-note (&optional purpose)
13283 "Pop up a window for taking a note, and add this note later at point."
13284 (remove-hook 'post-command-hook 'org-add-log-note)
13285 (setq org-log-note-window-configuration (current-window-configuration))
13286 (delete-other-windows)
13287 (move-marker org-log-note-return-to (point))
13288 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13289 (goto-char org-log-note-marker)
13290 (org-switch-to-buffer-other-window "*Org Note*")
13291 (erase-buffer)
13292 (if (memq org-log-note-how '(time state))
13293 (let (current-prefix-arg) (org-store-log-note))
13294 (let ((org-inhibit-startup t)) (org-mode))
13295 (insert (format "# Insert note for %s.
13296 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13297 (cond
13298 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13299 ((eq org-log-note-purpose 'done) "closed todo item")
13300 ((eq org-log-note-purpose 'state)
13301 (format "state change from \"%s\" to \"%s\""
13302 (or org-log-note-previous-state "")
13303 (or org-log-note-state "")))
13304 ((eq org-log-note-purpose 'reschedule)
13305 "rescheduling")
13306 ((eq org-log-note-purpose 'delschedule)
13307 "no longer scheduled")
13308 ((eq org-log-note-purpose 'redeadline)
13309 "changing deadline")
13310 ((eq org-log-note-purpose 'deldeadline)
13311 "removing deadline")
13312 ((eq org-log-note-purpose 'refile)
13313 "refiling")
13314 ((eq org-log-note-purpose 'note)
13315 "this entry")
13316 (t (error "This should not happen")))))
13317 (if org-log-note-extra (insert org-log-note-extra))
13318 (org-set-local 'org-finish-function 'org-store-log-note)
13319 (run-hooks 'org-log-buffer-setup-hook)))
13321 (defvar org-note-abort nil) ; dynamically scoped
13322 (defun org-store-log-note ()
13323 "Finish taking a log note, and insert it to where it belongs."
13324 (let ((txt (buffer-string)))
13325 (kill-buffer (current-buffer))
13326 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13327 lines ind bul)
13328 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13329 (setq txt (replace-match "" t t txt)))
13330 (if (string-match "\\s-+\\'" txt)
13331 (setq txt (replace-match "" t t txt)))
13332 (setq lines (org-split-string txt "\n"))
13333 (when (and note (string-match "\\S-" note))
13334 (setq note
13335 (org-replace-escapes
13336 note
13337 (list (cons "%u" (user-login-name))
13338 (cons "%U" user-full-name)
13339 (cons "%t" (format-time-string
13340 (org-time-stamp-format 'long 'inactive)
13341 org-log-note-effective-time))
13342 (cons "%T" (format-time-string
13343 (org-time-stamp-format 'long nil)
13344 org-log-note-effective-time))
13345 (cons "%d" (format-time-string
13346 (org-time-stamp-format nil 'inactive)
13347 org-log-note-effective-time))
13348 (cons "%D" (format-time-string
13349 (org-time-stamp-format nil nil)
13350 org-log-note-effective-time))
13351 (cons "%s" (if org-log-note-state
13352 (concat "\"" org-log-note-state "\"")
13353 ""))
13354 (cons "%S" (if org-log-note-previous-state
13355 (concat "\"" org-log-note-previous-state "\"")
13356 "\"\"")))))
13357 (if lines (setq note (concat note " \\\\")))
13358 (push note lines))
13359 (when (or current-prefix-arg org-note-abort)
13360 (when org-log-into-drawer
13361 (org-remove-empty-drawer-at
13362 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13363 org-log-note-marker))
13364 (setq lines nil))
13365 (when lines
13366 (with-current-buffer (marker-buffer org-log-note-marker)
13367 (save-excursion
13368 (goto-char org-log-note-marker)
13369 (move-marker org-log-note-marker nil)
13370 (end-of-line 1)
13371 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13372 (setq ind (save-excursion
13373 (if (ignore-errors (goto-char (org-in-item-p)))
13374 (let ((struct (org-list-struct)))
13375 (org-list-get-ind
13376 (org-list-get-top-point struct) struct))
13377 (skip-chars-backward " \r\t\n")
13378 (cond
13379 ((and (org-at-heading-p)
13380 org-adapt-indentation)
13381 (1+ (org-current-level)))
13382 ((org-at-heading-p) 0)
13383 (t (org-get-indentation))))))
13384 (setq bul (org-list-bullet-string "-"))
13385 (org-indent-line-to ind)
13386 (insert bul (pop lines))
13387 (let ((ind-body (+ (length bul) ind)))
13388 (while lines
13389 (insert "\n")
13390 (org-indent-line-to ind-body)
13391 (insert (pop lines))))
13392 (message "Note stored")
13393 (org-back-to-heading t)
13394 (org-cycle-hide-drawers 'children))
13395 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13396 ;; from within `org-add-log-note' because `buffer-undo-list'
13397 ;; is then modified outside of `org-with-remote-undo'.
13398 (when (eq this-command 'org-agenda-todo)
13399 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13400 ;; Don't add undo information when called from `org-agenda-todo'
13401 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13402 (set-window-configuration org-log-note-window-configuration)
13403 (with-current-buffer (marker-buffer org-log-note-return-to)
13404 (goto-char org-log-note-return-to))
13405 (move-marker org-log-note-return-to nil)
13406 (and org-log-post-message (message "%s" org-log-post-message))))
13408 (defun org-remove-empty-drawer-at (drawer pos)
13409 "Remove an empty drawer DRAWER at position POS.
13410 POS may also be a marker."
13411 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13412 (save-excursion
13413 (save-restriction
13414 (widen)
13415 (goto-char pos)
13416 (if (org-in-regexp
13417 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13418 (replace-match ""))))))
13420 (defvar org-ts-type nil)
13421 (defun org-sparse-tree (&optional arg type)
13422 "Create a sparse tree, prompt for the details.
13423 This command can create sparse trees. You first need to select the type
13424 of match used to create the tree:
13426 t Show all TODO entries.
13427 T Show entries with a specific TODO keyword.
13428 m Show entries selected by a tags/property match.
13429 p Enter a property name and its value (both with completion on existing
13430 names/values) and show entries with that property.
13431 r Show entries matching a regular expression (`/' can be used as well).
13432 b Show deadlines and scheduled items before a date.
13433 a Show deadlines and scheduled items after a date.
13434 d Show deadlines due within `org-deadline-warning-days'.
13435 D Show deadlines and scheduled items between a date range."
13436 (interactive "P")
13437 (let (ans kwd value ts-type)
13438 (setq type (or type org-sparse-tree-default-date-type))
13439 (setq org-ts-type type)
13440 (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"
13441 (cond ((eq type 'all) "all timestamps")
13442 ((eq type 'scheduled) "only scheduled")
13443 ((eq type 'deadline) "only deadline")
13444 ((eq type 'active) "only active timestamps")
13445 ((eq type 'inactive) "only inactive timestamps")
13446 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13447 ((eq type 'closed) "with a closed time-stamp")
13448 (t "scheduled/deadline")))
13449 (setq ans (read-char-exclusive))
13450 (cond
13451 ((equal ans ?c)
13452 (org-sparse-tree
13453 arg (cadr (member type '(scheduled-or-deadline
13454 all scheduled deadline active inactive closed)))))
13455 ((equal ans ?d)
13456 (call-interactively 'org-check-deadlines))
13457 ((equal ans ?b)
13458 (call-interactively 'org-check-before-date))
13459 ((equal ans ?a)
13460 (call-interactively 'org-check-after-date))
13461 ((equal ans ?D)
13462 (call-interactively 'org-check-dates-range))
13463 ((equal ans ?t)
13464 (call-interactively 'org-show-todo-tree))
13465 ((equal ans ?T)
13466 (org-show-todo-tree '(4)))
13467 ((member ans '(?T ?m))
13468 (call-interactively 'org-match-sparse-tree))
13469 ((member ans '(?p ?P))
13470 (setq kwd (org-icompleting-read "Property: "
13471 (mapcar 'list (org-buffer-property-keys))))
13472 (setq value (org-icompleting-read "Value: "
13473 (mapcar 'list (org-property-values kwd))))
13474 (unless (string-match "\\`{.*}\\'" value)
13475 (setq value (concat "\"" value "\"")))
13476 (org-match-sparse-tree arg (concat kwd "=" value)))
13477 ((member ans '(?r ?R ?/))
13478 (call-interactively 'org-occur))
13479 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13481 (defvar org-occur-highlights nil
13482 "List of overlays used for occur matches.")
13483 (make-variable-buffer-local 'org-occur-highlights)
13484 (defvar org-occur-parameters nil
13485 "Parameters of the active org-occur calls.
13486 This is a list, each call to org-occur pushes as cons cell,
13487 containing the regular expression and the callback, onto the list.
13488 The list can contain several entries if `org-occur' has been called
13489 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13490 will only contain one set of parameters. When the highlights are
13491 removed (for example with `C-c C-c', or with the next edit (depending
13492 on `org-remove-highlights-with-change'), this variable is emptied
13493 as well.")
13494 (make-variable-buffer-local 'org-occur-parameters)
13496 (defun org-occur (regexp &optional keep-previous callback)
13497 "Make a compact tree which shows all matches of REGEXP.
13498 The tree will show the lines where the regexp matches, and all higher
13499 headlines above the match. It will also show the heading after the match,
13500 to make sure editing the matching entry is easy.
13501 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13502 call to `org-occur' will be kept, to allow stacking of calls to this
13503 command.
13504 If CALLBACK is non-nil, it is a function which is called to confirm
13505 that the match should indeed be shown."
13506 (interactive "sRegexp: \nP")
13507 (when (equal regexp "")
13508 (user-error "Regexp cannot be empty"))
13509 (unless keep-previous
13510 (org-remove-occur-highlights nil nil t))
13511 (push (cons regexp callback) org-occur-parameters)
13512 (let ((cnt 0))
13513 (save-excursion
13514 (goto-char (point-min))
13515 (if (or (not keep-previous) ; do not want to keep
13516 (not org-occur-highlights)) ; no previous matches
13517 ;; hide everything
13518 (org-overview))
13519 (while (re-search-forward regexp nil t)
13520 (when (or (not callback)
13521 (save-match-data (funcall callback)))
13522 (setq cnt (1+ cnt))
13523 (when org-highlight-sparse-tree-matches
13524 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13525 (org-show-context 'occur-tree))))
13526 (when org-remove-highlights-with-change
13527 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13528 nil 'local))
13529 (unless org-sparse-tree-open-archived-trees
13530 (org-hide-archived-subtrees (point-min) (point-max)))
13531 (run-hooks 'org-occur-hook)
13532 (if (org-called-interactively-p 'interactive)
13533 (message "%d match(es) for regexp %s" cnt regexp))
13534 cnt))
13536 (defun org-occur-next-match (&optional n reset)
13537 "Function for `next-error-function' to find sparse tree matches.
13538 N is the number of matches to move, when negative move backwards.
13539 RESET is entirely ignored - this function always goes back to the
13540 starting point when no match is found."
13541 (let* ((limit (if (< n 0) (point-min) (point-max)))
13542 (search-func (if (< n 0)
13543 'previous-single-char-property-change
13544 'next-single-char-property-change))
13545 (n (abs n))
13546 (pos (point))
13548 (catch 'exit
13549 (while (setq p1 (funcall search-func (point) 'org-type))
13550 (when (equal p1 limit)
13551 (goto-char pos)
13552 (error "No more matches"))
13553 (when (equal (get-char-property p1 'org-type) 'org-occur)
13554 (setq n (1- n))
13555 (when (= n 0)
13556 (goto-char p1)
13557 (throw 'exit (point))))
13558 (goto-char p1))
13559 (goto-char p1)
13560 (error "No more matches"))))
13562 (defun org-show-context (&optional key)
13563 "Make sure point and context are visible.
13564 How much context is shown depends upon the variables
13565 `org-show-hierarchy-above', `org-show-following-heading',
13566 `org-show-entry-below' and `org-show-siblings'."
13567 (let ((heading-p (org-at-heading-p t))
13568 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13569 (following-p (org-get-alist-option org-show-following-heading key))
13570 (entry-p (org-get-alist-option org-show-entry-below key))
13571 (siblings-p (org-get-alist-option org-show-siblings key)))
13572 ;; Show heading or entry text
13573 (if (and heading-p (not entry-p))
13574 (org-flag-heading nil) ; only show the heading
13575 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13576 (org-show-hidden-entry))) ; show entire entry
13577 (when following-p
13578 ;; Show next sibling, or heading below text
13579 (save-excursion
13580 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13581 (org-flag-heading nil))))
13582 (when siblings-p (org-show-siblings))
13583 (when hierarchy-p
13584 ;; show all higher headings, possibly with siblings
13585 (save-excursion
13586 (while (and (condition-case nil
13587 (progn (org-up-heading-all 1) t)
13588 (error nil))
13589 (not (bobp)))
13590 (org-flag-heading nil)
13591 (when siblings-p (org-show-siblings)))))
13592 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13594 (defvar org-reveal-start-hook nil
13595 "Hook run before revealing a location.")
13597 (defun org-reveal (&optional siblings)
13598 "Show current entry, hierarchy above it, and the following headline.
13599 This can be used to show a consistent set of context around locations
13600 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13601 not t for the search context.
13603 With optional argument SIBLINGS, on each level of the hierarchy all
13604 siblings are shown. This repairs the tree structure to what it would
13605 look like when opened with hierarchical calls to `org-cycle'.
13606 With double optional argument \\[universal-argument] \\[universal-argument], \
13607 go to the parent and show the
13608 entire tree."
13609 (interactive "P")
13610 (run-hooks 'org-reveal-start-hook)
13611 (let ((org-show-hierarchy-above t)
13612 (org-show-following-heading t)
13613 (org-show-siblings (if siblings t org-show-siblings)))
13614 (org-show-context nil))
13615 (when (equal siblings '(16))
13616 (save-excursion
13617 (when (org-up-heading-safe)
13618 (org-show-subtree)
13619 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13621 (defun org-highlight-new-match (beg end)
13622 "Highlight from BEG to END and mark the highlight is an occur headline."
13623 (let ((ov (make-overlay beg end)))
13624 (overlay-put ov 'face 'secondary-selection)
13625 (overlay-put ov 'org-type 'org-occur)
13626 (push ov org-occur-highlights)))
13628 (defun org-remove-occur-highlights (&optional beg end noremove)
13629 "Remove the occur highlights from the buffer.
13630 BEG and END are ignored. If NOREMOVE is nil, remove this function
13631 from the `before-change-functions' in the current buffer."
13632 (interactive)
13633 (unless org-inhibit-highlight-removal
13634 (mapc 'delete-overlay org-occur-highlights)
13635 (setq org-occur-highlights nil)
13636 (setq org-occur-parameters nil)
13637 (unless noremove
13638 (remove-hook 'before-change-functions
13639 'org-remove-occur-highlights 'local))))
13641 ;;;; Priorities
13643 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13644 "Regular expression matching the priority indicator.")
13646 (defvar org-remove-priority-next-time nil)
13648 (defun org-priority-up ()
13649 "Increase the priority of the current item."
13650 (interactive)
13651 (org-priority 'up))
13653 (defun org-priority-down ()
13654 "Decrease the priority of the current item."
13655 (interactive)
13656 (org-priority 'down))
13658 (defun org-priority (&optional action show)
13659 "Change the priority of an item.
13660 ACTION can be `set', `up', `down', or a character."
13661 (interactive "P")
13662 (if (equal action '(4))
13663 (org-show-priority)
13664 (unless org-enable-priority-commands
13665 (user-error "Priority commands are disabled"))
13666 (setq action (or action 'set))
13667 (let (current new news have remove)
13668 (save-excursion
13669 (org-back-to-heading t)
13670 (if (looking-at org-priority-regexp)
13671 (setq current (string-to-char (match-string 2))
13672 have t))
13673 (cond
13674 ((eq action 'remove)
13675 (setq remove t new ?\ ))
13676 ((or (eq action 'set)
13677 (if (featurep 'xemacs) (characterp action) (integerp action)))
13678 (if (not (eq action 'set))
13679 (setq new action)
13680 (message "Priority %c-%c, SPC to remove: "
13681 org-highest-priority org-lowest-priority)
13682 (save-match-data
13683 (setq new (read-char-exclusive))))
13684 (if (and (= (upcase org-highest-priority) org-highest-priority)
13685 (= (upcase org-lowest-priority) org-lowest-priority))
13686 (setq new (upcase new)))
13687 (cond ((equal new ?\ ) (setq remove t))
13688 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13689 (user-error "Priority must be between `%c' and `%c'"
13690 org-highest-priority org-lowest-priority))))
13691 ((eq action 'up)
13692 (setq new (if have
13693 (1- current) ; normal cycling
13694 ;; last priority was empty
13695 (if (eq last-command this-command)
13696 org-lowest-priority ; wrap around empty to lowest
13697 ;; default
13698 (if org-priority-start-cycle-with-default
13699 org-default-priority
13700 (1- org-default-priority))))))
13701 ((eq action 'down)
13702 (setq new (if have
13703 (1+ current) ; normal cycling
13704 ;; last priority was empty
13705 (if (eq last-command this-command)
13706 org-highest-priority ; wrap around empty to highest
13707 ;; default
13708 (if org-priority-start-cycle-with-default
13709 org-default-priority
13710 (1+ org-default-priority))))))
13711 (t (user-error "Invalid action")))
13712 (if (or (< (upcase new) org-highest-priority)
13713 (> (upcase new) org-lowest-priority))
13714 (if (and (memq action '(up down))
13715 (not have) (not (eq last-command this-command)))
13716 ;; `new' is from default priority
13717 (error
13718 "The default can not be set, see `org-default-priority' why")
13719 ;; normal cycling: `new' is beyond highest/lowest priority
13720 ;; and is wrapped around to the empty priority
13721 (setq remove t)))
13722 (setq news (format "%c" new))
13723 (if have
13724 (if remove
13725 (replace-match "" t t nil 1)
13726 (replace-match news t t nil 2))
13727 (if remove
13728 (user-error "No priority cookie found in line")
13729 (let ((case-fold-search nil))
13730 (looking-at org-todo-line-regexp))
13731 (if (match-end 2)
13732 (progn
13733 (goto-char (match-end 2))
13734 (insert " [#" news "]"))
13735 (goto-char (match-beginning 3))
13736 (insert "[#" news "] "))))
13737 (org-preserve-lc (org-set-tags nil 'align)))
13738 (if remove
13739 (message "Priority removed")
13740 (message "Priority of current item set to %s" news)))))
13742 (defun org-show-priority ()
13743 "Show the priority of the current item.
13744 This priority is composed of the main priority given with the [#A] cookies,
13745 and by additional input from the age of a schedules or deadline entry."
13746 (interactive)
13747 (let ((pri (if (eq major-mode 'org-agenda-mode)
13748 (org-get-at-bol 'priority)
13749 (save-excursion
13750 (save-match-data
13751 (beginning-of-line)
13752 (and (looking-at org-heading-regexp)
13753 (org-get-priority (match-string 0))))))))
13754 (message "Priority is %d" (if pri pri -1000))))
13756 (defun org-get-priority (s)
13757 "Find priority cookie and return priority."
13758 (save-match-data
13759 (if (functionp org-get-priority-function)
13760 (funcall org-get-priority-function)
13761 (if (not (string-match org-priority-regexp s))
13762 (* 1000 (- org-lowest-priority org-default-priority))
13763 (* 1000 (- org-lowest-priority
13764 (string-to-char (match-string 2 s))))))))
13766 ;;;; Tags
13768 (defvar org-agenda-archives-mode)
13769 (defvar org-map-continue-from nil
13770 "Position from where mapping should continue.
13771 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13773 (defvar org-scanner-tags nil
13774 "The current tag list while the tags scanner is running.")
13775 (defvar org-trust-scanner-tags nil
13776 "Should `org-get-tags-at' use the tags for the scanner.
13777 This is for internal dynamical scoping only.
13778 When this is non-nil, the function `org-get-tags-at' will return the value
13779 of `org-scanner-tags' instead of building the list by itself. This
13780 can lead to large speed-ups when the tags scanner is used in a file with
13781 many entries, and when the list of tags is retrieved, for example to
13782 obtain a list of properties. Building the tags list for each entry in such
13783 a file becomes an N^2 operation - but with this variable set, it scales
13784 as N.")
13786 (defun org-scan-tags (action matcher todo-only &optional start-level)
13787 "Sca headline tags with inheritance and produce output ACTION.
13789 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13790 or `agenda' to produce an entry list for an agenda view. It can also be
13791 a Lisp form or a function that should be called at each matched headline, in
13792 this case the return value is a list of all return values from these calls.
13794 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13795 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13796 only lines with a not-done TODO keyword are included in the output.
13797 This should be the same variable that was scoped into
13798 and set by `org-make-tags-matcher' when it constructed MATCHER.
13800 START-LEVEL can be a string with asterisks, reducing the scope to
13801 headlines matching this string."
13802 (require 'org-agenda)
13803 (let* ((re (concat "^"
13804 (if start-level
13805 ;; Get the correct level to match
13806 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13807 org-outline-regexp)
13808 " *\\(\\<\\("
13809 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13810 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13811 (props (list 'face 'default
13812 'done-face 'org-agenda-done
13813 'undone-face 'default
13814 'mouse-face 'highlight
13815 'org-not-done-regexp org-not-done-regexp
13816 'org-todo-regexp org-todo-regexp
13817 'org-complex-heading-regexp org-complex-heading-regexp
13818 'help-echo
13819 (format "mouse-2 or RET jump to org file %s"
13820 (abbreviate-file-name
13821 (or (buffer-file-name (buffer-base-buffer))
13822 (buffer-name (buffer-base-buffer)))))))
13823 (org-map-continue-from nil)
13824 lspos tags tags-list
13825 (tags-alist (list (cons 0 org-file-tags)))
13826 (llast 0) rtn rtn1 level category i txt
13827 todo marker entry priority)
13828 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13829 (setq action (list 'lambda nil action)))
13830 (save-excursion
13831 (goto-char (point-min))
13832 (when (eq action 'sparse-tree)
13833 (org-overview)
13834 (org-remove-occur-highlights))
13835 (while (let (case-fold-search)
13836 (re-search-forward re nil t))
13837 (setq org-map-continue-from nil)
13838 (catch :skip
13839 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13840 tags (if (match-end 4) (org-match-string-no-properties 4)))
13841 (goto-char (setq lspos (match-beginning 0)))
13842 (setq level (org-reduced-level (org-outline-level))
13843 category (org-get-category))
13844 (setq i llast llast level)
13845 ;; remove tag lists from same and sublevels
13846 (while (>= i level)
13847 (when (setq entry (assoc i tags-alist))
13848 (setq tags-alist (delete entry tags-alist)))
13849 (setq i (1- i)))
13850 ;; add the next tags
13851 (when tags
13852 (setq tags (org-split-string tags ":")
13853 tags-alist
13854 (cons (cons level tags) tags-alist)))
13855 ;; compile tags for current headline
13856 (setq tags-list
13857 (if org-use-tag-inheritance
13858 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13859 tags)
13860 org-scanner-tags tags-list)
13861 (when org-use-tag-inheritance
13862 (setcdr (car tags-alist)
13863 (mapcar (lambda (x)
13864 (setq x (copy-sequence x))
13865 (org-add-prop-inherited x))
13866 (cdar tags-alist))))
13867 (when (and tags org-use-tag-inheritance
13868 (or (not (eq t org-use-tag-inheritance))
13869 org-tags-exclude-from-inheritance))
13870 ;; selective inheritance, remove uninherited ones
13871 (setcdr (car tags-alist)
13872 (org-remove-uninherited-tags (cdar tags-alist))))
13873 (when (and
13875 ;; eval matcher only when the todo condition is OK
13876 (and (or (not todo-only) (member todo org-not-done-keywords))
13877 (let ((case-fold-search t) (org-trust-scanner-tags t))
13878 (eval matcher)))
13880 ;; Call the skipper, but return t if it does not skip,
13881 ;; so that the `and' form continues evaluating
13882 (progn
13883 (unless (eq action 'sparse-tree) (org-agenda-skip))
13886 ;; Check if timestamps are deselecting this entry
13887 (or (not todo-only)
13888 (and (member todo org-not-done-keywords)
13889 (or (not org-agenda-tags-todo-honor-ignore-options)
13890 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13892 ;; select this headline
13893 (cond
13894 ((eq action 'sparse-tree)
13895 (and org-highlight-sparse-tree-matches
13896 (org-get-heading) (match-end 0)
13897 (org-highlight-new-match
13898 (match-beginning 1) (match-end 1)))
13899 (org-show-context 'tags-tree))
13900 ((eq action 'agenda)
13901 (setq txt (org-agenda-format-item
13903 (concat
13904 (if (eq org-tags-match-list-sublevels 'indented)
13905 (make-string (1- level) ?.) "")
13906 (org-get-heading))
13907 level category
13908 tags-list)
13909 priority (org-get-priority txt))
13910 (goto-char lspos)
13911 (setq marker (org-agenda-new-marker))
13912 (org-add-props txt props
13913 'org-marker marker 'org-hd-marker marker 'org-category category
13914 'todo-state todo
13915 'priority priority 'type "tagsmatch")
13916 (push txt rtn))
13917 ((functionp action)
13918 (setq org-map-continue-from nil)
13919 (save-excursion
13920 (setq rtn1 (funcall action))
13921 (push rtn1 rtn)))
13922 (t (user-error "Invalid action")))
13924 ;; if we are to skip sublevels, jump to end of subtree
13925 (unless org-tags-match-list-sublevels
13926 (org-end-of-subtree t)
13927 (backward-char 1))))
13928 ;; Get the correct position from where to continue
13929 (if org-map-continue-from
13930 (goto-char org-map-continue-from)
13931 (and (= (point) lspos) (end-of-line 1)))))
13932 (when (and (eq action 'sparse-tree)
13933 (not org-sparse-tree-open-archived-trees))
13934 (org-hide-archived-subtrees (point-min) (point-max)))
13935 (nreverse rtn)))
13937 (defun org-remove-uninherited-tags (tags)
13938 "Remove all tags that are not inherited from the list TAGS."
13939 (cond
13940 ((eq org-use-tag-inheritance t)
13941 (if org-tags-exclude-from-inheritance
13942 (org-delete-all org-tags-exclude-from-inheritance tags)
13943 tags))
13944 ((not org-use-tag-inheritance) nil)
13945 ((stringp org-use-tag-inheritance)
13946 (delq nil (mapcar
13947 (lambda (x)
13948 (if (and (string-match org-use-tag-inheritance x)
13949 (not (member x org-tags-exclude-from-inheritance)))
13950 x nil))
13951 tags)))
13952 ((listp org-use-tag-inheritance)
13953 (delq nil (mapcar
13954 (lambda (x)
13955 (if (member x org-use-tag-inheritance) x nil))
13956 tags)))))
13958 (defun org-match-sparse-tree (&optional todo-only match)
13959 "Create a sparse tree according to tags string MATCH.
13960 MATCH can contain positive and negative selection of tags, like
13961 \"+WORK+URGENT-WITHBOSS\".
13962 If optional argument TODO-ONLY is non-nil, only select lines that are
13963 also TODO lines."
13964 (interactive "P")
13965 (org-agenda-prepare-buffers (list (current-buffer)))
13966 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13968 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13970 (defvar org-cached-props nil)
13971 (defun org-cached-entry-get (pom property)
13972 (if (or (eq t org-use-property-inheritance)
13973 (and (stringp org-use-property-inheritance)
13974 (string-match org-use-property-inheritance property))
13975 (and (listp org-use-property-inheritance)
13976 (member property org-use-property-inheritance)))
13977 ;; Caching is not possible, check it directly
13978 (org-entry-get pom property 'inherit)
13979 ;; Get all properties, so that we can do complicated checks easily
13980 (cdr (assoc property (or org-cached-props
13981 (setq org-cached-props
13982 (org-entry-properties pom)))))))
13984 (defun org-global-tags-completion-table (&optional files)
13985 "Return the list of all tags in all agenda buffer/files.
13986 Optional FILES argument is a list of files which can be used
13987 instead of the agenda files."
13988 (save-excursion
13989 (org-uniquify
13990 (delq nil
13991 (apply 'append
13992 (mapcar
13993 (lambda (file)
13994 (set-buffer (find-file-noselect file))
13995 (append (org-get-buffer-tags)
13996 (mapcar (lambda (x) (if (stringp (car-safe x))
13997 (list (car-safe x)) nil))
13998 org-tag-alist)))
13999 (if (and files (car files))
14000 files
14001 (org-agenda-files))))))))
14003 (defun org-make-tags-matcher (match)
14004 "Create the TAGS/TODO matcher form for the selection string MATCH.
14006 The variable `todo-only' is scoped dynamically into this function.
14007 It will be set to t if the matcher restricts matching to TODO entries,
14008 otherwise will not be touched.
14010 Returns a cons of the selection string MATCH and the constructed
14011 lisp form implementing the matcher. The matcher is to be evaluated
14012 at an Org entry, with point on the headline, and returns t if the
14013 entry matches the selection string MATCH. The returned lisp form
14014 references two variables with information about the entry, which
14015 must be bound around the form's evaluation: todo, the TODO keyword
14016 at the entry (or nil of none); and tags-list, the list of all tags
14017 at the entry including inherited ones. Additionally, the category
14018 of the entry (if any) must be specified as the text property
14019 'org-category on the headline.
14021 See also `org-scan-tags'.
14023 (declare (special todo-only))
14024 (unless (boundp 'todo-only)
14025 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14026 (unless match
14027 ;; Get a new match request, with completion against the global
14028 ;; tags table and the local tags in current buffer
14029 (let ((org-last-tags-completion-table
14030 (org-uniquify
14031 (delq nil (append (org-get-buffer-tags)
14032 (org-global-tags-completion-table))))))
14033 (setq match (org-completing-read-no-i
14034 "Match: " 'org-tags-completion-function nil nil nil
14035 'org-tags-history))))
14037 ;; Parse the string and create a lisp form
14038 (let ((match0 match)
14039 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14040 minus tag mm
14041 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14042 orterms term orlist re-p str-p level-p level-op time-p
14043 prop-p pn pv po gv rest (start 0) (ss 0))
14044 ;; Expand group tags
14045 (setq match (org-tags-expand match))
14047 ;; Check if there is a TODO part of this match, which would be the
14048 ;; part after a "/". TO make sure that this slash is not part of
14049 ;; a property value to be matched against, we also check that there
14050 ;; is no " after that slash.
14051 ;; First, find the last slash
14052 (while (string-match "/+" match ss)
14053 (setq start (match-beginning 0) ss (match-end 0)))
14054 (if (and (string-match "/+" match start)
14055 (not (save-match-data (string-match "\"" match start))))
14056 ;; match contains also a todo-matching request
14057 (progn
14058 (setq tagsmatch (substring match 0 (match-beginning 0))
14059 todomatch (substring match (match-end 0)))
14060 (if (string-match "^!" todomatch)
14061 (setq todo-only t todomatch (substring todomatch 1)))
14062 (if (string-match "^\\s-*$" todomatch)
14063 (setq todomatch nil)))
14064 ;; only matching tags
14065 (setq tagsmatch match todomatch nil))
14067 ;; Make the tags matcher
14068 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14069 (setq tagsmatcher t)
14070 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14071 (while (setq term (pop orterms))
14072 (while (and (equal (substring term -1) "\\") orterms)
14073 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14074 (while (string-match re term)
14075 (setq rest (substring term (match-end 0))
14076 minus (and (match-end 1)
14077 (equal (match-string 1 term) "-"))
14078 tag (save-match-data (replace-regexp-in-string
14079 "\\\\-" "-"
14080 (match-string 2 term)))
14081 re-p (equal (string-to-char tag) ?{)
14082 level-p (match-end 4)
14083 prop-p (match-end 5)
14084 mm (cond
14085 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14086 (level-p
14087 (setq level-op (org-op-to-function (match-string 3 term)))
14088 `(,level-op level ,(string-to-number
14089 (match-string 4 term))))
14090 (prop-p
14091 (setq pn (match-string 5 term)
14092 po (match-string 6 term)
14093 pv (match-string 7 term)
14094 re-p (equal (string-to-char pv) ?{)
14095 str-p (equal (string-to-char pv) ?\")
14096 time-p (save-match-data
14097 (string-match "^\"[[<].*[]>]\"$" pv))
14098 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14099 (if time-p (setq pv (org-matcher-time pv)))
14100 (setq po (org-op-to-function po (if time-p 'time str-p)))
14101 (cond
14102 ((equal pn "CATEGORY")
14103 (setq gv '(get-text-property (point) 'org-category)))
14104 ((equal pn "TODO")
14105 (setq gv 'todo))
14107 (setq gv `(org-cached-entry-get nil ,pn))))
14108 (if re-p
14109 (if (eq po 'org<>)
14110 `(not (string-match ,pv (or ,gv "")))
14111 `(string-match ,pv (or ,gv "")))
14112 (if str-p
14113 `(,po (or ,gv "") ,pv)
14114 `(,po (string-to-number (or ,gv ""))
14115 ,(string-to-number pv) ))))
14116 (t `(member ,tag tags-list)))
14117 mm (if minus (list 'not mm) mm)
14118 term rest)
14119 (push mm tagsmatcher))
14120 (push (if (> (length tagsmatcher) 1)
14121 (cons 'and tagsmatcher)
14122 (car tagsmatcher))
14123 orlist)
14124 (setq tagsmatcher nil))
14125 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14126 (setq tagsmatcher
14127 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14128 ;; Make the todo matcher
14129 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14130 (setq todomatcher t)
14131 (setq orterms (org-split-string todomatch "|") orlist nil)
14132 (while (setq term (pop orterms))
14133 (while (string-match re term)
14134 (setq minus (and (match-end 1)
14135 (equal (match-string 1 term) "-"))
14136 kwd (match-string 2 term)
14137 re-p (equal (string-to-char kwd) ?{)
14138 term (substring term (match-end 0))
14139 mm (if re-p
14140 `(string-match ,(substring kwd 1 -1) todo)
14141 (list 'equal 'todo kwd))
14142 mm (if minus (list 'not mm) mm))
14143 (push mm todomatcher))
14144 (push (if (> (length todomatcher) 1)
14145 (cons 'and todomatcher)
14146 (car todomatcher))
14147 orlist)
14148 (setq todomatcher nil))
14149 (setq todomatcher (if (> (length orlist) 1)
14150 (cons 'or orlist) (car orlist))))
14152 ;; Return the string and lisp forms of the matcher
14153 (setq matcher (if todomatcher
14154 (list 'and tagsmatcher todomatcher)
14155 tagsmatcher))
14156 (when todo-only
14157 (setq matcher (list 'and '(member todo org-not-done-keywords)
14158 matcher)))
14159 (cons match0 matcher)))
14161 (defun org-tags-expand (match &optional single-as-list downcased)
14162 "Expand group tags in MATCH.
14164 This replaces every group tag in MATCH with a regexp tag search.
14165 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14166 will be replaced like this:
14168 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14169 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14170 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14172 Replacing by a regexp preserves the structure of the match.
14173 E.g., this expansion
14175 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14177 will match anything tagged with \"Lab\" and \"Home\", or tagged
14178 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14180 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14181 assumed to be a single group tag, and the function will return
14182 the list of tags in this group.
14184 When DOWNCASE is non-nil, expand downcased TAGS."
14185 (if org-group-tags
14186 (let* ((case-fold-search t)
14187 (stable org-mode-syntax-table)
14188 (tal (or org-tag-groups-alist-for-agenda
14189 org-tag-groups-alist))
14190 (tal (if downcased
14191 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14192 (tml (mapcar 'car tal))
14193 (rtnmatch match) rpl)
14194 ;; @ and _ are allowed as word-components in tags
14195 (modify-syntax-entry ?@ "w" stable)
14196 (modify-syntax-entry ?_ "w" stable)
14197 (while (and tml
14198 (with-syntax-table stable
14199 (string-match
14200 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14201 (regexp-opt tml) "\\>\\)") rtnmatch)))
14202 (let* ((dir (match-string 1 rtnmatch))
14203 (tag (match-string 2 rtnmatch))
14204 (tag (if downcased (downcase tag) tag)))
14205 (setq tml (delete tag tml))
14206 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14207 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14208 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14209 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14210 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14211 (if single-as-list
14212 (or (reverse rpl) (list rtnmatch))
14213 rtnmatch))
14214 (if single-as-list (list (if downcased (downcase match) match))
14215 match)))
14217 (defun org-op-to-function (op &optional stringp)
14218 "Turn an operator into the appropriate function."
14219 (setq op
14220 (cond
14221 ((equal op "<" ) '(< string< org-time<))
14222 ((equal op ">" ) '(> org-string> org-time>))
14223 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14224 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14225 ((member op '("=" "==")) '(= string= org-time=))
14226 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14227 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14229 (defun org<> (a b) (not (= a b)))
14230 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14231 (defun org-string>= (a b) (not (string< a b)))
14232 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14233 (defun org-string<> (a b) (not (string= a b)))
14234 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14235 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14236 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14237 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14238 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14239 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14240 (defun org-2ft (s)
14241 "Convert S to a floating point time.
14242 If S is already a number, just return it. If it is a string, parse
14243 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14244 (cond
14245 ((numberp s) s)
14246 ((stringp s)
14247 (condition-case nil
14248 (float-time (apply 'encode-time (org-parse-time-string s)))
14249 (error 0.)))
14250 (t 0.)))
14252 (defun org-time-today ()
14253 "Time in seconds today at 0:00.
14254 Returns the float number of seconds since the beginning of the
14255 epoch to the beginning of today (00:00)."
14256 (float-time (apply 'encode-time
14257 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14259 (defun org-matcher-time (s)
14260 "Interpret a time comparison value."
14261 (save-match-data
14262 (cond
14263 ((string= s "<now>") (float-time))
14264 ((string= s "<today>") (org-time-today))
14265 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14266 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14267 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14268 (+ (org-time-today)
14269 (* (string-to-number (match-string 1 s))
14270 (cdr (assoc (match-string 2 s)
14271 '(("d" . 86400.0) ("w" . 604800.0)
14272 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14273 (t (org-2ft s)))))
14275 (defun org-match-any-p (re list)
14276 "Does re match any element of list?"
14277 (setq list (mapcar (lambda (x) (string-match re x)) list))
14278 (delq nil list))
14280 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14281 (defvar org-tags-overlay (make-overlay 1 1))
14282 (org-detach-overlay org-tags-overlay)
14284 (defun org-get-local-tags-at (&optional pos)
14285 "Get a list of tags defined in the current headline."
14286 (org-get-tags-at pos 'local))
14288 (defun org-get-local-tags ()
14289 "Get a list of tags defined in the current headline."
14290 (org-get-tags-at nil 'local))
14292 (defun org-get-tags-at (&optional pos local)
14293 "Get a list of all headline tags applicable at POS.
14294 POS defaults to point. If tags are inherited, the list contains
14295 the targets in the same sequence as the headlines appear, i.e.
14296 the tags of the current headline come last.
14297 When LOCAL is non-nil, only return tags from the current headline,
14298 ignore inherited ones."
14299 (interactive)
14300 (if (and org-trust-scanner-tags
14301 (or (not pos) (equal pos (point)))
14302 (not local))
14303 org-scanner-tags
14304 (let (tags ltags lastpos parent)
14305 (save-excursion
14306 (save-restriction
14307 (widen)
14308 (goto-char (or pos (point)))
14309 (save-match-data
14310 (catch 'done
14311 (condition-case nil
14312 (progn
14313 (org-back-to-heading t)
14314 (while (not (equal lastpos (point)))
14315 (setq lastpos (point))
14316 (when (looking-at
14317 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14318 (setq ltags (org-split-string
14319 (org-match-string-no-properties 1) ":"))
14320 (when parent
14321 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14322 (setq tags (append
14323 (if parent
14324 (org-remove-uninherited-tags ltags)
14325 ltags)
14326 tags)))
14327 (or org-use-tag-inheritance (throw 'done t))
14328 (if local (throw 'done t))
14329 (or (org-up-heading-safe) (error nil))
14330 (setq parent t)))
14331 (error nil)))))
14332 (if local
14333 tags
14334 (reverse (delete-dups
14335 (reverse (append
14336 (org-remove-uninherited-tags
14337 org-file-tags) tags)))))))))
14339 (defun org-add-prop-inherited (s)
14340 (add-text-properties 0 (length s) '(inherited t) s)
14343 (defun org-toggle-tag (tag &optional onoff)
14344 "Toggle the tag TAG for the current line.
14345 If ONOFF is `on' or `off', don't toggle but set to this state."
14346 (let (res current)
14347 (save-excursion
14348 (org-back-to-heading t)
14349 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14350 (point-at-eol) t)
14351 (progn
14352 (setq current (match-string 1))
14353 (replace-match ""))
14354 (setq current ""))
14355 (setq current (nreverse (org-split-string current ":")))
14356 (cond
14357 ((eq onoff 'on)
14358 (setq res t)
14359 (or (member tag current) (push tag current)))
14360 ((eq onoff 'off)
14361 (or (not (member tag current)) (setq current (delete tag current))))
14362 (t (if (member tag current)
14363 (setq current (delete tag current))
14364 (setq res t)
14365 (push tag current))))
14366 (end-of-line 1)
14367 (if current
14368 (progn
14369 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14370 (org-set-tags nil t))
14371 (delete-horizontal-space))
14372 (run-hooks 'org-after-tags-change-hook))
14373 res))
14375 (defun org-align-tags-here (to-col)
14376 ;; Assumes that this is a headline
14377 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14378 (beginning-of-line 1)
14379 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14380 (< pos (match-beginning 2)))
14381 (progn
14382 (setq tags-l (- (match-end 2) (match-beginning 2)))
14383 (goto-char (match-beginning 1))
14384 (insert " ")
14385 (delete-region (point) (1+ (match-beginning 2)))
14386 (setq ncol (max (current-column)
14387 (1+ col)
14388 (if (> to-col 0)
14389 to-col
14390 (- (abs to-col) tags-l))))
14391 (setq p (point))
14392 (insert (make-string (- ncol (current-column)) ?\ ))
14393 (setq ncol (current-column))
14394 (when indent-tabs-mode (tabify p (point-at-eol)))
14395 (org-move-to-column (min ncol col) t nil t))
14396 (goto-char pos))))
14398 (defun org-set-tags-command (&optional arg just-align)
14399 "Call the set-tags command for the current entry."
14400 (interactive "P")
14401 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14402 (org-set-tags arg just-align)
14403 (save-excursion
14404 (unless (and (org-region-active-p)
14405 org-loop-over-headlines-in-active-region)
14406 (org-back-to-heading t))
14407 (org-set-tags arg just-align))))
14409 (defun org-set-tags-to (data)
14410 "Set the tags of the current entry to DATA, replacing the current tags.
14411 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14412 If DATA is nil or the empty string, any tags will be removed."
14413 (interactive "sTags: ")
14414 (setq data
14415 (cond
14416 ((eq data nil) "")
14417 ((equal data "") "")
14418 ((stringp data)
14419 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14420 ":"))
14421 ((listp data)
14422 (concat ":" (mapconcat 'identity data ":") ":"))))
14423 (when data
14424 (save-excursion
14425 (org-back-to-heading t)
14426 (when (looking-at org-complex-heading-regexp)
14427 (if (match-end 5)
14428 (progn
14429 (goto-char (match-beginning 5))
14430 (insert data)
14431 (delete-region (point) (point-at-eol))
14432 (org-set-tags nil 'align))
14433 (goto-char (point-at-eol))
14434 (insert " " data)
14435 (org-set-tags nil 'align)))
14436 (beginning-of-line 1)
14437 (if (looking-at ".*?\\([ \t]+\\)$")
14438 (delete-region (match-beginning 1) (match-end 1))))))
14440 (defun org-align-all-tags ()
14441 "Align the tags i all headings."
14442 (interactive)
14443 (save-excursion
14444 (or (ignore-errors (org-back-to-heading t))
14445 (outline-next-heading))
14446 (if (org-at-heading-p)
14447 (org-set-tags t)
14448 (message "No headings"))))
14450 (defvar org-indent-indentation-per-level)
14451 (defun org-set-tags (&optional arg just-align)
14452 "Set the tags for the current headline.
14453 With prefix ARG, realign all tags in headings in the current buffer.
14454 When JUST-ALIGN is non-nil, only align tags.
14455 When JUST-ALIGN is 'ignore-column, align tags without trying to set
14456 the column by ignoring invisible text."
14457 (interactive "P")
14458 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14459 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14460 'region-start-level 'region))
14461 org-loop-over-headlines-in-active-region)
14462 (org-map-entries
14463 ;; We don't use ARG and JUST-ALIGN here because these args
14464 ;; are not useful when looping over headlines.
14465 `(org-set-tags)
14466 org-loop-over-headlines-in-active-region
14467 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14468 (let* ((re org-outline-regexp-bol)
14469 (current (unless arg (org-get-tags-string)))
14470 (col (current-column))
14471 (org-setting-tags t)
14472 table current-tags inherited-tags ; computed below when needed
14473 tags p0 c0 c1 rpl di tc level)
14474 (if arg
14475 (save-excursion
14476 (goto-char (point-min))
14477 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14478 (while (re-search-forward re nil t)
14479 (org-set-tags nil t)
14480 (end-of-line 1)))
14481 (message "All tags realigned to column %d" org-tags-column))
14482 (if just-align
14483 (setq tags current)
14484 ;; Get a new set of tags from the user
14485 (save-excursion
14486 (setq table (append org-tag-persistent-alist
14487 (or org-tag-alist (org-get-buffer-tags))
14488 (and
14489 org-complete-tags-always-offer-all-agenda-tags
14490 (org-global-tags-completion-table
14491 (org-agenda-files))))
14492 org-last-tags-completion-table table
14493 current-tags (org-split-string current ":")
14494 inherited-tags (nreverse
14495 (nthcdr (length current-tags)
14496 (nreverse (org-get-tags-at))))
14497 tags
14498 (if (or (eq t org-use-fast-tag-selection)
14499 (and org-use-fast-tag-selection
14500 (delq nil (mapcar 'cdr table))))
14501 (org-fast-tag-selection
14502 current-tags inherited-tags table
14503 (if org-fast-tag-selection-include-todo
14504 org-todo-key-alist))
14505 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14506 (org-trim
14507 (org-icompleting-read "Tags: "
14508 'org-tags-completion-function
14509 nil nil current 'org-tags-history))))))
14510 (while (string-match "[-+&]+" tags)
14511 ;; No boolean logic, just a list
14512 (setq tags (replace-match ":" t t tags))))
14514 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14516 (if org-tags-sort-function
14517 (setq tags (mapconcat 'identity
14518 (sort (org-split-string
14519 tags (org-re "[^[:alnum:]_@#%]+"))
14520 org-tags-sort-function) ":")))
14522 (if (string-match "\\`[\t ]*\\'" tags)
14523 (setq tags "")
14524 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14525 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14527 ;; Insert new tags at the correct column
14528 (beginning-of-line 1)
14529 (setq level (or (and (looking-at org-outline-regexp)
14530 (- (match-end 0) (point) 1))
14532 (cond
14533 ((and (equal current "") (equal tags "")))
14534 ((re-search-forward
14535 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14536 (point-at-eol) t)
14537 (if (equal tags "")
14538 (setq rpl "")
14539 (goto-char (match-beginning 0))
14540 (setq c0 (current-column)
14541 ;; compute offset for the case of org-indent-mode active
14542 di (if org-indent-mode
14543 (* (1- org-indent-indentation-per-level) (1- level))
14545 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14546 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14547 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14548 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14549 (replace-match rpl t t)
14550 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14551 tags)
14552 (t (error "Tags alignment failed")))
14553 (org-move-to-column col nil nil (not (eq just-align 'ignore-column)))
14554 (unless just-align
14555 (run-hooks 'org-after-tags-change-hook))))))
14557 (defun org-change-tag-in-region (beg end tag off)
14558 "Add or remove TAG for each entry in the region.
14559 This works in the agenda, and also in an org-mode buffer."
14560 (interactive
14561 (list (region-beginning) (region-end)
14562 (let ((org-last-tags-completion-table
14563 (if (derived-mode-p 'org-mode)
14564 (org-uniquify
14565 (delq nil (append (org-get-buffer-tags)
14566 (org-global-tags-completion-table))))
14567 (org-global-tags-completion-table))))
14568 (org-icompleting-read
14569 "Tag: " 'org-tags-completion-function nil nil nil
14570 'org-tags-history))
14571 (progn
14572 (message "[s]et or [r]emove? ")
14573 (equal (read-char-exclusive) ?r))))
14574 (if (fboundp 'deactivate-mark) (deactivate-mark))
14575 (let ((agendap (equal major-mode 'org-agenda-mode))
14576 l1 l2 m buf pos newhead (cnt 0))
14577 (goto-char end)
14578 (setq l2 (1- (org-current-line)))
14579 (goto-char beg)
14580 (setq l1 (org-current-line))
14581 (loop for l from l1 to l2 do
14582 (org-goto-line l)
14583 (setq m (get-text-property (point) 'org-hd-marker))
14584 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14585 (and agendap m))
14586 (setq buf (if agendap (marker-buffer m) (current-buffer))
14587 pos (if agendap m (point)))
14588 (with-current-buffer buf
14589 (save-excursion
14590 (save-restriction
14591 (goto-char pos)
14592 (setq cnt (1+ cnt))
14593 (org-toggle-tag tag (if off 'off 'on))
14594 (setq newhead (org-get-heading)))))
14595 (and agendap (org-agenda-change-all-lines newhead m))))
14596 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14598 (defun org-tags-completion-function (string predicate &optional flag)
14599 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14600 (confirm (lambda (x) (stringp (car x)))))
14601 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14602 (setq s1 (match-string 1 string)
14603 s2 (match-string 2 string))
14604 (setq s1 "" s2 string))
14605 (cond
14606 ((eq flag nil)
14607 ;; try completion
14608 (setq rtn (try-completion s2 ctable confirm))
14609 (if (stringp rtn)
14610 (setq rtn
14611 (concat s1 s2 (substring rtn (length s2))
14612 (if (and org-add-colon-after-tag-completion
14613 (assoc rtn ctable))
14614 ":" ""))))
14615 rtn)
14616 ((eq flag t)
14617 ;; all-completions
14618 (all-completions s2 ctable confirm))
14619 ((eq flag 'lambda)
14620 ;; exact match?
14621 (assoc s2 ctable)))))
14623 (defun org-fast-tag-insert (kwd tags face &optional end)
14624 "Insert KDW, and the TAGS, the latter with face FACE.
14625 Also insert END."
14626 (insert (format "%-12s" (concat kwd ":"))
14627 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14628 (or end "")))
14630 (defun org-fast-tag-show-exit (flag)
14631 (save-excursion
14632 (org-goto-line 3)
14633 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14634 (replace-match ""))
14635 (when flag
14636 (end-of-line 1)
14637 (org-move-to-column (- (window-width) 19) t)
14638 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14640 (defun org-set-current-tags-overlay (current prefix)
14641 "Add an overlay to CURRENT tag with PREFIX."
14642 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14643 (if (featurep 'xemacs)
14644 (org-overlay-display org-tags-overlay (concat prefix s)
14645 'secondary-selection)
14646 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14647 (org-overlay-display org-tags-overlay (concat prefix s)))))
14649 (defvar org-last-tag-selection-key nil)
14650 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14651 "Fast tag selection with single keys.
14652 CURRENT is the current list of tags in the headline, INHERITED is the
14653 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14654 possibly with grouping information. TODO-TABLE is a similar table with
14655 TODO keywords, should these have keys assigned to them.
14656 If the keys are nil, a-z are automatically assigned.
14657 Returns the new tags string, or nil to not change the current settings."
14658 (let* ((fulltable (append table todo-table))
14659 (maxlen (apply 'max (mapcar
14660 (lambda (x)
14661 (if (stringp (car x)) (string-width (car x)) 0))
14662 fulltable)))
14663 (buf (current-buffer))
14664 (expert (eq org-fast-tag-selection-single-key 'expert))
14665 (buffer-tags nil)
14666 (fwidth (+ maxlen 3 1 3))
14667 (ncol (/ (- (window-width) 4) fwidth))
14668 (i-face 'org-done)
14669 (c-face 'org-todo)
14670 tg cnt e c char c1 c2 ntable tbl rtn
14671 ov-start ov-end ov-prefix
14672 (exit-after-next org-fast-tag-selection-single-key)
14673 (done-keywords org-done-keywords)
14674 groups ingroup)
14675 (save-excursion
14676 (beginning-of-line 1)
14677 (if (looking-at
14678 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14679 (setq ov-start (match-beginning 1)
14680 ov-end (match-end 1)
14681 ov-prefix "")
14682 (setq ov-start (1- (point-at-eol))
14683 ov-end (1+ ov-start))
14684 (skip-chars-forward "^\n\r")
14685 (setq ov-prefix
14686 (concat
14687 (buffer-substring (1- (point)) (point))
14688 (if (> (current-column) org-tags-column)
14690 (make-string (- org-tags-column (current-column)) ?\ ))))))
14691 (move-overlay org-tags-overlay ov-start ov-end)
14692 (save-window-excursion
14693 (if expert
14694 (set-buffer (get-buffer-create " *Org tags*"))
14695 (delete-other-windows)
14696 (split-window-vertically)
14697 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14698 (erase-buffer)
14699 (org-set-local 'org-done-keywords done-keywords)
14700 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14701 (org-fast-tag-insert "Current" current c-face "\n\n")
14702 (org-fast-tag-show-exit exit-after-next)
14703 (org-set-current-tags-overlay current ov-prefix)
14704 (setq tbl fulltable char ?a cnt 0)
14705 (while (setq e (pop tbl))
14706 (cond
14707 ((equal (car e) :startgroup)
14708 (push '() groups) (setq ingroup t)
14709 (when (not (= cnt 0))
14710 (setq cnt 0)
14711 (insert "\n"))
14712 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14713 ((equal (car e) :endgroup)
14714 (setq ingroup nil cnt 0)
14715 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14716 ((equal e '(:newline))
14717 (when (not (= cnt 0))
14718 (setq cnt 0)
14719 (insert "\n")
14720 (setq e (car tbl))
14721 (while (equal (car tbl) '(:newline))
14722 (insert "\n")
14723 (setq tbl (cdr tbl)))))
14724 ((equal e '(:grouptags)) nil)
14726 (setq tg (copy-sequence (car e)) c2 nil)
14727 (if (cdr e)
14728 (setq c (cdr e))
14729 ;; automatically assign a character.
14730 (setq c1 (string-to-char
14731 (downcase (substring
14732 tg (if (= (string-to-char tg) ?@) 1 0)))))
14733 (if (or (rassoc c1 ntable) (rassoc c1 table))
14734 (while (or (rassoc char ntable) (rassoc char table))
14735 (setq char (1+ char)))
14736 (setq c2 c1))
14737 (setq c (or c2 char)))
14738 (if ingroup (push tg (car groups)))
14739 (setq tg (org-add-props tg nil 'face
14740 (cond
14741 ((not (assoc tg table))
14742 (org-get-todo-face tg))
14743 ((member tg current) c-face)
14744 ((member tg inherited) i-face))))
14745 (if (equal (caar tbl) :grouptags)
14746 (org-add-props tg nil 'face 'org-tag-group))
14747 (if (and (= cnt 0) (not ingroup)) (insert " "))
14748 (insert "[" c "] " tg (make-string
14749 (- fwidth 4 (length tg)) ?\ ))
14750 (push (cons tg c) ntable)
14751 (when (= (setq cnt (1+ cnt)) ncol)
14752 (insert "\n")
14753 (if ingroup (insert " "))
14754 (setq cnt 0)))))
14755 (setq ntable (nreverse ntable))
14756 (insert "\n")
14757 (goto-char (point-min))
14758 (if (not expert) (org-fit-window-to-buffer))
14759 (setq rtn
14760 (catch 'exit
14761 (while t
14762 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14763 (if (not groups) "no " "")
14764 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14765 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14766 (setq org-last-tag-selection-key c)
14767 (cond
14768 ((= c ?\r) (throw 'exit t))
14769 ((= c ?!)
14770 (setq groups (not groups))
14771 (goto-char (point-min))
14772 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14773 ((= c ?\C-c)
14774 (if (not expert)
14775 (org-fast-tag-show-exit
14776 (setq exit-after-next (not exit-after-next)))
14777 (setq expert nil)
14778 (delete-other-windows)
14779 (set-window-buffer (split-window-vertically) " *Org tags*")
14780 (org-switch-to-buffer-other-window " *Org tags*")
14781 (org-fit-window-to-buffer)))
14782 ((or (= c ?\C-g)
14783 (and (= c ?q) (not (rassoc c ntable))))
14784 (org-detach-overlay org-tags-overlay)
14785 (setq quit-flag t))
14786 ((= c ?\ )
14787 (setq current nil)
14788 (if exit-after-next (setq exit-after-next 'now)))
14789 ((= c ?\t)
14790 (condition-case nil
14791 (setq tg (org-icompleting-read
14792 "Tag: "
14793 (or buffer-tags
14794 (with-current-buffer buf
14795 (org-get-buffer-tags)))))
14796 (quit (setq tg "")))
14797 (when (string-match "\\S-" tg)
14798 (add-to-list 'buffer-tags (list tg))
14799 (if (member tg current)
14800 (setq current (delete tg current))
14801 (push tg current)))
14802 (if exit-after-next (setq exit-after-next 'now)))
14803 ((setq e (rassoc c todo-table) tg (car e))
14804 (with-current-buffer buf
14805 (save-excursion (org-todo tg)))
14806 (if exit-after-next (setq exit-after-next 'now)))
14807 ((setq e (rassoc c ntable) tg (car e))
14808 (if (member tg current)
14809 (setq current (delete tg current))
14810 (loop for g in groups do
14811 (if (member tg g)
14812 (mapc (lambda (x)
14813 (setq current (delete x current)))
14814 g)))
14815 (push tg current))
14816 (if exit-after-next (setq exit-after-next 'now))))
14818 ;; Create a sorted list
14819 (setq current
14820 (sort current
14821 (lambda (a b)
14822 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14823 (if (eq exit-after-next 'now) (throw 'exit t))
14824 (goto-char (point-min))
14825 (beginning-of-line 2)
14826 (delete-region (point) (point-at-eol))
14827 (org-fast-tag-insert "Current" current c-face)
14828 (org-set-current-tags-overlay current ov-prefix)
14829 (while (re-search-forward
14830 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14831 (setq tg (match-string 1))
14832 (add-text-properties
14833 (match-beginning 1) (match-end 1)
14834 (list 'face
14835 (cond
14836 ((member tg current) c-face)
14837 ((member tg inherited) i-face)
14838 (t (get-text-property (match-beginning 1) 'face))))))
14839 (goto-char (point-min)))))
14840 (org-detach-overlay org-tags-overlay)
14841 (if rtn
14842 (mapconcat 'identity current ":")
14843 nil))))
14845 (defun org-get-tags-string ()
14846 "Get the TAGS string in the current headline."
14847 (unless (org-at-heading-p t)
14848 (user-error "Not on a heading"))
14849 (save-excursion
14850 (beginning-of-line 1)
14851 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14852 (org-match-string-no-properties 1)
14853 "")))
14855 (defun org-get-tags ()
14856 "Get the list of tags specified in the current headline."
14857 (org-split-string (org-get-tags-string) ":"))
14859 (defun org-get-buffer-tags ()
14860 "Get a table of all tags used in the buffer, for completion."
14861 (let (tags)
14862 (save-excursion
14863 (goto-char (point-min))
14864 (while (re-search-forward
14865 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14866 (when (equal (char-after (point-at-bol 0)) ?*)
14867 (mapc (lambda (x) (add-to-list 'tags x))
14868 (org-split-string (org-match-string-no-properties 1) ":")))))
14869 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14870 (mapcar 'list tags)))
14872 ;;;; The mapping API
14874 (defun org-map-entries (func &optional match scope &rest skip)
14875 "Call FUNC at each headline selected by MATCH in SCOPE.
14877 FUNC is a function or a lisp form. The function will be called without
14878 arguments, with the cursor positioned at the beginning of the headline.
14879 The return values of all calls to the function will be collected and
14880 returned as a list.
14882 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14883 does not need to preserve point. After evaluation, the cursor will be
14884 moved to the end of the line (presumably of the headline of the
14885 processed entry) and search continues from there. Under some
14886 circumstances, this may not produce the wanted results. For example,
14887 if you have removed (e.g. archived) the current (sub)tree it could
14888 mean that the next entry will be skipped entirely. In such cases, you
14889 can specify the position from where search should continue by making
14890 FUNC set the variable `org-map-continue-from' to the desired buffer
14891 position.
14893 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14894 Only headlines that are matched by this query will be considered during
14895 the iteration. When MATCH is nil or t, all headlines will be
14896 visited by the iteration.
14898 SCOPE determines the scope of this command. It can be any of:
14900 nil The current buffer, respecting the restriction if any
14901 tree The subtree started with the entry at point
14902 region The entries within the active region, if any
14903 region-start-level
14904 The entries within the active region, but only those at
14905 the same level than the first one.
14906 file The current buffer, without restriction
14907 file-with-archives
14908 The current buffer, and any archives associated with it
14909 agenda All agenda files
14910 agenda-with-archives
14911 All agenda files with any archive files associated with them
14912 \(file1 file2 ...)
14913 If this is a list, all files in the list will be scanned
14915 The remaining args are treated as settings for the skipping facilities of
14916 the scanner. The following items can be given here:
14918 archive skip trees with the archive tag
14919 comment skip trees with the COMMENT keyword
14920 function or Emacs Lisp form:
14921 will be used as value for `org-agenda-skip-function', so
14922 whenever the function returns a position, FUNC will not be
14923 called for that entry and search will continue from the
14924 position returned
14926 If your function needs to retrieve the tags including inherited tags
14927 at the *current* entry, you can use the value of the variable
14928 `org-scanner-tags' which will be much faster than getting the value
14929 with `org-get-tags-at'. If your function gets properties with
14930 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14931 to t around the call to `org-entry-properties' to get the same speedup.
14932 Note that if your function moves around to retrieve tags and properties at
14933 a *different* entry, you cannot use these techniques."
14934 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14935 (not (org-region-active-p)))
14936 (let* ((org-agenda-archives-mode nil) ; just to make sure
14937 (org-agenda-skip-archived-trees (memq 'archive skip))
14938 (org-agenda-skip-comment-trees (memq 'comment skip))
14939 (org-agenda-skip-function
14940 (car (org-delete-all '(comment archive) skip)))
14941 (org-tags-match-list-sublevels t)
14942 (start-level (eq scope 'region-start-level))
14943 matcher file res
14944 org-todo-keywords-for-agenda
14945 org-done-keywords-for-agenda
14946 org-todo-keyword-alist-for-agenda
14947 org-drawers-for-agenda
14948 org-tag-alist-for-agenda
14949 todo-only)
14951 (cond
14952 ((eq match t) (setq matcher t))
14953 ((eq match nil) (setq matcher t))
14954 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14956 (save-window-excursion
14957 (save-restriction
14958 (cond ((eq scope 'tree)
14959 (org-back-to-heading t)
14960 (org-narrow-to-subtree)
14961 (setq scope nil))
14962 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14963 (org-region-active-p))
14964 ;; If needed, set start-level to a string like "2"
14965 (when start-level
14966 (save-excursion
14967 (goto-char (region-beginning))
14968 (unless (org-at-heading-p) (outline-next-heading))
14969 (setq start-level (org-current-level))))
14970 (narrow-to-region (region-beginning)
14971 (save-excursion
14972 (goto-char (region-end))
14973 (unless (and (bolp) (org-at-heading-p))
14974 (outline-next-heading))
14975 (point)))
14976 (setq scope nil)))
14978 (if (not scope)
14979 (progn
14980 (org-agenda-prepare-buffers
14981 (list (buffer-file-name (current-buffer))))
14982 (setq res (org-scan-tags func matcher todo-only start-level)))
14983 ;; Get the right scope
14984 (cond
14985 ((and scope (listp scope) (symbolp (car scope)))
14986 (setq scope (eval scope)))
14987 ((eq scope 'agenda)
14988 (setq scope (org-agenda-files t)))
14989 ((eq scope 'agenda-with-archives)
14990 (setq scope (org-agenda-files t))
14991 (setq scope (org-add-archive-files scope)))
14992 ((eq scope 'file)
14993 (setq scope (list (buffer-file-name))))
14994 ((eq scope 'file-with-archives)
14995 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14996 (org-agenda-prepare-buffers scope)
14997 (while (setq file (pop scope))
14998 (with-current-buffer (org-find-base-buffer-visiting file)
14999 (save-excursion
15000 (save-restriction
15001 (widen)
15002 (goto-char (point-min))
15003 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15004 res)))
15006 ;;;; Properties
15008 ;;; Setting and retrieving properties
15010 (defconst org-special-properties
15011 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15012 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15013 "The special properties valid in Org-mode.
15015 These are properties that are not defined in the property drawer,
15016 but in some other way.")
15018 (defconst org-default-properties
15019 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15020 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15021 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15022 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15023 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15024 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15025 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15026 "Some properties that are used by Org-mode for various purposes.
15027 Being in this list makes sure that they are offered for completion.")
15029 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15030 "Regular expression matching the first line of a property drawer.")
15032 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15033 "Regular expression matching the last line of a property drawer.")
15035 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15036 "Regular expression matching the first line of a property drawer.")
15038 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15039 "Regular expression matching the first line of a property drawer.")
15041 (defconst org-property-drawer-re
15042 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15043 org-property-end-re "\\)\n?")
15044 "Matches an entire property drawer.")
15046 (defconst org-clock-drawer-re
15047 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15048 org-property-end-re "\\)\n?")
15049 "Matches an entire clock drawer.")
15051 (defun org-property-action ()
15052 "Do an action on properties."
15053 (interactive)
15054 (let (c)
15055 (org-at-property-p)
15056 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15057 (setq c (read-char-exclusive))
15058 (cond
15059 ((equal c ?s)
15060 (call-interactively 'org-set-property))
15061 ((equal c ?d)
15062 (call-interactively 'org-delete-property))
15063 ((equal c ?D)
15064 (call-interactively 'org-delete-property-globally))
15065 ((equal c ?c)
15066 (call-interactively 'org-compute-property-at-point))
15067 (t (user-error "No such property action %c" c)))))
15069 (defun org-inc-effort ()
15070 "Increment the value of the effort property in the current entry."
15071 (interactive)
15072 (org-set-effort nil t))
15074 (defvar org-clock-effort) ;; Defined in org-clock.el
15075 (defvar org-clock-current-task) ;; Defined in org-clock.el
15076 (defun org-set-effort (&optional value increment)
15077 "Set the effort property of the current entry.
15078 With numerical prefix arg, use the nth allowed value, 0 stands for the
15079 10th allowed value.
15081 When INCREMENT is non-nil, set the property to the next allowed value."
15082 (interactive "P")
15083 (if (equal value 0) (setq value 10))
15084 (let* ((completion-ignore-case t)
15085 (prop org-effort-property)
15086 (cur (org-entry-get nil prop))
15087 (allowed (org-property-get-allowed-values nil prop 'table))
15088 (existing (mapcar 'list (org-property-values prop)))
15089 (heading (nth 4 (org-heading-components)))
15091 (val (cond
15092 ((stringp value) value)
15093 ((and allowed (integerp value))
15094 (or (car (nth (1- value) allowed))
15095 (car (org-last allowed))))
15096 ((and allowed increment)
15097 (or (caadr (member (list cur) allowed))
15098 (user-error "Allowed effort values are not set")))
15099 (allowed
15100 (message "Select 1-9,0, [RET%s]: %s"
15101 (if cur (concat "=" cur) "")
15102 (mapconcat 'car allowed " "))
15103 (setq rpl (read-char-exclusive))
15104 (if (equal rpl ?\r)
15106 (setq rpl (- rpl ?0))
15107 (if (equal rpl 0) (setq rpl 10))
15108 (if (and (> rpl 0) (<= rpl (length allowed)))
15109 (car (nth (1- rpl) allowed))
15110 (org-completing-read "Effort: " allowed nil))))
15112 (let (org-completion-use-ido org-completion-use-iswitchb)
15113 (org-completing-read
15114 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15115 (concat "[" cur "]") "")
15116 ": ")
15117 existing nil nil "" nil cur))))))
15118 (unless (equal (org-entry-get nil prop) val)
15119 (org-entry-put nil prop val))
15120 (save-excursion
15121 (org-back-to-heading t)
15122 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15123 (when (string= heading org-clock-current-task)
15124 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15125 (org-clock-update-mode-line))
15126 (message "%s is now %s" prop val)))
15128 (defun org-at-property-p ()
15129 "Is cursor inside a property drawer?"
15130 (save-excursion
15131 (when (equal 'node-property (car (org-element-at-point)))
15132 (beginning-of-line 1)
15133 (looking-at org-property-re))))
15135 (defun org-get-property-block (&optional beg end force)
15136 "Return the (beg . end) range of the body of the property drawer.
15137 BEG and END are the beginning and end of the current subtree, or of
15138 the part before the first headline. If they are not given, they will
15139 be found. If the drawer does not exist and FORCE is non-nil, create
15140 the drawer."
15141 (catch 'exit
15142 (save-excursion
15143 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15144 (progn (org-back-to-heading t) (point))))
15145 (end (or end (and (not (outline-next-heading)) (point-max))
15146 (point))))
15147 (goto-char beg)
15148 (if (re-search-forward org-property-start-re end t)
15149 (setq beg (1+ (match-end 0)))
15150 (if force
15151 (save-excursion
15152 (org-insert-property-drawer)
15153 (setq end (progn (outline-next-heading) (point))))
15154 (throw 'exit nil))
15155 (goto-char beg)
15156 (if (re-search-forward org-property-start-re end t)
15157 (setq beg (1+ (match-end 0)))))
15158 (if (re-search-forward org-property-end-re end t)
15159 (setq end (match-beginning 0))
15160 (or force (throw 'exit nil))
15161 (goto-char beg)
15162 (setq end beg)
15163 (org-indent-line)
15164 (insert ":END:\n"))
15165 (cons beg end)))))
15167 (defun org-entry-properties (&optional pom which specific)
15168 "Get all properties of the entry at point-or-marker POM.
15169 This includes the TODO keyword, the tags, time strings for deadline,
15170 scheduled, and clocking, and any additional properties defined in the
15171 entry. The return value is an alist, keys may occur multiple times
15172 if the property key was used several times.
15173 POM may also be nil, in which case the current entry is used.
15174 If WHICH is nil or `all', get all properties. If WHICH is
15175 `special' or `standard', only get that subclass. If WHICH
15176 is a string only get exactly this property. SPECIFIC can be a string, the
15177 specific property we are interested in. Specifying it can speed
15178 things up because then unnecessary parsing is avoided."
15179 (setq which (or which 'all))
15180 (org-with-wide-buffer
15181 (org-with-point-at pom
15182 (let ((clockstr (substring org-clock-string 0 -1))
15183 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15184 (case-fold-search nil)
15185 beg end range props sum-props key key1 value string clocksum clocksumt)
15186 (when (and (derived-mode-p 'org-mode)
15187 (ignore-errors (org-back-to-heading t)))
15188 (setq beg (point))
15189 (setq sum-props (get-text-property (point) 'org-summaries))
15190 (setq clocksum (get-text-property (point) :org-clock-minutes)
15191 clocksumt (get-text-property (point) :org-clock-minutes-today))
15192 (outline-next-heading)
15193 (setq end (point))
15194 (when (memq which '(all special))
15195 ;; Get the special properties, like TODO and tags
15196 (goto-char beg)
15197 (when (and (or (not specific) (string= specific "TODO"))
15198 (looking-at org-todo-line-regexp) (match-end 2))
15199 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15200 (when (and (or (not specific) (string= specific "PRIORITY"))
15201 (looking-at org-priority-regexp))
15202 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15203 (when (or (not specific) (string= specific "FILE"))
15204 (push (cons "FILE" buffer-file-name) props))
15205 (when (and (or (not specific) (string= specific "TAGS"))
15206 (setq value (org-get-tags-string))
15207 (string-match "\\S-" value))
15208 (push (cons "TAGS" value) props))
15209 (when (and (or (not specific) (string= specific "ALLTAGS"))
15210 (setq value (org-get-tags-at)))
15211 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15212 ":"))
15213 props))
15214 (when (or (not specific) (string= specific "BLOCKED"))
15215 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15216 (when (or (not specific)
15217 (member specific
15218 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15219 "TIMESTAMP" "TIMESTAMP_IA")))
15220 (catch 'match
15221 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15222 (setq key (if (match-end 1)
15223 (substring (org-match-string-no-properties 1)
15224 0 -1))
15225 string (if (equal key clockstr)
15226 (org-trim
15227 (buffer-substring-no-properties
15228 (match-beginning 3) (goto-char
15229 (point-at-eol))))
15230 (substring (org-match-string-no-properties 3)
15231 1 -1)))
15232 ;; Get the correct property name from the key. This is
15233 ;; necessary if the user has configured time keywords.
15234 (setq key1 (concat key ":"))
15235 (cond
15236 ((not key)
15237 (setq key
15238 (if (= (char-after (match-beginning 3)) ?\[)
15239 "TIMESTAMP_IA" "TIMESTAMP")))
15240 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15241 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15242 ((equal key1 org-closed-string) (setq key "CLOSED"))
15243 ((equal key1 org-clock-string) (setq key "CLOCK")))
15244 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15245 (progn
15246 (push (cons key string) props)
15247 ;; no need to search further if match is found
15248 (throw 'match t))
15249 (when (or (equal key "CLOCK") (not (assoc key props)))
15250 (push (cons key string) props)))))))
15252 (when (memq which '(all standard))
15253 ;; Get the standard properties, like :PROP: ...
15254 (setq range (org-get-property-block beg end))
15255 (when range
15256 (goto-char (car range))
15257 (while (re-search-forward org-property-re
15258 (cdr range) t)
15259 (setq key (org-match-string-no-properties 2)
15260 value (org-trim (or (org-match-string-no-properties 3) "")))
15261 (unless (member key excluded)
15262 (push (cons key (or value "")) props)))))
15263 (if clocksum
15264 (push (cons "CLOCKSUM"
15265 (org-columns-number-to-string (/ (float clocksum) 60.)
15266 'add_times))
15267 props))
15268 (if clocksumt
15269 (push (cons "CLOCKSUM_T"
15270 (org-columns-number-to-string (/ (float clocksumt) 60.)
15271 'add_times))
15272 props))
15273 (unless (assoc "CATEGORY" props)
15274 (push (cons "CATEGORY" (org-get-category)) props))
15275 (append sum-props (nreverse props)))))))
15277 (defun org-entry-get (pom property &optional inherit literal-nil)
15278 "Get value of PROPERTY for entry or content at point-or-marker POM.
15279 If INHERIT is non-nil and the entry does not have the property,
15280 then also check higher levels of the hierarchy.
15281 If INHERIT is the symbol `selective', use inheritance only if the setting
15282 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15283 If the property is present but empty, the return value is the empty string.
15284 If the property is not present at all, nil is returned.
15286 Return the value as a string.
15288 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15289 do not interpret it as the list atom nil. This is used for inheritance
15290 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15291 (org-with-point-at pom
15292 (if (and inherit (if (eq inherit 'selective)
15293 (org-property-inherit-p property)
15295 (org-entry-get-with-inheritance property literal-nil)
15296 (if (member property org-special-properties)
15297 ;; We need a special property. Use `org-entry-properties'
15298 ;; to retrieve it, but specify the wanted property
15299 (cdr (assoc property (org-entry-properties nil 'special property)))
15300 (org-with-wide-buffer
15301 (let ((range (org-get-property-block)))
15302 (when (and range (not (eq (car range) (cdr range))))
15303 (let* ((props
15304 (list (or (assoc property org-file-properties)
15305 (assoc property org-global-properties)
15306 (assoc property org-global-properties-fixed))))
15307 (ap (lambda (key)
15308 (when (re-search-forward
15309 (org-re-property key) (cdr range) t)
15310 (setq props
15311 (org-update-property-plist
15313 (if (match-end 3)
15314 (org-match-string-no-properties 3) "")
15315 props)))))
15316 val)
15317 (goto-char (car range))
15318 (funcall ap property)
15319 (goto-char (car range))
15320 (while (funcall ap (concat property "+")))
15321 (setq val (cdr (assoc property props)))
15322 (when val (if literal-nil val (org-not-nil val)))))))))))
15324 (defun org-property-or-variable-value (var &optional inherit)
15325 "Check if there is a property fixing the value of VAR.
15326 If yes, return this value. If not, return the current value of the variable."
15327 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15328 (if (and prop (stringp prop) (string-match "\\S-" prop))
15329 (read prop)
15330 (symbol-value var))))
15332 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15333 "Delete the property PROPERTY from entry at point-or-marker POM.
15334 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15335 an empty drawer to delete."
15336 (org-with-point-at pom
15337 (if (member property org-special-properties)
15338 nil ; cannot delete these properties.
15339 (let ((range (org-get-property-block)))
15340 (if (and range
15341 (goto-char (car range))
15342 (re-search-forward
15343 (org-re-property property)
15344 (cdr range) t))
15345 (progn
15346 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15347 (and delete-empty-drawer
15348 (org-remove-empty-drawer-at
15349 delete-empty-drawer (car range)))
15351 nil)))))
15353 ;; Multi-values properties are properties that contain multiple values
15354 ;; These values are assumed to be single words, separated by whitespace.
15355 (defun org-entry-add-to-multivalued-property (pom property value)
15356 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15357 (let* ((old (org-entry-get pom property))
15358 (values (and old (org-split-string old "[ \t]"))))
15359 (setq value (org-entry-protect-space value))
15360 (unless (member value values)
15361 (setq values (append values (list value)))
15362 (org-entry-put pom property
15363 (mapconcat 'identity values " ")))))
15365 (defun org-entry-remove-from-multivalued-property (pom property value)
15366 "Remove VALUE from 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 (when (member value values)
15371 (setq values (delete value values))
15372 (org-entry-put pom property
15373 (mapconcat 'identity values " ")))))
15375 (defun org-entry-member-in-multivalued-property (pom property value)
15376 "Is VALUE one of the 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 (member value values)))
15382 (defun org-entry-get-multivalued-property (pom property)
15383 "Return a list of values in a multivalued property."
15384 (let* ((value (org-entry-get pom property))
15385 (values (and value (org-split-string value "[ \t]"))))
15386 (mapcar 'org-entry-restore-space values)))
15388 (defun org-entry-put-multivalued-property (pom property &rest values)
15389 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15390 VALUES should be a list of strings. Spaces will be protected."
15391 (org-entry-put pom property
15392 (mapconcat 'org-entry-protect-space values " "))
15393 (let* ((value (org-entry-get pom property))
15394 (values (and value (org-split-string value "[ \t]"))))
15395 (mapcar 'org-entry-restore-space values)))
15397 (defun org-entry-protect-space (s)
15398 "Protect spaces and newline in string S."
15399 (while (string-match " " s)
15400 (setq s (replace-match "%20" t t s)))
15401 (while (string-match "\n" s)
15402 (setq s (replace-match "%0A" t t s)))
15405 (defun org-entry-restore-space (s)
15406 "Restore spaces and newline in string S."
15407 (while (string-match "%20" s)
15408 (setq s (replace-match " " t t s)))
15409 (while (string-match "%0A" s)
15410 (setq s (replace-match "\n" t t s)))
15413 (defvar org-entry-property-inherited-from (make-marker)
15414 "Marker pointing to the entry from where a property was inherited.
15415 Each call to `org-entry-get-with-inheritance' will set this marker to the
15416 location of the entry where the inheritance search matched. If there was
15417 no match, the marker will point nowhere.
15418 Note that also `org-entry-get' calls this function, if the INHERIT flag
15419 is set.")
15421 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15422 "Get PROPERTY of entry or content at point, search higher levels if needed.
15423 The search will stop at the first ancestor which has the property defined.
15424 If the value found is \"nil\", return nil to show that the property
15425 should be considered as undefined (this is the meaning of nil here).
15426 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15427 (move-marker org-entry-property-inherited-from nil)
15428 (let (tmp)
15429 (save-excursion
15430 (save-restriction
15431 (widen)
15432 (catch 'ex
15433 (while t
15434 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15435 (or (ignore-errors (org-back-to-heading t))
15436 (goto-char (point-min)))
15437 (move-marker org-entry-property-inherited-from (point))
15438 (throw 'ex tmp))
15439 (or (ignore-errors (org-up-heading-safe))
15440 (throw 'ex nil))))))
15441 (setq tmp (or tmp
15442 (cdr (assoc property org-file-properties))
15443 (cdr (assoc property org-global-properties))
15444 (cdr (assoc property org-global-properties-fixed))))
15445 (if literal-nil tmp (org-not-nil tmp))))
15447 (defvar org-property-changed-functions nil
15448 "Hook called when the value of a property has changed.
15449 Each hook function should accept two arguments, the name of the property
15450 and the new value.")
15452 (defun org-entry-put (pom property value)
15453 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15454 If the value is `nil', it is converted to the empty string.
15455 If it is not a string, an error is raised."
15456 (cond ((null value) (setq value ""))
15457 ((not (stringp value))
15458 (error "Properties values should be strings.")))
15459 (org-with-point-at pom
15460 (org-back-to-heading t)
15461 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15462 range)
15463 (cond
15464 ((equal property "TODO")
15465 (when (and (string-match "\\S-" value)
15466 (not (member value org-todo-keywords-1)))
15467 (user-error "\"%s\" is not a valid TODO state" value))
15468 (if (or (not value)
15469 (not (string-match "\\S-" value)))
15470 (setq value 'none))
15471 (org-todo value)
15472 (org-set-tags nil 'align))
15473 ((equal property "PRIORITY")
15474 (org-priority (if (and value (string-match "\\S-" value))
15475 (string-to-char value) ?\ ))
15476 (org-set-tags nil 'align))
15477 ((equal property "CLOCKSUM")
15478 (if (not (re-search-forward
15479 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15480 (error "Cannot find a clock log")
15481 (goto-char (- (match-end 1) 2))
15482 (cond
15483 ((eq value 'earlier) (org-timestamp-down))
15484 ((eq value 'later) (org-timestamp-up)))
15485 (org-clock-sum-current-item)))
15486 ((equal property "SCHEDULED")
15487 (if (re-search-forward org-scheduled-time-regexp end t)
15488 (cond
15489 ((eq value 'earlier) (org-timestamp-change -1 'day))
15490 ((eq value 'later) (org-timestamp-change 1 'day))
15491 (t (call-interactively 'org-schedule)))
15492 (call-interactively 'org-schedule)))
15493 ((equal property "DEADLINE")
15494 (if (re-search-forward org-deadline-time-regexp end t)
15495 (cond
15496 ((eq value 'earlier) (org-timestamp-change -1 'day))
15497 ((eq value 'later) (org-timestamp-change 1 'day))
15498 (t (call-interactively 'org-deadline)))
15499 (call-interactively 'org-deadline)))
15500 ((member property org-special-properties)
15501 (error "The %s property can not yet be set with `org-entry-put'"
15502 property))
15503 (t ; a non-special property
15504 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15505 (setq range (org-get-property-block beg end 'force))
15506 (goto-char (car range))
15507 (if (re-search-forward
15508 (org-re-property property) (cdr range) t)
15509 (progn
15510 (delete-region (match-beginning 0) (match-end 0))
15511 (goto-char (match-beginning 0)))
15512 (goto-char (cdr range))
15513 (insert "\n")
15514 (backward-char 1)
15515 (org-indent-line))
15516 (insert ":" property ":")
15517 (and value (insert " " value))
15518 (org-indent-line)))))
15519 (run-hook-with-args 'org-property-changed-functions property value)))
15521 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15522 "Get all property keys in the current buffer.
15523 With INCLUDE-SPECIALS, also list the special properties that reflect things
15524 like tags and TODO state.
15525 With INCLUDE-DEFAULTS, also include properties that has special meaning
15526 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15527 and others.
15528 With INCLUDE-COLUMNS, also include property names given in COLUMN
15529 formats in the current buffer."
15530 (let (rtn range cfmt s p)
15531 (save-excursion
15532 (save-restriction
15533 (widen)
15534 (goto-char (point-min))
15535 (while (re-search-forward org-property-start-re nil t)
15536 (setq range (org-get-property-block))
15537 (goto-char (car range))
15538 (while (re-search-forward org-property-re
15539 (cdr range) t)
15540 (add-to-list 'rtn (org-match-string-no-properties 2)))
15541 (outline-next-heading))))
15543 (when include-specials
15544 (setq rtn (append org-special-properties rtn)))
15546 (when include-defaults
15547 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15548 (add-to-list 'rtn org-effort-property))
15550 (when include-columns
15551 (save-excursion
15552 (save-restriction
15553 (widen)
15554 (goto-char (point-min))
15555 (while (re-search-forward
15556 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15557 nil t)
15558 (setq cfmt (match-string 2) s 0)
15559 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15560 cfmt s)
15561 (setq s (match-end 0)
15562 p (match-string 1 cfmt))
15563 (unless (or (equal p "ITEM")
15564 (member p org-special-properties))
15565 (add-to-list 'rtn (match-string 1 cfmt))))))))
15567 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15569 (defun org-property-values (key)
15570 "Return a list of all values of property KEY in the current buffer."
15571 (save-excursion
15572 (save-restriction
15573 (widen)
15574 (goto-char (point-min))
15575 (let ((re (org-re-property key))
15576 values)
15577 (while (re-search-forward re nil t)
15578 (add-to-list 'values (org-trim (match-string 3))))
15579 (delete "" values)))))
15581 (defun org-insert-property-drawer ()
15582 "Insert a property drawer into the current entry."
15583 (org-back-to-heading t)
15584 (looking-at org-outline-regexp)
15585 (let ((indent (if org-adapt-indentation
15586 (- (match-end 0) (match-beginning 0))
15588 (beg (point))
15589 (re (concat "^[ \t]*" org-keyword-time-regexp))
15590 end hiddenp)
15591 (outline-next-heading)
15592 (setq end (point))
15593 (goto-char beg)
15594 (while (re-search-forward re end t))
15595 (setq hiddenp (outline-invisible-p))
15596 (end-of-line 1)
15597 (and (equal (char-after) ?\n) (forward-char 1))
15598 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15599 (if (member (match-string 1) '("CLOCK:" ":END:"))
15600 ;; just skip this line
15601 (beginning-of-line 2)
15602 ;; Drawer start, find the end
15603 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15604 (beginning-of-line 1)))
15605 (org-skip-over-state-notes)
15606 (skip-chars-backward " \t\n\r")
15607 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15608 (forward-char 1))
15609 (goto-char (point-at-eol))
15610 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15611 (beginning-of-line 0)
15612 (org-indent-to-column indent)
15613 (beginning-of-line 2)
15614 (org-indent-to-column indent)
15615 (beginning-of-line 0)
15616 (if hiddenp
15617 (save-excursion
15618 (org-back-to-heading t)
15619 (hide-entry))
15620 (org-flag-drawer t))))
15622 (defun org-insert-drawer (&optional arg drawer)
15623 "Insert a drawer at point.
15625 Optional argument DRAWER, when non-nil, is a string representing
15626 drawer's name. Otherwise, the user is prompted for a name.
15628 If a region is active, insert the drawer around that region
15629 instead.
15631 Point is left between drawer's boundaries."
15632 (interactive "P")
15633 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15634 "LOGBOOK"))
15635 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15636 ;; internally by Org. They are meant to be inserted
15637 ;; automatically.
15638 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15639 ;; Remove system drawers from list. Note: For some reason,
15640 ;; `org-completing-read' ignores the predicate while
15641 ;; `completing-read' handles it fine.
15642 (drawer (if arg "PROPERTIES"
15643 (or drawer
15644 (completing-read
15645 "Drawer: " org-drawers
15646 (lambda (d) (not (member d system-drawers))))))))
15647 (cond
15648 ;; With C-u, fall back on `org-insert-property-drawer'
15649 (arg (org-insert-property-drawer))
15650 ;; With an active region, insert a drawer at point.
15651 ((not (org-region-active-p))
15652 (progn
15653 (unless (bolp) (insert "\n"))
15654 (insert (format ":%s:\n\n:END:\n" drawer))
15655 (forward-line -2)))
15656 ;; Otherwise, insert the drawer at point
15658 (let ((rbeg (region-beginning))
15659 (rend (copy-marker (region-end))))
15660 (unwind-protect
15661 (progn
15662 (goto-char rbeg)
15663 (beginning-of-line)
15664 (when (save-excursion
15665 (re-search-forward org-outline-regexp-bol rend t))
15666 (user-error "Drawers cannot contain headlines"))
15667 ;; Position point at the beginning of the first
15668 ;; non-blank line in region. Insert drawer's opening
15669 ;; there, then indent it.
15670 (org-skip-whitespace)
15671 (beginning-of-line)
15672 (insert ":" drawer ":\n")
15673 (forward-line -1)
15674 (indent-for-tab-command)
15675 ;; Move point to the beginning of the first blank line
15676 ;; after the last non-blank line in region. Insert
15677 ;; drawer's closing, then indent it.
15678 (goto-char rend)
15679 (skip-chars-backward " \r\t\n")
15680 (insert "\n:END:")
15681 (deactivate-mark t)
15682 (indent-for-tab-command)
15683 (unless (eolp) (insert "\n")))
15684 ;; Clear marker, whatever the outcome of insertion is.
15685 (set-marker rend nil)))))))
15687 (defvar org-property-set-functions-alist nil
15688 "Property set function alist.
15689 Each entry should have the following format:
15691 (PROPERTY . READ-FUNCTION)
15693 The read function will be called with the same argument as
15694 `org-completing-read'.")
15696 (defun org-set-property-function (property)
15697 "Get the function that should be used to set PROPERTY.
15698 This is computed according to `org-property-set-functions-alist'."
15699 (or (cdr (assoc property org-property-set-functions-alist))
15700 'org-completing-read))
15702 (defun org-read-property-value (property)
15703 "Read PROPERTY value from user."
15704 (let* ((completion-ignore-case t)
15705 (allowed (org-property-get-allowed-values nil property 'table))
15706 (cur (org-entry-get nil property))
15707 (prompt (concat property " value"
15708 (if (and cur (string-match "\\S-" cur))
15709 (concat " [" cur "]") "") ": "))
15710 (set-function (org-set-property-function property))
15711 (val (if allowed
15712 (funcall set-function prompt allowed nil
15713 (not (get-text-property 0 'org-unrestricted
15714 (caar allowed))))
15715 (let (org-completion-use-ido org-completion-use-iswitchb)
15716 (funcall set-function prompt
15717 (mapcar 'list (org-property-values property))
15718 nil nil "" nil cur)))))
15719 (if (equal val "")
15721 val)))
15723 (defvar org-last-set-property nil)
15724 (defvar org-last-set-property-value nil)
15725 (defun org-read-property-name ()
15726 "Read a property name."
15727 (let* ((completion-ignore-case t)
15728 (keys (org-buffer-property-keys nil t t))
15729 (default-prop (or (save-excursion
15730 (save-match-data
15731 (beginning-of-line)
15732 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15733 (null (string= (match-string 1) "END"))
15734 (match-string 1))))
15735 org-last-set-property))
15736 (property (org-icompleting-read
15737 (concat "Property"
15738 (if default-prop (concat " [" default-prop "]") "")
15739 ": ")
15740 (mapcar 'list keys)
15741 nil nil nil nil
15742 default-prop)))
15743 (if (member property keys)
15744 property
15745 (or (cdr (assoc (downcase property)
15746 (mapcar (lambda (x) (cons (downcase x) x))
15747 keys)))
15748 property))))
15750 (defun org-set-property-and-value (use-last)
15751 "Allow to set [PROPERTY]: [value] direction from prompt.
15752 When use-default, don't even ask, just use the last
15753 \"[PROPERTY]: [value]\" string from the history."
15754 (interactive "P")
15755 (let* ((completion-ignore-case t)
15756 (pv (or (and use-last org-last-set-property-value)
15757 (org-completing-read
15758 "Enter a \"[Property]: [value]\" pair: "
15759 nil nil nil nil nil
15760 org-last-set-property-value)))
15761 prop val)
15762 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15763 (setq prop (match-string 1 pv)
15764 val (match-string 2 pv))
15765 (org-set-property prop val))))
15767 (defun org-set-property (property value)
15768 "In the current entry, set PROPERTY to VALUE.
15769 When called interactively, this will prompt for a property name, offering
15770 completion on existing and default properties. And then it will prompt
15771 for a value, offering completion either on allowed values (via an inherited
15772 xxx_ALL property) or on existing values in other instances of this property
15773 in the current file."
15774 (interactive (list nil nil))
15775 (let* ((property (or property (org-read-property-name)))
15776 (value (or value (org-read-property-value property)))
15777 (fn (cdr (assoc property org-properties-postprocess-alist))))
15778 (setq org-last-set-property property)
15779 (setq org-last-set-property-value (concat property ": " value))
15780 ;; Possibly postprocess the inserted value:
15781 (when fn (setq value (funcall fn value)))
15782 (unless (equal (org-entry-get nil property) value)
15783 (org-entry-put nil property value))))
15785 (defun org-delete-property (property &optional delete-empty-drawer)
15786 "In the current entry, delete PROPERTY.
15787 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15788 an empty drawer to delete."
15789 (interactive
15790 (let* ((completion-ignore-case t)
15791 (prop (org-icompleting-read "Property: "
15792 (org-entry-properties nil 'standard))))
15793 (list prop)))
15794 (message "Property %s %s" property
15795 (if (org-entry-delete nil property delete-empty-drawer)
15796 "deleted"
15797 "was not present in the entry")))
15799 (defun org-delete-property-globally (property)
15800 "Remove PROPERTY globally, from all entries."
15801 (interactive
15802 (let* ((completion-ignore-case t)
15803 (prop (org-icompleting-read
15804 "Globally remove property: "
15805 (mapcar 'list (org-buffer-property-keys)))))
15806 (list prop)))
15807 (save-excursion
15808 (save-restriction
15809 (widen)
15810 (goto-char (point-min))
15811 (let ((cnt 0))
15812 (while (re-search-forward
15813 (org-re-property property)
15814 nil t)
15815 (setq cnt (1+ cnt))
15816 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15817 (message "Property \"%s\" removed from %d entries" property cnt)))))
15819 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15821 (defun org-compute-property-at-point ()
15822 "Compute the property at point.
15823 This looks for an enclosing column format, extracts the operator and
15824 then applies it to the property in the column format's scope."
15825 (interactive)
15826 (unless (org-at-property-p)
15827 (user-error "Not at a property"))
15828 (let ((prop (org-match-string-no-properties 2)))
15829 (org-columns-get-format-and-top-level)
15830 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15831 (user-error "No operator defined for property %s" prop))
15832 (org-columns-compute prop)))
15834 (defvar org-property-allowed-value-functions nil
15835 "Hook for functions supplying allowed values for a specific property.
15836 The functions must take a single argument, the name of the property, and
15837 return a flat list of allowed values. If \":ETC\" is one of
15838 the values, this means that these values are intended as defaults for
15839 completion, but that other values should be allowed too.
15840 The functions must return nil if they are not responsible for this
15841 property.")
15843 (defun org-property-get-allowed-values (pom property &optional table)
15844 "Get allowed values for the property PROPERTY.
15845 When TABLE is non-nil, return an alist that can directly be used for
15846 completion."
15847 (let (vals)
15848 (cond
15849 ((equal property "TODO")
15850 (setq vals (org-with-point-at pom
15851 (append org-todo-keywords-1 '("")))))
15852 ((equal property "PRIORITY")
15853 (let ((n org-lowest-priority))
15854 (while (>= n org-highest-priority)
15855 (push (char-to-string n) vals)
15856 (setq n (1- n)))))
15857 ((member property org-special-properties))
15858 ((setq vals (run-hook-with-args-until-success
15859 'org-property-allowed-value-functions property)))
15861 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15862 (when (and vals (string-match "\\S-" vals))
15863 (setq vals (car (read-from-string (concat "(" vals ")"))))
15864 (setq vals (mapcar (lambda (x)
15865 (cond ((stringp x) x)
15866 ((numberp x) (number-to-string x))
15867 ((symbolp x) (symbol-name x))
15868 (t "???")))
15869 vals)))))
15870 (when (member ":ETC" vals)
15871 (setq vals (remove ":ETC" vals))
15872 (org-add-props (car vals) '(org-unrestricted t)))
15873 (if table (mapcar 'list vals) vals)))
15875 (defun org-property-previous-allowed-value (&optional previous)
15876 "Switch to the next allowed value for this property."
15877 (interactive)
15878 (org-property-next-allowed-value t))
15880 (defun org-property-next-allowed-value (&optional previous)
15881 "Switch to the next allowed value for this property."
15882 (interactive)
15883 (unless (org-at-property-p)
15884 (user-error "Not at a property"))
15885 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15886 (key (match-string 2))
15887 (value (match-string 3))
15888 (allowed (or (org-property-get-allowed-values (point) key)
15889 (and (member value '("[ ]" "[-]" "[X]"))
15890 '("[ ]" "[X]"))))
15891 (heading (save-match-data (nth 4 (org-heading-components))))
15892 nval)
15893 (unless allowed
15894 (user-error "Allowed values for this property have not been defined"))
15895 (if previous (setq allowed (reverse allowed)))
15896 (if (member value allowed)
15897 (setq nval (car (cdr (member value allowed)))))
15898 (setq nval (or nval (car allowed)))
15899 (if (equal nval value)
15900 (user-error "Only one allowed value for this property"))
15901 (org-at-property-p)
15902 (replace-match (concat " :" key ": " nval) t t)
15903 (org-indent-line)
15904 (beginning-of-line 1)
15905 (skip-chars-forward " \t")
15906 (when (equal prop org-effort-property)
15907 (save-excursion
15908 (org-back-to-heading t)
15909 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15910 (when (string= org-clock-current-task heading)
15911 (setq org-clock-effort nval)
15912 (org-clock-update-mode-line)))
15913 (run-hook-with-args 'org-property-changed-functions key nval)))
15915 (defun org-find-olp (path &optional this-buffer)
15916 "Return a marker pointing to the entry at outline path OLP.
15917 If anything goes wrong, throw an error.
15918 You can wrap this call to catch the error like this:
15920 (condition-case msg
15921 (org-mobile-locate-entry (match-string 4))
15922 (error (nth 1 msg)))
15924 The return value will then be either a string with the error message,
15925 or a marker if everything is OK.
15927 If THIS-BUFFER is set, the outline path does not contain a file,
15928 only headings."
15929 (let* ((file (if this-buffer buffer-file-name (pop path)))
15930 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15931 (level 1)
15932 (lmin 1)
15933 (lmax 1)
15934 limit re end found pos heading cnt flevel)
15935 (unless buffer (error "File not found :%s" file))
15936 (with-current-buffer buffer
15937 (save-excursion
15938 (save-restriction
15939 (widen)
15940 (setq limit (point-max))
15941 (goto-char (point-min))
15942 (while (setq heading (pop path))
15943 (setq re (format org-complex-heading-regexp-format
15944 (regexp-quote heading)))
15945 (setq cnt 0 pos (point))
15946 (while (re-search-forward re end t)
15947 (setq level (- (match-end 1) (match-beginning 1)))
15948 (if (and (>= level lmin) (<= level lmax))
15949 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15950 (when (= cnt 0) (error "Heading not found on level %d: %s"
15951 lmax heading))
15952 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15953 lmax heading))
15954 (goto-char found)
15955 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15956 (setq end (save-excursion (org-end-of-subtree t t))))
15957 (when (org-at-heading-p)
15958 (point-marker)))))))
15960 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15961 "Find node HEADING in BUFFER.
15962 Return a marker to the heading if it was found, or nil if not.
15963 If POS-ONLY is set, return just the position instead of a marker.
15965 The heading text must match exact, but it may have a TODO keyword,
15966 a priority cookie and tags in the standard locations."
15967 (with-current-buffer (or buffer (current-buffer))
15968 (save-excursion
15969 (save-restriction
15970 (widen)
15971 (goto-char (point-min))
15972 (let (case-fold-search)
15973 (if (re-search-forward
15974 (format org-complex-heading-regexp-format
15975 (regexp-quote heading)) nil t)
15976 (if pos-only
15977 (match-beginning 0)
15978 (move-marker (make-marker) (match-beginning 0)))))))))
15980 (defun org-find-exact-heading-in-directory (heading &optional dir)
15981 "Find Org node headline HEADING in all .org files in directory DIR.
15982 When the target headline is found, return a marker to this location."
15983 (let ((files (directory-files (or dir default-directory)
15984 nil "\\`[^.#].*\\.org\\'"))
15985 file visiting m buffer)
15986 (catch 'found
15987 (while (setq file (pop files))
15988 (message "trying %s" file)
15989 (setq visiting (org-find-base-buffer-visiting file))
15990 (setq buffer (or visiting (find-file-noselect file)))
15991 (setq m (org-find-exact-headline-in-buffer
15992 heading buffer))
15993 (when (and (not m) (not visiting)) (kill-buffer buffer))
15994 (and m (throw 'found m))))))
15996 (defun org-find-entry-with-id (ident)
15997 "Locate the entry that contains the ID property with exact value IDENT.
15998 IDENT can be a string, a symbol or a number, this function will search for
15999 the string representation of it.
16000 Return the position where this entry starts, or nil if there is no such entry."
16001 (interactive "sID: ")
16002 (let ((id (cond
16003 ((stringp ident) ident)
16004 ((symbol-name ident) (symbol-name ident))
16005 ((numberp ident) (number-to-string ident))
16006 (t (error "IDENT %s must be a string, symbol or number" ident))))
16007 (case-fold-search nil))
16008 (save-excursion
16009 (save-restriction
16010 (widen)
16011 (goto-char (point-min))
16012 (when (re-search-forward
16013 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16014 nil t)
16015 (org-back-to-heading t)
16016 (point))))))
16018 ;;;; Timestamps
16020 (defvar org-last-changed-timestamp nil)
16021 (defvar org-last-inserted-timestamp nil
16022 "The last time stamp inserted with `org-insert-time-stamp'.")
16023 (defvar org-ts-what) ; dynamically scoped parameter
16025 (defun org-time-stamp (arg &optional inactive)
16026 "Prompt for a date/time and insert a time stamp.
16027 If the user specifies a time like HH:MM or if this command is
16028 called with at least one prefix argument, the time stamp contains
16029 the date and the time. Otherwise, only the date is be included.
16031 All parts of a date not specified by the user is filled in from
16032 the current date/time. So if you just press return without
16033 typing anything, the time stamp will represent the current
16034 date/time.
16036 If there is already a timestamp at the cursor, it will be
16037 modified.
16039 With two universal prefix arguments, insert an active timestamp
16040 with the current time without prompting the user.
16042 When called from lisp, the timestamp is inactive if INACTIVE is
16043 non-nil."
16044 (interactive "P")
16045 (let* ((ts nil)
16046 (default-time
16047 ;; Default time is either today, or, when entering a range,
16048 ;; the range start.
16049 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16050 (save-excursion
16051 (re-search-backward
16052 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16053 (- (point) 20) t)))
16054 (apply 'encode-time (org-parse-time-string (match-string 1)))
16055 (current-time)))
16056 (default-input (and ts (org-get-compact-tod ts)))
16057 (repeater (save-excursion
16058 (save-match-data
16059 (beginning-of-line)
16060 (when (re-search-forward
16061 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16062 (save-excursion (progn (end-of-line) (point))) t)
16063 (match-string 0)))))
16064 org-time-was-given org-end-time-was-given time)
16065 (cond
16066 ((and (org-at-timestamp-p t)
16067 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16068 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16069 (insert "--")
16070 (setq time (let ((this-command this-command))
16071 (org-read-date arg 'totime nil nil
16072 default-time default-input inactive)))
16073 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16074 ((org-at-timestamp-p t)
16075 (setq time (let ((this-command this-command))
16076 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16077 (when (org-at-timestamp-p t) ; just to get the match data
16078 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16079 (replace-match "")
16080 (setq org-last-changed-timestamp
16081 (org-insert-time-stamp
16082 time (or org-time-was-given arg)
16083 inactive nil nil (list org-end-time-was-given)))
16084 (when repeater (goto-char (1- (point))) (insert " " repeater)
16085 (setq org-last-changed-timestamp
16086 (concat (substring org-last-inserted-timestamp 0 -1)
16087 " " repeater ">"))))
16088 (message "Timestamp updated"))
16089 ((equal arg '(16))
16090 (org-insert-time-stamp (current-time) t inactive))
16092 (setq time (let ((this-command this-command))
16093 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16094 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16095 nil nil (list org-end-time-was-given))))))
16097 ;; FIXME: can we use this for something else, like computing time differences?
16098 (defun org-get-compact-tod (s)
16099 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16100 (let* ((t1 (match-string 1 s))
16101 (h1 (string-to-number (match-string 2 s)))
16102 (m1 (string-to-number (match-string 3 s)))
16103 (t2 (and (match-end 4) (match-string 5 s)))
16104 (h2 (and t2 (string-to-number (match-string 6 s))))
16105 (m2 (and t2 (string-to-number (match-string 7 s))))
16106 dh dm)
16107 (if (not t2)
16109 (setq dh (- h2 h1) dm (- m2 m1))
16110 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16111 (concat t1 "+" (number-to-string dh)
16112 (and (/= 0 dm) (format ":%02d" dm)))))))
16114 (defun org-time-stamp-inactive (&optional arg)
16115 "Insert an inactive time stamp.
16116 An inactive time stamp is enclosed in square brackets instead of angle
16117 brackets. It is inactive in the sense that it does not trigger agenda entries,
16118 does not link to the calendar and cannot be changed with the S-cursor keys.
16119 So these are more for recording a certain time/date."
16120 (interactive "P")
16121 (org-time-stamp arg 'inactive))
16123 (defvar org-date-ovl (make-overlay 1 1))
16124 (overlay-put org-date-ovl 'face 'org-date-selected)
16125 (org-detach-overlay org-date-ovl)
16127 (defvar org-ans1) ; dynamically scoped parameter
16128 (defvar org-ans2) ; dynamically scoped parameter
16130 (defvar org-plain-time-of-day-regexp) ; defined below
16132 (defvar org-overriding-default-time nil) ; dynamically scoped
16133 (defvar org-read-date-overlay nil)
16134 (defvar org-dcst nil) ; dynamically scoped
16135 (defvar org-read-date-history nil)
16136 (defvar org-read-date-final-answer nil)
16137 (defvar org-read-date-analyze-futurep nil)
16138 (defvar org-read-date-analyze-forced-year nil)
16139 (defvar org-read-date-inactive)
16141 (defvar org-read-date-minibuffer-local-map
16142 (let* ((org-replace-disputed-keys nil)
16143 (map (make-sparse-keymap)))
16144 (set-keymap-parent map minibuffer-local-map)
16145 (org-defkey map (kbd ".")
16146 (lambda () (interactive)
16147 ;; Are we at the beginning of the prompt?
16148 (if (looking-back "^[^:]+: ")
16149 (org-eval-in-calendar '(calendar-goto-today))
16150 (insert "."))))
16151 (org-defkey map (kbd "C-.")
16152 (lambda () (interactive)
16153 (org-eval-in-calendar '(calendar-goto-today))))
16154 (org-defkey map [(meta shift left)]
16155 (lambda () (interactive)
16156 (org-eval-in-calendar '(calendar-backward-month 1))))
16157 (org-defkey map [(meta shift right)]
16158 (lambda () (interactive)
16159 (org-eval-in-calendar '(calendar-forward-month 1))))
16160 (org-defkey map [(meta shift up)]
16161 (lambda () (interactive)
16162 (org-eval-in-calendar '(calendar-backward-year 1))))
16163 (org-defkey map [(meta shift down)]
16164 (lambda () (interactive)
16165 (org-eval-in-calendar '(calendar-forward-year 1))))
16166 (org-defkey map [?\e (shift left)]
16167 (lambda () (interactive)
16168 (org-eval-in-calendar '(calendar-backward-month 1))))
16169 (org-defkey map [?\e (shift right)]
16170 (lambda () (interactive)
16171 (org-eval-in-calendar '(calendar-forward-month 1))))
16172 (org-defkey map [?\e (shift up)]
16173 (lambda () (interactive)
16174 (org-eval-in-calendar '(calendar-backward-year 1))))
16175 (org-defkey map [?\e (shift down)]
16176 (lambda () (interactive)
16177 (org-eval-in-calendar '(calendar-forward-year 1))))
16178 (org-defkey map [(shift up)]
16179 (lambda () (interactive)
16180 (org-eval-in-calendar '(calendar-backward-week 1))))
16181 (org-defkey map [(shift down)]
16182 (lambda () (interactive)
16183 (org-eval-in-calendar '(calendar-forward-week 1))))
16184 (org-defkey map [(shift left)]
16185 (lambda () (interactive)
16186 (org-eval-in-calendar '(calendar-backward-day 1))))
16187 (org-defkey map [(shift right)]
16188 (lambda () (interactive)
16189 (org-eval-in-calendar '(calendar-forward-day 1))))
16190 (org-defkey map "!"
16191 (lambda () (interactive)
16192 (org-eval-in-calendar '(diary-view-entries))
16193 (message "")))
16194 (org-defkey map ">"
16195 (lambda () (interactive)
16196 (org-eval-in-calendar '(scroll-calendar-left 1))))
16197 (org-defkey map "<"
16198 (lambda () (interactive)
16199 (org-eval-in-calendar '(scroll-calendar-right 1))))
16200 (org-defkey map "\C-v"
16201 (lambda () (interactive)
16202 (org-eval-in-calendar
16203 '(calendar-scroll-left-three-months 1))))
16204 (org-defkey map "\M-v"
16205 (lambda () (interactive)
16206 (org-eval-in-calendar
16207 '(calendar-scroll-right-three-months 1))))
16208 map)
16209 "Keymap for minibuffer commands when using `org-read-date'.")
16211 (defvar org-def)
16212 (defvar org-defdecode)
16213 (defvar org-with-time)
16215 (defun org-read-date (&optional org-with-time to-time from-string prompt
16216 default-time default-input inactive)
16217 "Read a date, possibly a time, and make things smooth for the user.
16218 The prompt will suggest to enter an ISO date, but you can also enter anything
16219 which will at least partially be understood by `parse-time-string'.
16220 Unrecognized parts of the date will default to the current day, month, year,
16221 hour and minute. If this command is called to replace a timestamp at point,
16222 or to enter the second timestamp of a range, the default time is taken
16223 from the existing stamp. Furthermore, the command prefers the future,
16224 so if you are giving a date where the year is not given, and the day-month
16225 combination is already past in the current year, it will assume you
16226 mean next year. For details, see the manual. A few examples:
16228 3-2-5 --> 2003-02-05
16229 feb 15 --> currentyear-02-15
16230 2/15 --> currentyear-02-15
16231 sep 12 9 --> 2009-09-12
16232 12:45 --> today 12:45
16233 22 sept 0:34 --> currentyear-09-22 0:34
16234 12 --> currentyear-currentmonth-12
16235 Fri --> nearest Friday after today
16236 -Tue --> last Tuesday
16237 etc.
16239 Furthermore you can specify a relative date by giving, as the *first* thing
16240 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16241 change in days weeks, months, years.
16242 With a single plus or minus, the date is relative to today. With a double
16243 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16244 +4d --> four days from today
16245 +4 --> same as above
16246 +2w --> two weeks from today
16247 ++5 --> five days from default date
16249 The function understands only English month and weekday abbreviations.
16251 While prompting, a calendar is popped up - you can also select the
16252 date with the mouse (button 1). The calendar shows a period of three
16253 months. To scroll it to other months, use the keys `>' and `<'.
16254 If you don't like the calendar, turn it off with
16255 \(setq org-read-date-popup-calendar nil)
16257 With optional argument TO-TIME, the date will immediately be converted
16258 to an internal time.
16259 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16260 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16261 still enter a time, and this function will inform the calling routine
16262 about this change. The calling routine may then choose to change the
16263 format used to insert the time stamp into the buffer to include the time.
16264 With optional argument FROM-STRING, read from this string instead from
16265 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16266 the time/date that is used for everything that is not specified by the
16267 user."
16268 (require 'parse-time)
16269 (let* ((org-time-stamp-rounding-minutes
16270 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16271 (org-dcst org-display-custom-times)
16272 (ct (org-current-time))
16273 (org-def (or org-overriding-default-time default-time ct))
16274 (org-defdecode (decode-time org-def))
16275 (dummy (progn
16276 (when (< (nth 2 org-defdecode) org-extend-today-until)
16277 (setcar (nthcdr 2 org-defdecode) -1)
16278 (setcar (nthcdr 1 org-defdecode) 59)
16279 (setq org-def (apply 'encode-time org-defdecode)
16280 org-defdecode (decode-time org-def)))))
16281 (mouse-autoselect-window nil) ; Don't let the mouse jump
16282 (calendar-frame-setup nil)
16283 (calendar-setup nil)
16284 (calendar-move-hook nil)
16285 (calendar-view-diary-initially-flag nil)
16286 (calendar-view-holidays-initially-flag nil)
16287 (timestr (format-time-string
16288 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16289 (prompt (concat (if prompt (concat prompt " ") "")
16290 (format "Date+time [%s]: " timestr)))
16291 ans (org-ans0 "") org-ans1 org-ans2 final)
16293 (cond
16294 (from-string (setq ans from-string))
16295 (org-read-date-popup-calendar
16296 (save-excursion
16297 (save-window-excursion
16298 (calendar)
16299 (org-eval-in-calendar '(setq cursor-type nil) t)
16300 (unwind-protect
16301 (progn
16302 (calendar-forward-day (- (time-to-days org-def)
16303 (calendar-absolute-from-gregorian
16304 (calendar-current-date))))
16305 (org-eval-in-calendar nil t)
16306 (let* ((old-map (current-local-map))
16307 (map (copy-keymap calendar-mode-map))
16308 (minibuffer-local-map
16309 (copy-keymap org-read-date-minibuffer-local-map)))
16310 (org-defkey map (kbd "RET") 'org-calendar-select)
16311 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16312 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16313 (unwind-protect
16314 (progn
16315 (use-local-map map)
16316 (setq org-read-date-inactive inactive)
16317 (add-hook 'post-command-hook 'org-read-date-display)
16318 (setq org-ans0 (read-string prompt default-input
16319 'org-read-date-history nil))
16320 ;; org-ans0: from prompt
16321 ;; org-ans1: from mouse click
16322 ;; org-ans2: from calendar motion
16323 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16324 (remove-hook 'post-command-hook 'org-read-date-display)
16325 (use-local-map old-map)
16326 (when org-read-date-overlay
16327 (delete-overlay org-read-date-overlay)
16328 (setq org-read-date-overlay nil)))))
16329 (bury-buffer "*Calendar*")))))
16331 (t ; Naked prompt only
16332 (unwind-protect
16333 (setq ans (read-string prompt default-input
16334 'org-read-date-history timestr))
16335 (when org-read-date-overlay
16336 (delete-overlay org-read-date-overlay)
16337 (setq org-read-date-overlay nil)))))
16339 (setq final (org-read-date-analyze ans org-def org-defdecode))
16341 (when org-read-date-analyze-forced-year
16342 (message "Year was forced into %s"
16343 (if org-read-date-force-compatible-dates
16344 "compatible range (1970-2037)"
16345 "range representable on this machine"))
16346 (ding))
16348 ;; One round trip to get rid of 34th of August and stuff like that....
16349 (setq final (decode-time (apply 'encode-time final)))
16351 (setq org-read-date-final-answer ans)
16353 (if to-time
16354 (apply 'encode-time final)
16355 (if (and (boundp 'org-time-was-given) org-time-was-given)
16356 (format "%04d-%02d-%02d %02d:%02d"
16357 (nth 5 final) (nth 4 final) (nth 3 final)
16358 (nth 2 final) (nth 1 final))
16359 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16361 (defun org-read-date-display ()
16362 "Display the current date prompt interpretation in the minibuffer."
16363 (when org-read-date-display-live
16364 (when org-read-date-overlay
16365 (delete-overlay org-read-date-overlay))
16366 (when (minibufferp (current-buffer))
16367 (save-excursion
16368 (end-of-line 1)
16369 (while (not (equal (buffer-substring
16370 (max (point-min) (- (point) 4)) (point))
16371 " "))
16372 (insert " ")))
16373 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16374 " " (or org-ans1 org-ans2)))
16375 (org-end-time-was-given nil)
16376 (f (org-read-date-analyze ans org-def org-defdecode))
16377 (fmts (if org-dcst
16378 org-time-stamp-custom-formats
16379 org-time-stamp-formats))
16380 (fmt (if (or org-with-time
16381 (and (boundp 'org-time-was-given) org-time-was-given))
16382 (cdr fmts)
16383 (car fmts)))
16384 (txt (format-time-string fmt (apply 'encode-time f)))
16385 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16386 (txt (concat "=> " txt)))
16387 (when (and org-end-time-was-given
16388 (string-match org-plain-time-of-day-regexp txt))
16389 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16390 org-end-time-was-given
16391 (substring txt (match-end 0)))))
16392 (when org-read-date-analyze-futurep
16393 (setq txt (concat txt " (=>F)")))
16394 (setq org-read-date-overlay
16395 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16396 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16398 (defun org-read-date-analyze (ans org-def org-defdecode)
16399 "Analyze the combined answer of the date prompt."
16400 ;; FIXME: cleanup and comment
16401 (let ((nowdecode (decode-time (current-time)))
16402 delta deltan deltaw deltadef year month day
16403 hour minute second wday pm h2 m2 tl wday1
16404 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16405 (setq org-read-date-analyze-futurep nil
16406 org-read-date-analyze-forced-year nil)
16407 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16408 (setq ans "+0"))
16410 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16411 (setq ans (replace-match "" t t ans)
16412 deltan (car delta)
16413 deltaw (nth 1 delta)
16414 deltadef (nth 2 delta)))
16416 ;; Check if there is an iso week date in there. If yes, store the
16417 ;; info and postpone interpreting it until the rest of the parsing
16418 ;; is done.
16419 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16420 (setq iso-year (if (match-end 1)
16421 (org-small-year-to-year
16422 (string-to-number (match-string 1 ans))))
16423 iso-weekday (if (match-end 3)
16424 (string-to-number (match-string 3 ans)))
16425 iso-week (string-to-number (match-string 2 ans)))
16426 (setq ans (replace-match "" t t ans)))
16428 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16429 (when (string-match
16430 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16431 (setq year (if (match-end 2)
16432 (string-to-number (match-string 2 ans))
16433 (progn (setq kill-year t)
16434 (string-to-number (format-time-string "%Y"))))
16435 month (string-to-number (match-string 3 ans))
16436 day (string-to-number (match-string 4 ans)))
16437 (if (< year 100) (setq year (+ 2000 year)))
16438 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16439 t nil ans)))
16441 ;; Help matching dotted european dates
16442 (when (string-match
16443 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16444 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16445 (setq kill-year t)
16446 (string-to-number (format-time-string "%Y")))
16447 day (string-to-number (match-string 1 ans))
16448 month (string-to-number (match-string 2 ans))
16449 ans (replace-match (format "%04d-%02d-%02d" year month day)
16450 t nil ans)))
16452 ;; Help matching american dates, like 5/30 or 5/30/7
16453 (when (string-match
16454 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16455 (setq year (if (match-end 4)
16456 (string-to-number (match-string 4 ans))
16457 (progn (setq kill-year t)
16458 (string-to-number (format-time-string "%Y"))))
16459 month (string-to-number (match-string 1 ans))
16460 day (string-to-number (match-string 2 ans)))
16461 (if (< year 100) (setq year (+ 2000 year)))
16462 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16463 t nil ans)))
16464 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16465 ;; If there is a time with am/pm, and *no* time without it, we convert
16466 ;; so that matching will be successful.
16467 (loop for i from 1 to 2 do ; twice, for end time as well
16468 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16469 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16470 (setq hour (string-to-number (match-string 1 ans))
16471 minute (if (match-end 3)
16472 (string-to-number (match-string 3 ans))
16474 pm (equal ?p
16475 (string-to-char (downcase (match-string 4 ans)))))
16476 (if (and (= hour 12) (not pm))
16477 (setq hour 0)
16478 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16479 (setq ans (replace-match (format "%02d:%02d" hour minute)
16480 t t ans))))
16482 ;; Check if a time range is given as a duration
16483 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16484 (setq hour (string-to-number (match-string 1 ans))
16485 h2 (+ hour (string-to-number (match-string 3 ans)))
16486 minute (string-to-number (match-string 2 ans))
16487 m2 (+ minute (if (match-end 5) (string-to-number
16488 (match-string 5 ans))0)))
16489 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16490 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16491 t t ans)))
16493 ;; Check if there is a time range
16494 (when (boundp 'org-end-time-was-given)
16495 (setq org-time-was-given nil)
16496 (when (and (string-match org-plain-time-of-day-regexp ans)
16497 (match-end 8))
16498 (setq org-end-time-was-given (match-string 8 ans))
16499 (setq ans (concat (substring ans 0 (match-beginning 7))
16500 (substring ans (match-end 7))))))
16502 (setq tl (parse-time-string ans)
16503 day (or (nth 3 tl) (nth 3 org-defdecode))
16504 month (or (nth 4 tl)
16505 (if (and org-read-date-prefer-future
16506 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16507 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16508 (nth 4 org-defdecode)))
16509 year (or (and (not kill-year) (nth 5 tl))
16510 (if (and org-read-date-prefer-future
16511 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16512 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16513 (nth 5 org-defdecode)))
16514 hour (or (nth 2 tl) (nth 2 org-defdecode))
16515 minute (or (nth 1 tl) (nth 1 org-defdecode))
16516 second (or (nth 0 tl) 0)
16517 wday (nth 6 tl))
16519 (when (and (eq org-read-date-prefer-future 'time)
16520 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16521 (equal day (nth 3 nowdecode))
16522 (equal month (nth 4 nowdecode))
16523 (equal year (nth 5 nowdecode))
16524 (nth 2 tl)
16525 (or (< (nth 2 tl) (nth 2 nowdecode))
16526 (and (= (nth 2 tl) (nth 2 nowdecode))
16527 (nth 1 tl)
16528 (< (nth 1 tl) (nth 1 nowdecode)))))
16529 (setq day (1+ day)
16530 futurep t))
16532 ;; Special date definitions below
16533 (cond
16534 (iso-week
16535 ;; There was an iso week
16536 (require 'cal-iso)
16537 (setq futurep nil)
16538 (setq year (or iso-year year)
16539 day (or iso-weekday wday 1)
16540 wday nil ; to make sure that the trigger below does not match
16541 iso-date (calendar-gregorian-from-absolute
16542 (calendar-absolute-from-iso
16543 (list iso-week day year))))
16544 ; FIXME: Should we also push ISO weeks into the future?
16545 ; (when (and org-read-date-prefer-future
16546 ; (not iso-year)
16547 ; (< (calendar-absolute-from-gregorian iso-date)
16548 ; (time-to-days (current-time))))
16549 ; (setq year (1+ year)
16550 ; iso-date (calendar-gregorian-from-absolute
16551 ; (calendar-absolute-from-iso
16552 ; (list iso-week day year)))))
16553 (setq month (car iso-date)
16554 year (nth 2 iso-date)
16555 day (nth 1 iso-date)))
16556 (deltan
16557 (setq futurep nil)
16558 (unless deltadef
16559 (let ((now (decode-time (current-time))))
16560 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16561 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16562 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16563 ((equal deltaw "m") (setq month (+ month deltan)))
16564 ((equal deltaw "y") (setq year (+ year deltan)))))
16565 ((and wday (not (nth 3 tl)))
16566 ;; Weekday was given, but no day, so pick that day in the week
16567 ;; on or after the derived date.
16568 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16569 (unless (equal wday wday1)
16570 (setq day (+ day (% (- wday wday1 -7) 7))))))
16571 (if (and (boundp 'org-time-was-given)
16572 (nth 2 tl))
16573 (setq org-time-was-given t))
16574 (if (< year 100) (setq year (+ 2000 year)))
16575 ;; Check of the date is representable
16576 (if org-read-date-force-compatible-dates
16577 (progn
16578 (if (< year 1970)
16579 (setq year 1970 org-read-date-analyze-forced-year t))
16580 (if (> year 2037)
16581 (setq year 2037 org-read-date-analyze-forced-year t)))
16582 (condition-case nil
16583 (ignore (encode-time second minute hour day month year))
16584 (error
16585 (setq year (nth 5 org-defdecode))
16586 (setq org-read-date-analyze-forced-year t))))
16587 (setq org-read-date-analyze-futurep futurep)
16588 (list second minute hour day month year)))
16590 (defvar parse-time-weekdays)
16591 (defun org-read-date-get-relative (s today default)
16592 "Check string S for special relative date string.
16593 TODAY and DEFAULT are internal times, for today and for a default.
16594 Return shift list (N what def-flag)
16595 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16596 N is the number of WHATs to shift.
16597 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16598 the DEFAULT date rather than TODAY."
16599 (require 'parse-time)
16600 (when (and
16601 (string-match
16602 (concat
16603 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16604 "\\([0-9]+\\)?"
16605 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16606 "\\([ \t]\\|$\\)") s)
16607 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16608 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16609 (string-to-char (substring (match-string 1 s) -1))
16610 ?+))
16611 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16612 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16613 (what (if (match-end 3) (match-string 3 s) "d"))
16614 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16615 (date (if rel default today))
16616 (wday (nth 6 (decode-time date)))
16617 delta)
16618 (if wday1
16619 (progn
16620 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16621 (if (= delta 0) (setq delta 7))
16622 (if (= dir ?-)
16623 (progn
16624 (setq delta (- delta 7))
16625 (if (= delta 0) (setq delta -7))))
16626 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16627 (list delta "d" rel))
16628 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16630 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16631 "Turn a user-specified date into the internal representation.
16632 The internal representation needed by the calendar is (month day year).
16633 This is a wrapper to handle the brain-dead convention in calendar that
16634 user function argument order change dependent on argument order."
16635 (if (boundp 'calendar-date-style)
16636 (cond
16637 ((eq calendar-date-style 'american)
16638 (list arg1 arg2 arg3))
16639 ((eq calendar-date-style 'european)
16640 (list arg2 arg1 arg3))
16641 ((eq calendar-date-style 'iso)
16642 (list arg2 arg3 arg1)))
16643 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16644 (if (org-bound-and-true-p european-calendar-style)
16645 (list arg2 arg1 arg3)
16646 (list arg1 arg2 arg3)))))
16648 (defun org-eval-in-calendar (form &optional keepdate)
16649 "Eval FORM in the calendar window and return to current window.
16650 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16651 otherwise stick to the current value of `org-ans2'."
16652 (let ((sf (selected-frame))
16653 (sw (selected-window)))
16654 (select-window (get-buffer-window "*Calendar*" t))
16655 (eval form)
16656 (when (and (not keepdate) (calendar-cursor-to-date))
16657 (let* ((date (calendar-cursor-to-date))
16658 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16659 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16660 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16661 (select-window sw)
16662 (org-select-frame-set-input-focus sf)))
16664 (defun org-calendar-select ()
16665 "Return to `org-read-date' with the date currently selected.
16666 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16667 (interactive)
16668 (when (calendar-cursor-to-date)
16669 (let* ((date (calendar-cursor-to-date))
16670 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16671 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16672 (if (active-minibuffer-window) (exit-minibuffer))))
16674 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16675 "Insert a date stamp for the date given by the internal TIME.
16676 WITH-HM means use the stamp format that includes the time of the day.
16677 INACTIVE means use square brackets instead of angular ones, so that the
16678 stamp will not contribute to the agenda.
16679 PRE and POST are optional strings to be inserted before and after the
16680 stamp.
16681 The command returns the inserted time stamp."
16682 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16683 stamp)
16684 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16685 (insert-before-markers (or pre ""))
16686 (when (listp extra)
16687 (setq extra (car extra))
16688 (if (and (stringp extra)
16689 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16690 (setq extra (format "-%02d:%02d"
16691 (string-to-number (match-string 1 extra))
16692 (string-to-number (match-string 2 extra))))
16693 (setq extra nil)))
16694 (when extra
16695 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16696 (insert-before-markers (setq stamp (format-time-string fmt time)))
16697 (insert-before-markers (or post ""))
16698 (setq org-last-inserted-timestamp stamp)))
16700 (defun org-toggle-time-stamp-overlays ()
16701 "Toggle the use of custom time stamp formats."
16702 (interactive)
16703 (setq org-display-custom-times (not org-display-custom-times))
16704 (unless org-display-custom-times
16705 (let ((p (point-min)) (bmp (buffer-modified-p)))
16706 (while (setq p (next-single-property-change p 'display))
16707 (if (and (get-text-property p 'display)
16708 (eq (get-text-property p 'face) 'org-date))
16709 (remove-text-properties
16710 p (setq p (next-single-property-change p 'display))
16711 '(display t))))
16712 (set-buffer-modified-p bmp)))
16713 (if (featurep 'xemacs)
16714 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16715 (org-restart-font-lock)
16716 (setq org-table-may-need-update t)
16717 (if org-display-custom-times
16718 (message "Time stamps are overlaid with custom format")
16719 (message "Time stamp overlays removed")))
16721 (defun org-display-custom-time (beg end)
16722 "Overlay modified time stamp format over timestamp between BEG and END."
16723 (let* ((ts (buffer-substring beg end))
16724 t1 w1 with-hm tf time str w2 (off 0))
16725 (save-match-data
16726 (setq t1 (org-parse-time-string ts t))
16727 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16728 (setq off (- (match-end 0) (match-beginning 0)))))
16729 (setq end (- end off))
16730 (setq w1 (- end beg)
16731 with-hm (and (nth 1 t1) (nth 2 t1))
16732 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16733 time (org-fix-decoded-time t1)
16734 str (org-add-props
16735 (format-time-string
16736 (substring tf 1 -1) (apply 'encode-time time))
16737 nil 'mouse-face 'highlight)
16738 w2 (length str))
16739 (if (not (= w2 w1))
16740 (add-text-properties (1+ beg) (+ 2 beg)
16741 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16742 (if (featurep 'xemacs)
16743 (progn
16744 (put-text-property beg end 'invisible t)
16745 (put-text-property beg end 'end-glyph (make-glyph str)))
16746 (put-text-property beg end 'display str))))
16748 (defun org-translate-time (string)
16749 "Translate all timestamps in STRING to custom format.
16750 But do this only if the variable `org-display-custom-times' is set."
16751 (when org-display-custom-times
16752 (save-match-data
16753 (let* ((start 0)
16754 (re org-ts-regexp-both)
16755 t1 with-hm inactive tf time str beg end)
16756 (while (setq start (string-match re string start))
16757 (setq beg (match-beginning 0)
16758 end (match-end 0)
16759 t1 (save-match-data
16760 (org-parse-time-string (substring string beg end) t))
16761 with-hm (and (nth 1 t1) (nth 2 t1))
16762 inactive (equal (substring string beg (1+ beg)) "[")
16763 tf (funcall (if with-hm 'cdr 'car)
16764 org-time-stamp-custom-formats)
16765 time (org-fix-decoded-time t1)
16766 str (format-time-string
16767 (concat
16768 (if inactive "[" "<") (substring tf 1 -1)
16769 (if inactive "]" ">"))
16770 (apply 'encode-time time))
16771 string (replace-match str t t string)
16772 start (+ start (length str)))))))
16773 string)
16775 (defun org-fix-decoded-time (time)
16776 "Set 0 instead of nil for the first 6 elements of time.
16777 Don't touch the rest."
16778 (let ((n 0))
16779 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16781 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16783 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16784 "Difference between TIMESTAMP-STRING and now in days.
16785 If SECONDS is non-nil, return the difference in seconds."
16786 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16787 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16788 (funcall fdiff (current-time)))))
16790 (defun org-deadline-close (timestamp-string &optional ndays)
16791 "Is the time in TIMESTAMP-STRING close to the current date?"
16792 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16793 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16794 (not (org-entry-is-done-p))))
16796 (defun org-get-wdays (ts &optional delay zero-delay)
16797 "Get the deadline lead time appropriate for timestring TS.
16798 When DELAY is non-nil, get the delay time for scheduled items
16799 instead of the deadline lead time. When ZERO-DELAY is non-nil
16800 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16801 don't try to find the delay cookie in the scheduled timestamp."
16802 (let ((tv (if delay org-scheduled-delay-days
16803 org-deadline-warning-days)))
16804 (cond
16805 ((or (and delay (< tv 0))
16806 (and delay zero-delay (<= tv 0))
16807 (and (not delay) (<= tv 0)))
16808 ;; Enforce this value no matter what
16809 (- tv))
16810 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16811 ;; lead time is specified.
16812 (floor (* (string-to-number (match-string 1 ts))
16813 (cdr (assoc (match-string 2 ts)
16814 '(("d" . 1) ("w" . 7)
16815 ("m" . 30.4) ("y" . 365.25)
16816 ("h" . 0.041667)))))))
16817 ;; go for the default.
16818 (t tv))))
16820 (defun org-calendar-select-mouse (ev)
16821 "Return to `org-read-date' with the date currently selected.
16822 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16823 (interactive "e")
16824 (mouse-set-point ev)
16825 (when (calendar-cursor-to-date)
16826 (let* ((date (calendar-cursor-to-date))
16827 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16828 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16829 (if (active-minibuffer-window) (exit-minibuffer))))
16831 (defun org-check-deadlines (ndays)
16832 "Check if there are any deadlines due or past due.
16833 A deadline is considered due if it happens within `org-deadline-warning-days'
16834 days from today's date. If the deadline appears in an entry marked DONE,
16835 it is not shown. The prefix arg NDAYS can be used to test that many
16836 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16837 (interactive "P")
16838 (let* ((org-warn-days
16839 (cond
16840 ((equal ndays '(4)) 100000)
16841 (ndays (prefix-numeric-value ndays))
16842 (t (abs org-deadline-warning-days))))
16843 (case-fold-search nil)
16844 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16845 (callback
16846 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16848 (message "%d deadlines past-due or due within %d days"
16849 (org-occur regexp nil callback)
16850 org-warn-days)))
16852 (defsubst org-re-timestamp (type)
16853 "Return a regexp for timestamp TYPE.
16854 Allowed values for TYPE are:
16856 all: all timestamps
16857 active: only active timestamps (<...>)
16858 inactive: only inactive timestamps ([...])
16859 scheduled: only scheduled timestamps
16860 deadline: only deadline timestamps
16861 closed: only closed time-stamps
16863 When TYPE is nil, fall back on returning a regexp that matches
16864 both scheduled and deadline timestamps."
16865 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16866 ((eq type 'active) org-ts-regexp)
16867 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16868 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16869 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16870 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16871 ((eq type 'scheduled-or-deadline)
16872 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16874 (defun org-check-before-date (date)
16875 "Check if there are deadlines or scheduled entries before DATE."
16876 (interactive (list (org-read-date)))
16877 (let ((case-fold-search nil)
16878 (regexp (org-re-timestamp org-ts-type))
16879 (callback
16880 (lambda () (time-less-p
16881 (org-time-string-to-time (match-string 1))
16882 (org-time-string-to-time date)))))
16883 (message "%d entries before %s"
16884 (org-occur regexp nil callback) date)))
16886 (defun org-check-after-date (date)
16887 "Check if there are deadlines or scheduled entries after DATE."
16888 (interactive (list (org-read-date)))
16889 (let ((case-fold-search nil)
16890 (regexp (org-re-timestamp org-ts-type))
16891 (callback
16892 (lambda () (not
16893 (time-less-p
16894 (org-time-string-to-time (match-string 1))
16895 (org-time-string-to-time date))))))
16896 (message "%d entries after %s"
16897 (org-occur regexp nil callback) date)))
16899 (defun org-check-dates-range (start-date end-date)
16900 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16901 (interactive (list (org-read-date nil nil nil "Range starts")
16902 (org-read-date nil nil nil "Range end")))
16903 (let ((case-fold-search nil)
16904 (regexp (org-re-timestamp org-ts-type))
16905 (callback
16906 (lambda ()
16907 (let ((match (match-string 1)))
16908 (and
16909 (not (time-less-p
16910 (org-time-string-to-time match)
16911 (org-time-string-to-time start-date)))
16912 (time-less-p
16913 (org-time-string-to-time match)
16914 (org-time-string-to-time end-date)))))))
16915 (message "%d entries between %s and %s"
16916 (org-occur regexp nil callback) start-date end-date)))
16918 (defun org-evaluate-time-range (&optional to-buffer)
16919 "Evaluate a time range by computing the difference between start and end.
16920 Normally the result is just printed in the echo area, but with prefix arg
16921 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16922 If the time range is actually in a table, the result is inserted into the
16923 next column.
16924 For time difference computation, a year is assumed to be exactly 365
16925 days in order to avoid rounding problems."
16926 (interactive "P")
16928 (org-clock-update-time-maybe)
16929 (save-excursion
16930 (unless (org-at-date-range-p t)
16931 (goto-char (point-at-bol))
16932 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16933 (if (not (org-at-date-range-p t))
16934 (user-error "Not at a time-stamp range, and none found in current line")))
16935 (let* ((ts1 (match-string 1))
16936 (ts2 (match-string 2))
16937 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16938 (match-end (match-end 0))
16939 (time1 (org-time-string-to-time ts1))
16940 (time2 (org-time-string-to-time ts2))
16941 (t1 (org-float-time time1))
16942 (t2 (org-float-time time2))
16943 (diff (abs (- t2 t1)))
16944 (negative (< (- t2 t1) 0))
16945 ;; (ys (floor (* 365 24 60 60)))
16946 (ds (* 24 60 60))
16947 (hs (* 60 60))
16948 (fy "%dy %dd %02d:%02d")
16949 (fy1 "%dy %dd")
16950 (fd "%dd %02d:%02d")
16951 (fd1 "%dd")
16952 (fh "%02d:%02d")
16953 y d h m align)
16954 (if havetime
16955 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16957 d (floor (/ diff ds)) diff (mod diff ds)
16958 h (floor (/ diff hs)) diff (mod diff hs)
16959 m (floor (/ diff 60)))
16960 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16962 d (floor (+ (/ diff ds) 0.5))
16963 h 0 m 0))
16964 (if (not to-buffer)
16965 (message "%s" (org-make-tdiff-string y d h m))
16966 (if (org-at-table-p)
16967 (progn
16968 (goto-char match-end)
16969 (setq align t)
16970 (and (looking-at " *|") (goto-char (match-end 0))))
16971 (goto-char match-end))
16972 (if (looking-at
16973 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16974 (replace-match ""))
16975 (if negative (insert " -"))
16976 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16977 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16978 (insert " " (format fh h m))))
16979 (if align (org-table-align))
16980 (message "Time difference inserted")))))
16982 (defun org-make-tdiff-string (y d h m)
16983 (let ((fmt "")
16984 (l nil))
16985 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16986 l (push y l)))
16987 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16988 l (push d l)))
16989 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16990 l (push h l)))
16991 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16992 l (push m l)))
16993 (apply 'format fmt (nreverse l))))
16995 (defun org-time-string-to-time (s &optional buffer pos)
16996 "Convert a timestamp string into internal time."
16997 (condition-case errdata
16998 (apply 'encode-time (org-parse-time-string s))
16999 (error (error "Bad timestamp `%s'%s\nError was: %s"
17000 s (if (not (and buffer pos))
17002 (format " at %d in buffer `%s'" pos buffer))
17003 (cdr errdata)))))
17005 (defun org-time-string-to-seconds (s)
17006 "Convert a timestamp string to a number of seconds."
17007 (org-float-time (org-time-string-to-time s)))
17009 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17010 "Convert a time stamp to an absolute day number.
17011 If there is a specifier for a cyclic time stamp, get the closest
17012 date to DAYNR.
17013 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17014 The variable `date' is bound by the calendar when this is called."
17015 (cond
17016 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17017 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17018 daynr
17019 (+ daynr 1000)))
17020 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17021 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17022 (time-to-days (current-time))) (match-string 0 s)
17023 prefer show-all))
17024 (t (time-to-days
17025 (condition-case errdata
17026 (apply 'encode-time (org-parse-time-string s))
17027 (error (error "Bad timestamp `%s'%s\nError was: %s"
17028 s (if (not (and buffer pos))
17030 (format " at %d in buffer `%s'" pos buffer))
17031 (cdr errdata))))))))
17033 (defun org-days-to-iso-week (days)
17034 "Return the iso week number."
17035 (require 'cal-iso)
17036 (car (calendar-iso-from-absolute days)))
17038 (defun org-small-year-to-year (year)
17039 "Convert 2-digit years into 4-digit years.
17040 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17041 The year 2000 cannot be abbreviated. Any year larger than 99
17042 is returned unchanged."
17043 (if (< year 38)
17044 (setq year (+ 2000 year))
17045 (if (< year 100)
17046 (setq year (+ 1900 year))))
17047 year)
17049 (defun org-time-from-absolute (d)
17050 "Return the time corresponding to date D.
17051 D may be an absolute day number, or a calendar-type list (month day year)."
17052 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17053 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17055 (defun org-calendar-holiday ()
17056 "List of holidays, for Diary display in Org-mode."
17057 (require 'holidays)
17058 (let ((hl (funcall
17059 (if (fboundp 'calendar-check-holidays)
17060 'calendar-check-holidays 'check-calendar-holidays) date)))
17061 (if hl (mapconcat 'identity hl "; "))))
17063 (defun org-diary-sexp-entry (sexp entry date)
17064 "Process a SEXP diary ENTRY for DATE."
17065 (require 'diary-lib)
17066 (let ((result (if calendar-debug-sexp
17067 (let ((stack-trace-on-error t))
17068 (eval (car (read-from-string sexp))))
17069 (condition-case nil
17070 (eval (car (read-from-string sexp)))
17071 (error
17072 (beep)
17073 (message "Bad sexp at line %d in %s: %s"
17074 (org-current-line)
17075 (buffer-file-name) sexp)
17076 (sleep-for 2))))))
17077 (cond ((stringp result) (split-string result "; "))
17078 ((and (consp result)
17079 (not (consp (cdr result)))
17080 (stringp (cdr result))) (cdr result))
17081 ((and (consp result)
17082 (stringp (car result))) result)
17083 (result entry))))
17085 (defun org-diary-to-ical-string (frombuf)
17086 "Get iCalendar entries from diary entries in buffer FROMBUF.
17087 This uses the icalendar.el library."
17088 (let* ((tmpdir (if (featurep 'xemacs)
17089 (temp-directory)
17090 temporary-file-directory))
17091 (tmpfile (make-temp-name
17092 (expand-file-name "orgics" tmpdir)))
17093 buf rtn b e)
17094 (with-current-buffer frombuf
17095 (icalendar-export-region (point-min) (point-max) tmpfile)
17096 (setq buf (find-buffer-visiting tmpfile))
17097 (set-buffer buf)
17098 (goto-char (point-min))
17099 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17100 (setq b (match-beginning 0)))
17101 (goto-char (point-max))
17102 (if (re-search-backward "^END:VEVENT" nil t)
17103 (setq e (match-end 0)))
17104 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17105 (kill-buffer buf)
17106 (delete-file tmpfile)
17107 rtn))
17109 (defun org-closest-date (start current change prefer show-all)
17110 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17111 When PREFER is `past', return a date that is either CURRENT or past.
17112 When PREFER is `future', return a date that is either CURRENT or future.
17113 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17114 ;; Make the proper lists from the dates
17115 (catch 'exit
17116 (let ((a1 '(("h" . hour)
17117 ("d" . day)
17118 ("w" . week)
17119 ("m" . month)
17120 ("y" . year)))
17121 (shour (nth 2 (org-parse-time-string start)))
17122 dn dw sday cday n1 n2 n0
17123 d m y y1 y2 date1 date2 nmonths nm ny m2)
17125 (setq start (org-date-to-gregorian start)
17126 current (org-date-to-gregorian
17127 (if show-all
17128 current
17129 (time-to-days (current-time))))
17130 sday (calendar-absolute-from-gregorian start)
17131 cday (calendar-absolute-from-gregorian current))
17133 (if (<= cday sday) (throw 'exit sday))
17135 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17136 (setq dn (string-to-number (match-string 1 change))
17137 dw (cdr (assoc (match-string 2 change) a1)))
17138 (user-error "Invalid change specifier: %s" change))
17139 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17140 (cond
17141 ((eq dw 'hour)
17142 (let ((missing-hours
17143 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17144 dn)))
17145 (setq n1 (if (zerop missing-hours) cday
17146 (- cday (1+ (floor (/ missing-hours 24)))))
17147 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17148 ((eq dw 'day)
17149 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17150 n2 (+ n1 dn)))
17151 ((eq dw 'year)
17152 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17153 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17154 (setq date1 (list m d y1)
17155 n1 (calendar-absolute-from-gregorian date1)
17156 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17157 n2 (calendar-absolute-from-gregorian date2)))
17158 ((eq dw 'month)
17159 ;; approx number of month between the two dates
17160 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17161 ;; How often does dn fit in there?
17162 (setq d (nth 1 start) m (car start) y (nth 2 start)
17163 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17164 m (+ m nm)
17165 ny (floor (/ m 12))
17166 y (+ y ny)
17167 m (- m (* ny 12)))
17168 (while (> m 12) (setq m (- m 12) y (1+ y)))
17169 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17170 (setq m2 (+ m dn) y2 y)
17171 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17172 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17173 (while (<= n2 cday)
17174 (setq n1 n2 m m2 y y2)
17175 (setq m2 (+ m dn) y2 y)
17176 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17177 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17178 ;; Make sure n1 is the earlier date
17179 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17180 (if show-all
17181 (cond
17182 ((eq prefer 'past) (if (= cday n2) n2 n1))
17183 ((eq prefer 'future) (if (= cday n1) n1 n2))
17184 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17185 (cond
17186 ((eq prefer 'past) (if (= cday n2) n2 n1))
17187 ((eq prefer 'future) (if (= cday n1) n1 n2))
17188 (t (if (= cday n1) n1 n2)))))))
17190 (defun org-date-to-gregorian (date)
17191 "Turn any specification of DATE into a Gregorian date for the calendar."
17192 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17193 ((and (listp date) (= (length date) 3)) date)
17194 ((stringp date)
17195 (setq date (org-parse-time-string date))
17196 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17197 ((listp date)
17198 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17200 (defun org-parse-time-string (s &optional nodefault)
17201 "Parse the standard Org-mode time string.
17202 This should be a lot faster than the normal `parse-time-string'.
17203 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17204 hour and minute fields will be nil if not given."
17205 (cond ((string-match org-ts-regexp0 s)
17206 (list 0
17207 (if (or (match-beginning 8) (not nodefault))
17208 (string-to-number (or (match-string 8 s) "0")))
17209 (if (or (match-beginning 7) (not nodefault))
17210 (string-to-number (or (match-string 7 s) "0")))
17211 (string-to-number (match-string 4 s))
17212 (string-to-number (match-string 3 s))
17213 (string-to-number (match-string 2 s))
17214 nil nil nil))
17215 ((string-match "^<[^>]+>$" s)
17216 (decode-time (seconds-to-time (org-matcher-time s))))
17217 (t (error "Not a standard Org-mode time string: %s" s))))
17219 (defun org-timestamp-up (&optional arg)
17220 "Increase the date item at the cursor by one.
17221 If the cursor is on the year, change the year. If it is on the month,
17222 the day or the time, change that.
17223 With prefix ARG, change by that many units."
17224 (interactive "p")
17225 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17227 (defun org-timestamp-down (&optional arg)
17228 "Decrease the date item at the cursor by one.
17229 If the cursor is on the year, change the year. If it is on the month,
17230 the day or the time, change that.
17231 With prefix ARG, change by that many units."
17232 (interactive "p")
17233 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17235 (defun org-timestamp-up-day (&optional arg)
17236 "Increase the date in the time stamp by one day.
17237 With prefix ARG, change that many days."
17238 (interactive "p")
17239 (if (and (not (org-at-timestamp-p t))
17240 (org-at-heading-p))
17241 (org-todo 'up)
17242 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17244 (defun org-timestamp-down-day (&optional arg)
17245 "Decrease the date in the time stamp by one day.
17246 With prefix ARG, change that many days."
17247 (interactive "p")
17248 (if (and (not (org-at-timestamp-p t))
17249 (org-at-heading-p))
17250 (org-todo 'down)
17251 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17253 (defun org-at-timestamp-p (&optional inactive-ok)
17254 "Determine if the cursor is in or at a timestamp."
17255 (interactive)
17256 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17257 (pos (point))
17258 (ans (or (looking-at tsr)
17259 (save-excursion
17260 (skip-chars-backward "^[<\n\r\t")
17261 (if (> (point) (point-min)) (backward-char 1))
17262 (and (looking-at tsr)
17263 (> (- (match-end 0) pos) -1))))))
17264 (and ans
17265 (boundp 'org-ts-what)
17266 (setq org-ts-what
17267 (cond
17268 ((= pos (match-beginning 0)) 'bracket)
17269 ;; Point is considered to be "on the bracket" whether
17270 ;; it's really on it or right after it.
17271 ((= pos (1- (match-end 0))) 'bracket)
17272 ((= pos (match-end 0)) 'after)
17273 ((org-pos-in-match-range pos 2) 'year)
17274 ((org-pos-in-match-range pos 3) 'month)
17275 ((org-pos-in-match-range pos 7) 'hour)
17276 ((org-pos-in-match-range pos 8) 'minute)
17277 ((or (org-pos-in-match-range pos 4)
17278 (org-pos-in-match-range pos 5)) 'day)
17279 ((and (> pos (or (match-end 8) (match-end 5)))
17280 (< pos (match-end 0)))
17281 (- pos (or (match-end 8) (match-end 5))))
17282 (t 'day))))
17283 ans))
17285 (defun org-toggle-timestamp-type ()
17286 "Toggle the type (<active> or [inactive]) of a time stamp."
17287 (interactive)
17288 (when (org-at-timestamp-p t)
17289 (let ((beg (match-beginning 0)) (end (match-end 0))
17290 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17291 (save-excursion
17292 (goto-char beg)
17293 (while (re-search-forward "[][<>]" end t)
17294 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17295 t t)))
17296 (message "Timestamp is now %sactive"
17297 (if (equal (char-after beg) ?<) "" "in")))))
17299 (defun org-at-clock-log-p nil
17300 "Is the cursor on the clock log line?"
17301 (save-excursion
17302 (move-beginning-of-line 1)
17303 (looking-at "^[ \t]*CLOCK:")))
17305 (defvar org-clock-history) ; defined in org-clock.el
17306 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17307 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17308 "Change the date in the time stamp at point.
17309 The date will be changed by N times WHAT. WHAT can be `day', `month',
17310 `year', `minute', `second'. If WHAT is not given, the cursor position
17311 in the timestamp determines what will be changed.
17312 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17313 (let ((origin (point)) origin-cat
17314 with-hm inactive
17315 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17316 org-ts-what
17317 extra rem
17318 ts time time0 fixnext clrgx)
17319 (if (not (org-at-timestamp-p t))
17320 (user-error "Not at a timestamp"))
17321 (if (and (not what) (eq org-ts-what 'bracket))
17322 (org-toggle-timestamp-type)
17323 ;; Point isn't on brackets. Remember the part of the time-stamp
17324 ;; the point was in. Indeed, size of time-stamps may change,
17325 ;; but point must be kept in the same category nonetheless.
17326 (setq origin-cat org-ts-what)
17327 (if (and (not what) (not (eq org-ts-what 'day))
17328 org-display-custom-times
17329 (get-text-property (point) 'display)
17330 (not (get-text-property (1- (point)) 'display)))
17331 (setq org-ts-what 'day))
17332 (setq org-ts-what (or what org-ts-what)
17333 inactive (= (char-after (match-beginning 0)) ?\[)
17334 ts (match-string 0))
17335 (replace-match "")
17336 (when (string-match
17337 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17339 (setq extra (match-string 1 ts))
17340 (if suppress-tmp-delay
17341 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17342 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17343 (setq with-hm t))
17344 (setq time0 (org-parse-time-string ts))
17345 (when (and updown
17346 (eq org-ts-what 'minute)
17347 (not current-prefix-arg))
17348 ;; This looks like s-up and s-down. Change by one rounding step.
17349 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17350 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17351 (setcar (cdr time0) (+ (nth 1 time0)
17352 (if (> n 0) (- rem) (- dm rem))))))
17353 (setq time
17354 (encode-time (or (car time0) 0)
17355 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17356 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17357 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17358 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17359 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17360 (nthcdr 6 time0)))
17361 (when (and (member org-ts-what '(hour minute))
17362 extra
17363 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17364 (setq extra (org-modify-ts-extra
17365 extra
17366 (if (eq org-ts-what 'hour) 2 5)
17367 n dm)))
17368 (when (integerp org-ts-what)
17369 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17370 (if (eq what 'calendar)
17371 (let ((cal-date (org-get-date-from-calendar)))
17372 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17373 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17374 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17375 (setcar time0 (or (car time0) 0))
17376 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17377 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17378 (setq time (apply 'encode-time time0))))
17379 ;; Insert the new time-stamp, and ensure point stays in the same
17380 ;; category as before (i.e. not after the last position in that
17381 ;; category).
17382 (let ((pos (point)))
17383 ;; Stay before inserted string. `save-excursion' is of no use.
17384 (setq org-last-changed-timestamp
17385 (org-insert-time-stamp time with-hm inactive nil nil extra))
17386 (goto-char pos))
17387 (save-match-data
17388 (looking-at org-ts-regexp3)
17389 (goto-char (cond
17390 ;; `day' category ends before `hour' if any, or at
17391 ;; the end of the day name.
17392 ((eq origin-cat 'day)
17393 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17394 ((eq origin-cat 'hour) (min (match-end 7) origin))
17395 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17396 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17397 ;; `year' and `month' have both fixed size: point
17398 ;; couldn't have moved into another part.
17399 (t origin))))
17400 ;; Update clock if on a CLOCK line.
17401 (org-clock-update-time-maybe)
17402 ;; Maybe adjust the closest clock in `org-clock-history'
17403 (when org-clock-adjust-closest
17404 (if (not (and (org-at-clock-log-p)
17405 (< 1 (length (delq nil (mapcar 'marker-position
17406 org-clock-history))))))
17407 (message "No clock to adjust")
17408 (cond ((save-excursion ; fix previous clock?
17409 (re-search-backward org-ts-regexp0 nil t)
17410 (org-looking-back (concat org-clock-string " \\[")))
17411 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17412 ((save-excursion ; fix next clock?
17413 (re-search-backward org-ts-regexp0 nil t)
17414 (looking-at (concat org-ts-regexp0 "\\] =>")))
17415 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17416 (save-window-excursion
17417 ;; Find closest clock to point, adjust the previous/next one in history
17418 (let* ((p (save-excursion (org-back-to-heading t)))
17419 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17420 (clfixnth
17421 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17422 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17423 (if (not clfixpos)
17424 (message "No clock to adjust")
17425 (save-excursion
17426 (org-goto-marker-or-bmk clfixpos)
17427 (org-show-subtree)
17428 (when (re-search-forward clrgx nil t)
17429 (goto-char (match-beginning 1))
17430 (let (org-clock-adjust-closest)
17431 (org-timestamp-change n org-ts-what updown))
17432 (message "Clock adjusted in %s for heading: %s"
17433 (file-name-nondirectory (buffer-file-name))
17434 (org-get-heading t t)))))))))
17435 ;; Try to recenter the calendar window, if any.
17436 (if (and org-calendar-follow-timestamp-change
17437 (get-buffer-window "*Calendar*" t)
17438 (memq org-ts-what '(day month year)))
17439 (org-recenter-calendar (time-to-days time))))))
17441 (defun org-modify-ts-extra (s pos n dm)
17442 "Change the different parts of the lead-time and repeat fields in timestamp."
17443 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17444 ng h m new rem)
17445 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17446 (cond
17447 ((or (org-pos-in-match-range pos 2)
17448 (org-pos-in-match-range pos 3))
17449 (setq m (string-to-number (match-string 3 s))
17450 h (string-to-number (match-string 2 s)))
17451 (if (org-pos-in-match-range pos 2)
17452 (setq h (+ h n))
17453 (setq n (* dm (org-no-warnings (signum n))))
17454 (when (not (= 0 (setq rem (% m dm))))
17455 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17456 (setq m (+ m n)))
17457 (if (< m 0) (setq m (+ m 60) h (1- h)))
17458 (if (> m 59) (setq m (- m 60) h (1+ h)))
17459 (setq h (min 24 (max 0 h)))
17460 (setq ng 1 new (format "-%02d:%02d" h m)))
17461 ((org-pos-in-match-range pos 6)
17462 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17463 ((org-pos-in-match-range pos 5)
17464 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17466 ((org-pos-in-match-range pos 9)
17467 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17468 ((org-pos-in-match-range pos 8)
17469 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17471 (when ng
17472 (setq s (concat
17473 (substring s 0 (match-beginning ng))
17475 (substring s (match-end ng))))))
17478 (defun org-recenter-calendar (date)
17479 "If the calendar is visible, recenter it to DATE."
17480 (let ((cwin (get-buffer-window "*Calendar*" t)))
17481 (when cwin
17482 (let ((calendar-move-hook nil))
17483 (with-selected-window cwin
17484 (calendar-goto-date (if (listp date) date
17485 (calendar-gregorian-from-absolute date))))))))
17487 (defun org-goto-calendar (&optional arg)
17488 "Go to the Emacs calendar at the current date.
17489 If there is a time stamp in the current line, go to that date.
17490 A prefix ARG can be used to force the current date."
17491 (interactive "P")
17492 (let ((tsr org-ts-regexp) diff
17493 (calendar-move-hook nil)
17494 (calendar-view-holidays-initially-flag nil)
17495 (calendar-view-diary-initially-flag nil))
17496 (if (or (org-at-timestamp-p)
17497 (save-excursion
17498 (beginning-of-line 1)
17499 (looking-at (concat ".*" tsr))))
17500 (let ((d1 (time-to-days (current-time)))
17501 (d2 (time-to-days
17502 (org-time-string-to-time (match-string 1)))))
17503 (setq diff (- d2 d1))))
17504 (calendar)
17505 (calendar-goto-today)
17506 (if (and diff (not arg)) (calendar-forward-day diff))))
17508 (defun org-get-date-from-calendar ()
17509 "Return a list (month day year) of date at point in calendar."
17510 (with-current-buffer "*Calendar*"
17511 (save-match-data
17512 (calendar-cursor-to-date))))
17514 (defun org-date-from-calendar ()
17515 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17516 If there is already a time stamp at the cursor position, update it."
17517 (interactive)
17518 (if (org-at-timestamp-p t)
17519 (org-timestamp-change 0 'calendar)
17520 (let ((cal-date (org-get-date-from-calendar)))
17521 (org-insert-time-stamp
17522 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17524 (defcustom org-effort-durations
17525 `(("h" . 60)
17526 ("d" . ,(* 60 8))
17527 ("w" . ,(* 60 8 5))
17528 ("m" . ,(* 60 8 5 4))
17529 ("y" . ,(* 60 8 5 40)))
17530 "Conversion factor to minutes for an effort modifier.
17532 Each entry has the form (MODIFIER . MINUTES).
17534 In an effort string, a number followed by MODIFIER is multiplied
17535 by the specified number of MINUTES to obtain an effort in
17536 minutes.
17538 For example, if the value of this variable is ((\"hours\" . 60)), then an
17539 effort string \"2hours\" is equivalent to 120 minutes."
17540 :group 'org-agenda
17541 :version "24.1"
17542 :type '(alist :key-type (string :tag "Modifier")
17543 :value-type (number :tag "Minutes")))
17545 (defun org-minutes-to-clocksum-string (m)
17546 "Format number of minutes as a clocksum string.
17547 The format is determined by `org-time-clocksum-format',
17548 `org-time-clocksum-use-fractional' and
17549 `org-time-clocksum-fractional-format' and
17550 `org-time-clocksum-use-effort-durations'."
17551 (let ((clocksum "")
17552 (m (round m)) ; Don't allow fractions of minutes
17553 h d w mo y fmt n)
17554 (setq h (if org-time-clocksum-use-effort-durations
17555 (cdr (assoc "h" org-effort-durations)) 60)
17556 d (if org-time-clocksum-use-effort-durations
17557 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17558 w (if org-time-clocksum-use-effort-durations
17559 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17560 mo (if org-time-clocksum-use-effort-durations
17561 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17562 y (if org-time-clocksum-use-effort-durations
17563 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17564 ;; fractional format
17565 (if org-time-clocksum-use-fractional
17566 (cond
17567 ;; single format string
17568 ((stringp org-time-clocksum-fractional-format)
17569 (format org-time-clocksum-fractional-format (/ m (float h))))
17570 ;; choice of fractional formats for different time units
17571 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17572 (> (/ (truncate m) (* y d h)) 0))
17573 (format fmt (/ m (* y d (float h)))))
17574 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17575 (> (/ (truncate m) (* mo d h)) 0))
17576 (format fmt (/ m (* mo d (float h)))))
17577 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17578 (> (/ (truncate m) (* w d h)) 0))
17579 (format fmt (/ m (* w d (float h)))))
17580 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17581 (> (/ (truncate m) (* d h)) 0))
17582 (format fmt (/ m (* d (float h)))))
17583 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17584 (> (/ (truncate m) h) 0))
17585 (format fmt (/ m (float h))))
17586 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17587 (format fmt m))
17588 ;; fall back to smallest time unit with a format
17589 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17590 (format fmt (/ m (float h))))
17591 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17592 (format fmt (/ m (* d (float h)))))
17593 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17594 (format fmt (/ m (* w d (float h)))))
17595 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17596 (format fmt (/ m (* mo d (float h)))))
17597 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17598 (format fmt (/ m (* y d (float h))))))
17599 ;; standard (non-fractional) format, with single format string
17600 (if (stringp org-time-clocksum-format)
17601 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17602 ;; separate formats components
17603 (and (setq fmt (plist-get org-time-clocksum-format :years))
17604 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17605 (plist-get org-time-clocksum-format :require-years))
17606 (setq clocksum (concat clocksum (format fmt n))
17607 m (- m (* n y d h))))
17608 (and (setq fmt (plist-get org-time-clocksum-format :months))
17609 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17610 (plist-get org-time-clocksum-format :require-months))
17611 (setq clocksum (concat clocksum (format fmt n))
17612 m (- m (* n mo d h))))
17613 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17614 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17615 (plist-get org-time-clocksum-format :require-weeks))
17616 (setq clocksum (concat clocksum (format fmt n))
17617 m (- m (* n w d h))))
17618 (and (setq fmt (plist-get org-time-clocksum-format :days))
17619 (or (> (setq n (/ (truncate m) (* d h))) 0)
17620 (plist-get org-time-clocksum-format :require-days))
17621 (setq clocksum (concat clocksum (format fmt n))
17622 m (- m (* n d h))))
17623 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17624 (or (> (setq n (/ (truncate m) h)) 0)
17625 (plist-get org-time-clocksum-format :require-hours))
17626 (setq clocksum (concat clocksum (format fmt n))
17627 m (- m (* n h))))
17628 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17629 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17630 (setq clocksum (concat clocksum (format fmt m))))
17631 ;; return formatted time duration
17632 clocksum))))
17634 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17635 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17636 "Org mode version 8.0")
17638 (defun org-hours-to-clocksum-string (n)
17639 (org-minutes-to-clocksum-string (* n 60)))
17641 (defun org-hh:mm-string-to-minutes (s)
17642 "Convert a string H:MM to a number of minutes.
17643 If the string is just a number, interpret it as minutes.
17644 In fact, the first hh:mm or number in the string will be taken,
17645 there can be extra stuff in the string.
17646 If no number is found, the return value is 0."
17647 (cond
17648 ((integerp s) s)
17649 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17650 (+ (* (string-to-number (match-string 1 s)) 60)
17651 (string-to-number (match-string 2 s))))
17652 ((string-match "\\([0-9]+\\)" s)
17653 (string-to-number (match-string 1 s)))
17654 (t 0)))
17656 (defcustom org-image-actual-width t
17657 "Should we use the actual width of images when inlining them?
17659 When set to `t', always use the image width.
17661 When set to a number, use imagemagick (when available) to set
17662 the image's width to this value.
17664 When set to a number in a list, try to get the width from any
17665 #+ATTR.* keyword if it matches a width specification like
17667 #+ATTR_HTML: :width 300px
17669 and fall back on that number if none is found.
17671 When set to nil, try to get the width from an #+ATTR.* keyword
17672 and fall back on the original width if none is found.
17674 This requires Emacs >= 24.1, build with imagemagick support."
17675 :group 'org-appearance
17676 :version "24.4"
17677 :package-version '(Org . "8.0")
17678 :type '(choice
17679 (const :tag "Use the image width" t)
17680 (integer :tag "Use a number of pixels")
17681 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17682 (const :tag "Use #+ATTR* or don't resize" nil)))
17684 (defcustom org-agenda-inhibit-startup nil
17685 "Inhibit startup when preparing agenda buffers.
17686 When this variable is `t' (the default), the initialization of
17687 the Org agenda buffers is inhibited: e.g. the visibility state
17688 is not set, the tables are not re-aligned, etc."
17689 :type 'boolean
17690 :version "24.3"
17691 :group 'org-agenda)
17693 (defcustom org-agenda-ignore-drawer-properties nil
17694 "Avoid updating text properties when building the agenda.
17695 Properties are used to prepare buffers for effort estimates, appointments,
17696 and subtree-local categories.
17697 If you don't use these in the agenda, you can add them to this list and
17698 agenda building will be a bit faster.
17699 The value is a list, with zero or more of the symbols `effort', `appt',
17700 or `category'."
17701 :type '(set :greedy t
17702 (const effort)
17703 (const appt)
17704 (const category))
17705 :version "24.3"
17706 :group 'org-agenda)
17708 (defun org-duration-string-to-minutes (s &optional output-to-string)
17709 "Convert a duration string S to minutes.
17711 A bare number is interpreted as minutes, modifiers can be set by
17712 customizing `org-effort-durations' (which see).
17714 Entries containing a colon are interpreted as H:MM by
17715 `org-hh:mm-string-to-minutes'."
17716 (let ((result 0)
17717 (re (concat "\\([0-9.]+\\) *\\("
17718 (regexp-opt (mapcar 'car org-effort-durations))
17719 "\\)")))
17720 (while (string-match re s)
17721 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17722 (string-to-number (match-string 1 s))))
17723 (setq s (replace-match "" nil t s)))
17724 (setq result (floor result))
17725 (incf result (org-hh:mm-string-to-minutes s))
17726 (if output-to-string (number-to-string result) result)))
17728 ;;;; Files
17730 (defun org-save-all-org-buffers ()
17731 "Save all Org-mode buffers without user confirmation."
17732 (interactive)
17733 (message "Saving all Org-mode buffers...")
17734 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17735 (when (featurep 'org-id) (org-id-locations-save))
17736 (message "Saving all Org-mode buffers... done"))
17738 (defun org-revert-all-org-buffers ()
17739 "Revert all Org-mode buffers.
17740 Prompt for confirmation when there are unsaved changes.
17741 Be sure you know what you are doing before letting this function
17742 overwrite your changes.
17744 This function is useful in a setup where one tracks org files
17745 with a version control system, to revert on one machine after pulling
17746 changes from another. I believe the procedure must be like this:
17748 1. M-x org-save-all-org-buffers
17749 2. Pull changes from the other machine, resolve conflicts
17750 3. M-x org-revert-all-org-buffers"
17751 (interactive)
17752 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17753 (user-error "Abort"))
17754 (save-excursion
17755 (save-window-excursion
17756 (mapc
17757 (lambda (b)
17758 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17759 (with-current-buffer b buffer-file-name))
17760 (org-pop-to-buffer-same-window b)
17761 (revert-buffer t 'no-confirm)))
17762 (buffer-list))
17763 (when (and (featurep 'org-id) org-id-track-globally)
17764 (org-id-locations-load)))))
17766 ;;;; Agenda files
17768 ;;;###autoload
17769 (defun org-switchb (&optional arg)
17770 "Switch between Org buffers.
17771 With one prefix argument, restrict available buffers to files.
17772 With two prefix arguments, restrict available buffers to agenda files.
17774 Defaults to `iswitchb' for buffer name completion.
17775 Set `org-completion-use-ido' to make it use ido instead."
17776 (interactive "P")
17777 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17778 ((equal arg '(16)) (org-buffer-list 'agenda))
17779 (t (org-buffer-list))))
17780 (org-completion-use-iswitchb org-completion-use-iswitchb)
17781 (org-completion-use-ido org-completion-use-ido))
17782 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17783 (setq org-completion-use-iswitchb t))
17784 (org-pop-to-buffer-same-window
17785 (org-icompleting-read "Org buffer: "
17786 (mapcar 'list (mapcar 'buffer-name blist))
17787 nil t))))
17789 ;;; Define some older names previously used for this functionality
17790 ;;;###autoload
17791 (defalias 'org-ido-switchb 'org-switchb)
17792 ;;;###autoload
17793 (defalias 'org-iswitchb 'org-switchb)
17795 (defun org-buffer-list (&optional predicate exclude-tmp)
17796 "Return a list of Org buffers.
17797 PREDICATE can be `export', `files' or `agenda'.
17799 export restrict the list to Export buffers.
17800 files restrict the list to buffers visiting Org files.
17801 agenda restrict the list to buffers visiting agenda files.
17803 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17804 (let* ((bfn nil)
17805 (agenda-files (and (eq predicate 'agenda)
17806 (mapcar 'file-truename (org-agenda-files t))))
17807 (filter
17808 (cond
17809 ((eq predicate 'files)
17810 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17811 ((eq predicate 'export)
17812 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17813 ((eq predicate 'agenda)
17814 (lambda (b)
17815 (with-current-buffer b
17816 (and (derived-mode-p 'org-mode)
17817 (setq bfn (buffer-file-name b))
17818 (member (file-truename bfn) agenda-files)))))
17819 (t (lambda (b) (with-current-buffer b
17820 (or (derived-mode-p 'org-mode)
17821 (string-match "\*Org .*Export"
17822 (buffer-name b)))))))))
17823 (delq nil
17824 (mapcar
17825 (lambda(b)
17826 (if (and (funcall filter b)
17827 (or (not exclude-tmp)
17828 (not (string-match "tmp" (buffer-name b)))))
17830 nil))
17831 (buffer-list)))))
17833 (defun org-agenda-files (&optional unrestricted archives)
17834 "Get the list of agenda files.
17835 Optional UNRESTRICTED means return the full list even if a restriction
17836 is currently in place.
17837 When ARCHIVES is t, include all archive files that are really being
17838 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17839 `org-agenda-archives-mode' is t."
17840 (let ((files
17841 (cond
17842 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17843 ((stringp org-agenda-files) (org-read-agenda-file-list))
17844 ((listp org-agenda-files) org-agenda-files)
17845 (t (error "Invalid value of `org-agenda-files'")))))
17846 (setq files (apply 'append
17847 (mapcar (lambda (f)
17848 (if (file-directory-p f)
17849 (directory-files
17850 f t org-agenda-file-regexp)
17851 (list f)))
17852 files)))
17853 (when org-agenda-skip-unavailable-files
17854 (setq files (delq nil
17855 (mapcar (function
17856 (lambda (file)
17857 (and (file-readable-p file) file)))
17858 files))))
17859 (when (or (eq archives t)
17860 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17861 (setq files (org-add-archive-files files)))
17862 files))
17864 (defun org-agenda-file-p (&optional file)
17865 "Return non-nil, if FILE is an agenda file.
17866 If FILE is omitted, use the file associated with the current
17867 buffer."
17868 (member (or file (buffer-file-name))
17869 (org-agenda-files t)))
17871 (defun org-edit-agenda-file-list ()
17872 "Edit the list of agenda files.
17873 Depending on setup, this either uses customize to edit the variable
17874 `org-agenda-files', or it visits the file that is holding the list. In the
17875 latter case, the buffer is set up in a way that saving it automatically kills
17876 the buffer and restores the previous window configuration."
17877 (interactive)
17878 (if (stringp org-agenda-files)
17879 (let ((cw (current-window-configuration)))
17880 (find-file org-agenda-files)
17881 (org-set-local 'org-window-configuration cw)
17882 (org-add-hook 'after-save-hook
17883 (lambda ()
17884 (set-window-configuration
17885 (prog1 org-window-configuration
17886 (kill-buffer (current-buffer))))
17887 (org-install-agenda-files-menu)
17888 (message "New agenda file list installed"))
17889 nil 'local)
17890 (message "%s" (substitute-command-keys
17891 "Edit list and finish with \\[save-buffer]")))
17892 (customize-variable 'org-agenda-files)))
17894 (defun org-store-new-agenda-file-list (list)
17895 "Set new value for the agenda file list and save it correctly."
17896 (if (stringp org-agenda-files)
17897 (let ((fe (org-read-agenda-file-list t)) b u)
17898 (while (setq b (find-buffer-visiting org-agenda-files))
17899 (kill-buffer b))
17900 (with-temp-file org-agenda-files
17901 (insert
17902 (mapconcat
17903 (lambda (f) ;; Keep un-expanded entries.
17904 (if (setq u (assoc f fe))
17905 (cdr u)
17907 list "\n")
17908 "\n")))
17909 (let ((org-mode-hook nil) (org-inhibit-startup t)
17910 (org-insert-mode-line-in-empty-file nil))
17911 (setq org-agenda-files list)
17912 (customize-save-variable 'org-agenda-files org-agenda-files))))
17914 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17915 "Read the list of agenda files from a file.
17916 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17917 filenames, used by `org-store-new-agenda-file-list' to write back
17918 un-expanded file names."
17919 (when (file-directory-p org-agenda-files)
17920 (error "`org-agenda-files' cannot be a single directory"))
17921 (when (stringp org-agenda-files)
17922 (with-temp-buffer
17923 (insert-file-contents org-agenda-files)
17924 (mapcar
17925 (lambda (f)
17926 (let ((e (expand-file-name (substitute-in-file-name f)
17927 org-directory)))
17928 (if pair-with-expansion
17929 (cons e f)
17930 e)))
17931 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17933 ;;;###autoload
17934 (defun org-cycle-agenda-files ()
17935 "Cycle through the files in `org-agenda-files'.
17936 If the current buffer visits an agenda file, find the next one in the list.
17937 If the current buffer does not, find the first agenda file."
17938 (interactive)
17939 (let* ((fs (org-agenda-files t))
17940 (files (append fs (list (car fs))))
17941 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17942 file)
17943 (unless files (user-error "No agenda files"))
17944 (catch 'exit
17945 (while (setq file (pop files))
17946 (if (equal (file-truename file) tcf)
17947 (when (car files)
17948 (find-file (car files))
17949 (throw 'exit t))))
17950 (find-file (car fs)))
17951 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17953 (defun org-agenda-file-to-front (&optional to-end)
17954 "Move/add the current file to the top of the agenda file list.
17955 If the file is not present in the list, it is added to the front. If it is
17956 present, it is moved there. With optional argument TO-END, add/move to the
17957 end of the list."
17958 (interactive "P")
17959 (let ((org-agenda-skip-unavailable-files nil)
17960 (file-alist (mapcar (lambda (x)
17961 (cons (file-truename x) x))
17962 (org-agenda-files t)))
17963 (ctf (file-truename
17964 (or buffer-file-name
17965 (user-error "Please save the current buffer to a file"))))
17966 x had)
17967 (setq x (assoc ctf file-alist) had x)
17969 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17970 (if to-end
17971 (setq file-alist (append (delq x file-alist) (list x)))
17972 (setq file-alist (cons x (delq x file-alist))))
17973 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17974 (org-install-agenda-files-menu)
17975 (message "File %s to %s of agenda file list"
17976 (if had "moved" "added") (if to-end "end" "front"))))
17978 (defun org-remove-file (&optional file)
17979 "Remove current file from the list of files in variable `org-agenda-files'.
17980 These are the files which are being checked for agenda entries.
17981 Optional argument FILE means use this file instead of the current."
17982 (interactive)
17983 (let* ((org-agenda-skip-unavailable-files nil)
17984 (file (or file buffer-file-name
17985 (user-error "Current buffer does not visit a file")))
17986 (true-file (file-truename file))
17987 (afile (abbreviate-file-name file))
17988 (files (delq nil (mapcar
17989 (lambda (x)
17990 (if (equal true-file
17991 (file-truename x))
17992 nil x))
17993 (org-agenda-files t)))))
17994 (if (not (= (length files) (length (org-agenda-files t))))
17995 (progn
17996 (org-store-new-agenda-file-list files)
17997 (org-install-agenda-files-menu)
17998 (message "Removed file: %s" afile))
17999 (message "File was not in list: %s (not removed)" afile))))
18001 (defun org-file-menu-entry (file)
18002 (vector file (list 'find-file file) t))
18004 (defun org-check-agenda-file (file)
18005 "Make sure FILE exists. If not, ask user what to do."
18006 (when (not (file-exists-p file))
18007 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18008 (abbreviate-file-name file))
18009 (let ((r (downcase (read-char-exclusive))))
18010 (cond
18011 ((equal r ?r)
18012 (org-remove-file file)
18013 (throw 'nextfile t))
18014 (t (error "Abort"))))))
18016 (defun org-get-agenda-file-buffer (file)
18017 "Get a buffer visiting FILE. If the buffer needs to be created, add
18018 it to the list of buffers which might be released later."
18019 (let ((buf (org-find-base-buffer-visiting file)))
18020 (if buf
18021 buf ; just return it
18022 ;; Make a new buffer and remember it
18023 (setq buf (find-file-noselect file))
18024 (if buf (push buf org-agenda-new-buffers))
18025 buf)))
18027 (defun org-release-buffers (blist)
18028 "Release all buffers in list, asking the user for confirmation when needed.
18029 When a buffer is unmodified, it is just killed. When modified, it is saved
18030 \(if the user agrees) and then killed."
18031 (let (buf file)
18032 (while (setq buf (pop blist))
18033 (setq file (buffer-file-name buf))
18034 (when (and (buffer-modified-p buf)
18035 file
18036 (y-or-n-p (format "Save file %s? " file)))
18037 (with-current-buffer buf (save-buffer)))
18038 (kill-buffer buf))))
18040 (defun org-agenda-prepare-buffers (files)
18041 "Create buffers for all agenda files, protect archived trees and comments."
18042 (interactive)
18043 (let ((pa '(:org-archived t))
18044 (pc '(:org-comment t))
18045 (pall '(:org-archived t :org-comment t))
18046 (inhibit-read-only t)
18047 (org-inhibit-startup org-agenda-inhibit-startup)
18048 (rea (concat ":" org-archive-tag ":"))
18049 file re pos)
18050 (setq org-tag-alist-for-agenda nil
18051 org-tag-groups-alist-for-agenda nil)
18052 (save-window-excursion
18053 (save-restriction
18054 (while (setq file (pop files))
18055 (catch 'nextfile
18056 (if (bufferp file)
18057 (set-buffer file)
18058 (org-check-agenda-file file)
18059 (set-buffer (org-get-agenda-file-buffer file)))
18060 (widen)
18061 (org-set-regexps-and-options-for-tags)
18062 (setq pos (point))
18063 (goto-char (point-min))
18064 (let ((case-fold-search t))
18065 (when (search-forward "#+setupfile" nil t)
18066 ;; Don't set all regexps and options systematically as
18067 ;; this is only run for setting agenda tags from setup
18068 ;; file
18069 (org-set-regexps-and-options)))
18070 (or (memq 'category org-agenda-ignore-drawer-properties)
18071 (org-refresh-category-properties))
18072 (or (memq 'effort org-agenda-ignore-drawer-properties)
18073 (org-refresh-properties org-effort-property 'org-effort))
18074 (or (memq 'appt org-agenda-ignore-drawer-properties)
18075 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18076 (setq org-todo-keywords-for-agenda
18077 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18078 (setq org-done-keywords-for-agenda
18079 (append org-done-keywords-for-agenda org-done-keywords))
18080 (setq org-todo-keyword-alist-for-agenda
18081 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18082 (setq org-drawers-for-agenda
18083 (append org-drawers-for-agenda org-drawers))
18084 (setq org-tag-alist-for-agenda
18085 (org-uniquify
18086 (append org-tag-alist-for-agenda
18087 org-tag-alist
18088 org-tag-persistent-alist)))
18089 (if org-group-tags
18090 (setq org-tag-groups-alist-for-agenda
18091 (org-uniquify-alist
18092 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18093 (org-with-silent-modifications
18094 (save-excursion
18095 (remove-text-properties (point-min) (point-max) pall)
18096 (when org-agenda-skip-archived-trees
18097 (goto-char (point-min))
18098 (while (re-search-forward rea nil t)
18099 (if (org-at-heading-p t)
18100 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18101 (goto-char (point-min))
18102 (setq re (format org-heading-keyword-regexp-format
18103 org-comment-string))
18104 (while (re-search-forward re nil t)
18105 (add-text-properties
18106 (match-beginning 0) (org-end-of-subtree t) pc))))
18107 (goto-char pos)))))
18108 (setq org-todo-keywords-for-agenda
18109 (org-uniquify org-todo-keywords-for-agenda))
18110 (setq org-todo-keyword-alist-for-agenda
18111 (org-uniquify org-todo-keyword-alist-for-agenda))))
18114 ;;;; CDLaTeX minor mode
18116 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18117 "Keymap for the minor `org-cdlatex-mode'.")
18119 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18120 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18121 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18122 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18123 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18125 (defvar org-cdlatex-texmathp-advice-is-done nil
18126 "Flag remembering if we have applied the advice to texmathp already.")
18128 (define-minor-mode org-cdlatex-mode
18129 "Toggle the minor `org-cdlatex-mode'.
18130 This mode supports entering LaTeX environment and math in LaTeX fragments
18131 in Org-mode.
18132 \\{org-cdlatex-mode-map}"
18133 nil " OCDL" nil
18134 (when org-cdlatex-mode
18135 (require 'cdlatex)
18136 (run-hooks 'cdlatex-mode-hook)
18137 (cdlatex-compute-tables))
18138 (unless org-cdlatex-texmathp-advice-is-done
18139 (setq org-cdlatex-texmathp-advice-is-done t)
18140 (defadvice texmathp (around org-math-always-on activate)
18141 "Always return t in org-mode buffers.
18142 This is because we want to insert math symbols without dollars even outside
18143 the LaTeX math segments. If Orgmode thinks that point is actually inside
18144 an embedded LaTeX fragment, let texmathp do its job.
18145 \\[org-cdlatex-mode-map]"
18146 (interactive)
18147 (let (p)
18148 (cond
18149 ((not (derived-mode-p 'org-mode)) ad-do-it)
18150 ((eq this-command 'cdlatex-math-symbol)
18151 (setq ad-return-value t
18152 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18154 (let ((p (org-inside-LaTeX-fragment-p)))
18155 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18156 (setq ad-return-value t
18157 texmathp-why '("Org-mode embedded math" . 0))
18158 (if p ad-do-it)))))))))
18160 (defun turn-on-org-cdlatex ()
18161 "Unconditionally turn on `org-cdlatex-mode'."
18162 (org-cdlatex-mode 1))
18164 (defun org-try-cdlatex-tab ()
18165 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18166 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18167 - inside a LaTeX fragment, or
18168 - after the first word in a line, where an abbreviation expansion could
18169 insert a LaTeX environment."
18170 (when org-cdlatex-mode
18171 (cond
18172 ;; Before any word on the line: No expansion possible.
18173 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18174 ;; Just after first word on the line: Expand it. Make sure it
18175 ;; cannot happen on headlines, though.
18176 ((save-excursion
18177 (skip-chars-backward "a-zA-Z0-9*")
18178 (skip-chars-backward " \t")
18179 (and (bolp) (not (org-at-heading-p))))
18180 (cdlatex-tab) t)
18181 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18183 (defun org-cdlatex-underscore-caret (&optional arg)
18184 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18185 Revert to the normal definition outside of these fragments."
18186 (interactive "P")
18187 (if (org-inside-LaTeX-fragment-p)
18188 (call-interactively 'cdlatex-sub-superscript)
18189 (let (org-cdlatex-mode)
18190 (call-interactively (key-binding (vector last-input-event))))))
18192 (defun org-cdlatex-math-modify (&optional arg)
18193 "Execute `cdlatex-math-modify' in LaTeX fragments.
18194 Revert to the normal definition outside of these fragments."
18195 (interactive "P")
18196 (if (org-inside-LaTeX-fragment-p)
18197 (call-interactively 'cdlatex-math-modify)
18198 (let (org-cdlatex-mode)
18199 (call-interactively (key-binding (vector last-input-event))))))
18203 ;;;; LaTeX fragments
18205 (defvar org-latex-regexps
18206 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18207 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18208 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18209 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18210 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18211 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18212 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18213 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18214 "Regular expressions for matching embedded LaTeX.")
18216 (defun org-inside-LaTeX-fragment-p ()
18217 "Test if point is inside a LaTeX fragment.
18218 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18219 sequence appearing also before point.
18220 Even though the matchers for math are configurable, this function assumes
18221 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18222 delimiters are skipped when they have been removed by customization.
18223 The return value is nil, or a cons cell with the delimiter and the
18224 position of this delimiter.
18226 This function does a reasonably good job, but can locally be fooled by
18227 for example currency specifications. For example it will assume being in
18228 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18229 fragments that are properly closed, but during editing, we have to live
18230 with the uncertainty caused by missing closing delimiters. This function
18231 looks only before point, not after."
18232 (catch 'exit
18233 (let ((pos (point))
18234 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18235 (lim (progn
18236 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18237 (point)))
18238 dd-on str (start 0) m re)
18239 (goto-char pos)
18240 (when dodollar
18241 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18242 re (nth 1 (assoc "$" org-latex-regexps)))
18243 (while (string-match re str start)
18244 (cond
18245 ((= (match-end 0) (length str))
18246 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18247 ((= (match-end 0) (- (length str) 5))
18248 (throw 'exit nil))
18249 (t (setq start (match-end 0))))))
18250 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18251 (goto-char pos)
18252 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18253 (and (match-beginning 2) (throw 'exit nil))
18254 ;; count $$
18255 (while (re-search-backward "\\$\\$" lim t)
18256 (setq dd-on (not dd-on)))
18257 (goto-char pos)
18258 (if dd-on (cons "$$" m))))))
18260 (defun org-inside-latex-macro-p ()
18261 "Is point inside a LaTeX macro or its arguments?"
18262 (save-match-data
18263 (org-in-regexp
18264 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18266 (defvar org-latex-fragment-image-overlays nil
18267 "List of overlays carrying the images of latex fragments.")
18268 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18270 (defun org-remove-latex-fragment-image-overlays ()
18271 "Remove all overlays with LaTeX fragment images in current buffer."
18272 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18273 (setq org-latex-fragment-image-overlays nil))
18275 (defun org-preview-latex-fragment (&optional subtree)
18276 "Preview the LaTeX fragment at point, or all locally or globally.
18277 If the cursor is in a LaTeX fragment, create the image and overlay
18278 it over the source code. If there is no fragment at point, display
18279 all fragments in the current text, from one headline to the next. With
18280 prefix SUBTREE, display all fragments in the current subtree. With a
18281 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18282 the cursor is before the first headline,
18283 display all fragments in the buffer.
18284 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18285 (interactive "P")
18286 (unless buffer-file-name
18287 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18288 (when (display-graphic-p)
18289 (org-remove-latex-fragment-image-overlays)
18290 (save-excursion
18291 (save-restriction
18292 (let (beg end at msg)
18293 (cond
18294 ((or (equal subtree '(16))
18295 (not (save-excursion
18296 (re-search-backward org-outline-regexp-bol nil t))))
18297 (setq beg (point-min) end (point-max)
18298 msg "Creating images for buffer...%s"))
18299 ((equal subtree '(4))
18300 (org-back-to-heading)
18301 (setq beg (point) end (org-end-of-subtree t)
18302 msg "Creating images for subtree...%s"))
18304 (if (setq at (org-inside-LaTeX-fragment-p))
18305 (goto-char (max (point-min) (- (cdr at) 2)))
18306 (org-back-to-heading))
18307 (setq beg (point) end (progn (outline-next-heading) (point))
18308 msg (if at "Creating image...%s"
18309 "Creating images for entry...%s"))))
18310 (message msg "")
18311 (narrow-to-region beg end)
18312 (goto-char beg)
18313 (org-format-latex
18314 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18315 (file-name-nondirectory
18316 buffer-file-name)))
18317 default-directory 'overlays msg at 'forbuffer
18318 org-latex-create-formula-image-program)
18319 (message msg "done. Use `C-c C-c' to remove images."))))))
18321 (defun org-format-latex (prefix &optional dir overlays msg at
18322 forbuffer processing-type)
18323 "Replace LaTeX fragments with links to an image, and produce images.
18324 Some of the options can be changed using the variable
18325 `org-format-latex-options'."
18326 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18327 (let* ((prefixnodir (file-name-nondirectory prefix))
18328 (absprefix (expand-file-name prefix dir))
18329 (todir (file-name-directory absprefix))
18330 (opt org-format-latex-options)
18331 (optnew org-format-latex-options)
18332 (matchers (plist-get opt :matchers))
18333 (re-list org-latex-regexps)
18334 (cnt 0) txt hash link beg end re e checkdir
18335 string
18336 m n block-type block linkfile movefile ov)
18337 ;; Check the different regular expressions
18338 (while (setq e (pop re-list))
18339 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18340 block (if block-type "\n\n" ""))
18341 (when (member m matchers)
18342 (goto-char (point-min))
18343 (while (re-search-forward re nil t)
18344 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18345 (or (not overlays)
18346 (not (eq (get-char-property (match-beginning n)
18347 'org-overlay-type)
18348 'org-latex-overlay))))
18349 (cond
18350 ((eq processing-type 'verbatim))
18351 ((eq processing-type 'mathjax)
18352 ;; Prepare for MathJax processing.
18353 (setq string (match-string n))
18354 (when (member m '("$" "$1"))
18355 (save-excursion
18356 (delete-region (match-beginning n) (match-end n))
18357 (goto-char (match-beginning n))
18358 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18359 ((or (eq processing-type 'dvipng)
18360 (eq processing-type 'imagemagick))
18361 ;; Process to an image.
18362 (setq txt (match-string n)
18363 beg (match-beginning n) end (match-end n)
18364 cnt (1+ cnt))
18365 (let ((face (face-at-point))
18366 (fg (plist-get opt :foreground))
18367 (bg (plist-get opt :background))
18368 ;; Ensure full list is printed.
18369 print-length print-level)
18370 (when forbuffer
18371 ;; Get the colors from the face at point.
18372 (goto-char beg)
18373 (when (eq fg 'auto)
18374 (setq fg (face-attribute face :foreground nil 'default)))
18375 (when (eq bg 'auto)
18376 (setq bg (face-attribute face :background nil 'default)))
18377 (setq optnew (copy-sequence opt))
18378 (plist-put optnew :foreground fg)
18379 (plist-put optnew :background bg))
18380 (setq hash (sha1 (prin1-to-string
18381 (list org-format-latex-header
18382 org-latex-default-packages-alist
18383 org-latex-packages-alist
18384 org-format-latex-options
18385 forbuffer txt fg bg)))
18386 linkfile (format "%s_%s.png" prefix hash)
18387 movefile (format "%s_%s.png" absprefix hash)))
18388 (setq link (concat block "[[file:" linkfile "]]" block))
18389 (if msg (message msg cnt))
18390 (goto-char beg)
18391 (unless checkdir ; Ensure the directory exists.
18392 (setq checkdir t)
18393 (or (file-directory-p todir) (make-directory todir t)))
18394 (unless (file-exists-p movefile)
18395 (org-create-formula-image
18396 txt movefile optnew forbuffer processing-type))
18397 (if overlays
18398 (progn
18399 (mapc (lambda (o)
18400 (if (eq (overlay-get o 'org-overlay-type)
18401 'org-latex-overlay)
18402 (delete-overlay o)))
18403 (overlays-in beg end))
18404 (setq ov (make-overlay beg end))
18405 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18406 (if (featurep 'xemacs)
18407 (progn
18408 (overlay-put ov 'invisible t)
18409 (overlay-put
18410 ov 'end-glyph
18411 (make-glyph (vector 'png :file movefile))))
18412 (overlay-put
18413 ov 'display
18414 (list 'image :type 'png :file movefile :ascent 'center)))
18415 (push ov org-latex-fragment-image-overlays)
18416 (goto-char end))
18417 (delete-region beg end)
18418 (insert (org-add-props link
18419 (list 'org-latex-src
18420 (replace-regexp-in-string
18421 "\"" "" txt)
18422 'org-latex-src-embed-type
18423 (if block-type 'paragraph 'character))))))
18424 ((eq processing-type 'mathml)
18425 ;; Process to MathML
18426 (unless (save-match-data (org-format-latex-mathml-available-p))
18427 (user-error "LaTeX to MathML converter not configured"))
18428 (setq txt (match-string n)
18429 beg (match-beginning n) end (match-end n)
18430 cnt (1+ cnt))
18431 (if msg (message msg cnt))
18432 (goto-char beg)
18433 (delete-region beg end)
18434 (insert (org-format-latex-as-mathml
18435 txt block-type prefix dir)))
18437 (error "Unknown conversion type %s for LaTeX fragments"
18438 processing-type)))))))))
18440 (defun org-create-math-formula (latex-frag &optional mathml-file)
18441 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18442 Use `org-latex-to-mathml-convert-command'. If the conversion is
18443 sucessful, return the portion between \"<math...> </math>\"
18444 elements otherwise return nil. When MATHML-FILE is specified,
18445 write the results in to that file. When invoked as an
18446 interactive command, prompt for LATEX-FRAG, with initial value
18447 set to the current active region and echo the results for user
18448 inspection."
18449 (interactive (list (let ((frag (when (org-region-active-p)
18450 (buffer-substring-no-properties
18451 (region-beginning) (region-end)))))
18452 (read-string "LaTeX Fragment: " frag nil frag))))
18453 (unless latex-frag (error "Invalid LaTeX fragment"))
18454 (let* ((tmp-in-file (file-relative-name
18455 (make-temp-name (expand-file-name "ltxmathml-in"))))
18456 (ignore (write-region latex-frag nil tmp-in-file))
18457 (tmp-out-file (file-relative-name
18458 (make-temp-name (expand-file-name "ltxmathml-out"))))
18459 (cmd (format-spec
18460 org-latex-to-mathml-convert-command
18461 `((?j . ,(shell-quote-argument
18462 (expand-file-name org-latex-to-mathml-jar-file)))
18463 (?I . ,(shell-quote-argument tmp-in-file))
18464 (?o . ,(shell-quote-argument tmp-out-file)))))
18465 mathml shell-command-output)
18466 (when (org-called-interactively-p 'any)
18467 (unless (org-format-latex-mathml-available-p)
18468 (user-error "LaTeX to MathML converter not configured")))
18469 (message "Running %s" cmd)
18470 (setq shell-command-output (shell-command-to-string cmd))
18471 (setq mathml
18472 (when (file-readable-p tmp-out-file)
18473 (with-current-buffer (find-file-noselect tmp-out-file t)
18474 (goto-char (point-min))
18475 (when (re-search-forward
18476 (concat
18477 (regexp-quote
18478 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18479 "\\(.\\|\n\\)*"
18480 (regexp-quote "</math>")) nil t)
18481 (prog1 (match-string 0) (kill-buffer))))))
18482 (cond
18483 (mathml
18484 (setq mathml
18485 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18486 (when mathml-file
18487 (write-region mathml nil mathml-file))
18488 (when (org-called-interactively-p 'any)
18489 (message mathml)))
18490 ((message "LaTeX to MathML conversion failed")
18491 (message shell-command-output)))
18492 (delete-file tmp-in-file)
18493 (when (file-exists-p tmp-out-file)
18494 (delete-file tmp-out-file))
18495 mathml))
18497 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18498 prefix &optional dir)
18499 "Use `org-create-math-formula' but check local cache first."
18500 (let* ((absprefix (expand-file-name prefix dir))
18501 (print-length nil) (print-level nil)
18502 (formula-id (concat
18503 "formula-"
18504 (sha1
18505 (prin1-to-string
18506 (list latex-frag
18507 org-latex-to-mathml-convert-command)))))
18508 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18509 (formula-cache-dir (file-name-directory formula-cache)))
18511 (unless (file-directory-p formula-cache-dir)
18512 (make-directory formula-cache-dir t))
18514 (unless (file-exists-p formula-cache)
18515 (org-create-math-formula latex-frag formula-cache))
18517 (if (file-exists-p formula-cache)
18518 ;; Successful conversion. Return the link to MathML file.
18519 (org-add-props
18520 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18521 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18522 'org-latex-src-embed-type (if latex-frag-type
18523 'paragraph 'character)))
18524 ;; Failed conversion. Return the LaTeX fragment verbatim
18525 latex-frag)))
18527 (defun org-create-formula-image (string tofile options buffer &optional type)
18528 "Create an image from LaTeX source using dvipng or convert.
18529 This function calls either `org-create-formula-image-with-dvipng'
18530 or `org-create-formula-image-with-imagemagick' depending on the
18531 value of `org-latex-create-formula-image-program' or on the value
18532 of the optional TYPE variable.
18534 Note: ultimately these two function should be combined as they
18535 share a good deal of logic."
18536 (org-check-external-command
18537 "latex" "needed to convert LaTeX fragments to images")
18538 (funcall
18539 (case (or type org-latex-create-formula-image-program)
18540 ('dvipng
18541 (org-check-external-command
18542 "dvipng" "needed to convert LaTeX fragments to images")
18543 #'org-create-formula-image-with-dvipng)
18544 ('imagemagick
18545 (org-check-external-command
18546 "convert" "you need to install imagemagick")
18547 #'org-create-formula-image-with-imagemagick)
18548 (t (error
18549 "Invalid value of `org-latex-create-formula-image-program'")))
18550 string tofile options buffer))
18552 (declare-function org-export-get-backend "ox" (name))
18553 (declare-function org-export--get-global-options "ox" (&optional backend))
18554 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18555 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18556 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18557 (defun org-create-formula--latex-header ()
18558 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18559 (let ((info (org-combine-plists (org-export--get-global-options
18560 (org-export-get-backend 'latex))
18561 (org-export--get-inbuffer-options
18562 (org-export-get-backend 'latex)))))
18563 (org-latex-guess-babel-language
18564 (org-latex-guess-inputenc
18565 (org-splice-latex-header
18566 org-format-latex-header
18567 org-latex-default-packages-alist
18568 org-latex-packages-alist t
18569 (plist-get info :latex-header)))
18570 info)))
18572 ;; This function borrows from Ganesh Swami's latex2png.el
18573 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18574 "This calls dvipng."
18575 (require 'ox-latex)
18576 (let* ((tmpdir (if (featurep 'xemacs)
18577 (temp-directory)
18578 temporary-file-directory))
18579 (texfilebase (make-temp-name
18580 (expand-file-name "orgtex" tmpdir)))
18581 (texfile (concat texfilebase ".tex"))
18582 (dvifile (concat texfilebase ".dvi"))
18583 (pngfile (concat texfilebase ".png"))
18584 (fnh (if (featurep 'xemacs)
18585 (font-height (face-font 'default))
18586 (face-attribute 'default :height nil)))
18587 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18588 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18589 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18590 "Black"))
18591 (bg (or (plist-get options (if buffer :background :html-background))
18592 "Transparent")))
18593 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18594 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18595 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18596 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18597 (let ((latex-header (org-create-formula--latex-header)))
18598 (with-temp-file texfile
18599 (insert latex-header)
18600 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18601 (let ((dir default-directory))
18602 (condition-case nil
18603 (progn
18604 (cd tmpdir)
18605 (call-process "latex" nil nil nil texfile))
18606 (error nil))
18607 (cd dir))
18608 (if (not (file-exists-p dvifile))
18609 (progn (message "Failed to create dvi file from %s" texfile) nil)
18610 (condition-case nil
18611 (if (featurep 'xemacs)
18612 (call-process "dvipng" nil nil nil
18613 "-fg" fg "-bg" bg
18614 "-T" "tight"
18615 "-o" pngfile
18616 dvifile)
18617 (call-process "dvipng" nil nil nil
18618 "-fg" fg "-bg" bg
18619 "-D" dpi
18620 ;;"-x" scale "-y" scale
18621 "-T" "tight"
18622 "-o" pngfile
18623 dvifile))
18624 (error nil))
18625 (if (not (file-exists-p pngfile))
18626 (if org-format-latex-signal-error
18627 (error "Failed to create png file from %s" texfile)
18628 (message "Failed to create png file from %s" texfile)
18629 nil)
18630 ;; Use the requested file name and clean up
18631 (copy-file pngfile tofile 'replace)
18632 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18633 (if (file-exists-p (concat texfilebase e))
18634 (delete-file (concat texfilebase e))))
18635 pngfile))))
18637 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18638 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18639 "This calls convert, which is included into imagemagick."
18640 (require 'ox-latex)
18641 (let* ((tmpdir (if (featurep 'xemacs)
18642 (temp-directory)
18643 temporary-file-directory))
18644 (texfilebase (make-temp-name
18645 (expand-file-name "orgtex" tmpdir)))
18646 (texfile (concat texfilebase ".tex"))
18647 (pdffile (concat texfilebase ".pdf"))
18648 (pngfile (concat texfilebase ".png"))
18649 (fnh (if (featurep 'xemacs)
18650 (font-height (face-font 'default))
18651 (face-attribute 'default :height nil)))
18652 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18653 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18654 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18655 "black"))
18656 (bg (or (plist-get options (if buffer :background :html-background))
18657 "white")))
18658 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18659 (setq fg (org-latex-color-format fg)))
18660 (if (eq bg 'default) (setq bg (org-latex-color :background))
18661 (setq bg (org-latex-color-format
18662 (if (string= bg "Transparent") "white" bg))))
18663 (let ((latex-header (org-create-formula--latex-header)))
18664 (with-temp-file texfile
18665 (insert latex-header)
18666 (insert "\n\\begin{document}\n"
18667 "\\definecolor{fg}{rgb}{" fg "}\n"
18668 "\\definecolor{bg}{rgb}{" bg "}\n"
18669 "\n\\pagecolor{bg}\n"
18670 "\n{\\color{fg}\n"
18671 string
18672 "\n}\n"
18673 "\n\\end{document}\n")))
18674 (org-latex-compile texfile t)
18675 (if (not (file-exists-p pdffile))
18676 (progn (message "Failed to create pdf file from %s" texfile) nil)
18677 (condition-case nil
18678 (if (featurep 'xemacs)
18679 (call-process "convert" nil nil nil
18680 "-density" "96"
18681 "-trim"
18682 "-antialias"
18683 pdffile
18684 "-quality" "100"
18685 ;; "-sharpen" "0x1.0"
18686 pngfile)
18687 (call-process "convert" nil nil nil
18688 "-density" dpi
18689 "-trim"
18690 "-antialias"
18691 pdffile
18692 "-quality" "100"
18693 ;; "-sharpen" "0x1.0"
18694 pngfile))
18695 (error nil))
18696 (if (not (file-exists-p pngfile))
18697 (if org-format-latex-signal-error
18698 (error "Failed to create png file from %s" texfile)
18699 (message "Failed to create png file from %s" texfile)
18700 nil)
18701 ;; Use the requested file name and clean up
18702 (copy-file pngfile tofile 'replace)
18703 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18704 (if (file-exists-p (concat texfilebase e))
18705 (delete-file (concat texfilebase e))))
18706 pngfile))))
18708 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18709 "Fill a LaTeX header template TPL.
18710 In the template, the following place holders will be recognized:
18712 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18713 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18714 [PACKAGES] \\usepackage statements for PKG
18715 [NO-PACKAGES] do not include PKG
18716 [EXTRA] the string EXTRA
18717 [NO-EXTRA] do not include EXTRA
18719 For backward compatibility, if both the positive and the negative place
18720 holder is missing, the positive one (without the \"NO-\") will be
18721 assumed to be present at the end of the template.
18722 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18723 EXTRA is a string.
18724 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18725 (let (rpl (end ""))
18726 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18727 (setq rpl (if (or (match-end 1) (not def-pkg))
18728 "" (org-latex-packages-to-string def-pkg snippets-p t))
18729 tpl (replace-match rpl t t tpl))
18730 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18732 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18733 (setq rpl (if (or (match-end 1) (not pkg))
18734 "" (org-latex-packages-to-string pkg snippets-p t))
18735 tpl (replace-match rpl t t tpl))
18736 (if pkg (setq end
18737 (concat end "\n"
18738 (org-latex-packages-to-string pkg snippets-p)))))
18740 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18741 (setq rpl (if (or (match-end 1) (not extra))
18742 "" (concat extra "\n"))
18743 tpl (replace-match rpl t t tpl))
18744 (if (and extra (string-match "\\S-" extra))
18745 (setq end (concat end "\n" extra))))
18747 (if (string-match "\\S-" end)
18748 (concat tpl "\n" end)
18749 tpl)))
18751 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18752 "Turn an alist of packages into a string with the \\usepackage macros."
18753 (setq pkg (mapconcat (lambda(p)
18754 (cond
18755 ((stringp p) p)
18756 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18757 (format "%% Package %s omitted" (cadr p)))
18758 ((equal "" (car p))
18759 (format "\\usepackage{%s}" (cadr p)))
18761 (format "\\usepackage[%s]{%s}"
18762 (car p) (cadr p)))))
18764 "\n"))
18765 (if newline (concat pkg "\n") pkg))
18767 (defun org-dvipng-color (attr)
18768 "Return a RGB color specification for dvipng."
18769 (apply 'format "rgb %s %s %s"
18770 (mapcar 'org-normalize-color
18771 (if (featurep 'xemacs)
18772 (color-rgb-components
18773 (face-property 'default
18774 (cond ((eq attr :foreground) 'foreground)
18775 ((eq attr :background) 'background))))
18776 (color-values (face-attribute 'default attr nil))))))
18778 (defun org-dvipng-color-format (color-name)
18779 "Convert COLOR-NAME to a RGB color value for dvipng."
18780 (apply 'format "rgb %s %s %s"
18781 (mapcar 'org-normalize-color
18782 (color-values color-name))))
18784 (defun org-latex-color (attr)
18785 "Return a RGB color for the LaTeX color package."
18786 (apply 'format "%s,%s,%s"
18787 (mapcar 'org-normalize-color
18788 (if (featurep 'xemacs)
18789 (color-rgb-components
18790 (face-property 'default
18791 (cond ((eq attr :foreground) 'foreground)
18792 ((eq attr :background) 'background))))
18793 (color-values (face-attribute 'default attr nil))))))
18795 (defun org-latex-color-format (color-name)
18796 "Convert COLOR-NAME to a RGB color value."
18797 (apply 'format "%s,%s,%s"
18798 (mapcar 'org-normalize-color
18799 (color-values color-name))))
18801 (defun org-normalize-color (value)
18802 "Return string to be used as color value for an RGB component."
18803 (format "%g" (/ value 65535.0)))
18807 ;; Image display
18809 (defvar org-inline-image-overlays nil)
18810 (make-variable-buffer-local 'org-inline-image-overlays)
18812 (defun org-toggle-inline-images (&optional include-linked)
18813 "Toggle the display of inline images.
18814 INCLUDE-LINKED is passed to `org-display-inline-images'."
18815 (interactive "P")
18816 (if org-inline-image-overlays
18817 (progn
18818 (org-remove-inline-images)
18819 (message "Inline image display turned off"))
18820 (org-display-inline-images include-linked)
18821 (if (and (org-called-interactively-p)
18822 org-inline-image-overlays)
18823 (message "%d images displayed inline"
18824 (length org-inline-image-overlays))
18825 (message "No images to display inline"))))
18827 (defun org-redisplay-inline-images ()
18828 "Refresh the display of inline images."
18829 (interactive)
18830 (if (not org-inline-image-overlays)
18831 (org-toggle-inline-images)
18832 (org-toggle-inline-images)
18833 (org-toggle-inline-images)))
18835 (defun org-display-inline-images (&optional include-linked refresh beg end)
18836 "Display inline images.
18837 Normally only links without a description part are inlined, because this
18838 is how it will work for export. When INCLUDE-LINKED is set, also links
18839 with a description part will be inlined. This can be nice for a quick
18840 look at those images, but it does not reflect what exported files will look
18841 like.
18842 When REFRESH is set, refresh existing images between BEG and END.
18843 This will create new image displays only if necessary.
18844 BEG and END default to the buffer boundaries."
18845 (interactive "P")
18846 (when (display-graphic-p)
18847 (unless refresh
18848 (org-remove-inline-images)
18849 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18850 (save-excursion
18851 (save-restriction
18852 (widen)
18853 (setq beg (or beg (point-min)) end (or end (point-max)))
18854 (goto-char beg)
18855 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18856 (substring (org-image-file-name-regexp) 0 -2)
18857 "\\)\\]" (if include-linked "" "\\]")))
18858 (case-fold-search t)
18859 old file ov img type attrwidth width)
18860 (while (re-search-forward re end t)
18861 (setq old (get-char-property-and-overlay (match-beginning 1)
18862 'org-image-overlay)
18863 file (expand-file-name
18864 (concat (or (match-string 3) "") (match-string 4))))
18865 (when (image-type-available-p 'imagemagick)
18866 (setq attrwidth (if (or (listp org-image-actual-width)
18867 (null org-image-actual-width))
18868 (save-excursion
18869 (save-match-data
18870 (when (re-search-backward
18871 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18872 (save-excursion
18873 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18874 (string-to-number (match-string 1))))))
18875 width (cond ((eq org-image-actual-width t) nil)
18876 ((null org-image-actual-width) attrwidth)
18877 ((numberp org-image-actual-width)
18878 org-image-actual-width)
18879 ((listp org-image-actual-width)
18880 (or attrwidth (car org-image-actual-width))))
18881 type (if width 'imagemagick)))
18882 (when (file-exists-p file)
18883 (if (and (car-safe old) refresh)
18884 (image-refresh (overlay-get (cdr old) 'display))
18885 (setq img (save-match-data (create-image file type nil :width width)))
18886 (when img
18887 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18888 (overlay-put ov 'display img)
18889 (overlay-put ov 'face 'default)
18890 (overlay-put ov 'org-image-overlay t)
18891 (overlay-put ov 'modification-hooks
18892 (list 'org-display-inline-remove-overlay))
18893 (push ov org-inline-image-overlays))))))))))
18895 (define-obsolete-function-alias
18896 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18898 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18899 "Remove inline-display overlay if a corresponding region is modified."
18900 (let ((inhibit-modification-hooks t))
18901 (when (and ov after)
18902 (delete ov org-inline-image-overlays)
18903 (delete-overlay ov))))
18905 (defun org-remove-inline-images ()
18906 "Remove inline display of images."
18907 (interactive)
18908 (mapc 'delete-overlay org-inline-image-overlays)
18909 (setq org-inline-image-overlays nil))
18911 ;;;; Key bindings
18913 ;; Outline functions from `outline-mode-prefix-map'
18914 ;; that can be remapped in Org:
18915 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18916 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18917 (define-key org-mode-map [remap outline-forward-same-level]
18918 'org-forward-heading-same-level)
18919 (define-key org-mode-map [remap outline-backward-same-level]
18920 'org-backward-heading-same-level)
18921 (define-key org-mode-map [remap show-branches]
18922 'org-kill-note-or-show-branches)
18923 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18924 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18925 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18927 ;; Outline functions from `outline-mode-prefix-map' that can not
18928 ;; be remapped in Org:
18930 ;; - the column "key binding" shows whether the Outline function is still
18931 ;; available in Org mode on the same key that it has been bound to in
18932 ;; Outline mode:
18933 ;; - "overridden": key used for a different functionality in Org mode
18934 ;; - else: key still bound to the same Outline function in Org mode
18936 ;; | Outline function | key binding | Org replacement |
18937 ;; |------------------------------------+-------------+-----------------------|
18938 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18939 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18940 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18941 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18942 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18943 ;; | `show-entry' | overridden | no replacement |
18944 ;; | `show-children' | `C-c C-i' | visibility cycling |
18945 ;; | `show-branches' | `C-c C-k' | still same function |
18946 ;; | `show-subtree' | overridden | visibility cycling |
18947 ;; | `show-all' | overridden | no replacement |
18948 ;; | `hide-subtree' | overridden | visibility cycling |
18949 ;; | `hide-body' | overridden | no replacement |
18950 ;; | `hide-entry' | overridden | visibility cycling |
18951 ;; | `hide-leaves' | overridden | no replacement |
18952 ;; | `hide-sublevels' | overridden | no replacement |
18953 ;; | `hide-other' | overridden | no replacement |
18955 ;; Make `C-c C-x' a prefix key
18956 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18958 ;; TAB key with modifiers
18959 (org-defkey org-mode-map "\C-i" 'org-cycle)
18960 (org-defkey org-mode-map [(tab)] 'org-cycle)
18961 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18962 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18963 ;; The following line is necessary under Suse GNU/Linux
18964 (unless (featurep 'xemacs)
18965 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18966 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18967 (define-key org-mode-map [backtab] 'org-shifttab)
18969 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18970 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18971 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18973 ;; Cursor keys with modifiers
18974 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18975 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18976 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18977 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18979 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18980 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18981 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18982 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18984 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18985 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18986 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18987 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18989 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18990 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18991 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18992 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18994 ;; Babel keys
18995 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18996 (mapc (lambda (pair)
18997 (define-key org-babel-map (car pair) (cdr pair)))
18998 org-babel-key-bindings)
19000 ;;; Extra keys for tty access.
19001 ;; We only set them when really needed because otherwise the
19002 ;; menus don't show the simple keys
19004 (when (or org-use-extra-keys
19005 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19006 (not window-system))
19007 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19008 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19009 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19010 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19011 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19012 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19013 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19014 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19015 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19016 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19017 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19018 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19019 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19020 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19021 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19022 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19023 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19024 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19025 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19026 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19027 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19028 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19029 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19030 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19031 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19032 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19033 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19034 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19036 ;; All the other keys
19038 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19039 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19040 (if (boundp 'narrow-map)
19041 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19042 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19043 (if (boundp 'narrow-map)
19044 (org-defkey narrow-map "b" 'org-narrow-to-block)
19045 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19046 (if (boundp 'narrow-map)
19047 (org-defkey narrow-map "e" 'org-narrow-to-element)
19048 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19049 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19050 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19051 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19052 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19053 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19054 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19055 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19056 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19057 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19058 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19059 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19060 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19061 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19062 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19063 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19064 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19065 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19066 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19067 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19068 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19069 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19070 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19071 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19072 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19073 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19074 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19075 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19076 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19077 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19078 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19079 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19080 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19081 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19082 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19083 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19084 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19085 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19086 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19087 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19088 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19089 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19090 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19091 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19092 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19093 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19094 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19095 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19096 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19097 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19098 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19099 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19100 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19101 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19102 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19103 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19104 (org-defkey org-mode-map "\C-c^" 'org-sort)
19105 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19106 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19107 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19108 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19109 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19110 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19111 (org-defkey org-mode-map "\C-m" 'org-return)
19112 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19113 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19114 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19115 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19116 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19117 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19118 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19119 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19120 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19121 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19122 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19123 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19124 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19125 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19126 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19127 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19128 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19129 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19130 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19131 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19132 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19133 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19134 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19136 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19137 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19138 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19140 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19141 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19142 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19143 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19144 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19145 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19146 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19147 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19148 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19149 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19150 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19151 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19152 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19153 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19154 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19155 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19156 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19157 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19158 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19159 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19160 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19161 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19162 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19164 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19165 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19166 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19167 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19168 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19170 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19172 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19174 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19175 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19177 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19180 (when (featurep 'xemacs)
19181 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19184 (defconst org-speed-commands-default
19186 ("Outline Navigation")
19187 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19188 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19189 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19190 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19191 ("F" . org-next-block)
19192 ("B" . org-previous-block)
19193 ("u" . (org-speed-move-safe 'outline-up-heading))
19194 ("j" . org-goto)
19195 ("g" . (org-refile t))
19196 ("Outline Visibility")
19197 ("c" . org-cycle)
19198 ("C" . org-shifttab)
19199 (" " . org-display-outline-path)
19200 ("s" . org-narrow-to-subtree)
19201 ("=" . org-columns)
19202 ("Outline Structure Editing")
19203 ("U" . org-shiftmetaup)
19204 ("D" . org-shiftmetadown)
19205 ("r" . org-metaright)
19206 ("l" . org-metaleft)
19207 ("R" . org-shiftmetaright)
19208 ("L" . org-shiftmetaleft)
19209 ("i" . (progn (forward-char 1) (call-interactively
19210 'org-insert-heading-respect-content)))
19211 ("^" . org-sort)
19212 ("w" . org-refile)
19213 ("a" . org-archive-subtree-default-with-confirmation)
19214 ("@" . org-mark-subtree)
19215 ("#" . org-toggle-comment)
19216 ("Clock Commands")
19217 ("I" . org-clock-in)
19218 ("O" . org-clock-out)
19219 ("Meta Data Editing")
19220 ("t" . org-todo)
19221 ("," . (org-priority))
19222 ("0" . (org-priority ?\ ))
19223 ("1" . (org-priority ?A))
19224 ("2" . (org-priority ?B))
19225 ("3" . (org-priority ?C))
19226 (":" . org-set-tags-command)
19227 ("e" . org-set-effort)
19228 ("E" . org-inc-effort)
19229 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19230 (org-entry-put (point) "APPT_WARNTIME" m)))
19231 ("Agenda Views etc")
19232 ("v" . org-agenda)
19233 ("/" . org-sparse-tree)
19234 ("Misc")
19235 ("o" . org-open-at-point)
19236 ("?" . org-speed-command-help)
19237 ("<" . (org-agenda-set-restriction-lock 'subtree))
19238 (">" . (org-agenda-remove-restriction-lock))
19240 "The default speed commands.")
19242 (defun org-print-speed-command (e)
19243 (if (> (length (car e)) 1)
19244 (progn
19245 (princ "\n")
19246 (princ (car e))
19247 (princ "\n")
19248 (princ (make-string (length (car e)) ?-))
19249 (princ "\n"))
19250 (princ (car e))
19251 (princ " ")
19252 (if (symbolp (cdr e))
19253 (princ (symbol-name (cdr e)))
19254 (prin1 (cdr e)))
19255 (princ "\n")))
19257 (defun org-speed-command-help ()
19258 "Show the available speed commands."
19259 (interactive)
19260 (if (not org-use-speed-commands)
19261 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19262 (with-output-to-temp-buffer "*Help*"
19263 (princ "User-defined Speed commands\n===========================\n")
19264 (mapc 'org-print-speed-command org-speed-commands-user)
19265 (princ "\n")
19266 (princ "Built-in Speed commands\n=======================\n")
19267 (mapc 'org-print-speed-command org-speed-commands-default))
19268 (with-current-buffer "*Help*"
19269 (setq truncate-lines t))))
19271 (defun org-speed-move-safe (cmd)
19272 "Execute CMD, but make sure that the cursor always ends up in a headline.
19273 If not, return to the original position and throw an error."
19274 (interactive)
19275 (let ((pos (point)))
19276 (call-interactively cmd)
19277 (unless (and (bolp) (org-at-heading-p))
19278 (goto-char pos)
19279 (error "Boundary reached while executing %s" cmd))))
19281 (defvar org-self-insert-command-undo-counter 0)
19283 (defvar org-table-auto-blank-field) ; defined in org-table.el
19284 (defvar org-speed-command nil)
19286 (define-obsolete-function-alias
19287 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19289 (defun org-speed-command-activate (keys)
19290 "Hook for activating single-letter speed commands.
19291 `org-speed-commands-default' specifies a minimal command set.
19292 Use `org-speed-commands-user' for further customization."
19293 (when (or (and (bolp) (looking-at org-outline-regexp))
19294 (and (functionp org-use-speed-commands)
19295 (funcall org-use-speed-commands)))
19296 (cdr (assoc keys (append org-speed-commands-user
19297 org-speed-commands-default)))))
19299 (define-obsolete-function-alias
19300 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19302 (defun org-babel-speed-command-activate (keys)
19303 "Hook for activating single-letter code block commands."
19304 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19305 (cdr (assoc keys org-babel-key-bindings))))
19307 (defcustom org-speed-command-hook
19308 '(org-speed-command-default-hook org-babel-speed-command-hook)
19309 "Hook for activating speed commands at strategic locations.
19310 Hook functions are called in sequence until a valid handler is
19311 found.
19313 Each hook takes a single argument, a user-pressed command key
19314 which is also a `self-insert-command' from the global map.
19316 Within the hook, examine the cursor position and the command key
19317 and return nil or a valid handler as appropriate. Handler could
19318 be one of an interactive command, a function, or a form.
19320 Set `org-use-speed-commands' to non-nil value to enable this
19321 hook. The default setting is `org-speed-command-activate'."
19322 :group 'org-structure
19323 :version "24.1"
19324 :type 'hook)
19326 (defun org-self-insert-command (N)
19327 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19328 If the cursor is in a table looking at whitespace, the whitespace is
19329 overwritten, and the table is not marked as requiring realignment."
19330 (interactive "p")
19331 (org-check-before-invisible-edit 'insert)
19332 (cond
19333 ((and org-use-speed-commands
19334 (setq org-speed-command
19335 (run-hook-with-args-until-success
19336 'org-speed-command-hook (this-command-keys))))
19337 (cond
19338 ((commandp org-speed-command)
19339 (setq this-command org-speed-command)
19340 (call-interactively org-speed-command))
19341 ((functionp org-speed-command)
19342 (funcall org-speed-command))
19343 ((and org-speed-command (listp org-speed-command))
19344 (eval org-speed-command))
19345 (t (let (org-use-speed-commands)
19346 (call-interactively 'org-self-insert-command)))))
19347 ((and
19348 (org-table-p)
19349 (progn
19350 ;; check if we blank the field, and if that triggers align
19351 (and (featurep 'org-table) org-table-auto-blank-field
19352 (member last-command
19353 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19354 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19355 ;; got extra space, this field does not determine column width
19356 (let (org-table-may-need-update) (org-table-blank-field))
19357 ;; no extra space, this field may determine column width
19358 (org-table-blank-field)))
19360 (eq N 1)
19361 (looking-at "[^|\n]* |"))
19362 (let (org-table-may-need-update)
19363 (goto-char (1- (match-end 0)))
19364 (backward-delete-char 1)
19365 (goto-char (match-beginning 0))
19366 (self-insert-command N)))
19368 (setq org-table-may-need-update t)
19369 (self-insert-command N)
19370 (org-fix-tags-on-the-fly)
19371 (if org-self-insert-cluster-for-undo
19372 (if (not (eq last-command 'org-self-insert-command))
19373 (setq org-self-insert-command-undo-counter 1)
19374 (if (>= org-self-insert-command-undo-counter 20)
19375 (setq org-self-insert-command-undo-counter 1)
19376 (and (> org-self-insert-command-undo-counter 0)
19377 buffer-undo-list (listp buffer-undo-list)
19378 (not (cadr buffer-undo-list)) ; remove nil entry
19379 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19380 (setq org-self-insert-command-undo-counter
19381 (1+ org-self-insert-command-undo-counter))))))))
19383 (defun org-check-before-invisible-edit (kind)
19384 "Check is editing if kind KIND would be dangerous with invisible text around.
19385 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19386 ;; First, try to get out of here as quickly as possible, to reduce overhead
19387 (if (and org-catch-invisible-edits
19388 (or (not (boundp 'visible-mode)) (not visible-mode))
19389 (or (get-char-property (point) 'invisible)
19390 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19391 ;; OK, we need to take a closer look
19392 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19393 (invisible-before-point (if (bobp) nil (get-char-property
19394 (1- (point)) 'invisible)))
19395 (border-and-ok-direction
19397 ;; Check if we are acting predictably before invisible text
19398 (and invisible-at-point (not invisible-before-point)
19399 (memq kind '(insert delete-backward)))
19400 ;; Check if we are acting predictably after invisible text
19401 ;; This works not well, and I have turned it off. It seems
19402 ;; better to always show and stop after invisible text.
19403 ;; (and (not invisible-at-point) invisible-before-point
19404 ;; (memq kind '(insert delete)))
19406 (when (or (memq invisible-at-point '(outline org-hide-block t))
19407 (memq invisible-before-point '(outline org-hide-block t)))
19408 (if (eq org-catch-invisible-edits 'error)
19409 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19410 (if (and org-custom-properties-overlays
19411 (y-or-n-p "Display invisible properties in this buffer? "))
19412 (org-toggle-custom-properties-visibility)
19413 ;; Make the area visible
19414 (save-excursion
19415 (if invisible-before-point
19416 (goto-char (previous-single-char-property-change
19417 (point) 'invisible)))
19418 (org-cycle))
19419 (cond
19420 ((eq org-catch-invisible-edits 'show)
19421 ;; That's it, we do the edit after showing
19422 (message
19423 "Unfolding invisible region around point before editing")
19424 (sit-for 1))
19425 ((and (eq org-catch-invisible-edits 'smart)
19426 border-and-ok-direction)
19427 (message "Unfolding invisible region around point before editing"))
19429 ;; Don't do the edit, make the user repeat it in full visibility
19430 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19432 (defun org-fix-tags-on-the-fly ()
19433 (when (and (equal (char-after (point-at-bol)) ?*)
19434 (org-at-heading-p))
19435 (org-align-tags-here org-tags-column)))
19437 (defun org-delete-backward-char (N)
19438 "Like `delete-backward-char', insert whitespace at field end in tables.
19439 When deleting backwards, in tables this function will insert whitespace in
19440 front of the next \"|\" separator, to keep the table aligned. The table will
19441 still be marked for re-alignment if the field did fill the entire column,
19442 because, in this case the deletion might narrow the column."
19443 (interactive "p")
19444 (save-match-data
19445 (org-check-before-invisible-edit 'delete-backward)
19446 (if (and (org-table-p)
19447 (eq N 1)
19448 (string-match "|" (buffer-substring (point-at-bol) (point)))
19449 (looking-at ".*?|"))
19450 (let ((pos (point))
19451 (noalign (looking-at "[^|\n\r]* |"))
19452 (c org-table-may-need-update))
19453 (backward-delete-char N)
19454 (if (not overwrite-mode)
19455 (progn
19456 (skip-chars-forward "^|")
19457 (insert " ")
19458 (goto-char (1- pos))))
19459 ;; noalign: if there were two spaces at the end, this field
19460 ;; does not determine the width of the column.
19461 (if noalign (setq org-table-may-need-update c)))
19462 (backward-delete-char N)
19463 (org-fix-tags-on-the-fly))))
19465 (defun org-delete-char (N)
19466 "Like `delete-char', but insert whitespace at field end in tables.
19467 When deleting characters, in tables this function will insert whitespace in
19468 front of the next \"|\" separator, to keep the table aligned. The table will
19469 still be marked for re-alignment if the field did fill the entire column,
19470 because, in this case the deletion might narrow the column."
19471 (interactive "p")
19472 (save-match-data
19473 (org-check-before-invisible-edit 'delete)
19474 (if (and (org-table-p)
19475 (not (bolp))
19476 (not (= (char-after) ?|))
19477 (eq N 1))
19478 (if (looking-at ".*?|")
19479 (let ((pos (point))
19480 (noalign (looking-at "[^|\n\r]* |"))
19481 (c org-table-may-need-update))
19482 (replace-match
19483 (concat (substring (match-string 0) 1 -1) " |") nil t)
19484 (goto-char pos)
19485 ;; noalign: if there were two spaces at the end, this field
19486 ;; does not determine the width of the column.
19487 (if noalign (setq org-table-may-need-update c)))
19488 (delete-char N))
19489 (delete-char N)
19490 (org-fix-tags-on-the-fly))))
19492 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19493 (put 'org-self-insert-command 'delete-selection
19494 (lambda ()
19495 (not (run-hook-with-args-until-success
19496 'self-insert-uses-region-functions))))
19497 (put 'orgtbl-self-insert-command 'delete-selection
19498 (lambda ()
19499 (not (run-hook-with-args-until-success
19500 'self-insert-uses-region-functions))))
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 (defun org-remap (map &rest commands)
19516 "In MAP, remap the functions given in COMMANDS.
19517 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19518 (let (new old)
19519 (while commands
19520 (setq old (pop commands) new (pop commands))
19521 (if (fboundp 'command-remapping)
19522 (org-defkey map (vector 'remap old) new)
19523 (substitute-key-definition old new map global-map)))))
19525 (defun org-transpose-words ()
19526 "Transpose words for Org.
19527 This uses the `org-mode-transpose-word-syntax-table' syntax
19528 table, which interprets characters in `org-emphasis-alist' as
19529 word constituents."
19530 (interactive)
19531 (with-syntax-table org-mode-transpose-word-syntax-table
19532 (call-interactively 'transpose-words)))
19533 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19535 (when (eq org-enable-table-editor 'optimized)
19536 ;; If the user wants maximum table support, we need to hijack
19537 ;; some standard editing functions
19538 (org-remap org-mode-map
19539 'self-insert-command 'org-self-insert-command
19540 'delete-char 'org-delete-char
19541 'delete-backward-char 'org-delete-backward-char)
19542 (org-defkey org-mode-map "|" 'org-force-self-insert))
19544 (defvar org-ctrl-c-ctrl-c-hook nil
19545 "Hook for functions attaching themselves to `C-c C-c'.
19547 This can be used to add additional functionality to the C-c C-c
19548 key which executes context-dependent commands. This hook is run
19549 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19550 run after the last test.
19552 Each function will be called with no arguments. The function
19553 must check if the context is appropriate for it to act. If yes,
19554 it should do its thing and then return a non-nil value. If the
19555 context is wrong, just do nothing and return nil.")
19557 (defvar org-ctrl-c-ctrl-c-final-hook nil
19558 "Hook for functions attaching themselves to `C-c C-c'.
19560 This can be used to add additional functionality to the C-c C-c
19561 key which executes context-dependent commands. This hook is run
19562 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19563 before the first test.
19565 Each function will be called with no arguments. The function
19566 must check if the context is appropriate for it to act. If yes,
19567 it should do its thing and then return a non-nil value. If the
19568 context is wrong, just do nothing and return nil.")
19570 (defvar org-tab-first-hook nil
19571 "Hook for functions to attach themselves to TAB.
19572 See `org-ctrl-c-ctrl-c-hook' for more information.
19573 This hook runs as the first action when TAB is pressed, even before
19574 `org-cycle' messes around with the `outline-regexp' to cater for
19575 inline tasks and plain list item folding.
19576 If any function in this hook returns t, any other actions that
19577 would have been caused by TAB (such as table field motion or visibility
19578 cycling) will not occur.")
19580 (defvar org-tab-after-check-for-table-hook nil
19581 "Hook for functions to attach themselves to TAB.
19582 See `org-ctrl-c-ctrl-c-hook' for more information.
19583 This hook runs after it has been established that the cursor is not in a
19584 table, but before checking if the cursor is in a headline or if global cycling
19585 should be done.
19586 If any function in this hook returns t, not other actions like visibility
19587 cycling will be done.")
19589 (defvar org-tab-after-check-for-cycling-hook nil
19590 "Hook for functions to attach themselves to TAB.
19591 See `org-ctrl-c-ctrl-c-hook' for more information.
19592 This hook runs after it has been established that not table field motion and
19593 not visibility should be done because of current context. This is probably
19594 the place where a package like yasnippets can hook in.")
19596 (defvar org-tab-before-tab-emulation-hook nil
19597 "Hook for functions to attach themselves to TAB.
19598 See `org-ctrl-c-ctrl-c-hook' for more information.
19599 This hook runs after every other options for TAB have been exhausted, but
19600 before indentation and \t insertion takes place.")
19602 (defvar org-metaleft-hook nil
19603 "Hook for functions attaching themselves to `M-left'.
19604 See `org-ctrl-c-ctrl-c-hook' for more information.")
19605 (defvar org-metaright-hook nil
19606 "Hook for functions attaching themselves to `M-right'.
19607 See `org-ctrl-c-ctrl-c-hook' for more information.")
19608 (defvar org-metaup-hook nil
19609 "Hook for functions attaching themselves to `M-up'.
19610 See `org-ctrl-c-ctrl-c-hook' for more information.")
19611 (defvar org-metadown-hook nil
19612 "Hook for functions attaching themselves to `M-down'.
19613 See `org-ctrl-c-ctrl-c-hook' for more information.")
19614 (defvar org-shiftmetaleft-hook nil
19615 "Hook for functions attaching themselves to `M-S-left'.
19616 See `org-ctrl-c-ctrl-c-hook' for more information.")
19617 (defvar org-shiftmetaright-hook nil
19618 "Hook for functions attaching themselves to `M-S-right'.
19619 See `org-ctrl-c-ctrl-c-hook' for more information.")
19620 (defvar org-shiftmetaup-hook nil
19621 "Hook for functions attaching themselves to `M-S-up'.
19622 See `org-ctrl-c-ctrl-c-hook' for more information.")
19623 (defvar org-shiftmetadown-hook nil
19624 "Hook for functions attaching themselves to `M-S-down'.
19625 See `org-ctrl-c-ctrl-c-hook' for more information.")
19626 (defvar org-metareturn-hook nil
19627 "Hook for functions attaching themselves to `M-RET'.
19628 See `org-ctrl-c-ctrl-c-hook' for more information.")
19629 (defvar org-shiftup-hook nil
19630 "Hook for functions attaching themselves to `S-up'.
19631 See `org-ctrl-c-ctrl-c-hook' for more information.")
19632 (defvar org-shiftup-final-hook nil
19633 "Hook for functions attaching themselves to `S-up'.
19634 This one runs after all other options except shift-select have been excluded.
19635 See `org-ctrl-c-ctrl-c-hook' for more information.")
19636 (defvar org-shiftdown-hook nil
19637 "Hook for functions attaching themselves to `S-down'.
19638 See `org-ctrl-c-ctrl-c-hook' for more information.")
19639 (defvar org-shiftdown-final-hook nil
19640 "Hook for functions attaching themselves to `S-down'.
19641 This one runs after all other options except shift-select have been excluded.
19642 See `org-ctrl-c-ctrl-c-hook' for more information.")
19643 (defvar org-shiftleft-hook nil
19644 "Hook for functions attaching themselves to `S-left'.
19645 See `org-ctrl-c-ctrl-c-hook' for more information.")
19646 (defvar org-shiftleft-final-hook nil
19647 "Hook for functions attaching themselves to `S-left'.
19648 This one runs after all other options except shift-select have been excluded.
19649 See `org-ctrl-c-ctrl-c-hook' for more information.")
19650 (defvar org-shiftright-hook nil
19651 "Hook for functions attaching themselves to `S-right'.
19652 See `org-ctrl-c-ctrl-c-hook' for more information.")
19653 (defvar org-shiftright-final-hook nil
19654 "Hook for functions attaching themselves to `S-right'.
19655 This one runs after all other options except shift-select have been excluded.
19656 See `org-ctrl-c-ctrl-c-hook' for more information.")
19658 (defun org-modifier-cursor-error ()
19659 "Throw an error, a modified cursor command was applied in wrong context."
19660 (user-error "This command is active in special context like tables, headlines or items"))
19662 (defun org-shiftselect-error ()
19663 "Throw an error because Shift-Cursor command was applied in wrong context."
19664 (if (and (boundp 'shift-select-mode) shift-select-mode)
19665 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19666 (user-error "This command works only in special context like headlines or timestamps")))
19668 (defun org-call-for-shift-select (cmd)
19669 (let ((this-command-keys-shift-translated t))
19670 (call-interactively cmd)))
19672 (defun org-shifttab (&optional arg)
19673 "Global visibility cycling or move to previous table field.
19674 Call `org-table-previous-field' within a table.
19675 When ARG is nil, cycle globally through visibility states.
19676 When ARG is a numeric prefix, show contents of this level."
19677 (interactive "P")
19678 (cond
19679 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19680 ((integerp arg)
19681 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19682 (message "Content view to level: %d" arg)
19683 (org-content (prefix-numeric-value arg2))
19684 (org-cycle-show-empty-lines t)
19685 (setq org-cycle-global-status 'overview)))
19686 (t (call-interactively 'org-global-cycle))))
19688 (defun org-shiftmetaleft ()
19689 "Promote subtree or delete table column.
19690 Calls `org-promote-subtree', `org-outdent-item-tree', or
19691 `org-table-delete-column', depending on context. See the
19692 individual commands for more information."
19693 (interactive)
19694 (cond
19695 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19696 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19697 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19698 ((if (not (org-region-active-p)) (org-at-item-p)
19699 (save-excursion (goto-char (region-beginning))
19700 (org-at-item-p)))
19701 (call-interactively 'org-outdent-item-tree))
19702 (t (org-modifier-cursor-error))))
19704 (defun org-shiftmetaright ()
19705 "Demote subtree or insert table column.
19706 Calls `org-demote-subtree', `org-indent-item-tree', or
19707 `org-table-insert-column', depending on context. See the
19708 individual commands for more information."
19709 (interactive)
19710 (cond
19711 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19712 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19713 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19714 ((if (not (org-region-active-p)) (org-at-item-p)
19715 (save-excursion (goto-char (region-beginning))
19716 (org-at-item-p)))
19717 (call-interactively 'org-indent-item-tree))
19718 (t (org-modifier-cursor-error))))
19720 (defun org-shiftmetaup (&optional arg)
19721 "Move subtree up or kill table row.
19722 Calls `org-move-subtree-up' or `org-table-kill-row' or
19723 `org-move-item-up' or `org-timestamp-up', depending on context.
19724 See the individual commands for more information."
19725 (interactive "P")
19726 (cond
19727 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19728 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19729 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19730 ((org-at-item-p) (call-interactively 'org-move-item-up))
19731 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19732 (call-interactively 'org-timestamp-up)))
19733 (t (call-interactively 'org-drag-line-backward))))
19735 (defun org-shiftmetadown (&optional arg)
19736 "Move subtree down or insert table row.
19737 Calls `org-move-subtree-down' or `org-table-insert-row' or
19738 `org-move-item-down' or `org-timestamp-up', depending on context.
19739 See the individual commands for more information."
19740 (interactive "P")
19741 (cond
19742 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19743 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19744 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19745 ((org-at-item-p) (call-interactively 'org-move-item-down))
19746 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19747 (call-interactively 'org-timestamp-down)))
19748 (t (call-interactively 'org-drag-line-forward))))
19750 (defsubst org-hidden-tree-error ()
19751 (user-error
19752 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19754 (defun org-metaleft (&optional arg)
19755 "Promote heading or move table column to left.
19756 Calls `org-do-promote' or `org-table-move-column', depending on context.
19757 With no specific context, calls the Emacs default `backward-word'.
19758 See the individual commands for more information."
19759 (interactive "P")
19760 (cond
19761 ((run-hook-with-args-until-success 'org-metaleft-hook))
19762 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19763 ((org-with-limited-levels
19764 (or (org-at-heading-p)
19765 (and (org-region-active-p)
19766 (save-excursion
19767 (goto-char (region-beginning))
19768 (org-at-heading-p)))))
19769 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19770 (call-interactively 'org-do-promote))
19771 ;; At an inline task.
19772 ((org-at-heading-p)
19773 (call-interactively 'org-inlinetask-promote))
19774 ((or (org-at-item-p)
19775 (and (org-region-active-p)
19776 (save-excursion
19777 (goto-char (region-beginning))
19778 (org-at-item-p))))
19779 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19780 (call-interactively 'org-outdent-item))
19781 (t (call-interactively 'backward-word))))
19783 (defun org-metaright (&optional arg)
19784 "Demote a subtree, a list item or move table column to right.
19785 In front of a drawer or a block keyword, indent it correctly.
19786 With no specific context, calls the Emacs default `forward-word'.
19787 See the individual commands for more information."
19788 (interactive "P")
19789 (cond
19790 ((run-hook-with-args-until-success 'org-metaright-hook))
19791 ((org-at-table-p) (call-interactively 'org-table-move-column))
19792 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19793 ((org-at-block-p) (call-interactively 'org-indent-block))
19794 ((org-with-limited-levels
19795 (or (org-at-heading-p)
19796 (and (org-region-active-p)
19797 (save-excursion
19798 (goto-char (region-beginning))
19799 (org-at-heading-p)))))
19800 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19801 (call-interactively 'org-do-demote))
19802 ;; At an inline task.
19803 ((org-at-heading-p)
19804 (call-interactively 'org-inlinetask-demote))
19805 ((or (org-at-item-p)
19806 (and (org-region-active-p)
19807 (save-excursion
19808 (goto-char (region-beginning))
19809 (org-at-item-p))))
19810 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19811 (call-interactively 'org-indent-item))
19812 (t (call-interactively 'forward-word))))
19814 (defun org-check-for-hidden (what)
19815 "Check if there are hidden headlines/items in the current visual line.
19816 WHAT can be either `headlines' or `items'. If the current line is
19817 an outline or item heading and it has a folded subtree below it,
19818 this function returns t, nil otherwise."
19819 (let ((re (cond
19820 ((eq what 'headlines) org-outline-regexp-bol)
19821 ((eq what 'items) (org-item-beginning-re))
19822 (t (error "This should not happen"))))
19823 beg end)
19824 (save-excursion
19825 (catch 'exit
19826 (unless (org-region-active-p)
19827 (setq beg (point-at-bol))
19828 (beginning-of-line 2)
19829 (while (and (not (eobp)) ;; this is like `next-line'
19830 (get-char-property (1- (point)) 'invisible))
19831 (beginning-of-line 2))
19832 (setq end (point))
19833 (goto-char beg)
19834 (goto-char (point-at-eol))
19835 (setq end (max end (point)))
19836 (while (re-search-forward re end t)
19837 (if (get-char-property (match-beginning 0) 'invisible)
19838 (throw 'exit t))))
19839 nil))))
19841 (defun org-metaup (&optional arg)
19842 "Move subtree up or move table row up.
19843 Calls `org-move-subtree-up' or `org-table-move-row' or
19844 `org-move-item-up', depending on context. See the individual commands
19845 for more information."
19846 (interactive "P")
19847 (cond
19848 ((run-hook-with-args-until-success 'org-metaup-hook))
19849 ((org-region-active-p)
19850 (let* ((a (min (region-beginning) (region-end)))
19851 (b (1- (max (region-beginning) (region-end))))
19852 (c (save-excursion (goto-char a)
19853 (move-beginning-of-line 0)))
19854 (d (save-excursion (goto-char a)
19855 (move-end-of-line 0) (point))))
19856 (transpose-regions a b c d)
19857 (goto-char c)))
19858 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19859 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19860 ((org-at-item-p) (call-interactively 'org-move-item-up))
19861 (t (org-drag-element-backward))))
19863 (defun org-metadown (&optional arg)
19864 "Move subtree down or move table row down.
19865 Calls `org-move-subtree-down' or `org-table-move-row' or
19866 `org-move-item-down', depending on context. See the individual
19867 commands for more information."
19868 (interactive "P")
19869 (cond
19870 ((run-hook-with-args-until-success 'org-metadown-hook))
19871 ((org-region-active-p)
19872 (let* ((a (min (region-beginning) (region-end)))
19873 (b (max (region-beginning) (region-end)))
19874 (c (save-excursion (goto-char b)
19875 (move-beginning-of-line 1)))
19876 (d (save-excursion (goto-char b)
19877 (move-end-of-line 1) (1+ (point)))))
19878 (transpose-regions a b c d)
19879 (goto-char d)))
19880 ((org-at-table-p) (call-interactively 'org-table-move-row))
19881 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19882 ((org-at-item-p) (call-interactively 'org-move-item-down))
19883 (t (org-drag-element-forward))))
19885 (defun org-shiftup (&optional arg)
19886 "Increase item in timestamp or increase priority of current headline.
19887 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19888 depending on context. See the individual commands for more information."
19889 (interactive "P")
19890 (cond
19891 ((run-hook-with-args-until-success 'org-shiftup-hook))
19892 ((and org-support-shift-select (org-region-active-p))
19893 (org-call-for-shift-select 'previous-line))
19894 ((org-at-timestamp-p t)
19895 (call-interactively (if org-edit-timestamp-down-means-later
19896 'org-timestamp-down 'org-timestamp-up)))
19897 ((and (not (eq org-support-shift-select 'always))
19898 org-enable-priority-commands
19899 (org-at-heading-p))
19900 (call-interactively 'org-priority-up))
19901 ((and (not org-support-shift-select) (org-at-item-p))
19902 (call-interactively 'org-previous-item))
19903 ((org-clocktable-try-shift 'up arg))
19904 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19905 (org-support-shift-select
19906 (org-call-for-shift-select 'previous-line))
19907 (t (org-shiftselect-error))))
19909 (defun org-shiftdown (&optional arg)
19910 "Decrease item in timestamp or decrease priority of current headline.
19911 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19912 depending on context. See the individual commands for more information."
19913 (interactive "P")
19914 (cond
19915 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19916 ((and org-support-shift-select (org-region-active-p))
19917 (org-call-for-shift-select 'next-line))
19918 ((org-at-timestamp-p t)
19919 (call-interactively (if org-edit-timestamp-down-means-later
19920 'org-timestamp-up 'org-timestamp-down)))
19921 ((and (not (eq org-support-shift-select 'always))
19922 org-enable-priority-commands
19923 (org-at-heading-p))
19924 (call-interactively 'org-priority-down))
19925 ((and (not org-support-shift-select) (org-at-item-p))
19926 (call-interactively 'org-next-item))
19927 ((org-clocktable-try-shift 'down arg))
19928 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19929 (org-support-shift-select
19930 (org-call-for-shift-select 'next-line))
19931 (t (org-shiftselect-error))))
19933 (defun org-shiftright (&optional arg)
19934 "Cycle the thing at point or in the current line, depending on context.
19935 Depending on context, this does one of the following:
19937 - switch a timestamp at point one day into the future
19938 - on a headline, switch to the next TODO keyword.
19939 - on an item, switch entire list to the next bullet type
19940 - on a property line, switch to the next allowed value
19941 - on a clocktable definition line, move time block into the future"
19942 (interactive "P")
19943 (cond
19944 ((run-hook-with-args-until-success 'org-shiftright-hook))
19945 ((and org-support-shift-select (org-region-active-p))
19946 (org-call-for-shift-select 'forward-char))
19947 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19948 ((and (not (eq org-support-shift-select 'always))
19949 (org-at-heading-p))
19950 (let ((org-inhibit-logging
19951 (not org-treat-S-cursor-todo-selection-as-state-change))
19952 (org-inhibit-blocking
19953 (not org-treat-S-cursor-todo-selection-as-state-change)))
19954 (org-call-with-arg 'org-todo 'right)))
19955 ((or (and org-support-shift-select
19956 (not (eq org-support-shift-select 'always))
19957 (org-at-item-bullet-p))
19958 (and (not org-support-shift-select) (org-at-item-p)))
19959 (org-call-with-arg 'org-cycle-list-bullet nil))
19960 ((and (not (eq org-support-shift-select 'always))
19961 (org-at-property-p))
19962 (call-interactively 'org-property-next-allowed-value))
19963 ((org-clocktable-try-shift 'right arg))
19964 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19965 (org-support-shift-select
19966 (org-call-for-shift-select 'forward-char))
19967 (t (org-shiftselect-error))))
19969 (defun org-shiftleft (&optional arg)
19970 "Cycle the thing at point or in the current line, depending on context.
19971 Depending on context, this does one of the following:
19973 - switch a timestamp at point one day into the past
19974 - on a headline, switch to the previous TODO keyword.
19975 - on an item, switch entire list to the previous bullet type
19976 - on a property line, switch to the previous allowed value
19977 - on a clocktable definition line, move time block into the past"
19978 (interactive "P")
19979 (cond
19980 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19981 ((and org-support-shift-select (org-region-active-p))
19982 (org-call-for-shift-select 'backward-char))
19983 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19984 ((and (not (eq org-support-shift-select 'always))
19985 (org-at-heading-p))
19986 (let ((org-inhibit-logging
19987 (not org-treat-S-cursor-todo-selection-as-state-change))
19988 (org-inhibit-blocking
19989 (not org-treat-S-cursor-todo-selection-as-state-change)))
19990 (org-call-with-arg 'org-todo 'left)))
19991 ((or (and org-support-shift-select
19992 (not (eq org-support-shift-select 'always))
19993 (org-at-item-bullet-p))
19994 (and (not org-support-shift-select) (org-at-item-p)))
19995 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19996 ((and (not (eq org-support-shift-select 'always))
19997 (org-at-property-p))
19998 (call-interactively 'org-property-previous-allowed-value))
19999 ((org-clocktable-try-shift 'left arg))
20000 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20001 (org-support-shift-select
20002 (org-call-for-shift-select 'backward-char))
20003 (t (org-shiftselect-error))))
20005 (defun org-shiftcontrolright ()
20006 "Switch to next TODO set."
20007 (interactive)
20008 (cond
20009 ((and org-support-shift-select (org-region-active-p))
20010 (org-call-for-shift-select 'forward-word))
20011 ((and (not (eq org-support-shift-select 'always))
20012 (org-at-heading-p))
20013 (org-call-with-arg 'org-todo 'nextset))
20014 (org-support-shift-select
20015 (org-call-for-shift-select 'forward-word))
20016 (t (org-shiftselect-error))))
20018 (defun org-shiftcontrolleft ()
20019 "Switch to previous TODO set."
20020 (interactive)
20021 (cond
20022 ((and org-support-shift-select (org-region-active-p))
20023 (org-call-for-shift-select 'backward-word))
20024 ((and (not (eq org-support-shift-select 'always))
20025 (org-at-heading-p))
20026 (org-call-with-arg 'org-todo 'previousset))
20027 (org-support-shift-select
20028 (org-call-for-shift-select 'backward-word))
20029 (t (org-shiftselect-error))))
20031 (defun org-shiftcontrolup (&optional n)
20032 "Change timestamps synchronously up in CLOCK log lines.
20033 Optional argument N tells to change by that many units."
20034 (interactive "P")
20035 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20036 (let (org-support-shift-select)
20037 (org-clock-timestamps-up n))
20038 (user-error "Not at a clock log")))
20040 (defun org-shiftcontroldown (&optional n)
20041 "Change timestamps synchronously down in CLOCK log lines.
20042 Optional argument N tells to change by that many units."
20043 (interactive "P")
20044 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20045 (let (org-support-shift-select)
20046 (org-clock-timestamps-down n))
20047 (user-error "Not at a clock log")))
20049 (defun org-ctrl-c-ret ()
20050 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20051 (interactive)
20052 (cond
20053 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20054 (t (call-interactively 'org-insert-heading))))
20056 (defun org-find-visible ()
20057 (let ((s (point)))
20058 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20059 (get-char-property s 'invisible)))
20061 (defun org-find-invisible ()
20062 (let ((s (point)))
20063 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20064 (not (get-char-property s 'invisible))))
20067 (defun org-copy-visible (beg end)
20068 "Copy the visible parts of the region."
20069 (interactive "r")
20070 (let (snippets s)
20071 (save-excursion
20072 (save-restriction
20073 (narrow-to-region beg end)
20074 (setq s (goto-char (point-min)))
20075 (while (not (= (point) (point-max)))
20076 (goto-char (org-find-invisible))
20077 (push (buffer-substring s (point)) snippets)
20078 (setq s (goto-char (org-find-visible))))))
20079 (kill-new (apply 'concat (nreverse snippets)))))
20081 (defun org-copy-special ()
20082 "Copy region in table or copy current subtree.
20083 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20084 See the individual commands for more information."
20085 (interactive)
20086 (call-interactively
20087 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20089 (defun org-cut-special ()
20090 "Cut region in table or cut current subtree.
20091 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20092 See the individual commands for more information."
20093 (interactive)
20094 (call-interactively
20095 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20097 (defun org-paste-special (arg)
20098 "Paste rectangular region into table, or past subtree relative to level.
20099 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20100 See the individual commands for more information."
20101 (interactive "P")
20102 (if (org-at-table-p)
20103 (org-table-paste-rectangle)
20104 (org-paste-subtree arg)))
20106 (defsubst org-in-fixed-width-region-p ()
20107 "Is point in a fixed-width region?"
20108 (save-match-data
20109 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20111 (defun org-edit-special (&optional arg)
20112 "Call a special editor for the element at point.
20113 When at a table, call the formula editor with `org-table-edit-formulas'.
20114 When in a source code block, call `org-edit-src-code'.
20115 When in a fixed-width region, call `org-edit-fixed-width-region'.
20116 When at an #+INCLUDE keyword, visit the included file.
20117 On a link, call `ffap' to visit the link at point.
20118 Otherwise, return a user error."
20119 (interactive "P")
20120 (let ((element (org-element-at-point)))
20121 (assert (not buffer-read-only) nil
20122 "Buffer is read-only: %s" (buffer-name))
20123 (case (org-element-type element)
20124 (src-block
20125 (if (not arg) (org-edit-src-code)
20126 (let* ((info (org-babel-get-src-block-info))
20127 (lang (nth 0 info))
20128 (params (nth 2 info))
20129 (session (cdr (assq :session params))))
20130 (if (not session) (org-edit-src-code)
20131 ;; At a src-block with a session and function called with
20132 ;; an ARG: switch to the buffer related to the inferior
20133 ;; process.
20134 (switch-to-buffer
20135 (funcall (intern (concat "org-babel-prep-session:" lang))
20136 session params))))))
20137 (keyword
20138 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20139 (find-file
20140 (org-remove-double-quotes
20141 (car (org-split-string (org-element-property :value element)))))
20142 (user-error "No special environment to edit here")))
20143 (table
20144 (if (eq (org-element-property :type element) 'table.el)
20145 (org-edit-src-code)
20146 (call-interactively 'org-table-edit-formulas)))
20147 ;; Only Org tables contain `table-row' type elements.
20148 (table-row (call-interactively 'org-table-edit-formulas))
20149 ((example-block export-block) (org-edit-src-code))
20150 (fixed-width (org-edit-fixed-width-region))
20151 (otherwise
20152 ;; No notable element at point. Though, we may be at a link,
20153 ;; which is an object. Thus, scan deeper.
20154 (if (eq (org-element-type (org-element-context element)) 'link)
20155 (call-interactively 'ffap)
20156 (user-error "No special environment to edit here"))))))
20158 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20159 (defun org-ctrl-c-ctrl-c (&optional arg)
20160 "Set tags in headline, or update according to changed information at point.
20162 This command does many different things, depending on context:
20164 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20165 this is what we do.
20167 - If the cursor is on a statistics cookie, update it.
20169 - If the cursor is in a headline, prompt for tags and insert them
20170 into the current line, aligned to `org-tags-column'. When called
20171 with prefix arg, realign all tags in the current buffer.
20173 - If the cursor is in one of the special #+KEYWORD lines, this
20174 triggers scanning the buffer for these lines and updating the
20175 information.
20177 - If the cursor is inside a table, realign the table. This command
20178 works even if the automatic table editor has been turned off.
20180 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20181 the entire table.
20183 - If the cursor is at a footnote reference or definition, jump to
20184 the corresponding definition or references, respectively.
20186 - If the cursor is a the beginning of a dynamic block, update it.
20188 - If the current buffer is a capture buffer, close note and file it.
20190 - If the cursor is on a <<<target>>>, update radio targets and
20191 corresponding links in this buffer.
20193 - If the cursor is on a numbered item in a plain list, renumber the
20194 ordered list.
20196 - If the cursor is on a checkbox, toggle it.
20198 - If the cursor is on a code block, evaluate it. The variable
20199 `org-confirm-babel-evaluate' can be used to control prompting
20200 before code block evaluation, by default every code block
20201 evaluation requires confirmation. Code block evaluation can be
20202 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20203 (interactive "P")
20204 (cond
20205 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20206 org-occur-highlights
20207 org-latex-fragment-image-overlays)
20208 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20209 (org-remove-occur-highlights)
20210 (org-remove-latex-fragment-image-overlays)
20211 (message "Temporary highlights/overlays removed from current buffer"))
20212 ((and (local-variable-p 'org-finish-function (current-buffer))
20213 (fboundp org-finish-function))
20214 (funcall org-finish-function))
20215 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20217 (let* ((context (org-element-context)) (type (org-element-type context)))
20218 ;; Test if point is within a blank line.
20219 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20220 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20221 (user-error "C-c C-c can do nothing useful at this location"))
20222 (case type
20223 ;; When at a link, act according to the parent instead.
20224 (link (setq context (org-element-property :parent context))
20225 (setq type (org-element-type context)))
20226 ;; Unsupported object types: check parent element instead.
20227 ((bold code entity export-snippet inline-babel-call inline-src-block
20228 italic latex-fragment line-break macro strike-through subscript
20229 superscript underline verbatim)
20230 (while (and (setq context (org-element-property :parent context))
20231 (not (memq (setq type (org-element-type context))
20232 '(paragraph verse-block)))))))
20233 ;; For convenience: at the first line of a paragraph on the
20234 ;; same line as an item, apply function on that item instead.
20235 (when (eq type 'paragraph)
20236 (let ((parent (org-element-property :parent context)))
20237 (when (and (eq (org-element-type parent) 'item)
20238 (= (point-at-bol) (org-element-property :begin parent)))
20239 (setq context parent type 'item))))
20240 ;; Act according to type of element or object at point.
20241 (case type
20242 (clock (org-clock-update-time-maybe))
20243 (dynamic-block
20244 (save-excursion
20245 (goto-char (org-element-property :post-affiliated context))
20246 (org-update-dblock)))
20247 (footnote-definition
20248 (goto-char (org-element-property :post-affiliated context))
20249 (call-interactively 'org-footnote-action))
20250 (footnote-reference (call-interactively 'org-footnote-action))
20251 ((headline inlinetask)
20252 (save-excursion (goto-char (org-element-property :begin context))
20253 (call-interactively 'org-set-tags)))
20254 (item
20255 ;; At an item: a double C-u set checkbox to "[-]"
20256 ;; unconditionally, whereas a single one will toggle its
20257 ;; presence. Without an universal argument, if the item
20258 ;; has a checkbox, toggle it. Otherwise repair the list.
20259 (let* ((box (org-element-property :checkbox context))
20260 (struct (org-element-property :structure context))
20261 (old-struct (copy-tree struct))
20262 (parents (org-list-parents-alist struct))
20263 (prevs (org-list-prevs-alist struct))
20264 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20265 (org-list-set-checkbox
20266 (org-element-property :begin context) struct
20267 (cond ((equal arg '(16)) "[-]")
20268 ((and (not box) (equal arg '(4))) "[ ]")
20269 ((or (not box) (equal arg '(4))) nil)
20270 ((eq box 'on) "[ ]")
20271 (t "[X]")))
20272 ;; Mimic `org-list-write-struct' but with grabbing
20273 ;; a return value from `org-list-struct-fix-box'.
20274 (org-list-struct-fix-ind struct parents 2)
20275 (org-list-struct-fix-item-end struct)
20276 (org-list-struct-fix-bul struct prevs)
20277 (org-list-struct-fix-ind struct parents)
20278 (let ((block-item
20279 (org-list-struct-fix-box struct parents prevs orderedp)))
20280 (if (and box (equal struct old-struct))
20281 (if (equal arg '(16))
20282 (message "Checkboxes already reset")
20283 (user-error "Cannot toggle this checkbox: %s"
20284 (if (eq box 'on)
20285 "all subitems checked"
20286 "unchecked subitems")))
20287 (org-list-struct-apply-struct struct old-struct)
20288 (org-update-checkbox-count-maybe))
20289 (when block-item
20290 (message "Checkboxes were removed due to empty box at line %d"
20291 (org-current-line block-item))))))
20292 (keyword
20293 (let ((org-inhibit-startup-visibility-stuff t)
20294 (org-startup-align-all-tables nil))
20295 (when (boundp 'org-table-coordinate-overlays)
20296 (mapc 'delete-overlay org-table-coordinate-overlays)
20297 (setq org-table-coordinate-overlays nil))
20298 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20299 (message "Local setup has been refreshed"))
20300 (plain-list
20301 ;; At a plain list, with a double C-u argument, set
20302 ;; checkboxes of each item to "[-]", whereas a single one
20303 ;; will toggle their presence according to the state of the
20304 ;; first item in the list. Without an argument, repair the
20305 ;; list.
20306 (let* ((begin (org-element-property :contents-begin context))
20307 (beginm (move-marker (make-marker) begin))
20308 (struct (org-element-property :structure context))
20309 (old-struct (copy-tree struct))
20310 (first-box (save-excursion
20311 (goto-char begin)
20312 (looking-at org-list-full-item-re)
20313 (match-string-no-properties 3)))
20314 (new-box (cond ((equal arg '(16)) "[-]")
20315 ((equal arg '(4)) (unless first-box "[ ]"))
20316 ((equal first-box "[X]") "[ ]")
20317 (t "[X]"))))
20318 (cond
20319 (arg
20320 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20321 (org-list-get-all-items
20322 begin struct (org-list-prevs-alist struct))))
20323 ((and first-box (eq (point) begin))
20324 ;; For convenience, when point is at bol on the first
20325 ;; item of the list and no argument is provided, simply
20326 ;; toggle checkbox of that item, if any.
20327 (org-list-set-checkbox begin struct new-box)))
20328 (org-list-write-struct
20329 struct (org-list-parents-alist struct) old-struct)
20330 (org-update-checkbox-count-maybe)
20331 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20332 ((property-drawer node-property)
20333 (call-interactively 'org-property-action))
20334 ((radio-target target)
20335 (call-interactively 'org-update-radio-target-regexp))
20336 (statistics-cookie
20337 (call-interactively 'org-update-statistics-cookies))
20338 ((table table-cell table-row)
20339 ;; At a table, recalculate every field and align it. Also
20340 ;; send the table if necessary. If the table has
20341 ;; a `table.el' type, just give up. At a table row or
20342 ;; cell, maybe recalculate line but always align table.
20343 (if (eq (org-element-property :type context) 'table.el)
20344 (message "Use C-c ' to edit table.el tables")
20345 (let ((org-enable-table-editor t))
20346 (if (or (eq type 'table)
20347 ;; Check if point is at a TBLFM line.
20348 (and (eq type 'table-row)
20349 (= (point) (org-element-property :end context))))
20350 (save-excursion
20351 (if (org-at-TBLFM-p)
20352 (progn (require 'org-table)
20353 (org-table-calc-current-TBLFM))
20354 (goto-char (org-element-property :contents-begin context))
20355 (org-call-with-arg 'org-table-recalculate (or arg t))
20356 (orgtbl-send-table 'maybe)))
20357 (org-table-maybe-eval-formula)
20358 (cond (arg (call-interactively 'org-table-recalculate))
20359 ((org-table-maybe-recalculate-line))
20360 (t (org-table-align)))))))
20361 (timestamp (org-timestamp-change 0 'day))
20362 (otherwise
20363 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20364 (user-error
20365 "C-c C-c can do nothing useful at this location")))))))))
20367 (defun org-mode-restart ()
20368 "Restart Org-mode, to scan again for special lines.
20369 Also updates the keyword regular expressions and file variables."
20370 (interactive)
20371 (funcall major-mode)
20372 (hack-local-variables)
20373 (message "%s restarted" major-mode))
20375 (defun org-kill-note-or-show-branches ()
20376 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20377 (interactive)
20378 (if (not org-finish-function)
20379 (progn
20380 (hide-subtree)
20381 (call-interactively 'show-branches))
20382 (let ((org-note-abort t))
20383 (funcall org-finish-function))))
20385 (defun org-open-line (n)
20386 "Insert a new row in tables, call `open-line' elsewhere.
20387 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20388 (interactive "*p")
20389 (cond
20390 ((not org-special-ctrl-o)
20391 (open-line n))
20392 ((org-at-table-p)
20393 (org-table-insert-row))
20395 (open-line n))))
20397 (defun org-return (&optional indent)
20398 "Goto next table row or insert a newline.
20399 Calls `org-table-next-row' or `newline', depending on context.
20400 See the individual commands for more information."
20401 (interactive)
20402 (let (org-ts-what)
20403 (cond
20404 ((or (bobp) (org-in-src-block-p))
20405 (if indent (newline-and-indent) (newline)))
20406 ((org-at-table-p)
20407 (org-table-justify-field-maybe)
20408 (call-interactively 'org-table-next-row))
20409 ;; when `newline-and-indent' is called within a list, make sure
20410 ;; text moved stays inside the item.
20411 ((and (org-in-item-p) indent)
20412 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20413 (progn
20414 (save-match-data (newline))
20415 (org-indent-line-to (length (match-string 0))))
20416 (let ((ind (org-get-indentation)))
20417 (newline)
20418 (if (org-looking-back org-list-end-re)
20419 (org-indent-line)
20420 (org-indent-line-to ind)))))
20421 ((and org-return-follows-link
20422 (org-at-timestamp-p t)
20423 (not (eq org-ts-what 'after)))
20424 (org-follow-timestamp-link))
20425 ((and org-return-follows-link
20426 (let ((tprop (get-text-property (point) 'face)))
20427 (or (eq tprop 'org-link)
20428 (and (listp tprop) (memq 'org-link tprop)))))
20429 (call-interactively 'org-open-at-point))
20430 ((and (org-at-heading-p)
20431 (looking-at
20432 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20433 (org-show-entry)
20434 (end-of-line 1)
20435 (newline))
20436 (t (if indent (newline-and-indent) (newline))))))
20438 (defun org-return-indent ()
20439 "Goto next table row or insert a newline and indent.
20440 Calls `org-table-next-row' or `newline-and-indent', depending on
20441 context. See the individual commands for more information."
20442 (interactive)
20443 (org-return t))
20445 (defun org-ctrl-c-star ()
20446 "Compute table, or change heading status of lines.
20447 Calls `org-table-recalculate' or `org-toggle-heading',
20448 depending on context."
20449 (interactive)
20450 (cond
20451 ((org-at-table-p)
20452 (call-interactively 'org-table-recalculate))
20454 ;; Convert all lines in region to list items
20455 (call-interactively 'org-toggle-heading))))
20457 (defun org-ctrl-c-minus ()
20458 "Insert separator line in table or modify bullet status of line.
20459 Also turns a plain line or a region of lines into list items.
20460 Calls `org-table-insert-hline', `org-toggle-item', or
20461 `org-cycle-list-bullet', depending on context."
20462 (interactive)
20463 (cond
20464 ((org-at-table-p)
20465 (call-interactively 'org-table-insert-hline))
20466 ((org-region-active-p)
20467 (call-interactively 'org-toggle-item))
20468 ((org-in-item-p)
20469 (call-interactively 'org-cycle-list-bullet))
20471 (call-interactively 'org-toggle-item))))
20473 (defun org-toggle-item (arg)
20474 "Convert headings or normal lines to items, items to normal lines.
20475 If there is no active region, only the current line is considered.
20477 If the first non blank line in the region is a headline, convert
20478 all headlines to items, shifting text accordingly.
20480 If it is an item, convert all items to normal lines.
20482 If it is normal text, change region into a list of items.
20483 With a prefix argument ARG, change the region in a single item."
20484 (interactive "P")
20485 (let ((shift-text
20486 (function
20487 ;; Shift text in current section to IND, from point to END.
20488 ;; The function leaves point to END line.
20489 (lambda (ind end)
20490 (let ((min-i 1000) (end (copy-marker end)))
20491 ;; First determine the minimum indentation (MIN-I) of
20492 ;; the text.
20493 (save-excursion
20494 (catch 'exit
20495 (while (< (point) end)
20496 (let ((i (org-get-indentation)))
20497 (cond
20498 ;; Skip blank lines and inline tasks.
20499 ((looking-at "^[ \t]*$"))
20500 ((looking-at org-outline-regexp-bol))
20501 ;; We can't find less than 0 indentation.
20502 ((zerop i) (throw 'exit (setq min-i 0)))
20503 ((< i min-i) (setq min-i i))))
20504 (forward-line))))
20505 ;; Then indent each line so that a line indented to
20506 ;; MIN-I becomes indented to IND. Ignore blank lines
20507 ;; and inline tasks in the process.
20508 (let ((delta (- ind min-i)))
20509 (while (< (point) end)
20510 (unless (or (looking-at "^[ \t]*$")
20511 (looking-at org-outline-regexp-bol))
20512 (org-indent-line-to (+ (org-get-indentation) delta)))
20513 (forward-line)))))))
20514 (skip-blanks
20515 (function
20516 ;; Return beginning of first non-blank line, starting from
20517 ;; line at POS.
20518 (lambda (pos)
20519 (save-excursion
20520 (goto-char pos)
20521 (skip-chars-forward " \r\t\n")
20522 (point-at-bol)))))
20523 beg end)
20524 ;; Determine boundaries of changes.
20525 (if (org-region-active-p)
20526 (setq beg (funcall skip-blanks (region-beginning))
20527 end (copy-marker (region-end)))
20528 (setq beg (funcall skip-blanks (point-at-bol))
20529 end (copy-marker (point-at-eol))))
20530 ;; Depending on the starting line, choose an action on the text
20531 ;; between BEG and END.
20532 (org-with-limited-levels
20533 (save-excursion
20534 (goto-char beg)
20535 (cond
20536 ;; Case 1. Start at an item: de-itemize. Note that it only
20537 ;; happens when a region is active: `org-ctrl-c-minus'
20538 ;; would call `org-cycle-list-bullet' otherwise.
20539 ((org-at-item-p)
20540 (while (< (point) end)
20541 (when (org-at-item-p)
20542 (skip-chars-forward " \t")
20543 (delete-region (point) (match-end 0)))
20544 (forward-line)))
20545 ;; Case 2. Start at an heading: convert to items.
20546 ((org-at-heading-p)
20547 (let* ((bul (org-list-bullet-string "-"))
20548 (bul-len (length bul))
20549 ;; Indentation of the first heading. It should be
20550 ;; relative to the indentation of its parent, if any.
20551 (start-ind (save-excursion
20552 (cond
20553 ((not org-adapt-indentation) 0)
20554 ((not (outline-previous-heading)) 0)
20555 (t (length (match-string 0))))))
20556 ;; Level of first heading. Further headings will be
20557 ;; compared to it to determine hierarchy in the list.
20558 (ref-level (org-reduced-level (org-outline-level))))
20559 (while (< (point) end)
20560 (let* ((level (org-reduced-level (org-outline-level)))
20561 (delta (max 0 (- level ref-level))))
20562 ;; If current headline is less indented than the first
20563 ;; one, set it as reference, in order to preserve
20564 ;; subtrees.
20565 (when (< level ref-level) (setq ref-level level))
20566 (replace-match bul t t)
20567 (org-indent-line-to (+ start-ind (* delta bul-len)))
20568 ;; Ensure all text down to END (or SECTION-END) belongs
20569 ;; to the newly created item.
20570 (let ((section-end (save-excursion
20571 (or (outline-next-heading) (point)))))
20572 (forward-line)
20573 (funcall shift-text
20574 (+ start-ind (* (1+ delta) bul-len))
20575 (min end section-end)))))))
20576 ;; Case 3. Normal line with ARG: make the first line of region
20577 ;; an item, and shift indentation of others lines to
20578 ;; set them as item's body.
20579 (arg (let* ((bul (org-list-bullet-string "-"))
20580 (bul-len (length bul))
20581 (ref-ind (org-get-indentation)))
20582 (skip-chars-forward " \t")
20583 (insert bul)
20584 (forward-line)
20585 (while (< (point) end)
20586 ;; Ensure that lines less indented than first one
20587 ;; still get included in item body.
20588 (funcall shift-text
20589 (+ ref-ind bul-len)
20590 (min end (save-excursion (or (outline-next-heading)
20591 (point)))))
20592 (forward-line))))
20593 ;; Case 4. Normal line without ARG: turn each non-item line
20594 ;; into an item.
20596 (while (< (point) end)
20597 (unless (or (org-at-heading-p) (org-at-item-p))
20598 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20599 (replace-match
20600 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20601 (forward-line))))))))
20603 (defun org-toggle-heading (&optional nstars)
20604 "Convert headings to normal text, or items or text to headings.
20605 If there is no active region, only convert the current line.
20607 With a \\[universal-argument] prefix, convert the whole list at
20608 point into heading.
20610 In a region:
20612 - If the first non blank line is a headline, remove the stars
20613 from all headlines in the region.
20615 - If it is a normal line, turn each and every normal line (i.e.,
20616 not an heading or an item) in the region into headings. If you
20617 want to convert only the first line of this region, use one
20618 universal prefix argument.
20620 - If it is a plain list item, turn all plain list items into headings.
20622 When converting a line into a heading, the number of stars is chosen
20623 such that the lines become children of the current entry. However,
20624 when a numeric prefix argument is given, its value determines the
20625 number of stars to add."
20626 (interactive "P")
20627 (let ((skip-blanks
20628 (function
20629 ;; Return beginning of first non-blank line, starting from
20630 ;; line at POS.
20631 (lambda (pos)
20632 (save-excursion
20633 (goto-char pos)
20634 (while (org-at-comment-p) (forward-line))
20635 (skip-chars-forward " \r\t\n")
20636 (point-at-bol)))))
20637 beg end toggled)
20638 ;; Determine boundaries of changes. If a universal prefix has
20639 ;; been given, put the list in a region. If region ends at a bol,
20640 ;; do not consider the last line to be in the region.
20642 (when (and current-prefix-arg (org-at-item-p))
20643 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20644 (org-mark-element))
20646 (if (org-region-active-p)
20647 (setq beg (funcall skip-blanks (region-beginning))
20648 end (copy-marker (save-excursion
20649 (goto-char (region-end))
20650 (if (bolp) (point) (point-at-eol)))))
20651 (setq beg (funcall skip-blanks (point-at-bol))
20652 end (copy-marker (point-at-eol))))
20653 ;; Ensure inline tasks don't count as headings.
20654 (org-with-limited-levels
20655 (save-excursion
20656 (goto-char beg)
20657 (cond
20658 ;; Case 1. Started at an heading: de-star headings.
20659 ((org-at-heading-p)
20660 (while (< (point) end)
20661 (when (org-at-heading-p t)
20662 (looking-at org-outline-regexp) (replace-match "")
20663 (setq toggled t))
20664 (forward-line)))
20665 ;; Case 2. Started at an item: change items into headlines.
20666 ;; One star will be added by `org-list-to-subtree'.
20667 ((org-at-item-p)
20668 (let* ((stars (make-string
20669 ;; subtract the star that will be added again by
20670 ;; `org-list-to-subtree'
20671 (if (numberp nstars) (1- nstars)
20672 (or (org-current-level) 0))
20673 ?*))
20674 (add-stars
20675 (cond (nstars "") ; stars from prefix only
20676 ((equal stars "") "") ; before first heading
20677 (org-odd-levels-only "*") ; inside heading, odd
20678 (t "")))) ; inside heading, oddeven
20679 (while (< (point) end)
20680 (when (org-at-item-p)
20681 ;; Pay attention to cases when region ends before list.
20682 (let* ((struct (org-list-struct))
20683 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20684 (save-restriction
20685 (narrow-to-region (point) list-end)
20686 (insert
20687 (org-list-to-subtree
20688 (org-list-parse-list t)
20689 '(:istart (concat stars add-stars (funcall get-stars depth))
20690 :icount (concat stars add-stars (funcall get-stars depth)))))))
20691 (setq toggled t))
20692 (forward-line))))
20693 ;; Case 3. Started at normal text: make every line an heading,
20694 ;; skipping headlines and items.
20695 (t (let* ((stars
20696 (make-string
20697 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20698 (add-stars
20699 (cond (nstars "") ; stars from prefix only
20700 ((equal stars "") "*") ; before first heading
20701 (org-odd-levels-only "**") ; inside heading, odd
20702 (t "*"))) ; inside heading, oddeven
20703 (rpl (concat stars add-stars " "))
20704 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20705 (while (< (point) (if (equal nstars '(4)) lend end))
20706 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20707 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20708 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20709 (forward-line)))))))
20710 (unless toggled (message "Cannot toggle heading from here"))))
20712 (defun org-meta-return (&optional arg)
20713 "Insert a new heading or wrap a region in a table.
20714 Calls `org-insert-heading' or `org-table-wrap-region', depending
20715 on context. See the individual commands for more information."
20716 (interactive "P")
20717 (org-check-before-invisible-edit 'insert)
20718 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20719 (let* ((element (org-element-at-point))
20720 (type (org-element-type element)))
20721 (when (eq type 'table-row)
20722 (setq element (org-element-property :parent element))
20723 (setq type 'table))
20724 (if (and (eq type 'table)
20725 (eq (org-element-property :type element) 'org)
20726 (>= (point) (org-element-property :contents-begin element))
20727 (< (point) (org-element-property :contents-end element)))
20728 (call-interactively 'org-table-wrap-region)
20729 (call-interactively 'org-insert-heading)))))
20731 ;;; Menu entries
20733 (defsubst org-in-subtree-not-table-p ()
20734 "Are we in a subtree and not in a table?"
20735 (and (not (org-before-first-heading-p))
20736 (not (org-at-table-p))))
20738 ;; Define the Org-mode menus
20739 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20740 '("Tbl"
20741 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20742 ["Next Field" org-cycle (org-at-table-p)]
20743 ["Previous Field" org-shifttab (org-at-table-p)]
20744 ["Next Row" org-return (org-at-table-p)]
20745 "--"
20746 ["Blank Field" org-table-blank-field (org-at-table-p)]
20747 ["Edit Field" org-table-edit-field (org-at-table-p)]
20748 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20749 "--"
20750 ("Column"
20751 ["Move Column Left" org-metaleft (org-at-table-p)]
20752 ["Move Column Right" org-metaright (org-at-table-p)]
20753 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20754 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20755 ("Row"
20756 ["Move Row Up" org-metaup (org-at-table-p)]
20757 ["Move Row Down" org-metadown (org-at-table-p)]
20758 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20759 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20760 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20761 "--"
20762 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20763 ("Rectangle"
20764 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20765 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20766 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20767 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20768 "--"
20769 ("Calculate"
20770 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20771 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20772 ["Edit Formulas" org-edit-special (org-at-table-p)]
20773 "--"
20774 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20775 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20776 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20777 "--"
20778 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20779 "--"
20780 ["Sum Column/Rectangle" org-table-sum
20781 (or (org-at-table-p) (org-region-active-p))]
20782 ["Which Column?" org-table-current-column (org-at-table-p)])
20783 ["Debug Formulas"
20784 org-table-toggle-formula-debugger
20785 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20786 ["Show Col/Row Numbers"
20787 org-table-toggle-coordinate-overlays
20788 :style toggle
20789 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20790 "--"
20791 ["Create" org-table-create (and (not (org-at-table-p))
20792 org-enable-table-editor)]
20793 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20794 ["Import from File" org-table-import (not (org-at-table-p))]
20795 ["Export to File" org-table-export (org-at-table-p)]
20796 "--"
20797 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20799 (easy-menu-define org-org-menu org-mode-map "Org menu"
20800 '("Org"
20801 ("Show/Hide"
20802 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20803 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20804 ["Sparse Tree..." org-sparse-tree t]
20805 ["Reveal Context" org-reveal t]
20806 ["Show All" show-all t]
20807 "--"
20808 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20809 "--"
20810 ["New Heading" org-insert-heading t]
20811 ("Navigate Headings"
20812 ["Up" outline-up-heading t]
20813 ["Next" outline-next-visible-heading t]
20814 ["Previous" outline-previous-visible-heading t]
20815 ["Next Same Level" outline-forward-same-level t]
20816 ["Previous Same Level" outline-backward-same-level t]
20817 "--"
20818 ["Jump" org-goto t])
20819 ("Edit Structure"
20820 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20821 "--"
20822 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20823 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20824 "--"
20825 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20826 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20827 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20828 "--"
20829 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20830 "--"
20831 ["Copy visible text" org-copy-visible t]
20832 "--"
20833 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20834 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20835 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20836 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20837 "--"
20838 ["Sort Region/Children" org-sort t]
20839 "--"
20840 ["Convert to odd levels" org-convert-to-odd-levels t]
20841 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20842 ("Editing"
20843 ["Emphasis..." org-emphasize t]
20844 ["Edit Source Example" org-edit-special t]
20845 "--"
20846 ["Footnote new/jump" org-footnote-action t]
20847 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20848 ("Archive"
20849 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20850 "--"
20851 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20852 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20853 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20855 "--"
20856 ("Hyperlinks"
20857 ["Store Link (Global)" org-store-link t]
20858 ["Find existing link to here" org-occur-link-in-agenda-files t]
20859 ["Insert Link" org-insert-link t]
20860 ["Follow Link" org-open-at-point t]
20861 "--"
20862 ["Next link" org-next-link t]
20863 ["Previous link" org-previous-link t]
20864 "--"
20865 ["Descriptive Links"
20866 org-toggle-link-display
20867 :style radio
20868 :selected org-descriptive-links
20870 ["Literal Links"
20871 org-toggle-link-display
20872 :style radio
20873 :selected (not org-descriptive-links)])
20874 "--"
20875 ("TODO Lists"
20876 ["TODO/DONE/-" org-todo t]
20877 ("Select keyword"
20878 ["Next keyword" org-shiftright (org-at-heading-p)]
20879 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20880 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20881 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20882 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20883 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20884 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20885 "--"
20886 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20887 :selected org-enforce-todo-dependencies :style toggle :active t]
20888 "Settings for tree at point"
20889 ["Do Children sequentially" org-toggle-ordered-property :style radio
20890 :selected (org-entry-get nil "ORDERED")
20891 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20892 ["Do Children parallel" org-toggle-ordered-property :style radio
20893 :selected (not (org-entry-get nil "ORDERED"))
20894 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20895 "--"
20896 ["Set Priority" org-priority t]
20897 ["Priority Up" org-shiftup t]
20898 ["Priority Down" org-shiftdown t]
20899 "--"
20900 ["Get news from all feeds" org-feed-update-all t]
20901 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20902 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20903 ("TAGS and Properties"
20904 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20905 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20906 "--"
20907 ["Set property" org-set-property (not (org-before-first-heading-p))]
20908 ["Column view of properties" org-columns t]
20909 ["Insert Column View DBlock" org-insert-columns-dblock t])
20910 ("Dates and Scheduling"
20911 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20912 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20913 ("Change Date"
20914 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20915 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20916 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20917 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20918 ["Compute Time Range" org-evaluate-time-range t]
20919 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20920 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20921 "--"
20922 ["Custom time format" org-toggle-time-stamp-overlays
20923 :style radio :selected org-display-custom-times]
20924 "--"
20925 ["Goto Calendar" org-goto-calendar t]
20926 ["Date from Calendar" org-date-from-calendar t]
20927 "--"
20928 ["Start/Restart Timer" org-timer-start t]
20929 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20930 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20931 ["Insert Timer String" org-timer t]
20932 ["Insert Timer Item" org-timer-item t])
20933 ("Logging work"
20934 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20935 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20936 ["Clock out" org-clock-out t]
20937 ["Clock cancel" org-clock-cancel t]
20938 "--"
20939 ["Mark as default task" org-clock-mark-default-task t]
20940 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20941 ["Goto running clock" org-clock-goto t]
20942 "--"
20943 ["Display times" org-clock-display t]
20944 ["Create clock table" org-clock-report t]
20945 "--"
20946 ["Record DONE time"
20947 (progn (setq org-log-done (not org-log-done))
20948 (message "Switching to %s will %s record a timestamp"
20949 (car org-done-keywords)
20950 (if org-log-done "automatically" "not")))
20951 :style toggle :selected org-log-done])
20952 "--"
20953 ["Agenda Command..." org-agenda t]
20954 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20955 ("File List for Agenda")
20956 ("Special views current file"
20957 ["TODO Tree" org-show-todo-tree t]
20958 ["Check Deadlines" org-check-deadlines t]
20959 ["Timeline" org-timeline t]
20960 ["Tags/Property tree" org-match-sparse-tree t])
20961 "--"
20962 ["Export/Publish..." org-export-dispatch t]
20963 ("LaTeX"
20964 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20965 :selected org-cdlatex-mode]
20966 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20967 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20968 ["Modify math symbol" org-cdlatex-math-modify
20969 (org-inside-LaTeX-fragment-p)]
20970 ["Insert citation" org-reftex-citation t]
20971 "--"
20972 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20973 "--"
20974 ("MobileOrg"
20975 ["Push Files and Views" org-mobile-push t]
20976 ["Get Captured and Flagged" org-mobile-pull t]
20977 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20978 "--"
20979 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20980 "--"
20981 ("Documentation"
20982 ["Show Version" org-version t]
20983 ["Info Documentation" org-info t])
20984 ("Customize"
20985 ["Browse Org Group" org-customize t]
20986 "--"
20987 ["Expand This Menu" org-create-customize-menu
20988 (fboundp 'customize-menu-create)])
20989 ["Send bug report" org-submit-bug-report t]
20990 "--"
20991 ("Refresh/Reload"
20992 ["Refresh setup current buffer" org-mode-restart t]
20993 ["Reload Org (after update)" org-reload t]
20994 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20997 (defun org-info (&optional node)
20998 "Read documentation for Org-mode in the info system.
20999 With optional NODE, go directly to that node."
21000 (interactive)
21001 (info (format "(org)%s" (or node ""))))
21003 ;;;###autoload
21004 (defun org-submit-bug-report ()
21005 "Submit a bug report on Org-mode via mail.
21007 Don't hesitate to report any problems or inaccurate documentation.
21009 If you don't have setup sending mail from (X)Emacs, please copy the
21010 output buffer into your mail program, as it gives us important
21011 information about your Org-mode version and configuration."
21012 (interactive)
21013 (require 'reporter)
21014 (org-load-modules-maybe)
21015 (org-require-autoloaded-modules)
21016 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21017 (reporter-submit-bug-report
21018 "emacs-orgmode@gnu.org"
21019 (org-version nil 'full)
21020 (let (list)
21021 (save-window-excursion
21022 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21023 (delete-other-windows)
21024 (erase-buffer)
21025 (insert "You are about to submit a bug report to the Org-mode mailing list.
21027 We would like to add your full Org-mode and Outline configuration to the
21028 bug report. This greatly simplifies the work of the maintainer and
21029 other experts on the mailing list.
21031 HOWEVER, some variables you have customized may contain private
21032 information. The names of customers, colleagues, or friends, might
21033 appear in the form of file names, tags, todo states, or search strings.
21034 If you answer yes to the prompt, you might want to check and remove
21035 such private information before sending the email.")
21036 (add-text-properties (point-min) (point-max) '(face org-warning))
21037 (when (yes-or-no-p "Include your Org-mode configuration ")
21038 (mapatoms
21039 (lambda (v)
21040 (and (boundp v)
21041 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21042 (or (and (symbol-value v)
21043 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21044 (and
21045 (get v 'custom-type) (get v 'standard-value)
21046 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21047 (push v list)))))
21048 (kill-buffer (get-buffer "*Warn about privacy*"))
21049 list))
21050 nil nil
21051 "Remember to cover the basics, that is, what you expected to happen and
21052 what in fact did happen. You don't know how to make a good report? See
21054 http://orgmode.org/manual/Feedback.html#Feedback
21056 Your bug report will be posted to the Org-mode mailing list.
21057 ------------------------------------------------------------------------")
21058 (save-excursion
21059 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21060 (replace-match "\\1Bug: \\3 [\\2]")))))
21063 (defun org-install-agenda-files-menu ()
21064 (let ((bl (buffer-list)))
21065 (save-excursion
21066 (while bl
21067 (set-buffer (pop bl))
21068 (if (derived-mode-p 'org-mode) (setq bl nil)))
21069 (when (derived-mode-p 'org-mode)
21070 (easy-menu-change
21071 '("Org") "File List for Agenda"
21072 (append
21073 (list
21074 ["Edit File List" (org-edit-agenda-file-list) t]
21075 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21076 ["Remove Current File from List" org-remove-file t]
21077 ["Cycle through agenda files" org-cycle-agenda-files t]
21078 ["Occur in all agenda files" org-occur-in-agenda-files t]
21079 "--")
21080 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21082 ;;;; Documentation
21084 (defun org-require-autoloaded-modules ()
21085 (interactive)
21086 (mapc 'require
21087 '(org-agenda org-archive org-attach org-clock org-colview org-id
21088 org-table org-timer)))
21090 ;;;###autoload
21091 (defun org-reload (&optional uncompiled)
21092 "Reload all org lisp files.
21093 With prefix arg UNCOMPILED, load the uncompiled versions."
21094 (interactive "P")
21095 (require 'loadhist)
21096 (let* ((org-dir (org-find-library-dir "org"))
21097 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21098 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21099 (remove-re (mapconcat 'identity
21100 (mapcar (lambda (f) (concat "^" f "$"))
21101 (list (if (featurep 'xemacs)
21102 "org-colview"
21103 "org-colview-xemacs")
21104 "org" "org-loaddefs" "org-version"))
21105 "\\|"))
21106 (feats (delete-dups
21107 (mapcar 'file-name-sans-extension
21108 (mapcar 'file-name-nondirectory
21109 (delq nil
21110 (mapcar 'feature-file
21111 features))))))
21112 (lfeat (append
21113 (sort
21114 (setq feats
21115 (delq nil (mapcar
21116 (lambda (f)
21117 (if (and (string-match feature-re f)
21118 (not (string-match remove-re f)))
21119 f nil))
21120 feats)))
21121 'string-lessp)
21122 (list "org-version" "org")))
21123 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21124 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21125 load-uncore load-misses)
21126 (setq load-misses
21127 (delq 't
21128 (mapcar (lambda (f)
21129 (or (org-load-noerror-mustsuffix (concat org-dir f))
21130 (and (string= org-dir contrib-dir)
21131 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21132 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21133 (add-to-list 'load-uncore f 'append)
21136 lfeat)))
21137 (if load-uncore
21138 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21139 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21140 (if load-misses
21141 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21142 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21143 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21145 ;;;###autoload
21146 (defun org-customize ()
21147 "Call the customize function with org as argument."
21148 (interactive)
21149 (org-load-modules-maybe)
21150 (org-require-autoloaded-modules)
21151 (customize-browse 'org))
21153 (defun org-create-customize-menu ()
21154 "Create a full customization menu for Org-mode, insert it into the menu."
21155 (interactive)
21156 (org-load-modules-maybe)
21157 (org-require-autoloaded-modules)
21158 (if (fboundp 'customize-menu-create)
21159 (progn
21160 (easy-menu-change
21161 '("Org") "Customize"
21162 `(["Browse Org group" org-customize t]
21163 "--"
21164 ,(customize-menu-create 'org)
21165 ["Set" Custom-set t]
21166 ["Save" Custom-save t]
21167 ["Reset to Current" Custom-reset-current t]
21168 ["Reset to Saved" Custom-reset-saved t]
21169 ["Reset to Standard Settings" Custom-reset-standard t]))
21170 (message "\"Org\"-menu now contains full customization menu"))
21171 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21173 ;;;; Miscellaneous stuff
21175 ;;; Generally useful functions
21177 (defun org-get-at-bol (property)
21178 "Get text property PROPERTY at beginning of line."
21179 (get-text-property (point-at-bol) property))
21181 (defun org-find-text-property-in-string (prop s)
21182 "Return the first non-nil value of property PROP in string S."
21183 (or (get-text-property 0 prop s)
21184 (get-text-property (or (next-single-property-change 0 prop s) 0)
21185 prop s)))
21187 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21188 "Display the given MESSAGE as a warning."
21189 (if (fboundp 'display-warning)
21190 (display-warning 'org message
21191 (if (featurep 'xemacs) 'warning :warning))
21192 (let ((buf (get-buffer-create "*Org warnings*")))
21193 (with-current-buffer buf
21194 (goto-char (point-max))
21195 (insert "Warning (Org): " message)
21196 (unless (bolp)
21197 (newline)))
21198 (display-buffer buf)
21199 (sit-for 0))))
21201 (defun org-eval (form)
21202 "Eval FORM and return result."
21203 (condition-case error
21204 (eval form)
21205 (error (format "%%![Error: %s]" error))))
21207 (defun org-in-clocktable-p ()
21208 "Check if the cursor is in a clocktable."
21209 (let ((pos (point)) start)
21210 (save-excursion
21211 (end-of-line 1)
21212 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21213 (setq start (match-beginning 0))
21214 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21215 (>= (match-end 0) pos)
21216 start))))
21218 (defun org-in-commented-line ()
21219 "Is point in a line starting with `#'?"
21220 (equal (char-after (point-at-bol)) ?#))
21222 (defun org-in-indented-comment-line ()
21223 "Is point in a line starting with `#' after some white space?"
21224 (save-excursion
21225 (save-match-data
21226 (goto-char (point-at-bol))
21227 (looking-at "[ \t]*#"))))
21229 (defun org-in-verbatim-emphasis ()
21230 (save-match-data
21231 (and (org-in-regexp org-emph-re 2)
21232 (>= (point) (match-beginning 3))
21233 (<= (point) (match-end 4))
21234 (member (match-string 3) '("=" "~")))))
21236 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21237 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21238 (if (and marker (marker-buffer marker)
21239 (buffer-live-p (marker-buffer marker)))
21240 (progn
21241 (org-pop-to-buffer-same-window (marker-buffer marker))
21242 (if (or (> marker (point-max)) (< marker (point-min)))
21243 (widen))
21244 (goto-char marker)
21245 (org-show-context 'org-goto))
21246 (if bookmark
21247 (bookmark-jump bookmark)
21248 (error "Cannot find location"))))
21250 (defun org-quote-csv-field (s)
21251 "Quote field for inclusion in CSV material."
21252 (if (string-match "[\",]" s)
21253 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21256 (defun org-force-self-insert (N)
21257 "Needed to enforce self-insert under remapping."
21258 (interactive "p")
21259 (self-insert-command N))
21261 (defun org-string-width (s)
21262 "Compute width of string, ignoring invisible characters.
21263 This ignores character with invisibility property `org-link', and also
21264 characters with property `org-cwidth', because these will become invisible
21265 upon the next fontification round."
21266 (let (b l)
21267 (when (or (eq t buffer-invisibility-spec)
21268 (assq 'org-link buffer-invisibility-spec))
21269 (while (setq b (text-property-any 0 (length s)
21270 'invisible 'org-link s))
21271 (setq s (concat (substring s 0 b)
21272 (substring s (or (next-single-property-change
21273 b 'invisible s) (length s)))))))
21274 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21275 (setq s (concat (substring s 0 b)
21276 (substring s (or (next-single-property-change
21277 b 'org-cwidth s) (length s))))))
21278 (setq l (string-width s) b -1)
21279 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21280 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21283 (defun org-shorten-string (s maxlength)
21284 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21285 If the string is shorter or has length MAXLENGTH, just return the
21286 original string. If it is longer, the functions finds a space in the
21287 string, breaks this string off at that locations and adds three dots
21288 as ellipsis. Including the ellipsis, the string will not be longer
21289 than MAXLENGTH. If finding a good breaking point in the string does
21290 not work, the string is just chopped off in the middle of a word
21291 if necessary."
21292 (if (<= (length s) maxlength)
21294 (let* ((n (max (- maxlength 4) 1))
21295 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21296 (if (string-match re s)
21297 (concat (match-string 1 s) "...")
21298 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21300 (defun org-get-indentation (&optional line)
21301 "Get the indentation of the current line, interpreting tabs.
21302 When LINE is given, assume it represents a line and compute its indentation."
21303 (if line
21304 (if (string-match "^ *" (org-remove-tabs line))
21305 (match-end 0))
21306 (save-excursion
21307 (beginning-of-line 1)
21308 (skip-chars-forward " \t")
21309 (current-column))))
21311 (defun org-get-string-indentation (s)
21312 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21313 (let ((n -1) (i 0) (w tab-width) c)
21314 (catch 'exit
21315 (while (< (setq n (1+ n)) (length s))
21316 (setq c (aref s n))
21317 (cond ((= c ?\ ) (setq i (1+ i)))
21318 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21319 (t (throw 'exit t)))))
21322 (defun org-remove-tabs (s &optional width)
21323 "Replace tabulators in S with spaces.
21324 Assumes that s is a single line, starting in column 0."
21325 (setq width (or width tab-width))
21326 (while (string-match "\t" s)
21327 (setq s (replace-match
21328 (make-string
21329 (- (* width (/ (+ (match-beginning 0) width) width))
21330 (match-beginning 0)) ?\ )
21331 t t s)))
21334 (defun org-fix-indentation (line ind)
21335 "Fix indentation in LINE.
21336 IND is a cons cell with target and minimum indentation.
21337 If the current indentation in LINE is smaller than the minimum,
21338 leave it alone. If it is larger than ind, set it to the target."
21339 (let* ((l (org-remove-tabs line))
21340 (i (org-get-indentation l))
21341 (i1 (car ind)) (i2 (cdr ind)))
21342 (if (>= i i2) (setq l (substring line i2)))
21343 (if (> i1 0)
21344 (concat (make-string i1 ?\ ) l)
21345 l)))
21347 (defun org-remove-indentation (code &optional n)
21348 "Remove the maximum common indentation from the lines in CODE.
21349 N may optionally be the number of spaces to remove."
21350 (with-temp-buffer
21351 (insert code)
21352 (org-do-remove-indentation n)
21353 (buffer-string)))
21355 (defun org-do-remove-indentation (&optional n)
21356 "Remove the maximum common indentation from the buffer."
21357 (untabify (point-min) (point-max))
21358 (let ((min 10000) re)
21359 (if n
21360 (setq min n)
21361 (goto-char (point-min))
21362 (while (re-search-forward "^ *[^ \n]" nil t)
21363 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21364 (unless (or (= min 0) (= min 10000))
21365 (setq re (format "^ \\{%d\\}" min))
21366 (goto-char (point-min))
21367 (while (re-search-forward re nil t)
21368 (replace-match "")
21369 (end-of-line 1))
21370 min)))
21372 (defun org-fill-template (template alist)
21373 "Find each %key of ALIST in TEMPLATE and replace it."
21374 (let ((case-fold-search nil)
21375 entry key value)
21376 (setq alist (sort (copy-sequence alist)
21377 (lambda (a b) (< (length (car a)) (length (car b))))))
21378 (while (setq entry (pop alist))
21379 (setq template
21380 (replace-regexp-in-string
21381 (concat "%" (regexp-quote (car entry)))
21382 (or (cdr entry) "") template t t)))
21383 template))
21385 (defun org-base-buffer (buffer)
21386 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21387 (if (not buffer)
21388 buffer
21389 (or (buffer-base-buffer buffer)
21390 buffer)))
21392 (defun org-trim (s)
21393 "Remove whitespace at beginning and end of string."
21394 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21395 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21398 (defun org-wrap (string &optional width lines)
21399 "Wrap string to either a number of lines, or a width in characters.
21400 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21401 that costs. If there is a word longer than WIDTH, the text is actually
21402 wrapped to the length of that word.
21403 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21404 many lines, whatever width that takes.
21405 The return value is a list of lines, without newlines at the end."
21406 (let* ((words (org-split-string string "[ \t\n]+"))
21407 (maxword (apply 'max (mapcar 'org-string-width words)))
21408 w ll)
21409 (cond (width
21410 (org-do-wrap words (max maxword width)))
21411 (lines
21412 (setq w maxword)
21413 (setq ll (org-do-wrap words maxword))
21414 (if (<= (length ll) lines)
21416 (setq ll words)
21417 (while (> (length ll) lines)
21418 (setq w (1+ w))
21419 (setq ll (org-do-wrap words w)))
21420 ll))
21421 (t (error "Cannot wrap this")))))
21423 (defun org-do-wrap (words width)
21424 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21425 (let (lines line)
21426 (while words
21427 (setq line (pop words))
21428 (while (and words (< (+ (length line) (length (car words))) width))
21429 (setq line (concat line " " (pop words))))
21430 (setq lines (push line lines)))
21431 (nreverse lines)))
21433 (defun org-split-string (string &optional separators)
21434 "Splits STRING into substrings at SEPARATORS.
21435 No empty strings are returned if there are matches at the beginning
21436 and end of string."
21437 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21438 (start 0)
21439 notfirst
21440 (list nil))
21441 (while (and (string-match rexp string
21442 (if (and notfirst
21443 (= start (match-beginning 0))
21444 (< start (length string)))
21445 (1+ start) start))
21446 (< (match-beginning 0) (length string)))
21447 (setq notfirst t)
21448 (or (eq (match-beginning 0) 0)
21449 (and (eq (match-beginning 0) (match-end 0))
21450 (eq (match-beginning 0) start))
21451 (setq list
21452 (cons (substring string start (match-beginning 0))
21453 list)))
21454 (setq start (match-end 0)))
21455 (or (eq start (length string))
21456 (setq list
21457 (cons (substring string start)
21458 list)))
21459 (nreverse list)))
21461 (defun org-quote-vert (s)
21462 "Replace \"|\" with \"\\vert\"."
21463 (while (string-match "|" s)
21464 (setq s (replace-match "\\vert" t t s)))
21467 (defun org-uuidgen-p (s)
21468 "Is S an ID created by UUIDGEN?"
21469 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21471 (defun org-in-src-block-p (&optional inside)
21472 "Whether point is in a code source block.
21473 When INSIDE is non-nil, don't consider we are within a src block
21474 when point is at #+BEGIN_SRC or #+END_SRC."
21475 (let ((case-fold-search t) ov)
21476 (or (and (setq ov (overlays-at (point)))
21477 (memq 'org-block-background
21478 (overlay-properties (car ov))))
21479 (and (not inside)
21480 (save-match-data
21481 (save-excursion
21482 (beginning-of-line)
21483 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21485 (defun org-context ()
21486 "Return a list of contexts of the current cursor position.
21487 If several contexts apply, all are returned.
21488 Each context entry is a list with a symbol naming the context, and
21489 two positions indicating start and end of the context. Possible
21490 contexts are:
21492 :headline anywhere in a headline
21493 :headline-stars on the leading stars in a headline
21494 :todo-keyword on a TODO keyword (including DONE) in a headline
21495 :tags on the TAGS in a headline
21496 :priority on the priority cookie in a headline
21497 :item on the first line of a plain list item
21498 :item-bullet on the bullet/number of a plain list item
21499 :checkbox on the checkbox in a plain list item
21500 :table in an org-mode table
21501 :table-special on a special filed in a table
21502 :table-table in a table.el table
21503 :clocktable in a clocktable
21504 :src-block in a source block
21505 :link on a hyperlink
21506 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21507 :target on a <<target>>
21508 :radio-target on a <<<radio-target>>>
21509 :latex-fragment on a LaTeX fragment
21510 :latex-preview on a LaTeX fragment with overlaid preview image
21512 This function expects the position to be visible because it uses font-lock
21513 faces as a help to recognize the following contexts: :table-special, :link,
21514 and :keyword."
21515 (let* ((f (get-text-property (point) 'face))
21516 (faces (if (listp f) f (list f)))
21517 (case-fold-search t)
21518 (p (point)) clist o)
21519 ;; First the large context
21520 (cond
21521 ((org-at-heading-p t)
21522 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21523 (when (progn
21524 (beginning-of-line 1)
21525 (looking-at org-todo-line-tags-regexp))
21526 (push (org-point-in-group p 1 :headline-stars) clist)
21527 (push (org-point-in-group p 2 :todo-keyword) clist)
21528 (push (org-point-in-group p 4 :tags) clist))
21529 (goto-char p)
21530 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21531 (if (looking-at "\\[#[A-Z0-9]\\]")
21532 (push (org-point-in-group p 0 :priority) clist)))
21534 ((org-at-item-p)
21535 (push (org-point-in-group p 2 :item-bullet) clist)
21536 (push (list :item (point-at-bol)
21537 (save-excursion (org-end-of-item) (point)))
21538 clist)
21539 (and (org-at-item-checkbox-p)
21540 (push (org-point-in-group p 0 :checkbox) clist)))
21542 ((org-at-table-p)
21543 (push (list :table (org-table-begin) (org-table-end)) clist)
21544 (if (memq 'org-formula faces)
21545 (push (list :table-special
21546 (previous-single-property-change p 'face)
21547 (next-single-property-change p 'face)) clist)))
21548 ((org-at-table-p 'any)
21549 (push (list :table-table) clist)))
21550 (goto-char p)
21552 (let ((case-fold-search t))
21553 ;; New the "medium" contexts: clocktables, source blocks
21554 (cond ((org-in-clocktable-p)
21555 (push (list :clocktable
21556 (and (or (looking-at "#\\+BEGIN: clocktable")
21557 (search-backward "#+BEGIN: clocktable" nil t))
21558 (match-beginning 0))
21559 (and (re-search-forward "#\\+END:?" nil t)
21560 (match-end 0))) clist))
21561 ((org-in-src-block-p)
21562 (push (list :src-block
21563 (and (or (looking-at "#\\+BEGIN_SRC")
21564 (search-backward "#+BEGIN_SRC" nil t))
21565 (match-beginning 0))
21566 (and (search-forward "#+END_SRC" nil t)
21567 (match-beginning 0))) clist))))
21568 (goto-char p)
21570 ;; Now the small context
21571 (cond
21572 ((org-at-timestamp-p)
21573 (push (org-point-in-group p 0 :timestamp) clist))
21574 ((memq 'org-link faces)
21575 (push (list :link
21576 (previous-single-property-change p 'face)
21577 (next-single-property-change p 'face)) clist))
21578 ((memq 'org-special-keyword faces)
21579 (push (list :keyword
21580 (previous-single-property-change p 'face)
21581 (next-single-property-change p 'face)) clist))
21582 ((org-at-target-p)
21583 (push (org-point-in-group p 0 :target) clist)
21584 (goto-char (1- (match-beginning 0)))
21585 (if (looking-at org-radio-target-regexp)
21586 (push (org-point-in-group p 0 :radio-target) clist))
21587 (goto-char p))
21588 ((setq o (car (delq nil
21589 (mapcar
21590 (lambda (x)
21591 (if (memq x org-latex-fragment-image-overlays) x))
21592 (overlays-at (point))))))
21593 (push (list :latex-fragment
21594 (overlay-start o) (overlay-end o)) clist)
21595 (push (list :latex-preview
21596 (overlay-start o) (overlay-end o)) clist))
21597 ((org-inside-LaTeX-fragment-p)
21598 ;; FIXME: positions wrong.
21599 (push (list :latex-fragment (point) (point)) clist)))
21601 (setq clist (nreverse (delq nil clist)))
21602 clist))
21604 ;; FIXME: Compare with at-regexp-p Do we need both?
21605 (defun org-in-regexp (re &optional nlines visually)
21606 "Check if point is inside a match of regexp.
21607 Normally only the current line is checked, but you can include NLINES extra
21608 lines both before and after point into the search.
21609 If VISUALLY is set, require that the cursor is not after the match but
21610 really on, so that the block visually is on the match."
21611 (catch 'exit
21612 (let ((pos (point))
21613 (eol (point-at-eol (+ 1 (or nlines 0))))
21614 (inc (if visually 1 0)))
21615 (save-excursion
21616 (beginning-of-line (- 1 (or nlines 0)))
21617 (while (re-search-forward re eol t)
21618 (if (and (<= (match-beginning 0) pos)
21619 (>= (+ inc (match-end 0)) pos))
21620 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21622 (defun org-at-regexp-p (regexp)
21623 "Is point inside a match of REGEXP in the current line?"
21624 (catch 'exit
21625 (save-excursion
21626 (let ((pos (point)) (end (point-at-eol)))
21627 (beginning-of-line 1)
21628 (while (re-search-forward regexp end t)
21629 (if (and (<= (match-beginning 0) pos)
21630 (>= (match-end 0) pos))
21631 (throw 'exit t)))
21632 nil))))
21634 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21635 "Non-nil when point is between matches of START-RE and END-RE.
21637 Also return a non-nil value when point is on one of the matches.
21639 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21640 buffer positions. Default values are the positions of headlines
21641 surrounding the point.
21643 The functions returns a cons cell whose car (resp. cdr) is the
21644 position before START-RE (resp. after END-RE)."
21645 (save-match-data
21646 (let ((pos (point))
21647 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21648 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21649 beg end)
21650 (save-excursion
21651 ;; Point is on a block when on START-RE or if START-RE can be
21652 ;; found before it...
21653 (and (or (org-at-regexp-p start-re)
21654 (re-search-backward start-re limit-up t))
21655 (setq beg (match-beginning 0))
21656 ;; ... and END-RE after it...
21657 (goto-char (match-end 0))
21658 (re-search-forward end-re limit-down t)
21659 (> (setq end (match-end 0)) pos)
21660 ;; ... without another START-RE in-between.
21661 (goto-char (match-beginning 0))
21662 (not (re-search-backward start-re (1+ beg) t))
21663 ;; Return value.
21664 (cons beg end))))))
21666 (defun org-in-block-p (names)
21667 "Non-nil when point belongs to a block whose name belongs to NAMES.
21669 NAMES is a list of strings containing names of blocks.
21671 Return first block name matched, or nil. Beware that in case of
21672 nested blocks, the returned name may not belong to the closest
21673 block from point."
21674 (save-match-data
21675 (catch 'exit
21676 (let ((case-fold-search t)
21677 (lim-up (save-excursion (outline-previous-heading)))
21678 (lim-down (save-excursion (outline-next-heading))))
21679 (mapc (lambda (name)
21680 (let ((n (regexp-quote name)))
21681 (when (org-between-regexps-p
21682 (concat "^[ \t]*#\\+begin_" n)
21683 (concat "^[ \t]*#\\+end_" n)
21684 lim-up lim-down)
21685 (throw 'exit n))))
21686 names))
21687 nil)))
21689 (defun org-in-drawer-p ()
21690 "Is point within a drawer?"
21691 (save-match-data
21692 (let ((case-fold-search t)
21693 (lim-up (save-excursion (outline-previous-heading)))
21694 (lim-down (save-excursion (outline-next-heading))))
21695 (org-between-regexps-p
21696 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21697 "^[ \t]*:end:.*$"
21698 lim-up lim-down))))
21700 (defun org-occur-in-agenda-files (regexp &optional nlines)
21701 "Call `multi-occur' with buffers for all agenda files."
21702 (interactive "sOrg-files matching: \np")
21703 (let* ((files (org-agenda-files))
21704 (tnames (mapcar 'file-truename files))
21705 (extra org-agenda-text-search-extra-files)
21707 (when (eq (car extra) 'agenda-archives)
21708 (setq extra (cdr extra))
21709 (setq files (org-add-archive-files files)))
21710 (while (setq f (pop extra))
21711 (unless (member (file-truename f) tnames)
21712 (add-to-list 'files f 'append)
21713 (add-to-list 'tnames (file-truename f) 'append)))
21714 (multi-occur
21715 (mapcar (lambda (x)
21716 (with-current-buffer
21717 (or (get-file-buffer x) (find-file-noselect x))
21718 (widen)
21719 (current-buffer)))
21720 files)
21721 regexp)))
21723 (if (boundp 'occur-mode-find-occurrence-hook)
21724 ;; Emacs 23
21725 (add-hook 'occur-mode-find-occurrence-hook
21726 (lambda ()
21727 (when (derived-mode-p 'org-mode)
21728 (org-reveal))))
21729 ;; Emacs 22
21730 (defadvice occur-mode-goto-occurrence
21731 (after org-occur-reveal activate)
21732 (and (derived-mode-p 'org-mode) (org-reveal)))
21733 (defadvice occur-mode-goto-occurrence-other-window
21734 (after org-occur-reveal activate)
21735 (and (derived-mode-p 'org-mode) (org-reveal)))
21736 (defadvice occur-mode-display-occurrence
21737 (after org-occur-reveal activate)
21738 (when (derived-mode-p 'org-mode)
21739 (let ((pos (occur-mode-find-occurrence)))
21740 (with-current-buffer (marker-buffer pos)
21741 (save-excursion
21742 (goto-char pos)
21743 (org-reveal)))))))
21745 (defun org-occur-link-in-agenda-files ()
21746 "Create a link and search for it in the agendas.
21747 The link is not stored in `org-stored-links', it is just created
21748 for the search purpose."
21749 (interactive)
21750 (let ((link (condition-case nil
21751 (org-store-link nil)
21752 (error "Unable to create a link to here"))))
21753 (org-occur-in-agenda-files (regexp-quote link))))
21755 (defun org-reverse-string (string)
21756 "Return the reverse of STRING."
21757 (apply 'string (reverse (string-to-list string))))
21759 (defsubst org-uniquify (list)
21760 "Non-destructively remove duplicate elements from LIST."
21761 (let ((res (copy-sequence list))) (delete-dups res)))
21763 (defun org-uniquify-alist (alist)
21764 "Merge elements of ALIST with the same key.
21766 For example, in this alist:
21768 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21769 => '((a 1 3) (b 2))
21771 merge (a 1) and (a 3) into (a 1 3).
21773 The function returns the new ALIST."
21774 (let (rtn)
21775 (mapc
21776 (lambda (e)
21777 (let (n)
21778 (if (not (assoc (car e) rtn))
21779 (push e rtn)
21780 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21781 (setq rtn (assq-delete-all (car e) rtn))
21782 (push n rtn))))
21783 alist)
21784 rtn))
21786 (defun org-delete-all (elts list)
21787 "Remove all elements in ELTS from LIST."
21788 (while elts
21789 (setq list (delete (pop elts) list)))
21790 list)
21792 (defun org-count (cl-item cl-seq)
21793 "Count the number of occurrences of ITEM in SEQ.
21794 Taken from `count' in cl-seq.el with all keyword arguments removed."
21795 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21796 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21797 (while (< cl-start cl-end)
21798 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21799 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21800 (setq cl-start (1+ cl-start)))
21801 cl-count))
21803 (defun org-remove-if (predicate seq)
21804 "Remove everything from SEQ that fulfills PREDICATE."
21805 (let (res e)
21806 (while seq
21807 (setq e (pop seq))
21808 (if (not (funcall predicate e)) (push e res)))
21809 (nreverse res)))
21811 (defun org-remove-if-not (predicate seq)
21812 "Remove everything from SEQ that does not fulfill PREDICATE."
21813 (let (res e)
21814 (while seq
21815 (setq e (pop seq))
21816 (if (funcall predicate e) (push e res)))
21817 (nreverse res)))
21819 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21820 "Reduce two-argument FUNCTION across SEQ.
21821 Taken from `reduce' in cl-seq.el with all keyword arguments but
21822 \":initial-value\" removed."
21823 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21824 (cadr (memq :initial-value cl-keys)))
21825 (cl-seq (pop cl-seq))
21826 (t (funcall cl-func)))))
21827 (while cl-seq
21828 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21829 cl-accum))
21831 (defun org-every (pred seq)
21832 "Return true if PREDICATE is true of every element of SEQ.
21833 Adapted from `every' in cl.el."
21834 (catch 'org-every
21835 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21838 (defun org-some (pred seq)
21839 "Return true if PREDICATE is true of any element of SEQ.
21840 Adapted from `some' in cl.el."
21841 (catch 'org-some
21842 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21843 nil))
21845 (defun org-back-over-empty-lines ()
21846 "Move backwards over whitespace, to the beginning of the first empty line.
21847 Returns the number of empty lines passed."
21848 (let ((pos (point)))
21849 (if (cdr (assoc 'heading org-blank-before-new-entry))
21850 (skip-chars-backward " \t\n\r")
21851 (unless (eobp)
21852 (forward-line -1)))
21853 (beginning-of-line 2)
21854 (goto-char (min (point) pos))
21855 (count-lines (point) pos)))
21857 (defun org-skip-whitespace ()
21858 (skip-chars-forward " \t\n\r"))
21860 (defun org-point-in-group (point group &optional context)
21861 "Check if POINT is in match-group GROUP.
21862 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21863 match. If the match group does not exist or point is not inside it,
21864 return nil."
21865 (and (match-beginning group)
21866 (>= point (match-beginning group))
21867 (<= point (match-end group))
21868 (if context
21869 (list context (match-beginning group) (match-end group))
21870 t)))
21872 (defun org-switch-to-buffer-other-window (&rest args)
21873 "Switch to buffer in a second window on the current frame.
21874 In particular, do not allow pop-up frames.
21875 Returns the newly created buffer."
21876 (org-no-popups
21877 (apply 'switch-to-buffer-other-window args)))
21879 (defun org-combine-plists (&rest plists)
21880 "Create a single property list from all plists in PLISTS.
21881 The process starts by copying the first list, and then setting properties
21882 from the other lists. Settings in the last list are the most significant
21883 ones and overrule settings in the other lists."
21884 (let ((rtn (copy-sequence (pop plists)))
21885 p v ls)
21886 (while plists
21887 (setq ls (pop plists))
21888 (while ls
21889 (setq p (pop ls) v (pop ls))
21890 (setq rtn (plist-put rtn p v))))
21891 rtn))
21893 (defun org-replace-escapes (string table)
21894 "Replace %-escapes in STRING with values in TABLE.
21895 TABLE is an association list with keys like \"%a\" and string values.
21896 The sequences in STRING may contain normal field width and padding information,
21897 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21898 so values can contain further %-escapes if they are define later in TABLE."
21899 (let ((tbl (copy-alist table))
21900 (case-fold-search nil)
21901 (pchg 0)
21902 e re rpl)
21903 (while (setq e (pop tbl))
21904 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21905 (when (and (cdr e) (string-match re (cdr e)))
21906 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21907 (safe "SREF"))
21908 (add-text-properties 0 3 (list 'sref sref) safe)
21909 (setcdr e (replace-match safe t t (cdr e)))))
21910 (while (string-match re string)
21911 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21912 (cdr e)))
21913 (setq string (replace-match rpl t t string))))
21914 (while (setq pchg (next-property-change pchg string))
21915 (let ((sref (get-text-property pchg 'sref string)))
21916 (when (and sref (string-match "SREF" string pchg))
21917 (setq string (replace-match sref t t string)))))
21918 string))
21920 (defun org-sublist (list start end)
21921 "Return a section of LIST, from START to END.
21922 Counting starts at 1."
21923 (let (rtn (c start))
21924 (setq list (nthcdr (1- start) list))
21925 (while (and list (<= c end))
21926 (push (pop list) rtn)
21927 (setq c (1+ c)))
21928 (nreverse rtn)))
21930 (defun org-find-base-buffer-visiting (file)
21931 "Like `find-buffer-visiting' but always return the base buffer and
21932 not an indirect buffer."
21933 (let ((buf (or (get-file-buffer file)
21934 (find-buffer-visiting file))))
21935 (if buf
21936 (or (buffer-base-buffer buf) buf)
21937 nil)))
21939 (defun org-image-file-name-regexp (&optional extensions)
21940 "Return regexp matching the file names of images.
21941 If EXTENSIONS is given, only match these."
21942 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21943 (image-file-name-regexp)
21944 (let ((image-file-name-extensions
21945 (or extensions
21946 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21947 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21948 (concat "\\."
21949 (regexp-opt (nconc (mapcar 'upcase
21950 image-file-name-extensions)
21951 image-file-name-extensions)
21953 "\\'"))))
21955 (defun org-file-image-p (file &optional extensions)
21956 "Return non-nil if FILE is an image."
21957 (save-match-data
21958 (string-match (org-image-file-name-regexp extensions) file)))
21960 (defun org-get-cursor-date (&optional with-time)
21961 "Return the date at cursor in as a time.
21962 This works in the calendar and in the agenda, anywhere else it just
21963 returns the current time.
21964 If WITH-TIME is non-nil, returns the time of the event at point (in
21965 the agenda) or the current time of the day."
21966 (let (date day defd tp tm hod mod)
21967 (when with-time
21968 (setq tp (get-text-property (point) 'time))
21969 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21970 (setq hod (string-to-number (match-string 1 tp))
21971 mod (string-to-number (match-string 2 tp))))
21972 (or tp (setq hod (nth 2 (decode-time (current-time)))
21973 mod (nth 1 (decode-time (current-time))))))
21974 (cond
21975 ((eq major-mode 'calendar-mode)
21976 (setq date (calendar-cursor-to-date)
21977 defd (encode-time 0 (or mod 0) (or hod 0)
21978 (nth 1 date) (nth 0 date) (nth 2 date))))
21979 ((eq major-mode 'org-agenda-mode)
21980 (setq day (get-text-property (point) 'day))
21981 (if day
21982 (setq date (calendar-gregorian-from-absolute day)
21983 defd (encode-time 0 (or mod 0) (or hod 0)
21984 (nth 1 date) (nth 0 date) (nth 2 date))))))
21985 (or defd (current-time))))
21987 (defun org-mark-subtree (&optional up)
21988 "Mark the current subtree.
21989 This puts point at the start of the current subtree, and mark at
21990 the end. If a numeric prefix UP is given, move up into the
21991 hierarchy of headlines by UP levels before marking the subtree."
21992 (interactive "P")
21993 (org-with-limited-levels
21994 (cond ((org-at-heading-p) (beginning-of-line))
21995 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21996 (t (outline-previous-visible-heading 1))))
21997 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21998 (if (org-called-interactively-p 'any)
21999 (call-interactively 'org-mark-element)
22000 (org-mark-element)))
22003 ;;; Indentation
22005 (defun org-indent-line ()
22006 "Indent line depending on context."
22007 (interactive)
22008 (let* ((pos (point))
22009 (itemp (org-at-item-p))
22010 (case-fold-search t)
22011 (org-drawer-regexp (or org-drawer-regexp "\000"))
22012 (inline-task-p (and (featurep 'org-inlinetask)
22013 (org-inlinetask-in-task-p)))
22014 (inline-re (and inline-task-p
22015 (org-inlinetask-outline-regexp)))
22016 column)
22017 (if (and orgstruct-is-++ (eq pos (point)))
22018 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22019 (indent-according-to-mode))
22020 (beginning-of-line 1)
22021 (cond
22022 ;; Headings
22023 ((looking-at org-outline-regexp) (setq column 0))
22024 ;; Footnote definition
22025 ((looking-at org-footnote-definition-re) (setq column 0))
22026 ;; Literal examples
22027 ((looking-at "[ \t]*:\\( \\|$\\)")
22028 (setq column (org-get-indentation))) ; do nothing
22029 ;; Lists
22030 ((ignore-errors (goto-char (org-in-item-p)))
22031 (setq column (if itemp
22032 (org-get-indentation)
22033 (org-list-item-body-column (point))))
22034 (goto-char pos))
22035 ;; Drawers
22036 ((and (looking-at "[ \t]*:END:")
22037 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22038 (save-excursion
22039 (goto-char (1- (match-beginning 1)))
22040 (setq column (current-column))))
22041 ;; Special blocks
22042 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22043 (save-excursion
22044 (re-search-backward
22045 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22046 (setq column (org-get-indentation (match-string 0))))
22047 ((and (not (looking-at "[ \t]*#\\+begin_"))
22048 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22049 (save-excursion
22050 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22051 (setq column
22052 (cond ((equal (downcase (match-string 1)) "src")
22053 ;; src blocks: let `org-edit-src-exit' handle them
22054 (org-get-indentation))
22055 ((equal (downcase (match-string 1)) "example")
22056 (max (org-get-indentation)
22057 (org-get-indentation (match-string 0))))
22059 (org-get-indentation (match-string 0))))))
22060 ;; This line has nothing special, look at the previous relevant
22061 ;; line to compute indentation
22063 (beginning-of-line 0)
22064 (while (and (not (bobp))
22065 (not (looking-at org-table-line-regexp))
22066 (not (looking-at org-drawer-regexp))
22067 ;; When point started in an inline task, do not move
22068 ;; above task starting line.
22069 (not (and inline-task-p (looking-at inline-re)))
22070 ;; Skip drawers, blocks, empty lines, verbatim,
22071 ;; comments, tables, footnotes definitions, lists,
22072 ;; inline tasks.
22073 (or (and (looking-at "[ \t]*:END:")
22074 (re-search-backward org-drawer-regexp nil t))
22075 (and (looking-at "[ \t]*#\\+end_")
22076 (re-search-backward "[ \t]*#\\+begin_"nil t))
22077 (looking-at "[ \t]*[\n:#|]")
22078 (looking-at org-footnote-definition-re)
22079 (and (not inline-task-p)
22080 (featurep 'org-inlinetask)
22081 (org-inlinetask-in-task-p)
22082 (or (org-inlinetask-goto-beginning) t))))
22083 (beginning-of-line 0))
22084 (cond
22085 ;; There was a list item above.
22086 ((ignore-errors (goto-char (org-in-item-p)))
22087 (goto-char (org-list-get-top-point (org-list-struct)))
22088 (setq column (org-get-indentation)))
22089 ;; There was an heading above.
22090 ((looking-at "\\*+[ \t]+")
22091 (if (not org-adapt-indentation)
22092 (setq column 0)
22093 (goto-char (match-end 0))
22094 (setq column (current-column))))
22095 ;; A drawer had started and is unfinished
22096 ((looking-at org-drawer-regexp)
22097 (goto-char (1- (match-beginning 1)))
22098 (setq column (current-column)))
22099 ;; Else, nothing noticeable found: get indentation and go on.
22100 (t (setq column (org-get-indentation))))))
22101 ;; Now apply indentation and move cursor accordingly
22102 (goto-char pos)
22103 (if (<= (current-column) (current-indentation))
22104 (org-indent-line-to column)
22105 (save-excursion (org-indent-line-to column)))
22106 ;; Special polishing for properties, see `org-property-format'
22107 (setq column (current-column))
22108 (beginning-of-line 1)
22109 (if (looking-at org-property-re)
22110 (replace-match (concat (match-string 4)
22111 (format org-property-format
22112 (match-string 1) (match-string 3)))
22113 t t))
22114 (org-move-to-column column))))
22116 (defun org-indent-drawer ()
22117 "Indent the drawer at point."
22118 (interactive)
22119 (let ((p (point))
22120 (e (and (save-excursion (re-search-forward ":END:" nil t))
22121 (match-end 0)))
22122 (folded
22123 (save-excursion
22124 (end-of-line)
22125 (when (overlays-at (point))
22126 (member 'invisible (overlay-properties
22127 (car (overlays-at (point)))))))))
22128 (when folded (org-cycle))
22129 (indent-for-tab-command)
22130 (while (and (move-beginning-of-line 2) (< (point) e))
22131 (indent-for-tab-command))
22132 (goto-char p)
22133 (when folded (org-cycle)))
22134 (message "Drawer at point indented"))
22136 (defun org-indent-block ()
22137 "Indent the block at point."
22138 (interactive)
22139 (let ((p (point))
22140 (case-fold-search t)
22141 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22142 (match-end 0)))
22143 (folded
22144 (save-excursion
22145 (end-of-line)
22146 (when (overlays-at (point))
22147 (member 'invisible (overlay-properties
22148 (car (overlays-at (point)))))))))
22149 (when folded (org-cycle))
22150 (indent-for-tab-command)
22151 (while (and (move-beginning-of-line 2) (< (point) e))
22152 (indent-for-tab-command))
22153 (goto-char p)
22154 (when folded (org-cycle)))
22155 (message "Block at point indented"))
22157 (defun org-indent-region (start end)
22158 "Indent region."
22159 (interactive "r")
22160 (save-excursion
22161 (let ((line-end (org-current-line end)))
22162 (goto-char start)
22163 (while (< (org-current-line) line-end)
22164 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22165 (t (call-interactively 'org-indent-line)))
22166 (move-beginning-of-line 2)))))
22169 ;;; Filling
22171 ;; We use our own fill-paragraph and auto-fill functions.
22173 ;; `org-fill-paragraph' relies on adaptive filling and context
22174 ;; checking. Appropriate `fill-prefix' is computed with
22175 ;; `org-adaptive-fill-function'.
22177 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22178 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22179 ;; `org-adaptive-fill-function' value. Internally,
22180 ;; `org-comment-line-break-function' breaks the line.
22182 ;; `org-setup-filling' installs filling and auto-filling related
22183 ;; variables during `org-mode' initialization.
22185 (defvar org-element-paragraph-separate) ; org-element.el
22186 (defun org-setup-filling ()
22187 (require 'org-element)
22188 ;; Prevent auto-fill from inserting unwanted new items.
22189 (when (boundp 'fill-nobreak-predicate)
22190 (org-set-local
22191 'fill-nobreak-predicate
22192 (org-uniquify
22193 (append fill-nobreak-predicate
22194 '(org-fill-line-break-nobreak-p
22195 org-fill-paragraph-with-timestamp-nobreak-p)))))
22196 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22197 (org-set-local 'paragraph-start paragraph-ending)
22198 (org-set-local 'paragraph-separate paragraph-ending))
22199 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22200 (org-set-local 'auto-fill-inhibit-regexp nil)
22201 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22202 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22203 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22205 (defun org-fill-line-break-nobreak-p ()
22206 "Non-nil when a new line at point would create an Org line break."
22207 (save-excursion
22208 (skip-chars-backward "[ \t]")
22209 (skip-chars-backward "\\\\")
22210 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22212 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22213 "Non-nil when a new line at point would split a timestamp."
22214 (and (org-at-timestamp-p t)
22215 (not (looking-at org-ts-regexp-both))))
22217 (declare-function message-in-body-p "message" ())
22218 (defvar orgtbl-line-start-regexp) ; From org-table.el
22219 (defun org-adaptive-fill-function ()
22220 "Compute a fill prefix for the current line.
22221 Return fill prefix, as a string, or nil if current line isn't
22222 meant to be filled. For convenience, if `adaptive-fill-regexp'
22223 matches in paragraphs or comments, use it."
22224 (catch 'exit
22225 (when (derived-mode-p 'message-mode)
22226 (save-excursion
22227 (beginning-of-line)
22228 (cond ((or (not (message-in-body-p))
22229 (looking-at orgtbl-line-start-regexp))
22230 (throw 'exit nil))
22231 ((looking-at message-cite-prefix-regexp)
22232 (throw 'exit (match-string-no-properties 0)))
22233 ((looking-at org-outline-regexp)
22234 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22235 (org-with-wide-buffer
22236 (let* ((p (line-beginning-position))
22237 (element (save-excursion
22238 (beginning-of-line)
22239 (or (ignore-errors (org-element-at-point))
22240 (user-error "An element cannot be parsed line %d"
22241 (line-number-at-pos (point))))))
22242 (type (org-element-type element))
22243 (post-affiliated (org-element-property :post-affiliated element)))
22244 (unless (and post-affiliated (< p post-affiliated))
22245 (case type
22246 (comment
22247 (save-excursion
22248 (beginning-of-line)
22249 (looking-at "[ \t]*")
22250 (concat (match-string 0) "# ")))
22251 (footnote-definition "")
22252 ((item plain-list)
22253 (make-string (org-list-item-body-column
22254 (or post-affiliated
22255 (org-element-property :begin element)))
22256 ? ))
22257 (paragraph
22258 ;; Fill prefix is usually the same as the current line,
22259 ;; unless the paragraph is at the beginning of an item.
22260 (let ((parent (org-element-property :parent element)))
22261 (save-excursion
22262 (beginning-of-line)
22263 (cond ((eq (org-element-type parent) 'item)
22264 (make-string (org-list-item-body-column
22265 (org-element-property :begin parent))
22266 ? ))
22267 ((and adaptive-fill-regexp
22268 ;; Locally disable
22269 ;; `adaptive-fill-function' to let
22270 ;; `fill-context-prefix' handle
22271 ;; `adaptive-fill-regexp' variable.
22272 (let (adaptive-fill-function)
22273 (fill-context-prefix
22274 post-affiliated
22275 (org-element-property :end element)))))
22276 ((looking-at "[ \t]+") (match-string 0))
22277 (t "")))))
22278 (comment-block
22279 ;; Only fill contents if P is within block boundaries.
22280 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22281 (forward-line)
22282 (point)))
22283 (cend (save-excursion
22284 (goto-char (org-element-property :end element))
22285 (skip-chars-backward " \r\t\n")
22286 (line-beginning-position))))
22287 (when (and (>= p cbeg) (< p cend))
22288 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22289 (match-string 0)
22290 ""))))))))))
22292 (declare-function message-goto-body "message" ())
22293 (defvar message-cite-prefix-regexp) ; From message.el
22294 (defun org-fill-paragraph (&optional justify)
22295 "Fill element at point, when applicable.
22297 This function only applies to comment blocks, comments, example
22298 blocks and paragraphs. Also, as a special case, re-align table
22299 when point is at one.
22301 If JUSTIFY is non-nil (interactively, with prefix argument),
22302 justify as well. If `sentence-end-double-space' is non-nil, then
22303 period followed by one space does not end a sentence, so don't
22304 break a line there. The variable `fill-column' controls the
22305 width for filling.
22307 For convenience, when point is at a plain list, an item or
22308 a footnote definition, try to fill the first paragraph within."
22309 (interactive)
22310 (if (and (derived-mode-p 'message-mode)
22311 (or (not (message-in-body-p))
22312 (save-excursion (move-beginning-of-line 1)
22313 (looking-at message-cite-prefix-regexp))))
22314 ;; First ensure filling is correct in message-mode.
22315 (let ((fill-paragraph-function
22316 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22317 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22318 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22319 (paragraph-separate
22320 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22321 (fill-paragraph nil))
22322 (with-syntax-table org-mode-transpose-word-syntax-table
22323 ;; Move to end of line in order to get the first paragraph
22324 ;; within a plain list or a footnote definition.
22325 (let ((element (save-excursion
22326 (end-of-line)
22327 (or (ignore-errors (org-element-at-point))
22328 (user-error "An element cannot be parsed line %d"
22329 (line-number-at-pos (point)))))))
22330 ;; First check if point is in a blank line at the beginning of
22331 ;; the buffer. In that case, ignore filling.
22332 (case (org-element-type element)
22333 ;; Use major mode filling function is src blocks.
22334 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22335 ;; Align Org tables, leave table.el tables as-is.
22336 (table-row (org-table-align) t)
22337 (table
22338 (when (eq (org-element-property :type element) 'org)
22339 (save-excursion
22340 (goto-char (org-element-property :post-affiliated element))
22341 (org-table-align)))
22343 (paragraph
22344 ;; Paragraphs may contain `line-break' type objects.
22345 (let ((beg (max (point-min)
22346 (org-element-property :contents-begin element)))
22347 (end (min (point-max)
22348 (org-element-property :contents-end element))))
22349 ;; Do nothing if point is at an affiliated keyword.
22350 (if (< (line-end-position) beg) t
22351 (when (derived-mode-p 'message-mode)
22352 ;; In `message-mode', do not fill following citation
22353 ;; in current paragraph nor text before message body.
22354 (let ((body-start (save-excursion (message-goto-body))))
22355 (when body-start (setq beg (max body-start beg))))
22356 (when (save-excursion
22357 (re-search-forward
22358 (concat "^" message-cite-prefix-regexp) end t))
22359 (setq end (match-beginning 0))))
22360 ;; Fill paragraph, taking line breaks into account.
22361 ;; For that, slice the paragraph using line breaks as
22362 ;; separators, and fill the parts in reverse order to
22363 ;; avoid messing with markers.
22364 (save-excursion
22365 (goto-char end)
22366 (mapc
22367 (lambda (pos)
22368 (fill-region-as-paragraph pos (point) justify)
22369 (goto-char pos))
22370 ;; Find the list of ending positions for line breaks
22371 ;; in the current paragraph. Add paragraph
22372 ;; beginning to include first slice.
22373 (nreverse
22374 (cons beg
22375 (org-element-map
22376 (org-element--parse-objects
22377 beg end nil (org-element-restriction 'paragraph))
22378 'line-break
22379 (lambda (lb) (org-element-property :end lb)))))))
22380 t)))
22381 ;; Contents of `comment-block' type elements should be
22382 ;; filled as plain text, but only if point is within block
22383 ;; markers.
22384 (comment-block
22385 (let* ((case-fold-search t)
22386 (beg (save-excursion
22387 (goto-char (org-element-property :begin element))
22388 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22389 (forward-line)
22390 (point)))
22391 (end (save-excursion
22392 (goto-char (org-element-property :end element))
22393 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22394 (line-beginning-position))))
22395 (if (or (< (point) beg) (> (point) end)) t
22396 (fill-region-as-paragraph
22397 (save-excursion (end-of-line)
22398 (re-search-backward "^[ \t]*$" beg 'move)
22399 (line-beginning-position))
22400 (save-excursion (beginning-of-line)
22401 (re-search-forward "^[ \t]*$" end 'move)
22402 (line-beginning-position))
22403 justify))))
22404 ;; Fill comments.
22405 (comment
22406 (let ((begin (org-element-property :post-affiliated element))
22407 (end (org-element-property :end element)))
22408 (when (and (>= (point) begin) (<= (point) end))
22409 (let ((begin (save-excursion
22410 (end-of-line)
22411 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22412 (progn (forward-line) (point))
22413 begin)))
22414 (end (save-excursion
22415 (end-of-line)
22416 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22417 (1- (line-beginning-position))
22418 (skip-chars-backward " \r\t\n")
22419 (line-end-position)))))
22420 ;; Do not fill comments when at a blank line.
22421 (when (> end begin)
22422 (let ((fill-prefix
22423 (save-excursion
22424 (beginning-of-line)
22425 (looking-at "[ \t]*#")
22426 (let ((comment-prefix (match-string 0)))
22427 (goto-char (match-end 0))
22428 (if (looking-at adaptive-fill-regexp)
22429 (concat comment-prefix (match-string 0))
22430 (concat comment-prefix " "))))))
22431 (save-excursion
22432 (fill-region-as-paragraph begin end justify))))))
22434 ;; Ignore every other element.
22435 (otherwise t))))))
22437 (defun org-auto-fill-function ()
22438 "Auto-fill function."
22439 ;; Check if auto-filling is meaningful.
22440 (let ((fc (current-fill-column)))
22441 (when (and fc (> (current-column) fc))
22442 (let* ((fill-prefix (org-adaptive-fill-function))
22443 ;; Enforce empty fill prefix, if required. Otherwise, it
22444 ;; will be computed again.
22445 (adaptive-fill-mode (not (equal fill-prefix ""))))
22446 (when fill-prefix (do-auto-fill))))))
22448 (defun org-comment-line-break-function (&optional soft)
22449 "Break line at point and indent, continuing comment if within one.
22450 The inserted newline is marked hard if variable
22451 `use-hard-newlines' is true, unless optional argument SOFT is
22452 non-nil."
22453 (if soft (insert-and-inherit ?\n) (newline 1))
22454 (save-excursion (forward-char -1) (delete-horizontal-space))
22455 (delete-horizontal-space)
22456 (indent-to-left-margin)
22457 (insert-before-markers-and-inherit fill-prefix))
22460 ;;; Comments
22462 ;; Org comments syntax is quite complex. It requires the entire line
22463 ;; to be just a comment. Also, even with the right syntax at the
22464 ;; beginning of line, some some elements (i.e. verse-block or
22465 ;; example-block) don't accept comments. Usual Emacs comment commands
22466 ;; cannot cope with those requirements. Therefore, Org replaces them.
22468 ;; Org still relies on `comment-dwim', but cannot trust
22469 ;; `comment-only-p'. So, `comment-region-function' and
22470 ;; `uncomment-region-function' both point
22471 ;; to`org-comment-or-uncomment-region'. Eventually,
22472 ;; `org-insert-comment' takes care of insertion of comments at the
22473 ;; beginning of line.
22475 ;; `org-setup-comments-handling' install comments related variables
22476 ;; during `org-mode' initialization.
22478 (defun org-setup-comments-handling ()
22479 (interactive)
22480 (org-set-local 'comment-use-syntax nil)
22481 (org-set-local 'comment-start "# ")
22482 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22483 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22484 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22485 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22487 (defun org-insert-comment ()
22488 "Insert an empty comment above current line.
22489 If the line is empty, insert comment at its beginning."
22490 (beginning-of-line)
22491 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22492 (org-indent-line)
22493 (insert "# "))
22495 (defvar comment-empty-lines) ; From newcomment.el.
22496 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22497 "Comment or uncomment each non-blank line in the region.
22498 Uncomment each non-blank line between BEG and END if it only
22499 contains commented lines. Otherwise, comment them."
22500 (save-restriction
22501 ;; Restrict region
22502 (narrow-to-region (save-excursion (goto-char beg)
22503 (skip-chars-forward " \r\t\n" end)
22504 (line-beginning-position))
22505 (save-excursion (goto-char end)
22506 (skip-chars-backward " \r\t\n" beg)
22507 (line-end-position)))
22508 (let ((uncommentp
22509 ;; UNCOMMENTP is non-nil when every non blank line between
22510 ;; BEG and END is a comment.
22511 (save-excursion
22512 (goto-char (point-min))
22513 (while (and (not (eobp))
22514 (let ((element (org-element-at-point)))
22515 (and (eq (org-element-type element) 'comment)
22516 (goto-char (min (point-max)
22517 (org-element-property
22518 :end element)))))))
22519 (eobp))))
22520 (if uncommentp
22521 ;; Only blank lines and comments in region: uncomment it.
22522 (save-excursion
22523 (goto-char (point-min))
22524 (while (not (eobp))
22525 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22526 (replace-match "" nil nil nil 1))
22527 (forward-line)))
22528 ;; Comment each line in region.
22529 (let ((min-indent (point-max)))
22530 ;; First find the minimum indentation across all lines.
22531 (save-excursion
22532 (goto-char (point-min))
22533 (while (and (not (eobp)) (not (zerop min-indent)))
22534 (unless (looking-at "[ \t]*$")
22535 (setq min-indent (min min-indent (current-indentation))))
22536 (forward-line)))
22537 ;; Then loop over all lines.
22538 (save-excursion
22539 (goto-char (point-min))
22540 (while (not (eobp))
22541 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22542 ;; Don't get fooled by invisible text (e.g. link path)
22543 ;; when moving to column MIN-INDENT.
22544 (let ((buffer-invisibility-spec nil))
22545 (org-move-to-column min-indent t))
22546 (insert comment-start))
22547 (forward-line))))))))
22550 ;;; Planning
22552 ;; This section contains tools to operate on timestamp objects, as
22553 ;; returned by, e.g. `org-element-context'.
22555 (defun org-timestamp-has-time-p (timestamp)
22556 "Non-nil when TIMESTAMP has a time specified."
22557 (org-element-property :hour-start timestamp))
22559 (defun org-timestamp-format (timestamp format &optional end utc)
22560 "Format a TIMESTAMP element into a string.
22562 FORMAT is a format specifier to be passed to
22563 `format-time-string'.
22565 When optional argument END is non-nil, use end of date-range or
22566 time-range, if possible.
22568 When optional argument UTC is non-nil, time will be expressed as
22569 Universal Time."
22570 (format-time-string
22571 format
22572 (apply 'encode-time
22573 (cons 0
22574 (mapcar
22575 (lambda (prop) (or (org-element-property prop timestamp) 0))
22576 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22577 '(:minute-start :hour-start :day-start :month-start
22578 :year-start)))))
22579 utc))
22581 (defun org-timestamp-split-range (timestamp &optional end)
22582 "Extract a timestamp object from a date or time range.
22584 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22585 the end of the range. Otherwise, extract its start.
22587 Return a new timestamp object sharing the same parent as
22588 TIMESTAMP."
22589 (let ((type (org-element-property :type timestamp)))
22590 (if (memq type '(active inactive diary)) timestamp
22591 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22592 ;; Set new type.
22593 (org-element-put-property
22594 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22595 ;; Copy start properties over end properties if END is
22596 ;; non-nil. Otherwise, copy end properties over `start' ones.
22597 (let ((p-alist '((:minute-start . :minute-end)
22598 (:hour-start . :hour-end)
22599 (:day-start . :day-end)
22600 (:month-start . :month-end)
22601 (:year-start . :year-end))))
22602 (dolist (p-cell p-alist)
22603 (org-element-put-property
22604 split-ts
22605 (funcall (if end 'car 'cdr) p-cell)
22606 (org-element-property
22607 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22608 ;; Eventually refresh `:raw-value'.
22609 (org-element-put-property split-ts :raw-value nil)
22610 (org-element-put-property
22611 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22613 (defun org-timestamp-translate (timestamp &optional boundary)
22614 "Apply `org-translate-time' on a TIMESTAMP object.
22615 When optional argument BOUNDARY is non-nil, it is either the
22616 symbol `start' or `end'. In this case, only translate the
22617 starting or ending part of TIMESTAMP if it is a date or time
22618 range. Otherwise, translate both parts."
22619 (if (and (not boundary)
22620 (memq (org-element-property :type timestamp)
22621 '(active-range inactive-range)))
22622 (concat
22623 (org-translate-time
22624 (org-element-property :raw-value
22625 (org-timestamp-split-range timestamp)))
22626 "--"
22627 (org-translate-time
22628 (org-element-property :raw-value
22629 (org-timestamp-split-range timestamp t))))
22630 (org-translate-time
22631 (org-element-property
22632 :raw-value
22633 (if (not boundary) timestamp
22634 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22638 ;;; Other stuff.
22640 (defun org-toggle-fixed-width-section (arg)
22641 "Toggle the fixed-width export.
22642 If there is no active region, the QUOTE keyword at the current headline is
22643 inserted or removed. When present, it causes the text between this headline
22644 and the next to be exported as fixed-width text, and unmodified.
22645 If there is an active region, this command adds or removes a colon as the
22646 first character of this line. If the first character of a line is a colon,
22647 this line is also exported in fixed-width font."
22648 (interactive "P")
22649 (let* ((cc 0)
22650 (regionp (org-region-active-p))
22651 (beg (if regionp (region-beginning) (point)))
22652 (end (if regionp (region-end)))
22653 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22654 (case-fold-search nil)
22655 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22656 off)
22657 (if regionp
22658 (save-excursion
22659 (goto-char beg)
22660 (setq cc (current-column))
22661 (beginning-of-line 1)
22662 (setq off (looking-at re))
22663 (while (> nlines 0)
22664 (setq nlines (1- nlines))
22665 (beginning-of-line 1)
22666 (cond
22667 (arg
22668 (org-move-to-column cc t)
22669 (insert ": \n")
22670 (forward-line -1))
22671 ((and off (looking-at re))
22672 (replace-match "" t t nil 1))
22673 ((not off) (org-move-to-column cc t) (insert ": ")))
22674 (forward-line 1)))
22675 (save-excursion
22676 (org-back-to-heading)
22677 (cond
22678 ((looking-at (format org-heading-keyword-regexp-format
22679 org-quote-string))
22680 (goto-char (match-end 1))
22681 (looking-at (concat " +" org-quote-string))
22682 (replace-match "" t t)
22683 (when (eolp) (insert " ")))
22684 ((looking-at org-outline-regexp)
22685 (goto-char (match-end 0))
22686 (insert org-quote-string " ")))))))
22688 (defun org-reftex-citation ()
22689 "Use reftex-citation to insert a citation into the buffer.
22690 This looks for a line like
22692 #+BIBLIOGRAPHY: foo plain option:-d
22694 and derives from it that foo.bib is the bibliography file relevant
22695 for this document. It then installs the necessary environment for RefTeX
22696 to work in this buffer and calls `reftex-citation' to insert a citation
22697 into the buffer.
22699 Export of such citations to both LaTeX and HTML is handled by the contributed
22700 package ox-bibtex by Taru Karttunen."
22701 (interactive)
22702 (let ((reftex-docstruct-symbol 'rds)
22703 (reftex-cite-format "\\cite{%l}")
22704 rds bib)
22705 (save-excursion
22706 (save-restriction
22707 (widen)
22708 (let ((case-fold-search t)
22709 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22710 (if (not (save-excursion
22711 (or (re-search-forward re nil t)
22712 (re-search-backward re nil t))))
22713 (error "No bibliography defined in file")
22714 (setq bib (concat (match-string 1) ".bib")
22715 rds (list (list 'bib bib)))))))
22716 (call-interactively 'reftex-citation)))
22718 ;;;; Functions extending outline functionality
22720 (defun org-beginning-of-line (&optional arg)
22721 "Go to the beginning of the current line. If that is invisible, continue
22722 to a visible line beginning. This makes the function of C-a more intuitive.
22723 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22724 first attempt, and only move to after the tags when the cursor is already
22725 beyond the end of the headline."
22726 (interactive "P")
22727 (let ((pos (point))
22728 (special (if (consp org-special-ctrl-a/e)
22729 (car org-special-ctrl-a/e)
22730 org-special-ctrl-a/e))
22731 deactivate-mark refpos)
22732 (if (org-bound-and-true-p visual-line-mode)
22733 (beginning-of-visual-line 1)
22734 (beginning-of-line 1))
22735 (if (and arg (fboundp 'move-beginning-of-line))
22736 (call-interactively 'move-beginning-of-line)
22737 (if (bobp)
22739 (backward-char 1)
22740 (if (org-truely-invisible-p)
22741 (while (and (not (bobp)) (org-truely-invisible-p))
22742 (backward-char 1)
22743 (beginning-of-line 1))
22744 (forward-char 1))))
22745 (when special
22746 (cond
22747 ((and (looking-at org-complex-heading-regexp)
22748 (= (char-after (match-end 1)) ?\ ))
22749 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22750 (point-at-eol)))
22751 (goto-char
22752 (if (eq special t)
22753 (cond ((> pos refpos) refpos)
22754 ((= pos (point)) refpos)
22755 (t (point)))
22756 (cond ((> pos (point)) (point))
22757 ((not (eq last-command this-command)) (point))
22758 (t refpos)))))
22759 ((org-at-item-p)
22760 ;; Being at an item and not looking at an the item means point
22761 ;; was previously moved to beginning of a visual line, which
22762 ;; doesn't contain the item. Therefore, do nothing special,
22763 ;; just stay here.
22764 (when (looking-at org-list-full-item-re)
22765 ;; Set special position at first white space character after
22766 ;; bullet, and check-box, if any.
22767 (let ((after-bullet
22768 (let ((box (match-end 3)))
22769 (if (not box) (match-end 1)
22770 (let ((after (char-after box)))
22771 (if (and after (= after ? )) (1+ box) box))))))
22772 ;; Special case: Move point to special position when
22773 ;; currently after it or at beginning of line.
22774 (if (eq special t)
22775 (when (or (> pos after-bullet) (= (point) pos))
22776 (goto-char after-bullet))
22777 ;; Reversed case: Move point to special position when
22778 ;; point was already at beginning of line and command is
22779 ;; repeated.
22780 (when (and (= (point) pos) (eq last-command this-command))
22781 (goto-char after-bullet))))))))
22782 (org-no-warnings
22783 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22784 (setq disable-point-adjustment
22785 (or (not (invisible-p (point)))
22786 (not (invisible-p (max (point-min) (1- (point))))))))
22788 (defun org-end-of-line (&optional arg)
22789 "Go to the end of the line.
22790 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22791 tags on the first attempt, and only move to after the tags when
22792 the cursor is already beyond the end of the headline."
22793 (interactive "P")
22794 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22795 org-special-ctrl-a/e))
22796 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22797 'end-of-visual-line)
22798 ((fboundp 'move-end-of-line) 'move-end-of-line)
22799 (t 'end-of-line)))
22800 deactivate-mark)
22801 (if (or (not special) arg) (call-interactively move-fun)
22802 (let* ((element (save-excursion (beginning-of-line)
22803 (org-element-at-point)))
22804 (type (org-element-type element)))
22805 (cond
22806 ((memq type '(headline inlinetask))
22807 (let ((pos (point)))
22808 (beginning-of-line 1)
22809 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22810 (if (eq special t)
22811 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22812 (goto-char (match-beginning 1))
22813 (goto-char (match-end 0)))
22814 (if (or (< pos (match-end 0))
22815 (not (eq this-command last-command)))
22816 (goto-char (match-end 0))
22817 (goto-char (match-beginning 1))))
22818 (call-interactively move-fun))))
22819 ((org-element-property :hiddenp element)
22820 ;; If element is hidden, `move-end-of-line' would put point
22821 ;; after it. Use `end-of-line' to stay on current line.
22822 (call-interactively 'end-of-line))
22823 (t (call-interactively move-fun)))))
22824 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22825 (setq disable-point-adjustment
22826 (or (not (invisible-p (point)))
22827 (not (invisible-p (max (point-min) (1- (point))))))))
22829 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22830 (define-key org-mode-map "\C-e" 'org-end-of-line)
22832 (defun org-backward-sentence (&optional arg)
22833 "Go to beginning of sentence, or beginning of table field.
22834 This will call `backward-sentence' or `org-table-beginning-of-field',
22835 depending on context."
22836 (interactive "P")
22837 (cond
22838 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22839 (t (call-interactively 'backward-sentence))))
22841 (defun org-forward-sentence (&optional arg)
22842 "Go to end of sentence, or end of table field.
22843 This will call `forward-sentence' or `org-table-end-of-field',
22844 depending on context."
22845 (interactive "P")
22846 (cond
22847 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22848 (t (call-interactively 'forward-sentence))))
22850 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22851 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22853 (defun org-kill-line (&optional arg)
22854 "Kill line, to tags or end of line."
22855 (interactive "P")
22856 (cond
22857 ((or (not org-special-ctrl-k)
22858 (bolp)
22859 (not (org-at-heading-p)))
22860 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22861 org-ctrl-k-protect-subtree)
22862 (if (or (eq org-ctrl-k-protect-subtree 'error)
22863 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22864 (user-error "C-k aborted as it would kill a hidden subtree")))
22865 (call-interactively
22866 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22867 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22868 (kill-region (point) (match-beginning 1))
22869 (org-set-tags nil t))
22870 (t (kill-region (point) (point-at-eol)))))
22872 (define-key org-mode-map "\C-k" 'org-kill-line)
22874 (defun org-yank (&optional arg)
22875 "Yank. If the kill is a subtree, treat it specially.
22876 This command will look at the current kill and check if is a single
22877 subtree, or a series of subtrees[1]. If it passes the test, and if the
22878 cursor is at the beginning of a line or after the stars of a currently
22879 empty headline, then the yank is handled specially. How exactly depends
22880 on the value of the following variables, both set by default.
22882 org-yank-folded-subtrees
22883 When set, the subtree(s) will be folded after insertion, but only
22884 if doing so would now swallow text after the yanked text.
22886 org-yank-adjusted-subtrees
22887 When set, the subtree will be promoted or demoted in order to
22888 fit into the local outline tree structure, which means that the level
22889 will be adjusted so that it becomes the smaller one of the two
22890 *visible* surrounding headings.
22892 Any prefix to this command will cause `yank' to be called directly with
22893 no special treatment. In particular, a simple \\[universal-argument] prefix \
22894 will just
22895 plainly yank the text as it is.
22897 \[1] The test checks if the first non-white line is a heading
22898 and if there are no other headings with fewer stars."
22899 (interactive "P")
22900 (org-yank-generic 'yank arg))
22902 (defun org-yank-generic (command arg)
22903 "Perform some yank-like command.
22905 This function implements the behavior described in the `org-yank'
22906 documentation. However, it has been generalized to work for any
22907 interactive command with similar behavior."
22909 ;; pretend to be command COMMAND
22910 (setq this-command command)
22912 (if arg
22913 (call-interactively command)
22915 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22916 (and (org-kill-is-subtree-p)
22917 (or (bolp)
22918 (and (looking-at "[ \t]*$")
22919 (string-match
22920 "\\`\\*+\\'"
22921 (buffer-substring (point-at-bol) (point)))))))
22922 swallowp)
22923 (cond
22924 ((and subtreep org-yank-folded-subtrees)
22925 (let ((beg (point))
22926 end)
22927 (if (and subtreep org-yank-adjusted-subtrees)
22928 (org-paste-subtree nil nil 'for-yank)
22929 (call-interactively command))
22931 (setq end (point))
22932 (goto-char beg)
22933 (when (and (bolp) subtreep
22934 (not (setq swallowp
22935 (org-yank-folding-would-swallow-text beg end))))
22936 (org-with-limited-levels
22937 (or (looking-at org-outline-regexp)
22938 (re-search-forward org-outline-regexp-bol end t))
22939 (while (and (< (point) end) (looking-at org-outline-regexp))
22940 (hide-subtree)
22941 (org-cycle-show-empty-lines 'folded)
22942 (condition-case nil
22943 (outline-forward-same-level 1)
22944 (error (goto-char end))))))
22945 (when swallowp
22946 (message
22947 "Inserted text not folded because that would swallow text"))
22949 (goto-char end)
22950 (skip-chars-forward " \t\n\r")
22951 (beginning-of-line 1)
22952 (push-mark beg 'nomsg)))
22953 ((and subtreep org-yank-adjusted-subtrees)
22954 (let ((beg (point-at-bol)))
22955 (org-paste-subtree nil nil 'for-yank)
22956 (push-mark beg 'nomsg)))
22958 (call-interactively command))))))
22960 (defun org-yank-folding-would-swallow-text (beg end)
22961 "Would hide-subtree at BEG swallow any text after END?"
22962 (let (level)
22963 (org-with-limited-levels
22964 (save-excursion
22965 (goto-char beg)
22966 (when (or (looking-at org-outline-regexp)
22967 (re-search-forward org-outline-regexp-bol end t))
22968 (setq level (org-outline-level)))
22969 (goto-char end)
22970 (skip-chars-forward " \t\r\n\v\f")
22971 (if (or (eobp)
22972 (and (bolp) (looking-at org-outline-regexp)
22973 (<= (org-outline-level) level)))
22974 nil ; Nothing would be swallowed
22975 t))))) ; something would swallow
22977 (define-key org-mode-map "\C-y" 'org-yank)
22979 (defun org-truely-invisible-p ()
22980 "Check if point is at a character currently not visible.
22981 This version does not only check the character property, but also
22982 `visible-mode'."
22983 ;; Early versions of noutline don't have `outline-invisible-p'.
22984 (if (org-bound-and-true-p visible-mode)
22986 (outline-invisible-p)))
22988 (defun org-invisible-p2 ()
22989 "Check if point is at a character currently not visible."
22990 (save-excursion
22991 (if (and (eolp) (not (bobp))) (backward-char 1))
22992 ;; Early versions of noutline don't have `outline-invisible-p'.
22993 (outline-invisible-p)))
22995 (defun org-back-to-heading (&optional invisible-ok)
22996 "Call `outline-back-to-heading', but provide a better error message."
22997 (condition-case nil
22998 (outline-back-to-heading invisible-ok)
22999 (error (error "Before first headline at position %d in buffer %s"
23000 (point) (current-buffer)))))
23002 (defun org-before-first-heading-p ()
23003 "Before first heading?"
23004 (save-excursion
23005 (end-of-line)
23006 (null (re-search-backward org-outline-regexp-bol nil t))))
23008 (defun org-at-heading-p (&optional ignored)
23009 (outline-on-heading-p t))
23010 ;; Compatibility alias with Org versions < 7.8.03
23011 (defalias 'org-on-heading-p 'org-at-heading-p)
23013 (defun org-at-comment-p nil
23014 "Is cursor in a line starting with a # character?"
23015 (save-excursion
23016 (beginning-of-line)
23017 (looking-at "^#")))
23019 (defun org-at-drawer-p nil
23020 "Is cursor at a drawer keyword?"
23021 (save-excursion
23022 (move-beginning-of-line 1)
23023 (looking-at org-drawer-regexp)))
23025 (defun org-at-block-p nil
23026 "Is cursor at a block keyword?"
23027 (save-excursion
23028 (move-beginning-of-line 1)
23029 (looking-at org-block-regexp)))
23031 (defun org-point-at-end-of-empty-headline ()
23032 "If point is at the end of an empty headline, return t, else nil.
23033 If the heading only contains a TODO keyword, it is still still considered
23034 empty."
23035 (and (looking-at "[ \t]*$")
23036 (when org-todo-line-regexp
23037 (save-excursion
23038 (beginning-of-line 1)
23039 (let ((case-fold-search nil))
23040 (looking-at org-todo-line-regexp)
23041 (string= (match-string 3) ""))))))
23043 (defun org-at-heading-or-item-p ()
23044 (or (org-at-heading-p) (org-at-item-p)))
23046 (defun org-at-target-p ()
23047 (or (org-in-regexp org-radio-target-regexp)
23048 (org-in-regexp org-target-regexp)))
23049 ;; Compatibility alias with Org versions < 7.8.03
23050 (defalias 'org-on-target-p 'org-at-target-p)
23052 (defun org-up-heading-all (arg)
23053 "Move to the heading line of which the present line is a subheading.
23054 This function considers both visible and invisible heading lines.
23055 With argument, move up ARG levels."
23056 (if (fboundp 'outline-up-heading-all)
23057 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23058 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23060 (defun org-up-heading-safe ()
23061 "Move to the heading line of which the present line is a subheading.
23062 This version will not throw an error. It will return the level of the
23063 headline found, or nil if no higher level is found.
23065 Also, this function will be a lot faster than `outline-up-heading',
23066 because it relies on stars being the outline starters. This can really
23067 make a significant difference in outlines with very many siblings."
23068 (let (start-level re)
23069 (org-back-to-heading t)
23070 (setq start-level (funcall outline-level))
23071 (if (equal start-level 1)
23073 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23074 (if (re-search-backward re nil t)
23075 (funcall outline-level)))))
23077 (defun org-first-sibling-p ()
23078 "Is this heading the first child of its parents?"
23079 (interactive)
23080 (let ((re org-outline-regexp-bol)
23081 level l)
23082 (unless (org-at-heading-p t)
23083 (user-error "Not at a heading"))
23084 (setq level (funcall outline-level))
23085 (save-excursion
23086 (if (not (re-search-backward re nil t))
23088 (setq l (funcall outline-level))
23089 (< l level)))))
23091 (defun org-goto-sibling (&optional previous)
23092 "Goto the next sibling, even if it is invisible.
23093 When PREVIOUS is set, go to the previous sibling instead. Returns t
23094 when a sibling was found. When none is found, return nil and don't
23095 move point."
23096 (let ((fun (if previous 're-search-backward 're-search-forward))
23097 (pos (point))
23098 (re org-outline-regexp-bol)
23099 level l)
23100 (when (condition-case nil (org-back-to-heading t) (error nil))
23101 (setq level (funcall outline-level))
23102 (catch 'exit
23103 (or previous (forward-char 1))
23104 (while (funcall fun re nil t)
23105 (setq l (funcall outline-level))
23106 (when (< l level) (goto-char pos) (throw 'exit nil))
23107 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23108 (goto-char pos)
23109 nil))))
23111 (defun org-show-siblings ()
23112 "Show all siblings of the current headline."
23113 (save-excursion
23114 (while (org-goto-sibling) (org-flag-heading nil)))
23115 (save-excursion
23116 (while (org-goto-sibling 'previous)
23117 (org-flag-heading nil))))
23119 (defun org-goto-first-child ()
23120 "Goto the first child, even if it is invisible.
23121 Return t when a child was found. Otherwise don't move point and
23122 return nil."
23123 (let (level (pos (point)) (re org-outline-regexp-bol))
23124 (when (condition-case nil (org-back-to-heading t) (error nil))
23125 (setq level (outline-level))
23126 (forward-char 1)
23127 (if (and (re-search-forward re nil t) (> (outline-level) level))
23128 (progn (goto-char (match-beginning 0)) t)
23129 (goto-char pos) nil))))
23131 (defun org-show-hidden-entry ()
23132 "Show an entry where even the heading is hidden."
23133 (save-excursion
23134 (org-show-entry)))
23136 (defun org-flag-heading (flag &optional entry)
23137 "Flag the current heading. FLAG non-nil means make invisible.
23138 When ENTRY is non-nil, show the entire entry."
23139 (save-excursion
23140 (org-back-to-heading t)
23141 ;; Check if we should show the entire entry
23142 (if entry
23143 (progn
23144 (org-show-entry)
23145 (save-excursion
23146 (and (outline-next-heading)
23147 (org-flag-heading nil))))
23148 (outline-flag-region (max (point-min) (1- (point)))
23149 (save-excursion (outline-end-of-heading) (point))
23150 flag))))
23152 (defun org-get-next-sibling ()
23153 "Move to next heading of the same level, and return point.
23154 If there is no such heading, return nil.
23155 This is like outline-next-sibling, but invisible headings are ok."
23156 (let ((level (funcall outline-level)))
23157 (outline-next-heading)
23158 (while (and (not (eobp)) (> (funcall outline-level) level))
23159 (outline-next-heading))
23160 (if (or (eobp) (< (funcall outline-level) level))
23162 (point))))
23164 (defun org-get-last-sibling ()
23165 "Move to previous heading of the same level, and return point.
23166 If there is no such heading, return nil."
23167 (let ((opoint (point))
23168 (level (funcall outline-level)))
23169 (outline-previous-heading)
23170 (when (and (/= (point) opoint) (outline-on-heading-p t))
23171 (while (and (> (funcall outline-level) level)
23172 (not (bobp)))
23173 (outline-previous-heading))
23174 (if (< (funcall outline-level) level)
23176 (point)))))
23178 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23179 "Goto to the end of a subtree."
23180 ;; This contains an exact copy of the original function, but it uses
23181 ;; `org-back-to-heading', to make it work also in invisible
23182 ;; trees. And is uses an invisible-ok argument.
23183 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23184 ;; Furthermore, when used inside Org, finding the end of a large subtree
23185 ;; with many children and grandchildren etc, this can be much faster
23186 ;; than the outline version.
23187 (org-back-to-heading invisible-ok)
23188 (let ((first t)
23189 (level (funcall outline-level)))
23190 (if (and (derived-mode-p 'org-mode) (< level 1000))
23191 ;; A true heading (not a plain list item), in Org-mode
23192 ;; This means we can easily find the end by looking
23193 ;; only for the right number of stars. Using a regexp to do
23194 ;; this is so much faster than using a Lisp loop.
23195 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23196 (forward-char 1)
23197 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23198 ;; something else, do it the slow way
23199 (while (and (not (eobp))
23200 (or first (> (funcall outline-level) level)))
23201 (setq first nil)
23202 (outline-next-heading)))
23203 (unless to-heading
23204 (if (memq (preceding-char) '(?\n ?\^M))
23205 (progn
23206 ;; Go to end of line before heading
23207 (forward-char -1)
23208 (if (memq (preceding-char) '(?\n ?\^M))
23209 ;; leave blank line before heading
23210 (forward-char -1))))))
23211 (point))
23213 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23214 "Use Org version in org-mode, for dramatic speed-up."
23215 (if (derived-mode-p 'org-mode)
23216 (progn
23217 (org-end-of-subtree nil t)
23218 (unless (eobp) (backward-char 1)))
23219 ad-do-it))
23221 (defun org-end-of-meta-data-and-drawers ()
23222 "Jump to the first text after meta data and drawers in the current entry.
23223 This will move over empty lines, lines with planning time stamps,
23224 clocking lines, and drawers."
23225 (org-back-to-heading t)
23226 (let ((end (save-excursion (outline-next-heading) (point)))
23227 (re (concat "\\(" org-drawer-regexp "\\)"
23228 "\\|" "[ \t]*" org-keyword-time-regexp)))
23229 (forward-line 1)
23230 (while (re-search-forward re end t)
23231 (if (not (match-end 1))
23232 ;; empty or planning line
23233 (forward-line 1)
23234 ;; a drawer, find the end
23235 (re-search-forward "^[ \t]*:END:" end 'move)
23236 (forward-line 1)))
23237 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23238 (point)))
23240 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23241 "Move forward to the ARG'th subheading at same level as this one.
23242 Stop at the first and last subheadings of a superior heading.
23243 Normally this only looks at visible headings, but when INVISIBLE-OK is
23244 non-nil it will also look at invisible ones."
23245 (interactive "p")
23246 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23247 (if (and arg (< arg 0))
23248 (goto-char (point-min))
23249 (outline-next-heading))
23250 (org-at-heading-p)
23251 (let ((level (- (match-end 0) (match-beginning 0) 1))
23252 (f (if (and arg (< arg 0))
23253 're-search-backward
23254 're-search-forward))
23255 (count (if arg (abs arg) 1))
23256 (result (point)))
23257 (while (and (prog1 (> count 0)
23258 (forward-char (if (and arg (< arg 0)) -1 1)))
23259 (funcall f org-outline-regexp-bol nil 'move))
23260 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23261 (cond ((< l level) (setq count 0))
23262 ((and (= l level)
23263 (or invisible-ok
23264 (progn
23265 (goto-char (line-beginning-position))
23266 (not (outline-invisible-p)))))
23267 (setq count (1- count))
23268 (when (eq l level)
23269 (setq result (point)))))))
23270 (goto-char result))
23271 (beginning-of-line 1)))
23273 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23274 "Move backward to the ARG'th subheading at same level as this one.
23275 Stop at the first and last subheadings of a superior heading."
23276 (interactive "p")
23277 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23279 (defun org-next-block (arg &optional backward block-regexp)
23280 "Jump to the next block.
23281 With a prefix argument ARG, jump forward ARG many source blocks.
23282 When BACKWARD is non-nil, jump to the previous block.
23283 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23284 (interactive "p")
23285 (let ((re (or block-regexp org-block-regexp))
23286 (re-search-fn (or (and backward 're-search-backward)
23287 're-search-forward)))
23288 (if (looking-at re) (forward-char 1))
23289 (condition-case nil
23290 (funcall re-search-fn re nil nil arg)
23291 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23292 (goto-char (match-beginning 0)) (org-show-context)))
23294 (defun org-previous-block (arg &optional block-regexp)
23295 "Jump to the previous block.
23296 With a prefix argument ARG, jump backward ARG many source blocks.
23297 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23298 (interactive "p")
23299 (org-next-block arg t block-regexp))
23301 (defun org-forward-paragraph ()
23302 "Move forward to beginning of next paragraph or equivalent.
23304 The function moves point to the beginning of the next visible
23305 structural element, which can be a paragraph, a table, a list
23306 item, etc. It also provides some special moves for convenience:
23308 - On an affiliated keyword, jump to the beginning of the
23309 relative element.
23310 - On an item or a footnote definition, move to the second
23311 element inside, if any.
23312 - On a table or a property drawer, jump after it.
23313 - On a verse or source block, stop after blank lines."
23314 (interactive)
23315 (when (eobp) (user-error "Cannot move further down"))
23316 (let* ((deactivate-mark nil)
23317 (element (org-element-at-point))
23318 (type (org-element-type element))
23319 (post-affiliated (org-element-property :post-affiliated element))
23320 (contents-begin (org-element-property :contents-begin element))
23321 (contents-end (org-element-property :contents-end element))
23322 (end (let ((end (org-element-property :end element)) (parent element))
23323 (while (and (setq parent (org-element-property :parent parent))
23324 (= (org-element-property :contents-end parent) end))
23325 (setq end (org-element-property :end parent)))
23326 end)))
23327 (cond ((not element)
23328 (skip-chars-forward " \r\t\n")
23329 (or (eobp) (beginning-of-line)))
23330 ;; On affiliated keywords, move to element's beginning.
23331 ((and post-affiliated (< (point) post-affiliated))
23332 (goto-char post-affiliated))
23333 ;; At a table row, move to the end of the table. Similarly,
23334 ;; at a node property, move to the end of the property
23335 ;; drawer.
23336 ((memq type '(node-property table-row))
23337 (goto-char (org-element-property
23338 :end (org-element-property :parent element))))
23339 ((memq type '(property-drawer table)) (goto-char end))
23340 ;; Consider blank lines as separators in verse and source
23341 ;; blocks to ease editing.
23342 ((memq type '(src-block verse-block))
23343 (when (eq type 'src-block)
23344 (setq contents-end
23345 (save-excursion (goto-char end)
23346 (skip-chars-backward " \r\t\n")
23347 (line-beginning-position))))
23348 (beginning-of-line)
23349 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23350 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23351 (goto-char end)
23352 (skip-chars-forward " \r\t\n")
23353 (if (= (point) contents-end) (goto-char end)
23354 (beginning-of-line))))
23355 ;; With no contents, just skip element.
23356 ((not contents-begin) (goto-char end))
23357 ;; If contents are invisible, skip the element altogether.
23358 ((outline-invisible-p (line-end-position))
23359 (case type
23360 (headline
23361 (org-with-limited-levels (outline-next-visible-heading 1)))
23362 ;; At a plain list, make sure we move to the next item
23363 ;; instead of skipping the whole list.
23364 (plain-list (forward-char)
23365 (org-forward-paragraph))
23366 (otherwise (goto-char end))))
23367 ((>= (point) contents-end) (goto-char end))
23368 ((>= (point) contents-begin)
23369 ;; This can only happen on paragraphs and plain lists.
23370 (case type
23371 (paragraph (goto-char end))
23372 ;; At a plain list, try to move to second element in
23373 ;; first item, if possible.
23374 (plain-list (end-of-line)
23375 (org-forward-paragraph))))
23376 ;; When contents start on the middle of a line (e.g. in
23377 ;; items and footnote definitions), try to reach first
23378 ;; element starting after current line.
23379 ((> (line-end-position) contents-begin)
23380 (end-of-line)
23381 (org-forward-paragraph))
23382 (t (goto-char contents-begin)))))
23384 (defun org-backward-paragraph ()
23385 "Move backward to start of previous paragraph or equivalent.
23387 The function moves point to the beginning of the current
23388 structural element, which can be a paragraph, a table, a list
23389 item, etc., or to the beginning of the previous visible one if
23390 point is already there. It also provides some special moves for
23391 convenience:
23393 - On an affiliated keyword, jump to the first one.
23394 - On a table or a property drawer, move to its beginning.
23395 - On a verse or source block, stop before blank lines."
23396 (interactive)
23397 (when (bobp) (user-error "Cannot move further up"))
23398 (let* ((deactivate-mark nil)
23399 (element (org-element-at-point))
23400 (type (org-element-type element))
23401 (contents-begin (org-element-property :contents-begin element))
23402 (contents-end (org-element-property :contents-end element))
23403 (post-affiliated (org-element-property :post-affiliated element))
23404 (begin (org-element-property :begin element)))
23405 (cond
23406 ((not element) (goto-char (point-min)))
23407 ((= (point) begin)
23408 (backward-char)
23409 (org-backward-paragraph))
23410 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23411 ((memq type '(node-property table-row))
23412 (goto-char (org-element-property
23413 :post-affiliated (org-element-property :parent element))))
23414 ((memq type '(property-drawer table)) (goto-char begin))
23415 ((memq type '(src-block verse-block))
23416 (when (eq type 'src-block)
23417 (setq contents-begin
23418 (save-excursion (goto-char begin) (forward-line) (point))))
23419 (if (= (point) contents-begin) (goto-char post-affiliated)
23420 ;; Inside a verse block, see blank lines as paragraph
23421 ;; separators.
23422 (let ((origin (point)))
23423 (skip-chars-backward " \r\t\n" contents-begin)
23424 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23425 (skip-chars-forward " \r\t\n" origin)
23426 (if (= (point) origin) (goto-char contents-begin)
23427 (beginning-of-line))))))
23428 ((not contents-begin) (goto-char (or post-affiliated begin)))
23429 ((eq type 'paragraph)
23430 (goto-char contents-begin)
23431 ;; When at first paragraph in an item or a footnote definition,
23432 ;; move directly to beginning of line.
23433 (let ((parent-contents
23434 (org-element-property
23435 :contents-begin (org-element-property :parent element))))
23436 (when (and parent-contents (= parent-contents contents-begin))
23437 (beginning-of-line))))
23438 ;; At the end of a greater element, move to the beginning of the
23439 ;; last element within.
23440 ((>= (point) contents-end)
23441 (goto-char (1- contents-end))
23442 (org-backward-paragraph))
23443 (t (goto-char (or post-affiliated begin))))
23444 ;; Ensure we never leave point invisible.
23445 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23447 (defun org-forward-element ()
23448 "Move forward by one element.
23449 Move to the next element at the same level, when possible."
23450 (interactive)
23451 (cond ((eobp) (user-error "Cannot move further down"))
23452 ((org-with-limited-levels (org-at-heading-p))
23453 (let ((origin (point)))
23454 (goto-char (org-end-of-subtree nil t))
23455 (unless (org-with-limited-levels (org-at-heading-p))
23456 (goto-char origin)
23457 (user-error "Cannot move further down"))))
23459 (let* ((elem (org-element-at-point))
23460 (end (org-element-property :end elem))
23461 (parent (org-element-property :parent elem)))
23462 (cond ((and parent (= (org-element-property :contents-end parent) end))
23463 (goto-char (org-element-property :end parent)))
23464 ((integer-or-marker-p end) (goto-char end))
23465 (t (message "No element at point")))))))
23467 (defun org-backward-element ()
23468 "Move backward by one element.
23469 Move to the previous element at the same level, when possible."
23470 (interactive)
23471 (cond ((bobp) (user-error "Cannot move further up"))
23472 ((org-with-limited-levels (org-at-heading-p))
23473 ;; At a headline, move to the previous one, if any, or stay
23474 ;; here.
23475 (let ((origin (point)))
23476 (org-with-limited-levels (org-backward-heading-same-level 1))
23477 ;; When current headline has no sibling above, move to its
23478 ;; parent.
23479 (when (= (point) origin)
23480 (or (org-with-limited-levels (org-up-heading-safe))
23481 (progn (goto-char origin)
23482 (user-error "Cannot move further up"))))))
23484 (let* ((trail (org-element-at-point 'keep-trail))
23485 (elem (car trail))
23486 (prev-elem (nth 1 trail))
23487 (beg (org-element-property :begin elem)))
23488 (cond
23489 ;; Move to beginning of current element if point isn't
23490 ;; there already.
23491 ((null beg) (message "No element at point"))
23492 ((/= (point) beg) (goto-char beg))
23493 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23494 ((org-before-first-heading-p) (goto-char (point-min)))
23495 (t (org-back-to-heading)))))))
23497 (defun org-up-element ()
23498 "Move to upper element."
23499 (interactive)
23500 (if (org-with-limited-levels (org-at-heading-p))
23501 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23502 (let* ((elem (org-element-at-point))
23503 (parent (org-element-property :parent elem)))
23504 (if parent (goto-char (org-element-property :begin parent))
23505 (if (org-with-limited-levels (org-before-first-heading-p))
23506 (user-error "No surrounding element")
23507 (org-with-limited-levels (org-back-to-heading)))))))
23509 (defvar org-element-greater-elements)
23510 (defun org-down-element ()
23511 "Move to inner element."
23512 (interactive)
23513 (let ((element (org-element-at-point)))
23514 (cond
23515 ((memq (org-element-type element) '(plain-list table))
23516 (goto-char (org-element-property :contents-begin element))
23517 (forward-char))
23518 ((memq (org-element-type element) org-element-greater-elements)
23519 ;; If contents are hidden, first disclose them.
23520 (when (org-element-property :hiddenp element) (org-cycle))
23521 (goto-char (or (org-element-property :contents-begin element)
23522 (user-error "No content for this element"))))
23523 (t (user-error "No inner element")))))
23525 (defun org-drag-element-backward ()
23526 "Move backward element at point."
23527 (interactive)
23528 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23529 (let* ((trail (org-element-at-point 'keep-trail))
23530 (elem (car trail))
23531 (prev-elem (nth 1 trail)))
23532 ;; Error out if no previous element or previous element is
23533 ;; a parent of the current one.
23534 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23535 (user-error "Cannot drag element backward")
23536 (let ((pos (point)))
23537 (org-element-swap-A-B prev-elem elem)
23538 (goto-char (+ (org-element-property :begin prev-elem)
23539 (- pos (org-element-property :begin elem)))))))))
23541 (defun org-drag-element-forward ()
23542 "Move forward element at point."
23543 (interactive)
23544 (let* ((pos (point))
23545 (elem (org-element-at-point)))
23546 (when (= (point-max) (org-element-property :end elem))
23547 (user-error "Cannot drag element forward"))
23548 (goto-char (org-element-property :end elem))
23549 (let ((next-elem (org-element-at-point)))
23550 (when (or (org-element-nested-p elem next-elem)
23551 (and (eq (org-element-type next-elem) 'headline)
23552 (not (eq (org-element-type elem) 'headline))))
23553 (goto-char pos)
23554 (user-error "Cannot drag element forward"))
23555 ;; Compute new position of point: it's shifted by NEXT-ELEM
23556 ;; body's length (without final blanks) and by the length of
23557 ;; blanks between ELEM and NEXT-ELEM.
23558 (let ((size-next (- (save-excursion
23559 (goto-char (org-element-property :end next-elem))
23560 (skip-chars-backward " \r\t\n")
23561 (forward-line)
23562 ;; Small correction if buffer doesn't end
23563 ;; with a newline character.
23564 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23565 (org-element-property :begin next-elem)))
23566 (size-blank (- (org-element-property :end elem)
23567 (save-excursion
23568 (goto-char (org-element-property :end elem))
23569 (skip-chars-backward " \r\t\n")
23570 (forward-line)
23571 (point)))))
23572 (org-element-swap-A-B elem next-elem)
23573 (goto-char (+ pos size-next size-blank))))))
23575 (defun org-drag-line-forward (arg)
23576 "Drag the line at point ARG lines forward."
23577 (interactive "p")
23578 (dotimes (n (abs arg))
23579 (let ((c (current-column)))
23580 (if (< 0 arg)
23581 (progn
23582 (beginning-of-line 2)
23583 (transpose-lines 1)
23584 (beginning-of-line 0))
23585 (transpose-lines 1)
23586 (beginning-of-line -1))
23587 (org-move-to-column c))))
23589 (defun org-drag-line-backward (arg)
23590 "Drag the line at point ARG lines backward."
23591 (interactive "p")
23592 (org-drag-line-forward (- arg)))
23594 (defun org-mark-element ()
23595 "Put point at beginning of this element, mark at end.
23597 Interactively, if this command is repeated or (in Transient Mark
23598 mode) if the mark is active, it marks the next element after the
23599 ones already marked."
23600 (interactive)
23601 (let (deactivate-mark)
23602 (if (and (org-called-interactively-p 'any)
23603 (or (and (eq last-command this-command) (mark t))
23604 (and transient-mark-mode mark-active)))
23605 (set-mark
23606 (save-excursion
23607 (goto-char (mark))
23608 (goto-char (org-element-property :end (org-element-at-point)))))
23609 (let ((element (org-element-at-point)))
23610 (end-of-line)
23611 (push-mark (org-element-property :end element) t t)
23612 (goto-char (org-element-property :begin element))))))
23614 (defun org-narrow-to-element ()
23615 "Narrow buffer to current element."
23616 (interactive)
23617 (let ((elem (org-element-at-point)))
23618 (cond
23619 ((eq (car elem) 'headline)
23620 (narrow-to-region
23621 (org-element-property :begin elem)
23622 (org-element-property :end elem)))
23623 ((memq (car elem) org-element-greater-elements)
23624 (narrow-to-region
23625 (org-element-property :contents-begin elem)
23626 (org-element-property :contents-end elem)))
23628 (narrow-to-region
23629 (org-element-property :begin elem)
23630 (org-element-property :end elem))))))
23632 (defun org-transpose-element ()
23633 "Transpose current and previous elements, keeping blank lines between.
23634 Point is moved after both elements."
23635 (interactive)
23636 (org-skip-whitespace)
23637 (let ((end (org-element-property :end (org-element-at-point))))
23638 (org-drag-element-backward)
23639 (goto-char end)))
23641 (defun org-unindent-buffer ()
23642 "Un-indent the visible part of the buffer.
23643 Relative indentation (between items, inside blocks, etc.) isn't
23644 modified."
23645 (interactive)
23646 (unless (eq major-mode 'org-mode)
23647 (user-error "Cannot un-indent a buffer not in Org mode"))
23648 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23649 unindent-tree ; For byte-compiler.
23650 (unindent-tree
23651 (function
23652 (lambda (contents)
23653 (mapc
23654 (lambda (element)
23655 (if (memq (org-element-type element) '(headline section))
23656 (funcall unindent-tree (org-element-contents element))
23657 (save-excursion
23658 (save-restriction
23659 (narrow-to-region
23660 (org-element-property :begin element)
23661 (org-element-property :end element))
23662 (org-do-remove-indentation)))))
23663 (reverse contents))))))
23664 (funcall unindent-tree (org-element-contents parse-tree))))
23666 (defun org-show-subtree ()
23667 "Show everything after this heading at deeper levels."
23668 (interactive)
23669 (outline-flag-region
23670 (point)
23671 (save-excursion
23672 (org-end-of-subtree t t))
23673 nil))
23675 (defun org-show-entry ()
23676 "Show the body directly following this heading.
23677 Show the heading too, if it is currently invisible."
23678 (interactive)
23679 (save-excursion
23680 (condition-case nil
23681 (progn
23682 (org-back-to-heading t)
23683 (outline-flag-region
23684 (max (point-min) (1- (point)))
23685 (save-excursion
23686 (if (re-search-forward
23687 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23688 (match-beginning 1)
23689 (point-max)))
23690 nil)
23691 (org-cycle-hide-drawers 'children))
23692 (error nil))))
23694 (defun org-make-options-regexp (kwds &optional extra)
23695 "Make a regular expression for keyword lines."
23696 (concat
23697 "^#\\+\\("
23698 (mapconcat 'regexp-quote kwds "\\|")
23699 (if extra (concat "\\|" extra))
23700 "\\):[ \t]*\\(.*\\)"))
23702 ;; Make isearch reveal the necessary context
23703 (defun org-isearch-end ()
23704 "Reveal context after isearch exits."
23705 (when isearch-success ; only if search was successful
23706 (if (featurep 'xemacs)
23707 ;; Under XEmacs, the hook is run in the correct place,
23708 ;; we directly show the context.
23709 (org-show-context 'isearch)
23710 ;; In Emacs the hook runs *before* restoring the overlays.
23711 ;; So we have to use a one-time post-command-hook to do this.
23712 ;; (Emacs 22 has a special variable, see function `org-mode')
23713 (unless (and (boundp 'isearch-mode-end-hook-quit)
23714 isearch-mode-end-hook-quit)
23715 ;; Only when the isearch was not quitted.
23716 (org-add-hook 'post-command-hook 'org-isearch-post-command
23717 'append 'local)))
23718 (org-fix-ellipsis-at-bol)))
23720 (defun org-isearch-post-command ()
23721 "Remove self from hook, and show context."
23722 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23723 (org-show-context 'isearch))
23726 ;;;; Integration with and fixes for other packages
23728 ;;; Imenu support
23730 (defvar org-imenu-markers nil
23731 "All markers currently used by Imenu.")
23732 (make-variable-buffer-local 'org-imenu-markers)
23734 (defun org-imenu-new-marker (&optional pos)
23735 "Return a new marker for use by Imenu, and remember the marker."
23736 (let ((m (make-marker)))
23737 (move-marker m (or pos (point)))
23738 (push m org-imenu-markers)
23741 (defun org-imenu-get-tree ()
23742 "Produce the index for Imenu."
23743 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23744 (setq org-imenu-markers nil)
23745 (let* ((n org-imenu-depth)
23746 (re (concat "^" (org-get-limited-outline-regexp)))
23747 (subs (make-vector (1+ n) nil))
23748 (last-level 0)
23749 m level head0 head)
23750 (save-excursion
23751 (save-restriction
23752 (widen)
23753 (goto-char (point-max))
23754 (while (re-search-backward re nil t)
23755 (setq level (org-reduced-level (funcall outline-level)))
23756 (when (and (<= level n)
23757 (looking-at org-complex-heading-regexp)
23758 (setq head0 (org-match-string-no-properties 4)))
23759 (setq head (org-link-display-format head0)
23760 m (org-imenu-new-marker))
23761 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23762 (if (>= level last-level)
23763 (push (cons head m) (aref subs level))
23764 (push (cons head (aref subs (1+ level))) (aref subs level))
23765 (loop for i from (1+ level) to n do (aset subs i nil)))
23766 (setq last-level level)))))
23767 (aref subs 1)))
23769 (eval-after-load "imenu"
23770 '(progn
23771 (add-hook 'imenu-after-jump-hook
23772 (lambda ()
23773 (if (derived-mode-p 'org-mode)
23774 (org-show-context 'org-goto))))))
23776 (defun org-link-display-format (link)
23777 "Replace a link with its the description.
23778 If there is no description, use the link target."
23779 (save-match-data
23780 (if (string-match org-bracket-link-analytic-regexp link)
23781 (replace-match (if (match-end 5)
23782 (match-string 5 link)
23783 (concat (match-string 1 link)
23784 (match-string 3 link)))
23785 nil t link)
23786 link)))
23788 (defun org-toggle-link-display ()
23789 "Toggle the literal or descriptive display of links."
23790 (interactive)
23791 (if org-descriptive-links
23792 (progn (org-remove-from-invisibility-spec '(org-link))
23793 (org-restart-font-lock)
23794 (setq org-descriptive-links nil))
23795 (progn (add-to-invisibility-spec '(org-link))
23796 (org-restart-font-lock)
23797 (setq org-descriptive-links t))))
23799 ;; Speedbar support
23801 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23802 "Overlay marking the agenda restriction line in speedbar.")
23803 (overlay-put org-speedbar-restriction-lock-overlay
23804 'face 'org-agenda-restriction-lock)
23805 (overlay-put org-speedbar-restriction-lock-overlay
23806 'help-echo "Agendas are currently limited to this item.")
23807 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23809 (defun org-speedbar-set-agenda-restriction ()
23810 "Restrict future agenda commands to the location at point in speedbar.
23811 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23812 (interactive)
23813 (require 'org-agenda)
23814 (let (p m tp np dir txt)
23815 (cond
23816 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23817 'org-imenu t))
23818 (setq m (get-text-property p 'org-imenu-marker))
23819 (with-current-buffer (marker-buffer m)
23820 (goto-char m)
23821 (org-agenda-set-restriction-lock 'subtree)))
23822 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23823 'speedbar-function 'speedbar-find-file))
23824 (setq tp (previous-single-property-change
23825 (1+ p) 'speedbar-function)
23826 np (next-single-property-change
23827 tp 'speedbar-function)
23828 dir (speedbar-line-directory)
23829 txt (buffer-substring-no-properties (or tp (point-min))
23830 (or np (point-max))))
23831 (with-current-buffer (find-file-noselect
23832 (let ((default-directory dir))
23833 (expand-file-name txt)))
23834 (unless (derived-mode-p 'org-mode)
23835 (user-error "Cannot restrict to non-Org-mode file"))
23836 (org-agenda-set-restriction-lock 'file)))
23837 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23838 (move-overlay org-speedbar-restriction-lock-overlay
23839 (point-at-bol) (point-at-eol))
23840 (setq current-prefix-arg nil)
23841 (org-agenda-maybe-redo)))
23843 (defvar speedbar-file-key-map)
23844 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23845 (eval-after-load "speedbar"
23846 '(progn
23847 (speedbar-add-supported-extension ".org")
23848 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23849 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23850 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23851 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23852 (add-hook 'speedbar-visiting-tag-hook
23853 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23855 ;;; Fixes and Hacks for problems with other packages
23857 ;; Make flyspell not check words in links, to not mess up our keymap
23858 (defvar org-element-affiliated-keywords) ; From org-element.el
23859 (defvar org-element-block-name-alist) ; From org-element.el
23860 (defun org-mode-flyspell-verify ()
23861 "Don't let flyspell put overlays at active buttons, or on
23862 {todo,all-time,additional-option-like}-keywords."
23863 (require 'org-element) ; For `org-element-affiliated-keywords'
23864 (let ((pos (max (1- (point)) (point-min)))
23865 (word (thing-at-point 'word)))
23866 (and (not (get-text-property pos 'keymap))
23867 (not (get-text-property pos 'org-no-flyspell))
23868 (not (member word org-todo-keywords-1))
23869 (not (member word org-all-time-keywords))
23870 (not (member word org-options-keywords))
23871 (not (member word (mapcar 'car org-startup-options)))
23872 (not (member-ignore-case word org-element-affiliated-keywords))
23873 (not (member-ignore-case word (org-get-export-keywords)))
23874 (not (member-ignore-case
23875 word (mapcar 'car org-element-block-name-alist)))
23876 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23877 (not (org-in-src-block-p)))))
23879 (defun org-remove-flyspell-overlays-in (beg end)
23880 "Remove flyspell overlays in region."
23881 (and (org-bound-and-true-p flyspell-mode)
23882 (fboundp 'flyspell-delete-region-overlays)
23883 (flyspell-delete-region-overlays beg end))
23884 (add-text-properties beg end '(org-no-flyspell t)))
23886 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23887 (eval-after-load "bookmark"
23888 '(if (boundp 'bookmark-after-jump-hook)
23889 ;; We can use the hook
23890 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23891 ;; Hook not available, use advice
23892 (defadvice bookmark-jump (after org-make-visible activate)
23893 "Make the position visible."
23894 (org-bookmark-jump-unhide))))
23896 ;; Make sure saveplace shows the location if it was hidden
23897 (eval-after-load "saveplace"
23898 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23899 "Make the position visible."
23900 (org-bookmark-jump-unhide)))
23902 ;; Make sure ecb shows the location if it was hidden
23903 (eval-after-load "ecb"
23904 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23905 "Make hierarchy visible when jumping into location from ECB tree buffer."
23906 (if (derived-mode-p 'org-mode)
23907 (org-show-context))))
23909 (defun org-bookmark-jump-unhide ()
23910 "Unhide the current position, to show the bookmark location."
23911 (and (derived-mode-p 'org-mode)
23912 (or (outline-invisible-p)
23913 (save-excursion (goto-char (max (point-min) (1- (point))))
23914 (outline-invisible-p)))
23915 (org-show-context 'bookmark-jump)))
23917 ;; Make session.el ignore our circular variable
23918 (defvar session-globals-exclude)
23919 (eval-after-load "session"
23920 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23922 ;;;; Finish up
23924 (provide 'org)
23926 (run-hooks 'org-load-hook)
23928 ;;; org.el ends here