make comment-dwim in source code blocks more DWIM-ish
[org-mode/org-tableheadings.git] / lisp / org.el
blob485f6d0b794c673b215c6f860a17e128a7538055
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-cache-reset "org-element" (&optional all))
144 (declare-function org-element-contents "org-element" (element))
145 (declare-function org-element-context "org-element" (&optional element))
146 (declare-function org-element-interpret-data "org-element"
147 (data &optional parent))
148 (declare-function org-element-map "org-element"
149 (data types fun &optional info first-match no-recursion))
150 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
151 (declare-function org-element-parse-buffer "org-element"
152 (&optional granularity visible-only))
153 (declare-function org-element-property "org-element" (property element))
154 (declare-function org-element-put-property "org-element"
155 (element property value))
156 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
157 (declare-function org-element--parse-objects "org-element"
158 (beg end acc restriction))
159 (declare-function org-element-parse-buffer "org-element"
160 (&optional granularity visible-only))
161 (declare-function org-element-restriction "org-element" (element))
162 (declare-function org-element-type "org-element" (element))
164 ;; load languages based on value of `org-babel-load-languages'
165 (defvar org-babel-load-languages)
167 ;;;###autoload
168 (defun org-babel-do-load-languages (sym value)
169 "Load the languages defined in `org-babel-load-languages'."
170 (set-default sym value)
171 (mapc (lambda (pair)
172 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
173 (if active
174 (progn
175 (require (intern (concat "ob-" lang))))
176 (progn
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-execute:" lang)))
179 (funcall 'fmakunbound
180 (intern (concat "org-babel-expand-body:" lang)))))))
181 org-babel-load-languages))
183 ;;;###autoload
184 (defun org-babel-load-file (file &optional compile)
185 "Load Emacs Lisp source code blocks in the Org-mode FILE.
186 This function exports the source code using `org-babel-tangle'
187 and then loads the resulting file using `load-file'. With prefix
188 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
189 file to byte-code before it is loaded."
190 (interactive "fFile to load: \nP")
191 (require 'ob-core)
192 (let* ((age (lambda (file)
193 (float-time
194 (time-subtract (current-time)
195 (nth 5 (or (file-attributes (file-truename file))
196 (file-attributes file)))))))
197 (base-name (file-name-sans-extension file))
198 (exported-file (concat base-name ".el")))
199 ;; tangle if the org-mode file is newer than the elisp file
200 (unless (and (file-exists-p exported-file)
201 (> (funcall age file) (funcall age exported-file)))
202 (setq exported-file
203 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
204 (message "%s %s"
205 (if compile
206 (progn (byte-compile-file exported-file 'load)
207 "Compiled and loaded")
208 (progn (load-file exported-file) "Loaded"))
209 exported-file)))
211 (defcustom org-babel-load-languages '((emacs-lisp . t))
212 "Languages which can be evaluated in Org-mode buffers.
213 This list can be used to load support for any of the languages
214 below, note that each language will depend on a different set of
215 system executables and/or Emacs modes. When a language is
216 \"loaded\", then code blocks in that language can be evaluated
217 with `org-babel-execute-src-block' bound by default to C-c
218 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
219 be set to remove code block evaluation from the C-c C-c
220 keybinding. By default only Emacs Lisp (which has no
221 requirements) is loaded."
222 :group 'org-babel
223 :set 'org-babel-do-load-languages
224 :version "24.1"
225 :type '(alist :tag "Babel Languages"
226 :key-type
227 (choice
228 (const :tag "Awk" awk)
229 (const :tag "C" C)
230 (const :tag "R" R)
231 (const :tag "Asymptote" asymptote)
232 (const :tag "Calc" calc)
233 (const :tag "Clojure" clojure)
234 (const :tag "CSS" css)
235 (const :tag "Ditaa" ditaa)
236 (const :tag "Dot" dot)
237 (const :tag "Emacs Lisp" emacs-lisp)
238 (const :tag "Fortran" fortran)
239 (const :tag "Gnuplot" gnuplot)
240 (const :tag "Haskell" haskell)
241 (const :tag "IO" io)
242 (const :tag "Java" java)
243 (const :tag "Javascript" js)
244 (const :tag "LaTeX" latex)
245 (const :tag "Ledger" ledger)
246 (const :tag "Lilypond" lilypond)
247 (const :tag "Lisp" lisp)
248 (const :tag "Makefile" makefile)
249 (const :tag "Maxima" maxima)
250 (const :tag "Matlab" matlab)
251 (const :tag "Mscgen" mscgen)
252 (const :tag "Ocaml" ocaml)
253 (const :tag "Octave" octave)
254 (const :tag "Org" org)
255 (const :tag "Perl" perl)
256 (const :tag "Pico Lisp" picolisp)
257 (const :tag "PlantUML" plantuml)
258 (const :tag "Python" python)
259 (const :tag "Ruby" ruby)
260 (const :tag "Sass" sass)
261 (const :tag "Scala" scala)
262 (const :tag "Scheme" scheme)
263 (const :tag "Screen" screen)
264 (const :tag "Shell Script" sh)
265 (const :tag "Shen" shen)
266 (const :tag "Sql" sql)
267 (const :tag "Sqlite" sqlite)
268 (const :tag "ebnf2ps" ebnf2ps))
269 :value-type (boolean :tag "Activate" :value t)))
271 ;;;; Customization variables
272 (defcustom org-clone-delete-id nil
273 "Remove ID property of clones of a subtree.
274 When non-nil, clones of a subtree don't inherit the ID property.
275 Otherwise they inherit the ID property with a new unique
276 identifier."
277 :type 'boolean
278 :version "24.1"
279 :group 'org-id)
281 ;;; Version
282 (org-check-version)
284 ;;;###autoload
285 (defun org-version (&optional here full message)
286 "Show the org-mode version in the echo area.
287 With prefix argument HERE, insert it at point.
288 When FULL is non-nil, use a verbose version string.
289 When MESSAGE is non-nil, display a message with the version."
290 (interactive "P")
291 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
292 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
293 (load-suffixes (list ".el"))
294 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
295 (org-trash (or
296 (and (fboundp 'org-release) (fboundp 'org-git-version))
297 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
298 (load-suffixes save-load-suffixes)
299 (org-version (org-release))
300 (git-version (org-git-version))
301 (version (format "Org-mode version %s (%s @ %s)"
302 org-version
303 git-version
304 (if org-install-dir
305 (if (string= org-dir org-install-dir)
306 org-install-dir
307 (concat "mixed installation! " org-install-dir " and " org-dir))
308 "org-loaddefs.el can not be found!")))
309 (_version (if full version org-version)))
310 (if (org-called-interactively-p 'interactive)
311 (if here
312 (insert version)
313 (message version))
314 (if message (message _version))
315 _version)))
317 (defconst org-version (org-version))
319 ;;; Compatibility constants
321 ;;; The custom variables
323 (defgroup org nil
324 "Outline-based notes management and organizer."
325 :tag "Org"
326 :group 'outlines
327 :group 'calendar)
329 (defcustom org-mode-hook nil
330 "Mode hook for Org-mode, run after the mode was turned on."
331 :group 'org
332 :type 'hook)
334 (defcustom org-load-hook nil
335 "Hook that is run after org.el has been loaded."
336 :group 'org
337 :type 'hook)
339 (defcustom org-log-buffer-setup-hook nil
340 "Hook that is run after an Org log buffer is created."
341 :group 'org
342 :version "24.1"
343 :type 'hook)
345 (defvar org-modules) ; defined below
346 (defvar org-modules-loaded nil
347 "Have the modules been loaded already?")
349 (defun org-load-modules-maybe (&optional force)
350 "Load all extensions listed in `org-modules'."
351 (when (or force (not org-modules-loaded))
352 (mapc (lambda (ext)
353 (condition-case nil (require ext)
354 (error (message "Problems while trying to load feature `%s'" ext))))
355 org-modules)
356 (setq org-modules-loaded t)))
358 (defun org-set-modules (var value)
359 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
360 (set var value)
361 (when (featurep 'org)
362 (org-load-modules-maybe 'force)
363 (org-element-cache-reset 'all)))
365 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
366 "Modules that should always be loaded together with org.el.
368 If a description starts with <C>, the file is not part of Emacs
369 and loading it will require that you have downloaded and properly
370 installed the Org mode distribution.
372 You can also use this system to load external packages (i.e. neither Org
373 core modules, nor modules from the CONTRIB directory). Just add symbols
374 to the end of the list. If the package is called org-xyz.el, then you need
375 to add the symbol `xyz', and the package must have a call to:
377 \(provide 'org-xyz)
379 For export specific modules, see also `org-export-backends'."
380 :group 'org
381 :set 'org-set-modules
382 :version "24.4"
383 :package-version '(Org . "8.0")
384 :type
385 '(set :greedy t
386 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
387 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
388 (const :tag " crypt: Encryption of subtrees" org-crypt)
389 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
390 (const :tag " docview: Links to doc-view buffers" org-docview)
391 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
392 (const :tag " habit: Track your consistency with habits" org-habit)
393 (const :tag " id: Global IDs for identifying entries" org-id)
394 (const :tag " info: Links to Info nodes" org-info)
395 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
396 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
397 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
398 (const :tag " mouse: Additional mouse support" org-mouse)
399 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
400 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
401 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
403 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
404 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
405 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
406 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
407 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
408 (const :tag "C collector: Collect properties into tables" org-collector)
409 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
410 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
411 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
412 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
413 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
414 (const :tag "C eval: Include command output as text" org-eval)
415 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
416 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
417 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
418 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
419 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
420 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
421 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
422 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
423 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
424 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
425 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
426 (const :tag "C mew: Links to Mew folders/messages" org-mew)
427 (const :tag "C mtags: Support for muse-like tags" org-mtags)
428 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
429 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
430 (const :tag "C registry: A registry for Org-mode links" org-registry)
431 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
432 (const :tag "C secretary: Team management with org-mode" org-secretary)
433 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
434 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
435 (const :tag "C track: Keep up with Org-mode development" org-track)
436 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
437 (const :tag "C vm: Links to VM folders/messages" org-vm)
438 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
439 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
440 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
442 (defvar org-export--registered-backends) ; From ox.el.
443 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
444 (declare-function org-export-backend-name "ox" (backend))
445 (defcustom org-export-backends '(ascii html icalendar latex)
446 "List of export back-ends that should be always available.
448 If a description starts with <C>, the file is not part of Emacs
449 and loading it will require that you have downloaded and properly
450 installed the Org mode distribution.
452 Unlike to `org-modules', libraries in this list will not be
453 loaded along with Org, but only once the export framework is
454 needed.
456 This variable needs to be set before org.el is loaded. If you
457 need to make a change while Emacs is running, use the customize
458 interface or run the following code, where VAL stands for the new
459 value of the variable, after updating it:
461 \(progn
462 \(setq org-export--registered-backends
463 \(org-remove-if-not
464 \(lambda (backend)
465 \(let ((name (org-export-backend-name backend)))
466 \(or (memq name val)
467 \(catch 'parentp
468 \(dolist (b val)
469 \(and (org-export-derived-backend-p b name)
470 \(throw 'parentp t)))))))
471 org-export--registered-backends))
472 \(let ((new-list (mapcar 'org-export-backend-name
473 org-export--registered-backends)))
474 \(dolist (backend val)
475 \(cond
476 \((not (load (format \"ox-%s\" backend) t t))
477 \(message \"Problems while trying to load export back-end `%s'\"
478 backend))
479 \((not (memq backend new-list)) (push backend new-list))))
480 \(set-default 'org-export-backends new-list)))
482 Adding a back-end to this list will also pull the back-end it
483 depends on, if any."
484 :group 'org
485 :group 'org-export
486 :version "24.4"
487 :package-version '(Org . "8.0")
488 :initialize 'custom-initialize-set
489 :set (lambda (var val)
490 (if (not (featurep 'ox)) (set-default var val)
491 ;; Any back-end not required anymore (not present in VAL and not
492 ;; a parent of any back-end in the new value) is removed from the
493 ;; list of registered back-ends.
494 (setq org-export--registered-backends
495 (org-remove-if-not
496 (lambda (backend)
497 (let ((name (org-export-backend-name backend)))
498 (or (memq name val)
499 (catch 'parentp
500 (dolist (b val)
501 (and (org-export-derived-backend-p b name)
502 (throw 'parentp t)))))))
503 org-export--registered-backends))
504 ;; Now build NEW-LIST of both new back-ends and required
505 ;; parents.
506 (let ((new-list (mapcar 'org-export-backend-name
507 org-export--registered-backends)))
508 (dolist (backend val)
509 (cond
510 ((not (load (format "ox-%s" backend) t t))
511 (message "Problems while trying to load export back-end `%s'"
512 backend))
513 ((not (memq backend new-list)) (push backend new-list))))
514 ;; Set VAR to that list with fixed dependencies.
515 (set-default var new-list))))
516 :type '(set :greedy t
517 (const :tag " ascii Export buffer to ASCII format" ascii)
518 (const :tag " beamer Export buffer to Beamer presentation" beamer)
519 (const :tag " html Export buffer to HTML format" html)
520 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
521 (const :tag " latex Export buffer to LaTeX format" latex)
522 (const :tag " man Export buffer to MAN format" man)
523 (const :tag " md Export buffer to Markdown format" md)
524 (const :tag " odt Export buffer to ODT format" odt)
525 (const :tag " org Export buffer to Org format" org)
526 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
527 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
528 (const :tag "C deck Export buffer to deck.js presentations" deck)
529 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
530 (const :tag "C groff Export buffer to Groff format" groff)
531 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
532 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
533 (const :tag "C s5 Export buffer to s5 presentations" s5)
534 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
536 (eval-after-load 'ox
537 '(mapc
538 (lambda (backend)
539 (condition-case nil (require (intern (format "ox-%s" backend)))
540 (error (message "Problems while trying to load export back-end `%s'"
541 backend))))
542 org-export-backends))
544 (defcustom org-support-shift-select nil
545 "Non-nil means make shift-cursor commands select text when possible.
547 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
548 start selecting a region, or enlarge regions started in this way.
549 In Org-mode, in special contexts, these same keys are used for
550 other purposes, important enough to compete with shift selection.
551 Org tries to balance these needs by supporting `shift-select-mode'
552 outside these special contexts, under control of this variable.
554 The default of this variable is nil, to avoid confusing behavior. Shifted
555 cursor keys will then execute Org commands in the following contexts:
556 - on a headline, changing TODO state (left/right) and priority (up/down)
557 - on a time stamp, changing the time
558 - in a plain list item, changing the bullet type
559 - in a property definition line, switching between allowed values
560 - in the BEGIN line of a clock table (changing the time block).
561 Outside these contexts, the commands will throw an error.
563 When this variable is t and the cursor is not in a special
564 context, Org-mode will support shift-selection for making and
565 enlarging regions. To make this more effective, the bullet
566 cycling will no longer happen anywhere in an item line, but only
567 if the cursor is exactly on the bullet.
569 If you set this variable to the symbol `always', then the keys
570 will not be special in headlines, property lines, and item lines,
571 to make shift selection work there as well. If this is what you
572 want, you can use the following alternative commands: `C-c C-t'
573 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
574 can be used to switch TODO sets, `C-c -' to cycle item bullet
575 types, and properties can be edited by hand or in column view.
577 However, when the cursor is on a timestamp, shift-cursor commands
578 will still edit the time stamp - this is just too good to give up.
580 XEmacs user should have this variable set to nil, because
581 `shift-select-mode' is in Emacs 23 or later only."
582 :group 'org
583 :type '(choice
584 (const :tag "Never" nil)
585 (const :tag "When outside special context" t)
586 (const :tag "Everywhere except timestamps" always)))
588 (defcustom org-loop-over-headlines-in-active-region nil
589 "Shall some commands act upon headlines in the active region?
591 When set to `t', some commands will be performed in all headlines
592 within the active region.
594 When set to `start-level', some commands will be performed in all
595 headlines within the active region, provided that these headlines
596 are of the same level than the first one.
598 When set to a string, those commands will be performed on the
599 matching headlines within the active region. Such string must be
600 a tags/property/todo match as it is used in the agenda tags view.
602 The list of commands is: `org-schedule', `org-deadline',
603 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
604 `org-archive-to-archive-sibling'. The archiving commands skip
605 already archived entries."
606 :type '(choice (const :tag "Don't loop" nil)
607 (const :tag "All headlines in active region" t)
608 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
609 (string :tag "Tags/Property/Todo matcher"))
610 :version "24.1"
611 :group 'org-todo
612 :group 'org-archive)
614 (defgroup org-startup nil
615 "Options concerning startup of Org-mode."
616 :tag "Org Startup"
617 :group 'org)
619 (defcustom org-startup-folded t
620 "Non-nil means entering Org-mode will switch to OVERVIEW.
621 This can also be configured on a per-file basis by adding one of
622 the following lines anywhere in the buffer:
624 #+STARTUP: fold (or `overview', this is equivalent)
625 #+STARTUP: nofold (or `showall', this is equivalent)
626 #+STARTUP: content
627 #+STARTUP: showeverything
629 By default, this option is ignored when Org opens agenda files
630 for the first time. If you want the agenda to honor the startup
631 option, set `org-agenda-inhibit-startup' to nil."
632 :group 'org-startup
633 :type '(choice
634 (const :tag "nofold: show all" nil)
635 (const :tag "fold: overview" t)
636 (const :tag "content: all headlines" content)
637 (const :tag "show everything, even drawers" showeverything)))
639 (defcustom org-startup-truncated t
640 "Non-nil means entering Org-mode will set `truncate-lines'.
641 This is useful since some lines containing links can be very long and
642 uninteresting. Also tables look terrible when wrapped."
643 :group 'org-startup
644 :type 'boolean)
646 (defcustom org-startup-indented nil
647 "Non-nil means turn on `org-indent-mode' on startup.
648 This can also be configured on a per-file basis by adding one of
649 the following lines anywhere in the buffer:
651 #+STARTUP: indent
652 #+STARTUP: noindent"
653 :group 'org-structure
654 :type '(choice
655 (const :tag "Not" nil)
656 (const :tag "Globally (slow on startup in large files)" t)))
658 (defcustom org-use-sub-superscripts t
659 "Non-nil means interpret \"_\" and \"^\" for display.
660 When this option is turned on, you can use TeX-like syntax for sub- and
661 superscripts. Several characters after \"_\" or \"^\" will be
662 considered as a single item - so grouping with {} is normally not
663 needed. For example, the following things will be parsed as single
664 sub- or superscripts.
666 10^24 or 10^tau several digits will be considered 1 item.
667 10^-12 or 10^-tau a leading sign with digits or a word
668 x^2-y^3 will be read as x^2 - y^3, because items are
669 terminated by almost any nonword/nondigit char.
670 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
672 Still, ambiguity is possible - so when in doubt use {} to enclose
673 the sub/superscript. If you set this variable to the symbol
674 `{}', the braces are *required* in order to trigger
675 interpretations as sub/superscript. This can be helpful in
676 documents that need \"_\" frequently in plain text."
677 :group 'org-startup
678 :version "24.1"
679 :type '(choice
680 (const :tag "Always interpret" t)
681 (const :tag "Only with braces" {})
682 (const :tag "Never interpret" nil)))
684 (defcustom org-startup-with-beamer-mode nil
685 "Non-nil means turn on `org-beamer-mode' on startup.
686 This can also be configured on a per-file basis by adding one of
687 the following lines anywhere in the buffer:
689 #+STARTUP: beamer"
690 :group 'org-startup
691 :version "24.1"
692 :type 'boolean)
694 (defcustom org-startup-align-all-tables nil
695 "Non-nil means align all tables when visiting a file.
696 This is useful when the column width in tables is forced with <N> cookies
697 in table fields. Such tables will look correct only after the first re-align.
698 This can also be configured on a per-file basis by adding one of
699 the following lines anywhere in the buffer:
700 #+STARTUP: align
701 #+STARTUP: noalign"
702 :group 'org-startup
703 :type 'boolean)
705 (defcustom org-startup-with-inline-images nil
706 "Non-nil means show inline images when loading a new Org file.
707 This can also be configured on a per-file basis by adding one of
708 the following lines anywhere in the buffer:
709 #+STARTUP: inlineimages
710 #+STARTUP: noinlineimages"
711 :group 'org-startup
712 :version "24.1"
713 :type 'boolean)
715 (defcustom org-startup-with-latex-preview nil
716 "Non-nil means preview LaTeX fragments when loading a new Org file.
718 This can also be configured on a per-file basis by adding one of
719 the followinglines anywhere in the buffer:
720 #+STARTUP: latexpreview
721 #+STARTUP: nolatexpreview"
722 :group 'org-startup
723 :version "24.4"
724 :package-version '(Org . "8.0")
725 :type 'boolean)
727 (defcustom org-insert-mode-line-in-empty-file nil
728 "Non-nil means insert the first line setting Org-mode in empty files.
729 When the function `org-mode' is called interactively in an empty file, this
730 normally means that the file name does not automatically trigger Org-mode.
731 To ensure that the file will always be in Org-mode in the future, a
732 line enforcing Org-mode will be inserted into the buffer, if this option
733 has been set."
734 :group 'org-startup
735 :type 'boolean)
737 (defcustom org-replace-disputed-keys nil
738 "Non-nil means use alternative key bindings for some keys.
739 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
740 These keys are also used by other packages like shift-selection-mode'
741 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
742 If you want to use Org-mode together with one of these other modes,
743 or more generally if you would like to move some Org-mode commands to
744 other keys, set this variable and configure the keys with the variable
745 `org-disputed-keys'.
747 This option is only relevant at load-time of Org-mode, and must be set
748 *before* org.el is loaded. Changing it requires a restart of Emacs to
749 become effective."
750 :group 'org-startup
751 :type 'boolean)
753 (defcustom org-use-extra-keys nil
754 "Non-nil means use extra key sequence definitions for certain commands.
755 This happens automatically if you run XEmacs or if `window-system'
756 is nil. This variable lets you do the same manually. You must
757 set it before loading org.
759 Example: on Carbon Emacs 22 running graphically, with an external
760 keyboard on a Powerbook, the default way of setting M-left might
761 not work for either Alt or ESC. Setting this variable will make
762 it work for ESC."
763 :group 'org-startup
764 :type 'boolean)
766 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
768 (defcustom org-disputed-keys
769 '(([(shift up)] . [(meta p)])
770 ([(shift down)] . [(meta n)])
771 ([(shift left)] . [(meta -)])
772 ([(shift right)] . [(meta +)])
773 ([(control shift right)] . [(meta shift +)])
774 ([(control shift left)] . [(meta shift -)]))
775 "Keys for which Org-mode and other modes compete.
776 This is an alist, cars are the default keys, second element specifies
777 the alternative to use when `org-replace-disputed-keys' is t.
779 Keys can be specified in any syntax supported by `define-key'.
780 The value of this option takes effect only at Org-mode's startup,
781 therefore you'll have to restart Emacs to apply it after changing."
782 :group 'org-startup
783 :type 'alist)
785 (defun org-key (key)
786 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
787 Or return the original if not disputed.
788 Also apply the translations defined in `org-xemacs-key-equivalents'."
789 (when org-replace-disputed-keys
790 (let* ((nkey (key-description key))
791 (x (org-find-if (lambda (x)
792 (equal (key-description (car x)) nkey))
793 org-disputed-keys)))
794 (setq key (if x (cdr x) key))))
795 (when (featurep 'xemacs)
796 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
797 key)
799 (defun org-find-if (predicate seq)
800 (catch 'exit
801 (while seq
802 (if (funcall predicate (car seq))
803 (throw 'exit (car seq))
804 (pop seq)))))
806 (defun org-defkey (keymap key def)
807 "Define a key, possibly translated, as returned by `org-key'."
808 (define-key keymap (org-key key) def))
810 (defcustom org-ellipsis nil
811 "The ellipsis to use in the Org-mode outline.
812 When nil, just use the standard three dots. When a string, use that instead,
813 When a face, use the standard 3 dots, but with the specified face.
814 The change affects only Org-mode (which will then use its own display table).
815 Changing this requires executing `M-x org-mode' in a buffer to become
816 effective."
817 :group 'org-startup
818 :type '(choice (const :tag "Default" nil)
819 (face :tag "Face" :value org-warning)
820 (string :tag "String" :value "...#")))
822 (defvar org-display-table nil
823 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
825 (defgroup org-keywords nil
826 "Keywords in Org-mode."
827 :tag "Org Keywords"
828 :group 'org)
830 (defcustom org-deadline-string "DEADLINE:"
831 "String to mark deadline entries.
832 A deadline is this string, followed by a time stamp. Should be a word,
833 terminated by a colon. You can insert a schedule keyword and
834 a timestamp with \\[org-deadline].
835 Changes become only effective after restarting Emacs."
836 :group 'org-keywords
837 :type 'string)
839 (defcustom org-scheduled-string "SCHEDULED:"
840 "String to mark scheduled TODO entries.
841 A schedule is this string, followed by a time stamp. Should be a word,
842 terminated by a colon. You can insert a schedule keyword and
843 a timestamp with \\[org-schedule].
844 Changes become only effective after restarting Emacs."
845 :group 'org-keywords
846 :type 'string)
848 (defcustom org-closed-string "CLOSED:"
849 "String used as the prefix for timestamps logging closing a TODO entry."
850 :group 'org-keywords
851 :type 'string)
853 (defcustom org-clock-string "CLOCK:"
854 "String used as prefix for timestamps clocking work hours on an item."
855 :group 'org-keywords
856 :type 'string)
858 (defcustom org-closed-keep-when-no-todo nil
859 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
860 :group 'org-todo
861 :group 'org-keywords
862 :version "24.4"
863 :package-version '(Org . "8.0")
864 :type 'boolean)
866 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
867 org-scheduled-string "\\|"
868 org-deadline-string "\\|"
869 org-closed-string "\\|"
870 org-clock-string "\\)")
871 "Matches a line with planning or clock info.")
873 (defcustom org-comment-string "COMMENT"
874 "Entries starting with this keyword will never be exported.
875 An entry can be toggled between COMMENT and normal with
876 \\[org-toggle-comment].
877 Changes become only effective after restarting Emacs."
878 :group 'org-keywords
879 :type 'string)
881 (defcustom org-quote-string "QUOTE"
882 "Entries starting with this keyword will be exported in fixed-width font.
883 Quoting applies only to the text in the entry following the headline, and does
884 not extend beyond the next headline, even if that is lower level.
885 An entry can be toggled between QUOTE and normal with
886 \\[org-toggle-fixed-width-section]."
887 :group 'org-keywords
888 :type 'string)
890 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
891 "Matches first line of a hidden block.
892 Group 1 contains drawer's name.")
894 (defconst org-repeat-re
895 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
896 "Regular expression for specifying repeated events.
897 After a match, group 1 contains the repeat expression.")
899 (defgroup org-structure nil
900 "Options concerning the general structure of Org-mode files."
901 :tag "Org Structure"
902 :group 'org)
904 (defgroup org-reveal-location nil
905 "Options about how to make context of a location visible."
906 :tag "Org Reveal Location"
907 :group 'org-structure)
909 (defconst org-context-choice
910 '(choice
911 (const :tag "Always" t)
912 (const :tag "Never" nil)
913 (repeat :greedy t :tag "Individual contexts"
914 (cons
915 (choice :tag "Context"
916 (const agenda)
917 (const org-goto)
918 (const occur-tree)
919 (const tags-tree)
920 (const link-search)
921 (const mark-goto)
922 (const bookmark-jump)
923 (const isearch)
924 (const default))
925 (boolean))))
926 "Contexts for the reveal options.")
928 (defcustom org-show-hierarchy-above '((default . t))
929 "Non-nil means show full hierarchy when revealing a location.
930 Org-mode often shows locations in an org-mode file which might have
931 been invisible before. When this is set, the hierarchy of headings
932 above the exposed location is shown.
933 Turning this off for example for sparse trees makes them very compact.
934 Instead of t, this can also be an alist specifying this option for different
935 contexts. Valid contexts are
936 agenda when exposing an entry from the agenda
937 org-goto when using the command `org-goto' on key C-c C-j
938 occur-tree when using the command `org-occur' on key C-c /
939 tags-tree when constructing a sparse tree based on tags matches
940 link-search when exposing search matches associated with a link
941 mark-goto when exposing the jump goal of a mark
942 bookmark-jump when exposing a bookmark location
943 isearch when exiting from an incremental search
944 default default for all contexts not set explicitly"
945 :group 'org-reveal-location
946 :type org-context-choice)
948 (defcustom org-show-following-heading '((default . nil))
949 "Non-nil means show following heading when revealing a location.
950 Org-mode often shows locations in an org-mode file which might have
951 been invisible before. When this is set, the heading following the
952 match is shown.
953 Turning this off for example for sparse trees makes them very compact,
954 but makes it harder to edit the location of the match. In such a case,
955 use the command \\[org-reveal] to show more context.
956 Instead of t, this can also be an alist specifying this option for different
957 contexts. See `org-show-hierarchy-above' for valid contexts."
958 :group 'org-reveal-location
959 :type org-context-choice)
961 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
962 "Non-nil means show all sibling heading when revealing a location.
963 Org-mode often shows locations in an org-mode file which might have
964 been invisible before. When this is set, the sibling of the current entry
965 heading are all made visible. If `org-show-hierarchy-above' is t,
966 the same happens on each level of the hierarchy above the current entry.
968 By default this is on for the isearch context, off for all other contexts.
969 Turning this off for example for sparse trees makes them very compact,
970 but makes it harder to edit the location of the match. In such a case,
971 use the command \\[org-reveal] to show more context.
972 Instead of t, this can also be an alist specifying this option for different
973 contexts. See `org-show-hierarchy-above' for valid contexts."
974 :group 'org-reveal-location
975 :type org-context-choice
976 :version "24.4"
977 :package-version '(Org . "8.0"))
979 (defcustom org-show-entry-below '((default . nil))
980 "Non-nil means show the entry below a headline when revealing a location.
981 Org-mode often shows locations in an org-mode file which might have
982 been invisible before. When this is set, the text below the headline that is
983 exposed is also shown.
985 By default this is off for all contexts.
986 Instead of t, this can also be an alist specifying this option for different
987 contexts. See `org-show-hierarchy-above' for valid contexts."
988 :group 'org-reveal-location
989 :type org-context-choice)
991 (defcustom org-indirect-buffer-display 'other-window
992 "How should indirect tree buffers be displayed?
993 This applies to indirect buffers created with the commands
994 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
995 Valid values are:
996 current-window Display in the current window
997 other-window Just display in another window.
998 dedicated-frame Create one new frame, and re-use it each time.
999 new-frame Make a new frame each time. Note that in this case
1000 previously-made indirect buffers are kept, and you need to
1001 kill these buffers yourself."
1002 :group 'org-structure
1003 :group 'org-agenda-windows
1004 :type '(choice
1005 (const :tag "In current window" current-window)
1006 (const :tag "In current frame, other window" other-window)
1007 (const :tag "Each time a new frame" new-frame)
1008 (const :tag "One dedicated frame" dedicated-frame)))
1010 (defcustom org-use-speed-commands nil
1011 "Non-nil means activate single letter commands at beginning of a headline.
1012 This may also be a function to test for appropriate locations where speed
1013 commands should be active."
1014 :group 'org-structure
1015 :type '(choice
1016 (const :tag "Never" nil)
1017 (const :tag "At beginning of headline stars" t)
1018 (function)))
1020 (defcustom org-speed-commands-user nil
1021 "Alist of additional speed commands.
1022 This list will be checked before `org-speed-commands-default'
1023 when the variable `org-use-speed-commands' is non-nil
1024 and when the cursor is at the beginning of a headline.
1025 The car if each entry is a string with a single letter, which must
1026 be assigned to `self-insert-command' in the global map.
1027 The cdr is either a command to be called interactively, a function
1028 to be called, or a form to be evaluated.
1029 An entry that is just a list with a single string will be interpreted
1030 as a descriptive headline that will be added when listing the speed
1031 commands in the Help buffer using the `?' speed command."
1032 :group 'org-structure
1033 :type '(repeat :value ("k" . ignore)
1034 (choice :value ("k" . ignore)
1035 (list :tag "Descriptive Headline" (string :tag "Headline"))
1036 (cons :tag "Letter and Command"
1037 (string :tag "Command letter")
1038 (choice
1039 (function)
1040 (sexp))))))
1042 (defcustom org-bookmark-names-plist
1043 '(:last-capture "org-capture-last-stored"
1044 :last-refile "org-refile-last-stored"
1045 :last-capture-marker "org-capture-last-stored-marker")
1046 "Names for bookmarks automatically set by some Org commands.
1047 This can provide strings as names for a number of bookmakrs Org sets
1048 automatically. The following keys are currently implemented:
1049 :last-capture
1050 :last-capture-marker
1051 :last-refile
1052 When a key does not show up in the property list, the corresponding bookmark
1053 is not set."
1054 :group 'org-structure
1055 :type 'plist)
1057 (defgroup org-cycle nil
1058 "Options concerning visibility cycling in Org-mode."
1059 :tag "Org Cycle"
1060 :group 'org-structure)
1062 (defcustom org-cycle-skip-children-state-if-no-children t
1063 "Non-nil means skip CHILDREN state in entries that don't have any."
1064 :group 'org-cycle
1065 :type 'boolean)
1067 (defcustom org-cycle-max-level nil
1068 "Maximum level which should still be subject to visibility cycling.
1069 Levels higher than this will, for cycling, be treated as text, not a headline.
1070 When `org-odd-levels-only' is set, a value of N in this variable actually
1071 means 2N-1 stars as the limiting headline.
1072 When nil, cycle all levels.
1073 Note that the limiting level of cycling is also influenced by
1074 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1075 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1076 than its value."
1077 :group 'org-cycle
1078 :type '(choice
1079 (const :tag "No limit" nil)
1080 (integer :tag "Maximum level")))
1082 (defcustom org-hide-block-startup nil
1083 "Non-nil means entering Org-mode will fold all blocks.
1084 This can also be set in on a per-file basis with
1086 #+STARTUP: hideblocks
1087 #+STARTUP: showblocks"
1088 :group 'org-startup
1089 :group 'org-cycle
1090 :type 'boolean)
1092 (defcustom org-cycle-global-at-bob nil
1093 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1094 This makes it possible to do global cycling without having to use S-TAB or
1095 \\[universal-argument] TAB. For this special case to work, the first line
1096 of the buffer must not be a headline -- it may be empty or some other text.
1097 When used in this way, `org-cycle-hook' is disabled temporarily to make
1098 sure the cursor stays at the beginning of the buffer. When this option is
1099 nil, don't do anything special at the beginning of the buffer."
1100 :group 'org-cycle
1101 :type 'boolean)
1103 (defcustom org-cycle-level-after-item/entry-creation t
1104 "Non-nil means cycle entry level or item indentation in new empty entries.
1106 When the cursor is at the end of an empty headline, i.e., with only stars
1107 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1108 and then all possible ancestor states, before returning to the original state.
1109 This makes data entry extremely fast: M-RET to create a new headline,
1110 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1112 When the cursor is at the end of an empty plain list item, one TAB will
1113 make it a subitem, two or more tabs will back up to make this an item
1114 higher up in the item hierarchy."
1115 :group 'org-cycle
1116 :type 'boolean)
1118 (defcustom org-cycle-emulate-tab t
1119 "Where should `org-cycle' emulate TAB.
1120 nil Never
1121 white Only in completely white lines
1122 whitestart Only at the beginning of lines, before the first non-white char
1123 t Everywhere except in headlines
1124 exc-hl-bol Everywhere except at the start of a headline
1125 If TAB is used in a place where it does not emulate TAB, the current subtree
1126 visibility is cycled."
1127 :group 'org-cycle
1128 :type '(choice (const :tag "Never" nil)
1129 (const :tag "Only in completely white lines" white)
1130 (const :tag "Before first char in a line" whitestart)
1131 (const :tag "Everywhere except in headlines" t)
1132 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1134 (defcustom org-cycle-separator-lines 2
1135 "Number of empty lines needed to keep an empty line between collapsed trees.
1136 If you leave an empty line between the end of a subtree and the following
1137 headline, this empty line is hidden when the subtree is folded.
1138 Org-mode will leave (exactly) one empty line visible if the number of
1139 empty lines is equal or larger to the number given in this variable.
1140 So the default 2 means at least 2 empty lines after the end of a subtree
1141 are needed to produce free space between a collapsed subtree and the
1142 following headline.
1144 If the number is negative, and the number of empty lines is at least -N,
1145 all empty lines are shown.
1147 Special case: when 0, never leave empty lines in collapsed view."
1148 :group 'org-cycle
1149 :type 'integer)
1150 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1152 (defcustom org-pre-cycle-hook nil
1153 "Hook that is run before visibility cycling is happening.
1154 The function(s) in this hook must accept a single argument which indicates
1155 the new state that will be set right after running this hook. The
1156 argument is a symbol. Before a global state change, it can have the values
1157 `overview', `content', or `all'. Before a local state change, it can have
1158 the values `folded', `children', or `subtree'."
1159 :group 'org-cycle
1160 :type 'hook)
1162 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1163 org-cycle-hide-drawers
1164 org-cycle-hide-inline-tasks
1165 org-cycle-show-empty-lines
1166 org-optimize-window-after-visibility-change)
1167 "Hook that is run after `org-cycle' has changed the buffer visibility.
1168 The function(s) in this hook must accept a single argument which indicates
1169 the new state that was set by the most recent `org-cycle' command. The
1170 argument is a symbol. After a global state change, it can have the values
1171 `overview', `contents', or `all'. After a local state change, it can have
1172 the values `folded', `children', or `subtree'."
1173 :group 'org-cycle
1174 :type 'hook)
1176 (defgroup org-edit-structure nil
1177 "Options concerning structure editing in Org-mode."
1178 :tag "Org Edit Structure"
1179 :group 'org-structure)
1181 (defcustom org-odd-levels-only nil
1182 "Non-nil means skip even levels and only use odd levels for the outline.
1183 This has the effect that two stars are being added/taken away in
1184 promotion/demotion commands. It also influences how levels are
1185 handled by the exporters.
1186 Changing it requires restart of `font-lock-mode' to become effective
1187 for fontification also in regions already fontified.
1188 You may also set this on a per-file basis by adding one of the following
1189 lines to the buffer:
1191 #+STARTUP: odd
1192 #+STARTUP: oddeven"
1193 :group 'org-edit-structure
1194 :group 'org-appearance
1195 :type 'boolean)
1197 (defcustom org-adapt-indentation t
1198 "Non-nil means adapt indentation to outline node level.
1200 When this variable is set, Org assumes that you write outlines by
1201 indenting text in each node to align with the headline (after the stars).
1202 The following issues are influenced by this variable:
1204 - When this is set and the *entire* text in an entry is indented, the
1205 indentation is increased by one space in a demotion command, and
1206 decreased by one in a promotion command. If any line in the entry
1207 body starts with text at column 0, indentation is not changed at all.
1209 - Property drawers and planning information is inserted indented when
1210 this variable s set. When nil, they will not be indented.
1212 - TAB indents a line relative to context. The lines below a headline
1213 will be indented when this variable is set.
1215 Note that this is all about true indentation, by adding and removing
1216 space characters. See also `org-indent.el' which does level-dependent
1217 indentation in a virtual way, i.e. at display time in Emacs."
1218 :group 'org-edit-structure
1219 :type 'boolean)
1221 (defcustom org-special-ctrl-a/e nil
1222 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1224 When t, `C-a' will bring back the cursor to the beginning of the
1225 headline text, i.e. after the stars and after a possible TODO
1226 keyword. In an item, this will be the position after bullet and
1227 check-box, if any. When the cursor is already at that position,
1228 another `C-a' will bring it to the beginning of the line.
1230 `C-e' will jump to the end of the headline, ignoring the presence
1231 of tags in the headline. A second `C-e' will then jump to the
1232 true end of the line, after any tags. This also means that, when
1233 this variable is non-nil, `C-e' also will never jump beyond the
1234 end of the heading of a folded section, i.e. not after the
1235 ellipses.
1237 When set to the symbol `reversed', the first `C-a' or `C-e' works
1238 normally, going to the true line boundary first. Only a directly
1239 following, identical keypress will bring the cursor to the
1240 special positions.
1242 This may also be a cons cell where the behavior for `C-a' and
1243 `C-e' is set separately."
1244 :group 'org-edit-structure
1245 :type '(choice
1246 (const :tag "off" nil)
1247 (const :tag "on: after stars/bullet and before tags first" t)
1248 (const :tag "reversed: true line boundary first" reversed)
1249 (cons :tag "Set C-a and C-e separately"
1250 (choice :tag "Special C-a"
1251 (const :tag "off" nil)
1252 (const :tag "on: after stars/bullet first" t)
1253 (const :tag "reversed: before stars/bullet first" reversed))
1254 (choice :tag "Special C-e"
1255 (const :tag "off" nil)
1256 (const :tag "on: before tags first" t)
1257 (const :tag "reversed: after tags first" reversed)))))
1258 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1260 (defcustom org-special-ctrl-k nil
1261 "Non-nil means `C-k' will behave specially in headlines.
1262 When nil, `C-k' will call the default `kill-line' command.
1263 When t, the following will happen while the cursor is in the headline:
1265 - When the cursor is at the beginning of a headline, kill the entire
1266 line and possible the folded subtree below the line.
1267 - When in the middle of the headline text, kill the headline up to the tags.
1268 - When after the headline text, kill the tags."
1269 :group 'org-edit-structure
1270 :type 'boolean)
1272 (defcustom org-ctrl-k-protect-subtree nil
1273 "Non-nil means, do not delete a hidden subtree with C-k.
1274 When set to the symbol `error', simply throw an error when C-k is
1275 used to kill (part-of) a headline that has hidden text behind it.
1276 Any other non-nil value will result in a query to the user, if it is
1277 OK to kill that hidden subtree. When nil, kill without remorse."
1278 :group 'org-edit-structure
1279 :version "24.1"
1280 :type '(choice
1281 (const :tag "Do not protect hidden subtrees" nil)
1282 (const :tag "Protect hidden subtrees with a security query" t)
1283 (const :tag "Never kill a hidden subtree with C-k" error)))
1285 (defcustom org-special-ctrl-o t
1286 "Non-nil means, make `C-o' insert a row in tables."
1287 :group 'org-edit-structure
1288 :type 'boolean)
1290 (defcustom org-catch-invisible-edits nil
1291 "Check if in invisible region before inserting or deleting a character.
1292 Valid values are:
1294 nil Do not check, so just do invisible edits.
1295 error Throw an error and do nothing.
1296 show Make point visible, and do the requested edit.
1297 show-and-error Make point visible, then throw an error and abort the edit.
1298 smart Make point visible, and do insertion/deletion if it is
1299 adjacent to visible text and the change feels predictable.
1300 Never delete a previously invisible character or add in the
1301 middle or right after an invisible region. Basically, this
1302 allows insertion and backward-delete right before ellipses.
1303 FIXME: maybe in this case we should not even show?"
1304 :group 'org-edit-structure
1305 :version "24.1"
1306 :type '(choice
1307 (const :tag "Do not check" nil)
1308 (const :tag "Throw error when trying to edit" error)
1309 (const :tag "Unhide, but do not do the edit" show-and-error)
1310 (const :tag "Show invisible part and do the edit" show)
1311 (const :tag "Be smart and do the right thing" smart)))
1313 (defcustom org-yank-folded-subtrees t
1314 "Non-nil means when yanking subtrees, fold them.
1315 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1316 it starts with a heading and all other headings in it are either children
1317 or siblings, then fold all the subtrees. However, do this only if no
1318 text after the yank would be swallowed into a folded tree by this action."
1319 :group 'org-edit-structure
1320 :type 'boolean)
1322 (defcustom org-yank-adjusted-subtrees nil
1323 "Non-nil means when yanking subtrees, adjust the level.
1324 With this setting, `org-paste-subtree' is used to insert the subtree, see
1325 this function for details."
1326 :group 'org-edit-structure
1327 :type 'boolean)
1329 (defcustom org-M-RET-may-split-line '((default . t))
1330 "Non-nil means M-RET will split the line at the cursor position.
1331 When nil, it will go to the end of the line before making a
1332 new line.
1333 You may also set this option in a different way for different
1334 contexts. Valid contexts are:
1336 headline when creating a new headline
1337 item when creating a new item
1338 table in a table field
1339 default the value to be used for all contexts not explicitly
1340 customized"
1341 :group 'org-structure
1342 :group 'org-table
1343 :type '(choice
1344 (const :tag "Always" t)
1345 (const :tag "Never" nil)
1346 (repeat :greedy t :tag "Individual contexts"
1347 (cons
1348 (choice :tag "Context"
1349 (const headline)
1350 (const item)
1351 (const table)
1352 (const default))
1353 (boolean)))))
1356 (defcustom org-insert-heading-respect-content nil
1357 "Non-nil means insert new headings after the current subtree.
1358 When nil, the new heading is created directly after the current line.
1359 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1360 this variable on for the duration of the command."
1361 :group 'org-structure
1362 :type 'boolean)
1364 (defcustom org-blank-before-new-entry '((heading . auto)
1365 (plain-list-item . auto))
1366 "Should `org-insert-heading' leave a blank line before new heading/item?
1367 The value is an alist, with `heading' and `plain-list-item' as CAR,
1368 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1369 which case Org will look at the surrounding headings/items and try to
1370 make an intelligent decision whether to insert a blank line or not.
1372 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1373 the setting here is ignored and no empty line is inserted to avoid breaking
1374 the list structure."
1375 :group 'org-edit-structure
1376 :type '(list
1377 (cons (const heading)
1378 (choice (const :tag "Never" nil)
1379 (const :tag "Always" t)
1380 (const :tag "Auto" auto)))
1381 (cons (const plain-list-item)
1382 (choice (const :tag "Never" nil)
1383 (const :tag "Always" t)
1384 (const :tag "Auto" auto)))))
1386 (defcustom org-insert-heading-hook nil
1387 "Hook being run after inserting a new heading."
1388 :group 'org-edit-structure
1389 :type 'hook)
1391 (defcustom org-enable-fixed-width-editor t
1392 "Non-nil means lines starting with \":\" are treated as fixed-width.
1393 This currently only means they are never auto-wrapped.
1394 When nil, such lines will be treated like ordinary lines.
1395 See also the QUOTE keyword."
1396 :group 'org-edit-structure
1397 :type 'boolean)
1399 (defcustom org-goto-auto-isearch t
1400 "Non-nil means typing characters in `org-goto' starts incremental search.
1401 When nil, you can use these keybindings to navigate the buffer:
1403 q Quit the org-goto interface
1404 n Go to the next visible heading
1405 p Go to the previous visible heading
1406 f Go one heading forward on same level
1407 b Go one heading backward on same level
1408 u Go one heading up"
1409 :group 'org-edit-structure
1410 :type 'boolean)
1412 (defgroup org-sparse-trees nil
1413 "Options concerning sparse trees in Org-mode."
1414 :tag "Org Sparse Trees"
1415 :group 'org-structure)
1417 (defcustom org-highlight-sparse-tree-matches t
1418 "Non-nil means highlight all matches that define a sparse tree.
1419 The highlights will automatically disappear the next time the buffer is
1420 changed by an edit command."
1421 :group 'org-sparse-trees
1422 :type 'boolean)
1424 (defcustom org-remove-highlights-with-change t
1425 "Non-nil means any change to the buffer will remove temporary highlights.
1426 Such highlights are created by `org-occur' and `org-clock-display'.
1427 When nil, `C-c C-c needs to be used to get rid of the highlights.
1428 The highlights created by `org-preview-latex-fragment' always need
1429 `C-c C-c' to be removed."
1430 :group 'org-sparse-trees
1431 :group 'org-time
1432 :type 'boolean)
1435 (defcustom org-occur-hook '(org-first-headline-recenter)
1436 "Hook that is run after `org-occur' has constructed a sparse tree.
1437 This can be used to recenter the window to show as much of the structure
1438 as possible."
1439 :group 'org-sparse-trees
1440 :type 'hook)
1442 (defgroup org-imenu-and-speedbar nil
1443 "Options concerning imenu and speedbar in Org-mode."
1444 :tag "Org Imenu and Speedbar"
1445 :group 'org-structure)
1447 (defcustom org-imenu-depth 2
1448 "The maximum level for Imenu access to Org-mode headlines.
1449 This also applied for speedbar access."
1450 :group 'org-imenu-and-speedbar
1451 :type 'integer)
1453 (defgroup org-table nil
1454 "Options concerning tables in Org-mode."
1455 :tag "Org Table"
1456 :group 'org)
1458 (defcustom org-enable-table-editor 'optimized
1459 "Non-nil means lines starting with \"|\" are handled by the table editor.
1460 When nil, such lines will be treated like ordinary lines.
1462 When equal to the symbol `optimized', the table editor will be optimized to
1463 do the following:
1464 - Automatic overwrite mode in front of whitespace in table fields.
1465 This makes the structure of the table stay in tact as long as the edited
1466 field does not exceed the column width.
1467 - Minimize the number of realigns. Normally, the table is aligned each time
1468 TAB or RET are pressed to move to another field. With optimization this
1469 happens only if changes to a field might have changed the column width.
1470 Optimization requires replacing the functions `self-insert-command',
1471 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1472 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1473 very good at guessing when a re-align will be necessary, but you can always
1474 force one with \\[org-ctrl-c-ctrl-c].
1476 If you would like to use the optimized version in Org-mode, but the
1477 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1479 This variable can be used to turn on and off the table editor during a session,
1480 but in order to toggle optimization, a restart is required.
1482 See also the variable `org-table-auto-blank-field'."
1483 :group 'org-table
1484 :type '(choice
1485 (const :tag "off" nil)
1486 (const :tag "on" t)
1487 (const :tag "on, optimized" optimized)))
1489 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1490 (version<= emacs-version "24.1"))
1491 "Non-nil means cluster self-insert commands for undo when possible.
1492 If this is set, then, like in the Emacs command loop, 20 consecutive
1493 characters will be undone together.
1494 This is configurable, because there is some impact on typing performance."
1495 :group 'org-table
1496 :type 'boolean)
1498 (defcustom org-table-tab-recognizes-table.el t
1499 "Non-nil means TAB will automatically notice a table.el table.
1500 When it sees such a table, it moves point into it and - if necessary -
1501 calls `table-recognize-table'."
1502 :group 'org-table-editing
1503 :type 'boolean)
1505 (defgroup org-link nil
1506 "Options concerning links in Org-mode."
1507 :tag "Org Link"
1508 :group 'org)
1510 (defvar org-link-abbrev-alist-local nil
1511 "Buffer-local version of `org-link-abbrev-alist', which see.
1512 The value of this is taken from the #+LINK lines.")
1513 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1515 (defcustom org-link-abbrev-alist nil
1516 "Alist of link abbreviations.
1517 The car of each element is a string, to be replaced at the start of a link.
1518 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1519 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1521 [[linkkey:tag][description]]
1523 The 'linkkey' must be a word word, starting with a letter, followed
1524 by letters, numbers, '-' or '_'.
1526 If REPLACE is a string, the tag will simply be appended to create the link.
1527 If the string contains \"%s\", the tag will be inserted there. If the string
1528 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1529 at that point (see the function `url-hexify-string'). If the string contains
1530 the specifier \"%(my-function)\", then the custom function `my-function' will
1531 be invoked: this function takes the tag as its only argument and must return
1532 a string.
1534 REPLACE may also be a function that will be called with the tag as the
1535 only argument to create the link, which should be returned as a string.
1537 See the manual for examples."
1538 :group 'org-link
1539 :type '(repeat
1540 (cons
1541 (string :tag "Protocol")
1542 (choice
1543 (string :tag "Format")
1544 (function)))))
1546 (defcustom org-descriptive-links t
1547 "Non-nil means Org will display descriptive links.
1548 E.g. [[http://orgmode.org][Org website]] will be displayed as
1549 \"Org Website\", hiding the link itself and just displaying its
1550 description. When set to `nil', Org will display the full links
1551 literally.
1553 You can interactively set the value of this variable by calling
1554 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1555 :group 'org-link
1556 :type 'boolean)
1558 (defcustom org-link-file-path-type 'adaptive
1559 "How the path name in file links should be stored.
1560 Valid values are:
1562 relative Relative to the current directory, i.e. the directory of the file
1563 into which the link is being inserted.
1564 absolute Absolute path, if possible with ~ for home directory.
1565 noabbrev Absolute path, no abbreviation of home directory.
1566 adaptive Use relative path for files in the current directory and sub-
1567 directories of it. For other files, use an absolute path."
1568 :group 'org-link
1569 :type '(choice
1570 (const relative)
1571 (const absolute)
1572 (const noabbrev)
1573 (const adaptive)))
1575 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1576 "Types of links that should be activated in Org-mode files.
1577 This is a list of symbols, each leading to the activation of a certain link
1578 type. In principle, it does not hurt to turn on most link types - there may
1579 be a small gain when turning off unused link types. The types are:
1581 bracket The recommended [[link][description]] or [[link]] links with hiding.
1582 angle Links in angular brackets that may contain whitespace like
1583 <bbdb:Carsten Dominik>.
1584 plain Plain links in normal text, no whitespace, like http://google.com.
1585 radio Text that is matched by a radio target, see manual for details.
1586 tag Tag settings in a headline (link to tag search).
1587 date Time stamps (link to calendar).
1588 footnote Footnote labels.
1590 Changing this variable requires a restart of Emacs to become effective."
1591 :group 'org-link
1592 :type '(set :greedy t
1593 (const :tag "Double bracket links" bracket)
1594 (const :tag "Angular bracket links" angle)
1595 (const :tag "Plain text links" plain)
1596 (const :tag "Radio target matches" radio)
1597 (const :tag "Tags" tag)
1598 (const :tag "Timestamps" date)
1599 (const :tag "Footnotes" footnote)))
1601 (defcustom org-make-link-description-function nil
1602 "Function to use for generating link descriptions from links.
1603 When nil, the link location will be used. This function must take
1604 two parameters: the first one is the link, the second one is the
1605 description generated by `org-insert-link'. The function should
1606 return the description to use."
1607 :group 'org-link
1608 :type '(choice (const nil) (function)))
1610 (defgroup org-link-store nil
1611 "Options concerning storing links in Org-mode."
1612 :tag "Org Store Link"
1613 :group 'org-link)
1615 (defcustom org-url-hexify-p t
1616 "When non-nil, hexify URL when creating a link."
1617 :type 'boolean
1618 :version "24.3"
1619 :group 'org-link-store)
1621 (defcustom org-email-link-description-format "Email %c: %.30s"
1622 "Format of the description part of a link to an email or usenet message.
1623 The following %-escapes will be replaced by corresponding information:
1625 %F full \"From\" field
1626 %f name, taken from \"From\" field, address if no name
1627 %T full \"To\" field
1628 %t first name in \"To\" field, address if no name
1629 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1630 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1631 %s subject
1632 %d date
1633 %m message-id.
1635 You may use normal field width specification between the % and the letter.
1636 This is for example useful to limit the length of the subject.
1638 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1639 :group 'org-link-store
1640 :type 'string)
1642 (defcustom org-from-is-user-regexp
1643 (let (r1 r2)
1644 (when (and user-mail-address (not (string= user-mail-address "")))
1645 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1646 (when (and user-full-name (not (string= user-full-name "")))
1647 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1648 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1649 "Regexp matched against the \"From:\" header of an email or usenet message.
1650 It should match if the message is from the user him/herself."
1651 :group 'org-link-store
1652 :type 'regexp)
1654 (defcustom org-context-in-file-links t
1655 "Non-nil means file links from `org-store-link' contain context.
1656 A search string will be added to the file name with :: as separator and
1657 used to find the context when the link is activated by the command
1658 `org-open-at-point'. When this option is t, the entire active region
1659 will be placed in the search string of the file link. If set to a
1660 positive integer, only the first n lines of context will be stored.
1662 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1663 negates this setting for the duration of the command."
1664 :group 'org-link-store
1665 :type '(choice boolean integer))
1667 (defcustom org-keep-stored-link-after-insertion nil
1668 "Non-nil means keep link in list for entire session.
1670 The command `org-store-link' adds a link pointing to the current
1671 location to an internal list. These links accumulate during a session.
1672 The command `org-insert-link' can be used to insert links into any
1673 Org-mode file (offering completion for all stored links). When this
1674 option is nil, every link which has been inserted once using \\[org-insert-link]
1675 will be removed from the list, to make completing the unused links
1676 more efficient."
1677 :group 'org-link-store
1678 :type 'boolean)
1680 (defgroup org-link-follow nil
1681 "Options concerning following links in Org-mode."
1682 :tag "Org Follow Link"
1683 :group 'org-link)
1685 (defcustom org-link-translation-function nil
1686 "Function to translate links with different syntax to Org syntax.
1687 This can be used to translate links created for example by the Planner
1688 or emacs-wiki packages to Org syntax.
1689 The function must accept two parameters, a TYPE containing the link
1690 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1691 which is everything after the link protocol. It should return a cons
1692 with possibly modified values of type and path.
1693 Org contains a function for this, so if you set this variable to
1694 `org-translate-link-from-planner', you should be able follow many
1695 links created by planner."
1696 :group 'org-link-follow
1697 :type '(choice (const nil) (function)))
1699 (defcustom org-follow-link-hook nil
1700 "Hook that is run after a link has been followed."
1701 :group 'org-link-follow
1702 :type 'hook)
1704 (defcustom org-tab-follows-link nil
1705 "Non-nil means on links TAB will follow the link.
1706 Needs to be set before org.el is loaded.
1707 This really should not be used, it does not make sense, and the
1708 implementation is bad."
1709 :group 'org-link-follow
1710 :type 'boolean)
1712 (defcustom org-return-follows-link nil
1713 "Non-nil means on links RET will follow the link.
1714 In tables, the special behavior of RET has precedence."
1715 :group 'org-link-follow
1716 :type 'boolean)
1718 (defcustom org-mouse-1-follows-link
1719 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1720 "Non-nil means mouse-1 on a link will follow the link.
1721 A longer mouse click will still set point. Does not work on XEmacs.
1722 Needs to be set before org.el is loaded."
1723 :group 'org-link-follow
1724 :type 'boolean)
1726 (defcustom org-mark-ring-length 4
1727 "Number of different positions to be recorded in the ring.
1728 Changing this requires a restart of Emacs to work correctly."
1729 :group 'org-link-follow
1730 :type 'integer)
1732 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1733 "Non-nil means internal links in Org files must exactly match a headline.
1734 When nil, the link search tries to match a phrase with all words
1735 in the search text."
1736 :group 'org-link-follow
1737 :version "24.1"
1738 :type '(choice
1739 (const :tag "Use fuzzy text search" nil)
1740 (const :tag "Match only exact headline" t)
1741 (const :tag "Match exact headline or query to create it"
1742 query-to-create)))
1744 (defcustom org-link-frame-setup
1745 '((vm . vm-visit-folder-other-frame)
1746 (vm-imap . vm-visit-imap-folder-other-frame)
1747 (gnus . org-gnus-no-new-news)
1748 (file . find-file-other-window)
1749 (wl . wl-other-frame))
1750 "Setup the frame configuration for following links.
1751 When following a link with Emacs, it may often be useful to display
1752 this link in another window or frame. This variable can be used to
1753 set this up for the different types of links.
1754 For VM, use any of
1755 `vm-visit-folder'
1756 `vm-visit-folder-other-window'
1757 `vm-visit-folder-other-frame'
1758 For Gnus, use any of
1759 `gnus'
1760 `gnus-other-frame'
1761 `org-gnus-no-new-news'
1762 For FILE, use any of
1763 `find-file'
1764 `find-file-other-window'
1765 `find-file-other-frame'
1766 For Wanderlust use any of
1767 `wl'
1768 `wl-other-frame'
1769 For the calendar, use the variable `calendar-setup'.
1770 For BBDB, it is currently only possible to display the matches in
1771 another window."
1772 :group 'org-link-follow
1773 :type '(list
1774 (cons (const vm)
1775 (choice
1776 (const vm-visit-folder)
1777 (const vm-visit-folder-other-window)
1778 (const vm-visit-folder-other-frame)))
1779 (cons (const vm-imap)
1780 (choice
1781 (const vm-visit-imap-folder)
1782 (const vm-visit-imap-folder-other-window)
1783 (const vm-visit-imap-folder-other-frame)))
1784 (cons (const gnus)
1785 (choice
1786 (const gnus)
1787 (const gnus-other-frame)
1788 (const org-gnus-no-new-news)))
1789 (cons (const file)
1790 (choice
1791 (const find-file)
1792 (const find-file-other-window)
1793 (const find-file-other-frame)))
1794 (cons (const wl)
1795 (choice
1796 (const wl)
1797 (const wl-other-frame)))))
1799 (defcustom org-display-internal-link-with-indirect-buffer nil
1800 "Non-nil means use indirect buffer to display infile links.
1801 Activating internal links (from one location in a file to another location
1802 in the same file) normally just jumps to the location. When the link is
1803 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1804 is displayed in
1805 another window. When this option is set, the other window actually displays
1806 an indirect buffer clone of the current buffer, to avoid any visibility
1807 changes to the current buffer."
1808 :group 'org-link-follow
1809 :type 'boolean)
1811 (defcustom org-open-non-existing-files nil
1812 "Non-nil means `org-open-file' will open non-existing files.
1813 When nil, an error will be generated.
1814 This variable applies only to external applications because they
1815 might choke on non-existing files. If the link is to a file that
1816 will be opened in Emacs, the variable is ignored."
1817 :group 'org-link-follow
1818 :type 'boolean)
1820 (defcustom org-open-directory-means-index-dot-org nil
1821 "Non-nil means a link to a directory really means to index.org.
1822 When nil, following a directory link will run dired or open a finder/explorer
1823 window on that directory."
1824 :group 'org-link-follow
1825 :type 'boolean)
1827 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1828 "Function and arguments to call for following mailto links.
1829 This is a list with the first element being a Lisp function, and the
1830 remaining elements being arguments to the function. In string arguments,
1831 %a will be replaced by the address, and %s will be replaced by the subject
1832 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1833 :group 'org-link-follow
1834 :type '(choice
1835 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1836 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1837 (const :tag "message-mail" (message-mail "%a" "%s"))
1838 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1840 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1841 "Non-nil means ask for confirmation before executing shell links.
1842 Shell links can be dangerous: just think about a link
1844 [[shell:rm -rf ~/*][Google Search]]
1846 This link would show up in your Org-mode document as \"Google Search\",
1847 but really it would remove your entire home directory.
1848 Therefore we advise against setting this variable to nil.
1849 Just change it to `y-or-n-p' if you want to confirm with a
1850 single keystroke rather than having to type \"yes\"."
1851 :group 'org-link-follow
1852 :type '(choice
1853 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1854 (const :tag "with y-or-n (faster)" y-or-n-p)
1855 (const :tag "no confirmation (dangerous)" nil)))
1856 (put 'org-confirm-shell-link-function
1857 'safe-local-variable
1858 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1860 (defcustom org-confirm-shell-link-not-regexp ""
1861 "A regexp to skip confirmation for shell links."
1862 :group 'org-link-follow
1863 :version "24.1"
1864 :type 'regexp)
1866 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1867 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1868 Elisp links can be dangerous: just think about a link
1870 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1872 This link would show up in your Org-mode document as \"Google Search\",
1873 but really it would remove your entire home directory.
1874 Therefore we advise against setting this variable to nil.
1875 Just change it to `y-or-n-p' if you want to confirm with a
1876 single keystroke rather than having to type \"yes\"."
1877 :group 'org-link-follow
1878 :type '(choice
1879 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1880 (const :tag "with y-or-n (faster)" y-or-n-p)
1881 (const :tag "no confirmation (dangerous)" nil)))
1882 (put 'org-confirm-shell-link-function
1883 'safe-local-variable
1884 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1886 (defcustom org-confirm-elisp-link-not-regexp ""
1887 "A regexp to skip confirmation for Elisp links."
1888 :group 'org-link-follow
1889 :version "24.1"
1890 :type 'regexp)
1892 (defconst org-file-apps-defaults-gnu
1893 '((remote . emacs)
1894 (system . mailcap)
1895 (t . mailcap))
1896 "Default file applications on a UNIX or GNU/Linux system.
1897 See `org-file-apps'.")
1899 (defconst org-file-apps-defaults-macosx
1900 '((remote . emacs)
1901 (t . "open %s")
1902 (system . "open %s")
1903 ("ps.gz" . "gv %s")
1904 ("eps.gz" . "gv %s")
1905 ("dvi" . "xdvi %s")
1906 ("fig" . "xfig %s"))
1907 "Default file applications on a MacOS X system.
1908 The system \"open\" is known as a default, but we use X11 applications
1909 for some files for which the OS does not have a good default.
1910 See `org-file-apps'.")
1912 (defconst org-file-apps-defaults-windowsnt
1913 (list
1914 '(remote . emacs)
1915 (cons t
1916 (list (if (featurep 'xemacs)
1917 'mswindows-shell-execute
1918 'w32-shell-execute)
1919 "open" 'file))
1920 (cons 'system
1921 (list (if (featurep 'xemacs)
1922 'mswindows-shell-execute
1923 'w32-shell-execute)
1924 "open" 'file)))
1925 "Default file applications on a Windows NT system.
1926 The system \"open\" is used for most files.
1927 See `org-file-apps'.")
1929 (defcustom org-file-apps
1930 '((auto-mode . emacs)
1931 ("\\.mm\\'" . default)
1932 ("\\.x?html?\\'" . default)
1933 ("\\.pdf\\'" . default))
1934 "External applications for opening `file:path' items in a document.
1935 Org-mode uses system defaults for different file types, but
1936 you can use this variable to set the application for a given file
1937 extension. The entries in this list are cons cells where the car identifies
1938 files and the cdr the corresponding command. Possible values for the
1939 file identifier are
1940 \"string\" A string as a file identifier can be interpreted in different
1941 ways, depending on its contents:
1943 - Alphanumeric characters only:
1944 Match links with this file extension.
1945 Example: (\"pdf\" . \"evince %s\")
1946 to open PDFs with evince.
1948 - Regular expression: Match links where the
1949 filename matches the regexp. If you want to
1950 use groups here, use shy groups.
1952 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1953 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1954 to open *.html and *.xhtml with firefox.
1956 - Regular expression which contains (non-shy) groups:
1957 Match links where the whole link, including \"::\", and
1958 anything after that, matches the regexp.
1959 In a custom command string, %1, %2, etc. are replaced with
1960 the parts of the link that were matched by the groups.
1961 For backwards compatibility, if a command string is given
1962 that does not use any of the group matches, this case is
1963 handled identically to the second one (i.e. match against
1964 file name only).
1965 In a custom lisp form, you can access the group matches with
1966 (match-string n link).
1968 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1969 to open [[file:document.pdf::5]] with evince at page 5.
1971 `directory' Matches a directory
1972 `remote' Matches a remote file, accessible through tramp or efs.
1973 Remote files most likely should be visited through Emacs
1974 because external applications cannot handle such paths.
1975 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1976 so all files Emacs knows how to handle. Using this with
1977 command `emacs' will open most files in Emacs. Beware that this
1978 will also open html files inside Emacs, unless you add
1979 (\"html\" . default) to the list as well.
1980 t Default for files not matched by any of the other options.
1981 `system' The system command to open files, like `open' on Windows
1982 and Mac OS X, and mailcap under GNU/Linux. This is the command
1983 that will be selected if you call `C-c C-o' with a double
1984 \\[universal-argument] \\[universal-argument] prefix.
1986 Possible values for the command are:
1987 `emacs' The file will be visited by the current Emacs process.
1988 `default' Use the default application for this file type, which is the
1989 association for t in the list, most likely in the system-specific
1990 part.
1991 This can be used to overrule an unwanted setting in the
1992 system-specific variable.
1993 `system' Use the system command for opening files, like \"open\".
1994 This command is specified by the entry whose car is `system'.
1995 Most likely, the system-specific version of this variable
1996 does define this command, but you can overrule/replace it
1997 here.
1998 string A command to be executed by a shell; %s will be replaced
1999 by the path to the file.
2000 sexp A Lisp form which will be evaluated. The file path will
2001 be available in the Lisp variable `file'.
2002 For more examples, see the system specific constants
2003 `org-file-apps-defaults-macosx'
2004 `org-file-apps-defaults-windowsnt'
2005 `org-file-apps-defaults-gnu'."
2006 :group 'org-link-follow
2007 :type '(repeat
2008 (cons (choice :value ""
2009 (string :tag "Extension")
2010 (const :tag "System command to open files" system)
2011 (const :tag "Default for unrecognized files" t)
2012 (const :tag "Remote file" remote)
2013 (const :tag "Links to a directory" directory)
2014 (const :tag "Any files that have Emacs modes"
2015 auto-mode))
2016 (choice :value ""
2017 (const :tag "Visit with Emacs" emacs)
2018 (const :tag "Use default" default)
2019 (const :tag "Use the system command" system)
2020 (string :tag "Command")
2021 (sexp :tag "Lisp form")))))
2023 (defcustom org-doi-server-url "http://dx.doi.org/"
2024 "The URL of the DOI server."
2025 :type 'string
2026 :version "24.3"
2027 :group 'org-link-follow)
2029 (defgroup org-refile nil
2030 "Options concerning refiling entries in Org-mode."
2031 :tag "Org Refile"
2032 :group 'org)
2034 (defcustom org-directory "~/org"
2035 "Directory with org files.
2036 This is just a default location to look for Org files. There is no need
2037 at all to put your files into this directory. It is only used in the
2038 following situations:
2040 1. When a capture template specifies a target file that is not an
2041 absolute path. The path will then be interpreted relative to
2042 `org-directory'
2043 2. When a capture note is filed away in an interactive way (when exiting the
2044 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2045 with `org-directory' as the default path."
2046 :group 'org-refile
2047 :group 'org-remember
2048 :group 'org-capture
2049 :type 'directory)
2051 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2052 "Default target for storing notes.
2053 Used as a fall back file for org-remember.el and org-capture.el, for
2054 templates that do not specify a target file."
2055 :group 'org-refile
2056 :group 'org-remember
2057 :group 'org-capture
2058 :type '(choice
2059 (const :tag "Default from remember-data-file" nil)
2060 file))
2062 (defcustom org-goto-interface 'outline
2063 "The default interface to be used for `org-goto'.
2064 Allowed values are:
2065 outline The interface shows an outline of the relevant file
2066 and the correct heading is found by moving through
2067 the outline or by searching with incremental search.
2068 outline-path-completion Headlines in the current buffer are offered via
2069 completion. This is the interface also used by
2070 the refile command."
2071 :group 'org-refile
2072 :type '(choice
2073 (const :tag "Outline" outline)
2074 (const :tag "Outline-path-completion" outline-path-completion)))
2076 (defcustom org-goto-max-level 5
2077 "Maximum target level when running `org-goto' with refile interface."
2078 :group 'org-refile
2079 :type 'integer)
2081 (defcustom org-reverse-note-order nil
2082 "Non-nil means store new notes at the beginning of a file or entry.
2083 When nil, new notes will be filed to the end of a file or entry.
2084 This can also be a list with cons cells of regular expressions that
2085 are matched against file names, and values."
2086 :group 'org-remember
2087 :group 'org-capture
2088 :group 'org-refile
2089 :type '(choice
2090 (const :tag "Reverse always" t)
2091 (const :tag "Reverse never" nil)
2092 (repeat :tag "By file name regexp"
2093 (cons regexp boolean))))
2095 (defcustom org-log-refile nil
2096 "Information to record when a task is refiled.
2098 Possible values are:
2100 nil Don't add anything
2101 time Add a time stamp to the task
2102 note Prompt for a note and add it with template `org-log-note-headings'
2104 This option can also be set with on a per-file-basis with
2106 #+STARTUP: nologrefile
2107 #+STARTUP: logrefile
2108 #+STARTUP: lognoterefile
2110 You can have local logging settings for a subtree by setting the LOGGING
2111 property to one or more of these keywords.
2113 When bulk-refiling from the agenda, the value `note' is forbidden and
2114 will temporarily be changed to `time'."
2115 :group 'org-refile
2116 :group 'org-progress
2117 :version "24.1"
2118 :type '(choice
2119 (const :tag "No logging" nil)
2120 (const :tag "Record timestamp" time)
2121 (const :tag "Record timestamp with note." note)))
2123 (defcustom org-refile-targets nil
2124 "Targets for refiling entries with \\[org-refile].
2125 This is a list of cons cells. Each cell contains:
2126 - a specification of the files to be considered, either a list of files,
2127 or a symbol whose function or variable value will be used to retrieve
2128 a file name or a list of file names. If you use `org-agenda-files' for
2129 that, all agenda files will be scanned for targets. Nil means consider
2130 headings in the current buffer.
2131 - A specification of how to find candidate refile targets. This may be
2132 any of:
2133 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2134 This tag has to be present in all target headlines, inheritance will
2135 not be considered.
2136 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2137 todo keyword.
2138 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2139 headlines that are refiling targets.
2140 - a cons cell (:level . N). Any headline of level N is considered a target.
2141 Note that, when `org-odd-levels-only' is set, level corresponds to
2142 order in hierarchy, not to the number of stars.
2143 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2144 Note that, when `org-odd-levels-only' is set, level corresponds to
2145 order in hierarchy, not to the number of stars.
2147 Each element of this list generates a set of possible targets.
2148 The union of these sets is presented (with completion) to
2149 the user by `org-refile'.
2151 You can set the variable `org-refile-target-verify-function' to a function
2152 to verify each headline found by the simple criteria above.
2154 When this variable is nil, all top-level headlines in the current buffer
2155 are used, equivalent to the value `((nil . (:level . 1))'."
2156 :group 'org-refile
2157 :type '(repeat
2158 (cons
2159 (choice :value org-agenda-files
2160 (const :tag "All agenda files" org-agenda-files)
2161 (const :tag "Current buffer" nil)
2162 (function) (variable) (file))
2163 (choice :tag "Identify target headline by"
2164 (cons :tag "Specific tag" (const :value :tag) (string))
2165 (cons :tag "TODO keyword" (const :value :todo) (string))
2166 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2167 (cons :tag "Level number" (const :value :level) (integer))
2168 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2170 (defcustom org-refile-target-verify-function nil
2171 "Function to verify if the headline at point should be a refile target.
2172 The function will be called without arguments, with point at the
2173 beginning of the headline. It should return t and leave point
2174 where it is if the headline is a valid target for refiling.
2176 If the target should not be selected, the function must return nil.
2177 In addition to this, it may move point to a place from where the search
2178 should be continued. For example, the function may decide that the entire
2179 subtree of the current entry should be excluded and move point to the end
2180 of the subtree."
2181 :group 'org-refile
2182 :type '(choice
2183 (const nil)
2184 (function)))
2186 (defcustom org-refile-use-cache nil
2187 "Non-nil means cache refile targets to speed up the process.
2188 The cache for a particular file will be updated automatically when
2189 the buffer has been killed, or when any of the marker used for flagging
2190 refile targets no longer points at a live buffer.
2191 If you have added new entries to a buffer that might themselves be targets,
2192 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2193 find that easier, `C-u C-u C-u C-c C-w'."
2194 :group 'org-refile
2195 :version "24.1"
2196 :type 'boolean)
2198 (defcustom org-refile-use-outline-path nil
2199 "Non-nil means provide refile targets as paths.
2200 So a level 3 headline will be available as level1/level2/level3.
2202 When the value is `file', also include the file name (without directory)
2203 into the path. In this case, you can also stop the completion after
2204 the file name, to get entries inserted as top level in the file.
2206 When `full-file-path', include the full file path."
2207 :group 'org-refile
2208 :type '(choice
2209 (const :tag "Not" nil)
2210 (const :tag "Yes" t)
2211 (const :tag "Start with file name" file)
2212 (const :tag "Start with full file path" full-file-path)))
2214 (defcustom org-outline-path-complete-in-steps t
2215 "Non-nil means complete the outline path in hierarchical steps.
2216 When Org-mode uses the refile interface to select an outline path
2217 \(see variable `org-refile-use-outline-path'), the completion of
2218 the path can be done is a single go, or if can be done in steps down
2219 the headline hierarchy. Going in steps is probably the best if you
2220 do not use a special completion package like `ido' or `icicles'.
2221 However, when using these packages, going in one step can be very
2222 fast, while still showing the whole path to the entry."
2223 :group 'org-refile
2224 :type 'boolean)
2226 (defcustom org-refile-allow-creating-parent-nodes nil
2227 "Non-nil means allow to create new nodes as refile targets.
2228 New nodes are then created by adding \"/new node name\" to the completion
2229 of an existing node. When the value of this variable is `confirm',
2230 new node creation must be confirmed by the user (recommended)
2231 When nil, the completion must match an existing entry.
2233 Note that, if the new heading is not seen by the criteria
2234 listed in `org-refile-targets', multiple instances of the same
2235 heading would be created by trying again to file under the new
2236 heading."
2237 :group 'org-refile
2238 :type '(choice
2239 (const :tag "Never" nil)
2240 (const :tag "Always" t)
2241 (const :tag "Prompt for confirmation" confirm)))
2243 (defcustom org-refile-active-region-within-subtree nil
2244 "Non-nil means also refile active region within a subtree.
2246 By default `org-refile' doesn't allow refiling regions if they
2247 don't contain a set of subtrees, but it might be convenient to
2248 do so sometimes: in that case, the first line of the region is
2249 converted to a headline before refiling."
2250 :group 'org-refile
2251 :version "24.1"
2252 :type 'boolean)
2254 (defgroup org-todo nil
2255 "Options concerning TODO items in Org-mode."
2256 :tag "Org TODO"
2257 :group 'org)
2259 (defgroup org-progress nil
2260 "Options concerning Progress logging in Org-mode."
2261 :tag "Org Progress"
2262 :group 'org-time)
2264 (defvar org-todo-interpretation-widgets
2265 '((:tag "Sequence (cycling hits every state)" sequence)
2266 (:tag "Type (cycling directly to DONE)" type))
2267 "The available interpretation symbols for customizing `org-todo-keywords'.
2268 Interested libraries should add to this list.")
2270 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2271 "List of TODO entry keyword sequences and their interpretation.
2272 \\<org-mode-map>This is a list of sequences.
2274 Each sequence starts with a symbol, either `sequence' or `type',
2275 indicating if the keywords should be interpreted as a sequence of
2276 action steps, or as different types of TODO items. The first
2277 keywords are states requiring action - these states will select a headline
2278 for inclusion into the global TODO list Org-mode produces. If one of
2279 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2280 signify that no further action is necessary. If \"|\" is not found,
2281 the last keyword is treated as the only DONE state of the sequence.
2283 The command \\[org-todo] cycles an entry through these states, and one
2284 additional state where no keyword is present. For details about this
2285 cycling, see the manual.
2287 TODO keywords and interpretation can also be set on a per-file basis with
2288 the special #+SEQ_TODO and #+TYP_TODO lines.
2290 Each keyword can optionally specify a character for fast state selection
2291 \(in combination with the variable `org-use-fast-todo-selection')
2292 and specifiers for state change logging, using the same syntax that
2293 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2294 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2295 indicates to record a time stamp each time this state is selected.
2297 Each keyword may also specify if a timestamp or a note should be
2298 recorded when entering or leaving the state, by adding additional
2299 characters in the parenthesis after the keyword. This looks like this:
2300 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2301 record only the time of the state change. With X and Y being either
2302 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2303 Y when leaving the state if and only if the *target* state does not
2304 define X. You may omit any of the fast-selection key or X or /Y,
2305 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2307 For backward compatibility, this variable may also be just a list
2308 of keywords. In this case the interpretation (sequence or type) will be
2309 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2310 :group 'org-todo
2311 :group 'org-keywords
2312 :type '(choice
2313 (repeat :tag "Old syntax, just keywords"
2314 (string :tag "Keyword"))
2315 (repeat :tag "New syntax"
2316 (cons
2317 (choice
2318 :tag "Interpretation"
2319 ;;Quick and dirty way to see
2320 ;;`org-todo-interpretations'. This takes the
2321 ;;place of item arguments
2322 :convert-widget
2323 (lambda (widget)
2324 (widget-put widget
2325 :args (mapcar
2326 #'(lambda (x)
2327 (widget-convert
2328 (cons 'const x)))
2329 org-todo-interpretation-widgets))
2330 widget))
2331 (repeat
2332 (string :tag "Keyword"))))))
2334 (defvar org-todo-keywords-1 nil
2335 "All TODO and DONE keywords active in a buffer.")
2336 (make-variable-buffer-local 'org-todo-keywords-1)
2337 (defvar org-todo-keywords-for-agenda nil)
2338 (defvar org-done-keywords-for-agenda nil)
2339 (defvar org-todo-keyword-alist-for-agenda nil)
2340 (defvar org-tag-alist-for-agenda nil
2341 "Alist of all tags from all agenda files.")
2342 (defvar org-tag-groups-alist-for-agenda nil
2343 "Alist of all groups tags from all current agenda files.")
2344 (defvar org-tag-groups-alist nil)
2345 (make-variable-buffer-local 'org-tag-groups-alist)
2346 (defvar org-agenda-contributing-files nil)
2347 (defvar org-not-done-keywords nil)
2348 (make-variable-buffer-local 'org-not-done-keywords)
2349 (defvar org-done-keywords nil)
2350 (make-variable-buffer-local 'org-done-keywords)
2351 (defvar org-todo-heads nil)
2352 (make-variable-buffer-local 'org-todo-heads)
2353 (defvar org-todo-sets nil)
2354 (make-variable-buffer-local 'org-todo-sets)
2355 (defvar org-todo-log-states nil)
2356 (make-variable-buffer-local 'org-todo-log-states)
2357 (defvar org-todo-kwd-alist nil)
2358 (make-variable-buffer-local 'org-todo-kwd-alist)
2359 (defvar org-todo-key-alist nil)
2360 (make-variable-buffer-local 'org-todo-key-alist)
2361 (defvar org-todo-key-trigger nil)
2362 (make-variable-buffer-local 'org-todo-key-trigger)
2364 (defcustom org-todo-interpretation 'sequence
2365 "Controls how TODO keywords are interpreted.
2366 This variable is in principle obsolete and is only used for
2367 backward compatibility, if the interpretation of todo keywords is
2368 not given already in `org-todo-keywords'. See that variable for
2369 more information."
2370 :group 'org-todo
2371 :group 'org-keywords
2372 :type '(choice (const sequence)
2373 (const type)))
2375 (defcustom org-use-fast-todo-selection t
2376 "Non-nil means use the fast todo selection scheme with C-c C-t.
2377 This variable describes if and under what circumstances the cycling
2378 mechanism for TODO keywords will be replaced by a single-key, direct
2379 selection scheme.
2381 When nil, fast selection is never used.
2383 When the symbol `prefix', it will be used when `org-todo' is called
2384 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2385 `C-u t' in an agenda buffer.
2387 When t, fast selection is used by default. In this case, the prefix
2388 argument forces cycling instead.
2390 In all cases, the special interface is only used if access keys have
2391 actually been assigned by the user, i.e. if keywords in the configuration
2392 are followed by a letter in parenthesis, like TODO(t)."
2393 :group 'org-todo
2394 :type '(choice
2395 (const :tag "Never" nil)
2396 (const :tag "By default" t)
2397 (const :tag "Only with C-u C-c C-t" prefix)))
2399 (defcustom org-provide-todo-statistics t
2400 "Non-nil means update todo statistics after insert and toggle.
2401 ALL-HEADLINES means update todo statistics by including headlines
2402 with no TODO keyword as well, counting them as not done.
2403 A list of TODO keywords means the same, but skip keywords that are
2404 not in this list.
2406 When this is set, todo statistics is updated in the parent of the
2407 current entry each time a todo state is changed."
2408 :group 'org-todo
2409 :type '(choice
2410 (const :tag "Yes, only for TODO entries" t)
2411 (const :tag "Yes, including all entries" 'all-headlines)
2412 (repeat :tag "Yes, for TODOs in this list"
2413 (string :tag "TODO keyword"))
2414 (other :tag "No TODO statistics" nil)))
2416 (defcustom org-hierarchical-todo-statistics t
2417 "Non-nil means TODO statistics covers just direct children.
2418 When nil, all entries in the subtree are considered.
2419 This has only an effect if `org-provide-todo-statistics' is set.
2420 To set this to nil for only a single subtree, use a COOKIE_DATA
2421 property and include the word \"recursive\" into the value."
2422 :group 'org-todo
2423 :type 'boolean)
2425 (defcustom org-after-todo-state-change-hook nil
2426 "Hook which is run after the state of a TODO item was changed.
2427 The new state (a string with a TODO keyword, or nil) is available in the
2428 Lisp variable `org-state'."
2429 :group 'org-todo
2430 :type 'hook)
2432 (defvar org-blocker-hook nil
2433 "Hook for functions that are allowed to block a state change.
2435 Functions in this hook should not modify the buffer.
2436 Each function gets as its single argument a property list,
2437 see `org-trigger-hook' for more information about this list.
2439 If any of the functions in this hook returns nil, the state change
2440 is blocked.")
2442 (defvar org-trigger-hook nil
2443 "Hook for functions that are triggered by a state change.
2445 Each function gets as its single argument a property list with at
2446 least the following elements:
2448 (:type type-of-change :position pos-at-entry-start
2449 :from old-state :to new-state)
2451 Depending on the type, more properties may be present.
2453 This mechanism is currently implemented for:
2455 TODO state changes
2456 ------------------
2457 :type todo-state-change
2458 :from previous state (keyword as a string), or nil, or a symbol
2459 'todo' or 'done', to indicate the general type of state.
2460 :to new state, like in :from")
2462 (defcustom org-enforce-todo-dependencies nil
2463 "Non-nil means undone TODO entries will block switching the parent to DONE.
2464 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2465 be blocked if any prior sibling is not yet done.
2466 Finally, if the parent is blocked because of ordered siblings of its own,
2467 the child will also be blocked."
2468 :set (lambda (var val)
2469 (set var val)
2470 (if val
2471 (add-hook 'org-blocker-hook
2472 'org-block-todo-from-children-or-siblings-or-parent)
2473 (remove-hook 'org-blocker-hook
2474 'org-block-todo-from-children-or-siblings-or-parent)))
2475 :group 'org-todo
2476 :type 'boolean)
2478 (defcustom org-enforce-todo-checkbox-dependencies nil
2479 "Non-nil means unchecked boxes will block switching the parent to DONE.
2480 When this is nil, checkboxes have no influence on switching TODO states.
2481 When non-nil, you first need to check off all check boxes before the TODO
2482 entry can be switched to DONE.
2483 This variable needs to be set before org.el is loaded, and you need to
2484 restart Emacs after a change to make the change effective. The only way
2485 to change is while Emacs is running is through the customize interface."
2486 :set (lambda (var val)
2487 (set var val)
2488 (if val
2489 (add-hook 'org-blocker-hook
2490 'org-block-todo-from-checkboxes)
2491 (remove-hook 'org-blocker-hook
2492 'org-block-todo-from-checkboxes)))
2493 :group 'org-todo
2494 :type 'boolean)
2496 (defcustom org-treat-insert-todo-heading-as-state-change nil
2497 "Non-nil means inserting a TODO heading is treated as state change.
2498 So when the command \\[org-insert-todo-heading] is used, state change
2499 logging will apply if appropriate. When nil, the new TODO item will
2500 be inserted directly, and no logging will take place."
2501 :group 'org-todo
2502 :type 'boolean)
2504 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2505 "Non-nil means switching TODO states with S-cursor counts as state change.
2506 This is the default behavior. However, setting this to nil allows a
2507 convenient way to select a TODO state and bypass any logging associated
2508 with that."
2509 :group 'org-todo
2510 :type 'boolean)
2512 (defcustom org-todo-state-tags-triggers nil
2513 "Tag changes that should be triggered by TODO state changes.
2514 This is a list. Each entry is
2516 (state-change (tag . flag) .......)
2518 State-change can be a string with a state, and empty string to indicate the
2519 state that has no TODO keyword, or it can be one of the symbols `todo'
2520 or `done', meaning any not-done or done state, respectively."
2521 :group 'org-todo
2522 :group 'org-tags
2523 :type '(repeat
2524 (cons (choice :tag "When changing to"
2525 (const :tag "Not-done state" todo)
2526 (const :tag "Done state" done)
2527 (string :tag "State"))
2528 (repeat
2529 (cons :tag "Tag action"
2530 (string :tag "Tag")
2531 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2533 (defcustom org-log-done nil
2534 "Information to record when a task moves to the DONE state.
2536 Possible values are:
2538 nil Don't add anything, just change the keyword
2539 time Add a time stamp to the task
2540 note Prompt for a note and add it with template `org-log-note-headings'
2542 This option can also be set with on a per-file-basis with
2544 #+STARTUP: nologdone
2545 #+STARTUP: logdone
2546 #+STARTUP: lognotedone
2548 You can have local logging settings for a subtree by setting the LOGGING
2549 property to one or more of these keywords."
2550 :group 'org-todo
2551 :group 'org-progress
2552 :type '(choice
2553 (const :tag "No logging" nil)
2554 (const :tag "Record CLOSED timestamp" time)
2555 (const :tag "Record CLOSED timestamp with note." note)))
2557 ;; Normalize old uses of org-log-done.
2558 (cond
2559 ((eq org-log-done t) (setq org-log-done 'time))
2560 ((and (listp org-log-done) (memq 'done org-log-done))
2561 (setq org-log-done 'note)))
2563 (defcustom org-log-reschedule nil
2564 "Information to record when the scheduling date of a tasks is modified.
2566 Possible values are:
2568 nil Don't add anything, just change the date
2569 time Add a time stamp to the task
2570 note Prompt for a note and add it with template `org-log-note-headings'
2572 This option can also be set with on a per-file-basis with
2574 #+STARTUP: nologreschedule
2575 #+STARTUP: logreschedule
2576 #+STARTUP: lognotereschedule"
2577 :group 'org-todo
2578 :group 'org-progress
2579 :type '(choice
2580 (const :tag "No logging" nil)
2581 (const :tag "Record timestamp" time)
2582 (const :tag "Record timestamp with note." note)))
2584 (defcustom org-log-redeadline nil
2585 "Information to record when the deadline 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: nologredeadline
2596 #+STARTUP: logredeadline
2597 #+STARTUP: lognoteredeadline
2599 You can have local logging settings for a subtree by setting the LOGGING
2600 property to one or more of these keywords."
2601 :group 'org-todo
2602 :group 'org-progress
2603 :type '(choice
2604 (const :tag "No logging" nil)
2605 (const :tag "Record timestamp" time)
2606 (const :tag "Record timestamp with note." note)))
2608 (defcustom org-log-note-clock-out nil
2609 "Non-nil means record a note when clocking out of an item.
2610 This can also be configured on a per-file basis by adding one of
2611 the following lines anywhere in the buffer:
2613 #+STARTUP: lognoteclock-out
2614 #+STARTUP: nolognoteclock-out"
2615 :group 'org-todo
2616 :group 'org-progress
2617 :type 'boolean)
2619 (defcustom org-log-done-with-time t
2620 "Non-nil means the CLOSED time stamp will contain date and time.
2621 When nil, only the date will be recorded."
2622 :group 'org-progress
2623 :type 'boolean)
2625 (defcustom org-log-note-headings
2626 '((done . "CLOSING NOTE %t")
2627 (state . "State %-12s from %-12S %t")
2628 (note . "Note taken on %t")
2629 (reschedule . "Rescheduled from %S on %t")
2630 (delschedule . "Not scheduled, was %S on %t")
2631 (redeadline . "New deadline from %S on %t")
2632 (deldeadline . "Removed deadline, was %S on %t")
2633 (refile . "Refiled on %t")
2634 (clock-out . ""))
2635 "Headings for notes added to entries.
2636 The value is an alist, with the car being a symbol indicating the note
2637 context, and the cdr is the heading to be used. The heading may also be the
2638 empty string.
2639 %t in the heading will be replaced by a time stamp.
2640 %T will be an active time stamp instead the default inactive one
2641 %d will be replaced by a short-format time stamp.
2642 %D will be replaced by an active short-format time stamp.
2643 %s will be replaced by the new TODO state, in double quotes.
2644 %S will be replaced by the old TODO state, in double quotes.
2645 %u will be replaced by the user name.
2646 %U will be replaced by the full user name.
2648 In fact, it is not a good idea to change the `state' entry, because
2649 agenda log mode depends on the format of these entries."
2650 :group 'org-todo
2651 :group 'org-progress
2652 :type '(list :greedy t
2653 (cons (const :tag "Heading when closing an item" done) string)
2654 (cons (const :tag
2655 "Heading when changing todo state (todo sequence only)"
2656 state) string)
2657 (cons (const :tag "Heading when just taking a note" note) string)
2658 (cons (const :tag "Heading when clocking out" clock-out) string)
2659 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2660 (cons (const :tag "Heading when rescheduling" reschedule) string)
2661 (cons (const :tag "Heading when changing deadline" redeadline) string)
2662 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2663 (cons (const :tag "Heading when refiling" refile) string)))
2665 (unless (assq 'note org-log-note-headings)
2666 (push '(note . "%t") org-log-note-headings))
2668 (defcustom org-log-into-drawer nil
2669 "Non-nil means insert state change notes and time stamps into a drawer.
2670 When nil, state changes notes will be inserted after the headline and
2671 any scheduling and clock lines, but not inside a drawer.
2673 The value of this variable should be the name of the drawer to use.
2674 LOGBOOK is proposed as the default drawer for this purpose, you can
2675 also set this to a string to define the drawer of your choice.
2677 A value of t is also allowed, representing \"LOGBOOK\".
2679 A value of t or nil can also be set with on a per-file-basis with
2681 #+STARTUP: logdrawer
2682 #+STARTUP: nologdrawer
2684 If this variable is set, `org-log-state-notes-insert-after-drawers'
2685 will be ignored.
2687 You can set the property LOG_INTO_DRAWER to overrule this setting for
2688 a subtree."
2689 :group 'org-todo
2690 :group 'org-progress
2691 :type '(choice
2692 (const :tag "Not into a drawer" nil)
2693 (const :tag "LOGBOOK" t)
2694 (string :tag "Other")))
2696 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2698 (defun org-log-into-drawer ()
2699 "Return the value of `org-log-into-drawer', but let properties overrule.
2700 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2701 used instead of the default value."
2702 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2703 (cond
2704 ((not p) org-log-into-drawer)
2705 ((equal p "nil") nil)
2706 ((equal p "t") "LOGBOOK")
2707 (t p))))
2709 (defcustom org-log-state-notes-insert-after-drawers nil
2710 "Non-nil means insert state change notes after any drawers in entry.
2711 Only the drawers that *immediately* follow the headline and the
2712 deadline/scheduled line are skipped.
2713 When nil, insert notes right after the heading and perhaps the line
2714 with deadline/scheduling if present.
2716 This variable will have no effect if `org-log-into-drawer' is
2717 set."
2718 :group 'org-todo
2719 :group 'org-progress
2720 :type 'boolean)
2722 (defcustom org-log-states-order-reversed t
2723 "Non-nil means the latest state note will be directly after heading.
2724 When nil, the state change notes will be ordered according to time.
2726 This option can also be set with on a per-file-basis with
2728 #+STARTUP: logstatesreversed
2729 #+STARTUP: nologstatesreversed"
2730 :group 'org-todo
2731 :group 'org-progress
2732 :type 'boolean)
2734 (defcustom org-todo-repeat-to-state nil
2735 "The TODO state to which a repeater should return the repeating task.
2736 By default this is the first task in a TODO sequence, or the previous state
2737 in a TODO_TYP set. But you can specify another task here.
2738 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2739 :group 'org-todo
2740 :version "24.1"
2741 :type '(choice (const :tag "Head of sequence" nil)
2742 (string :tag "Specific state")))
2744 (defcustom org-log-repeat 'time
2745 "Non-nil means record moving through the DONE state when triggering repeat.
2746 An auto-repeating task is immediately switched back to TODO when
2747 marked DONE. If you are not logging state changes (by adding \"@\"
2748 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2749 record a closing note, there will be no record of the task moving
2750 through DONE. This variable forces taking a note anyway.
2752 nil Don't force a record
2753 time Record a time stamp
2754 note Prompt for a note and add it with template `org-log-note-headings'
2756 This option can also be set with on a per-file-basis with
2758 #+STARTUP: nologrepeat
2759 #+STARTUP: logrepeat
2760 #+STARTUP: lognoterepeat
2762 You can have local logging settings for a subtree by setting the LOGGING
2763 property to one or more of these keywords."
2764 :group 'org-todo
2765 :group 'org-progress
2766 :type '(choice
2767 (const :tag "Don't force a record" nil)
2768 (const :tag "Force recording the DONE state" time)
2769 (const :tag "Force recording a note with the DONE state" note)))
2772 (defgroup org-priorities nil
2773 "Priorities in Org-mode."
2774 :tag "Org Priorities"
2775 :group 'org-todo)
2777 (defcustom org-enable-priority-commands t
2778 "Non-nil means priority commands are active.
2779 When nil, these commands will be disabled, so that you never accidentally
2780 set a priority."
2781 :group 'org-priorities
2782 :type 'boolean)
2784 (defcustom org-highest-priority ?A
2785 "The highest priority of TODO items. A character like ?A, ?B etc.
2786 Must have a smaller ASCII number than `org-lowest-priority'."
2787 :group 'org-priorities
2788 :type 'character)
2790 (defcustom org-lowest-priority ?C
2791 "The lowest priority of TODO items. A character like ?A, ?B etc.
2792 Must have a larger ASCII number than `org-highest-priority'."
2793 :group 'org-priorities
2794 :type 'character)
2796 (defcustom org-default-priority ?B
2797 "The default priority of TODO items.
2798 This is the priority an item gets if no explicit priority is given.
2799 When starting to cycle on an empty priority the first step in the cycle
2800 depends on `org-priority-start-cycle-with-default'. The resulting first
2801 step priority must not exceed the range from `org-highest-priority' to
2802 `org-lowest-priority' which means that `org-default-priority' has to be
2803 in this range exclusive or inclusive the range boundaries. Else the
2804 first step refuses to set the default and the second will fall back
2805 to (depending on the command used) the highest or lowest priority."
2806 :group 'org-priorities
2807 :type 'character)
2809 (defcustom org-priority-start-cycle-with-default t
2810 "Non-nil means start with default priority when starting to cycle.
2811 When this is nil, the first step in the cycle will be (depending on the
2812 command used) one higher or lower than the default priority.
2813 See also `org-default-priority'."
2814 :group 'org-priorities
2815 :type 'boolean)
2817 (defcustom org-get-priority-function nil
2818 "Function to extract the priority from a string.
2819 The string is normally the headline. If this is nil Org computes the
2820 priority from the priority cookie like [#A] in the headline. It returns
2821 an integer, increasing by 1000 for each priority level.
2822 The user can set a different function here, which should take a string
2823 as an argument and return the numeric priority."
2824 :group 'org-priorities
2825 :version "24.1"
2826 :type '(choice
2827 (const nil)
2828 (function)))
2830 (defgroup org-time nil
2831 "Options concerning time stamps and deadlines in Org-mode."
2832 :tag "Org Time"
2833 :group 'org)
2835 (defcustom org-insert-labeled-timestamps-at-point nil
2836 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2837 When nil, these labeled time stamps are forces into the second line of an
2838 entry, just after the headline. When scheduling from the global TODO list,
2839 the time stamp will always be forced into the second line."
2840 :group 'org-time
2841 :type 'boolean)
2843 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2844 "Formats for `format-time-string' which are used for time stamps.
2845 It is not recommended to change this constant.")
2847 (defcustom org-time-stamp-rounding-minutes '(0 5)
2848 "Number of minutes to round time stamps to.
2849 These are two values, the first applies when first creating a time stamp.
2850 The second applies when changing it with the commands `S-up' and `S-down'.
2851 When changing the time stamp, this means that it will change in steps
2852 of N minutes, as given by the second value.
2854 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2855 numbers should be factors of 60, so for example 5, 10, 15.
2857 When this is larger than 1, you can still force an exact time stamp by using
2858 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2859 and by using a prefix arg to `S-up/down' to specify the exact number
2860 of minutes to shift."
2861 :group 'org-time
2862 :get #'(lambda (var) ; Make sure both elements are there
2863 (if (integerp (default-value var))
2864 (list (default-value var) 5)
2865 (default-value var)))
2866 :type '(list
2867 (integer :tag "when inserting times")
2868 (integer :tag "when modifying times")))
2870 ;; Normalize old customizations of this variable.
2871 (when (integerp org-time-stamp-rounding-minutes)
2872 (setq org-time-stamp-rounding-minutes
2873 (list org-time-stamp-rounding-minutes
2874 org-time-stamp-rounding-minutes)))
2876 (defcustom org-display-custom-times nil
2877 "Non-nil means overlay custom formats over all time stamps.
2878 The formats are defined through the variable `org-time-stamp-custom-formats'.
2879 To turn this on on a per-file basis, insert anywhere in the file:
2880 #+STARTUP: customtime"
2881 :group 'org-time
2882 :set 'set-default
2883 :type 'sexp)
2884 (make-variable-buffer-local 'org-display-custom-times)
2886 (defcustom org-time-stamp-custom-formats
2887 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2888 "Custom formats for time stamps. See `format-time-string' for the syntax.
2889 These are overlaid over the default ISO format if the variable
2890 `org-display-custom-times' is set. Time like %H:%M should be at the
2891 end of the second format. The custom formats are also honored by export
2892 commands, if custom time display is turned on at the time of export."
2893 :group 'org-time
2894 :type 'sexp)
2896 (defun org-time-stamp-format (&optional long inactive)
2897 "Get the right format for a time string."
2898 (let ((f (if long (cdr org-time-stamp-formats)
2899 (car org-time-stamp-formats))))
2900 (if inactive
2901 (concat "[" (substring f 1 -1) "]")
2902 f)))
2904 (defcustom org-time-clocksum-format
2905 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2906 "The format string used when creating CLOCKSUM lines.
2907 This is also used when Org mode generates a time duration.
2909 The value can be a single format string containing two
2910 %-sequences, which will be filled with the number of hours and
2911 minutes in that order.
2913 Alternatively, the value can be a plist associating any of the
2914 keys :years, :months, :weeks, :days, :hours or :minutes with
2915 format strings. The time duration is formatted using only the
2916 time components that are needed and concatenating the results.
2917 If a time unit in absent, it falls back to the next smallest
2918 unit.
2920 The keys :require-years, :require-months, :require-days,
2921 :require-weeks, :require-hours, :require-minutes are also
2922 meaningful. A non-nil value for these keys indicates that the
2923 corresponding time component should always be included, even if
2924 its value is 0.
2927 For example,
2929 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2930 :require-minutes t)
2932 means durations longer than a day will be expressed in days,
2933 hours and minutes, and durations less than a day will always be
2934 expressed in hours and minutes (even for durations less than an
2935 hour).
2937 The value
2939 \(:days \"%dd\" :minutes \"%dm\")
2941 means durations longer than a day will be expressed in days and
2942 minutes, and durations less than a day will be expressed entirely
2943 in minutes (even for durations longer than an hour)."
2944 :group 'org-time
2945 :group 'org-clock
2946 :version "24.4"
2947 :package-version '(Org . "8.0")
2948 :type '(choice (string :tag "Format string")
2949 (set :tag "Plist"
2950 (group :inline t (const :tag "Years" :years)
2951 (string :tag "Format string"))
2952 (group :inline t
2953 (const :tag "Always show years" :require-years)
2954 (const t))
2955 (group :inline t (const :tag "Months" :months)
2956 (string :tag "Format string"))
2957 (group :inline t
2958 (const :tag "Always show months" :require-months)
2959 (const t))
2960 (group :inline t (const :tag "Weeks" :weeks)
2961 (string :tag "Format string"))
2962 (group :inline t
2963 (const :tag "Always show weeks" :require-weeks)
2964 (const t))
2965 (group :inline t (const :tag "Days" :days)
2966 (string :tag "Format string"))
2967 (group :inline t
2968 (const :tag "Always show days" :require-days)
2969 (const t))
2970 (group :inline t (const :tag "Hours" :hours)
2971 (string :tag "Format string"))
2972 (group :inline t
2973 (const :tag "Always show hours" :require-hours)
2974 (const t))
2975 (group :inline t (const :tag "Minutes" :minutes)
2976 (string :tag "Format string"))
2977 (group :inline t
2978 (const :tag "Always show minutes" :require-minutes)
2979 (const t)))))
2981 (defcustom org-time-clocksum-use-fractional nil
2982 "When non-nil, \\[org-clock-display] uses fractional times.
2983 See `org-time-clocksum-format' for more on time clock formats."
2984 :group 'org-time
2985 :group 'org-clock
2986 :version "24.3"
2987 :type 'boolean)
2989 (defcustom org-time-clocksum-use-effort-durations nil
2990 "When non-nil, \\[org-clock-display] uses effort durations.
2991 E.g. by default, one day is considered to be a 8 hours effort,
2992 so a task that has been clocked for 16 hours will be displayed
2993 as during 2 days in the clock display or in the clocktable.
2995 See `org-effort-durations' on how to set effort durations
2996 and `org-time-clocksum-format' for more on time clock formats."
2997 :group 'org-time
2998 :group 'org-clock
2999 :version "24.4"
3000 :package-version '(Org . "8.0")
3001 :type 'boolean)
3003 (defcustom org-time-clocksum-fractional-format "%.2f"
3004 "The format string used when creating CLOCKSUM lines,
3005 or when Org mode generates a time duration, if
3006 `org-time-clocksum-use-fractional' is enabled.
3008 The value can be a single format string containing one
3009 %-sequence, which will be filled with the number of hours as
3010 a float.
3012 Alternatively, the value can be a plist associating any of the
3013 keys :years, :months, :weeks, :days, :hours or :minutes with
3014 a format string. The time duration is formatted using the
3015 largest time unit which gives a non-zero integer part. If all
3016 specified formats have zero integer part, the smallest time unit
3017 is used."
3018 :group 'org-time
3019 :type '(choice (string :tag "Format string")
3020 (set (group :inline t (const :tag "Years" :years)
3021 (string :tag "Format string"))
3022 (group :inline t (const :tag "Months" :months)
3023 (string :tag "Format string"))
3024 (group :inline t (const :tag "Weeks" :weeks)
3025 (string :tag "Format string"))
3026 (group :inline t (const :tag "Days" :days)
3027 (string :tag "Format string"))
3028 (group :inline t (const :tag "Hours" :hours)
3029 (string :tag "Format string"))
3030 (group :inline t (const :tag "Minutes" :minutes)
3031 (string :tag "Format string")))))
3033 (defcustom org-deadline-warning-days 14
3034 "Number of days before expiration during which a deadline becomes active.
3035 This variable governs the display in sparse trees and in the agenda.
3036 When 0 or negative, it means use this number (the absolute value of it)
3037 even if a deadline has a different individual lead time specified.
3039 Custom commands can set this variable in the options section."
3040 :group 'org-time
3041 :group 'org-agenda-daily/weekly
3042 :type 'integer)
3044 (defcustom org-scheduled-delay-days 0
3045 "Number of days before a scheduled item becomes active.
3046 This variable governs the display in sparse trees and in the agenda.
3047 The default value (i.e. 0) means: don't delay scheduled item.
3048 When negative, it means use this number (the absolute value of it)
3049 even if a scheduled item has a different individual delay time
3050 specified.
3052 Custom commands can set this variable in the options section."
3053 :group 'org-time
3054 :group 'org-agenda-daily/weekly
3055 :version "24.4"
3056 :package-version '(Org . "8.0")
3057 :type 'integer)
3059 (defcustom org-read-date-prefer-future t
3060 "Non-nil means assume future for incomplete date input from user.
3061 This affects the following situations:
3062 1. The user gives a month but not a year.
3063 For example, if it is April and you enter \"feb 2\", this will be read
3064 as Feb 2, *next* year. \"May 5\", however, will be this year.
3065 2. The user gives a day, but no month.
3066 For example, if today is the 15th, and you enter \"3\", Org-mode will
3067 read this as the third of *next* month. However, if you enter \"17\",
3068 it will be considered as *this* month.
3070 If you set this variable to the symbol `time', then also the following
3071 will work:
3073 3. If the user gives a time.
3074 If the time is before now, it will be interpreted as tomorrow.
3076 Currently none of this works for ISO week specifications.
3078 When this option is nil, the current day, month and year will always be
3079 used as defaults.
3081 See also `org-agenda-jump-prefer-future'."
3082 :group 'org-time
3083 :type '(choice
3084 (const :tag "Never" nil)
3085 (const :tag "Check month and day" t)
3086 (const :tag "Check month, day, and time" time)))
3088 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3089 "Should the agenda jump command prefer the future for incomplete dates?
3090 The default is to do the same as configured in `org-read-date-prefer-future'.
3091 But you can also set a deviating value here.
3092 This may t or nil, or the symbol `org-read-date-prefer-future'."
3093 :group 'org-agenda
3094 :group 'org-time
3095 :version "24.1"
3096 :type '(choice
3097 (const :tag "Use org-read-date-prefer-future"
3098 org-read-date-prefer-future)
3099 (const :tag "Never" nil)
3100 (const :tag "Always" t)))
3102 (defcustom org-read-date-force-compatible-dates t
3103 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3105 Depending on the system Emacs is running on, certain dates cannot
3106 be represented with the type used internally to represent time.
3107 Dates between 1970-1-1 and 2038-1-1 can always be represented
3108 correctly. Some systems allow for earlier dates, some for later,
3109 some for both. One way to find out it to insert any date into an
3110 Org buffer, putting the cursor on the year and hitting S-up and
3111 S-down to test the range.
3113 When this variable is set to t, the date/time prompt will not let
3114 you specify dates outside the 1970-2037 range, so it is certain that
3115 these dates will work in whatever version of Emacs you are
3116 running, and also that you can move a file from one Emacs implementation
3117 to another. WHenever Org is forcing the year for you, it will display
3118 a message and beep.
3120 When this variable is nil, Org will check if the date is
3121 representable in the specific Emacs implementation you are using.
3122 If not, it will force a year, usually the current year, and beep
3123 to remind you. Currently this setting is not recommended because
3124 the likelihood that you will open your Org files in an Emacs that
3125 has limited date range is not negligible.
3127 A workaround for this problem is to use diary sexp dates for time
3128 stamps outside of this range."
3129 :group 'org-time
3130 :version "24.1"
3131 :type 'boolean)
3133 (defcustom org-read-date-display-live t
3134 "Non-nil means display current interpretation of date prompt live.
3135 This display will be in an overlay, in the minibuffer."
3136 :group 'org-time
3137 :type 'boolean)
3139 (defcustom org-read-date-popup-calendar t
3140 "Non-nil means pop up a calendar when prompting for a date.
3141 In the calendar, the date can be selected with mouse-1. However, the
3142 minibuffer will also be active, and you can simply enter the date as well.
3143 When nil, only the minibuffer will be available."
3144 :group 'org-time
3145 :type 'boolean)
3146 (org-defvaralias 'org-popup-calendar-for-date-prompt
3147 'org-read-date-popup-calendar)
3149 (make-obsolete-variable
3150 'org-read-date-minibuffer-setup-hook
3151 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3152 (defcustom org-read-date-minibuffer-setup-hook nil
3153 "Hook to be used to set up keys for the date/time interface.
3154 Add key definitions to `minibuffer-local-map', which will be a
3155 temporary copy.
3157 WARNING: This option is obsolete, you should use
3158 `org-read-date-minibuffer-local-map' to set up keys."
3159 :group 'org-time
3160 :type 'hook)
3162 (defcustom org-extend-today-until 0
3163 "The hour when your day really ends. Must be an integer.
3164 This has influence for the following applications:
3165 - When switching the agenda to \"today\". It it is still earlier than
3166 the time given here, the day recognized as TODAY is actually yesterday.
3167 - When a date is read from the user and it is still before the time given
3168 here, the current date and time will be assumed to be yesterday, 23:59.
3169 Also, timestamps inserted in capture templates follow this rule.
3171 IMPORTANT: This is a feature whose implementation is and likely will
3172 remain incomplete. Really, it is only here because past midnight seems to
3173 be the favorite working time of John Wiegley :-)"
3174 :group 'org-time
3175 :type 'integer)
3177 (defcustom org-use-effective-time nil
3178 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3179 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3180 \"effective time\" of any timestamps between midnight and 8am will be
3181 23:59 of the previous day."
3182 :group 'org-time
3183 :version "24.1"
3184 :type 'boolean)
3186 (defcustom org-use-last-clock-out-time-as-effective-time nil
3187 "When non-nil, use the last clock out time for `org-todo'.
3188 Note that this option has precedence over the combined use of
3189 `org-use-effective-time' and `org-extend-today-until'."
3190 :group 'org-time
3191 :version "24.4"
3192 :package-version '(Org . "8.0")
3193 :type 'boolean)
3195 (defcustom org-edit-timestamp-down-means-later nil
3196 "Non-nil means S-down will increase the time in a time stamp.
3197 When nil, S-up will increase."
3198 :group 'org-time
3199 :type 'boolean)
3201 (defcustom org-calendar-follow-timestamp-change t
3202 "Non-nil means make the calendar window follow timestamp changes.
3203 When a timestamp is modified and the calendar window is visible, it will be
3204 moved to the new date."
3205 :group 'org-time
3206 :type 'boolean)
3208 (defgroup org-tags nil
3209 "Options concerning tags in Org-mode."
3210 :tag "Org Tags"
3211 :group 'org)
3213 (defcustom org-tag-alist nil
3214 "List of tags allowed in Org-mode files.
3215 When this list is nil, Org-mode will base TAG input on what is already in the
3216 buffer.
3217 The value of this variable is an alist, the car of each entry must be a
3218 keyword as a string, the cdr may be a character that is used to select
3219 that tag through the fast-tag-selection interface.
3220 See the manual for details."
3221 :group 'org-tags
3222 :type '(repeat
3223 (choice
3224 (cons (string :tag "Tag name")
3225 (character :tag "Access char"))
3226 (list :tag "Start radio group"
3227 (const :startgroup)
3228 (option (string :tag "Group description")))
3229 (list :tag "Group tags delimiter"
3230 (const :grouptags))
3231 (list :tag "End radio group"
3232 (const :endgroup)
3233 (option (string :tag "Group description")))
3234 (const :tag "New line" (:newline)))))
3236 (defcustom org-tag-persistent-alist nil
3237 "List of tags that will always appear in all Org-mode files.
3238 This is in addition to any in buffer settings or customizations
3239 of `org-tag-alist'.
3240 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3241 The value of this variable is an alist, the car of each entry must be a
3242 keyword as a string, the cdr may be a character that is used to select
3243 that tag through the fast-tag-selection interface.
3244 See the manual for details.
3245 To disable these tags on a per-file basis, insert anywhere in the file:
3246 #+STARTUP: noptag"
3247 :group 'org-tags
3248 :type '(repeat
3249 (choice
3250 (cons (string :tag "Tag name")
3251 (character :tag "Access char"))
3252 (const :tag "Start radio group" (:startgroup))
3253 (const :tag "Group tags delimiter" (:grouptags))
3254 (const :tag "End radio group" (:endgroup))
3255 (const :tag "New line" (:newline)))))
3257 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3258 "If non-nil, always offer completion for all tags of all agenda files.
3259 Instead of customizing this variable directly, you might want to
3260 set it locally for capture buffers, because there no list of
3261 tags in that file can be created dynamically (there are none).
3263 (add-hook 'org-capture-mode-hook
3264 (lambda ()
3265 (set (make-local-variable
3266 'org-complete-tags-always-offer-all-agenda-tags)
3267 t)))"
3268 :group 'org-tags
3269 :version "24.1"
3270 :type 'boolean)
3272 (defvar org-file-tags nil
3273 "List of tags that can be inherited by all entries in the file.
3274 The tags will be inherited if the variable `org-use-tag-inheritance'
3275 says they should be.
3276 This variable is populated from #+FILETAGS lines.")
3278 (defcustom org-use-fast-tag-selection 'auto
3279 "Non-nil means use fast tag selection scheme.
3280 This is a special interface to select and deselect tags with single keys.
3281 When nil, fast selection is never used.
3282 When the symbol `auto', fast selection is used if and only if selection
3283 characters for tags have been configured, either through the variable
3284 `org-tag-alist' or through a #+TAGS line in the buffer.
3285 When t, fast selection is always used and selection keys are assigned
3286 automatically if necessary."
3287 :group 'org-tags
3288 :type '(choice
3289 (const :tag "Always" t)
3290 (const :tag "Never" nil)
3291 (const :tag "When selection characters are configured" auto)))
3293 (defcustom org-fast-tag-selection-single-key nil
3294 "Non-nil means fast tag selection exits after first change.
3295 When nil, you have to press RET to exit it.
3296 During fast tag selection, you can toggle this flag with `C-c'.
3297 This variable can also have the value `expert'. In this case, the window
3298 displaying the tags menu is not even shown, until you press C-c again."
3299 :group 'org-tags
3300 :type '(choice
3301 (const :tag "No" nil)
3302 (const :tag "Yes" t)
3303 (const :tag "Expert" expert)))
3305 (defvar org-fast-tag-selection-include-todo nil
3306 "Non-nil means fast tags selection interface will also offer TODO states.
3307 This is an undocumented feature, you should not rely on it.")
3309 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3310 "The column to which tags should be indented in a headline.
3311 If this number is positive, it specifies the column. If it is negative,
3312 it means that the tags should be flushright to that column. For example,
3313 -80 works well for a normal 80 character screen.
3314 When 0, place tags directly after headline text, with only one space in
3315 between."
3316 :group 'org-tags
3317 :type 'integer)
3319 (defcustom org-auto-align-tags t
3320 "Non-nil keeps tags aligned when modifying headlines.
3321 Some operations (i.e. demoting) change the length of a headline and
3322 therefore shift the tags around. With this option turned on, after
3323 each such operation the tags are again aligned to `org-tags-column'."
3324 :group 'org-tags
3325 :type 'boolean)
3327 (defcustom org-use-tag-inheritance t
3328 "Non-nil means tags in levels apply also for sublevels.
3329 When nil, only the tags directly given in a specific line apply there.
3330 This may also be a list of tags that should be inherited, or a regexp that
3331 matches tags that should be inherited. Additional control is possible
3332 with the variable `org-tags-exclude-from-inheritance' which gives an
3333 explicit list of tags to be excluded from inheritance, even if the value of
3334 `org-use-tag-inheritance' would select it for inheritance.
3336 If this option is t, a match early-on in a tree can lead to a large
3337 number of matches in the subtree when constructing the agenda or creating
3338 a sparse tree. If you only want to see the first match in a tree during
3339 a search, check out the variable `org-tags-match-list-sublevels'."
3340 :group 'org-tags
3341 :type '(choice
3342 (const :tag "Not" nil)
3343 (const :tag "Always" t)
3344 (repeat :tag "Specific tags" (string :tag "Tag"))
3345 (regexp :tag "Tags matched by regexp")))
3347 (defcustom org-tags-exclude-from-inheritance nil
3348 "List of tags that should never be inherited.
3349 This is a way to exclude a few tags from inheritance. For way to do
3350 the opposite, to actively allow inheritance for selected tags,
3351 see the variable `org-use-tag-inheritance'."
3352 :group 'org-tags
3353 :type '(repeat (string :tag "Tag")))
3355 (defun org-tag-inherit-p (tag)
3356 "Check if TAG is one that should be inherited."
3357 (cond
3358 ((member tag org-tags-exclude-from-inheritance) nil)
3359 ((eq org-use-tag-inheritance t) t)
3360 ((not org-use-tag-inheritance) nil)
3361 ((stringp org-use-tag-inheritance)
3362 (string-match org-use-tag-inheritance tag))
3363 ((listp org-use-tag-inheritance)
3364 (member tag org-use-tag-inheritance))
3365 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3367 (defcustom org-tags-match-list-sublevels t
3368 "Non-nil means list also sublevels of headlines matching a search.
3369 This variable applies to tags/property searches, and also to stuck
3370 projects because this search is based on a tags match as well.
3372 When set to the symbol `indented', sublevels are indented with
3373 leading dots.
3375 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3376 the sublevels of a headline matching a tag search often also match
3377 the same search. Listing all of them can create very long lists.
3378 Setting this variable to nil causes subtrees of a match to be skipped.
3380 This variable is semi-obsolete and probably should always be true. It
3381 is better to limit inheritance to certain tags using the variables
3382 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3383 :group 'org-tags
3384 :type '(choice
3385 (const :tag "No, don't list them" nil)
3386 (const :tag "Yes, do list them" t)
3387 (const :tag "List them, indented with leading dots" indented)))
3389 (defcustom org-tags-sort-function nil
3390 "When set, tags are sorted using this function as a comparator."
3391 :group 'org-tags
3392 :type '(choice
3393 (const :tag "No sorting" nil)
3394 (const :tag "Alphabetical" string<)
3395 (const :tag "Reverse alphabetical" string>)
3396 (function :tag "Custom function" nil)))
3398 (defvar org-tags-history nil
3399 "History of minibuffer reads for tags.")
3400 (defvar org-last-tags-completion-table nil
3401 "The last used completion table for tags.")
3402 (defvar org-after-tags-change-hook nil
3403 "Hook that is run after the tags in a line have changed.")
3405 (defgroup org-properties nil
3406 "Options concerning properties in Org-mode."
3407 :tag "Org Properties"
3408 :group 'org)
3410 (defcustom org-property-format "%-10s %s"
3411 "How property key/value pairs should be formatted by `indent-line'.
3412 When `indent-line' hits a property definition, it will format the line
3413 according to this format, mainly to make sure that the values are
3414 lined-up with respect to each other."
3415 :group 'org-properties
3416 :type 'string)
3418 (defcustom org-properties-postprocess-alist nil
3419 "Alist of properties and functions to adjust inserted values.
3420 Elements of this alist must be of the form
3422 ([string] [function])
3424 where [string] must be a property name and [function] must be a
3425 lambda expression: this lambda expression must take one argument,
3426 the value to adjust, and return the new value as a string.
3428 For example, this element will allow the property \"Remaining\"
3429 to be updated wrt the relation between the \"Effort\" property
3430 and the clock summary:
3432 ((\"Remaining\" (lambda(value)
3433 (let ((clocksum (org-clock-sum-current-item))
3434 (effort (org-duration-string-to-minutes
3435 (org-entry-get (point) \"Effort\"))))
3436 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3437 :group 'org-properties
3438 :version "24.1"
3439 :type '(alist :key-type (string :tag "Property")
3440 :value-type (function :tag "Function")))
3442 (defcustom org-use-property-inheritance nil
3443 "Non-nil means properties apply also for sublevels.
3445 This setting is chiefly used during property searches. Turning it on can
3446 cause significant overhead when doing a search, which is why it is not
3447 on by default.
3449 When nil, only the properties directly given in the current entry count.
3450 When t, every property is inherited. The value may also be a list of
3451 properties that should have inheritance, or a regular expression matching
3452 properties that should be inherited.
3454 However, note that some special properties use inheritance under special
3455 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3456 and the properties ending in \"_ALL\" when they are used as descriptor
3457 for valid values of a property.
3459 Note for programmers:
3460 When querying an entry with `org-entry-get', you can control if inheritance
3461 should be used. By default, `org-entry-get' looks only at the local
3462 properties. You can request inheritance by setting the inherit argument
3463 to t (to force inheritance) or to `selective' (to respect the setting
3464 in this variable)."
3465 :group 'org-properties
3466 :type '(choice
3467 (const :tag "Not" nil)
3468 (const :tag "Always" t)
3469 (repeat :tag "Specific properties" (string :tag "Property"))
3470 (regexp :tag "Properties matched by regexp")))
3472 (defun org-property-inherit-p (property)
3473 "Check if PROPERTY is one that should be inherited."
3474 (cond
3475 ((eq org-use-property-inheritance t) t)
3476 ((not org-use-property-inheritance) nil)
3477 ((stringp org-use-property-inheritance)
3478 (string-match org-use-property-inheritance property))
3479 ((listp org-use-property-inheritance)
3480 (member property org-use-property-inheritance))
3481 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3483 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3484 "The default column format, if no other format has been defined.
3485 This variable can be set on the per-file basis by inserting a line
3487 #+COLUMNS: %25ITEM ....."
3488 :group 'org-properties
3489 :type 'string)
3491 (defcustom org-columns-ellipses ".."
3492 "The ellipses to be used when a field in column view is truncated.
3493 When this is the empty string, as many characters as possible are shown,
3494 but then there will be no visual indication that the field has been truncated.
3495 When this is a string of length N, the last N characters of a truncated
3496 field are replaced by this string. If the column is narrower than the
3497 ellipses string, only part of the ellipses string will be shown."
3498 :group 'org-properties
3499 :type 'string)
3501 (defcustom org-columns-modify-value-for-display-function nil
3502 "Function that modifies values for display in column view.
3503 For example, it can be used to cut out a certain part from a time stamp.
3504 The function must take 2 arguments:
3506 column-title The title of the column (*not* the property name)
3507 value The value that should be modified.
3509 The function should return the value that should be displayed,
3510 or nil if the normal value should be used."
3511 :group 'org-properties
3512 :type '(choice (const nil) (function)))
3514 (defcustom org-effort-property "Effort"
3515 "The property that is being used to keep track of effort estimates.
3516 Effort estimates given in this property need to have the format H:MM."
3517 :group 'org-properties
3518 :group 'org-progress
3519 :type '(string :tag "Property"))
3521 (defconst org-global-properties-fixed
3522 '(("VISIBILITY_ALL" . "folded children content all")
3523 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3524 "List of property/value pairs that can be inherited by any entry.
3526 These are fixed values, for the preset properties. The user variable
3527 that can be used to add to this list is `org-global-properties'.
3529 The entries in this list are cons cells where the car is a property
3530 name and cdr is a string with the value. If the value represents
3531 multiple items like an \"_ALL\" property, separate the items by
3532 spaces.")
3534 (defcustom org-global-properties nil
3535 "List of property/value pairs that can be inherited by any entry.
3537 This list will be combined with the constant `org-global-properties-fixed'.
3539 The entries in this list are cons cells where the car is a property
3540 name and cdr is a string with the value.
3542 You can set buffer-local values for the same purpose in the variable
3543 `org-file-properties' this by adding lines like
3545 #+PROPERTY: NAME VALUE"
3546 :group 'org-properties
3547 :type '(repeat
3548 (cons (string :tag "Property")
3549 (string :tag "Value"))))
3551 (defvar org-file-properties nil
3552 "List of property/value pairs that can be inherited by any entry.
3553 Valid for the current buffer.
3554 This variable is populated from #+PROPERTY lines.")
3555 (make-variable-buffer-local 'org-file-properties)
3557 (defgroup org-agenda nil
3558 "Options concerning agenda views in Org-mode."
3559 :tag "Org Agenda"
3560 :group 'org)
3562 (defvar org-category nil
3563 "Variable used by org files to set a category for agenda display.
3564 Such files should use a file variable to set it, for example
3566 # -*- mode: org; org-category: \"ELisp\"
3568 or contain a special line
3570 #+CATEGORY: ELisp
3572 If the file does not specify a category, then file's base name
3573 is used instead.")
3574 (make-variable-buffer-local 'org-category)
3575 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3577 (defcustom org-agenda-files nil
3578 "The files to be used for agenda display.
3579 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3580 \\[org-remove-file]. You can also use customize to edit the list.
3582 If an entry is a directory, all files in that directory that are matched by
3583 `org-agenda-file-regexp' will be part of the file list.
3585 If the value of the variable is not a list but a single file name, then
3586 the list of agenda files is actually stored and maintained in that file, one
3587 agenda file per line. In this file paths can be given relative to
3588 `org-directory'. Tilde expansion and environment variable substitution
3589 are also made."
3590 :group 'org-agenda
3591 :type '(choice
3592 (repeat :tag "List of files and directories" file)
3593 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3595 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3596 "Regular expression to match files for `org-agenda-files'.
3597 If any element in the list in that variable contains a directory instead
3598 of a normal file, all files in that directory that are matched by this
3599 regular expression will be included."
3600 :group 'org-agenda
3601 :type 'regexp)
3603 (defcustom org-agenda-text-search-extra-files nil
3604 "List of extra files to be searched by text search commands.
3605 These files will be searched in addition to the agenda files by the
3606 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3607 Note that these files will only be searched for text search commands,
3608 not for the other agenda views like todo lists, tag searches or the weekly
3609 agenda. This variable is intended to list notes and possibly archive files
3610 that should also be searched by these two commands.
3611 In fact, if the first element in the list is the symbol `agenda-archives',
3612 then all archive files of all agenda files will be added to the search
3613 scope."
3614 :group 'org-agenda
3615 :type '(set :greedy t
3616 (const :tag "Agenda Archives" agenda-archives)
3617 (repeat :inline t (file))))
3619 (org-defvaralias 'org-agenda-multi-occur-extra-files
3620 'org-agenda-text-search-extra-files)
3622 (defcustom org-agenda-skip-unavailable-files nil
3623 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3624 A nil value means to remove them, after a query, from the list."
3625 :group 'org-agenda
3626 :type 'boolean)
3628 (defcustom org-calendar-to-agenda-key [?c]
3629 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3630 The command `org-calendar-goto-agenda' will be bound to this key. The
3631 default is the character `c' because then `c' can be used to switch back and
3632 forth between agenda and calendar."
3633 :group 'org-agenda
3634 :type 'sexp)
3636 (defcustom org-calendar-insert-diary-entry-key [?i]
3637 "The key to be installed in `calendar-mode-map' for adding diary entries.
3638 This option is irrelevant until `org-agenda-diary-file' has been configured
3639 to point to an Org-mode file. When that is the case, the command
3640 `org-agenda-diary-entry' will be bound to the key given here, by default
3641 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3642 if you want to continue doing this, you need to change this to a different
3643 key."
3644 :group 'org-agenda
3645 :type 'sexp)
3647 (defcustom org-agenda-diary-file 'diary-file
3648 "File to which to add new entries with the `i' key in agenda and calendar.
3649 When this is the symbol `diary-file', the functionality in the Emacs
3650 calendar will be used to add entries to the `diary-file'. But when this
3651 points to a file, `org-agenda-diary-entry' will be used instead."
3652 :group 'org-agenda
3653 :type '(choice
3654 (const :tag "The standard Emacs diary file" diary-file)
3655 (file :tag "Special Org file diary entries")))
3657 (eval-after-load "calendar"
3658 '(progn
3659 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3660 'org-calendar-goto-agenda)
3661 (add-hook 'calendar-mode-hook
3662 (lambda ()
3663 (unless (eq org-agenda-diary-file 'diary-file)
3664 (define-key calendar-mode-map
3665 org-calendar-insert-diary-entry-key
3666 'org-agenda-diary-entry))))))
3668 (defgroup org-latex nil
3669 "Options for embedding LaTeX code into Org-mode."
3670 :tag "Org LaTeX"
3671 :group 'org)
3673 (defcustom org-format-latex-options
3674 '(:foreground default :background default :scale 1.0
3675 :html-foreground "Black" :html-background "Transparent"
3676 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3677 "Options for creating images from LaTeX fragments.
3678 This is a property list with the following properties:
3679 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3680 `default' means use the foreground of the default face.
3681 `auto' means use the foreground from the text face.
3682 :background the background color, or \"Transparent\".
3683 `default' means use the background of the default face.
3684 `auto' means use the background from the text face.
3685 :scale a scaling factor for the size of the images, to get more pixels
3686 :html-foreground, :html-background, :html-scale
3687 the same numbers for HTML export.
3688 :matchers a list indicating which matchers should be used to
3689 find LaTeX fragments. Valid members of this list are:
3690 \"begin\" find environments
3691 \"$1\" find single characters surrounded by $.$
3692 \"$\" find math expressions surrounded by $...$
3693 \"$$\" find math expressions surrounded by $$....$$
3694 \"\\(\" find math expressions surrounded by \\(...\\)
3695 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3696 :group 'org-latex
3697 :type 'plist)
3699 (defcustom org-format-latex-signal-error t
3700 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3701 When nil, just push out a message."
3702 :group 'org-latex
3703 :version "24.1"
3704 :type 'boolean)
3706 (defcustom org-latex-to-mathml-jar-file nil
3707 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3708 Use this to specify additional executable file say a jar file.
3710 When using MathToWeb as the converter, specify the full-path to
3711 your mathtoweb.jar file."
3712 :group 'org-latex
3713 :version "24.1"
3714 :type '(choice
3715 (const :tag "None" nil)
3716 (file :tag "JAR file" :must-match t)))
3718 (defcustom org-latex-to-mathml-convert-command nil
3719 "Command to convert LaTeX fragments to MathML.
3720 Replace format-specifiers in the command as noted below and use
3721 `shell-command' to convert LaTeX to MathML.
3722 %j: Executable file in fully expanded form as specified by
3723 `org-latex-to-mathml-jar-file'.
3724 %I: Input LaTeX file in fully expanded form
3725 %o: Output MathML file
3726 This command is used by `org-create-math-formula'.
3728 When using MathToWeb as the converter, set this to
3729 \"java -jar %j -unicode -force -df %o %I\"."
3730 :group 'org-latex
3731 :version "24.1"
3732 :type '(choice
3733 (const :tag "None" nil)
3734 (string :tag "\nShell command")))
3736 (defcustom org-latex-create-formula-image-program 'dvipng
3737 "Program to convert LaTeX fragments with.
3739 dvipng Process the LaTeX fragments to dvi file, then convert
3740 dvi files to png files using dvipng.
3741 This will also include processing of non-math environments.
3742 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3743 to convert pdf files to png files"
3744 :group 'org-latex
3745 :version "24.1"
3746 :type '(choice
3747 (const :tag "dvipng" dvipng)
3748 (const :tag "imagemagick" imagemagick)))
3750 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3751 "Path to store latex preview images.
3752 A relative path here creates many directories relative to the
3753 processed org files paths. An absolute path puts all preview
3754 images at the same place."
3755 :group 'org-latex
3756 :version "24.3"
3757 :type 'string)
3759 (defun org-format-latex-mathml-available-p ()
3760 "Return t if `org-latex-to-mathml-convert-command' is usable."
3761 (save-match-data
3762 (when (and (boundp 'org-latex-to-mathml-convert-command)
3763 org-latex-to-mathml-convert-command)
3764 (let ((executable (car (split-string
3765 org-latex-to-mathml-convert-command))))
3766 (when (executable-find executable)
3767 (if (string-match
3768 "%j" org-latex-to-mathml-convert-command)
3769 (file-readable-p org-latex-to-mathml-jar-file)
3770 t))))))
3772 (defcustom org-format-latex-header "\\documentclass{article}
3773 \\usepackage[usenames]{color}
3774 \[PACKAGES]
3775 \[DEFAULT-PACKAGES]
3776 \\pagestyle{empty} % do not remove
3777 % The settings below are copied from fullpage.sty
3778 \\setlength{\\textwidth}{\\paperwidth}
3779 \\addtolength{\\textwidth}{-3cm}
3780 \\setlength{\\oddsidemargin}{1.5cm}
3781 \\addtolength{\\oddsidemargin}{-2.54cm}
3782 \\setlength{\\evensidemargin}{\\oddsidemargin}
3783 \\setlength{\\textheight}{\\paperheight}
3784 \\addtolength{\\textheight}{-\\headheight}
3785 \\addtolength{\\textheight}{-\\headsep}
3786 \\addtolength{\\textheight}{-\\footskip}
3787 \\addtolength{\\textheight}{-3cm}
3788 \\setlength{\\topmargin}{1.5cm}
3789 \\addtolength{\\topmargin}{-2.54cm}"
3790 "The document header used for processing LaTeX fragments.
3791 It is imperative that this header make sure that no page number
3792 appears on the page. The package defined in the variables
3793 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3794 will either replace the placeholder \"[PACKAGES]\" in this
3795 header, or they will be appended."
3796 :group 'org-latex
3797 :type 'string)
3799 (defun org-set-packages-alist (var val)
3800 "Set the packages alist and make sure it has 3 elements per entry."
3801 (set var (mapcar (lambda (x)
3802 (if (and (consp x) (= (length x) 2))
3803 (list (car x) (nth 1 x) t)
3805 val)))
3807 (defun org-get-packages-alist (var)
3808 "Get the packages alist and make sure it has 3 elements per entry."
3809 (mapcar (lambda (x)
3810 (if (and (consp x) (= (length x) 2))
3811 (list (car x) (nth 1 x) t)
3813 (default-value var)))
3815 (defcustom org-latex-default-packages-alist
3816 '(("AUTO" "inputenc" t)
3817 ("T1" "fontenc" t)
3818 ("" "fixltx2e" nil)
3819 ("" "graphicx" t)
3820 ("" "longtable" nil)
3821 ("" "float" nil)
3822 ("" "wrapfig" nil)
3823 ("" "rotating" nil)
3824 ("normalem" "ulem" t)
3825 ("" "amsmath" t)
3826 ("" "textcomp" t)
3827 ("" "marvosym" t)
3828 ("" "wasysym" t)
3829 ("" "amssymb" t)
3830 ("" "hyperref" nil)
3831 "\\tolerance=1000")
3832 "Alist of default packages to be inserted in the header.
3834 Change this only if one of the packages here causes an
3835 incompatibility with another package you are using.
3837 The packages in this list are needed by one part or another of
3838 Org mode to function properly:
3840 - inputenc, fontenc: for basic font and character selection
3841 - fixltx2e: Important patches of LaTeX itself
3842 - graphicx: for including images
3843 - longtable: For multipage tables
3844 - float, wrapfig: for figure placement
3845 - rotating: for sideways figures and tables
3846 - ulem: for underline and strike-through
3847 - amsmath: for subscript and superscript and math environments
3848 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3849 for interpreting the entities in `org-entities'. You can skip
3850 some of these packages if you don't use any of their symbols.
3851 - hyperref: for cross references
3853 Therefore you should not modify this variable unless you know
3854 what you are doing. The one reason to change it anyway is that
3855 you might be loading some other package that conflicts with one
3856 of the default packages. Each cell is of the format
3857 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3858 the package also needs to be included when compiling LaTeX
3859 snippets into images for inclusion into non-LaTeX output."
3860 :group 'org-latex
3861 :group 'org-export-latex
3862 :set 'org-set-packages-alist
3863 :get 'org-get-packages-alist
3864 :version "24.1"
3865 :type '(repeat
3866 (choice
3867 (list :tag "options/package pair"
3868 (string :tag "options")
3869 (string :tag "package")
3870 (boolean :tag "Snippet"))
3871 (string :tag "A line of LaTeX"))))
3873 (defcustom org-latex-packages-alist nil
3874 "Alist of packages to be inserted in every LaTeX header.
3876 These will be inserted after `org-latex-default-packages-alist'.
3877 Each cell is of the format:
3879 \(\"options\" \"package\" snippet-flag)
3881 SNIPPET-FLAG, when t, indicates that this package is also needed
3882 when turning LaTeX snippets into images for inclusion into
3883 non-LaTeX output.
3885 Make sure that you only list packages here which:
3887 - you want in every file
3888 - do not conflict with the setup in `org-format-latex-header'.
3889 - do not conflict with the default packages in
3890 `org-latex-default-packages-alist'."
3891 :group 'org-latex
3892 :group 'org-export-latex
3893 :set 'org-set-packages-alist
3894 :get 'org-get-packages-alist
3895 :type '(repeat
3896 (choice
3897 (list :tag "options/package pair"
3898 (string :tag "options")
3899 (string :tag "package")
3900 (boolean :tag "Snippet"))
3901 (string :tag "A line of LaTeX"))))
3903 (defgroup org-appearance nil
3904 "Settings for Org-mode appearance."
3905 :tag "Org Appearance"
3906 :group 'org)
3908 (defcustom org-level-color-stars-only nil
3909 "Non-nil means fontify only the stars in each headline.
3910 When nil, the entire headline is fontified.
3911 Changing it requires restart of `font-lock-mode' to become effective
3912 also in regions already fontified."
3913 :group 'org-appearance
3914 :type 'boolean)
3916 (defcustom org-hide-leading-stars nil
3917 "Non-nil means hide the first N-1 stars in a headline.
3918 This works by using the face `org-hide' for these stars. This
3919 face is white for a light background, and black for a dark
3920 background. You may have to customize the face `org-hide' to
3921 make this work.
3922 Changing it requires restart of `font-lock-mode' to become effective
3923 also in regions already fontified.
3924 You may also set this on a per-file basis by adding one of the following
3925 lines to the buffer:
3927 #+STARTUP: hidestars
3928 #+STARTUP: showstars"
3929 :group 'org-appearance
3930 :type 'boolean)
3932 (defcustom org-hidden-keywords nil
3933 "List of symbols corresponding to keywords to be hidden the org buffer.
3934 For example, a value '(title) for this list will make the document's title
3935 appear in the buffer without the initial #+TITLE: keyword."
3936 :group 'org-appearance
3937 :version "24.1"
3938 :type '(set (const :tag "#+AUTHOR" author)
3939 (const :tag "#+DATE" date)
3940 (const :tag "#+EMAIL" email)
3941 (const :tag "#+TITLE" title)))
3943 (defcustom org-custom-properties nil
3944 "List of properties (as strings) with a special meaning.
3945 The default use of these custom properties is to let the user
3946 hide them with `org-toggle-custom-properties-visibility'."
3947 :group 'org-properties
3948 :group 'org-appearance
3949 :version "24.3"
3950 :type '(repeat (string :tag "Property Name")))
3952 (defcustom org-fontify-done-headline nil
3953 "Non-nil means change the face of a headline if it is marked DONE.
3954 Normally, only the TODO/DONE keyword indicates the state of a headline.
3955 When this is non-nil, the headline after the keyword is set to the
3956 `org-headline-done' as an additional indication."
3957 :group 'org-appearance
3958 :type 'boolean)
3960 (defcustom org-fontify-emphasized-text t
3961 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3962 Changing this variable requires a restart of Emacs to take effect."
3963 :group 'org-appearance
3964 :type 'boolean)
3966 (defcustom org-fontify-whole-heading-line nil
3967 "Non-nil means fontify the whole line for headings.
3968 This is useful when setting a background color for the
3969 org-level-* faces."
3970 :group 'org-appearance
3971 :type 'boolean)
3973 (defcustom org-highlight-latex-and-related nil
3974 "Non-nil means highlight LaTeX related syntax in the buffer.
3975 When non nil, the value should be a list containing any of the
3976 following symbols:
3977 `latex' Highlight LaTeX snippets and environments.
3978 `script' Highlight subscript and superscript.
3979 `entities' Highlight entities."
3980 :group 'org-appearance
3981 :version "24.4"
3982 :package-version '(Org . "8.0")
3983 :type '(choice
3984 (const :tag "No highlighting" nil)
3985 (set :greedy t :tag "Highlight"
3986 (const :tag "LaTeX snippets and environments" latex)
3987 (const :tag "Subscript and superscript" script)
3988 (const :tag "Entities" entities))))
3990 (defcustom org-hide-emphasis-markers nil
3991 "Non-nil mean font-lock should hide the emphasis marker characters."
3992 :group 'org-appearance
3993 :type 'boolean)
3995 (defcustom org-pretty-entities nil
3996 "Non-nil means show entities as UTF8 characters.
3997 When nil, the \\name form remains in the buffer."
3998 :group 'org-appearance
3999 :version "24.1"
4000 :type 'boolean)
4002 (defcustom org-pretty-entities-include-sub-superscripts t
4003 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4004 :group 'org-appearance
4005 :version "24.1"
4006 :type 'boolean)
4008 (defvar org-emph-re nil
4009 "Regular expression for matching emphasis.
4010 After a match, the match groups contain these elements:
4011 0 The match of the full regular expression, including the characters
4012 before and after the proper match
4013 1 The character before the proper match, or empty at beginning of line
4014 2 The proper match, including the leading and trailing markers
4015 3 The leading marker like * or /, indicating the type of highlighting
4016 4 The text between the emphasis markers, not including the markers
4017 5 The character after the match, empty at the end of a line")
4018 (defvar org-verbatim-re nil
4019 "Regular expression for matching verbatim text.")
4020 (defvar org-emphasis-regexp-components) ; defined just below
4021 (defvar org-emphasis-alist) ; defined just below
4022 (defun org-set-emph-re (var val)
4023 "Set variable and compute the emphasis regular expression."
4024 (set var val)
4025 (when (and (boundp 'org-emphasis-alist)
4026 (boundp 'org-emphasis-regexp-components)
4027 org-emphasis-alist org-emphasis-regexp-components)
4028 (let* ((e org-emphasis-regexp-components)
4029 (pre (car e))
4030 (post (nth 1 e))
4031 (border (nth 2 e))
4032 (body (nth 3 e))
4033 (nl (nth 4 e))
4034 (body1 (concat body "*?"))
4035 (markers (mapconcat 'car org-emphasis-alist ""))
4036 (vmarkers (mapconcat
4037 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4038 org-emphasis-alist "")))
4039 ;; make sure special characters appear at the right position in the class
4040 (if (string-match "\\^" markers)
4041 (setq markers (concat (replace-match "" t t markers) "^")))
4042 (if (string-match "-" markers)
4043 (setq markers (concat (replace-match "" t t markers) "-")))
4044 (if (string-match "\\^" vmarkers)
4045 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4046 (if (string-match "-" vmarkers)
4047 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4048 (if (> nl 0)
4049 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4050 (int-to-string nl) "\\}")))
4051 ;; Make the regexp
4052 (setq org-emph-re
4053 (concat "\\([" pre "]\\|^\\)"
4054 "\\("
4055 "\\([" markers "]\\)"
4056 "\\("
4057 "[^" border "]\\|"
4058 "[^" border "]"
4059 body1
4060 "[^" border "]"
4061 "\\)"
4062 "\\3\\)"
4063 "\\([" post "]\\|$\\)"))
4064 (setq org-verbatim-re
4065 (concat "\\([" pre "]\\|^\\)"
4066 "\\("
4067 "\\([" vmarkers "]\\)"
4068 "\\("
4069 "[^" border "]\\|"
4070 "[^" border "]"
4071 body1
4072 "[^" border "]"
4073 "\\)"
4074 "\\3\\)"
4075 "\\([" post "]\\|$\\)")))))
4077 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4078 ;; set this option proved cumbersome. See this message/thread:
4079 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4080 (defvar org-emphasis-regexp-components
4081 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4082 "Components used to build the regular expression for emphasis.
4083 This is a list with five entries. Terminology: In an emphasis string
4084 like \" *strong word* \", we call the initial space PREMATCH, the final
4085 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4086 and \"trong wor\" is the body. The different components in this variable
4087 specify what is allowed/forbidden in each part:
4089 pre Chars allowed as prematch. Beginning of line will be allowed too.
4090 post Chars allowed as postmatch. End of line will be allowed too.
4091 border The chars *forbidden* as border characters.
4092 body-regexp A regexp like \".\" to match a body character. Don't use
4093 non-shy groups here, and don't allow newline here.
4094 newline The maximum number of newlines allowed in an emphasis exp.
4096 You need to reload Org or to restart Emacs after customizing this.")
4098 (defcustom org-emphasis-alist
4099 `(("*" bold)
4100 ("/" italic)
4101 ("_" underline)
4102 ("=" org-code verbatim)
4103 ("~" org-verbatim verbatim)
4104 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4105 "Alist of characters and faces to emphasize text.
4106 Text starting and ending with a special character will be emphasized,
4107 for example *bold*, _underlined_ and /italic/. This variable sets the
4108 marker characters and the face to be used by font-lock for highlighting
4109 in Org-mode Emacs buffers.
4111 You need to reload Org or to restart Emacs after customizing this."
4112 :group 'org-appearance
4113 :set 'org-set-emph-re
4114 :version "24.4"
4115 :package-version '(Org . "8.0")
4116 :type '(repeat
4117 (list
4118 (string :tag "Marker character")
4119 (choice
4120 (face :tag "Font-lock-face")
4121 (plist :tag "Face property list"))
4122 (option (const verbatim)))))
4124 (defvar org-protecting-blocks
4125 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4126 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4127 This is needed for font-lock setup.")
4129 ;;; Miscellaneous options
4131 (defgroup org-completion nil
4132 "Completion in Org-mode."
4133 :tag "Org Completion"
4134 :group 'org)
4136 (defcustom org-completion-use-ido nil
4137 "Non-nil means use ido completion wherever possible.
4138 Note that `ido-mode' must be active for this variable to be relevant.
4139 If you decide to turn this variable on, you might well want to turn off
4140 `org-outline-path-complete-in-steps'.
4141 See also `org-completion-use-iswitchb'."
4142 :group 'org-completion
4143 :type 'boolean)
4145 (defcustom org-completion-use-iswitchb nil
4146 "Non-nil means use iswitchb completion wherever possible.
4147 Note that `iswitchb-mode' must be active for this variable to be relevant.
4148 If you decide to turn this variable on, you might well want to turn off
4149 `org-outline-path-complete-in-steps'.
4150 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4151 :group 'org-completion
4152 :type 'boolean)
4154 (defcustom org-completion-fallback-command 'hippie-expand
4155 "The expansion command called by \\[pcomplete] in normal context.
4156 Normal means, no org-mode-specific context."
4157 :group 'org-completion
4158 :type 'function)
4160 ;;; Functions and variables from their packages
4161 ;; Declared here to avoid compiler warnings
4163 ;; XEmacs only
4164 (defvar outline-mode-menu-heading)
4165 (defvar outline-mode-menu-show)
4166 (defvar outline-mode-menu-hide)
4167 (defvar zmacs-regions) ; XEmacs regions
4169 ;; Emacs only
4170 (defvar mark-active)
4172 ;; Various packages
4173 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4174 (declare-function calendar-forward-day "cal-move" (arg))
4175 (declare-function calendar-goto-date "cal-move" (date))
4176 (declare-function calendar-goto-today "cal-move" ())
4177 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4178 (defvar calc-embedded-close-formula)
4179 (defvar calc-embedded-open-formula)
4180 (declare-function cdlatex-tab "ext:cdlatex" ())
4181 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4182 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4183 (defvar font-lock-unfontify-region-function)
4184 (declare-function iswitchb-read-buffer "iswitchb"
4185 (prompt &optional default require-match start matches-set))
4186 (defvar iswitchb-temp-buflist)
4187 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4188 (defvar org-agenda-tags-todo-honor-ignore-options)
4189 (declare-function org-agenda-skip "org-agenda" ())
4190 (declare-function
4191 org-agenda-format-item "org-agenda"
4192 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4193 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4194 (declare-function org-agenda-change-all-lines "org-agenda"
4195 (newhead hdmarker &optional fixface just-this))
4196 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4197 (declare-function org-agenda-maybe-redo "org-agenda" ())
4198 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4199 (beg end))
4200 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4201 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4202 "org-agenda" (&optional end))
4203 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4204 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4205 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4206 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4207 (declare-function org-indent-mode "org-indent" (&optional arg))
4208 (declare-function parse-time-string "parse-time" (string))
4209 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4210 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4211 (defvar remember-data-file)
4212 (defvar texmathp-why)
4213 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4214 (declare-function table--at-cell-p "table" (position &optional object at-column))
4216 (defvar org-latex-regexps)
4218 ;;; Autoload and prepare some org modules
4220 ;; Some table stuff that needs to be defined here, because it is used
4221 ;; by the functions setting up org-mode or checking for table context.
4223 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4224 "Detect an org-type or table-type table.")
4225 (defconst org-table-line-regexp "^[ \t]*|"
4226 "Detect an org-type table line.")
4227 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4228 "Detect an org-type table line.")
4229 (defconst org-table-hline-regexp "^[ \t]*|-"
4230 "Detect an org-type table hline.")
4231 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4232 "Detect a table-type table hline.")
4233 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4234 "Detect the first line outside a table when searching from within it.
4235 This works for both table types.")
4237 ;; Autoload the functions in org-table.el that are needed by functions here.
4239 (eval-and-compile
4240 (org-autoload "org-table"
4241 '(org-table-begin org-table-blank-field org-table-end)))
4243 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4244 "Detect a #+TBLFM line.")
4246 ;;;###autoload
4247 (defun turn-on-orgtbl ()
4248 "Unconditionally turn on `orgtbl-mode'."
4249 (require 'org-table)
4250 (orgtbl-mode 1))
4252 (defun org-at-table-p (&optional table-type)
4253 "Return t if the cursor is inside an org-type table.
4254 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4255 (if org-enable-table-editor
4256 (save-excursion
4257 (beginning-of-line 1)
4258 (looking-at (if table-type org-table-any-line-regexp
4259 org-table-line-regexp)))
4260 nil))
4261 (defsubst org-table-p () (org-at-table-p))
4263 (defun org-at-table.el-p ()
4264 "Return t if and only if we are at a table.el table."
4265 (and (org-at-table-p 'any)
4266 (save-excursion
4267 (goto-char (org-table-begin 'any))
4268 (looking-at org-table1-hline-regexp))))
4270 (defun org-table-recognize-table.el ()
4271 "If there is a table.el table nearby, recognize it and move into it."
4272 (if org-table-tab-recognizes-table.el
4273 (if (org-at-table.el-p)
4274 (progn
4275 (beginning-of-line 1)
4276 (if (looking-at org-table-dataline-regexp)
4278 (if (looking-at org-table1-hline-regexp)
4279 (progn
4280 (beginning-of-line 2)
4281 (if (looking-at org-table-any-border-regexp)
4282 (beginning-of-line -1)))))
4283 (if (re-search-forward "|" (org-table-end t) t)
4284 (progn
4285 (require 'table)
4286 (if (table--at-cell-p (point))
4288 (message "recognizing table.el table...")
4289 (table-recognize-table)
4290 (message "recognizing table.el table...done")))
4291 (error "This should not happen"))
4293 nil)
4294 nil))
4296 (defun org-at-table-hline-p ()
4297 "Return t if the cursor is inside a hline in a table."
4298 (if org-enable-table-editor
4299 (save-excursion
4300 (beginning-of-line 1)
4301 (looking-at org-table-hline-regexp))
4302 nil))
4304 (defun org-table-map-tables (function &optional quietly)
4305 "Apply FUNCTION to the start of all tables in the buffer."
4306 (save-excursion
4307 (save-restriction
4308 (widen)
4309 (goto-char (point-min))
4310 (while (re-search-forward org-table-any-line-regexp nil t)
4311 (unless quietly
4312 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4313 (beginning-of-line 1)
4314 (when (and (looking-at org-table-line-regexp)
4315 ;; Exclude tables in src/example/verbatim/clocktable blocks
4316 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4317 (save-excursion (funcall function))
4318 (or (looking-at org-table-line-regexp)
4319 (forward-char 1)))
4320 (re-search-forward org-table-any-border-regexp nil 1))))
4321 (unless quietly (message "Mapping tables: done")))
4323 ;; Declare and autoload functions from org-agenda.el
4325 (eval-and-compile
4326 (org-autoload "org-agenda"
4327 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4329 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4330 (declare-function org-clock-update-mode-line "org-clock" ())
4331 (declare-function org-resolve-clocks "org-clock"
4332 (&optional also-non-dangling-p prompt last-valid))
4334 (defun org-at-TBLFM-p (&optional pos)
4335 "Return t when point (or POS) is in #+TBLFM line."
4336 (save-excursion
4337 (let ((pos pos)))
4338 (goto-char (or pos (point)))
4339 (beginning-of-line 1)
4340 (looking-at org-TBLFM-regexp)))
4342 (defvar org-clock-start-time)
4343 (defvar org-clock-marker (make-marker)
4344 "Marker recording the last clock-in.")
4345 (defvar org-clock-hd-marker (make-marker)
4346 "Marker recording the last clock-in, but the headline position.")
4347 (defvar org-clock-heading ""
4348 "The heading of the current clock entry.")
4349 (defun org-clock-is-active ()
4350 "Return the buffer where the clock is currently running.
4351 Return nil if no clock is running."
4352 (marker-buffer org-clock-marker))
4354 (eval-and-compile
4355 (org-autoload "org-clock" '(org-clock-remove-overlays
4356 org-clock-update-time-maybe
4357 org-clocktable-shift)))
4359 (defun org-check-running-clock ()
4360 "Check if the current buffer contains the running clock.
4361 If yes, offer to stop it and to save the buffer with the changes."
4362 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4363 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4364 (buffer-name))))
4365 (org-clock-out)
4366 (when (y-or-n-p "Save changed buffer?")
4367 (save-buffer))))
4369 (defun org-clocktable-try-shift (dir n)
4370 "Check if this line starts a clock table, if yes, shift the time block."
4371 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4372 (org-clocktable-shift dir n)))
4374 ;;;###autoload
4375 (defun org-clock-persistence-insinuate ()
4376 "Set up hooks for clock persistence."
4377 (require 'org-clock)
4378 (add-hook 'org-mode-hook 'org-clock-load)
4379 (add-hook 'kill-emacs-hook 'org-clock-save))
4381 ;; Define the variable already here, to make sure we have it.
4382 (defvar org-indent-mode nil
4383 "Non-nil if Org-Indent mode is enabled.
4384 Use the command `org-indent-mode' to change this variable.")
4386 ;; Autoload archiving code
4387 ;; The stuff that is needed for cycling and tags has to be defined here.
4389 (defgroup org-archive nil
4390 "Options concerning archiving in Org-mode."
4391 :tag "Org Archive"
4392 :group 'org-structure)
4394 (defcustom org-archive-location "%s_archive::"
4395 "The location where subtrees should be archived.
4397 The value of this variable is a string, consisting of two parts,
4398 separated by a double-colon. The first part is a filename and
4399 the second part is a headline.
4401 When the filename is omitted, archiving happens in the same file.
4402 %s in the filename will be replaced by the current file
4403 name (without the directory part). Archiving to a different file
4404 is useful to keep archived entries from contributing to the
4405 Org-mode Agenda.
4407 The archived entries will be filed as subtrees of the specified
4408 headline. When the headline is omitted, the subtrees are simply
4409 filed away at the end of the file, as top-level entries. Also in
4410 the heading you can use %s to represent the file name, this can be
4411 useful when using the same archive for a number of different files.
4413 Here are a few examples:
4414 \"%s_archive::\"
4415 If the current file is Projects.org, archive in file
4416 Projects.org_archive, as top-level trees. This is the default.
4418 \"::* Archived Tasks\"
4419 Archive in the current file, under the top-level headline
4420 \"* Archived Tasks\".
4422 \"~/org/archive.org::\"
4423 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4425 \"~/org/archive.org::* From %s\"
4426 Archive in file ~/org/archive.org (absolute path), under headlines
4427 \"From FILENAME\" where file name is the current file name.
4429 \"~/org/datetree.org::datetree/* Finished Tasks\"
4430 The \"datetree/\" string is special, signifying to archive
4431 items to the datetree. Items are placed in either the CLOSED
4432 date of the item, or the current date if there is no CLOSED date.
4433 The heading will be a subentry to the current date. There doesn't
4434 need to be a heading, but there always needs to be a slash after
4435 datetree. For example, to store archived items directly in the
4436 datetree, use \"~/org/datetree.org::datetree/\".
4438 \"basement::** Finished Tasks\"
4439 Archive in file ./basement (relative path), as level 3 trees
4440 below the level 2 heading \"** Finished Tasks\".
4442 You may set this option on a per-file basis by adding to the buffer a
4443 line like
4445 #+ARCHIVE: basement::** Finished Tasks
4447 You may also define it locally for a subtree by setting an ARCHIVE property
4448 in the entry. If such a property is found in an entry, or anywhere up
4449 the hierarchy, it will be used."
4450 :group 'org-archive
4451 :type 'string)
4453 (defcustom org-archive-tag "ARCHIVE"
4454 "The tag that marks a subtree as archived.
4455 An archived subtree does not open during visibility cycling, and does
4456 not contribute to the agenda listings.
4457 After changing this, font-lock must be restarted in the relevant buffers to
4458 get the proper fontification."
4459 :group 'org-archive
4460 :group 'org-keywords
4461 :type 'string)
4463 (defcustom org-agenda-skip-archived-trees t
4464 "Non-nil means the agenda will skip any items located in archived trees.
4465 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4466 variable is no longer recommended, you should leave it at the value t.
4467 Instead, use the key `v' to cycle the archives-mode in the agenda."
4468 :group 'org-archive
4469 :group 'org-agenda-skip
4470 :type 'boolean)
4472 (defcustom org-columns-skip-archived-trees t
4473 "Non-nil means ignore archived trees when creating column view."
4474 :group 'org-archive
4475 :group 'org-properties
4476 :type 'boolean)
4478 (defcustom org-cycle-open-archived-trees nil
4479 "Non-nil means `org-cycle' will open archived trees.
4480 An archived tree is a tree marked with the tag ARCHIVE.
4481 When nil, archived trees will stay folded. You can still open them with
4482 normal outline commands like `show-all', but not with the cycling commands."
4483 :group 'org-archive
4484 :group 'org-cycle
4485 :type 'boolean)
4487 (defcustom org-sparse-tree-open-archived-trees nil
4488 "Non-nil means sparse tree construction shows matches in archived trees.
4489 When nil, matches in these trees are highlighted, but the trees are kept in
4490 collapsed state."
4491 :group 'org-archive
4492 :group 'org-sparse-trees
4493 :type 'boolean)
4495 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4496 "The default date type when building a sparse tree.
4497 When this is nil, a date is a scheduled or a deadline timestamp.
4498 Otherwise, these types are allowed:
4500 all: all timestamps
4501 active: only active timestamps (<...>)
4502 inactive: only inactive timestamps (<...)
4503 scheduled: only scheduled timestamps
4504 deadline: only deadline timestamps"
4505 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4506 (const :tag "All timestamps" all)
4507 (const :tag "Only active timestamps" active)
4508 (const :tag "Only inactive timestamps" inactive)
4509 (const :tag "Only scheduled timestamps" scheduled)
4510 (const :tag "Only deadline timestamps" deadline)
4511 (const :tag "Only closed timestamps" closed))
4512 :version "24.3"
4513 :group 'org-sparse-trees)
4515 (defun org-cycle-hide-archived-subtrees (state)
4516 "Re-hide all archived subtrees after a visibility state change."
4517 (when (and (not org-cycle-open-archived-trees)
4518 (not (memq state '(overview folded))))
4519 (save-excursion
4520 (let* ((globalp (memq state '(contents all)))
4521 (beg (if globalp (point-min) (point)))
4522 (end (if globalp (point-max) (org-end-of-subtree t))))
4523 (org-hide-archived-subtrees beg end)
4524 (goto-char beg)
4525 (if (looking-at (concat ".*:" org-archive-tag ":"))
4526 (message "%s" (substitute-command-keys
4527 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4529 (defun org-force-cycle-archived ()
4530 "Cycle subtree even if it is archived."
4531 (interactive)
4532 (setq this-command 'org-cycle)
4533 (let ((org-cycle-open-archived-trees t))
4534 (call-interactively 'org-cycle)))
4536 (defun org-hide-archived-subtrees (beg end)
4537 "Re-hide all archived subtrees after a visibility state change."
4538 (save-excursion
4539 (let* ((re (concat ":" org-archive-tag ":")))
4540 (goto-char beg)
4541 (while (re-search-forward re end t)
4542 (when (org-at-heading-p)
4543 (org-flag-subtree t)
4544 (org-end-of-subtree t))))))
4546 (declare-function outline-end-of-heading "outline" ())
4547 (declare-function outline-flag-region "outline" (from to flag))
4548 (defun org-flag-subtree (flag)
4549 (save-excursion
4550 (org-back-to-heading t)
4551 (outline-end-of-heading)
4552 (outline-flag-region (point)
4553 (progn (org-end-of-subtree t) (point))
4554 flag)))
4556 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4558 (eval-and-compile
4559 (org-autoload "org-archive"
4560 '(org-add-archive-files)))
4562 ;; Autoload Column View Code
4564 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4565 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4566 (declare-function org-columns-compute "org-colview" (property))
4568 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4569 '(org-columns-number-to-string
4570 org-columns-get-format-and-top-level
4571 org-columns-compute
4572 org-columns-remove-overlays))
4574 ;; Autoload ID code
4576 (declare-function org-id-store-link "org-id")
4577 (declare-function org-id-locations-load "org-id")
4578 (declare-function org-id-locations-save "org-id")
4579 (defvar org-id-track-globally)
4580 (org-autoload "org-id"
4581 '(org-id-new
4582 org-id-copy
4583 org-id-get-with-outline-path-completion
4584 org-id-get-with-outline-drilling))
4586 ;;; Variables for pre-computed regular expressions, all buffer local
4588 (defvar org-todo-regexp nil
4589 "Matches any of the TODO state keywords.")
4590 (make-variable-buffer-local 'org-todo-regexp)
4591 (defvar org-not-done-regexp nil
4592 "Matches any of the TODO state keywords except the last one.")
4593 (make-variable-buffer-local 'org-not-done-regexp)
4594 (defvar org-not-done-heading-regexp nil
4595 "Matches a TODO headline that is not done.")
4596 (make-variable-buffer-local 'org-not-done-regexp)
4597 (defvar org-todo-line-regexp nil
4598 "Matches a headline and puts TODO state into group 2 if present.")
4599 (make-variable-buffer-local 'org-todo-line-regexp)
4600 (defvar org-complex-heading-regexp nil
4601 "Matches a headline and puts everything into groups:
4602 group 1: the stars
4603 group 2: The todo keyword, maybe
4604 group 3: Priority cookie
4605 group 4: True headline
4606 group 5: Tags")
4607 (make-variable-buffer-local 'org-complex-heading-regexp)
4608 (defvar org-complex-heading-regexp-format nil
4609 "Printf format to make regexp to match an exact headline.
4610 This regexp will match the headline of any node which has the
4611 exact headline text that is put into the format, but may have any
4612 TODO state, priority and tags.")
4613 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4614 (defvar org-todo-line-tags-regexp nil
4615 "Matches a headline and puts TODO state into group 2 if present.
4616 Also put tags into group 4 if tags are present.")
4617 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4618 (defvar org-ds-keyword-length 12
4619 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4620 (make-variable-buffer-local 'org-ds-keyword-length)
4621 (defvar org-deadline-regexp nil
4622 "Matches the DEADLINE keyword.")
4623 (make-variable-buffer-local 'org-deadline-regexp)
4624 (defvar org-deadline-time-regexp nil
4625 "Matches the DEADLINE keyword together with a time stamp.")
4626 (make-variable-buffer-local 'org-deadline-time-regexp)
4627 (defvar org-deadline-time-hour-regexp nil
4628 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4629 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4630 (defvar org-deadline-line-regexp nil
4631 "Matches the DEADLINE keyword and the rest of the line.")
4632 (make-variable-buffer-local 'org-deadline-line-regexp)
4633 (defvar org-scheduled-regexp nil
4634 "Matches the SCHEDULED keyword.")
4635 (make-variable-buffer-local 'org-scheduled-regexp)
4636 (defvar org-scheduled-time-regexp nil
4637 "Matches the SCHEDULED keyword together with a time stamp.")
4638 (make-variable-buffer-local 'org-scheduled-time-regexp)
4639 (defvar org-scheduled-time-hour-regexp nil
4640 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4641 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4642 (defvar org-closed-time-regexp nil
4643 "Matches the CLOSED keyword together with a time stamp.")
4644 (make-variable-buffer-local 'org-closed-time-regexp)
4646 (defvar org-keyword-time-regexp nil
4647 "Matches any of the 4 keywords, together with the time stamp.")
4648 (make-variable-buffer-local 'org-keyword-time-regexp)
4649 (defvar org-keyword-time-not-clock-regexp nil
4650 "Matches any of the 3 keywords, together with the time stamp.")
4651 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4652 (defvar org-maybe-keyword-time-regexp nil
4653 "Matches a timestamp, possibly preceded by a keyword.")
4654 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4655 (defvar org-all-time-keywords nil
4656 "List of time keywords.")
4657 (make-variable-buffer-local 'org-all-time-keywords)
4659 (defconst org-plain-time-of-day-regexp
4660 (concat
4661 "\\(\\<[012]?[0-9]"
4662 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4663 "\\(--?"
4664 "\\(\\<[012]?[0-9]"
4665 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4666 "\\)?")
4667 "Regular expression to match a plain time or time range.
4668 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4669 groups carry important information:
4670 0 the full match
4671 1 the first time, range or not
4672 8 the second time, if it is a range.")
4674 (defconst org-plain-time-extension-regexp
4675 (concat
4676 "\\(\\<[012]?[0-9]"
4677 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4678 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4679 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4680 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4681 groups carry important information:
4682 0 the full match
4683 7 hours of duration
4684 9 minutes of duration")
4686 (defconst org-stamp-time-of-day-regexp
4687 (concat
4688 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4689 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4690 "\\(--?"
4691 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4692 "Regular expression to match a timestamp time or time range.
4693 After a match, the following groups carry important information:
4694 0 the full match
4695 1 date plus weekday, for back referencing to make sure both times are on the same day
4696 2 the first time, range or not
4697 4 the second time, if it is a range.")
4699 (defconst org-startup-options
4700 '(("fold" org-startup-folded t)
4701 ("overview" org-startup-folded t)
4702 ("nofold" org-startup-folded nil)
4703 ("showall" org-startup-folded nil)
4704 ("showeverything" org-startup-folded showeverything)
4705 ("content" org-startup-folded content)
4706 ("indent" org-startup-indented t)
4707 ("noindent" org-startup-indented nil)
4708 ("hidestars" org-hide-leading-stars t)
4709 ("showstars" org-hide-leading-stars nil)
4710 ("odd" org-odd-levels-only t)
4711 ("oddeven" org-odd-levels-only nil)
4712 ("align" org-startup-align-all-tables t)
4713 ("noalign" org-startup-align-all-tables nil)
4714 ("inlineimages" org-startup-with-inline-images t)
4715 ("noinlineimages" org-startup-with-inline-images nil)
4716 ("latexpreview" org-startup-with-latex-preview t)
4717 ("nolatexpreview" org-startup-with-latex-preview nil)
4718 ("customtime" org-display-custom-times t)
4719 ("logdone" org-log-done time)
4720 ("lognotedone" org-log-done note)
4721 ("nologdone" org-log-done nil)
4722 ("lognoteclock-out" org-log-note-clock-out t)
4723 ("nolognoteclock-out" org-log-note-clock-out nil)
4724 ("logrepeat" org-log-repeat state)
4725 ("lognoterepeat" org-log-repeat note)
4726 ("logdrawer" org-log-into-drawer t)
4727 ("nologdrawer" org-log-into-drawer nil)
4728 ("logstatesreversed" org-log-states-order-reversed t)
4729 ("nologstatesreversed" org-log-states-order-reversed nil)
4730 ("nologrepeat" org-log-repeat nil)
4731 ("logreschedule" org-log-reschedule time)
4732 ("lognotereschedule" org-log-reschedule note)
4733 ("nologreschedule" org-log-reschedule nil)
4734 ("logredeadline" org-log-redeadline time)
4735 ("lognoteredeadline" org-log-redeadline note)
4736 ("nologredeadline" org-log-redeadline nil)
4737 ("logrefile" org-log-refile time)
4738 ("lognoterefile" org-log-refile note)
4739 ("nologrefile" org-log-refile nil)
4740 ("fninline" org-footnote-define-inline t)
4741 ("nofninline" org-footnote-define-inline nil)
4742 ("fnlocal" org-footnote-section nil)
4743 ("fnauto" org-footnote-auto-label t)
4744 ("fnprompt" org-footnote-auto-label nil)
4745 ("fnconfirm" org-footnote-auto-label confirm)
4746 ("fnplain" org-footnote-auto-label plain)
4747 ("fnadjust" org-footnote-auto-adjust t)
4748 ("nofnadjust" org-footnote-auto-adjust nil)
4749 ("constcgs" constants-unit-system cgs)
4750 ("constSI" constants-unit-system SI)
4751 ("noptag" org-tag-persistent-alist nil)
4752 ("hideblocks" org-hide-block-startup t)
4753 ("nohideblocks" org-hide-block-startup nil)
4754 ("beamer" org-startup-with-beamer-mode t)
4755 ("entitiespretty" org-pretty-entities t)
4756 ("entitiesplain" org-pretty-entities nil))
4757 "Variable associated with STARTUP options for org-mode.
4758 Each element is a list of three items: the startup options (as written
4759 in the #+STARTUP line), the corresponding variable, and the value to set
4760 this variable to if the option is found. An optional forth element PUSH
4761 means to push this value onto the list in the variable.")
4763 (defun org-update-property-plist (key val props)
4764 "Update PROPS with KEY and VAL."
4765 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4766 (key (if appending (substring key 0 (- (length key) 1)) key))
4767 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4768 (previous (cdr (assoc key props))))
4769 (if appending
4770 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4771 (cons (cons key val) remainder))))
4773 (defconst org-block-regexp
4774 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4775 "Regular expression for hiding blocks.")
4776 (defconst org-heading-keyword-regexp-format
4777 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4778 "Printf format for a regexp matching a headline with some keyword.
4779 This regexp will match the headline of any node which has the
4780 exact keyword that is put into the format. The keyword isn't in
4781 any group by default, but the stars and the body are.")
4782 (defconst org-heading-keyword-maybe-regexp-format
4783 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4784 "Printf format for a regexp matching a headline, possibly with some keyword.
4785 This regexp can match any headline with the specified keyword, or
4786 without a keyword. The keyword isn't in any group by default,
4787 but the stars and the body are.")
4789 (defcustom org-group-tags t
4790 "When non-nil (the default), use group tags.
4791 This can be turned on/off through `org-toggle-tags-groups'."
4792 :group 'org-tags
4793 :group 'org-startup
4794 :type 'boolean)
4796 (defun org-toggle-tags-groups ()
4797 "Toggle support for group tags.
4798 Support for group tags is controlled by the option
4799 `org-group-tags', which is non-nil by default."
4800 (interactive)
4801 (setq org-group-tags (not org-group-tags))
4802 (cond ((and (derived-mode-p 'org-agenda-mode)
4803 org-group-tags)
4804 (org-agenda-redo))
4805 ((derived-mode-p 'org-mode)
4806 (let ((org-inhibit-startup t)) (org-mode))))
4807 (message "Groups tags support has been turned %s"
4808 (if org-group-tags "on" "off")))
4810 (defun org-set-regexps-and-options-for-tags ()
4811 "Precompute variables used for tags."
4812 (when (derived-mode-p 'org-mode)
4813 (org-set-local 'org-file-tags nil)
4814 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4815 (splitre "[ \t]+")
4816 (start 0)
4817 tags ftags key value)
4818 (save-excursion
4819 (save-restriction
4820 (widen)
4821 (goto-char (point-min))
4822 (while (re-search-forward re nil t)
4823 (setq key (upcase (org-match-string-no-properties 1))
4824 value (org-match-string-no-properties 2))
4825 (if (stringp value) (setq value (org-trim value)))
4826 (cond
4827 ((equal key "TAGS")
4828 (setq tags (append tags (if tags '("\\n") nil)
4829 (org-split-string value splitre))))
4830 ((equal key "FILETAGS")
4831 (when (string-match "\\S-" value)
4832 (setq ftags
4833 (append
4834 ftags
4835 (apply 'append
4836 (mapcar (lambda (x) (org-split-string x ":"))
4837 (org-split-string value)))))))))))
4838 ;; Process the file tags.
4839 (and ftags (org-set-local 'org-file-tags
4840 (mapcar 'org-add-prop-inherited ftags)))
4841 (org-set-local 'org-tag-groups-alist nil)
4842 ;; Process the tags.
4843 (when (and (not tags) org-tag-alist)
4844 (setq tags
4845 (mapcar
4846 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4847 ((eq (car tg) :endgroup) "}")
4848 ((eq (car tg) :grouptags) ":")
4849 ((eq (car tg) :newline) "\n")
4850 (t (concat (car tg)
4851 (if (characterp (cdr tg))
4852 (format "(%s)" (char-to-string (cdr tg))) "")))))
4853 org-tag-alist)))
4854 (let (e tgs g)
4855 (while (setq e (pop tags))
4856 (cond
4857 ((equal e "{")
4858 (progn (push '(:startgroup) tgs)
4859 (when (equal (nth 1 tags) ":")
4860 (push (list (replace-regexp-in-string
4861 "(.+)$" "" (nth 0 tags)))
4862 org-tag-groups-alist)
4863 (setq g 0))))
4864 ((equal e ":") (push '(:grouptags) tgs))
4865 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4866 ((equal e "\\n") (push '(:newline) tgs))
4867 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4868 (push (cons (match-string 1 e)
4869 (string-to-char (match-string 2 e))) tgs)
4870 (if (and g (> g 0))
4871 (setcar org-tag-groups-alist
4872 (append (car org-tag-groups-alist)
4873 (list (match-string 1 e)))))
4874 (if g (setq g (1+ g))))
4875 (t (push (list e) tgs)
4876 (if (and g (> g 0))
4877 (setcar org-tag-groups-alist
4878 (append (car org-tag-groups-alist) (list e))))
4879 (if g (setq g (1+ g))))))
4880 (org-set-local 'org-tag-alist nil)
4881 (while (setq e (pop tgs))
4882 (or (and (stringp (car e))
4883 (assoc (car e) org-tag-alist))
4884 (push e org-tag-alist)))
4885 ;; Return a list with tag variables
4886 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4888 (defvar org-ota nil)
4889 (defun org-set-regexps-and-options ()
4890 "Precompute regular expressions used in the current buffer."
4891 (when (derived-mode-p 'org-mode)
4892 (org-set-local 'org-todo-kwd-alist nil)
4893 (org-set-local 'org-todo-key-alist nil)
4894 (org-set-local 'org-todo-key-trigger nil)
4895 (org-set-local 'org-todo-keywords-1 nil)
4896 (org-set-local 'org-done-keywords nil)
4897 (org-set-local 'org-todo-heads nil)
4898 (org-set-local 'org-todo-sets nil)
4899 (org-set-local 'org-todo-log-states nil)
4900 (org-set-local 'org-file-properties nil)
4901 (let ((re (org-make-options-regexp
4902 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4903 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4904 "SETUPFILE" "OPTIONS")
4905 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4906 (splitre "[ \t]+")
4907 (scripts org-use-sub-superscripts)
4908 kwds kws0 kwsa key log value cat arch const links hw dws
4909 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4910 (start 0))
4911 (save-excursion
4912 (save-restriction
4913 (widen)
4914 (goto-char (point-min))
4915 (while
4916 (or (and
4917 ext-setup-or-nil
4918 (not org-ota)
4919 (let (ret)
4920 (with-temp-buffer
4921 (insert ext-setup-or-nil)
4922 (let ((major-mode 'org-mode) org-ota)
4923 (setq ret (save-match-data
4924 (org-set-regexps-and-options-for-tags)))))
4925 ;; Append setupfile tags to existing tags
4926 (setq org-ota t)
4927 (setq org-file-tags
4928 (delq nil (append org-file-tags (nth 0 ret)))
4929 org-tag-alist
4930 (delq nil (append org-tag-alist (nth 1 ret)))
4931 org-tag-groups-alist
4932 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4933 (and ext-setup-or-nil
4934 (string-match re ext-setup-or-nil start)
4935 (setq start (match-end 0)))
4936 (and (setq ext-setup-or-nil nil start 0)
4937 (re-search-forward re nil t)))
4938 (setq key (upcase (match-string 1 ext-setup-or-nil))
4939 value (org-match-string-no-properties 2 ext-setup-or-nil))
4940 (if (stringp value) (setq value (org-trim value)))
4941 (cond
4942 ((equal key "CATEGORY")
4943 (setq cat value))
4944 ((member key '("SEQ_TODO" "TODO"))
4945 (push (cons 'sequence (org-split-string value splitre)) kwds))
4946 ((equal key "TYP_TODO")
4947 (push (cons 'type (org-split-string value splitre)) kwds))
4948 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4949 ;; general TODO-like setup
4950 (push (cons (intern (downcase (match-string 1 key)))
4951 (org-split-string value splitre)) kwds))
4952 ((equal key "COLUMNS")
4953 (org-set-local 'org-columns-default-format value))
4954 ((equal key "LINK")
4955 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4956 (push (cons (match-string 1 value)
4957 (org-trim (match-string 2 value)))
4958 links)))
4959 ((equal key "PRIORITIES")
4960 (setq prio (org-split-string value " +")))
4961 ((equal key "PROPERTY")
4962 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4963 (setq props (org-update-property-plist (match-string 1 value)
4964 (match-string 2 value)
4965 props))))
4966 ((equal key "CONSTANTS")
4967 (org-table-set-constants))
4968 ((equal key "STARTUP")
4969 (let ((opts (org-split-string value splitre))
4970 l var val)
4971 (while (setq l (pop opts))
4972 (when (setq l (assoc l org-startup-options))
4973 (setq var (nth 1 l) val (nth 2 l))
4974 (if (not (nth 3 l))
4975 (set (make-local-variable var) val)
4976 (if (not (listp (symbol-value var)))
4977 (set (make-local-variable var) nil))
4978 (set (make-local-variable var) (symbol-value var))
4979 (add-to-list var val))))))
4980 ((equal key "ARCHIVE")
4981 (setq arch value)
4982 (remove-text-properties 0 (length arch)
4983 '(face t fontified t) arch))
4984 ((equal key "OPTIONS")
4985 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4986 (setq scripts (read (match-string 2 value)))))
4987 ((and (equal key "SETUPFILE")
4988 ;; Prevent checking in Gnus messages
4989 (not buffer-read-only))
4990 (setq setup-contents (org-file-contents
4991 (expand-file-name
4992 (org-remove-double-quotes value))
4993 'noerror))
4994 (if (not ext-setup-or-nil)
4995 (setq ext-setup-or-nil setup-contents start 0)
4996 (setq ext-setup-or-nil
4997 (concat (substring ext-setup-or-nil 0 start)
4998 "\n" setup-contents "\n"
4999 (substring ext-setup-or-nil start)))))))
5000 ;; search for property blocks
5001 (goto-char (point-min))
5002 (while (re-search-forward org-block-regexp nil t)
5003 (when (equal "PROPERTY" (upcase (match-string 1)))
5004 (setq value (replace-regexp-in-string
5005 "[\n\r]" " " (match-string 4)))
5006 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5007 (setq props (org-update-property-plist (match-string 1 value)
5008 (match-string 2 value)
5009 props)))))))
5010 (org-set-local 'org-use-sub-superscripts scripts)
5011 (when cat
5012 (org-set-local 'org-category (intern cat))
5013 (push (cons "CATEGORY" cat) props))
5014 (when prio
5015 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5016 (setq prio (mapcar 'string-to-char prio))
5017 (org-set-local 'org-highest-priority (nth 0 prio))
5018 (org-set-local 'org-lowest-priority (nth 1 prio))
5019 (org-set-local 'org-default-priority (nth 2 prio)))
5020 (and props (org-set-local 'org-file-properties (nreverse props)))
5021 (and arch (org-set-local 'org-archive-location arch))
5022 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5023 ;; Process the TODO keywords
5024 (unless kwds
5025 ;; Use the global values as if they had been given locally.
5026 (setq kwds (default-value 'org-todo-keywords))
5027 (if (stringp (car kwds))
5028 (setq kwds (list (cons org-todo-interpretation
5029 (default-value 'org-todo-keywords)))))
5030 (setq kwds (reverse kwds)))
5031 (setq kwds (nreverse kwds))
5032 (let (inter kws kw)
5033 (while (setq kws (pop kwds))
5034 (let ((kws (or
5035 (run-hook-with-args-until-success
5036 'org-todo-setup-filter-hook kws)
5037 kws)))
5038 (setq inter (pop kws) sep (member "|" kws)
5039 kws0 (delete "|" (copy-sequence kws))
5040 kwsa nil
5041 kws1 (mapcar
5042 (lambda (x)
5043 ;; 1 2
5044 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5045 (progn
5046 (setq kw (match-string 1 x)
5047 key (and (match-end 2) (match-string 2 x))
5048 log (org-extract-log-state-settings x))
5049 (push (cons kw (and key (string-to-char key))) kwsa)
5050 (and log (push log org-todo-log-states))
5052 (error "Invalid TODO keyword %s" x)))
5053 kws0)
5054 kwsa (if kwsa (append '((:startgroup))
5055 (nreverse kwsa)
5056 '((:endgroup))))
5057 hw (car kws1)
5058 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5059 tail (list inter hw (car dws) (org-last dws))))
5060 (add-to-list 'org-todo-heads hw 'append)
5061 (push kws1 org-todo-sets)
5062 (setq org-done-keywords (append org-done-keywords dws nil))
5063 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5064 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5065 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5066 (setq org-todo-sets (nreverse org-todo-sets)
5067 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5068 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5069 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5070 ;; Compute the regular expressions and other local variables.
5071 ;; Using `org-outline-regexp-bol' would complicate them much,
5072 ;; because of the fixed white space at the end of that string.
5073 (if (not org-done-keywords)
5074 (setq org-done-keywords (and org-todo-keywords-1
5075 (list (org-last org-todo-keywords-1)))))
5076 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5077 (length org-scheduled-string)
5078 (length org-clock-string)
5079 (length org-closed-string)))
5080 org-not-done-keywords
5081 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5082 org-todo-regexp
5083 (concat "\\("
5084 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5085 "\\)")
5086 org-not-done-regexp
5087 (concat "\\("
5088 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5089 "\\)")
5090 org-not-done-heading-regexp
5091 (format org-heading-keyword-regexp-format org-not-done-regexp)
5092 org-todo-line-regexp
5093 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5094 org-complex-heading-regexp
5095 (concat "^\\(\\*+\\)"
5096 "\\(?: +" org-todo-regexp "\\)?"
5097 "\\(?: +\\(\\[#.\\]\\)\\)?"
5098 "\\(?: +\\(.*?\\)\\)??"
5099 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5100 "[ \t]*$")
5101 org-complex-heading-regexp-format
5102 (concat "^\\(\\*+\\)"
5103 "\\(?: +" org-todo-regexp "\\)?"
5104 "\\(?: +\\(\\[#.\\]\\)\\)?"
5105 "\\(?: +"
5106 ;; Stats cookies can be stuck to body.
5107 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5108 "\\(%s\\)"
5109 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5110 "\\)"
5111 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5112 "[ \t]*$")
5113 org-todo-line-tags-regexp
5114 (concat "^\\(\\*+\\)"
5115 "\\(?: +" org-todo-regexp "\\)?"
5116 "\\(?: +\\(.*?\\)\\)??"
5117 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5118 "[ \t]*$")
5119 org-deadline-regexp (concat "\\<" org-deadline-string)
5120 org-deadline-time-regexp
5121 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5122 org-deadline-time-hour-regexp
5123 (concat "\\<" org-deadline-string
5124 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5125 org-deadline-line-regexp
5126 (concat "\\<\\(" org-deadline-string "\\).*")
5127 org-scheduled-regexp
5128 (concat "\\<" org-scheduled-string)
5129 org-scheduled-time-regexp
5130 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5131 org-scheduled-time-hour-regexp
5132 (concat "\\<" org-scheduled-string
5133 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5134 org-closed-time-regexp
5135 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5136 org-keyword-time-regexp
5137 (concat "\\<\\(" org-scheduled-string
5138 "\\|" org-deadline-string
5139 "\\|" org-closed-string
5140 "\\|" org-clock-string "\\)"
5141 " *[[<]\\([^]>]+\\)[]>]")
5142 org-keyword-time-not-clock-regexp
5143 (concat "\\<\\(" org-scheduled-string
5144 "\\|" org-deadline-string
5145 "\\|" org-closed-string
5146 "\\)"
5147 " *[[<]\\([^]>]+\\)[]>]")
5148 org-maybe-keyword-time-regexp
5149 (concat "\\(\\<\\(" org-scheduled-string
5150 "\\|" org-deadline-string
5151 "\\|" org-closed-string
5152 "\\|" org-clock-string "\\)\\)?"
5153 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5154 org-all-time-keywords
5155 (mapcar (lambda (w) (substring w 0 -1))
5156 (list org-scheduled-string org-deadline-string
5157 org-clock-string org-closed-string)))
5158 (setq org-ota nil)
5159 (org-compute-latex-and-related-regexp))))
5161 (defun org-file-contents (file &optional noerror)
5162 "Return the contents of FILE, as a string."
5163 (if (or (not file)
5164 (not (file-readable-p file)))
5165 (if noerror
5166 (message "Cannot read file \"%s\"" file)
5167 (error "Cannot read file \"%s\"" file))
5168 (with-temp-buffer
5169 (insert-file-contents file)
5170 (buffer-string))))
5172 (defun org-extract-log-state-settings (x)
5173 "Extract the log state setting from a TODO keyword string.
5174 This will extract info from a string like \"WAIT(w@/!)\"."
5175 (let (kw key log1 log2)
5176 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5177 (setq kw (match-string 1 x)
5178 key (and (match-end 2) (match-string 2 x))
5179 log1 (and (match-end 3) (match-string 3 x))
5180 log2 (and (match-end 4) (match-string 4 x)))
5181 (and (or log1 log2)
5182 (list kw
5183 (and log1 (if (equal log1 "!") 'time 'note))
5184 (and log2 (if (equal log2 "!") 'time 'note)))))))
5186 (defun org-remove-keyword-keys (list)
5187 "Remove a pair of parenthesis at the end of each string in LIST."
5188 (mapcar (lambda (x)
5189 (if (string-match "(.*)$" x)
5190 (substring x 0 (match-beginning 0))
5192 list))
5194 (defun org-assign-fast-keys (alist)
5195 "Assign fast keys to a keyword-key alist.
5196 Respect keys that are already there."
5197 (let (new e (alt ?0))
5198 (while (setq e (pop alist))
5199 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5200 (cdr e)) ;; Key already assigned.
5201 (push e new)
5202 (let ((clist (string-to-list (downcase (car e))))
5203 (used (append new alist)))
5204 (when (= (car clist) ?@)
5205 (pop clist))
5206 (while (and clist (rassoc (car clist) used))
5207 (pop clist))
5208 (unless clist
5209 (while (rassoc alt used)
5210 (incf alt)))
5211 (push (cons (car e) (or (car clist) alt)) new))))
5212 (nreverse new)))
5214 ;;; Some variables used in various places
5216 (defvar org-window-configuration nil
5217 "Used in various places to store a window configuration.")
5218 (defvar org-selected-window nil
5219 "Used in various places to store a window configuration.")
5220 (defvar org-finish-function nil
5221 "Function to be called when `C-c C-c' is used.
5222 This is for getting out of special buffers like capture.")
5225 ;; FIXME: Occasionally check by commenting these, to make sure
5226 ;; no other functions uses these, forgetting to let-bind them.
5227 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5228 (defvar org-last-state)
5229 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5231 ;; Defined somewhere in this file, but used before definition.
5232 (defvar org-entities) ;; defined in org-entities.el
5233 (defvar org-struct-menu)
5234 (defvar org-org-menu)
5235 (defvar org-tbl-menu)
5237 ;;;; Define the Org-mode
5239 ;; We use a before-change function to check if a table might need
5240 ;; an update.
5241 (defvar org-table-may-need-update t
5242 "Indicates that a table might need an update.
5243 This variable is set by `org-before-change-function'.
5244 `org-table-align' sets it back to nil.")
5245 (defun org-before-change-function (beg end)
5246 "Every change indicates that a table might need an update."
5247 (setq org-table-may-need-update t))
5248 (defvar org-mode-map)
5249 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5250 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5251 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5252 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5253 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5254 (defvar org-table-buffer-is-an nil)
5256 (defvar bidi-paragraph-direction)
5257 (defvar buffer-face-mode-face)
5259 (require 'outline)
5260 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5261 (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"))
5262 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5264 ;; Other stuff we need.
5265 (require 'time-date)
5266 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5267 (require 'easymenu)
5268 (require 'overlay)
5270 ;; (require 'org-macs) moved higher up in the file before it is first used
5271 (require 'org-entities)
5272 ;; (require 'org-compat) moved higher up in the file before it is first used
5273 (require 'org-faces)
5274 (require 'org-list)
5275 (require 'org-pcomplete)
5276 (require 'org-src)
5277 (require 'org-footnote)
5278 (require 'org-macro)
5280 ;; babel
5281 (require 'ob)
5283 ;;;###autoload
5284 (define-derived-mode org-mode outline-mode "Org"
5285 "Outline-based notes management and organizer, alias
5286 \"Carsten's outline-mode for keeping track of everything.\"
5288 Org-mode develops organizational tasks around a NOTES file which
5289 contains information about projects as plain text. Org-mode is
5290 implemented on top of outline-mode, which is ideal to keep the content
5291 of large files well structured. It supports ToDo items, deadlines and
5292 time stamps, which magically appear in the diary listing of the Emacs
5293 calendar. Tables are easily created with a built-in table editor.
5294 Plain text URL-like links connect to websites, emails (VM), Usenet
5295 messages (Gnus), BBDB entries, and any files related to the project.
5296 For printing and sharing of notes, an Org-mode file (or a part of it)
5297 can be exported as a structured ASCII or HTML file.
5299 The following commands are available:
5301 \\{org-mode-map}"
5303 ;; Get rid of Outline menus, they are not needed
5304 ;; Need to do this here because define-derived-mode sets up
5305 ;; the keymap so late. Still, it is a waste to call this each time
5306 ;; we switch another buffer into org-mode.
5307 (if (featurep 'xemacs)
5308 (when (boundp 'outline-mode-menu-heading)
5309 ;; Assume this is Greg's port, it uses easymenu
5310 (easy-menu-remove outline-mode-menu-heading)
5311 (easy-menu-remove outline-mode-menu-show)
5312 (easy-menu-remove outline-mode-menu-hide))
5313 (define-key org-mode-map [menu-bar headings] 'undefined)
5314 (define-key org-mode-map [menu-bar hide] 'undefined)
5315 (define-key org-mode-map [menu-bar show] 'undefined))
5317 (org-load-modules-maybe)
5318 (easy-menu-add org-org-menu)
5319 (easy-menu-add org-tbl-menu)
5320 (org-install-agenda-files-menu)
5321 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5322 (add-to-invisibility-spec '(org-cwidth))
5323 (add-to-invisibility-spec '(org-hide-block . t))
5324 (when (featurep 'xemacs)
5325 (org-set-local 'line-move-ignore-invisible t))
5326 (org-set-local 'outline-regexp org-outline-regexp)
5327 (org-set-local 'outline-level 'org-outline-level)
5328 (setq bidi-paragraph-direction 'left-to-right)
5329 (when (and org-ellipsis
5330 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5331 (fboundp 'make-glyph-code))
5332 (unless org-display-table
5333 (setq org-display-table (make-display-table)))
5334 (set-display-table-slot
5335 org-display-table 4
5336 (vconcat (mapcar
5337 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5338 org-ellipsis)))
5339 (if (stringp org-ellipsis) org-ellipsis "..."))))
5340 (setq buffer-display-table org-display-table))
5341 (org-set-regexps-and-options-for-tags)
5342 (org-set-regexps-and-options)
5343 (org-set-font-lock-defaults)
5344 (when (and org-tag-faces (not org-tags-special-faces-re))
5345 ;; tag faces set outside customize.... force initialization.
5346 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5347 ;; Calc embedded
5348 (org-set-local 'calc-embedded-open-mode "# ")
5349 ;; Modify a few syntax entries
5350 (modify-syntax-entry ?@ "w")
5351 (modify-syntax-entry ?\" "\"")
5352 (if org-startup-truncated (setq truncate-lines t))
5353 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5354 (org-set-local 'font-lock-unfontify-region-function
5355 'org-unfontify-region)
5356 ;; Activate before-change-function
5357 (org-set-local 'org-table-may-need-update t)
5358 (org-add-hook 'before-change-functions 'org-before-change-function nil
5359 'local)
5360 ;; Check for running clock before killing a buffer
5361 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5362 ;; Initialize macros templates.
5363 (org-macro-initialize-templates)
5364 ;; Initialize radio targets.
5365 (org-update-radio-target-regexp)
5366 ;; Indentation.
5367 (org-set-local 'indent-line-function 'org-indent-line)
5368 (org-set-local 'indent-region-function 'org-indent-region)
5369 ;; Filling and auto-filling.
5370 (org-setup-filling)
5371 ;; Comments.
5372 (org-setup-comments-handling)
5373 ;; Initialize cache.
5374 (org-element-cache-reset)
5375 ;; Beginning/end of defun
5376 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5377 (org-set-local 'end-of-defun-function 'org-forward-element)
5378 ;; Next error for sparse trees
5379 (org-set-local 'next-error-function 'org-occur-next-match)
5380 ;; Make sure dependence stuff works reliably, even for users who set it
5381 ;; too late :-(
5382 (if org-enforce-todo-dependencies
5383 (add-hook 'org-blocker-hook
5384 'org-block-todo-from-children-or-siblings-or-parent)
5385 (remove-hook 'org-blocker-hook
5386 'org-block-todo-from-children-or-siblings-or-parent))
5387 (if org-enforce-todo-checkbox-dependencies
5388 (add-hook 'org-blocker-hook
5389 'org-block-todo-from-checkboxes)
5390 (remove-hook 'org-blocker-hook
5391 'org-block-todo-from-checkboxes))
5393 ;; Align options lines
5394 (org-set-local
5395 'align-mode-rules-list
5396 '((org-in-buffer-settings
5397 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5398 (modes . '(org-mode)))))
5400 ;; Imenu
5401 (org-set-local 'imenu-create-index-function
5402 'org-imenu-get-tree)
5404 ;; Make isearch reveal context
5405 (if (or (featurep 'xemacs)
5406 (not (boundp 'outline-isearch-open-invisible-function)))
5407 ;; Emacs 21 and XEmacs make use of the hook
5408 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5409 ;; Emacs 22 deals with this through a special variable
5410 (org-set-local 'outline-isearch-open-invisible-function
5411 (lambda (&rest ignore) (org-show-context 'isearch)))
5412 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5414 ;; Setup the pcomplete hooks
5415 (set (make-local-variable 'pcomplete-command-completion-function)
5416 'org-pcomplete-initial)
5417 (set (make-local-variable 'pcomplete-command-name-function)
5418 'org-command-at-point)
5419 (set (make-local-variable 'pcomplete-default-completion-function)
5420 'ignore)
5421 (set (make-local-variable 'pcomplete-parse-arguments-function)
5422 'org-parse-arguments)
5423 (set (make-local-variable 'pcomplete-termination-string) "")
5424 (when (>= emacs-major-version 23)
5425 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5427 ;; If empty file that did not turn on org-mode automatically, make it to.
5428 (if (and org-insert-mode-line-in-empty-file
5429 (org-called-interactively-p 'any)
5430 (= (point-min) (point-max)))
5431 (insert "# -*- mode: org -*-\n\n"))
5432 (unless org-inhibit-startup
5433 (org-unmodified
5434 (and org-startup-with-beamer-mode (org-beamer-mode))
5435 (when org-startup-align-all-tables
5436 (org-table-map-tables 'org-table-align 'quietly))
5437 (when org-startup-with-inline-images
5438 (org-display-inline-images))
5439 (when org-startup-with-latex-preview
5440 (org-preview-latex-fragment))
5441 (unless org-inhibit-startup-visibility-stuff
5442 (org-set-startup-visibility))))
5443 ;; Try to set org-hide correctly
5444 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5446 ;; Update `customize-package-emacs-version-alist'
5447 (add-to-list 'customize-package-emacs-version-alist
5448 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5449 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5450 ("8.0" . "24.4")))
5452 (defvar org-mode-transpose-word-syntax-table
5453 (let ((st (make-syntax-table)))
5454 (mapc (lambda(c) (modify-syntax-entry
5455 (string-to-char (car c)) "w p" st))
5456 org-emphasis-alist)
5457 st))
5459 (when (fboundp 'abbrev-table-put)
5460 (abbrev-table-put org-mode-abbrev-table
5461 :parents (list text-mode-abbrev-table)))
5463 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5465 (defsubst org-fix-ellipsis-at-bol ()
5466 (save-excursion (goto-char (window-start)) (recenter 0)))
5468 (defun org-find-invisible-foreground ()
5469 (let ((candidates (remove
5470 "unspecified-bg"
5471 (nconc
5472 (list (face-background 'default)
5473 (face-background 'org-default))
5474 (mapcar
5475 (lambda (alist)
5476 (when (boundp alist)
5477 (cdr (assoc 'background-color (symbol-value alist)))))
5478 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5479 (list (face-foreground 'org-hide))))))
5480 (car (remove nil candidates))))
5482 (defun org-current-time (&optional rounding-minutes past)
5483 "Current time, possibly rounded to ROUNDING-MINUTES.
5484 When ROUNDING-MINUTES is not an integer, fall back on the car of
5485 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5486 the rounding returns a past time."
5487 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5488 (car org-time-stamp-rounding-minutes)))
5489 (time (decode-time)) res)
5490 (if (< r 1)
5491 (current-time)
5492 (setq res
5493 (apply 'encode-time
5494 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5495 (nthcdr 2 time))))
5496 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5497 (seconds-to-time (- (org-float-time res) (* r 60)))
5498 res))))
5500 (defun org-today ()
5501 "Return today date, considering `org-extend-today-until'."
5502 (time-to-days
5503 (time-subtract (current-time)
5504 (list 0 (* 3600 org-extend-today-until) 0))))
5506 ;;;; Font-Lock stuff, including the activators
5508 (defvar org-mouse-map (make-sparse-keymap))
5509 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5510 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5511 (when org-mouse-1-follows-link
5512 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5513 (when org-tab-follows-link
5514 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5515 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5517 (require 'font-lock)
5519 (defconst org-non-link-chars "]\t\n\r<>")
5520 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5521 "shell" "elisp" "doi" "message"))
5522 (defvar org-link-types-re nil
5523 "Matches a link that has a url-like prefix like \"http:\"")
5524 (defvar org-link-re-with-space nil
5525 "Matches a link with spaces, optional angular brackets around it.")
5526 (defvar org-link-re-with-space2 nil
5527 "Matches a link with spaces, optional angular brackets around it.")
5528 (defvar org-link-re-with-space3 nil
5529 "Matches a link with spaces, only for internal part in bracket links.")
5530 (defvar org-angle-link-re nil
5531 "Matches link with angular brackets, spaces are allowed.")
5532 (defvar org-plain-link-re nil
5533 "Matches plain link, without spaces.")
5534 (defvar org-bracket-link-regexp nil
5535 "Matches a link in double brackets.")
5536 (defvar org-bracket-link-analytic-regexp nil
5537 "Regular expression used to analyze links.
5538 Here is what the match groups contain after a match:
5539 1: http:
5540 2: http
5541 3: path
5542 4: [desc]
5543 5: desc")
5544 (defvar org-bracket-link-analytic-regexp++ nil
5545 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5546 (defvar org-any-link-re nil
5547 "Regular expression matching any link.")
5549 (defconst org-match-sexp-depth 3
5550 "Number of stacked braces for sub/superscript matching.")
5552 (defun org-create-multibrace-regexp (left right n)
5553 "Create a regular expression which will match a balanced sexp.
5554 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5555 as single character strings.
5556 The regexp returned will match the entire expression including the
5557 delimiters. It will also define a single group which contains the
5558 match except for the outermost delimiters. The maximum depth of
5559 stacked delimiters is N. Escaping delimiters is not possible."
5560 (let* ((nothing (concat "[^" left right "]*?"))
5561 (or "\\|")
5562 (re nothing)
5563 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5564 (while (> n 1)
5565 (setq n (1- n)
5566 re (concat re or next)
5567 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5568 (concat left "\\(" re "\\)" right)))
5570 (defvar org-match-substring-regexp
5571 (concat
5572 "\\(\\S-\\)\\([_^]\\)\\("
5573 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5574 "\\|"
5575 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5576 "\\|"
5577 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5578 "The regular expression matching a sub- or superscript.")
5580 (defvar org-match-substring-with-braces-regexp
5581 (concat
5582 "\\(\\S-\\)\\([_^]\\)\\("
5583 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5584 "\\)")
5585 "The regular expression matching a sub- or superscript, forcing braces.")
5587 (defun org-make-link-regexps ()
5588 "Update the link regular expressions.
5589 This should be called after the variable `org-link-types' has changed."
5590 (setq org-link-types-re
5591 (concat
5592 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5593 org-link-re-with-space
5594 (concat
5595 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5596 "\\([^" org-non-link-chars " ]"
5597 "[^" org-non-link-chars "]*"
5598 "[^" org-non-link-chars " ]\\)>?")
5599 org-link-re-with-space2
5600 (concat
5601 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5602 "\\([^" org-non-link-chars " ]"
5603 "[^\t\n\r]*"
5604 "[^" org-non-link-chars " ]\\)>?")
5605 org-link-re-with-space3
5606 (concat
5607 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5608 "\\([^" org-non-link-chars " ]"
5609 "[^\t\n\r]*\\)")
5610 org-angle-link-re
5611 (concat
5612 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5613 "\\([^" org-non-link-chars " ]"
5614 "[^" org-non-link-chars "]*"
5615 "\\)>")
5616 org-plain-link-re
5617 (concat
5618 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5619 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5620 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5621 org-bracket-link-regexp
5622 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5623 org-bracket-link-analytic-regexp
5624 (concat
5625 "\\[\\["
5626 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5627 "\\([^]]+\\)"
5628 "\\]"
5629 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5630 "\\]")
5631 org-bracket-link-analytic-regexp++
5632 (concat
5633 "\\[\\["
5634 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5635 "\\([^]]+\\)"
5636 "\\]"
5637 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5638 "\\]")
5639 org-any-link-re
5640 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5641 org-angle-link-re "\\)\\|\\("
5642 org-plain-link-re "\\)")))
5644 (org-make-link-regexps)
5646 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5647 "Regular expression for fast time stamp matching.")
5648 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5649 "Regular expression for fast time stamp matching.")
5650 (defconst org-ts-regexp0
5651 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5652 "Regular expression matching time strings for analysis.
5653 This one does not require the space after the date, so it can be used
5654 on a string that terminates immediately after the date.")
5655 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5656 "Regular expression matching time strings for analysis.")
5657 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5658 "Regular expression matching time stamps, with groups.")
5659 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5660 "Regular expression matching time stamps (also [..]), with groups.")
5661 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5662 "Regular expression matching a time stamp range.")
5663 (defconst org-tr-regexp-both
5664 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5665 "Regular expression matching a time stamp range.")
5666 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5667 org-ts-regexp "\\)?")
5668 "Regular expression matching a time stamp or time stamp range.")
5669 (defconst org-tsr-regexp-both
5670 (concat org-ts-regexp-both "\\(--?-?"
5671 org-ts-regexp-both "\\)?")
5672 "Regular expression matching a time stamp or time stamp range.
5673 The time stamps may be either active or inactive.")
5675 (defvar org-emph-face nil)
5677 (defun org-do-emphasis-faces (limit)
5678 "Run through the buffer and add overlays to emphasized strings."
5679 (let (rtn a)
5680 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5681 (if (not (= (char-after (match-beginning 3))
5682 (char-after (match-beginning 4))))
5683 (progn
5684 (setq rtn t)
5685 (setq a (assoc (match-string 3) org-emphasis-alist))
5686 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5687 'face
5688 (nth 1 a))
5689 (and (nth 2 a)
5690 (org-remove-flyspell-overlays-in
5691 (match-beginning 0) (match-end 0)))
5692 (add-text-properties (match-beginning 2) (match-end 2)
5693 '(font-lock-multiline t org-emphasis t))
5694 (when org-hide-emphasis-markers
5695 (add-text-properties (match-end 4) (match-beginning 5)
5696 '(invisible org-link))
5697 (add-text-properties (match-beginning 3) (match-end 3)
5698 '(invisible org-link)))))
5699 (backward-char 1))
5700 rtn))
5702 (defun org-emphasize (&optional char)
5703 "Insert or change an emphasis, i.e. a font like bold or italic.
5704 If there is an active region, change that region to a new emphasis.
5705 If there is no region, just insert the marker characters and position
5706 the cursor between them.
5707 CHAR should be the marker character. If it is a space, it means to
5708 remove the emphasis of the selected region.
5709 If CHAR is not given (for example in an interactive call) it will be
5710 prompted for."
5711 (interactive)
5712 (let ((erc org-emphasis-regexp-components)
5713 (prompt "")
5714 (string "") beg end move c s)
5715 (if (org-region-active-p)
5716 (setq beg (region-beginning) end (region-end)
5717 string (buffer-substring beg end))
5718 (setq move t))
5720 (unless char
5721 (message "Emphasis marker or tag: [%s]"
5722 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5723 (setq char (read-char-exclusive)))
5724 (if (equal char ?\ )
5725 (setq s "" move nil)
5726 (unless (assoc (char-to-string char) org-emphasis-alist)
5727 (user-error "No such emphasis marker: \"%c\"" char))
5728 (setq s (char-to-string char)))
5729 (while (and (> (length string) 1)
5730 (equal (substring string 0 1) (substring string -1))
5731 (assoc (substring string 0 1) org-emphasis-alist))
5732 (setq string (substring string 1 -1)))
5733 (setq string (concat s string s))
5734 (if beg (delete-region beg end))
5735 (unless (or (bolp)
5736 (string-match (concat "[" (nth 0 erc) "\n]")
5737 (char-to-string (char-before (point)))))
5738 (insert " "))
5739 (unless (or (eobp)
5740 (string-match (concat "[" (nth 1 erc) "\n]")
5741 (char-to-string (char-after (point)))))
5742 (insert " ") (backward-char 1))
5743 (insert string)
5744 (and move (backward-char 1))))
5746 (defconst org-nonsticky-props
5747 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5749 (defsubst org-rear-nonsticky-at (pos)
5750 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5752 (defun org-activate-plain-links (limit)
5753 "Run through the buffer and add overlays to links."
5754 (let (f hl)
5755 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5756 (not (org-in-src-block-p)))
5757 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5758 (setq f (get-text-property (match-beginning 0) 'face))
5759 (setq hl (org-match-string-no-properties 0))
5760 (if (or (eq f 'org-tag)
5761 (and (listp f) (memq 'org-tag f)))
5763 (add-text-properties (match-beginning 0) (match-end 0)
5764 (list 'mouse-face 'highlight
5765 'face 'org-link
5766 'htmlize-link `(:uri ,hl)
5767 'keymap org-mouse-map))
5768 (org-rear-nonsticky-at (match-end 0)))
5769 t)))
5771 (defun org-activate-code (limit)
5772 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5773 (progn
5774 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5775 (remove-text-properties (match-beginning 0) (match-end 0)
5776 '(display t invisible t intangible t))
5777 t)))
5779 (defcustom org-src-fontify-natively nil
5780 "When non-nil, fontify code in code blocks."
5781 :type 'boolean
5782 :version "24.1"
5783 :group 'org-appearance
5784 :group 'org-babel)
5786 (defcustom org-allow-promoting-top-level-subtree nil
5787 "When non-nil, allow promoting a top level subtree.
5788 The leading star of the top level headline will be replaced
5789 by a #."
5790 :type 'boolean
5791 :version "24.1"
5792 :group 'org-appearance)
5794 (defun org-fontify-meta-lines-and-blocks (limit)
5795 (condition-case nil
5796 (org-fontify-meta-lines-and-blocks-1 limit)
5797 (error (message "org-mode fontification error"))))
5799 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5800 "Fontify #+ lines and blocks."
5801 (let ((case-fold-search t))
5802 (if (re-search-forward
5803 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5804 limit t)
5805 (let ((beg (match-beginning 0))
5806 (block-start (match-end 0))
5807 (block-end nil)
5808 (lang (match-string 7))
5809 (beg1 (line-beginning-position 2))
5810 (dc1 (downcase (match-string 2)))
5811 (dc3 (downcase (match-string 3)))
5812 end end1 quoting block-type ovl)
5813 (cond
5814 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5815 ;; a single line of backend-specific content
5816 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5817 (remove-text-properties (match-beginning 0) (match-end 0)
5818 '(display t invisible t intangible t))
5819 (add-text-properties (match-beginning 1) (match-end 3)
5820 '(font-lock-fontified t face org-meta-line))
5821 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5822 '(font-lock-fontified t face org-block))
5823 ; for backend-specific code
5825 ((and (match-end 4) (equal dc3 "+begin"))
5826 ;; Truly a block
5827 (setq block-type (downcase (match-string 5))
5828 quoting (member block-type org-protecting-blocks))
5829 (when (re-search-forward
5830 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5831 nil t) ;; on purpose, we look further than LIMIT
5832 (setq end (min (point-max) (match-end 0))
5833 end1 (min (point-max) (1- (match-beginning 0))))
5834 (setq block-end (match-beginning 0))
5835 (when quoting
5836 (remove-text-properties beg end
5837 '(display t invisible t intangible t)))
5838 (add-text-properties
5839 beg end
5840 '(font-lock-fontified t font-lock-multiline t))
5841 (add-text-properties beg beg1 '(face org-meta-line))
5842 (add-text-properties end1 (min (point-max) (1+ end))
5843 '(face org-meta-line)) ; for end_src
5844 (cond
5845 ((and lang (not (string= lang "")) org-src-fontify-natively)
5846 (org-src-font-lock-fontify-block lang block-start block-end)
5847 ;; remove old background overlays
5848 (mapc (lambda (ov)
5849 (if (eq (overlay-get ov 'face) 'org-block-background)
5850 (delete-overlay ov)))
5851 (overlays-at (/ (+ beg1 block-end) 2)))
5852 ;; add a background overlay
5853 (setq ovl (make-overlay beg1 block-end))
5854 (overlay-put ovl 'face 'org-block-background)
5855 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5856 (quoting
5857 (add-text-properties beg1 (min (point-max) (1+ end1))
5858 '(face org-block))) ; end of source block
5859 ((not org-fontify-quote-and-verse-blocks))
5860 ((string= block-type "quote")
5861 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5862 ((string= block-type "verse")
5863 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5864 (add-text-properties beg beg1 '(face org-block-begin-line))
5865 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5866 '(face org-block-end-line))
5868 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5869 (add-text-properties
5870 beg (match-end 3)
5871 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5872 '(font-lock-fontified t invisible t)
5873 '(font-lock-fontified t face org-document-info-keyword)))
5874 (add-text-properties
5875 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5876 (if (string-equal dc1 "+title:")
5877 '(font-lock-fontified t face org-document-title)
5878 '(font-lock-fontified t face org-document-info))))
5879 ((or (equal dc1 "+results")
5880 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5881 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5882 "+call:" "+header:" "+headers:" "+name:"))
5883 (and (match-end 4) (equal dc3 "+attr")))
5884 (add-text-properties
5885 beg (match-end 0)
5886 '(font-lock-fontified t face org-meta-line))
5888 ((member dc3 '(" " ""))
5889 (add-text-properties
5890 beg (match-end 0)
5891 '(font-lock-fontified t face font-lock-comment-face)))
5892 ((not (member (char-after beg) '(?\ ?\t)))
5893 ;; just any other in-buffer setting, but not indented
5894 (add-text-properties
5895 beg (match-end 0)
5896 '(font-lock-fontified t face org-meta-line))
5898 (t nil))))))
5900 (defun org-activate-angle-links (limit)
5901 "Run through the buffer and add overlays to links."
5902 (if (and (re-search-forward org-angle-link-re limit t)
5903 (not (org-in-src-block-p)))
5904 (progn
5905 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5906 (add-text-properties (match-beginning 0) (match-end 0)
5907 (list 'mouse-face 'highlight
5908 'keymap org-mouse-map))
5909 (org-rear-nonsticky-at (match-end 0))
5910 t)))
5912 (defun org-activate-footnote-links (limit)
5913 "Run through the buffer and add overlays to footnotes."
5914 (let ((fn (org-footnote-next-reference-or-definition limit)))
5915 (when fn
5916 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5917 (org-remove-flyspell-overlays-in beg end)
5918 (add-text-properties beg end
5919 (list 'mouse-face 'highlight
5920 'keymap org-mouse-map
5921 'help-echo
5922 (if (= (point-at-bol) beg)
5923 "Footnote definition"
5924 "Footnote reference")
5925 'font-lock-fontified t
5926 'font-lock-multiline t
5927 'face 'org-footnote))))))
5929 (defun org-activate-bracket-links (limit)
5930 "Run through the buffer and add overlays to bracketed links."
5931 (if (and (re-search-forward org-bracket-link-regexp limit t)
5932 (not (org-in-src-block-p)))
5933 (let* ((hl (org-match-string-no-properties 1))
5934 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5935 (ip (org-maybe-intangible
5936 (list 'invisible 'org-link
5937 'keymap org-mouse-map 'mouse-face 'highlight
5938 'font-lock-multiline t 'help-echo help
5939 'htmlize-link `(:uri ,hl))))
5940 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5941 'font-lock-multiline t 'help-echo help
5942 'htmlize-link `(:uri ,hl))))
5943 ;; We need to remove the invisible property here. Table narrowing
5944 ;; may have made some of this invisible.
5945 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5946 (remove-text-properties (match-beginning 0) (match-end 0)
5947 '(invisible nil))
5948 (if (match-end 3)
5949 (progn
5950 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5951 (org-rear-nonsticky-at (match-beginning 3))
5952 (add-text-properties (match-beginning 3) (match-end 3) vp)
5953 (org-rear-nonsticky-at (match-end 3))
5954 (add-text-properties (match-end 3) (match-end 0) ip)
5955 (org-rear-nonsticky-at (match-end 0)))
5956 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5957 (org-rear-nonsticky-at (match-beginning 1))
5958 (add-text-properties (match-beginning 1) (match-end 1) vp)
5959 (org-rear-nonsticky-at (match-end 1))
5960 (add-text-properties (match-end 1) (match-end 0) ip)
5961 (org-rear-nonsticky-at (match-end 0)))
5962 t)))
5964 (defun org-activate-dates (limit)
5965 "Run through the buffer and add overlays to dates."
5966 (if (and (re-search-forward org-tsr-regexp-both limit t)
5967 (not (equal (char-before (match-beginning 0)) 91)))
5968 (progn
5969 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5970 (add-text-properties (match-beginning 0) (match-end 0)
5971 (list 'mouse-face 'highlight
5972 'keymap org-mouse-map))
5973 (org-rear-nonsticky-at (match-end 0))
5974 (when org-display-custom-times
5975 (if (match-end 3)
5976 (org-display-custom-time (match-beginning 3) (match-end 3)))
5977 (org-display-custom-time (match-beginning 1) (match-end 1)))
5978 t)))
5980 (defvar org-target-link-regexp nil
5981 "Regular expression matching radio targets in plain text.")
5982 (make-variable-buffer-local 'org-target-link-regexp)
5983 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5984 "Regular expression matching a link target.")
5985 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5986 "Regular expression matching a radio target.")
5987 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5988 "Regular expression matching any target.")
5990 (defun org-activate-target-links (limit)
5991 "Run through the buffer and add overlays to target matches."
5992 (when org-target-link-regexp
5993 (let ((case-fold-search t))
5994 (if (re-search-forward org-target-link-regexp limit t)
5995 (progn
5996 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5997 (add-text-properties (match-beginning 0) (match-end 0)
5998 (list 'mouse-face 'highlight
5999 'keymap org-mouse-map
6000 'help-echo "Radio target link"
6001 'org-linked-text t))
6002 (org-rear-nonsticky-at (match-end 0))
6003 t)))))
6005 (defun org-update-radio-target-regexp ()
6006 "Find all radio targets in this file and update the regular expression."
6007 (interactive)
6008 (when (memq 'radio org-activate-links)
6009 (setq org-target-link-regexp
6010 (org-make-target-link-regexp (org-all-targets 'radio)))
6011 (org-restart-font-lock)))
6013 (defun org-hide-wide-columns (limit)
6014 (let (s e)
6015 (setq s (text-property-any (point) (or limit (point-max))
6016 'org-cwidth t))
6017 (when s
6018 (setq e (next-single-property-change s 'org-cwidth))
6019 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6020 (goto-char e)
6021 t)))
6023 (defvar org-latex-and-related-regexp nil
6024 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6025 (defvar org-match-substring-regexp)
6026 (defvar org-match-substring-with-braces-regexp)
6028 (defun org-compute-latex-and-related-regexp ()
6029 "Compute regular expression for LaTeX, entities and sub/superscript.
6030 Result depends on variable `org-highlight-latex-and-related'."
6031 (org-set-local
6032 'org-latex-and-related-regexp
6033 (let* ((re-sub
6034 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6035 ((eq org-use-sub-superscripts '{})
6036 (list org-match-substring-with-braces-regexp))
6037 (org-use-sub-superscripts (list org-match-substring-regexp))))
6038 (re-latex
6039 (when (memq 'latex org-highlight-latex-and-related)
6040 (let ((matchers (plist-get org-format-latex-options :matchers)))
6041 (delq nil
6042 (mapcar (lambda (x)
6043 (and (member (car x) matchers) (nth 1 x)))
6044 org-latex-regexps)))))
6045 (re-entities
6046 (when (memq 'entities org-highlight-latex-and-related)
6047 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6048 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6050 (defun org-do-latex-and-related (limit)
6051 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6052 LIMIT bounds the search for syntax to highlight. Stop at first
6053 highlighted object, if any. Return t if some highlighting was
6054 done, nil otherwise."
6055 (when (org-string-nw-p org-latex-and-related-regexp)
6056 (catch 'found
6057 (while (re-search-forward org-latex-and-related-regexp limit t)
6058 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6059 'face))
6060 '(org-code org-verbatim underline))
6061 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6062 '(?_ ?^))
6064 0)))
6065 (font-lock-prepend-text-property
6066 (+ offset (match-beginning 0)) (match-end 0)
6067 'face 'org-latex-and-related)
6068 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6069 '(font-lock-multiline t)))
6070 (throw 'found t)))
6071 nil)))
6073 (defun org-restart-font-lock ()
6074 "Restart `font-lock-mode', to force refontification."
6075 (when (and (boundp 'font-lock-mode) font-lock-mode)
6076 (font-lock-mode -1)
6077 (font-lock-mode 1)))
6079 (defun org-all-targets (&optional radio)
6080 "Return a list of all targets in this file.
6081 When optional argument RADIO is non-nil, only find radio
6082 targets."
6083 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6084 (save-excursion
6085 (goto-char (point-min))
6086 (while (re-search-forward re nil t)
6087 ;; Make sure point is really within the object.
6088 (backward-char)
6089 (let ((obj (org-element-context)))
6090 (when (memq (org-element-type obj) '(radio-target target))
6091 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6092 rtn)))
6094 (defun org-make-target-link-regexp (targets)
6095 "Make regular expression matching all strings in TARGETS.
6096 The regular expression finds the targets also if there is a line break
6097 between words."
6098 (and targets
6099 (concat
6100 "\\<\\("
6101 (mapconcat
6102 (lambda (x)
6103 (setq x (regexp-quote x))
6104 (while (string-match " +" x)
6105 (setq x (replace-match "\\s-+" t t x)))
6107 targets
6108 "\\|")
6109 "\\)\\>")))
6111 (defun org-activate-tags (limit)
6112 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6113 (progn
6114 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6115 (add-text-properties (match-beginning 1) (match-end 1)
6116 (list 'mouse-face 'highlight
6117 'keymap org-mouse-map))
6118 (org-rear-nonsticky-at (match-end 1))
6119 t)))
6121 (defun org-outline-level ()
6122 "Compute the outline level of the heading at point.
6123 If this is called at a normal headline, the level is the number of stars.
6124 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6125 (save-excursion
6126 (if (not (condition-case nil
6127 (org-back-to-heading t)
6128 (error nil)))
6130 (looking-at org-outline-regexp)
6131 (1- (- (match-end 0) (match-beginning 0))))))
6133 (defvar org-font-lock-keywords nil)
6135 (defsubst org-re-property (property &optional literal)
6136 "Return a regexp matching a PROPERTY line.
6137 Match group 3 will be set to the value if it exists."
6138 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6139 (if literal property (regexp-quote property))
6140 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6142 (defconst org-property-re
6143 (org-re-property ".*?" 'literal)
6144 "Regular expression matching a property line.
6145 There are four matching groups:
6146 1: :PROPKEY: including the leading and trailing colon,
6147 2: PROPKEY without the leading and trailing colon,
6148 3: PROPVAL without leading or trailing spaces,
6149 4: the indentation of the current line,
6150 5: trailing whitespace.")
6152 (defvar org-font-lock-hook nil
6153 "Functions to be called for special font lock stuff.")
6155 (defvar org-font-lock-set-keywords-hook nil
6156 "Functions that can manipulate `org-font-lock-extra-keywords'.
6157 This is called after `org-font-lock-extra-keywords' is defined, but before
6158 it is installed to be used by font lock. This can be useful if something
6159 needs to be inserted at a specific position in the font-lock sequence.")
6161 (defun org-font-lock-hook (limit)
6162 "Run `org-font-lock-hook' within LIMIT."
6163 (run-hook-with-args 'org-font-lock-hook limit))
6165 (defun org-set-font-lock-defaults ()
6166 "Set font lock defaults for the current buffer."
6167 (let* ((em org-fontify-emphasized-text)
6168 (lk org-activate-links)
6169 (org-font-lock-extra-keywords
6170 (list
6171 ;; Call the hook
6172 '(org-font-lock-hook)
6173 ;; Headlines
6174 `(,(if org-fontify-whole-heading-line
6175 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6176 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6177 (1 (org-get-level-face 1))
6178 (2 (org-get-level-face 2))
6179 (3 (org-get-level-face 3)))
6180 ;; Table lines
6181 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6182 (1 'org-table t))
6183 ;; Table internals
6184 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6185 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6186 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6187 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6188 ;; Drawers
6189 (list org-drawer-regexp '(0 'org-special-keyword t))
6190 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6191 ;; Properties
6192 (list org-property-re
6193 '(1 'org-special-keyword t)
6194 '(3 'org-property-value t))
6195 ;; Links
6196 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6197 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6198 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6199 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6200 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6201 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6202 (if (memq 'footnote lk) '(org-activate-footnote-links))
6203 ;; Targets.
6204 (list org-any-target-regexp '(0 'org-target t))
6205 ;; Diary sexps.
6206 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6207 ;; Macro
6208 '("{{{.+}}}" (0 'org-macro t))
6209 '(org-hide-wide-columns (0 nil append))
6210 ;; TODO keyword
6211 (list (format org-heading-keyword-regexp-format
6212 org-todo-regexp)
6213 '(2 (org-get-todo-face 2) t))
6214 ;; DONE
6215 (if org-fontify-done-headline
6216 (list (format org-heading-keyword-regexp-format
6217 (concat
6218 "\\(?:"
6219 (mapconcat 'regexp-quote org-done-keywords "\\|")
6220 "\\)"))
6221 '(2 'org-headline-done t))
6222 nil)
6223 ;; Priorities
6224 '(org-font-lock-add-priority-faces)
6225 ;; Tags
6226 '(org-font-lock-add-tag-faces)
6227 ;; Tags groups
6228 (if (and org-group-tags org-tag-groups-alist)
6229 (list (concat org-outline-regexp-bol ".+\\(:"
6230 (regexp-opt (mapcar 'car org-tag-groups-alist))
6231 ":\\).*$")
6232 '(1 'org-tag-group prepend)))
6233 ;; Special keywords
6234 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6235 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6236 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6237 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6238 ;; Emphasis
6239 (if em
6240 (if (featurep 'xemacs)
6241 '(org-do-emphasis-faces (0 nil append))
6242 '(org-do-emphasis-faces)))
6243 ;; Checkboxes
6244 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6245 1 'org-checkbox prepend)
6246 (if (cdr (assq 'checkbox org-list-automatic-rules))
6247 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6248 (0 (org-get-checkbox-statistics-face) t)))
6249 ;; Description list items
6250 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6251 1 'org-list-dt prepend)
6252 ;; ARCHIVEd headings
6253 (list (concat
6254 org-outline-regexp-bol
6255 "\\(.*:" org-archive-tag ":.*\\)")
6256 '(1 'org-archived prepend))
6257 ;; Specials
6258 '(org-do-latex-and-related)
6259 '(org-fontify-entities)
6260 '(org-raise-scripts)
6261 ;; Code
6262 '(org-activate-code (1 'org-code t))
6263 ;; COMMENT
6264 (list (format org-heading-keyword-regexp-format
6265 (concat "\\("
6266 org-comment-string "\\|" org-quote-string
6267 "\\)"))
6268 '(2 'org-special-keyword t))
6269 ;; Blocks and meta lines
6270 '(org-fontify-meta-lines-and-blocks))))
6271 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6272 (run-hooks 'org-font-lock-set-keywords-hook)
6273 ;; Now set the full font-lock-keywords
6274 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6275 (org-set-local 'font-lock-defaults
6276 '(org-font-lock-keywords t nil nil backward-paragraph))
6277 (kill-local-variable 'font-lock-keywords) nil))
6279 (defun org-toggle-pretty-entities ()
6280 "Toggle the composition display of entities as UTF8 characters."
6281 (interactive)
6282 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6283 (org-restart-font-lock)
6284 (if org-pretty-entities
6285 (message "Entities are now displayed as UTF8 characters")
6286 (save-restriction
6287 (widen)
6288 (org-decompose-region (point-min) (point-max))
6289 (message "Entities are now displayed as plain text"))))
6291 (defvar org-custom-properties-overlays nil
6292 "List of overlays used for custom properties.")
6293 (make-variable-buffer-local 'org-custom-properties-overlays)
6295 (defun org-toggle-custom-properties-visibility ()
6296 "Display or hide properties in `org-custom-properties'."
6297 (interactive)
6298 (if org-custom-properties-overlays
6299 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6300 (setq org-custom-properties-overlays nil))
6301 (unless (not org-custom-properties)
6302 (save-excursion
6303 (save-restriction
6304 (widen)
6305 (goto-char (point-min))
6306 (while (re-search-forward org-property-re nil t)
6307 (mapc (lambda(p)
6308 (when (equal p (substring (match-string 1) 1 -1))
6309 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6310 (overlay-put o 'invisible t)
6311 (overlay-put o 'org-custom-property t)
6312 (push o org-custom-properties-overlays))))
6313 org-custom-properties)))))))
6315 (defun org-fontify-entities (limit)
6316 "Find an entity to fontify."
6317 (let (ee)
6318 (when org-pretty-entities
6319 (catch 'match
6320 (while (re-search-forward
6321 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6322 limit t)
6323 (if (and (not (org-in-indented-comment-line))
6324 (setq ee (org-entity-get (match-string 1)))
6325 (= (length (nth 6 ee)) 1))
6326 (let*
6327 ((end (if (equal (match-string 2) "{}")
6328 (match-end 2)
6329 (match-end 1))))
6330 (add-text-properties
6331 (match-beginning 0) end
6332 (list 'font-lock-fontified t))
6333 (compose-region (match-beginning 0) end
6334 (nth 6 ee) nil)
6335 (backward-char 1)
6336 (throw 'match t))))
6337 nil))))
6339 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6340 "Fontify string S like in Org-mode."
6341 (with-temp-buffer
6342 (insert s)
6343 (let ((org-odd-levels-only odd-levels))
6344 (org-mode)
6345 (font-lock-fontify-buffer)
6346 (buffer-string))))
6348 (defvar org-m nil)
6349 (defvar org-l nil)
6350 (defvar org-f nil)
6351 (defun org-get-level-face (n)
6352 "Get the right face for match N in font-lock matching of headlines."
6353 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6354 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6355 (if org-cycle-level-faces
6356 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6357 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6358 (cond
6359 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6360 ((eq n 2) org-f)
6361 (t (if org-level-color-stars-only nil org-f))))
6364 (defun org-get-todo-face (kwd)
6365 "Get the right face for a TODO keyword KWD.
6366 If KWD is a number, get the corresponding match group."
6367 (if (numberp kwd) (setq kwd (match-string kwd)))
6368 (or (org-face-from-face-or-color
6369 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6370 (and (member kwd org-done-keywords) 'org-done)
6371 'org-todo))
6373 (defun org-face-from-face-or-color (context inherit face-or-color)
6374 "Create a face list that inherits INHERIT, but sets the foreground color.
6375 When FACE-OR-COLOR is not a string, just return it."
6376 (if (stringp face-or-color)
6377 (list :inherit inherit
6378 (cdr (assoc context org-faces-easy-properties))
6379 face-or-color)
6380 face-or-color))
6382 (defun org-font-lock-add-tag-faces (limit)
6383 "Add the special tag faces."
6384 (when (and org-tag-faces org-tags-special-faces-re)
6385 (while (re-search-forward org-tags-special-faces-re limit t)
6386 (add-text-properties (match-beginning 1) (match-end 1)
6387 (list 'face (org-get-tag-face 1)
6388 'font-lock-fontified t))
6389 (backward-char 1))))
6391 (defun org-font-lock-add-priority-faces (limit)
6392 "Add the special priority faces."
6393 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6394 (when (save-match-data (org-at-heading-p))
6395 (add-text-properties
6396 (match-beginning 0) (match-end 0)
6397 (list 'face (or (org-face-from-face-or-color
6398 'priority 'org-priority
6399 (cdr (assoc (char-after (match-beginning 1))
6400 org-priority-faces)))
6401 'org-priority)
6402 'font-lock-fontified t)))))
6404 (defun org-get-tag-face (kwd)
6405 "Get the right face for a TODO keyword KWD.
6406 If KWD is a number, get the corresponding match group."
6407 (if (numberp kwd) (setq kwd (match-string kwd)))
6408 (or (org-face-from-face-or-color
6409 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6410 'org-tag))
6412 (defun org-unfontify-region (beg end &optional maybe_loudly)
6413 "Remove fontification and activation overlays from links."
6414 (font-lock-default-unfontify-region beg end)
6415 (let* ((buffer-undo-list t)
6416 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6417 (inhibit-modification-hooks t)
6418 deactivate-mark buffer-file-name buffer-file-truename)
6419 (org-decompose-region beg end)
6420 (remove-text-properties beg end
6421 '(mouse-face t keymap t org-linked-text t
6422 invisible t intangible t
6423 org-no-flyspell t org-emphasis t))
6424 (org-remove-font-lock-display-properties beg end)))
6426 (defconst org-script-display '(((raise -0.3) (height 0.7))
6427 ((raise 0.3) (height 0.7))
6428 ((raise -0.5))
6429 ((raise 0.5)))
6430 "Display properties for showing superscripts and subscripts.")
6432 (defun org-remove-font-lock-display-properties (beg end)
6433 "Remove specific display properties that have been added by font lock.
6434 The will remove the raise properties that are used to show superscripts
6435 and subscripts."
6436 (let (next prop)
6437 (while (< beg end)
6438 (setq next (next-single-property-change beg 'display nil end)
6439 prop (get-text-property beg 'display))
6440 (if (member prop org-script-display)
6441 (put-text-property beg next 'display nil))
6442 (setq beg next))))
6444 (defun org-raise-scripts (limit)
6445 "Add raise properties to sub/superscripts."
6446 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6447 (if (re-search-forward
6448 (if (eq org-use-sub-superscripts t)
6449 org-match-substring-regexp
6450 org-match-substring-with-braces-regexp)
6451 limit t)
6452 (let* ((pos (point)) table-p comment-p
6453 (mpos (match-beginning 3))
6454 (emph-p (get-text-property mpos 'org-emphasis))
6455 (link-p (get-text-property mpos 'mouse-face))
6456 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6457 (goto-char (point-at-bol))
6458 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6459 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6460 (goto-char pos)
6461 ;; Handle a_b^c
6462 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6463 (if (or comment-p emph-p link-p keyw-p)
6465 (put-text-property (match-beginning 3) (match-end 0)
6466 'display
6467 (if (equal (char-after (match-beginning 2)) ?^)
6468 (nth (if table-p 3 1) org-script-display)
6469 (nth (if table-p 2 0) org-script-display)))
6470 (add-text-properties (match-beginning 2) (match-end 2)
6471 (list 'invisible t
6472 'org-dwidth t 'org-dwidth-n 1))
6473 (if (and (eq (char-after (match-beginning 3)) ?{)
6474 (eq (char-before (match-end 3)) ?}))
6475 (progn
6476 (add-text-properties
6477 (match-beginning 3) (1+ (match-beginning 3))
6478 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6479 (add-text-properties
6480 (1- (match-end 3)) (match-end 3)
6481 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6482 t)))))
6484 ;;;; Visibility cycling, including org-goto and indirect buffer
6486 ;;; Cycling
6488 (defvar org-cycle-global-status nil)
6489 (make-variable-buffer-local 'org-cycle-global-status)
6490 (put 'org-cycle-global-status 'org-state t)
6491 (defvar org-cycle-subtree-status nil)
6492 (make-variable-buffer-local 'org-cycle-subtree-status)
6493 (put 'org-cycle-subtree-status 'org-state t)
6495 (defvar org-inlinetask-min-level)
6497 (defun org-unlogged-message (&rest args)
6498 "Display a message, but avoid logging it in the *Messages* buffer."
6499 (let ((message-log-max nil))
6500 (apply 'message args)))
6502 ;;;###autoload
6503 (defun org-cycle (&optional arg)
6504 "TAB-action and visibility cycling for Org-mode.
6506 This is the command invoked in Org-mode by the TAB key. Its main purpose
6507 is outline visibility cycling, but it also invokes other actions
6508 in special contexts.
6510 - When this function is called with a prefix argument, rotate the entire
6511 buffer through 3 states (global cycling)
6512 1. OVERVIEW: Show only top-level headlines.
6513 2. CONTENTS: Show all headlines of all levels, but no body text.
6514 3. SHOW ALL: Show everything.
6515 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6516 determined by the variable `org-startup-folded', and by any VISIBILITY
6517 properties in the buffer.
6518 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6519 including any drawers.
6521 - When inside a table, re-align the table and move to the next field.
6523 - When point is at the beginning of a headline, rotate the subtree started
6524 by this line through 3 different states (local cycling)
6525 1. FOLDED: Only the main headline is shown.
6526 2. CHILDREN: The main headline and the direct children are shown.
6527 From this state, you can move to one of the children
6528 and zoom in further.
6529 3. SUBTREE: Show the entire subtree, including body text.
6530 If there is no subtree, switch directly from CHILDREN to FOLDED.
6532 - When point is at the beginning of an empty headline and the variable
6533 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6534 of the headline by demoting and promoting it to likely levels. This
6535 speeds up creation document structure by pressing TAB once or several
6536 times right after creating a new headline.
6538 - When there is a numeric prefix, go up to a heading with level ARG, do
6539 a `show-subtree' and return to the previous cursor position. If ARG
6540 is negative, go up that many levels.
6542 - When point is not at the beginning of a headline, execute the global
6543 binding for TAB, which is re-indenting the line. See the option
6544 `org-cycle-emulate-tab' for details.
6546 - Special case: if point is at the beginning of the buffer and there is
6547 no headline in line 1, this function will act as if called with prefix arg
6548 (C-u TAB, same as S-TAB) also when called without prefix arg.
6549 But only if also the variable `org-cycle-global-at-bob' is t."
6550 (interactive "P")
6551 (org-load-modules-maybe)
6552 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6553 (and org-cycle-level-after-item/entry-creation
6554 (or (org-cycle-level)
6555 (org-cycle-item-indentation))))
6556 (let* ((limit-level
6557 (or org-cycle-max-level
6558 (and (boundp 'org-inlinetask-min-level)
6559 org-inlinetask-min-level
6560 (1- org-inlinetask-min-level))))
6561 (nstars (and limit-level
6562 (if org-odd-levels-only
6563 (and limit-level (1- (* limit-level 2)))
6564 limit-level)))
6565 (org-outline-regexp
6566 (if (not (derived-mode-p 'org-mode))
6567 outline-regexp
6568 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6569 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6570 (not (looking-at org-outline-regexp))))
6571 (org-cycle-hook
6572 (if bob-special
6573 (delq 'org-optimize-window-after-visibility-change
6574 (copy-sequence org-cycle-hook))
6575 org-cycle-hook))
6576 (pos (point)))
6578 (if (or bob-special (equal arg '(4)))
6579 ;; special case: use global cycling
6580 (setq arg t))
6582 (cond
6584 ((equal arg '(16))
6585 (setq last-command 'dummy)
6586 (org-set-startup-visibility)
6587 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6589 ((equal arg '(64))
6590 (show-all)
6591 (org-unlogged-message "Entire buffer visible, including drawers"))
6593 ;; Table: enter it or move to the next field.
6594 ((org-at-table-p 'any)
6595 (if (org-at-table.el-p)
6596 (message "Use C-c ' to edit table.el tables")
6597 (if arg (org-table-edit-field t)
6598 (org-table-justify-field-maybe)
6599 (call-interactively 'org-table-next-field))))
6601 ((run-hook-with-args-until-success
6602 'org-tab-after-check-for-table-hook))
6604 ;; Global cycling: delegate to `org-cycle-internal-global'.
6605 ((eq arg t) (org-cycle-internal-global))
6607 ;; Drawers: delegate to `org-flag-drawer'.
6608 ((save-excursion
6609 (beginning-of-line 1)
6610 (looking-at org-drawer-regexp))
6611 (org-flag-drawer ; toggle block visibility
6612 (not (get-char-property (match-end 0) 'invisible))))
6614 ;; Show-subtree, ARG levels up from here.
6615 ((integerp arg)
6616 (save-excursion
6617 (org-back-to-heading)
6618 (outline-up-heading (if (< arg 0) (- arg)
6619 (- (funcall outline-level) arg)))
6620 (org-show-subtree)))
6622 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6623 ((and (featurep 'org-inlinetask)
6624 (org-inlinetask-at-task-p)
6625 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6626 (org-inlinetask-toggle-visibility))
6628 ((org-try-cdlatex-tab))
6630 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6631 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6632 (save-excursion (beginning-of-line 1)
6633 (looking-at org-outline-regexp)))
6634 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6635 (org-cycle-internal-local))
6637 ;; From there: TAB emulation and template completion.
6638 (buffer-read-only (org-back-to-heading))
6640 ((run-hook-with-args-until-success
6641 'org-tab-after-check-for-cycling-hook))
6643 ((org-try-structure-completion))
6645 ((run-hook-with-args-until-success
6646 'org-tab-before-tab-emulation-hook))
6648 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6649 (or (not (bolp))
6650 (not (looking-at org-outline-regexp))))
6651 (call-interactively (global-key-binding "\t")))
6653 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6654 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6655 (or (and (eq org-cycle-emulate-tab 'white)
6656 (= (match-end 0) (point-at-eol)))
6657 (and (eq org-cycle-emulate-tab 'whitestart)
6658 (>= (match-end 0) pos))))
6660 (eq org-cycle-emulate-tab t))
6661 (call-interactively (global-key-binding "\t")))
6663 (t (save-excursion
6664 (org-back-to-heading)
6665 (org-cycle)))))))
6667 (defun org-cycle-internal-global ()
6668 "Do the global cycling action."
6669 ;; Hack to avoid display of messages for .org attachments in Gnus
6670 (let ((ga (string-match "\\*fontification" (buffer-name))))
6671 (cond
6672 ((and (eq last-command this-command)
6673 (eq org-cycle-global-status 'overview))
6674 ;; We just created the overview - now do table of contents
6675 ;; This can be slow in very large buffers, so indicate action
6676 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6677 (unless ga (org-unlogged-message "CONTENTS..."))
6678 (org-content)
6679 (unless ga (org-unlogged-message "CONTENTS...done"))
6680 (setq org-cycle-global-status 'contents)
6681 (run-hook-with-args 'org-cycle-hook 'contents))
6683 ((and (eq last-command this-command)
6684 (eq org-cycle-global-status 'contents))
6685 ;; We just showed the table of contents - now show everything
6686 (run-hook-with-args 'org-pre-cycle-hook 'all)
6687 (show-all)
6688 (unless ga (org-unlogged-message "SHOW ALL"))
6689 (setq org-cycle-global-status 'all)
6690 (run-hook-with-args 'org-cycle-hook 'all))
6693 ;; Default action: go to overview
6694 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6695 (org-overview)
6696 (unless ga (org-unlogged-message "OVERVIEW"))
6697 (setq org-cycle-global-status 'overview)
6698 (run-hook-with-args 'org-cycle-hook 'overview)))))
6700 (defun org-cycle-internal-local ()
6701 "Do the local cycling action."
6702 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6703 ;; First, determine end of headline (EOH), end of subtree or item
6704 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6705 (save-excursion
6706 (if (org-at-item-p)
6707 (progn
6708 (beginning-of-line)
6709 (setq struct (org-list-struct))
6710 (setq eoh (point-at-eol))
6711 (setq eos (org-list-get-item-end-before-blank (point) struct))
6712 (setq has-children (org-list-has-child-p (point) struct)))
6713 (org-back-to-heading)
6714 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6715 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6716 (setq has-children
6717 (or (save-excursion
6718 (let ((level (funcall outline-level)))
6719 (outline-next-heading)
6720 (and (org-at-heading-p t)
6721 (> (funcall outline-level) level))))
6722 (save-excursion
6723 (org-list-search-forward (org-item-beginning-re) eos t)))))
6724 ;; Determine end invisible part of buffer (EOL)
6725 (beginning-of-line 2)
6726 ;; XEmacs doesn't have `next-single-char-property-change'
6727 (if (featurep 'xemacs)
6728 (while (and (not (eobp)) ;; this is like `next-line'
6729 (get-char-property (1- (point)) 'invisible))
6730 (beginning-of-line 2))
6731 (while (and (not (eobp)) ;; this is like `next-line'
6732 (get-char-property (1- (point)) 'invisible))
6733 (goto-char (next-single-char-property-change (point) 'invisible))
6734 (and (eolp) (beginning-of-line 2))))
6735 (setq eol (point)))
6736 ;; Find out what to do next and set `this-command'
6737 (cond
6738 ((= eos eoh)
6739 ;; Nothing is hidden behind this heading
6740 (unless (org-before-first-heading-p)
6741 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6742 (org-unlogged-message "EMPTY ENTRY")
6743 (setq org-cycle-subtree-status nil)
6744 (save-excursion
6745 (goto-char eos)
6746 (outline-next-heading)
6747 (if (outline-invisible-p) (org-flag-heading nil))))
6748 ((and (or (>= eol eos)
6749 (not (string-match "\\S-" (buffer-substring eol eos))))
6750 (or has-children
6751 (not (setq children-skipped
6752 org-cycle-skip-children-state-if-no-children))))
6753 ;; Entire subtree is hidden in one line: children view
6754 (unless (org-before-first-heading-p)
6755 (run-hook-with-args 'org-pre-cycle-hook 'children))
6756 (if (org-at-item-p)
6757 (org-list-set-item-visibility (point-at-bol) struct 'children)
6758 (org-show-entry)
6759 (org-with-limited-levels (show-children))
6760 ;; FIXME: This slows down the func way too much.
6761 ;; How keep drawers hidden in subtree anyway?
6762 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6763 ;; (org-cycle-hide-drawers 'subtree))
6765 ;; Fold every list in subtree to top-level items.
6766 (when (eq org-cycle-include-plain-lists 'integrate)
6767 (save-excursion
6768 (org-back-to-heading)
6769 (while (org-list-search-forward (org-item-beginning-re) eos t)
6770 (beginning-of-line 1)
6771 (let* ((struct (org-list-struct))
6772 (prevs (org-list-prevs-alist struct))
6773 (end (org-list-get-bottom-point struct)))
6774 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6775 (org-list-get-all-items (point) struct prevs))
6776 (goto-char (if (< end eos) end eos)))))))
6777 (org-unlogged-message "CHILDREN")
6778 (save-excursion
6779 (goto-char eos)
6780 (outline-next-heading)
6781 (if (outline-invisible-p) (org-flag-heading nil)))
6782 (setq org-cycle-subtree-status 'children)
6783 (unless (org-before-first-heading-p)
6784 (run-hook-with-args 'org-cycle-hook 'children)))
6785 ((or children-skipped
6786 (and (eq last-command this-command)
6787 (eq org-cycle-subtree-status 'children)))
6788 ;; We just showed the children, or no children are there,
6789 ;; now show everything.
6790 (unless (org-before-first-heading-p)
6791 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6792 (outline-flag-region eoh eos nil)
6793 (org-unlogged-message
6794 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6795 (setq org-cycle-subtree-status 'subtree)
6796 (unless (org-before-first-heading-p)
6797 (run-hook-with-args 'org-cycle-hook 'subtree)))
6799 ;; Default action: hide the subtree.
6800 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6801 (outline-flag-region eoh eos t)
6802 (org-unlogged-message "FOLDED")
6803 (setq org-cycle-subtree-status 'folded)
6804 (unless (org-before-first-heading-p)
6805 (run-hook-with-args 'org-cycle-hook 'folded))))))
6807 ;;;###autoload
6808 (defun org-global-cycle (&optional arg)
6809 "Cycle the global visibility. For details see `org-cycle'.
6810 With \\[universal-argument] prefix arg, switch to startup visibility.
6811 With a numeric prefix, show all headlines up to that level."
6812 (interactive "P")
6813 (let ((org-cycle-include-plain-lists
6814 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6815 (cond
6816 ((integerp arg)
6817 (show-all)
6818 (hide-sublevels arg)
6819 (setq org-cycle-global-status 'contents))
6820 ((equal arg '(4))
6821 (org-set-startup-visibility)
6822 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6824 (org-cycle '(4))))))
6826 (defun org-set-startup-visibility ()
6827 "Set the visibility required by startup options and properties."
6828 (cond
6829 ((eq org-startup-folded t)
6830 (org-cycle '(4)))
6831 ((eq org-startup-folded 'content)
6832 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6833 (org-cycle '(4)) (org-cycle '(4)))))
6834 (unless (eq org-startup-folded 'showeverything)
6835 (if org-hide-block-startup (org-hide-block-all))
6836 (org-set-visibility-according-to-property 'no-cleanup)
6837 (org-cycle-hide-archived-subtrees 'all)
6838 (org-cycle-hide-drawers 'all)
6839 (org-cycle-show-empty-lines t)))
6841 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6842 "Switch subtree visibilities according to :VISIBILITY: property."
6843 (interactive)
6844 (let (org-show-entry-below state)
6845 (save-excursion
6846 (goto-char (point-min))
6847 (while (re-search-forward
6848 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6849 nil t)
6850 (setq state (match-string 1))
6851 (save-excursion
6852 (org-back-to-heading t)
6853 (hide-subtree)
6854 (org-reveal)
6855 (cond
6856 ((equal state '("fold" "folded"))
6857 (hide-subtree))
6858 ((equal state "children")
6859 (org-show-hidden-entry)
6860 (show-children))
6861 ((equal state "content")
6862 (save-excursion
6863 (save-restriction
6864 (org-narrow-to-subtree)
6865 (org-content))))
6866 ((member state '("all" "showall"))
6867 (show-subtree)))))
6868 (unless no-cleanup
6869 (org-cycle-hide-archived-subtrees 'all)
6870 (org-cycle-hide-drawers 'all)
6871 (org-cycle-show-empty-lines 'all)))))
6873 ;; This function uses outline-regexp instead of the more fundamental
6874 ;; org-outline-regexp so that org-cycle-global works outside of Org
6875 ;; buffers, where outline-regexp is needed.
6876 (defun org-overview ()
6877 "Switch to overview mode, showing only top-level headlines.
6878 Really, this shows all headlines with level equal or greater than the level
6879 of the first headline in the buffer. This is important, because if the
6880 first headline is not level one, then (hide-sublevels 1) gives confusing
6881 results."
6882 (interactive)
6883 (let ((pos (point))
6884 (level (save-excursion
6885 (goto-char (point-min))
6886 (if (re-search-forward (concat "^" outline-regexp) nil t)
6887 (progn
6888 (goto-char (match-beginning 0))
6889 (funcall outline-level))))))
6890 (and level (hide-sublevels level))
6891 (recenter '(4))
6892 (goto-char pos)))
6894 (defun org-content (&optional arg)
6895 "Show all headlines in the buffer, like a table of contents.
6896 With numerical argument N, show content up to level N."
6897 (interactive "P")
6898 (save-excursion
6899 ;; Visit all headings and show their offspring
6900 (and (integerp arg) (org-overview))
6901 (goto-char (point-max))
6902 (catch 'exit
6903 (while (and (progn (condition-case nil
6904 (outline-previous-visible-heading 1)
6905 (error (goto-char (point-min))))
6907 (looking-at org-outline-regexp))
6908 (if (integerp arg)
6909 (show-children (1- arg))
6910 (show-branches))
6911 (if (bobp) (throw 'exit nil))))))
6914 (defun org-optimize-window-after-visibility-change (state)
6915 "Adjust the window after a change in outline visibility.
6916 This function is the default value of the hook `org-cycle-hook'."
6917 (when (get-buffer-window (current-buffer))
6918 (cond
6919 ((eq state 'content) nil)
6920 ((eq state 'all) nil)
6921 ((eq state 'folded) nil)
6922 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6923 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6925 (defun org-remove-empty-overlays-at (pos)
6926 "Remove outline overlays that do not contain non-white stuff."
6927 (mapc
6928 (lambda (o)
6929 (and (eq 'outline (overlay-get o 'invisible))
6930 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6931 (overlay-end o))))
6932 (delete-overlay o)))
6933 (overlays-at pos)))
6935 (defun org-clean-visibility-after-subtree-move ()
6936 "Fix visibility issues after moving a subtree."
6937 ;; First, find a reasonable region to look at:
6938 ;; Start two siblings above, end three below
6939 (let* ((beg (save-excursion
6940 (and (org-get-last-sibling)
6941 (org-get-last-sibling))
6942 (point)))
6943 (end (save-excursion
6944 (and (org-get-next-sibling)
6945 (org-get-next-sibling)
6946 (org-get-next-sibling))
6947 (if (org-at-heading-p)
6948 (point-at-eol)
6949 (point))))
6950 (level (looking-at "\\*+"))
6951 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6952 (save-excursion
6953 (save-restriction
6954 (narrow-to-region beg end)
6955 (when re
6956 ;; Properly fold already folded siblings
6957 (goto-char (point-min))
6958 (while (re-search-forward re nil t)
6959 (if (and (not (outline-invisible-p))
6960 (save-excursion
6961 (goto-char (point-at-eol)) (outline-invisible-p)))
6962 (hide-entry))))
6963 (org-cycle-show-empty-lines 'overview)
6964 (org-cycle-hide-drawers 'overview)))))
6966 (defun org-cycle-show-empty-lines (state)
6967 "Show empty lines above all visible headlines.
6968 The region to be covered depends on STATE when called through
6969 `org-cycle-hook'. Lisp program can use t for STATE to get the
6970 entire buffer covered. Note that an empty line is only shown if there
6971 are at least `org-cycle-separator-lines' empty lines before the headline."
6972 (when (not (= org-cycle-separator-lines 0))
6973 (save-excursion
6974 (let* ((n (abs org-cycle-separator-lines))
6975 (re (cond
6976 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6977 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6978 (t (let ((ns (number-to-string (- n 2))))
6979 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6980 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6981 beg end b e)
6982 (cond
6983 ((memq state '(overview contents t))
6984 (setq beg (point-min) end (point-max)))
6985 ((memq state '(children folded))
6986 (setq beg (point) end (progn (org-end-of-subtree t t)
6987 (beginning-of-line 2)
6988 (point)))))
6989 (when beg
6990 (goto-char beg)
6991 (while (re-search-forward re end t)
6992 (unless (get-char-property (match-end 1) 'invisible)
6993 (setq e (match-end 1))
6994 (if (< org-cycle-separator-lines 0)
6995 (setq b (save-excursion
6996 (goto-char (match-beginning 0))
6997 (org-back-over-empty-lines)
6998 (if (save-excursion
6999 (goto-char (max (point-min) (1- (point))))
7000 (org-at-heading-p))
7001 (1- (point))
7002 (point))))
7003 (setq b (match-beginning 1)))
7004 (outline-flag-region b e nil)))))))
7005 ;; Never hide empty lines at the end of the file.
7006 (save-excursion
7007 (goto-char (point-max))
7008 (outline-previous-heading)
7009 (outline-end-of-heading)
7010 (if (and (looking-at "[ \t\n]+")
7011 (= (match-end 0) (point-max)))
7012 (outline-flag-region (point) (match-end 0) nil))))
7014 (defun org-show-empty-lines-in-parent ()
7015 "Move to the parent and re-show empty lines before visible headlines."
7016 (save-excursion
7017 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7018 (org-cycle-show-empty-lines context))))
7020 (defun org-files-list ()
7021 "Return `org-agenda-files' list, plus all open org-mode files.
7022 This is useful for operations that need to scan all of a user's
7023 open and agenda-wise Org files."
7024 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7025 (dolist (buf (buffer-list))
7026 (with-current-buffer buf
7027 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7028 (let ((file (expand-file-name (buffer-file-name))))
7029 (unless (member file files)
7030 (push file files))))))
7031 files))
7033 (defsubst org-entry-beginning-position ()
7034 "Return the beginning position of the current entry."
7035 (save-excursion (outline-back-to-heading t) (point)))
7037 (defsubst org-entry-end-position ()
7038 "Return the end position of the current entry."
7039 (save-excursion (outline-next-heading) (point)))
7041 (defun org-cycle-hide-drawers (state &optional exceptions)
7042 "Re-hide all drawers after a visibility state change.
7043 When non-nil, optional argument EXCEPTIONS is a list of strings
7044 specifying which drawers should not be hidden."
7045 (when (and (derived-mode-p 'org-mode)
7046 (not (memq state '(overview folded contents))))
7047 (save-excursion
7048 (let* ((globalp (memq state '(contents all)))
7049 (beg (if globalp (point-min) (point)))
7050 (end (if globalp (point-max)
7051 (if (eq state 'children)
7052 (save-excursion (outline-next-heading) (point))
7053 (org-end-of-subtree t)))))
7054 (goto-char beg)
7055 (while (re-search-forward org-drawer-regexp end t)
7056 (unless (member-ignore-case (match-string 1) exceptions)
7057 (org-flag-drawer t)))))))
7059 (defun org-cycle-hide-inline-tasks (state)
7060 "Re-hide inline task when switching to 'contents visibility state."
7061 (when (and (eq state 'contents)
7062 (boundp 'org-inlinetask-min-level)
7063 org-inlinetask-min-level)
7064 (hide-sublevels (1- org-inlinetask-min-level))))
7066 (defun org-flag-drawer (flag &optional element)
7067 "When FLAG is non-nil, hide the drawer we are at.
7068 Otherwise make it visible. When optional argument ELEMENT is
7069 a parsed drawer, as returned by `org-element-at-point', hide or
7070 show that drawer instead."
7071 (let ((drawer (or element (org-element-at-point))))
7072 (when (memq (org-element-type drawer) '(drawer property-drawer))
7073 (save-excursion
7074 (goto-char (org-element-property :post-affiliated drawer))
7075 (outline-flag-region
7076 (line-end-position)
7077 (progn (goto-char (org-element-property :end drawer))
7078 (skip-chars-backward " \r\t\n")
7079 (line-end-position))
7080 flag)))))
7082 (defun org-subtree-end-visible-p ()
7083 "Is the end of the current subtree visible?"
7084 (pos-visible-in-window-p
7085 (save-excursion (org-end-of-subtree t) (point))))
7087 (defun org-first-headline-recenter (&optional N)
7088 "Move cursor to the first headline and recenter the headline.
7089 Optional argument N means put the headline into the Nth line of the window."
7090 (goto-char (point-min))
7091 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7092 (beginning-of-line)
7093 (recenter (prefix-numeric-value N))))
7095 ;;; Saving and restoring visibility
7097 (defun org-outline-overlay-data (&optional use-markers)
7098 "Return a list of the locations of all outline overlays.
7099 These are overlays with the `invisible' property value `outline'.
7100 The return value is a list of cons cells, with start and stop
7101 positions for each overlay.
7102 If USE-MARKERS is set, return the positions as markers."
7103 (let (beg end)
7104 (save-excursion
7105 (save-restriction
7106 (widen)
7107 (delq nil
7108 (mapcar (lambda (o)
7109 (when (eq (overlay-get o 'invisible) 'outline)
7110 (setq beg (overlay-start o)
7111 end (overlay-end o))
7112 (and beg end (> end beg)
7113 (if use-markers
7114 (cons (move-marker (make-marker) beg)
7115 (move-marker (make-marker) end))
7116 (cons beg end)))))
7117 (overlays-in (point-min) (point-max))))))))
7119 (defun org-set-outline-overlay-data (data)
7120 "Create visibility overlays for all positions in DATA.
7121 DATA should have been made by `org-outline-overlay-data'."
7122 (let (o)
7123 (save-excursion
7124 (save-restriction
7125 (widen)
7126 (show-all)
7127 (mapc (lambda (c)
7128 (outline-flag-region (car c) (cdr c) t))
7129 data)))))
7131 ;;; Folding of blocks
7133 (defvar org-hide-block-overlays nil
7134 "Overlays hiding blocks.")
7135 (make-variable-buffer-local 'org-hide-block-overlays)
7137 (defun org-block-map (function &optional start end)
7138 "Call FUNCTION at the head of all source blocks in the current buffer.
7139 Optional arguments START and END can be used to limit the range."
7140 (let ((start (or start (point-min)))
7141 (end (or end (point-max))))
7142 (save-excursion
7143 (goto-char start)
7144 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7145 (save-excursion
7146 (save-match-data
7147 (goto-char (match-beginning 0))
7148 (funcall function)))))))
7150 (defun org-hide-block-toggle-all ()
7151 "Toggle the visibility of all blocks in the current buffer."
7152 (org-block-map #'org-hide-block-toggle))
7154 (defun org-hide-block-all ()
7155 "Fold all blocks in the current buffer."
7156 (interactive)
7157 (org-show-block-all)
7158 (org-block-map #'org-hide-block-toggle-maybe))
7160 (defun org-show-block-all ()
7161 "Unfold all blocks in the current buffer."
7162 (interactive)
7163 (mapc 'delete-overlay org-hide-block-overlays)
7164 (setq org-hide-block-overlays nil))
7166 (defun org-hide-block-toggle-maybe ()
7167 "Toggle visibility of block at point."
7168 (interactive)
7169 (let ((case-fold-search t))
7170 (if (save-excursion
7171 (beginning-of-line 1)
7172 (looking-at org-block-regexp))
7173 (progn (org-hide-block-toggle)
7174 t) ;; to signal that we took action
7175 nil))) ;; to signal that we did not
7177 (defun org-hide-block-toggle (&optional force)
7178 "Toggle the visibility of the current block."
7179 (interactive)
7180 (save-excursion
7181 (beginning-of-line)
7182 (if (re-search-forward org-block-regexp nil t)
7183 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7184 (end (match-end 0)) ;; end of entire body
7186 (if (memq t (mapcar (lambda (overlay)
7187 (eq (overlay-get overlay 'invisible)
7188 'org-hide-block))
7189 (overlays-at start)))
7190 (if (or (not force) (eq force 'off))
7191 (mapc (lambda (ov)
7192 (when (member ov org-hide-block-overlays)
7193 (setq org-hide-block-overlays
7194 (delq ov org-hide-block-overlays)))
7195 (when (eq (overlay-get ov 'invisible)
7196 'org-hide-block)
7197 (delete-overlay ov)))
7198 (overlays-at start)))
7199 (setq ov (make-overlay start end))
7200 (overlay-put ov 'invisible 'org-hide-block)
7201 ;; make the block accessible to isearch
7202 (overlay-put
7203 ov 'isearch-open-invisible
7204 (lambda (ov)
7205 (when (member ov org-hide-block-overlays)
7206 (setq org-hide-block-overlays
7207 (delq ov org-hide-block-overlays)))
7208 (when (eq (overlay-get ov 'invisible)
7209 'org-hide-block)
7210 (delete-overlay ov))))
7211 (push ov org-hide-block-overlays)))
7212 (user-error "Not looking at a source block"))))
7214 ;; org-tab-after-check-for-cycling-hook
7215 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7216 ;; Remove overlays when changing major mode
7217 (add-hook 'org-mode-hook
7218 (lambda () (org-add-hook 'change-major-mode-hook
7219 'org-show-block-all 'append 'local)))
7221 ;;; Org-goto
7223 (defvar org-goto-window-configuration nil)
7224 (defvar org-goto-marker nil)
7225 (defvar org-goto-map)
7226 (defun org-goto-map ()
7227 "Set the keymap `org-goto'."
7228 (setq org-goto-map
7229 (let ((map (make-sparse-keymap)))
7230 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7231 mouse-drag-region universal-argument org-occur))
7232 cmd)
7233 (while (setq cmd (pop cmds))
7234 (substitute-key-definition cmd cmd map global-map)))
7235 (suppress-keymap map)
7236 (org-defkey map "\C-m" 'org-goto-ret)
7237 (org-defkey map [(return)] 'org-goto-ret)
7238 (org-defkey map [(left)] 'org-goto-left)
7239 (org-defkey map [(right)] 'org-goto-right)
7240 (org-defkey map [(control ?g)] 'org-goto-quit)
7241 (org-defkey map "\C-i" 'org-cycle)
7242 (org-defkey map [(tab)] 'org-cycle)
7243 (org-defkey map [(down)] 'outline-next-visible-heading)
7244 (org-defkey map [(up)] 'outline-previous-visible-heading)
7245 (if org-goto-auto-isearch
7246 (if (fboundp 'define-key-after)
7247 (define-key-after map [t] 'org-goto-local-auto-isearch)
7248 nil)
7249 (org-defkey map "q" 'org-goto-quit)
7250 (org-defkey map "n" 'outline-next-visible-heading)
7251 (org-defkey map "p" 'outline-previous-visible-heading)
7252 (org-defkey map "f" 'outline-forward-same-level)
7253 (org-defkey map "b" 'outline-backward-same-level)
7254 (org-defkey map "u" 'outline-up-heading))
7255 (org-defkey map "/" 'org-occur)
7256 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7257 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7258 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7259 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7260 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7261 map)))
7263 (defconst org-goto-help
7264 "Browse buffer copy, to find location or copy text.%s
7265 RET=jump to location C-g=quit and return to previous location
7266 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7268 (defvar org-goto-start-pos) ; dynamically scoped parameter
7270 (defun org-goto (&optional alternative-interface)
7271 "Look up a different location in the current file, keeping current visibility.
7273 When you want look-up or go to a different location in a
7274 document, the fastest way is often to fold the entire buffer and
7275 then dive into the tree. This method has the disadvantage, that
7276 the previous location will be folded, which may not be what you
7277 want.
7279 This command works around this by showing a copy of the current
7280 buffer in an indirect buffer, in overview mode. You can dive
7281 into the tree in that copy, use org-occur and incremental search
7282 to find a location. When pressing RET or `Q', the command
7283 returns to the original buffer in which the visibility is still
7284 unchanged. After RET it will also jump to the location selected
7285 in the indirect buffer and expose the headline hierarchy above.
7287 With a prefix argument, use the alternative interface: e.g. if
7288 `org-goto-interface' is 'outline use 'outline-path-completion."
7289 (interactive "P")
7290 (org-goto-map)
7291 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7292 (org-refile-use-outline-path t)
7293 (org-refile-target-verify-function nil)
7294 (interface
7295 (if (not alternative-interface)
7296 org-goto-interface
7297 (if (eq org-goto-interface 'outline)
7298 'outline-path-completion
7299 'outline)))
7300 (org-goto-start-pos (point))
7301 (selected-point
7302 (if (eq interface 'outline)
7303 (car (org-get-location (current-buffer) org-goto-help))
7304 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7305 (org-refile-check-position pa)
7306 (nth 3 pa)))))
7307 (if selected-point
7308 (progn
7309 (org-mark-ring-push org-goto-start-pos)
7310 (goto-char selected-point)
7311 (if (or (outline-invisible-p) (org-invisible-p2))
7312 (org-show-context 'org-goto)))
7313 (message "Quit"))))
7315 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7316 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7317 (defvar org-goto-local-auto-isearch-map) ; defined below
7319 (defun org-get-location (buf help)
7320 "Let the user select a location in the Org-mode buffer BUF.
7321 This function uses a recursive edit. It returns the selected position
7322 or nil."
7323 (org-no-popups
7324 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7325 (isearch-hide-immediately nil)
7326 (isearch-search-fun-function
7327 (lambda () 'org-goto-local-search-headings))
7328 (org-goto-selected-point org-goto-exit-command))
7329 (save-excursion
7330 (save-window-excursion
7331 (delete-other-windows)
7332 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7333 (org-pop-to-buffer-same-window
7334 (condition-case nil
7335 (make-indirect-buffer (current-buffer) "*org-goto*")
7336 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7337 (with-output-to-temp-buffer "*Org Help*"
7338 (princ (format help (if org-goto-auto-isearch
7339 " Just type for auto-isearch."
7340 " n/p/f/b/u to navigate, q to quit."))))
7341 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7342 (setq buffer-read-only nil)
7343 (let ((org-startup-truncated t)
7344 (org-startup-folded nil)
7345 (org-startup-align-all-tables nil))
7346 (org-mode)
7347 (org-overview))
7348 (setq buffer-read-only t)
7349 (if (and (boundp 'org-goto-start-pos)
7350 (integer-or-marker-p org-goto-start-pos))
7351 (let ((org-show-hierarchy-above t)
7352 (org-show-siblings t)
7353 (org-show-following-heading t))
7354 (goto-char org-goto-start-pos)
7355 (and (outline-invisible-p) (org-show-context)))
7356 (goto-char (point-min)))
7357 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7358 (message "Select location and press RET")
7359 (use-local-map org-goto-map)
7360 (recursive-edit)))
7361 (kill-buffer "*org-goto*")
7362 (cons org-goto-selected-point org-goto-exit-command))))
7364 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7365 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7366 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7367 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7369 (defun org-goto-local-search-headings (string bound noerror)
7370 "Search and make sure that any matches are in headlines."
7371 (catch 'return
7372 (while (if isearch-forward
7373 (search-forward string bound noerror)
7374 (search-backward string bound noerror))
7375 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7376 (and (member :headline context)
7377 (not (member :tags context))))
7378 (throw 'return (point))))))
7380 (defun org-goto-local-auto-isearch ()
7381 "Start isearch."
7382 (interactive)
7383 (goto-char (point-min))
7384 (let ((keys (this-command-keys)))
7385 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7386 (isearch-mode t)
7387 (isearch-process-search-char (string-to-char keys)))))
7389 (defun org-goto-ret (&optional arg)
7390 "Finish `org-goto' by going to the new location."
7391 (interactive "P")
7392 (setq org-goto-selected-point (point)
7393 org-goto-exit-command 'return)
7394 (throw 'exit nil))
7396 (defun org-goto-left ()
7397 "Finish `org-goto' by going to the new location."
7398 (interactive)
7399 (if (org-at-heading-p)
7400 (progn
7401 (beginning-of-line 1)
7402 (setq org-goto-selected-point (point)
7403 org-goto-exit-command 'left)
7404 (throw 'exit nil))
7405 (user-error "Not on a heading")))
7407 (defun org-goto-right ()
7408 "Finish `org-goto' by going to the new location."
7409 (interactive)
7410 (if (org-at-heading-p)
7411 (progn
7412 (setq org-goto-selected-point (point)
7413 org-goto-exit-command 'right)
7414 (throw 'exit nil))
7415 (user-error "Not on a heading")))
7417 (defun org-goto-quit ()
7418 "Finish `org-goto' without cursor motion."
7419 (interactive)
7420 (setq org-goto-selected-point nil)
7421 (setq org-goto-exit-command 'quit)
7422 (throw 'exit nil))
7424 ;;; Indirect buffer display of subtrees
7426 (defvar org-indirect-dedicated-frame nil
7427 "This is the frame being used for indirect tree display.")
7428 (defvar org-last-indirect-buffer nil)
7430 (defun org-tree-to-indirect-buffer (&optional arg)
7431 "Create indirect buffer and narrow it to current subtree.
7432 With a numerical prefix ARG, go up to this level and then take that tree.
7433 If ARG is negative, go up that many levels.
7435 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7436 indirect buffer previously made with this command, to avoid proliferation of
7437 indirect buffers. However, when you call the command with a \
7438 \\[universal-argument] prefix, or
7439 when `org-indirect-buffer-display' is `new-frame', the last buffer
7440 is kept so that you can work with several indirect buffers at the same time.
7441 If `org-indirect-buffer-display' is `dedicated-frame', the \
7442 \\[universal-argument] prefix also
7443 requests that a new frame be made for the new buffer, so that the dedicated
7444 frame is not changed."
7445 (interactive "P")
7446 (let ((cbuf (current-buffer))
7447 (cwin (selected-window))
7448 (pos (point))
7449 beg end level heading ibuf)
7450 (save-excursion
7451 (org-back-to-heading t)
7452 (when (numberp arg)
7453 (setq level (org-outline-level))
7454 (if (< arg 0) (setq arg (+ level arg)))
7455 (while (> (setq level (org-outline-level)) arg)
7456 (org-up-heading-safe)))
7457 (setq beg (point)
7458 heading (org-get-heading))
7459 (org-end-of-subtree t t)
7460 (if (org-at-heading-p) (backward-char 1))
7461 (setq end (point)))
7462 (if (and (buffer-live-p org-last-indirect-buffer)
7463 (not (eq org-indirect-buffer-display 'new-frame))
7464 (not arg))
7465 (kill-buffer org-last-indirect-buffer))
7466 (setq ibuf (org-get-indirect-buffer cbuf)
7467 org-last-indirect-buffer ibuf)
7468 (cond
7469 ((or (eq org-indirect-buffer-display 'new-frame)
7470 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7471 (select-frame (make-frame))
7472 (delete-other-windows)
7473 (org-pop-to-buffer-same-window ibuf)
7474 (org-set-frame-title heading))
7475 ((eq org-indirect-buffer-display 'dedicated-frame)
7476 (raise-frame
7477 (select-frame (or (and org-indirect-dedicated-frame
7478 (frame-live-p org-indirect-dedicated-frame)
7479 org-indirect-dedicated-frame)
7480 (setq org-indirect-dedicated-frame (make-frame)))))
7481 (delete-other-windows)
7482 (org-pop-to-buffer-same-window ibuf)
7483 (org-set-frame-title (concat "Indirect: " heading)))
7484 ((eq org-indirect-buffer-display 'current-window)
7485 (org-pop-to-buffer-same-window ibuf))
7486 ((eq org-indirect-buffer-display 'other-window)
7487 (pop-to-buffer ibuf))
7488 (t (error "Invalid value")))
7489 (if (featurep 'xemacs)
7490 (save-excursion (org-mode) (turn-on-font-lock)))
7491 (narrow-to-region beg end)
7492 (show-all)
7493 (goto-char pos)
7494 (run-hook-with-args 'org-cycle-hook 'all)
7495 (and (window-live-p cwin) (select-window cwin))))
7497 (defun org-get-indirect-buffer (&optional buffer)
7498 (setq buffer (or buffer (current-buffer)))
7499 (let ((n 1) (base (buffer-name buffer)) bname)
7500 (while (buffer-live-p
7501 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7502 (setq n (1+ n)))
7503 (condition-case nil
7504 (make-indirect-buffer buffer bname 'clone)
7505 (error (make-indirect-buffer buffer bname)))))
7507 (defun org-set-frame-title (title)
7508 "Set the title of the current frame to the string TITLE."
7509 ;; FIXME: how to name a single frame in XEmacs???
7510 (unless (featurep 'xemacs)
7511 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7513 ;;;; Structure editing
7515 ;;; Inserting headlines
7517 (defun org-previous-line-empty-p (&optional next)
7518 "Is the previous line a blank line?
7519 When NEXT is non-nil, check the next line instead."
7520 (save-excursion
7521 (and (not (bobp))
7522 (or (beginning-of-line (if next 2 0)) t)
7523 (save-match-data
7524 (looking-at "[ \t]*$")))))
7526 (defun org-insert-heading (&optional arg invisible-ok)
7527 "Insert a new heading or item with same depth at point.
7528 If point is in a plain list and ARG is nil, create a new list item.
7529 With one universal prefix argument, insert a heading even in lists.
7530 With two universal prefix arguments, insert the heading at the end
7531 of the parent subtree.
7533 If point is at the beginning of a headline, insert a sibling before
7534 the current headline. If point is not at the beginning, split the line
7535 and create a new headline with the text in the current line after point
7536 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7538 If point is at the beginning of a normal line, turn this line into
7539 a heading.
7541 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7542 This is important for non-interactive uses of the command."
7543 (interactive "P")
7544 (if (org-called-interactively-p 'any) (org-reveal))
7545 (let ((itemp (org-in-item-p))
7546 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7547 (respect-content (or org-insert-heading-respect-content
7548 (equal arg '(16))))
7549 (initial-content "")
7550 (adjust-empty-lines t))
7552 (cond
7554 ((or (= (buffer-size) 0)
7555 (and (not (save-excursion
7556 (and (ignore-errors (org-back-to-heading invisible-ok))
7557 (org-at-heading-p))))
7558 (or arg (not itemp))))
7559 ;; At beginning of buffer or so high up that only a heading
7560 ;; makes sense.
7561 (insert
7562 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7563 (if (org-in-src-block-p) ",* " "* "))
7564 (run-hooks 'org-insert-heading-hook))
7566 ((and itemp (not (equal arg '(4))))
7567 ;; Insert an item
7568 (org-insert-item))
7571 ;; Insert a heading
7572 (save-restriction
7573 (widen)
7574 (let* ((level nil)
7575 (on-heading (org-at-heading-p))
7576 (empty-line-p (if on-heading
7577 (org-previous-line-empty-p)
7578 ;; We will decide later
7579 nil))
7580 ;; Get a level string to fall back on
7581 (fix-level
7582 (save-excursion
7583 (org-back-to-heading t)
7584 (if (org-previous-line-empty-p) (setq empty-line-p t))
7585 (looking-at org-outline-regexp)
7586 (make-string (1- (length (match-string 0))) ?*)))
7587 (stars
7588 (save-excursion
7589 (condition-case nil
7590 (progn
7591 (org-back-to-heading invisible-ok)
7592 (when (and (not on-heading)
7593 (featurep 'org-inlinetask)
7594 (integerp org-inlinetask-min-level)
7595 (>= (length (match-string 0))
7596 org-inlinetask-min-level))
7597 ;; Find a heading level before the inline task
7598 (while (and (setq level (org-up-heading-safe))
7599 (>= level org-inlinetask-min-level)))
7600 (if (org-at-heading-p)
7601 (org-back-to-heading invisible-ok)
7602 (error "This should not happen")))
7603 (unless (and (save-excursion
7604 (save-match-data
7605 (org-backward-heading-same-level
7606 1 invisible-ok))
7607 (= (point) (match-beginning 0)))
7608 (not (org-previous-line-empty-p t)))
7609 (setq empty-line-p (or empty-line-p
7610 (org-previous-line-empty-p))))
7611 (match-string 0))
7612 (error (or fix-level "* ")))))
7613 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7614 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7615 pos hide-previous previous-pos)
7617 ;; If we insert after content, move there and clean up whitespace
7618 (when respect-content
7619 (org-end-of-subtree nil t)
7620 (skip-chars-backward " \r\n")
7621 (and (looking-at "[ \t]+") (replace-match ""))
7622 (unless (eobp) (forward-char 1))
7623 (when (looking-at "^\\*")
7624 (unless (bobp) (backward-char 1))
7625 (insert "\n")))
7627 ;; If we are splitting, grab the text that should be moved to the new headline
7628 (when may-split
7629 (if (org-on-heading-p)
7630 ;; This is a heading, we split intelligently (keeping tags)
7631 (let ((pos (point)))
7632 (goto-char (point-at-bol))
7633 (unless (looking-at org-complex-heading-regexp)
7634 (error "This should not happen"))
7635 (when (and (match-beginning 4)
7636 (> pos (match-beginning 4))
7637 (< pos (match-end 4)))
7638 (setq initial-content (buffer-substring pos (match-end 4)))
7639 (goto-char pos)
7640 (delete-region (point) (match-end 4))
7641 (if (looking-at "[ \t]*$")
7642 (replace-match "")
7643 (insert (make-string (length initial-content) ?\ )))
7644 (setq initial-content (org-trim initial-content)))
7645 (goto-char pos))
7646 ;; a normal line
7647 (unless (bolp)
7648 (setq initial-content (buffer-substring (point) (point-at-eol)))
7649 (delete-region (point) (point-at-eol))
7650 (setq initial-content (org-trim initial-content)))))
7652 ;; If we are at the beginning of the line, insert before it. Else after
7653 (cond
7654 ((and (bolp) (looking-at "[ \t]*$")))
7655 ((and (bolp) (not (looking-at "[ \t]*$")))
7656 (open-line 1))
7658 (goto-char (point-at-eol))
7659 (insert "\n")))
7661 ;; Insert the new heading
7662 (insert stars)
7663 (just-one-space)
7664 (insert initial-content)
7665 (when adjust-empty-lines
7666 (if (or (not blank)
7667 (and blank (not (org-previous-line-empty-p))))
7668 (org-N-empty-lines-before-current (if blank 1 0))))
7669 (run-hooks 'org-insert-heading-hook)))))))
7671 (defun org-N-empty-lines-before-current (N)
7672 "Make the number of empty lines before current exactly N.
7673 So this will delete or add empty lines."
7674 (save-excursion
7675 (goto-char (point-at-bol))
7676 (if (looking-back "\\s-+" nil 'greedy)
7677 (replace-match ""))
7678 (or (bobp) (insert "\n"))
7679 (while (> N 0)
7680 (insert "\n")
7681 (setq N (1- N)))))
7683 (defun org-get-heading (&optional no-tags no-todo)
7684 "Return the heading of the current entry, without the stars.
7685 When NO-TAGS is non-nil, don't include tags.
7686 When NO-TODO is non-nil, don't include TODO keywords."
7687 (save-excursion
7688 (org-back-to-heading t)
7689 (cond
7690 ((and no-tags no-todo)
7691 (looking-at org-complex-heading-regexp)
7692 (match-string 4))
7693 (no-tags
7694 (looking-at (concat org-outline-regexp
7695 "\\(.*?\\)"
7696 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7697 (match-string 1))
7698 (no-todo
7699 (looking-at org-todo-line-regexp)
7700 (match-string 3))
7701 (t (looking-at org-heading-regexp)
7702 (match-string 2)))))
7704 (defvar orgstruct-mode) ; defined below
7706 (defun org-heading-components ()
7707 "Return the components of the current heading.
7708 This is a list with the following elements:
7709 - the level as an integer
7710 - the reduced level, different if `org-odd-levels-only' is set.
7711 - the TODO keyword, or nil
7712 - the priority character, like ?A, or nil if no priority is given
7713 - the headline text itself, or the tags string if no headline text
7714 - the tags string, or nil."
7715 (save-excursion
7716 (org-back-to-heading t)
7717 (if (let (case-fold-search)
7718 (looking-at
7719 (if orgstruct-mode
7720 org-heading-regexp
7721 org-complex-heading-regexp)))
7722 (if orgstruct-mode
7723 (list (length (match-string 1))
7724 (org-reduced-level (length (match-string 1)))
7727 (match-string 2)
7728 nil)
7729 (list (length (match-string 1))
7730 (org-reduced-level (length (match-string 1)))
7731 (org-match-string-no-properties 2)
7732 (and (match-end 3) (aref (match-string 3) 2))
7733 (org-match-string-no-properties 4)
7734 (org-match-string-no-properties 5))))))
7736 (defun org-get-entry ()
7737 "Get the entry text, after heading, entire subtree."
7738 (save-excursion
7739 (org-back-to-heading t)
7740 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7742 (defun org-insert-heading-after-current ()
7743 "Insert a new heading with same level as current, after current subtree."
7744 (interactive)
7745 (org-back-to-heading)
7746 (org-insert-heading)
7747 (org-move-subtree-down)
7748 (end-of-line 1))
7750 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7751 "Insert heading with `org-insert-heading-respect-content' set to t."
7752 (interactive "P")
7753 (let ((org-insert-heading-respect-content t))
7754 (org-insert-heading '(4) invisible-ok)))
7756 (defun org-insert-todo-heading-respect-content (&optional force-state)
7757 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7758 (interactive "P")
7759 (let ((org-insert-heading-respect-content t))
7760 (org-insert-todo-heading force-state '(4))))
7762 (defun org-insert-todo-heading (arg &optional force-heading)
7763 "Insert a new heading with the same level and TODO state as current heading.
7764 If the heading has no TODO state, or if the state is DONE, use the first
7765 state (TODO by default). Also one prefix arg, force first state. With two
7766 prefix args, force inserting at the end of the parent subtree."
7767 (interactive "P")
7768 (when (or force-heading (not (org-insert-item 'checkbox)))
7769 (org-insert-heading (or (and (equal arg '(16)) '(16))
7770 force-heading))
7771 (save-excursion
7772 (org-back-to-heading)
7773 (outline-previous-heading)
7774 (looking-at org-todo-line-regexp))
7775 (let*
7776 ((new-mark-x
7777 (if (or arg
7778 (not (match-beginning 2))
7779 (member (match-string 2) org-done-keywords))
7780 (car org-todo-keywords-1)
7781 (match-string 2)))
7782 (new-mark
7784 (run-hook-with-args-until-success
7785 'org-todo-get-default-hook new-mark-x nil)
7786 new-mark-x)))
7787 (beginning-of-line 1)
7788 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7789 (if org-treat-insert-todo-heading-as-state-change
7790 (org-todo new-mark)
7791 (insert new-mark " "))))
7792 (when org-provide-todo-statistics
7793 (org-update-parent-todo-statistics))))
7795 (defun org-insert-subheading (arg)
7796 "Insert a new subheading and demote it.
7797 Works for outline headings and for plain lists alike."
7798 (interactive "P")
7799 (org-insert-heading arg)
7800 (cond
7801 ((org-at-heading-p) (org-do-demote))
7802 ((org-at-item-p) (org-indent-item))))
7804 (defun org-insert-todo-subheading (arg)
7805 "Insert a new subheading with TODO keyword or checkbox and demote it.
7806 Works for outline headings and for plain lists alike."
7807 (interactive "P")
7808 (org-insert-todo-heading arg)
7809 (cond
7810 ((org-at-heading-p) (org-do-demote))
7811 ((org-at-item-p) (org-indent-item))))
7813 ;;; Promotion and Demotion
7815 (defvar org-after-demote-entry-hook nil
7816 "Hook run after an entry has been demoted.
7817 The cursor will be at the beginning of the entry.
7818 When a subtree is being demoted, the hook will be called for each node.")
7820 (defvar org-after-promote-entry-hook nil
7821 "Hook run after an entry has been promoted.
7822 The cursor will be at the beginning of the entry.
7823 When a subtree is being promoted, the hook will be called for each node.")
7825 (defun org-promote-subtree ()
7826 "Promote the entire subtree.
7827 See also `org-promote'."
7828 (interactive)
7829 (save-excursion
7830 (org-with-limited-levels (org-map-tree 'org-promote)))
7831 (org-fix-position-after-promote))
7833 (defun org-demote-subtree ()
7834 "Demote the entire subtree. See `org-demote'.
7835 See also `org-promote'."
7836 (interactive)
7837 (save-excursion
7838 (org-with-limited-levels (org-map-tree 'org-demote)))
7839 (org-fix-position-after-promote))
7842 (defun org-do-promote ()
7843 "Promote the current heading higher up the tree.
7844 If the region is active in `transient-mark-mode', promote all headings
7845 in the region."
7846 (interactive)
7847 (save-excursion
7848 (if (org-region-active-p)
7849 (org-map-region 'org-promote (region-beginning) (region-end))
7850 (org-promote)))
7851 (org-fix-position-after-promote))
7853 (defun org-do-demote ()
7854 "Demote the current heading lower down the tree.
7855 If the region is active in `transient-mark-mode', demote all headings
7856 in the region."
7857 (interactive)
7858 (save-excursion
7859 (if (org-region-active-p)
7860 (org-map-region 'org-demote (region-beginning) (region-end))
7861 (org-demote)))
7862 (org-fix-position-after-promote))
7864 (defun org-fix-position-after-promote ()
7865 "Make sure that after pro/demotion cursor position is right."
7866 (let ((pos (point)))
7867 (when (save-excursion
7868 (beginning-of-line 1)
7869 (looking-at org-todo-line-regexp)
7870 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7871 (cond ((eobp) (insert " "))
7872 ((eolp) (insert " "))
7873 ((equal (char-after) ?\ ) (forward-char 1))))))
7875 (defun org-current-level ()
7876 "Return the level of the current entry, or nil if before the first headline.
7877 The level is the number of stars at the beginning of the headline."
7878 (save-excursion
7879 (org-with-limited-levels
7880 (if (ignore-errors (org-back-to-heading t))
7881 (funcall outline-level)))))
7883 (defun org-get-previous-line-level ()
7884 "Return the outline depth of the last headline before the current line.
7885 Returns 0 for the first headline in the buffer, and nil if before the
7886 first headline."
7887 (let ((current-level (org-current-level))
7888 (prev-level (when (> (line-number-at-pos) 1)
7889 (save-excursion
7890 (beginning-of-line 0)
7891 (org-current-level)))))
7892 (cond ((null current-level) nil) ; Before first headline
7893 ((null prev-level) 0) ; At first headline
7894 (prev-level))))
7896 (defun org-reduced-level (l)
7897 "Compute the effective level of a heading.
7898 This takes into account the setting of `org-odd-levels-only'."
7899 (cond
7900 ((zerop l) 0)
7901 (org-odd-levels-only (1+ (floor (/ l 2))))
7902 (t l)))
7904 (defun org-level-increment ()
7905 "Return the number of stars that will be added or removed at a
7906 time to headlines when structure editing, based on the value of
7907 `org-odd-levels-only'."
7908 (if org-odd-levels-only 2 1))
7910 (defun org-get-valid-level (level &optional change)
7911 "Rectify a level change under the influence of `org-odd-levels-only'
7912 LEVEL is a current level, CHANGE is by how much the level should be
7913 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7914 even level numbers will become the next higher odd number."
7915 (if org-odd-levels-only
7916 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7917 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7918 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7919 (max 1 (+ level (or change 0)))))
7921 (if (boundp 'define-obsolete-function-alias)
7922 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7923 (define-obsolete-function-alias 'org-get-legal-level
7924 'org-get-valid-level)
7925 (define-obsolete-function-alias 'org-get-legal-level
7926 'org-get-valid-level "23.1")))
7928 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7929 ;; ̀org-with-limited-levels'
7930 (defun org-promote ()
7931 "Promote the current heading higher up the tree.
7932 If the region is active in `transient-mark-mode', promote all headings
7933 in the region."
7934 (org-back-to-heading t)
7935 (let* ((level (save-match-data (funcall outline-level)))
7936 (after-change-functions (remove 'flyspell-after-change-function
7937 after-change-functions))
7938 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7939 (diff (abs (- level (length up-head) -1))))
7940 (cond ((and (= level 1) org-called-with-limited-levels
7941 org-allow-promoting-top-level-subtree)
7942 (replace-match "# " nil t))
7943 ((= level 1)
7944 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7945 (t (replace-match up-head nil t)))
7946 ;; Fixup tag positioning
7947 (unless (= level 1)
7948 (and org-auto-align-tags (org-set-tags nil t))
7949 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7950 (run-hooks 'org-after-promote-entry-hook)))
7952 (defun org-demote ()
7953 "Demote the current heading lower down the tree.
7954 If the region is active in `transient-mark-mode', demote all headings
7955 in the region."
7956 (org-back-to-heading t)
7957 (let* ((level (save-match-data (funcall outline-level)))
7958 (after-change-functions (remove 'flyspell-after-change-function
7959 after-change-functions))
7960 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7961 (diff (abs (- level (length down-head) -1))))
7962 (replace-match down-head nil t)
7963 ;; Fixup tag positioning
7964 (and org-auto-align-tags (org-set-tags nil t))
7965 (if org-adapt-indentation (org-fixup-indentation diff))
7966 (run-hooks 'org-after-demote-entry-hook)))
7968 (defun org-cycle-level ()
7969 "Cycle the level of an empty headline through possible states.
7970 This goes first to child, then to parent, level, then up the hierarchy.
7971 After top level, it switches back to sibling level."
7972 (interactive)
7973 (let ((org-adapt-indentation nil))
7974 (when (org-point-at-end-of-empty-headline)
7975 (setq this-command 'org-cycle-level) ; Only needed for caching
7976 (let ((cur-level (org-current-level))
7977 (prev-level (org-get-previous-line-level)))
7978 (cond
7979 ;; If first headline in file, promote to top-level.
7980 ((= prev-level 0)
7981 (loop repeat (/ (- cur-level 1) (org-level-increment))
7982 do (org-do-promote)))
7983 ;; If same level as prev, demote one.
7984 ((= prev-level cur-level)
7985 (org-do-demote))
7986 ;; If parent is top-level, promote to top level if not already.
7987 ((= prev-level 1)
7988 (loop repeat (/ (- cur-level 1) (org-level-increment))
7989 do (org-do-promote)))
7990 ;; If top-level, return to prev-level.
7991 ((= cur-level 1)
7992 (loop repeat (/ (- prev-level 1) (org-level-increment))
7993 do (org-do-demote)))
7994 ;; If less than prev-level, promote one.
7995 ((< cur-level prev-level)
7996 (org-do-promote))
7997 ;; If deeper than prev-level, promote until higher than
7998 ;; prev-level.
7999 ((> cur-level prev-level)
8000 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8001 do (org-do-promote))))
8002 t))))
8004 (defun org-map-tree (fun)
8005 "Call FUN for every heading underneath the current one."
8006 (org-back-to-heading)
8007 (let ((level (funcall outline-level)))
8008 (save-excursion
8009 (funcall fun)
8010 (while (and (progn
8011 (outline-next-heading)
8012 (> (funcall outline-level) level))
8013 (not (eobp)))
8014 (funcall fun)))))
8016 (defun org-map-region (fun beg end)
8017 "Call FUN for every heading between BEG and END."
8018 (let ((org-ignore-region t))
8019 (save-excursion
8020 (setq end (copy-marker end))
8021 (goto-char beg)
8022 (if (and (re-search-forward org-outline-regexp-bol nil t)
8023 (< (point) end))
8024 (funcall fun))
8025 (while (and (progn
8026 (outline-next-heading)
8027 (< (point) end))
8028 (not (eobp)))
8029 (funcall fun)))))
8031 (defvar org-property-end-re) ; silence byte-compiler
8032 (defun org-fixup-indentation (diff)
8033 "Change the indentation in the current entry by DIFF.
8034 However, if any line in the current entry has no indentation, or if it
8035 would end up with no indentation after the change, nothing at all is done."
8036 (save-excursion
8037 (let ((end (save-excursion (outline-next-heading)
8038 (point-marker)))
8039 (prohibit (if (> diff 0)
8040 "^\\S-"
8041 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8042 col)
8043 (unless (save-excursion (end-of-line 1)
8044 (re-search-forward prohibit end t))
8045 (while (and (< (point) end)
8046 (re-search-forward "^[ \t]+" end t))
8047 (goto-char (match-end 0))
8048 (setq col (current-column))
8049 (if (< diff 0) (replace-match ""))
8050 (org-indent-to-column (+ diff col))))
8051 (move-marker end nil))))
8053 (defun org-convert-to-odd-levels ()
8054 "Convert an org-mode file with all levels allowed to one with odd levels.
8055 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8056 level 5 etc."
8057 (interactive)
8058 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8059 (let ((outline-level 'org-outline-level)
8060 (org-odd-levels-only nil) n)
8061 (save-excursion
8062 (goto-char (point-min))
8063 (while (re-search-forward "^\\*\\*+ " nil t)
8064 (setq n (- (length (match-string 0)) 2))
8065 (while (>= (setq n (1- n)) 0)
8066 (org-demote))
8067 (end-of-line 1))))))
8069 (defun org-convert-to-oddeven-levels ()
8070 "Convert an org-mode file with only odd levels to one with odd/even levels.
8071 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8072 file contains a section with an even level, conversion would
8073 destroy the structure of the file. An error is signaled in this
8074 case."
8075 (interactive)
8076 (goto-char (point-min))
8077 ;; First check if there are no even levels
8078 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8079 (org-show-context t)
8080 (error "Not all levels are odd in this file. Conversion not possible"))
8081 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8082 (let ((outline-regexp org-outline-regexp)
8083 (outline-level 'org-outline-level)
8084 (org-odd-levels-only nil) n)
8085 (save-excursion
8086 (goto-char (point-min))
8087 (while (re-search-forward "^\\*\\*+ " nil t)
8088 (setq n (/ (1- (length (match-string 0))) 2))
8089 (while (>= (setq n (1- n)) 0)
8090 (org-promote))
8091 (end-of-line 1))))))
8093 (defun org-tr-level (n)
8094 "Make N odd if required."
8095 (if org-odd-levels-only (1+ (/ n 2)) n))
8097 ;;; Vertical tree motion, cutting and pasting of subtrees
8099 (defun org-move-subtree-up (&optional arg)
8100 "Move the current subtree up past ARG headlines of the same level."
8101 (interactive "p")
8102 (org-move-subtree-down (- (prefix-numeric-value arg))))
8104 (defun org-move-subtree-down (&optional arg)
8105 "Move the current subtree down past ARG headlines of the same level."
8106 (interactive "p")
8107 (setq arg (prefix-numeric-value arg))
8108 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8109 'org-get-last-sibling))
8110 (ins-point (make-marker))
8111 (cnt (abs arg))
8112 (col (current-column))
8113 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8114 ;; Select the tree
8115 (org-back-to-heading)
8116 (setq beg0 (point))
8117 (save-excursion
8118 (setq ne-beg (org-back-over-empty-lines))
8119 (setq beg (point)))
8120 (save-match-data
8121 (save-excursion (outline-end-of-heading)
8122 (setq folded (outline-invisible-p)))
8123 (outline-end-of-subtree))
8124 (outline-next-heading)
8125 (setq ne-end (org-back-over-empty-lines))
8126 (setq end (point))
8127 (goto-char beg0)
8128 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8129 ;; include less whitespace
8130 (save-excursion
8131 (goto-char beg)
8132 (forward-line (- ne-beg ne-end))
8133 (setq beg (point))))
8134 ;; Find insertion point, with error handling
8135 (while (> cnt 0)
8136 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8137 (progn (goto-char beg0)
8138 (user-error "Cannot move past superior level or buffer limit")))
8139 (setq cnt (1- cnt)))
8140 (if (> arg 0)
8141 ;; Moving forward - still need to move over subtree
8142 (progn (org-end-of-subtree t t)
8143 (save-excursion
8144 (org-back-over-empty-lines)
8145 (or (bolp) (newline)))))
8146 (setq ne-ins (org-back-over-empty-lines))
8147 (move-marker ins-point (point))
8148 (setq txt (buffer-substring beg end))
8149 (org-save-markers-in-region beg end)
8150 (delete-region beg end)
8151 (org-remove-empty-overlays-at beg)
8152 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8153 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8154 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8155 (let ((bbb (point)))
8156 (insert-before-markers txt)
8157 (org-reinstall-markers-in-region bbb)
8158 (move-marker ins-point bbb))
8159 (or (bolp) (insert "\n"))
8160 (setq ins-end (point))
8161 (goto-char ins-point)
8162 (org-skip-whitespace)
8163 (when (and (< arg 0)
8164 (org-first-sibling-p)
8165 (> ne-ins ne-beg))
8166 ;; Move whitespace back to beginning
8167 (save-excursion
8168 (goto-char ins-end)
8169 (let ((kill-whole-line t))
8170 (kill-line (- ne-ins ne-beg)) (point)))
8171 (insert (make-string (- ne-ins ne-beg) ?\n)))
8172 (move-marker ins-point nil)
8173 (if folded
8174 (hide-subtree)
8175 (org-show-entry)
8176 (show-children)
8177 (org-cycle-hide-drawers 'children))
8178 (org-clean-visibility-after-subtree-move)
8179 ;; move back to the initial column we were at
8180 (move-to-column col)))
8182 (defvar org-subtree-clip ""
8183 "Clipboard for cut and paste of subtrees.
8184 This is actually only a copy of the kill, because we use the normal kill
8185 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8187 (defvar org-subtree-clip-folded nil
8188 "Was the last copied subtree folded?
8189 This is used to fold the tree back after pasting.")
8191 (defun org-cut-subtree (&optional n)
8192 "Cut the current subtree into the clipboard.
8193 With prefix arg N, cut this many sequential subtrees.
8194 This is a short-hand for marking the subtree and then cutting it."
8195 (interactive "p")
8196 (org-copy-subtree n 'cut))
8198 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8199 "Copy the current subtree it in the clipboard.
8200 With prefix arg N, copy this many sequential subtrees.
8201 This is a short-hand for marking the subtree and then copying it.
8202 If CUT is non-nil, actually cut the subtree.
8203 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8204 of some markers in the region, even if CUT is non-nil. This is
8205 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8206 (interactive "p")
8207 (let (beg end folded (beg0 (point)))
8208 (if (org-called-interactively-p 'any)
8209 (org-back-to-heading nil) ; take what looks like a subtree
8210 (org-back-to-heading t)) ; take what is really there
8211 (setq beg (point))
8212 (skip-chars-forward " \t\r\n")
8213 (save-match-data
8214 (if nosubtrees
8215 (outline-next-heading)
8216 (save-excursion (outline-end-of-heading)
8217 (setq folded (outline-invisible-p)))
8218 (condition-case nil
8219 (org-forward-heading-same-level (1- n) t)
8220 (error nil))
8221 (org-end-of-subtree t t)))
8222 (setq end (point))
8223 (goto-char beg0)
8224 (when (> end beg)
8225 (setq org-subtree-clip-folded folded)
8226 (when (or cut force-store-markers)
8227 (org-save-markers-in-region beg end))
8228 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8229 (setq org-subtree-clip (current-kill 0))
8230 (message "%s: Subtree(s) with %d characters"
8231 (if cut "Cut" "Copied")
8232 (length org-subtree-clip)))))
8234 (defun org-paste-subtree (&optional level tree for-yank)
8235 "Paste the clipboard as a subtree, with modification of headline level.
8236 The entire subtree is promoted or demoted in order to match a new headline
8237 level.
8239 If the cursor is at the beginning of a headline, the same level as
8240 that headline is used to paste the tree.
8242 If not, the new level is derived from the *visible* headings
8243 before and after the insertion point, and taken to be the inferior headline
8244 level of the two. So if the previous visible heading is level 3 and the
8245 next is level 4 (or vice versa), level 4 will be used for insertion.
8246 This makes sure that the subtree remains an independent subtree and does
8247 not swallow low level entries.
8249 You can also force a different level, either by using a numeric prefix
8250 argument, or by inserting the heading marker by hand. For example, if the
8251 cursor is after \"*****\", then the tree will be shifted to level 5.
8253 If optional TREE is given, use this text instead of the kill ring.
8255 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8256 move back over whitespace before inserting, and move point to the end of
8257 the inserted text when done."
8258 (interactive "P")
8259 (setq tree (or tree (and kill-ring (current-kill 0))))
8260 (unless (org-kill-is-subtree-p tree)
8261 (user-error "%s"
8262 (substitute-command-keys
8263 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8264 (org-with-limited-levels
8265 (let* ((visp (not (outline-invisible-p)))
8266 (txt tree)
8267 (^re_ "\\(\\*+\\)[ \t]*")
8268 (old-level (if (string-match org-outline-regexp-bol txt)
8269 (- (match-end 0) (match-beginning 0) 1)
8270 -1))
8271 (force-level (cond (level (prefix-numeric-value level))
8272 ((and (looking-at "[ \t]*$")
8273 (string-match
8274 "^\\*+$" (buffer-substring
8275 (point-at-bol) (point))))
8276 (- (match-end 1) (match-beginning 1)))
8277 ((and (bolp)
8278 (looking-at org-outline-regexp))
8279 (- (match-end 0) (point) 1))))
8280 (previous-level (save-excursion
8281 (condition-case nil
8282 (progn
8283 (outline-previous-visible-heading 1)
8284 (if (looking-at ^re_)
8285 (- (match-end 0) (match-beginning 0) 1)
8287 (error 1))))
8288 (next-level (save-excursion
8289 (condition-case nil
8290 (progn
8291 (or (looking-at org-outline-regexp)
8292 (outline-next-visible-heading 1))
8293 (if (looking-at ^re_)
8294 (- (match-end 0) (match-beginning 0) 1)
8296 (error 1))))
8297 (new-level (or force-level (max previous-level next-level)))
8298 (shift (if (or (= old-level -1)
8299 (= new-level -1)
8300 (= old-level new-level))
8302 (- new-level old-level)))
8303 (delta (if (> shift 0) -1 1))
8304 (func (if (> shift 0) 'org-demote 'org-promote))
8305 (org-odd-levels-only nil)
8306 beg end newend)
8307 ;; Remove the forced level indicator
8308 (if force-level
8309 (delete-region (point-at-bol) (point)))
8310 ;; Paste
8311 (beginning-of-line (if (bolp) 1 2))
8312 (setq beg (point))
8313 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8314 (insert-before-markers txt)
8315 (unless (string-match "\n\\'" txt) (insert "\n"))
8316 (setq newend (point))
8317 (org-reinstall-markers-in-region beg)
8318 (setq end (point))
8319 (goto-char beg)
8320 (skip-chars-forward " \t\n\r")
8321 (setq beg (point))
8322 (if (and (outline-invisible-p) visp)
8323 (save-excursion (outline-show-heading)))
8324 ;; Shift if necessary
8325 (unless (= shift 0)
8326 (save-restriction
8327 (narrow-to-region beg end)
8328 (while (not (= shift 0))
8329 (org-map-region func (point-min) (point-max))
8330 (setq shift (+ delta shift)))
8331 (goto-char (point-min))
8332 (setq newend (point-max))))
8333 (when (or (org-called-interactively-p 'interactive) for-yank)
8334 (message "Clipboard pasted as level %d subtree" new-level))
8335 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8336 kill-ring
8337 (eq org-subtree-clip (current-kill 0))
8338 org-subtree-clip-folded)
8339 ;; The tree was folded before it was killed/copied
8340 (hide-subtree))
8341 (and for-yank (goto-char newend)))))
8343 (defun org-kill-is-subtree-p (&optional txt)
8344 "Check if the current kill is an outline subtree, or a set of trees.
8345 Returns nil if kill does not start with a headline, or if the first
8346 headline level is not the largest headline level in the tree.
8347 So this will actually accept several entries of equal levels as well,
8348 which is OK for `org-paste-subtree'.
8349 If optional TXT is given, check this string instead of the current kill."
8350 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8351 (re (org-get-limited-outline-regexp))
8352 (^re (concat "^" re))
8353 (start-level (and kill
8354 (string-match
8355 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8356 kill)
8357 (- (match-end 2) (match-beginning 2) 1)))
8358 (start (1+ (or (match-beginning 2) -1))))
8359 (if (not start-level)
8360 (progn
8361 nil) ;; does not even start with a heading
8362 (catch 'exit
8363 (while (setq start (string-match ^re kill (1+ start)))
8364 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8365 (throw 'exit nil)))
8366 t))))
8368 (defvar org-markers-to-move nil
8369 "Markers that should be moved with a cut-and-paste operation.
8370 Those markers are stored together with their positions relative to
8371 the start of the region.")
8373 (defun org-save-markers-in-region (beg end)
8374 "Check markers in region.
8375 If these markers are between BEG and END, record their position relative
8376 to BEG, so that after moving the block of text, we can put the markers back
8377 into place.
8378 This function gets called just before an entry or tree gets cut from the
8379 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8380 called immediately, to move the markers with the entries."
8381 (setq org-markers-to-move nil)
8382 (when (featurep 'org-clock)
8383 (org-clock-save-markers-for-cut-and-paste beg end))
8384 (when (featurep 'org-agenda)
8385 (org-agenda-save-markers-for-cut-and-paste beg end)))
8387 (defun org-check-and-save-marker (marker beg end)
8388 "Check if MARKER is between BEG and END.
8389 If yes, remember the marker and the distance to BEG."
8390 (when (and (marker-buffer marker)
8391 (equal (marker-buffer marker) (current-buffer)))
8392 (if (and (>= marker beg) (< marker end))
8393 (push (cons marker (- marker beg)) org-markers-to-move))))
8395 (defun org-reinstall-markers-in-region (beg)
8396 "Move all remembered markers to their position relative to BEG."
8397 (mapc (lambda (x)
8398 (move-marker (car x) (+ beg (cdr x))))
8399 org-markers-to-move)
8400 (setq org-markers-to-move nil))
8402 (defun org-narrow-to-subtree ()
8403 "Narrow buffer to the current subtree."
8404 (interactive)
8405 (save-excursion
8406 (save-match-data
8407 (org-with-limited-levels
8408 (narrow-to-region
8409 (progn (org-back-to-heading t) (point))
8410 (progn (org-end-of-subtree t t)
8411 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8412 (point)))))))
8414 (defun org-narrow-to-block ()
8415 "Narrow buffer to the current block."
8416 (interactive)
8417 (let* ((case-fold-search t)
8418 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8419 "^[ \t]*#\\+end_.*")))
8420 (if blockp
8421 (narrow-to-region (car blockp) (cdr blockp))
8422 (user-error "Not in a block"))))
8424 (eval-when-compile
8425 (defvar org-property-drawer-re))
8427 (defvar org-property-start-re) ;; defined below
8428 (defun org-clone-subtree-with-time-shift (n &optional shift)
8429 "Clone the task (subtree) at point N times.
8430 The clones will be inserted as siblings.
8432 In interactive use, the user will be prompted for the number of
8433 clones to be produced. If the entry has a timestamp, the user
8434 will also be prompted for a time shift, which may be a repeater
8435 as used in time stamps, for example `+3d'. To disable this,
8436 you can call the function with a universal prefix argument.
8438 When a valid repeater is given and the entry contains any time
8439 stamps, the clones will become a sequence in time, with time
8440 stamps in the subtree shifted for each clone produced. If SHIFT
8441 is nil or the empty string, time stamps will be left alone. The
8442 ID property of the original subtree is removed.
8444 If the original subtree did contain time stamps with a repeater,
8445 the following will happen:
8446 - the repeater will be removed in each clone
8447 - an additional clone will be produced, with the current, unshifted
8448 date(s) in the entry.
8449 - the original entry will be placed *after* all the clones, with
8450 repeater intact.
8451 - the start days in the repeater in the original entry will be shifted
8452 to past the last clone.
8453 In this way you can spell out a number of instances of a repeating task,
8454 and still retain the repeater to cover future instances of the task."
8455 (interactive "nNumber of clones to produce: ")
8456 (let ((shift
8457 (or shift
8458 (if (and (not (equal current-prefix-arg '(4)))
8459 (save-excursion
8460 (re-search-forward org-ts-regexp-both
8461 (save-excursion
8462 (org-end-of-subtree t)
8463 (point)) t)))
8464 (read-from-minibuffer
8465 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8466 ""))) ;; No time shift
8467 (n-no-remove -1)
8468 (drawer-re org-drawer-regexp)
8469 beg end template task idprop
8470 shift-n shift-what doshift nmin nmax)
8471 (if (not (and (integerp n) (> n 0)))
8472 (error "Invalid number of replications %s" n))
8473 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8474 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8475 shift)))
8476 (error "Invalid shift specification %s" shift))
8477 (when doshift
8478 (setq shift-n (string-to-number (match-string 1 shift))
8479 shift-what (cdr (assoc (match-string 2 shift)
8480 '(("d" . day) ("w" . week)
8481 ("m" . month) ("y" . year))))))
8482 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8483 (setq nmin 1 nmax n)
8484 (org-back-to-heading t)
8485 (setq beg (point))
8486 (setq idprop (org-entry-get nil "ID"))
8487 (org-end-of-subtree t t)
8488 (or (bolp) (insert "\n"))
8489 (setq end (point))
8490 (setq template (buffer-substring beg end))
8491 (when (and doshift
8492 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8493 (delete-region beg end)
8494 (setq end beg)
8495 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8496 (goto-char end)
8497 (loop for n from nmin to nmax do
8498 ;; prepare clone
8499 (with-temp-buffer
8500 (insert template)
8501 (org-mode)
8502 (goto-char (point-min))
8503 (org-show-subtree)
8504 (and idprop (if org-clone-delete-id
8505 (org-entry-delete nil "ID")
8506 (org-id-get-create t)))
8507 (unless (= n 0)
8508 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8509 (kill-whole-line))
8510 (goto-char (point-min))
8511 (while (re-search-forward drawer-re nil t)
8512 (org-remove-empty-drawer-at (point))))
8513 (goto-char (point-min))
8514 (when doshift
8515 (while (re-search-forward org-ts-regexp-both nil t)
8516 (org-timestamp-change (* n shift-n) shift-what))
8517 (unless (= n n-no-remove)
8518 (goto-char (point-min))
8519 (while (re-search-forward org-ts-regexp nil t)
8520 (save-excursion
8521 (goto-char (match-beginning 0))
8522 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8523 (delete-region (match-beginning 1) (match-end 1)))))))
8524 (setq task (buffer-string)))
8525 (insert task))
8526 (goto-char beg)))
8528 ;;; Outline Sorting
8530 (defun org-sort (with-case)
8531 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8532 Optional argument WITH-CASE means sort case-sensitively."
8533 (interactive "P")
8534 (cond
8535 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8536 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8538 (org-call-with-arg 'org-sort-entries with-case))))
8540 (defun org-sort-remove-invisible (s)
8541 "Remove invisible links from string S."
8542 (remove-text-properties 0 (length s) org-rm-props s)
8543 (while (string-match org-bracket-link-regexp s)
8544 (setq s (replace-match (if (match-end 2)
8545 (match-string 3 s)
8546 (match-string 1 s)) t t s)))
8547 (let ((st (format " %s " s)))
8548 (while (string-match org-emph-re st)
8549 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8550 (setq s (substring st 1 -1)))
8553 (defvar org-priority-regexp) ; defined later in the file
8555 (defvar org-after-sorting-entries-or-items-hook nil
8556 "Hook that is run after a bunch of entries or items have been sorted.
8557 When children are sorted, the cursor is in the parent line when this
8558 hook gets called. When a region or a plain list is sorted, the cursor
8559 will be in the first entry of the sorted region/list.")
8561 (defun org-sort-entries
8562 (&optional with-case sorting-type getkey-func compare-func property)
8563 "Sort entries on a certain level of an outline tree.
8564 If there is an active region, the entries in the region are sorted.
8565 Else, if the cursor is before the first entry, sort the top-level items.
8566 Else, the children of the entry at point are sorted.
8568 Sorting can be alphabetically, numerically, by date/time as given by
8569 a time stamp, by a property, by priority order, or by a custom function.
8571 The command prompts for the sorting type unless it has been given to the
8572 function through the SORTING-TYPE argument, which needs to be a character,
8573 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8574 precise meaning of each character:
8576 n Numerically, by converting the beginning of the entry/item to a number.
8577 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8578 o By order of TODO keywords.
8579 t By date/time, either the first active time stamp in the entry, or, if
8580 none exist, by the first inactive one.
8581 s By the scheduled date/time.
8582 d By deadline date/time.
8583 c By creation time, which is assumed to be the first inactive time stamp
8584 at the beginning of a line.
8585 p By priority according to the cookie.
8586 r By the value of a property.
8588 Capital letters will reverse the sort order.
8590 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8591 called with point at the beginning of the record. It must return either
8592 a string or a number that should serve as the sorting key for that record.
8594 Comparing entries ignores case by default. However, with an optional argument
8595 WITH-CASE, the sorting considers case as well.
8597 Sorting is done against the visible part of the headlines, it ignores hidden
8598 links."
8599 (interactive "P")
8600 (let ((case-func (if with-case 'identity 'downcase))
8601 (cmstr
8602 ;; The clock marker is lost when using `sort-subr', let's
8603 ;; store the clocking string.
8604 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8605 (save-excursion
8606 (goto-char org-clock-marker)
8607 (looking-back "^.*") (match-string-no-properties 0))))
8608 start beg end stars re re2
8609 txt what tmp)
8610 ;; Find beginning and end of region to sort
8611 (cond
8612 ((org-region-active-p)
8613 ;; we will sort the region
8614 (setq end (region-end)
8615 what "region")
8616 (goto-char (region-beginning))
8617 (if (not (org-at-heading-p)) (outline-next-heading))
8618 (setq start (point)))
8619 ((or (org-at-heading-p)
8620 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8621 ;; we will sort the children of the current headline
8622 (org-back-to-heading)
8623 (setq start (point)
8624 end (progn (org-end-of-subtree t t)
8625 (or (bolp) (insert "\n"))
8626 (org-back-over-empty-lines)
8627 (point))
8628 what "children")
8629 (goto-char start)
8630 (show-subtree)
8631 (outline-next-heading))
8633 ;; we will sort the top-level entries in this file
8634 (goto-char (point-min))
8635 (or (org-at-heading-p) (outline-next-heading))
8636 (setq start (point))
8637 (goto-char (point-max))
8638 (beginning-of-line 1)
8639 (when (looking-at ".*?\\S-")
8640 ;; File ends in a non-white line
8641 (end-of-line 1)
8642 (insert "\n"))
8643 (setq end (point-max))
8644 (setq what "top-level")
8645 (goto-char start)
8646 (show-all)))
8648 (setq beg (point))
8649 (if (>= beg end) (user-error "Nothing to sort"))
8651 (looking-at "\\(\\*+\\)")
8652 (setq stars (match-string 1)
8653 re (concat "^" (regexp-quote stars) " +")
8654 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8655 txt (buffer-substring beg end))
8656 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8657 (if (and (not (equal stars "*")) (string-match re2 txt))
8658 (user-error "Region to sort contains a level above the first entry"))
8660 (unless sorting-type
8661 (message
8662 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8663 [t]ime [s]cheduled [d]eadline [c]reated
8664 A/N/P/R/O/F/T/S/D/C means reversed:"
8665 what)
8666 (setq sorting-type (read-char-exclusive))
8668 (unless getkey-func
8669 (and (= (downcase sorting-type) ?f)
8670 (setq getkey-func
8671 (org-icompleting-read "Sort using function: "
8672 obarray 'fboundp t nil nil))
8673 (setq getkey-func (intern getkey-func))))
8675 (and (= (downcase sorting-type) ?r)
8676 (not property)
8677 (setq property
8678 (org-icompleting-read "Property: "
8679 (mapcar 'list (org-buffer-property-keys t))
8680 nil t))))
8682 (message "Sorting entries...")
8684 (save-restriction
8685 (narrow-to-region start end)
8686 (let ((dcst (downcase sorting-type))
8687 (case-fold-search nil)
8688 (now (current-time)))
8689 (sort-subr
8690 (/= dcst sorting-type)
8691 ;; This function moves to the beginning character of the "record" to
8692 ;; be sorted.
8693 (lambda nil
8694 (if (re-search-forward re nil t)
8695 (goto-char (match-beginning 0))
8696 (goto-char (point-max))))
8697 ;; This function moves to the last character of the "record" being
8698 ;; sorted.
8699 (lambda nil
8700 (save-match-data
8701 (condition-case nil
8702 (outline-forward-same-level 1)
8703 (error
8704 (goto-char (point-max))))))
8705 ;; This function returns the value that gets sorted against.
8706 (lambda nil
8707 (cond
8708 ((= dcst ?n)
8709 (if (looking-at org-complex-heading-regexp)
8710 (string-to-number (org-sort-remove-invisible (match-string 4)))
8711 nil))
8712 ((= dcst ?a)
8713 (if (looking-at org-complex-heading-regexp)
8714 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8715 nil))
8716 ((= dcst ?t)
8717 (let ((end (save-excursion (outline-next-heading) (point))))
8718 (if (or (re-search-forward org-ts-regexp end t)
8719 (re-search-forward org-ts-regexp-both end t))
8720 (org-time-string-to-seconds (match-string 0))
8721 (org-float-time now))))
8722 ((= dcst ?c)
8723 (let ((end (save-excursion (outline-next-heading) (point))))
8724 (if (re-search-forward
8725 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8726 end t)
8727 (org-time-string-to-seconds (match-string 0))
8728 (org-float-time now))))
8729 ((= dcst ?s)
8730 (let ((end (save-excursion (outline-next-heading) (point))))
8731 (if (re-search-forward org-scheduled-time-regexp end t)
8732 (org-time-string-to-seconds (match-string 1))
8733 (org-float-time now))))
8734 ((= dcst ?d)
8735 (let ((end (save-excursion (outline-next-heading) (point))))
8736 (if (re-search-forward org-deadline-time-regexp end t)
8737 (org-time-string-to-seconds (match-string 1))
8738 (org-float-time now))))
8739 ((= dcst ?p)
8740 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8741 (string-to-char (match-string 2))
8742 org-default-priority))
8743 ((= dcst ?r)
8744 (or (org-entry-get nil property) ""))
8745 ((= dcst ?o)
8746 (if (looking-at org-complex-heading-regexp)
8747 (- 9999 (length (member (match-string 2)
8748 org-todo-keywords-1)))))
8749 ((= dcst ?f)
8750 (if getkey-func
8751 (progn
8752 (setq tmp (funcall getkey-func))
8753 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8754 tmp)
8755 (error "Invalid key function `%s'" getkey-func)))
8756 (t (error "Invalid sorting type `%c'" sorting-type))))
8758 (cond
8759 ((= dcst ?a) 'string<)
8760 ((= dcst ?f) compare-func)
8761 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8762 (run-hooks 'org-after-sorting-entries-or-items-hook)
8763 ;; Reset the clock marker if needed
8764 (when cmstr
8765 (save-excursion
8766 (goto-char start)
8767 (search-forward cmstr nil t)
8768 (move-marker org-clock-marker (point))))
8769 (message "Sorting entries...done")))
8771 (defun org-do-sort (table what &optional with-case sorting-type)
8772 "Sort TABLE of WHAT according to SORTING-TYPE.
8773 The user will be prompted for the SORTING-TYPE if the call to this
8774 function does not specify it. WHAT is only for the prompt, to indicate
8775 what is being sorted. The sorting key will be extracted from
8776 the car of the elements of the table.
8777 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8778 (unless sorting-type
8779 (message
8780 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8781 what)
8782 (setq sorting-type (read-char-exclusive)))
8783 (let ((dcst (downcase sorting-type))
8784 extractfun comparefun)
8785 ;; Define the appropriate functions
8786 (cond
8787 ((= dcst ?n)
8788 (setq extractfun 'string-to-number
8789 comparefun (if (= dcst sorting-type) '< '>)))
8790 ((= dcst ?a)
8791 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8792 (lambda(x) (downcase (org-sort-remove-invisible x))))
8793 comparefun (if (= dcst sorting-type)
8794 'string<
8795 (lambda (a b) (and (not (string< a b))
8796 (not (string= a b)))))))
8797 ((= dcst ?t)
8798 (setq extractfun
8799 (lambda (x)
8800 (if (or (string-match org-ts-regexp x)
8801 (string-match org-ts-regexp-both x))
8802 (org-float-time
8803 (org-time-string-to-time (match-string 0 x)))
8805 comparefun (if (= dcst sorting-type) '< '>)))
8806 (t (error "Invalid sorting type `%c'" sorting-type)))
8808 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8809 table)
8810 (lambda (a b) (funcall comparefun (car a) (car b))))))
8813 ;;; The orgstruct minor mode
8815 ;; Define a minor mode which can be used in other modes in order to
8816 ;; integrate the org-mode structure editing commands.
8818 ;; This is really a hack, because the org-mode structure commands use
8819 ;; keys which normally belong to the major mode. Here is how it
8820 ;; works: The minor mode defines all the keys necessary to operate the
8821 ;; structure commands, but wraps the commands into a function which
8822 ;; tests if the cursor is currently at a headline or a plain list
8823 ;; item. If that is the case, the structure command is used,
8824 ;; temporarily setting many Org-mode variables like regular
8825 ;; expressions for filling etc. However, when any of those keys is
8826 ;; used at a different location, function uses `key-binding' to look
8827 ;; up if the key has an associated command in another currently active
8828 ;; keymap (minor modes, major mode, global), and executes that
8829 ;; command. There might be problems if any of the keys is otherwise
8830 ;; used as a prefix key.
8832 (defcustom orgstruct-heading-prefix-regexp nil
8833 "Regexp that matches the custom prefix of Org headlines in
8834 orgstruct(++)-mode."
8835 :group 'org
8836 :version "24.4"
8837 :package-version '(Org . "8.0")
8838 :type 'string)
8839 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8841 (defcustom orgstruct-setup-hook nil
8842 "Hook run after orgstruct-mode-map is filled."
8843 :group 'org
8844 :version "24.4"
8845 :package-version '(Org . "8.0")
8846 :type 'hook)
8848 (defvar orgstruct-initialized nil)
8850 (defvar org-local-vars nil
8851 "List of local variables, for use by `orgstruct-mode'.")
8853 ;;;###autoload
8854 (define-minor-mode orgstruct-mode
8855 "Toggle the minor mode `orgstruct-mode'.
8856 This mode is for using Org-mode structure commands in other
8857 modes. The following keys behave as if Org-mode were active, if
8858 the cursor is on a headline, or on a plain list item (both as
8859 defined by Org-mode)."
8860 nil " OrgStruct" (make-sparse-keymap)
8861 (funcall (if orgstruct-mode
8862 'add-to-invisibility-spec
8863 'remove-from-invisibility-spec)
8864 '(outline . t))
8865 (when orgstruct-mode
8866 (org-load-modules-maybe)
8867 (unless orgstruct-initialized
8868 (orgstruct-setup)
8869 (setq orgstruct-initialized t))))
8871 ;;;###autoload
8872 (defun turn-on-orgstruct ()
8873 "Unconditionally turn on `orgstruct-mode'."
8874 (orgstruct-mode 1))
8876 (defvar org-fb-vars nil)
8877 (make-variable-buffer-local 'org-fb-vars)
8878 (defun orgstruct++-mode (&optional arg)
8879 "Toggle `orgstruct-mode', the enhanced version of it.
8880 In addition to setting orgstruct-mode, this also exports all
8881 indentation and autofilling variables from org-mode into the
8882 buffer. It will also recognize item context in multiline items."
8883 (interactive "P")
8884 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8885 (if (< arg 1)
8886 (progn (orgstruct-mode -1)
8887 (mapc (lambda(v)
8888 (org-set-local (car v)
8889 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8890 org-fb-vars))
8891 (orgstruct-mode 1)
8892 (setq org-fb-vars nil)
8893 (unless org-local-vars
8894 (setq org-local-vars (org-get-local-variables)))
8895 (let (var val)
8896 (mapc
8897 (lambda (x)
8898 (when (string-match
8899 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8900 (symbol-name (car x)))
8901 (setq var (car x) val (nth 1 x))
8902 (push (list var `(quote ,(eval var))) org-fb-vars)
8903 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8904 org-local-vars)
8905 (org-set-local 'orgstruct-is-++ t))))
8907 (defvar orgstruct-is-++ nil
8908 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8909 (make-variable-buffer-local 'orgstruct-is-++)
8911 ;;;###autoload
8912 (defun turn-on-orgstruct++ ()
8913 "Unconditionally turn on `orgstruct++-mode'."
8914 (orgstruct++-mode 1))
8916 (defun orgstruct-error ()
8917 "Error when there is no default binding for a structure key."
8918 (interactive)
8919 (funcall (if (fboundp 'user-error)
8920 'user-error
8921 'error)
8922 "This key has no function outside structure elements"))
8924 (defun orgstruct-setup ()
8925 "Setup orgstruct keymap."
8926 (dolist (cell '((org-demote . t)
8927 (org-metaleft . t)
8928 (org-metaright . t)
8929 (org-promote . t)
8930 (org-shiftmetaleft . t)
8931 (org-shiftmetaright . t)
8932 org-backward-element
8933 org-backward-heading-same-level
8934 org-ctrl-c-ret
8935 org-ctrl-c-minus
8936 org-ctrl-c-star
8937 org-cycle
8938 org-forward-heading-same-level
8939 org-insert-heading
8940 org-insert-heading-respect-content
8941 org-kill-note-or-show-branches
8942 org-mark-subtree
8943 org-meta-return
8944 org-metadown
8945 org-metaup
8946 org-narrow-to-subtree
8947 org-promote-subtree
8948 org-reveal
8949 org-shiftdown
8950 org-shiftleft
8951 org-shiftmetadown
8952 org-shiftmetaup
8953 org-shiftright
8954 org-shifttab
8955 org-shifttab
8956 org-shiftup
8957 org-show-subtree
8958 org-sort
8959 org-up-element
8960 outline-demote
8961 outline-next-visible-heading
8962 outline-previous-visible-heading
8963 outline-promote
8964 outline-up-heading
8965 show-children))
8966 (let ((f (or (car-safe cell) cell))
8967 (disable-when-heading-prefix (cdr-safe cell)))
8968 (when (fboundp f)
8969 (let ((new-bindings))
8970 (dolist (binding (nconc (where-is-internal f org-mode-map)
8971 (where-is-internal f outline-mode-map)))
8972 (push binding new-bindings)
8973 ;; TODO use local-function-key-map
8974 (dolist (rep '(("<tab>" . "TAB")
8975 ("<return>" . "RET")
8976 ("<escape>" . "ESC")
8977 ("<delete>" . "DEL")))
8978 (setq binding (read-kbd-macro
8979 (let ((case-fold-search))
8980 (replace-regexp-in-string
8981 (regexp-quote (cdr rep))
8982 (car rep)
8983 (key-description binding)))))
8984 (pushnew binding new-bindings :test 'equal)))
8985 (dolist (binding new-bindings)
8986 (let ((key (lookup-key orgstruct-mode-map binding)))
8987 (when (or (not key) (numberp key))
8988 (condition-case nil
8989 (org-defkey orgstruct-mode-map
8990 binding
8991 (orgstruct-make-binding f binding disable-when-heading-prefix))
8992 (error nil)))))))))
8993 (run-hooks 'orgstruct-setup-hook))
8995 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8996 "Create a function for binding in the structure minor mode.
8997 FUN is the command to call inside a table. KEY is the key that
8998 should be checked in for a command to execute outside of tables.
8999 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
9000 if `orgstruct-heading-prefix-regexp' is non-nil."
9001 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9002 (let ((nname name)
9003 (i 0))
9004 (while (fboundp (intern nname))
9005 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9006 (setq name (intern nname)))
9007 (eval
9008 (let ((bindings '((org-heading-regexp
9009 (concat "^"
9010 orgstruct-heading-prefix-regexp
9011 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9012 (org-outline-regexp
9013 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9014 (org-outline-regexp-bol
9015 (concat "^" org-outline-regexp))
9016 (outline-regexp org-outline-regexp)
9017 (outline-heading-end-regexp "\n")
9018 (outline-level 'org-outline-level)
9019 (outline-heading-alist))))
9020 `(defun ,name (arg)
9021 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9022 "Outside of structure, run the binding of `"
9023 (key-description key) "'."
9024 (when disable-when-heading-prefix
9025 (concat
9026 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9027 "back to the default binding due to limitations of Org's implementation of\n"
9028 "`" (symbol-name fun) "'.")))
9029 (interactive "p")
9030 (let* ((disable
9031 ,(when disable-when-heading-prefix
9032 '(and orgstruct-heading-prefix-regexp
9033 (not (string= orgstruct-heading-prefix-regexp "")))))
9034 (fallback
9035 (or disable
9036 (not
9037 (let* ,bindings
9038 (org-context-p 'headline 'item
9039 ,(when (memq fun
9040 '(org-insert-heading
9041 org-insert-heading-respect-content
9042 org-meta-return))
9043 '(when orgstruct-is-++
9044 'item-body))))))))
9045 (if fallback
9046 (let* ((orgstruct-mode)
9047 (binding
9048 (loop with key = ,key
9049 for rep in
9050 '(nil
9051 ("<\\([^>]*\\)tab>" . "\\1TAB")
9052 ("<\\([^>]*\\)return>" . "\\1RET")
9053 ("<\\([^>]*\\)escape>" . "\\1ESC")
9054 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9056 (when rep
9057 (setq key (read-kbd-macro
9058 (let ((case-fold-search))
9059 (replace-regexp-in-string
9060 (car rep)
9061 (cdr rep)
9062 (key-description key))))))
9063 thereis (key-binding key))))
9064 (if (keymapp binding)
9065 (set-temporary-overlay-map binding)
9066 (let ((func (or binding
9067 (unless disable
9068 'orgstruct-error))))
9069 (when func
9070 (call-interactively func)))))
9071 (org-run-like-in-org-mode
9072 (lambda ()
9073 (interactive)
9074 (let* ,bindings
9075 (call-interactively ',fun)))))))))
9076 name))
9078 (defun org-contextualize-keys (alist contexts)
9079 "Return valid elements in ALIST depending on CONTEXTS.
9081 `org-agenda-custom-commands' or `org-capture-templates' are the
9082 values used for ALIST, and `org-agenda-custom-commands-contexts'
9083 or `org-capture-templates-contexts' are the associated contexts
9084 definitions."
9085 (let ((contexts
9086 ;; normalize contexts
9087 (mapcar
9088 (lambda(c) (cond ((listp (cadr c))
9089 (list (car c) (car c) (cadr c)))
9090 ((string= "" (cadr c))
9091 (list (car c) (car c) (caddr c)))
9092 (t c))) contexts))
9093 (a alist) c r s)
9094 ;; loop over all commands or templates
9095 (while (setq c (pop a))
9096 (let (vrules repl)
9097 (cond
9098 ((not (assoc (car c) contexts))
9099 (push c r))
9100 ((and (assoc (car c) contexts)
9101 (setq vrules (org-contextualize-validate-key
9102 (car c) contexts)))
9103 (mapc (lambda (vr)
9104 (when (not (equal (car vr) (cadr vr)))
9105 (setq repl vr))) vrules)
9106 (if (not repl) (push c r)
9107 (push (cadr repl) s)
9108 (push
9109 (cons (car c)
9110 (cdr (or (assoc (cadr repl) alist)
9111 (error "Undefined key `%s' as contextual replacement for `%s'"
9112 (cadr repl) (car c)))))
9113 r))))))
9114 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9115 (delq
9117 (delete-dups
9118 (mapcar (lambda (x)
9119 (let ((tpl (car x)))
9120 (when (not (delq
9122 (mapcar (lambda(y)
9123 (equal y tpl)) s))) x)))
9124 (reverse r))))))
9126 (defun org-contextualize-validate-key (key contexts)
9127 "Check CONTEXTS for agenda or capture KEY."
9128 (let (r rr res)
9129 (while (setq r (pop contexts))
9130 (mapc
9131 (lambda (rr)
9132 (when
9133 (and (equal key (car r))
9134 (if (functionp rr) (funcall rr)
9135 (or (and (eq (car rr) 'in-file)
9136 (buffer-file-name)
9137 (string-match (cdr rr) (buffer-file-name)))
9138 (and (eq (car rr) 'in-mode)
9139 (string-match (cdr rr) (symbol-name major-mode)))
9140 (and (eq (car rr) 'in-buffer)
9141 (string-match (cdr rr) (buffer-name)))
9142 (when (and (eq (car rr) 'not-in-file)
9143 (buffer-file-name))
9144 (not (string-match (cdr rr) (buffer-file-name))))
9145 (when (eq (car rr) 'not-in-mode)
9146 (not (string-match (cdr rr) (symbol-name major-mode))))
9147 (when (eq (car rr) 'not-in-buffer)
9148 (not (string-match (cdr rr) (buffer-name)))))))
9149 (push r res)))
9150 (car (last r))))
9151 (delete-dups (delq nil res))))
9153 (defun org-context-p (&rest contexts)
9154 "Check if local context is any of CONTEXTS.
9155 Possible values in the list of contexts are `table', `headline', and `item'."
9156 (let ((pos (point)))
9157 (goto-char (point-at-bol))
9158 (prog1 (or (and (memq 'table contexts)
9159 (looking-at "[ \t]*|"))
9160 (and (memq 'headline contexts)
9161 (looking-at org-outline-regexp))
9162 (and (memq 'item contexts)
9163 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9164 (and (memq 'item-body contexts)
9165 (org-in-item-p)))
9166 (goto-char pos))))
9168 (defun org-get-local-variables ()
9169 "Return a list of all local variables in an Org mode buffer."
9170 (let (varlist)
9171 (with-current-buffer (get-buffer-create "*Org tmp*")
9172 (erase-buffer)
9173 (org-mode)
9174 (setq varlist (buffer-local-variables)))
9175 (kill-buffer "*Org tmp*")
9176 (delq nil
9177 (mapcar
9178 (lambda (x)
9179 (setq x
9180 (if (symbolp x)
9181 (list x)
9182 (list (car x) (cdr x))))
9183 (if (and (not (get (car x) 'org-state))
9184 (string-match
9185 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9186 (symbol-name (car x))))
9187 x nil))
9188 varlist))))
9190 (defun org-clone-local-variables (from-buffer &optional regexp)
9191 "Clone local variables from FROM-BUFFER.
9192 Optional argument REGEXP selects variables to clone."
9193 (mapc
9194 (lambda (pair)
9195 (and (symbolp (car pair))
9196 (or (null regexp)
9197 (string-match regexp (symbol-name (car pair))))
9198 (set (make-local-variable (car pair))
9199 (cdr pair))))
9200 (buffer-local-variables from-buffer)))
9202 ;;;###autoload
9203 (defun org-run-like-in-org-mode (cmd)
9204 "Run a command, pretending that the current buffer is in Org-mode.
9205 This will temporarily bind local variables that are typically bound in
9206 Org-mode to the values they have in Org-mode, and then interactively
9207 call CMD."
9208 (org-load-modules-maybe)
9209 (unless org-local-vars
9210 (setq org-local-vars (org-get-local-variables)))
9211 (let (binds)
9212 (dolist (var org-local-vars)
9213 (when (or (not (boundp (car var)))
9214 (eq (symbol-value (car var))
9215 (default-value (car var))))
9216 (push (list (car var) `(quote ,(cadr var))) binds)))
9217 (eval `(let ,binds
9218 (call-interactively (quote ,cmd))))))
9220 ;;;; Archiving
9222 (defun org-get-category (&optional pos force-refresh)
9223 "Get the category applying to position POS."
9224 (save-match-data
9225 (if force-refresh (org-refresh-category-properties))
9226 (let ((pos (or pos (point))))
9227 (or (get-text-property pos 'org-category)
9228 (progn (org-refresh-category-properties)
9229 (get-text-property pos 'org-category))))))
9231 (defun org-refresh-category-properties ()
9232 "Refresh category text properties in the buffer."
9233 (let ((case-fold-search t)
9234 (inhibit-read-only t)
9235 (def-cat (cond
9236 ((null org-category)
9237 (if buffer-file-name
9238 (file-name-sans-extension
9239 (file-name-nondirectory buffer-file-name))
9240 "???"))
9241 ((symbolp org-category) (symbol-name org-category))
9242 (t org-category)))
9243 beg end cat pos optionp)
9244 (org-with-silent-modifications
9245 (save-excursion
9246 (save-restriction
9247 (widen)
9248 (goto-char (point-min))
9249 (put-text-property (point) (point-max) 'org-category def-cat)
9250 (while (re-search-forward
9251 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9252 (setq pos (match-end 0)
9253 optionp (equal (char-after (match-beginning 0)) ?#)
9254 cat (org-trim (match-string 2)))
9255 (if optionp
9256 (setq beg (point-at-bol) end (point-max))
9257 (org-back-to-heading t)
9258 (setq beg (point) end (org-end-of-subtree t t)))
9259 (put-text-property beg end 'org-category cat)
9260 (put-text-property beg end 'org-category-position beg)
9261 (goto-char pos)))))))
9263 (defun org-refresh-properties (dprop tprop)
9264 "Refresh buffer text properties.
9265 DPROP is the drawer property and TPROP is the corresponding text
9266 property to set."
9267 (let ((case-fold-search t)
9268 (inhibit-read-only t) p)
9269 (org-with-silent-modifications
9270 (save-excursion
9271 (save-restriction
9272 (widen)
9273 (goto-char (point-min))
9274 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9275 (setq p (org-match-string-no-properties 1))
9276 (save-excursion
9277 (org-back-to-heading t)
9278 (put-text-property
9279 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9282 ;;;; Link Stuff
9284 ;;; Link abbreviations
9286 (defun org-link-expand-abbrev (link)
9287 "Apply replacements as defined in `org-link-abbrev-alist'."
9288 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9289 (let* ((key (match-string 1 link))
9290 (as (or (assoc key org-link-abbrev-alist-local)
9291 (assoc key org-link-abbrev-alist)))
9292 (tag (and (match-end 2) (match-string 3 link)))
9293 rpl)
9294 (if (not as)
9295 link
9296 (setq rpl (cdr as))
9297 (cond
9298 ((symbolp rpl) (funcall rpl tag))
9299 ((string-match "%(\\([^)]+\\))" rpl)
9300 (replace-match
9301 (save-match-data
9302 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9303 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9304 ((string-match "%h" rpl)
9305 (replace-match (url-hexify-string (or tag "")) t t rpl))
9306 (t (concat rpl tag)))))
9307 link))
9309 ;;; Storing and inserting links
9311 (defvar org-insert-link-history nil
9312 "Minibuffer history for links inserted with `org-insert-link'.")
9314 (defvar org-stored-links nil
9315 "Contains the links stored with `org-store-link'.")
9317 (defvar org-store-link-plist nil
9318 "Plist with info about the most recently link created with `org-store-link'.")
9320 (defvar org-link-protocols nil
9321 "Link protocols added to Org-mode using `org-add-link-type'.")
9323 (defvar org-store-link-functions nil
9324 "List of functions that are called to create and store a link.
9325 Each function will be called in turn until one returns a non-nil
9326 value. Each function should check if it is responsible for creating
9327 this link (for example by looking at the major mode).
9328 If not, it must exit and return nil.
9329 If yes, it should return a non-nil value after a calling
9330 `org-store-link-props' with a list of properties and values.
9331 Special properties are:
9333 :type The link prefix, like \"http\". This must be given.
9334 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9335 This is obligatory as well.
9336 :description Optional default description for the second pair
9337 of brackets in an Org-mode link. The user can still change
9338 this when inserting this link into an Org-mode buffer.
9340 In addition to these, any additional properties can be specified
9341 and then used in capture templates.")
9343 (defun org-add-link-type (type &optional follow export)
9344 "Add TYPE to the list of `org-link-types'.
9345 Re-compute all regular expressions depending on `org-link-types'
9347 FOLLOW and EXPORT are two functions.
9349 FOLLOW should take the link path as the single argument and do whatever
9350 is necessary to follow the link, for example find a file or display
9351 a mail message.
9353 EXPORT should format the link path for export to one of the export formats.
9354 It should be a function accepting three arguments:
9356 path the path of the link, the text after the prefix (like \"http:\")
9357 desc the description of the link, if any, or a description added by
9358 org-export-normalize-links if there is none
9359 format the export format, a symbol like `html' or `latex' or `ascii'..
9361 The function may use the FORMAT information to return different values
9362 depending on the format. The return value will be put literally into
9363 the exported file. If the return value is nil, this means Org should
9364 do what it normally does with links which do not have EXPORT defined.
9366 Org-mode has a built-in default for exporting links. If you are happy with
9367 this default, there is no need to define an export function for the link
9368 type. For a simple example of an export function, see `org-bbdb.el'."
9369 (add-to-list 'org-link-types type t)
9370 (org-make-link-regexps)
9371 (if (assoc type org-link-protocols)
9372 (setcdr (assoc type org-link-protocols) (list follow export))
9373 (push (list type follow export) org-link-protocols)))
9375 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9376 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9378 ;;;###autoload
9379 (defun org-store-link (arg)
9380 "\\<org-mode-map>Store an org-link to the current location.
9381 This link is added to `org-stored-links' and can later be inserted
9382 into an org-buffer with \\[org-insert-link].
9384 For some link types, a prefix arg is interpreted.
9385 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9386 For file links, arg negates `org-context-in-file-links'.
9388 A double prefix arg force skipping storing functions that are not
9389 part of Org's core.
9391 A triple prefix arg force storing a link for each line in the
9392 active region."
9393 (interactive "P")
9394 (org-load-modules-maybe)
9395 (if (and (equal arg '(64)) (org-region-active-p))
9396 (save-excursion
9397 (let ((end (region-end)))
9398 (goto-char (region-beginning))
9399 (set-mark (point))
9400 (while (< (point-at-eol) end)
9401 (move-end-of-line 1) (activate-mark)
9402 (let (current-prefix-arg)
9403 (call-interactively 'org-store-link))
9404 (move-beginning-of-line 2)
9405 (set-mark (point)))))
9406 (org-with-limited-levels
9407 (setq org-store-link-plist nil)
9408 (let (link cpltxt desc description search
9409 txt custom-id agenda-link sfuns sfunsn)
9410 (cond
9412 ;; Store a link using an external link type
9413 ((and (not (equal arg '(16)))
9414 (setq sfuns
9415 (delq
9416 nil (mapcar (lambda (f)
9417 (let (fs) (if (funcall f) (push f fs))))
9418 org-store-link-functions))
9419 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9420 (or (and (cdr sfuns)
9421 (funcall (intern
9422 (completing-read
9423 "Which function for creating the link? "
9424 sfunsn t (car sfunsn)))))
9425 (funcall (caar sfuns)))
9426 (setq link (plist-get org-store-link-plist :link)
9427 desc (or (plist-get org-store-link-plist
9428 :description) link))))
9430 ;; Store a link from a source code buffer
9431 ((org-src-edit-buffer-p)
9432 (let (label gc)
9433 (while (or (not label)
9434 (save-excursion
9435 (save-restriction
9436 (widen)
9437 (goto-char (point-min))
9438 (re-search-forward
9439 (regexp-quote (format org-coderef-label-format label))
9440 nil t))))
9441 (when label (message "Label exists already") (sit-for 2))
9442 (setq label (read-string "Code line label: " label)))
9443 (end-of-line 1)
9444 (setq link (format org-coderef-label-format label))
9445 (setq gc (- 79 (length link)))
9446 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9447 (insert link)
9448 (setq link (concat "(" label ")") desc nil)))
9450 ;; We are in the agenda, link to referenced location
9451 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9452 (let ((m (or (get-text-property (point) 'org-hd-marker)
9453 (get-text-property (point) 'org-marker))))
9454 (when m
9455 (org-with-point-at m
9456 (setq agenda-link
9457 (if (org-called-interactively-p 'any)
9458 (call-interactively 'org-store-link)
9459 (org-store-link nil)))))))
9461 ((eq major-mode 'calendar-mode)
9462 (let ((cd (calendar-cursor-to-date)))
9463 (setq link
9464 (format-time-string
9465 (car org-time-stamp-formats)
9466 (apply 'encode-time
9467 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9468 nil nil nil))))
9469 (org-store-link-props :type "calendar" :date cd)))
9471 ((eq major-mode 'help-mode)
9472 (setq link (concat "help:" (save-excursion
9473 (goto-char (point-min))
9474 (looking-at "^[^ ]+")
9475 (match-string 0))))
9476 (org-store-link-props :type "help"))
9478 ((eq major-mode 'w3-mode)
9479 (setq cpltxt (if (and (buffer-name)
9480 (not (string-match "Untitled" (buffer-name))))
9481 (buffer-name)
9482 (url-view-url t))
9483 link (url-view-url t))
9484 (org-store-link-props :type "w3" :url (url-view-url t)))
9486 ((eq major-mode 'image-mode)
9487 (setq cpltxt (concat "file:"
9488 (abbreviate-file-name buffer-file-name))
9489 link cpltxt)
9490 (org-store-link-props :type "image" :file buffer-file-name))
9492 ;; In dired, store a link to the file of the current line
9493 ((eq major-mode 'dired-mode)
9494 (let ((file (dired-get-filename nil t)))
9495 (setq file (if file
9496 (abbreviate-file-name
9497 (expand-file-name (dired-get-filename nil t)))
9498 ;; otherwise, no file so use current directory.
9499 default-directory))
9500 (setq cpltxt (concat "file:" file)
9501 link cpltxt)))
9503 ((setq search (run-hook-with-args-until-success
9504 'org-create-file-search-functions))
9505 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9506 "::" search))
9507 (setq cpltxt (or description link)))
9509 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9510 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9511 (cond
9512 ;; Store a link using the target at point
9513 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9514 (setq cpltxt
9515 (concat "file:"
9516 (abbreviate-file-name
9517 (buffer-file-name (buffer-base-buffer)))
9518 "::" (match-string 1))
9519 link cpltxt))
9520 ((and (featurep 'org-id)
9521 (or (eq org-id-link-to-org-use-id t)
9522 (and (org-called-interactively-p 'any)
9523 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9524 (and (eq org-id-link-to-org-use-id
9525 'create-if-interactive-and-no-custom-id)
9526 (not custom-id))))
9527 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9528 ;; Store a link using the ID at point
9529 (setq link (condition-case nil
9530 (prog1 (org-id-store-link)
9531 (setq desc (plist-get org-store-link-plist
9532 :description)))
9533 (error
9534 ;; Probably before first headline, link only to file
9535 (concat "file:"
9536 (abbreviate-file-name
9537 (buffer-file-name (buffer-base-buffer))))))))
9539 ;; Just link to current headline
9540 (setq cpltxt (concat "file:"
9541 (abbreviate-file-name
9542 (buffer-file-name (buffer-base-buffer)))))
9543 ;; Add a context search string
9544 (when (org-xor org-context-in-file-links arg)
9545 (let* ((ee (org-element-at-point))
9546 (et (org-element-type ee))
9547 (ev (plist-get (cadr ee) :value))
9548 (ek (plist-get (cadr ee) :key))
9549 (eok (and (stringp ek) (string-match "name" ek))))
9550 (setq txt (cond
9551 ((org-at-heading-p) nil)
9552 ((and (eq et 'keyword) eok) ev)
9553 ((org-region-active-p)
9554 (buffer-substring (region-beginning) (region-end)))))
9555 (when (or (null txt) (string-match "\\S-" txt))
9556 (setq cpltxt
9557 (concat cpltxt "::"
9558 (condition-case nil
9559 (org-make-org-heading-search-string txt)
9560 (error "")))
9561 desc (or (and (eq et 'keyword) eok ev)
9562 (nth 4 (ignore-errors (org-heading-components)))
9563 "NONE")))))
9564 (if (string-match "::\\'" cpltxt)
9565 (setq cpltxt (substring cpltxt 0 -2)))
9566 (setq link cpltxt))))
9568 ((buffer-file-name (buffer-base-buffer))
9569 ;; Just link to this file here.
9570 (setq cpltxt (concat "file:"
9571 (abbreviate-file-name
9572 (buffer-file-name (buffer-base-buffer)))))
9573 ;; Add a context string.
9574 (when (org-xor org-context-in-file-links arg)
9575 (setq txt (if (org-region-active-p)
9576 (buffer-substring (region-beginning) (region-end))
9577 (buffer-substring (point-at-bol) (point-at-eol))))
9578 ;; Only use search option if there is some text.
9579 (when (string-match "\\S-" txt)
9580 (setq cpltxt
9581 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9582 desc "NONE")))
9583 (setq link cpltxt))
9585 ((org-called-interactively-p 'interactive)
9586 (user-error "No method for storing a link from this buffer"))
9588 (t (setq link nil)))
9590 ;; We're done setting link and desc, clean up
9591 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9592 (setq link (or link cpltxt)
9593 desc (or desc cpltxt))
9594 (cond ((equal desc "NONE") (setq desc nil))
9595 ((string-match org-bracket-link-analytic-regexp desc)
9596 (let ((d0 (match-string 3 desc))
9597 (p0 (match-string 5 desc)))
9598 (setq desc
9599 (replace-regexp-in-string
9600 org-bracket-link-regexp
9601 (concat (or p0 d0)
9602 (if (equal (length (match-string 0 desc))
9603 (length desc)) "*" "")) desc)))))
9605 ;; Return the link
9606 (if (not (and (or (org-called-interactively-p 'any)
9607 executing-kbd-macro) link))
9608 (or agenda-link (and link (org-make-link-string link desc)))
9609 (push (list link desc) org-stored-links)
9610 (message "Stored: %s" (or desc link))
9611 (when custom-id
9612 (setq link (concat "file:" (abbreviate-file-name
9613 (buffer-file-name)) "::#" custom-id))
9614 (push (list link desc) org-stored-links)))))))
9616 (defun org-store-link-props (&rest plist)
9617 "Store link properties, extract names and addresses."
9618 (let (x adr)
9619 (when (setq x (plist-get plist :from))
9620 (setq adr (mail-extract-address-components x))
9621 (setq plist (plist-put plist :fromname (car adr)))
9622 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9623 (when (setq x (plist-get plist :to))
9624 (setq adr (mail-extract-address-components x))
9625 (setq plist (plist-put plist :toname (car adr)))
9626 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9627 (let ((from (plist-get plist :from))
9628 (to (plist-get plist :to)))
9629 (when (and from to org-from-is-user-regexp)
9630 (setq plist
9631 (plist-put plist :fromto
9632 (if (string-match org-from-is-user-regexp from)
9633 (concat "to %t")
9634 (concat "from %f"))))))
9635 (setq org-store-link-plist plist))
9637 (defun org-add-link-props (&rest plist)
9638 "Add these properties to the link property list."
9639 (let (key value)
9640 (while plist
9641 (setq key (pop plist) value (pop plist))
9642 (setq org-store-link-plist
9643 (plist-put org-store-link-plist key value)))))
9645 (defun org-email-link-description (&optional fmt)
9646 "Return the description part of an email link.
9647 This takes information from `org-store-link-plist' and formats it
9648 according to FMT (default from `org-email-link-description-format')."
9649 (setq fmt (or fmt org-email-link-description-format))
9650 (let* ((p org-store-link-plist)
9651 (to (plist-get p :toaddress))
9652 (from (plist-get p :fromaddress))
9653 (table
9654 (list
9655 (cons "%c" (plist-get p :fromto))
9656 (cons "%F" (plist-get p :from))
9657 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9658 (cons "%T" (plist-get p :to))
9659 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9660 (cons "%s" (plist-get p :subject))
9661 (cons "%d" (plist-get p :date))
9662 (cons "%m" (plist-get p :message-id)))))
9663 (when (string-match "%c" fmt)
9664 ;; Check if the user wrote this message
9665 (if (and org-from-is-user-regexp from to
9666 (save-match-data (string-match org-from-is-user-regexp from)))
9667 (setq fmt (replace-match "to %t" t t fmt))
9668 (setq fmt (replace-match "from %f" t t fmt))))
9669 (org-replace-escapes fmt table)))
9671 (defun org-make-org-heading-search-string (&optional string)
9672 "Make search string for the current headline or STRING."
9673 (let ((s (or string
9674 (and (derived-mode-p 'org-mode)
9675 (save-excursion
9676 (org-back-to-heading t)
9677 (org-element-property :raw-value (org-element-at-point))))))
9678 (lines org-context-in-file-links))
9679 (or string (setq s (concat "*" s))) ; Add * for headlines
9680 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9681 (when (and string (integerp lines) (> lines 0))
9682 (let ((slines (org-split-string s "\n")))
9683 (when (< lines (length slines))
9684 (setq s (mapconcat
9685 'identity
9686 (reverse (nthcdr (- (length slines) lines)
9687 (reverse slines))) "\n")))))
9688 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9690 (defun org-make-link-string (link &optional description)
9691 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9692 (unless (string-match "\\S-" link)
9693 (error "Empty link"))
9694 (when (and description
9695 (stringp description)
9696 (not (string-match "\\S-" description)))
9697 (setq description nil))
9698 (when (stringp description)
9699 ;; Remove brackets from the description, they are fatal.
9700 (while (string-match "\\[" description)
9701 (setq description (replace-match "{" t t description)))
9702 (while (string-match "\\]" description)
9703 (setq description (replace-match "}" t t description))))
9704 (when (equal link description)
9705 ;; No description needed, it is identical
9706 (setq description nil))
9707 (when (and (not description)
9708 (not (string-match (org-image-file-name-regexp) link))
9709 (not (equal link (org-link-escape link))))
9710 (setq description (org-extract-attributes link)))
9711 (setq link
9712 (cond ((string-match (org-image-file-name-regexp) link) link)
9713 ((string-match org-link-types-re link)
9714 (concat (match-string 1 link)
9715 (org-link-escape (substring link (match-end 1)))))
9716 (t (org-link-escape link))))
9717 (concat "[[" link "]"
9718 (if description (concat "[" description "]") "")
9719 "]"))
9721 (defconst org-link-escape-chars
9722 ;;%20 %2B %3B %3D %5B %5D
9723 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9724 "List of characters that should be escaped in link.
9725 This is the list that is used for internal purposes.")
9727 (defconst org-link-escape-chars-browser
9728 ;;%20 %22
9729 '(?\ ?\")
9730 "List of escapes for characters that are problematic in links.
9731 This is the list that is used before handing over to the browser.")
9733 (defun org-link-escape (text &optional table merge)
9734 "Return percent escaped representation of TEXT.
9735 TEXT is a string with the text to escape.
9736 Optional argument TABLE is a list with characters that should be
9737 escaped. When nil, `org-link-escape-chars' is used.
9738 If optional argument MERGE is set, merge TABLE into
9739 `org-link-escape-chars'."
9740 (cond
9741 ((and table merge)
9742 (mapc (lambda (defchr)
9743 (unless (member defchr table)
9744 (setq table (cons defchr table)))) org-link-escape-chars))
9745 ((null table)
9746 (setq table org-link-escape-chars)))
9747 (mapconcat
9748 (lambda (char)
9749 (if (or (member char table)
9750 (and (or (< char 32) (= char ?\%) (> char 126))
9751 org-url-hexify-p))
9752 (mapconcat (lambda (sequence-element)
9753 (format "%%%.2X" sequence-element))
9754 (or (encode-coding-char char 'utf-8)
9755 (error "Unable to percent escape character: %s"
9756 (char-to-string char))) "")
9757 (char-to-string char))) text ""))
9759 (defun org-link-escape-browser (text)
9760 (if (org-string-match-p
9761 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9762 text)
9763 (org-link-escape text org-link-escape-chars-browser)
9764 text))
9766 (defun org-link-unescape (str)
9767 "Unhex hexified Unicode strings as returned from the JavaScript function
9768 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9769 (unless (and (null str) (string= "" str))
9770 (let ((pos 0) (case-fold-search t) unhexed)
9771 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9772 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9773 (setq str (replace-match unhexed t t str))
9774 (setq pos (+ pos (length unhexed))))))
9775 str)
9777 (defun org-link-unescape-compound (hex)
9778 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9779 Note: this function also decodes single byte encodings like
9780 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9781 (save-match-data
9782 (let* ((bytes (cdr (split-string hex "%")))
9783 (ret "")
9784 (eat 0)
9785 (sum 0))
9786 (while bytes
9787 (let* ((val (string-to-number (pop bytes) 16))
9788 (shift-xor
9789 (if (= 0 eat)
9790 (cond
9791 ((>= val 252) (cons 6 252))
9792 ((>= val 248) (cons 5 248))
9793 ((>= val 240) (cons 4 240))
9794 ((>= val 224) (cons 3 224))
9795 ((>= val 192) (cons 2 192))
9796 (t (cons 0 0)))
9797 (cons 6 128))))
9798 (if (>= val 192) (setq eat (car shift-xor)))
9799 (setq val (logxor val (cdr shift-xor)))
9800 (setq sum (+ (lsh sum (car shift-xor)) val))
9801 (if (> eat 0) (setq eat (- eat 1)))
9802 (cond
9803 ((= 0 eat) ;multi byte
9804 (setq ret (concat ret (org-char-to-string sum)))
9805 (setq sum 0))
9806 ((not bytes) ; single byte(s)
9807 (setq ret (org-link-unescape-single-byte-sequence hex))))
9808 )) ;; end (while bytes
9809 ret )))
9811 (defun org-link-unescape-single-byte-sequence (hex)
9812 "Unhexify hex-encoded single byte character sequences."
9813 (mapconcat (lambda (byte)
9814 (char-to-string (string-to-number byte 16)))
9815 (cdr (split-string hex "%")) ""))
9817 (defun org-xor (a b)
9818 "Exclusive or."
9819 (if a (not b) b))
9821 (defun org-fixup-message-id-for-http (s)
9822 "Replace special characters in a message id, so it can be used in an http query."
9823 (when (string-match "%" s)
9824 (setq s (mapconcat (lambda (c)
9825 (if (eq c ?%)
9826 "%25"
9827 (char-to-string c)))
9828 s "")))
9829 (while (string-match "<" s)
9830 (setq s (replace-match "%3C" t t s)))
9831 (while (string-match ">" s)
9832 (setq s (replace-match "%3E" t t s)))
9833 (while (string-match "@" s)
9834 (setq s (replace-match "%40" t t s)))
9837 (defun org-link-prettify (link)
9838 "Return a human-readable representation of LINK.
9839 The car of LINK must be a raw link the cdr of LINK must be either
9840 a link description or nil."
9841 (let ((desc (or (cadr link) "<no description>")))
9842 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9843 "<" (car link) ">")))
9845 ;;;###autoload
9846 (defun org-insert-link-global ()
9847 "Insert a link like Org-mode does.
9848 This command can be called in any mode to insert a link in Org-mode syntax."
9849 (interactive)
9850 (org-load-modules-maybe)
9851 (org-run-like-in-org-mode 'org-insert-link))
9853 (defun org-insert-all-links (&optional keep)
9854 "Insert all links in `org-stored-links'."
9855 (interactive "P")
9856 (let ((links (copy-sequence org-stored-links)) l)
9857 (while (setq l (if keep (pop links) (pop org-stored-links)))
9858 (insert "- ")
9859 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9860 (insert "\n"))))
9862 (defun org-link-fontify-links-to-this-file ()
9863 "Fontify links to the current file in `org-stored-links'."
9864 (let ((f (buffer-file-name)) a b)
9865 (setq a (mapcar (lambda(l)
9866 (let ((ll (car l)))
9867 (when (and (string-match "^file:\\(.+\\)::" ll)
9868 (equal f (expand-file-name (match-string 1 ll))))
9869 ll)))
9870 org-stored-links))
9871 (when (featurep 'org-id)
9872 (setq b (mapcar (lambda(l)
9873 (let ((ll (car l)))
9874 (when (and (string-match "^id:\\(.+\\)$" ll)
9875 (equal f (expand-file-name
9876 (or (org-id-find-id-file
9877 (match-string 1 ll)) ""))))
9878 ll)))
9879 org-stored-links)))
9880 (mapcar (lambda(l)
9881 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9882 (delq nil (append a b)))))
9884 (defvar org-link-links-in-this-file nil)
9885 (defun org-insert-link (&optional complete-file link-location default-description)
9886 "Insert a link. At the prompt, enter the link.
9888 Completion can be used to insert any of the link protocol prefixes like
9889 http or ftp in use.
9891 The history can be used to select a link previously stored with
9892 `org-store-link'. When the empty string is entered (i.e. if you just
9893 press RET at the prompt), the link defaults to the most recently
9894 stored link. As SPC triggers completion in the minibuffer, you need to
9895 use M-SPC or C-q SPC to force the insertion of a space character.
9897 You will also be prompted for a description, and if one is given, it will
9898 be displayed in the buffer instead of the link.
9900 If there is already a link at point, this command will allow you to edit link
9901 and description parts.
9903 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9904 be selected using completion. The path to the file will be relative to the
9905 current directory if the file is in the current directory or a subdirectory.
9906 Otherwise, the link will be the absolute path as completed in the minibuffer
9907 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9908 option `org-link-file-path-type'.
9910 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9911 the current directory or below.
9913 With three \\[universal-argument] prefixes, negate the meaning of
9914 `org-keep-stored-link-after-insertion'.
9916 If `org-make-link-description-function' is non-nil, this function will be
9917 called with the link target, and the result will be the default
9918 link description.
9920 If the LINK-LOCATION parameter is non-nil, this value will be
9921 used as the link location instead of reading one interactively.
9923 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9924 be used as the default description."
9925 (interactive "P")
9926 (let* ((wcf (current-window-configuration))
9927 (origbuf (current-buffer))
9928 (region (if (org-region-active-p)
9929 (buffer-substring (region-beginning) (region-end))))
9930 (remove (and region (list (region-beginning) (region-end))))
9931 (desc region)
9932 tmphist ; byte-compile incorrectly complains about this
9933 (link link-location)
9934 (abbrevs org-link-abbrev-alist-local)
9935 entry file all-prefixes auto-desc)
9936 (cond
9937 (link-location) ; specified by arg, just use it.
9938 ((org-in-regexp org-bracket-link-regexp 1)
9939 ;; We do have a link at point, and we are going to edit it.
9940 (setq remove (list (match-beginning 0) (match-end 0)))
9941 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9942 (setq link (read-string "Link: "
9943 (org-link-unescape
9944 (org-match-string-no-properties 1)))))
9945 ((or (org-in-regexp org-angle-link-re)
9946 (org-in-regexp org-plain-link-re))
9947 ;; Convert to bracket link
9948 (setq remove (list (match-beginning 0) (match-end 0))
9949 link (read-string "Link: "
9950 (org-remove-angle-brackets (match-string 0)))))
9951 ((member complete-file '((4) (16)))
9952 ;; Completing read for file names.
9953 (setq link (org-file-complete-link complete-file)))
9955 ;; Read link, with completion for stored links.
9956 (org-link-fontify-links-to-this-file)
9957 (org-switch-to-buffer-other-window "*Org Links*")
9958 (with-current-buffer "*Org Links*"
9959 (erase-buffer)
9960 (insert "Insert a link.
9961 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9962 (when org-stored-links
9963 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9964 (insert (mapconcat 'org-link-prettify
9965 (reverse org-stored-links) "\n")))
9966 (goto-char (point-min)))
9967 (let ((cw (selected-window)))
9968 (select-window (get-buffer-window "*Org Links*" 'visible))
9969 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9970 (unless (pos-visible-in-window-p (point-max))
9971 (org-fit-window-to-buffer))
9972 (and (window-live-p cw) (select-window cw)))
9973 ;; Fake a link history, containing the stored links.
9974 (setq tmphist (append (mapcar 'car org-stored-links)
9975 org-insert-link-history))
9976 (setq all-prefixes (append (mapcar 'car abbrevs)
9977 (mapcar 'car org-link-abbrev-alist)
9978 org-link-types))
9979 (unwind-protect
9980 (progn
9981 (setq link
9982 (org-completing-read
9983 "Link: "
9984 (append
9985 (mapcar (lambda (x) (concat x ":"))
9986 all-prefixes)
9987 (mapcar 'car org-stored-links))
9988 nil nil nil
9989 'tmphist
9990 (caar org-stored-links)))
9991 (if (not (string-match "\\S-" link))
9992 (user-error "No link selected"))
9993 (mapc (lambda(l)
9994 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9995 org-stored-links)
9996 (if (or (member link all-prefixes)
9997 (and (equal ":" (substring link -1))
9998 (member (substring link 0 -1) all-prefixes)
9999 (setq link (substring link 0 -1))))
10000 (setq link (with-current-buffer origbuf
10001 (org-link-try-special-completion link)))))
10002 (set-window-configuration wcf)
10003 (kill-buffer "*Org Links*"))
10004 (setq entry (assoc link org-stored-links))
10005 (or entry (push link org-insert-link-history))
10006 (setq desc (or desc (nth 1 entry)))))
10008 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10009 (not org-keep-stored-link-after-insertion))
10010 (setq org-stored-links (delq (assoc link org-stored-links)
10011 org-stored-links)))
10013 (if (string-match org-plain-link-re link)
10014 ;; URL-like link, normalize the use of angular brackets.
10015 (setq link (org-remove-angle-brackets link)))
10017 ;; Check if we are linking to the current file with a search
10018 ;; option If yes, simplify the link by using only the search
10019 ;; option.
10020 (when (and buffer-file-name
10021 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10022 (let* ((path (match-string 1 link))
10023 (case-fold-search nil)
10024 (search (match-string 2 link)))
10025 (save-match-data
10026 (if (equal (file-truename buffer-file-name) (file-truename path))
10027 ;; We are linking to this same file, with a search option
10028 (setq link search)))))
10030 ;; Check if we can/should use a relative path. If yes, simplify the link
10031 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10032 (let* ((type (match-string 1 link))
10033 (path (match-string 2 link))
10034 (origpath path)
10035 (case-fold-search nil))
10036 (cond
10037 ((or (eq org-link-file-path-type 'absolute)
10038 (equal complete-file '(16)))
10039 (setq path (abbreviate-file-name (expand-file-name path))))
10040 ((eq org-link-file-path-type 'noabbrev)
10041 (setq path (expand-file-name path)))
10042 ((eq org-link-file-path-type 'relative)
10043 (setq path (file-relative-name path)))
10045 (save-match-data
10046 (if (string-match (concat "^" (regexp-quote
10047 (expand-file-name
10048 (file-name-as-directory
10049 default-directory))))
10050 (expand-file-name path))
10051 ;; We are linking a file with relative path name.
10052 (setq path (substring (expand-file-name path)
10053 (match-end 0)))
10054 (setq path (abbreviate-file-name (expand-file-name path)))))))
10055 (setq link (concat type path))
10056 (if (equal desc origpath)
10057 (setq desc path))))
10059 (if org-make-link-description-function
10060 (setq desc
10061 (or (condition-case nil
10062 (funcall org-make-link-description-function link desc)
10063 (error (progn (message "Can't get link description from `%s'"
10064 (symbol-name org-make-link-description-function))
10065 (sit-for 2) nil)))
10066 (read-string "Description: " default-description)))
10067 (if default-description (setq desc default-description)
10068 (setq desc (or (and auto-desc desc)
10069 (read-string "Description: " desc)))))
10071 (unless (string-match "\\S-" desc) (setq desc nil))
10072 (if remove (apply 'delete-region remove))
10073 (insert (org-make-link-string link desc))))
10075 (defun org-link-try-special-completion (type)
10076 "If there is completion support for link type TYPE, offer it."
10077 (let ((fun (intern (concat "org-" type "-complete-link"))))
10078 (if (functionp fun)
10079 (funcall fun)
10080 (read-string "Link (no completion support): " (concat type ":")))))
10082 (defun org-file-complete-link (&optional arg)
10083 "Create a file link using completion."
10084 (let (file link)
10085 (setq file (org-iread-file-name "File: "))
10086 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10087 (pwd1 (file-name-as-directory (abbreviate-file-name
10088 (expand-file-name ".")))))
10089 (cond
10090 ((equal arg '(16))
10091 (setq link (concat
10092 "file:"
10093 (abbreviate-file-name (expand-file-name file)))))
10094 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10095 (setq link (concat "file:" (match-string 1 file))))
10096 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10097 (expand-file-name file))
10098 (setq link (concat
10099 "file:" (match-string 1 (expand-file-name file)))))
10100 (t (setq link (concat "file:" file)))))
10101 link))
10103 (defun org-iread-file-name (&rest args)
10104 "Read-file-name using `ido-mode' speedup if available.
10105 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10106 See `read-file-name' for a description of parameters."
10107 (org-without-partial-completion
10108 (if (and org-completion-use-ido
10109 (fboundp 'ido-read-file-name)
10110 (boundp 'ido-mode) ido-mode
10111 (listp (second args)))
10112 (let ((ido-enter-matching-directory nil))
10113 (apply 'ido-read-file-name args))
10114 (apply 'read-file-name args))))
10116 (defun org-completing-read (&rest args)
10117 "Completing-read with SPACE being a normal character."
10118 (let ((enable-recursive-minibuffers t)
10119 (minibuffer-local-completion-map
10120 (copy-keymap minibuffer-local-completion-map)))
10121 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10122 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10123 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10124 (apply 'org-icompleting-read args)))
10126 (defun org-completing-read-no-i (&rest args)
10127 (let (org-completion-use-ido org-completion-use-iswitchb)
10128 (apply 'org-completing-read args)))
10130 (defun org-iswitchb-completing-read (prompt choices &rest args)
10131 "Use iswitch as a completing-read replacement to choose from choices.
10132 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10133 from."
10134 (let* ((iswitchb-use-virtual-buffers nil)
10135 (iswitchb-make-buflist-hook
10136 (lambda ()
10137 (setq iswitchb-temp-buflist choices))))
10138 (iswitchb-read-buffer prompt)))
10140 (defun org-icompleting-read (&rest args)
10141 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10142 (org-without-partial-completion
10143 (if (and org-completion-use-ido
10144 (fboundp 'ido-completing-read)
10145 (boundp 'ido-mode) ido-mode
10146 (listp (second args)))
10147 (let ((ido-enter-matching-directory nil))
10148 (apply 'ido-completing-read (concat (car args))
10149 (if (consp (car (nth 1 args)))
10150 (mapcar 'car (nth 1 args))
10151 (nth 1 args))
10152 (cddr args)))
10153 (if (and org-completion-use-iswitchb
10154 (boundp 'iswitchb-mode) iswitchb-mode
10155 (listp (second args)))
10156 (apply 'org-iswitchb-completing-read (concat (car args))
10157 (if (consp (car (nth 1 args)))
10158 (mapcar 'car (nth 1 args))
10159 (nth 1 args))
10160 (cddr args))
10161 (apply 'completing-read args)))))
10163 (defun org-extract-attributes (s)
10164 "Extract the attributes cookie from a string and set as text property."
10165 (let (a attr (start 0) key value)
10166 (save-match-data
10167 (when (string-match "{{\\([^}]+\\)}}$" s)
10168 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10169 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10170 (setq key (match-string 1 a) value (match-string 2 a)
10171 start (match-end 0)
10172 attr (plist-put attr (intern key) value))))
10173 (org-add-props s nil 'org-attr attr))
10176 ;;; Opening/following a link
10178 (defvar org-link-search-failed nil)
10180 (defvar org-open-link-functions nil
10181 "Hook for functions finding a plain text link.
10182 These functions must take a single argument, the link content.
10183 They will be called for links that look like [[link text][description]]
10184 when LINK TEXT does not have a protocol like \"http:\" and does not look
10185 like a filename (e.g. \"./blue.png\").
10187 These functions will be called *before* Org attempts to resolve the
10188 link by doing text searches in the current buffer - so if you want a
10189 link \"[[target]]\" to still find \"<<target>>\", your function should
10190 handle this as a special case.
10192 When the function does handle the link, it must return a non-nil value.
10193 If it decides that it is not responsible for this link, it must return
10194 nil to indicate that that Org-mode can continue with other options
10195 like exact and fuzzy text search.")
10197 (defun org-next-link (&optional search-backward)
10198 "Move forward to the next link.
10199 If the link is in hidden text, expose it."
10200 (interactive "P")
10201 (when (and org-link-search-failed (eq this-command last-command))
10202 (goto-char (point-min))
10203 (message "Link search wrapped back to beginning of buffer"))
10204 (setq org-link-search-failed nil)
10205 (let* ((pos (point))
10206 (ct (org-context))
10207 (a (assoc :link ct))
10208 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10209 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10210 ((looking-at org-any-link-re)
10211 ;; Don't stay stuck at link without an org-link face
10212 (forward-char (if search-backward -1 1))))
10213 (if (funcall srch-fun org-any-link-re nil t)
10214 (progn
10215 (goto-char (match-beginning 0))
10216 (if (outline-invisible-p) (org-show-context)))
10217 (goto-char pos)
10218 (setq org-link-search-failed t)
10219 (message "No further link found"))))
10221 (defun org-previous-link ()
10222 "Move backward to the previous link.
10223 If the link is in hidden text, expose it."
10224 (interactive)
10225 (funcall 'org-next-link t))
10227 (defun org-translate-link (s)
10228 "Translate a link string if a translation function has been defined."
10229 (if (and org-link-translation-function
10230 (fboundp org-link-translation-function)
10231 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10232 (progn
10233 (setq s (funcall org-link-translation-function
10234 (match-string 1 s) (match-string 2 s)))
10235 (concat (car s) ":" (cdr s)))
10238 (defun org-translate-link-from-planner (type path)
10239 "Translate a link from Emacs Planner syntax so that Org can follow it.
10240 This is still an experimental function, your mileage may vary."
10241 (cond
10242 ((member type '("http" "https" "news" "ftp"))
10243 ;; standard Internet links are the same.
10244 nil)
10245 ((and (equal type "irc") (string-match "^//" path))
10246 ;; Planner has two / at the beginning of an irc link, we have 1.
10247 ;; We should have zero, actually....
10248 (setq path (substring path 1)))
10249 ((and (equal type "lisp") (string-match "^/" path))
10250 ;; Planner has a slash, we do not.
10251 (setq type "elisp" path (substring path 1)))
10252 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10253 ;; A typical message link. Planner has the id after the final slash,
10254 ;; we separate it with a hash mark
10255 (setq path (concat (match-string 1 path) "#"
10256 (org-remove-angle-brackets (match-string 2 path))))))
10257 (cons type path))
10259 (defun org-find-file-at-mouse (ev)
10260 "Open file link or URL at mouse."
10261 (interactive "e")
10262 (mouse-set-point ev)
10263 (org-open-at-point 'in-emacs))
10265 (defun org-open-at-mouse (ev)
10266 "Open file link or URL at mouse.
10267 See the docstring of `org-open-file' for details."
10268 (interactive "e")
10269 (mouse-set-point ev)
10270 (if (eq major-mode 'org-agenda-mode)
10271 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10272 (org-open-at-point))
10274 (defvar org-window-config-before-follow-link nil
10275 "The window configuration before following a link.
10276 This is saved in case the need arises to restore it.")
10278 (defvar org-open-link-marker (make-marker)
10279 "Marker pointing to the location where `org-open-at-point; was called.")
10281 ;;;###autoload
10282 (defun org-open-at-point-global ()
10283 "Follow a link like Org-mode does.
10284 This command can be called in any mode to follow a link that has
10285 Org-mode syntax."
10286 (interactive)
10287 (org-run-like-in-org-mode 'org-open-at-point))
10289 ;;;###autoload
10290 (defun org-open-link-from-string (s &optional arg reference-buffer)
10291 "Open a link in the string S, as if it was in Org-mode."
10292 (interactive "sLink: \nP")
10293 (let ((reference-buffer (or reference-buffer (current-buffer))))
10294 (with-temp-buffer
10295 (let ((org-inhibit-startup (not reference-buffer)))
10296 (org-mode)
10297 (insert s)
10298 (goto-char (point-min))
10299 (when reference-buffer
10300 (setq org-link-abbrev-alist-local
10301 (with-current-buffer reference-buffer
10302 org-link-abbrev-alist-local)))
10303 (org-open-at-point arg reference-buffer)))))
10305 (defvar org-open-at-point-functions nil
10306 "Hook that is run when following a link at point.
10308 Functions in this hook must return t if they identify and follow
10309 a link at point. If they don't find anything interesting at point,
10310 they must return nil.")
10312 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10313 (defun org-open-at-point (&optional arg reference-buffer)
10314 "Open link at or after point.
10315 If there is no link at point, this function will search forward up to
10316 the end of the current line.
10317 Normally, files will be opened by an appropriate application. If the
10318 optional prefix argument ARG is non-nil, Emacs will visit the file.
10319 With a double prefix argument, try to open outside of Emacs, in the
10320 application the system uses for this file type."
10321 (interactive "P")
10322 ;; if in a code block, then open the block's results
10323 (unless (call-interactively #'org-babel-open-src-block-result)
10324 (org-load-modules-maybe)
10325 (move-marker org-open-link-marker (point))
10326 (setq org-window-config-before-follow-link (current-window-configuration))
10327 (org-remove-occur-highlights nil nil t)
10328 (cond
10329 ((and (org-at-heading-p)
10330 (not (org-at-timestamp-p t))
10331 (not (org-in-regexp
10332 (concat org-plain-link-re "\\|"
10333 org-bracket-link-regexp "\\|"
10334 org-angle-link-re "\\|"
10335 "[ \t]:[^ \t\n]+:[ \t]*$")))
10336 (not (get-text-property (point) 'org-linked-text)))
10337 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10338 (lk0 (car lkall))
10339 (lk (if (stringp lk0) (list lk0) lk0))
10340 (lkend (cdr lkall)))
10341 (mapcar (lambda(l)
10342 (search-forward l nil lkend)
10343 (goto-char (match-beginning 0))
10344 (org-open-at-point))
10345 lk))
10346 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10347 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10348 ((and (org-at-timestamp-p t)
10349 (not (org-in-regexp org-bracket-link-regexp)))
10350 (org-follow-timestamp-link))
10351 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10352 (not (org-in-regexp org-any-link-re)))
10353 (org-footnote-action))
10355 (let (type path link line search (pos (point)))
10356 (catch 'match
10357 (save-excursion
10358 (skip-chars-forward "^]\n\r")
10359 (when (org-in-regexp org-bracket-link-regexp 1)
10360 (setq link (org-extract-attributes
10361 (org-link-unescape (org-match-string-no-properties 1))))
10362 (while (string-match " *\n *" link)
10363 (setq link (replace-match " " t t link)))
10364 (setq link (org-link-expand-abbrev link))
10365 (cond
10366 ((or (file-name-absolute-p link)
10367 (string-match "^\\.\\.?/" link))
10368 (setq type "file" path link))
10369 ((string-match org-link-re-with-space3 link)
10370 (setq type (match-string 1 link) path (match-string 2 link)))
10371 ((string-match "^help:+\\(.+\\)" link)
10372 (setq type "help" path (match-string 1 link)))
10373 (t (setq type "thisfile" path link)))
10374 (throw 'match t)))
10376 (when (get-text-property (point) 'org-linked-text)
10377 (setq type "thisfile"
10378 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10379 (1+ (point)) (point))
10380 path (buffer-substring
10381 (or (previous-single-property-change pos 'org-linked-text)
10382 (point-min))
10383 (or (next-single-property-change pos 'org-linked-text)
10384 (point-max)))
10385 ;; Ensure we will search for a <<<radio>>> link, not
10386 ;; a simple reference like <<ref>>
10387 path (concat "<" path))
10388 (throw 'match t))
10390 (save-excursion
10391 (when (or (org-in-regexp org-angle-link-re)
10392 (let ((match (org-in-regexp org-plain-link-re)))
10393 ;; Check a plain link is not within a bracket link
10394 (and match
10395 (save-excursion
10396 (progn
10397 (goto-char (car match))
10398 (not (org-in-regexp org-bracket-link-regexp))))))
10399 (let ((line_ending (save-excursion (end-of-line) (point))))
10400 ;; We are in a line before a plain or bracket link
10401 (or (re-search-forward org-plain-link-re line_ending t)
10402 (re-search-forward org-bracket-link-regexp line_ending t))))
10403 (setq type (match-string 1)
10404 path (org-link-unescape (match-string 2)))
10405 (throw 'match t)))
10406 (save-excursion
10407 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10408 (setq type "tags"
10409 path (match-string 1))
10410 (while (string-match ":" path)
10411 (setq path (replace-match "+" t t path)))
10412 (throw 'match t)))
10413 (when (org-in-regexp "<\\([^><\n]+\\)>")
10414 (setq type "tree-match"
10415 path (match-string 1))
10416 (throw 'match t)))
10417 (unless path
10418 (user-error "No link found"))
10420 ;; switch back to reference buffer
10421 ;; needed when if called in a temporary buffer through
10422 ;; org-open-link-from-string
10423 (with-current-buffer (or reference-buffer (current-buffer))
10425 ;; Remove any trailing spaces in path
10426 (if (string-match " +\\'" path)
10427 (setq path (replace-match "" t t path)))
10428 (if (and org-link-translation-function
10429 (fboundp org-link-translation-function))
10430 ;; Check if we need to translate the link
10431 (let ((tmp (funcall org-link-translation-function type path)))
10432 (setq type (car tmp) path (cdr tmp))))
10434 (cond
10436 ((assoc type org-link-protocols)
10437 (funcall (nth 1 (assoc type org-link-protocols)) path))
10439 ((equal type "help")
10440 (let ((f-or-v (intern path)))
10441 (cond ((fboundp f-or-v)
10442 (describe-function f-or-v))
10443 ((boundp f-or-v)
10444 (describe-variable f-or-v))
10445 (t (error "Not a known function or variable")))))
10447 ((equal type "mailto")
10448 (let ((cmd (car org-link-mailto-program))
10449 (args (cdr org-link-mailto-program)) args1
10450 (address path) (subject "") a)
10451 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10452 (setq address (match-string 1 path)
10453 subject (org-link-escape (match-string 2 path))))
10454 (while args
10455 (cond
10456 ((not (stringp (car args))) (push (pop args) args1))
10457 (t (setq a (pop args))
10458 (if (string-match "%a" a)
10459 (setq a (replace-match address t t a)))
10460 (if (string-match "%s" a)
10461 (setq a (replace-match subject t t a)))
10462 (push a args1))))
10463 (apply cmd (nreverse args1))))
10465 ((member type '("http" "https" "ftp" "news"))
10466 (browse-url (concat type ":" (org-link-escape-browser path))))
10468 ((string= type "doi")
10469 (browse-url (concat org-doi-server-url
10470 (org-link-escape-browser path))))
10472 ((member type '("message"))
10473 (browse-url (concat type ":" path)))
10475 ((string= type "tags")
10476 (org-tags-view arg path))
10478 ((string= type "tree-match")
10479 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10481 ((string= type "file")
10482 (if (string-match "::\\([0-9]+\\)\\'" path)
10483 (setq line (string-to-number (match-string 1 path))
10484 path (substring path 0 (match-beginning 0)))
10485 (if (string-match "::\\(.+\\)\\'" path)
10486 (setq search (match-string 1 path)
10487 path (substring path 0 (match-beginning 0)))))
10488 (if (string-match "[*?{]" (file-name-nondirectory path))
10489 (dired path)
10490 (org-open-file path arg line search)))
10492 ((string= type "shell")
10493 (let ((buf (generate-new-buffer "*Org Shell Output"))
10494 (cmd path))
10495 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10496 (string-match org-confirm-shell-link-not-regexp cmd))
10497 (not org-confirm-shell-link-function)
10498 (funcall org-confirm-shell-link-function
10499 (format "Execute \"%s\" in shell? "
10500 (org-add-props cmd nil
10501 'face 'org-warning))))
10502 (progn
10503 (message "Executing %s" cmd)
10504 (shell-command cmd buf)
10505 (if (featurep 'midnight)
10506 (setq clean-buffer-list-kill-buffer-names
10507 (cons buf clean-buffer-list-kill-buffer-names))))
10508 (error "Abort"))))
10510 ((string= type "elisp")
10511 (let ((cmd path))
10512 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10513 (string-match org-confirm-elisp-link-not-regexp cmd))
10514 (not org-confirm-elisp-link-function)
10515 (funcall org-confirm-elisp-link-function
10516 (format "Execute \"%s\" as elisp? "
10517 (org-add-props cmd nil
10518 'face 'org-warning))))
10519 (message "%s => %s" cmd
10520 (if (equal (string-to-char cmd) ?\()
10521 (eval (read cmd))
10522 (call-interactively (read cmd))))
10523 (error "Abort"))))
10525 ((and (string= type "thisfile")
10526 (or (run-hook-with-args-until-success
10527 'org-open-link-functions path)
10528 (and link
10529 (string-match "^id:" link)
10530 (or (featurep 'org-id) (require 'org-id))
10531 (progn
10532 (funcall (nth 1 (assoc "id" org-link-protocols))
10533 (substring path 3))
10534 t)))))
10536 ((string= type "thisfile")
10537 (if arg
10538 (switch-to-buffer-other-window
10539 (org-get-buffer-for-internal-link (current-buffer)))
10540 (org-mark-ring-push))
10541 (let ((cmd `(org-link-search
10542 ,path
10543 ,(cond ((equal arg '(4)) ''occur)
10544 ((equal arg '(16)) ''org-occur))
10545 ,pos)))
10546 (condition-case nil (let ((org-link-search-inhibit-query t))
10547 (eval cmd))
10548 (error (progn (widen) (eval cmd))))))
10550 (t (browse-url-at-point)))))))
10551 (move-marker org-open-link-marker nil)
10552 (run-hook-with-args 'org-follow-link-hook)))
10554 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10555 "Offer links in the current entry and return the selected link.
10556 If there is only one link, return it.
10557 If NTH is an integer, return the NTH link found.
10558 If ZERO is a string, check also this string for a link, and if
10559 there is one, return it."
10560 (with-current-buffer buffer
10561 (save-excursion
10562 (save-restriction
10563 (widen)
10564 (goto-char marker)
10565 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10566 "\\(" org-angle-link-re "\\)\\|"
10567 "\\(" org-plain-link-re "\\)"))
10568 (cnt ?0)
10569 (in-emacs (if (integerp nth) nil nth))
10570 have-zero end links link c)
10571 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10572 (push (match-string 0 zero) links)
10573 (setq cnt (1- cnt) have-zero t))
10574 (save-excursion
10575 (org-back-to-heading t)
10576 (setq end (save-excursion (outline-next-heading) (point)))
10577 (while (re-search-forward re end t)
10578 (push (match-string 0) links))
10579 (setq links (org-uniquify (reverse links))))
10580 (cond
10581 ((null links)
10582 (message "No links"))
10583 ((equal (length links) 1)
10584 (setq link (car links)))
10585 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10586 (setq link (nth (if have-zero nth (1- nth)) links)))
10587 (t ; we have to select a link
10588 (save-excursion
10589 (save-window-excursion
10590 (delete-other-windows)
10591 (with-output-to-temp-buffer "*Select Link*"
10592 (mapc (lambda (l)
10593 (if (not (string-match org-bracket-link-regexp l))
10594 (princ (format "[%c] %s\n" (incf cnt)
10595 (org-remove-angle-brackets l)))
10596 (if (match-end 3)
10597 (princ (format "[%c] %s (%s)\n" (incf cnt)
10598 (match-string 3 l) (match-string 1 l)))
10599 (princ (format "[%c] %s\n" (incf cnt)
10600 (match-string 1 l))))))
10601 links))
10602 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10603 (message "Select link to open, RET to open all:")
10604 (setq c (read-char-exclusive))
10605 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10606 (when (equal c ?q) (error "Abort"))
10607 (if (equal c ?\C-m)
10608 (setq link links)
10609 (setq nth (- c ?0))
10610 (if have-zero (setq nth (1+ nth)))
10611 (unless (and (integerp nth) (>= (length links) nth))
10612 (user-error "Invalid link selection"))
10613 (setq link (nth (1- nth) links)))))
10614 (cons link end))))))
10616 ;; Add special file links that specify the way of opening
10618 (org-add-link-type "file+sys" 'org-open-file-with-system)
10619 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10620 (defun org-open-file-with-system (path)
10621 "Open file at PATH using the system way of opening it."
10622 (org-open-file path 'system))
10623 (defun org-open-file-with-emacs (path)
10624 "Open file at PATH in Emacs."
10625 (org-open-file path 'emacs))
10628 ;;; File search
10630 (defvar org-create-file-search-functions nil
10631 "List of functions to construct the right search string for a file link.
10632 These functions are called in turn with point at the location to
10633 which the link should point.
10635 A function in the hook should first test if it would like to
10636 handle this file type, for example by checking the `major-mode'
10637 or the file extension. If it decides not to handle this file, it
10638 should just return nil to give other functions a chance. If it
10639 does handle the file, it must return the search string to be used
10640 when following the link. The search string will be part of the
10641 file link, given after a double colon, and `org-open-at-point'
10642 will automatically search for it. If special measures must be
10643 taken to make the search successful, another function should be
10644 added to the companion hook `org-execute-file-search-functions',
10645 which see.
10647 A function in this hook may also use `setq' to set the variable
10648 `description' to provide a suggestion for the descriptive text to
10649 be used for this link when it gets inserted into an Org-mode
10650 buffer with \\[org-insert-link].")
10652 (defvar org-execute-file-search-functions nil
10653 "List of functions to execute a file search triggered by a link.
10655 Functions added to this hook must accept a single argument, the
10656 search string that was part of the file link, the part after the
10657 double colon. The function must first check if it would like to
10658 handle this search, for example by checking the `major-mode' or
10659 the file extension. If it decides not to handle this search, it
10660 should just return nil to give other functions a chance. If it
10661 does handle the search, it must return a non-nil value to keep
10662 other functions from trying.
10664 Each function can access the current prefix argument through the
10665 variable `current-prefix-arg'. Note that a single prefix is used
10666 to force opening a link in Emacs, so it may be good to only use a
10667 numeric or double prefix to guide the search function.
10669 In case this is needed, a function in this hook can also restore
10670 the window configuration before `org-open-at-point' was called using:
10672 (set-window-configuration org-window-config-before-follow-link)")
10674 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10675 (defun org-link-search (s &optional type avoid-pos stealth)
10676 "Search for a link search option.
10677 If S is surrounded by forward slashes, it is interpreted as a
10678 regular expression. In org-mode files, this will create an `org-occur'
10679 sparse tree. In ordinary files, `occur' will be used to list matches.
10680 If the current buffer is in `dired-mode', grep will be used to search
10681 in all files. If AVOID-POS is given, ignore matches near that position.
10683 When optional argument STEALTH is non-nil, do not modify
10684 visibility around point, thus ignoring
10685 `org-show-hierarchy-above', `org-show-following-heading' and
10686 `org-show-siblings' variables."
10687 (let ((case-fold-search t)
10688 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10689 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10690 (append '(("") (" ") ("\t") ("\n"))
10691 org-emphasis-alist)
10692 "\\|") "\\)"))
10693 (pos (point))
10694 (pre nil) (post nil)
10695 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10696 (cond
10697 ;; First check if there are any special search functions
10698 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10699 ;; Now try the builtin stuff
10700 ((and (equal (string-to-char s0) ?#)
10701 (> (length s0) 1)
10702 (save-excursion
10703 (goto-char (point-min))
10704 (and
10705 (re-search-forward
10706 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10707 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10708 (setq type 'dedicated
10709 pos (match-beginning 0))))
10710 ;; There is an exact target for this
10711 (goto-char pos)
10712 (org-back-to-heading t)))
10713 ((save-excursion
10714 (goto-char (point-min))
10715 (and
10716 (re-search-forward
10717 (concat "<<" (regexp-quote s0) ">>") nil t)
10718 (setq type 'dedicated
10719 pos (match-beginning 0))))
10720 ;; There is an exact target for this
10721 (goto-char pos))
10722 ((save-excursion
10723 (goto-char (point-min))
10724 (and
10725 (re-search-forward
10726 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10727 (setq type 'dedicated pos (match-beginning 0))))
10728 ;; Found an element with a matching #+name affiliated keyword.
10729 (goto-char pos))
10730 ((and (string-match "^(\\(.*\\))$" s0)
10731 (save-excursion
10732 (goto-char (point-min))
10733 (and
10734 (re-search-forward
10735 (concat "[^[]" (regexp-quote
10736 (format org-coderef-label-format
10737 (match-string 1 s0))))
10738 nil t)
10739 (setq type 'dedicated
10740 pos (1+ (match-beginning 0))))))
10741 ;; There is a coderef target for this
10742 (goto-char pos))
10743 ((string-match "^/\\(.*\\)/$" s)
10744 ;; A regular expression
10745 (cond
10746 ((derived-mode-p 'org-mode)
10747 (org-occur (match-string 1 s)))
10748 (t (org-do-occur (match-string 1 s)))))
10749 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10750 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10751 (goto-char (point-min))
10752 (cond
10753 ((let (case-fold-search)
10754 (re-search-forward (format org-complex-heading-regexp-format
10755 (regexp-quote s))
10756 nil t))
10757 ;; OK, found a match
10758 (setq type 'dedicated)
10759 (goto-char (match-beginning 0)))
10760 ((and (not org-link-search-inhibit-query)
10761 (eq org-link-search-must-match-exact-headline 'query-to-create)
10762 (y-or-n-p "No match - create this as a new heading? "))
10763 (goto-char (point-max))
10764 (or (bolp) (newline))
10765 (insert "* " s "\n")
10766 (beginning-of-line 0))
10768 (goto-char pos)
10769 (error "No match"))))
10771 ;; A normal search string
10772 (when (equal (string-to-char s) ?*)
10773 ;; Anchor on headlines, post may include tags.
10774 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10775 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10776 s (substring s 1)))
10777 (remove-text-properties
10778 0 (length s)
10779 '(face nil mouse-face nil keymap nil fontified nil) s)
10780 ;; Make a series of regular expressions to find a match
10781 (setq words (org-split-string s "[ \n\r\t]+")
10783 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10784 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10785 "\\)" markers)
10786 re2a_ (concat "\\(" (mapconcat 'downcase words
10787 "[ \t\r\n]+") "\\)[ \t\r\n]")
10788 re2a (concat "[ \t\r\n]" re2a_)
10789 re4_ (concat "\\(" (mapconcat 'downcase words
10790 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10791 re4 (concat "[^a-zA-Z_]" re4_)
10793 re1 (concat pre re2 post)
10794 re3 (concat pre (if pre re4_ re4) post)
10795 re5 (concat pre ".*" re4)
10796 re2 (concat pre re2)
10797 re2a (concat pre (if pre re2a_ re2a))
10798 re4 (concat pre (if pre re4_ re4))
10799 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10800 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10801 re5 "\\)"))
10802 (cond
10803 ((eq type 'org-occur) (org-occur reall))
10804 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10805 (t (goto-char (point-min))
10806 (setq type 'fuzzy)
10807 (if (or (and (org-search-not-self 1 re0 nil t)
10808 (setq type 'dedicated))
10809 (org-search-not-self 1 re1 nil t)
10810 (org-search-not-self 1 re2 nil t)
10811 (org-search-not-self 1 re2a nil t)
10812 (org-search-not-self 1 re3 nil t)
10813 (org-search-not-self 1 re4 nil t)
10814 (org-search-not-self 1 re5 nil t))
10815 (goto-char (match-beginning 1))
10816 (goto-char pos)
10817 (error "No match"))))))
10818 (and (derived-mode-p 'org-mode)
10819 (not stealth)
10820 (org-show-context 'link-search))
10821 type))
10823 (defun org-search-not-self (group &rest args)
10824 "Execute `re-search-forward', but only accept matches that do not
10825 enclose the position of `org-open-link-marker'."
10826 (let ((m org-open-link-marker))
10827 (catch 'exit
10828 (while (apply 're-search-forward args)
10829 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10830 (goto-char (match-end group))
10831 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10832 (> (match-beginning 0) (marker-position m))
10833 (< (match-end 0) (marker-position m)))
10834 (save-match-data
10835 (or (not (org-in-regexp
10836 org-bracket-link-analytic-regexp 1))
10837 (not (match-end 4)) ; no description
10838 (and (<= (match-beginning 4) (point))
10839 (>= (match-end 4) (point))))))
10840 (throw 'exit (point))))))))
10842 (defun org-get-buffer-for-internal-link (buffer)
10843 "Return a buffer to be used for displaying the link target of internal links."
10844 (cond
10845 ((not org-display-internal-link-with-indirect-buffer)
10846 buffer)
10847 ((string-match "(Clone)$" (buffer-name buffer))
10848 (message "Buffer is already a clone, not making another one")
10849 ;; we also do not modify visibility in this case
10850 buffer)
10851 (t ; make a new indirect buffer for displaying the link
10852 (let* ((bn (buffer-name buffer))
10853 (ibn (concat bn "(Clone)"))
10854 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10855 (with-current-buffer ib (org-overview))
10856 ib))))
10858 (defun org-do-occur (regexp &optional cleanup)
10859 "Call the Emacs command `occur'.
10860 If CLEANUP is non-nil, remove the printout of the regular expression
10861 in the *Occur* buffer. This is useful if the regex is long and not useful
10862 to read."
10863 (occur regexp)
10864 (when cleanup
10865 (let ((cwin (selected-window)) win beg end)
10866 (when (setq win (get-buffer-window "*Occur*"))
10867 (select-window win))
10868 (goto-char (point-min))
10869 (when (re-search-forward "match[a-z]+" nil t)
10870 (setq beg (match-end 0))
10871 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10872 (setq end (1- (match-beginning 0)))))
10873 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10874 (goto-char (point-min))
10875 (select-window cwin))))
10877 ;;; The mark ring for links jumps
10879 (defvar org-mark-ring nil
10880 "Mark ring for positions before jumps in Org-mode.")
10881 (defvar org-mark-ring-last-goto nil
10882 "Last position in the mark ring used to go back.")
10883 ;; Fill and close the ring
10884 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10885 (loop for i from 1 to org-mark-ring-length do
10886 (push (make-marker) org-mark-ring))
10887 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10888 org-mark-ring)
10890 (defun org-mark-ring-push (&optional pos buffer)
10891 "Put the current position or POS into the mark ring and rotate it."
10892 (interactive)
10893 (setq pos (or pos (point)))
10894 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10895 (move-marker (car org-mark-ring)
10896 (or pos (point))
10897 (or buffer (current-buffer)))
10898 (message "%s"
10899 (substitute-command-keys
10900 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10902 (defun org-mark-ring-goto (&optional n)
10903 "Jump to the previous position in the mark ring.
10904 With prefix arg N, jump back that many stored positions. When
10905 called several times in succession, walk through the entire ring.
10906 Org-mode commands jumping to a different position in the current file,
10907 or to another Org-mode file, automatically push the old position
10908 onto the ring."
10909 (interactive "p")
10910 (let (p m)
10911 (if (eq last-command this-command)
10912 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10913 (setq p org-mark-ring))
10914 (setq org-mark-ring-last-goto p)
10915 (setq m (car p))
10916 (org-pop-to-buffer-same-window (marker-buffer m))
10917 (goto-char m)
10918 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10920 (defun org-remove-angle-brackets (s)
10921 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10922 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10924 (defun org-add-angle-brackets (s)
10925 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10926 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10928 (defun org-remove-double-quotes (s)
10929 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10930 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10933 ;;; Following specific links
10935 (defun org-follow-timestamp-link ()
10936 "Open an agenda view for the time-stamp date/range at point."
10937 (cond
10938 ((org-at-date-range-p t)
10939 (let ((org-agenda-start-on-weekday)
10940 (t1 (match-string 1))
10941 (t2 (match-string 2)) tt1 tt2)
10942 (setq tt1 (time-to-days (org-time-string-to-time t1))
10943 tt2 (time-to-days (org-time-string-to-time t2)))
10944 (let ((org-agenda-buffer-tmp-name
10945 (format "*Org Agenda(a:%s)"
10946 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10947 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10948 ((org-at-timestamp-p t)
10949 (let ((org-agenda-buffer-tmp-name
10950 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10951 (org-agenda-list nil (time-to-days (org-time-string-to-time
10952 (substring (match-string 1) 0 10)))
10953 1)))
10954 (t (error "This should not happen"))))
10957 ;;; Following file links
10958 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10959 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10960 (declare-function mailcap-mime-info
10961 "mailcap" (string &optional request no-decode))
10962 (defvar org-wait nil)
10963 (defun org-open-file (path &optional in-emacs line search)
10964 "Open the file at PATH.
10965 First, this expands any special file name abbreviations. Then the
10966 configuration variable `org-file-apps' is checked if it contains an
10967 entry for this file type, and if yes, the corresponding command is launched.
10969 If no application is found, Emacs simply visits the file.
10971 With optional prefix argument IN-EMACS, Emacs will visit the file.
10972 With a double \\[universal-argument] \\[universal-argument] \
10973 prefix arg, Org tries to avoid opening in Emacs
10974 and to use an external application to visit the file.
10976 Optional LINE specifies a line to go to, optional SEARCH a string
10977 to search for. If LINE or SEARCH is given, the file will be
10978 opened in Emacs, unless an entry from org-file-apps that makes
10979 use of groups in a regexp matches.
10981 If you want to change the way frames are used when following a
10982 link, please customize `org-link-frame-setup'.
10984 If the file does not exist, an error is thrown."
10985 (let* ((file (if (equal path "")
10986 buffer-file-name
10987 (substitute-in-file-name (expand-file-name path))))
10988 (file-apps (append org-file-apps (org-default-apps)))
10989 (apps (org-remove-if
10990 'org-file-apps-entry-match-against-dlink-p file-apps))
10991 (apps-dlink (org-remove-if-not
10992 'org-file-apps-entry-match-against-dlink-p file-apps))
10993 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10994 (dirp (if remp nil (file-directory-p file)))
10995 (file (if (and dirp org-open-directory-means-index-dot-org)
10996 (concat (file-name-as-directory file) "index.org")
10997 file))
10998 (a-m-a-p (assq 'auto-mode apps))
10999 (dfile (downcase file))
11000 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11001 (link (cond ((and (eq line nil)
11002 (eq search nil))
11003 file)
11004 (line
11005 (concat file "::" (number-to-string line)))
11006 (search
11007 (concat file "::" search))))
11008 (dlink (downcase link))
11009 (old-buffer (current-buffer))
11010 (old-pos (point))
11011 (old-mode major-mode)
11012 ext cmd link-match-data)
11013 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11014 (setq ext (match-string 1 dfile))
11015 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11016 (setq ext (match-string 1 dfile))))
11017 (cond
11018 ((member in-emacs '((16) system))
11019 (setq cmd (cdr (assoc 'system apps))))
11020 (in-emacs (setq cmd 'emacs))
11022 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11023 (and dirp (cdr (assoc 'directory apps)))
11024 ; first, try matching against apps-dlink
11025 ; if we get a match here, store the match data for later
11026 (let ((match (assoc-default dlink apps-dlink
11027 'string-match)))
11028 (if match
11029 (progn (setq link-match-data (match-data))
11030 match)
11031 (progn (setq in-emacs (or in-emacs line search))
11032 nil))) ; if we have no match in apps-dlink,
11033 ; always open the file in emacs if line or search
11034 ; is given (for backwards compatibility)
11035 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11036 'string-match)
11037 (cdr (assoc ext apps))
11038 (cdr (assoc t apps))))))
11039 (when (eq cmd 'system)
11040 (setq cmd (cdr (assoc 'system apps))))
11041 (when (eq cmd 'default)
11042 (setq cmd (cdr (assoc t apps))))
11043 (when (eq cmd 'mailcap)
11044 (require 'mailcap)
11045 (mailcap-parse-mailcaps)
11046 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11047 (command (mailcap-mime-info mime-type)))
11048 (if (stringp command)
11049 (setq cmd command)
11050 (setq cmd 'emacs))))
11051 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11052 (not (file-exists-p file))
11053 (not org-open-non-existing-files))
11054 (user-error "No such file: %s" file))
11055 (cond
11056 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11057 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11058 (while (string-match "['\"]%s['\"]" cmd)
11059 (setq cmd (replace-match "%s" t t cmd)))
11060 (while (string-match "%s" cmd)
11061 (setq cmd (replace-match
11062 (save-match-data
11063 (shell-quote-argument
11064 (convert-standard-filename file)))
11065 t t cmd)))
11067 ;; Replace "%1", "%2" etc. in command with group matches from regex
11068 (save-match-data
11069 (let ((match-index 1)
11070 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11071 (set-match-data link-match-data)
11072 (while (<= match-index number-of-groups)
11073 (let ((regex (concat "%" (number-to-string match-index)))
11074 (replace-with (match-string match-index dlink)))
11075 (while (string-match regex cmd)
11076 (setq cmd (replace-match replace-with t t cmd))))
11077 (setq match-index (+ match-index 1)))))
11079 (save-window-excursion
11080 (message "Running %s...done" cmd)
11081 (start-process-shell-command cmd nil cmd)
11082 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11083 ((or (stringp cmd)
11084 (eq cmd 'emacs))
11085 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11086 (widen)
11087 (if line (org-goto-line line)
11088 (if search (org-link-search search))))
11089 ((consp cmd)
11090 (let ((file (convert-standard-filename file)))
11091 (save-match-data
11092 (set-match-data link-match-data)
11093 (eval cmd))))
11094 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11095 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11096 (or (not (equal old-buffer (current-buffer)))
11097 (not (equal old-pos (point))))
11098 (org-mark-ring-push old-pos old-buffer))))
11100 (defun org-file-apps-entry-match-against-dlink-p (entry)
11101 "This function returns non-nil if `entry' uses a regular
11102 expression which should be matched against the whole link by
11103 org-open-file.
11105 It assumes that is the case when the entry uses a regular
11106 expression which has at least one grouping construct and the
11107 action is either a lisp form or a command string containing
11108 '%1', i.e. using at least one subexpression match as a
11109 parameter."
11110 (let ((selector (car entry))
11111 (action (cdr entry)))
11112 (if (stringp selector)
11113 (and (> (regexp-opt-depth selector) 0)
11114 (or (and (stringp action)
11115 (string-match "%[0-9]" action))
11116 (consp action)))
11117 nil)))
11119 (defun org-default-apps ()
11120 "Return the default applications for this operating system."
11121 (cond
11122 ((eq system-type 'darwin)
11123 org-file-apps-defaults-macosx)
11124 ((eq system-type 'windows-nt)
11125 org-file-apps-defaults-windowsnt)
11126 (t org-file-apps-defaults-gnu)))
11128 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11129 "Convert extensions to regular expressions in the cars of LIST.
11130 Also, weed out any non-string entries, because the return value is used
11131 only for regexp matching.
11132 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11133 point to the symbol `emacs', indicating that the file should
11134 be opened in Emacs."
11135 (append
11136 (delq nil
11137 (mapcar (lambda (x)
11138 (if (not (stringp (car x)))
11140 (if (string-match "\\W" (car x))
11142 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11143 list))
11144 (if add-auto-mode
11145 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11147 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11148 (defun org-file-remote-p (file)
11149 "Test whether FILE specifies a location on a remote system.
11150 Return non-nil if the location is indeed remote.
11152 For example, the filename \"/user@host:/foo\" specifies a location
11153 on the system \"/user@host:\"."
11154 (cond ((fboundp 'file-remote-p)
11155 (file-remote-p file))
11156 ((fboundp 'tramp-handle-file-remote-p)
11157 (tramp-handle-file-remote-p file))
11158 ((and (boundp 'ange-ftp-name-format)
11159 (string-match (car ange-ftp-name-format) file))
11160 t)))
11163 ;;;; Refiling
11165 (defun org-get-org-file ()
11166 "Read a filename, with default directory `org-directory'."
11167 (let ((default (or org-default-notes-file remember-data-file)))
11168 (read-file-name (format "File name [%s]: " default)
11169 (file-name-as-directory org-directory)
11170 default)))
11172 (defun org-notes-order-reversed-p ()
11173 "Check if the current file should receive notes in reversed order."
11174 (cond
11175 ((not org-reverse-note-order) nil)
11176 ((eq t org-reverse-note-order) t)
11177 ((not (listp org-reverse-note-order)) nil)
11178 (t (catch 'exit
11179 (let ((all org-reverse-note-order)
11180 entry)
11181 (while (setq entry (pop all))
11182 (if (string-match (car entry) buffer-file-name)
11183 (throw 'exit (cdr entry))))
11184 nil)))))
11186 (defvar org-refile-target-table nil
11187 "The list of refile targets, created by `org-refile'.")
11189 (defvar org-agenda-new-buffers nil
11190 "Buffers created to visit agenda files.")
11192 (defvar org-refile-cache nil
11193 "Cache for refile targets.")
11195 (defvar org-refile-markers nil
11196 "All the markers used for caching refile locations.")
11198 (defun org-refile-marker (pos)
11199 "Get a new refile marker, but only if caching is in use."
11200 (if (not org-refile-use-cache)
11202 (let ((m (make-marker)))
11203 (move-marker m pos)
11204 (push m org-refile-markers)
11205 m)))
11207 (defun org-refile-cache-clear ()
11208 "Clear the refile cache and disable all the markers."
11209 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11210 (setq org-refile-markers nil)
11211 (setq org-refile-cache nil)
11212 (message "Refile cache has been cleared"))
11214 (defun org-refile-cache-check-set (set)
11215 "Check if all the markers in the cache still have live buffers."
11216 (let (marker)
11217 (catch 'exit
11218 (while (and set (setq marker (nth 3 (pop set))))
11219 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11220 (when (and marker (null (marker-buffer marker)))
11221 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11222 (sit-for 3)
11223 (throw 'exit nil)))
11224 t)))
11226 (defun org-refile-cache-put (set &rest identifiers)
11227 "Push the refile targets SET into the cache, under IDENTIFIERS."
11228 (let* ((key (sha1 (prin1-to-string identifiers)))
11229 (entry (assoc key org-refile-cache)))
11230 (if entry
11231 (setcdr entry set)
11232 (push (cons key set) org-refile-cache))))
11234 (defun org-refile-cache-get (&rest identifiers)
11235 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11236 (cond
11237 ((not org-refile-cache) nil)
11238 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11240 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11241 org-refile-cache))))
11242 (and set (org-refile-cache-check-set set) set)))))
11244 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11245 "Produce a table with refile targets."
11246 (let ((case-fold-search nil)
11247 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11248 (entries (or org-refile-targets '((nil . (:level . 1)))))
11249 targets tgs txt re files f desc descre fast-path-p level pos0)
11250 (message "Getting targets...")
11251 (with-current-buffer (or default-buffer (current-buffer))
11252 (while (setq entry (pop entries))
11253 (setq files (car entry) desc (cdr entry))
11254 (setq fast-path-p nil)
11255 (cond
11256 ((null files) (setq files (list (current-buffer))))
11257 ((eq files 'org-agenda-files)
11258 (setq files (org-agenda-files 'unrestricted)))
11259 ((and (symbolp files) (fboundp files))
11260 (setq files (funcall files)))
11261 ((and (symbolp files) (boundp files))
11262 (setq files (symbol-value files))))
11263 (if (stringp files) (setq files (list files)))
11264 (cond
11265 ((eq (car desc) :tag)
11266 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11267 ((eq (car desc) :todo)
11268 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11269 ((eq (car desc) :regexp)
11270 (setq descre (cdr desc)))
11271 ((eq (car desc) :level)
11272 (setq descre (concat "^\\*\\{" (number-to-string
11273 (if org-odd-levels-only
11274 (1- (* 2 (cdr desc)))
11275 (cdr desc)))
11276 "\\}[ \t]")))
11277 ((eq (car desc) :maxlevel)
11278 (setq fast-path-p t)
11279 (setq descre (concat "^\\*\\{1," (number-to-string
11280 (if org-odd-levels-only
11281 (1- (* 2 (cdr desc)))
11282 (cdr desc)))
11283 "\\}[ \t]")))
11284 (t (error "Bad refiling target description %s" desc)))
11285 (while (setq f (pop files))
11286 (with-current-buffer
11287 (if (bufferp f) f (org-get-agenda-file-buffer f))
11289 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11290 (progn
11291 (if (bufferp f) (setq f (buffer-file-name
11292 (buffer-base-buffer f))))
11293 (setq f (and f (expand-file-name f)))
11294 (if (eq org-refile-use-outline-path 'file)
11295 (push (list (file-name-nondirectory f) f nil nil) tgs))
11296 (save-excursion
11297 (save-restriction
11298 (widen)
11299 (goto-char (point-min))
11300 (while (re-search-forward descre nil t)
11301 (goto-char (setq pos0 (point-at-bol)))
11302 (catch 'next
11303 (when org-refile-target-verify-function
11304 (save-match-data
11305 (or (funcall org-refile-target-verify-function)
11306 (throw 'next t))))
11307 (when (and (looking-at org-complex-heading-regexp)
11308 (not (member (match-string 4) excluded-entries))
11309 (match-string 4))
11310 (setq level (org-reduced-level
11311 (- (match-end 1) (match-beginning 1)))
11312 txt (org-link-display-format (match-string 4))
11313 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11314 re (format org-complex-heading-regexp-format
11315 (regexp-quote (match-string 4))))
11316 (when org-refile-use-outline-path
11317 (setq txt (mapconcat
11318 'org-protect-slash
11319 (append
11320 (if (eq org-refile-use-outline-path
11321 'file)
11322 (list (file-name-nondirectory
11323 (buffer-file-name
11324 (buffer-base-buffer))))
11325 (if (eq org-refile-use-outline-path
11326 'full-file-path)
11327 (list (buffer-file-name
11328 (buffer-base-buffer)))))
11329 (org-get-outline-path fast-path-p
11330 level txt)
11331 (list txt))
11332 "/")))
11333 (push (list txt f re (org-refile-marker (point)))
11334 tgs)))
11335 (when (= (point) pos0)
11336 ;; verification function has not moved point
11337 (goto-char (point-at-eol))))))))
11338 (when org-refile-use-cache
11339 (org-refile-cache-put tgs (buffer-file-name) descre))
11340 (setq targets (append tgs targets))))))
11341 (message "Getting targets...done")
11342 (nreverse targets)))
11344 (defun org-protect-slash (s)
11345 (while (string-match "/" s)
11346 (setq s (replace-match "\\" t t s)))
11349 (defvar org-olpa (make-vector 20 nil))
11351 (defun org-get-outline-path (&optional fastp level heading)
11352 "Return the outline path to the current entry, as a list.
11354 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11355 routine which makes outline path derivations for an entire file,
11356 avoiding backtracing. Refile target collection makes use of that."
11357 (if fastp
11358 (progn
11359 (if (> level 19)
11360 (error "Outline path failure, more than 19 levels"))
11361 (loop for i from level upto 19 do
11362 (aset org-olpa i nil))
11363 (prog1
11364 (delq nil (append org-olpa nil))
11365 (aset org-olpa level heading)))
11366 (let (rtn case-fold-search)
11367 (save-excursion
11368 (save-restriction
11369 (widen)
11370 (while (org-up-heading-safe)
11371 (when (looking-at org-complex-heading-regexp)
11372 (push (org-trim
11373 (replace-regexp-in-string
11374 ;; Remove statistical/checkboxes cookies
11375 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11376 (org-match-string-no-properties 4)))
11377 rtn)))
11378 rtn)))))
11380 (defun org-format-outline-path (path &optional width prefix separator)
11381 "Format the outline path PATH for display.
11382 WIDTH is the maximum number of characters that is available.
11383 PREFIX is a prefix to be included in the returned string,
11384 such as the file name.
11385 SEPARATOR is inserted between the different parts of the path,
11386 the default is \"/\"."
11387 (setq width (or width 79))
11388 (if prefix (setq width (- width (length prefix))))
11389 (if (not path)
11390 (or prefix "")
11391 (let* ((nsteps (length path))
11392 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11393 (maxwidth (if (<= total-width width)
11394 10000 ;; everything fits
11395 ;; we need to shorten the level headings
11396 (/ (- width nsteps) nsteps)))
11397 (org-odd-levels-only nil)
11398 (n 0)
11399 (total (1+ (length prefix))))
11400 (setq maxwidth (max maxwidth 10))
11401 (concat prefix
11402 (if prefix (or separator "/"))
11403 (mapconcat
11404 (lambda (h)
11405 (setq n (1+ n))
11406 (if (and (= n nsteps) (< maxwidth 10000))
11407 (setq maxwidth (- total-width total)))
11408 (if (< (length h) maxwidth)
11409 (progn (setq total (+ total (length h) 1)) h)
11410 (setq h (substring h 0 (- maxwidth 2))
11411 total (+ total maxwidth 1))
11412 (if (string-match "[ \t]+\\'" h)
11413 (setq h (substring h 0 (match-beginning 0))))
11414 (setq h (concat h "..")))
11415 (org-add-props h nil 'face
11416 (nth (% (1- n) org-n-level-faces)
11417 org-level-faces))
11419 path (or separator "/"))))))
11421 (defun org-display-outline-path (&optional file current separator just-return-string)
11422 "Display the current outline path in the echo area.
11424 If FILE is non-nil, prepend the output with the file name.
11425 If CURRENT is non-nil, append the current heading to the output.
11426 SEPARATOR is passed through to `org-format-outline-path'. It separates
11427 the different parts of the path and defaults to \"/\".
11428 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11429 (interactive "P")
11430 (let* (case-fold-search
11431 (bfn (buffer-file-name (buffer-base-buffer)))
11432 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11433 res)
11434 (if current (setq path (append path
11435 (save-excursion
11436 (org-back-to-heading t)
11437 (if (looking-at org-complex-heading-regexp)
11438 (list (match-string 4)))))))
11439 (setq res
11440 (org-format-outline-path
11441 path
11442 (1- (frame-width))
11443 (and file bfn (concat (file-name-nondirectory bfn) separator))
11444 separator))
11445 (if just-return-string
11446 (org-no-properties res)
11447 (org-unlogged-message "%s" res))))
11449 (defvar org-refile-history nil
11450 "History for refiling operations.")
11452 (defvar org-after-refile-insert-hook nil
11453 "Hook run after `org-refile' has inserted its stuff at the new location.
11454 Note that this is still *before* the stuff will be removed from
11455 the *old* location.")
11457 (defvar org-capture-last-stored-marker)
11458 (defvar org-refile-keep nil
11459 "Non-nil means `org-refile' will copy instead of refile.")
11461 (defun org-copy ()
11462 "Like `org-refile', but copy."
11463 (interactive)
11464 (let ((org-refile-keep t))
11465 (funcall 'org-refile nil nil nil "Copy")))
11467 (defun org-refile (&optional goto default-buffer rfloc msg)
11468 "Move the entry or entries at point to another heading.
11469 The list of target headings is compiled using the information in
11470 `org-refile-targets', which see.
11472 At the target location, the entry is filed as a subitem of the target
11473 heading. Depending on `org-reverse-note-order', the new subitem will
11474 either be the first or the last subitem.
11476 If there is an active region, all entries in that region will be moved.
11477 However, the region must fulfill the requirement that the first heading
11478 is the first one sets the top-level of the moved text - at most siblings
11479 below it are allowed.
11481 With prefix arg GOTO, the command will only visit the target location
11482 and not actually move anything.
11484 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11485 go to the location where the last refiling operation has put the subtree.
11487 With a numeric prefix argument of `2', refile to the running clock.
11489 With a numeric prefix argument of `3', emulate `org-refile-keep'
11490 being set to `t' and copy to the target location, don't move it.
11491 Beware that keeping refiled entries may result in duplicated ID
11492 properties.
11494 RFLOC can be a refile location obtained in a different way.
11496 MSG is a string to replace \"Refile\" in the default prompt with
11497 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11499 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11501 If you are using target caching (see `org-refile-use-cache'),
11502 you have to clear the target cache in order to find new targets.
11503 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11504 prefix argument (`C-u C-u C-u C-c C-w')."
11506 (interactive "P")
11507 (if (member goto '(0 (64)))
11508 (org-refile-cache-clear)
11509 (let* ((actionmsg (or msg "Refile"))
11510 (cbuf (current-buffer))
11511 (regionp (org-region-active-p))
11512 (region-start (and regionp (region-beginning)))
11513 (region-end (and regionp (region-end)))
11514 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11515 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11516 pos it nbuf file re level reversed)
11517 (setq last-command nil)
11518 (when regionp
11519 (goto-char region-start)
11520 (or (bolp) (goto-char (point-at-bol)))
11521 (setq region-start (point))
11522 (unless (or (org-kill-is-subtree-p
11523 (buffer-substring region-start region-end))
11524 (prog1 org-refile-active-region-within-subtree
11525 (let ((s (point-at-eol)))
11526 (org-toggle-heading)
11527 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11528 (user-error "The region is not a (sequence of) subtree(s)")))
11529 (if (equal goto '(16))
11530 (org-refile-goto-last-stored)
11531 (when (or
11532 (and (equal goto 2)
11533 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11534 (prog1
11535 (setq it (list (or org-clock-heading "running clock")
11536 (buffer-file-name
11537 (marker-buffer org-clock-hd-marker))
11539 (marker-position org-clock-hd-marker)))
11540 (setq goto nil)))
11541 (setq it (or rfloc
11542 (let (heading-text)
11543 (save-excursion
11544 (unless goto
11545 (org-back-to-heading t)
11546 (setq heading-text
11547 (nth 4 (org-heading-components))))
11549 (org-refile-get-location
11550 (cond (goto "Goto")
11551 (regionp (concat actionmsg " region to"))
11552 (t (concat actionmsg " subtree \""
11553 heading-text "\" to")))
11554 default-buffer
11555 (and (not (equal '(4) goto))
11556 org-refile-allow-creating-parent-nodes)
11557 goto))))))
11558 (setq file (nth 1 it)
11559 re (nth 2 it)
11560 pos (nth 3 it))
11561 (if (and (not goto)
11563 (equal (buffer-file-name) file)
11564 (if regionp
11565 (and (>= pos region-start)
11566 (<= pos region-end))
11567 (and (>= pos (point))
11568 (< pos (save-excursion
11569 (org-end-of-subtree t t))))))
11570 (error "Cannot refile to position inside the tree or region"))
11572 (setq nbuf (or (find-buffer-visiting file)
11573 (find-file-noselect file)))
11574 (if (and goto (not (equal goto 3)))
11575 (progn
11576 (org-pop-to-buffer-same-window nbuf)
11577 (goto-char pos)
11578 (org-show-context 'org-goto))
11579 (if regionp
11580 (progn
11581 (org-kill-new (buffer-substring region-start region-end))
11582 (org-save-markers-in-region region-start region-end))
11583 (org-copy-subtree 1 nil t))
11584 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11585 (find-file-noselect file)))
11586 (setq reversed (org-notes-order-reversed-p))
11587 (save-excursion
11588 (save-restriction
11589 (widen)
11590 (if pos
11591 (progn
11592 (goto-char pos)
11593 (looking-at org-outline-regexp)
11594 (setq level (org-get-valid-level (funcall outline-level) 1))
11595 (goto-char
11596 (if reversed
11597 (or (outline-next-heading) (point-max))
11598 (or (save-excursion (org-get-next-sibling))
11599 (org-end-of-subtree t t)
11600 (point-max)))))
11601 (setq level 1)
11602 (if (not reversed)
11603 (goto-char (point-max))
11604 (goto-char (point-min))
11605 (or (outline-next-heading) (goto-char (point-max)))))
11606 (if (not (bolp)) (newline))
11607 (org-paste-subtree level)
11608 (when org-log-refile
11609 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11610 (unless (eq org-log-refile 'note)
11611 (save-excursion (org-add-log-note))))
11612 (and org-auto-align-tags
11613 (let ((org-loop-over-headlines-in-active-region nil))
11614 (org-set-tags nil t)))
11615 (let ((bookmark-name (plist-get org-bookmark-names-plist
11616 :last-refile)))
11617 (when bookmark-name
11618 (with-demoted-errors
11619 (bookmark-set bookmark-name))))
11620 ;; If we are refiling for capture, make sure that the
11621 ;; last-capture pointers point here
11622 (when (org-bound-and-true-p org-refile-for-capture)
11623 (let ((bookmark-name (plist-get org-bookmark-names-plist
11624 :last-capture-marker)))
11625 (when bookmark-name
11626 (with-demoted-errors
11627 (bookmark-set bookmark-name))))
11628 (move-marker org-capture-last-stored-marker (point)))
11629 (if (fboundp 'deactivate-mark) (deactivate-mark))
11630 (run-hooks 'org-after-refile-insert-hook))))
11631 (unless org-refile-keep
11632 (if regionp
11633 (delete-region (point) (+ (point) (- region-end region-start)))
11634 (delete-region
11635 (and (org-back-to-heading t) (point))
11636 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11637 (when (featurep 'org-inlinetask)
11638 (org-inlinetask-remove-END-maybe))
11639 (setq org-markers-to-move nil)
11640 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11642 (defun org-refile-goto-last-stored ()
11643 "Go to the location where the last refile was stored."
11644 (interactive)
11645 (bookmark-jump "org-refile-last-stored")
11646 (message "This is the location of the last refile"))
11648 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11649 no-exclude)
11650 "Prompt the user for a refile location, using PROMPT.
11651 PROMPT should not be suffixed with a colon and a space, because
11652 this function appends the default value from
11653 `org-refile-history' automatically, if that is not empty.
11654 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11655 this is used for the GOTO interface."
11656 (let ((org-refile-targets org-refile-targets)
11657 (org-refile-use-outline-path org-refile-use-outline-path)
11658 excluded-entries)
11659 (when (and (derived-mode-p 'org-mode)
11660 (not org-refile-use-cache)
11661 (not no-exclude))
11662 (org-map-tree
11663 (lambda()
11664 (setq excluded-entries
11665 (append excluded-entries (list (org-get-heading t t)))))))
11666 (setq org-refile-target-table
11667 (org-refile-get-targets default-buffer excluded-entries)))
11668 (unless org-refile-target-table
11669 (user-error "No refile targets"))
11670 (let* ((cbuf (current-buffer))
11671 (partial-completion-mode nil)
11672 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11673 (cfunc (if (and org-refile-use-outline-path
11674 org-outline-path-complete-in-steps)
11675 'org-olpath-completing-read
11676 'org-icompleting-read))
11677 (extra (if org-refile-use-outline-path "/" ""))
11678 (cbnex (concat (buffer-name) extra))
11679 (filename (and cfn (expand-file-name cfn)))
11680 (tbl (mapcar
11681 (lambda (x)
11682 (if (and (not (member org-refile-use-outline-path
11683 '(file full-file-path)))
11684 (not (equal filename (nth 1 x))))
11685 (cons (concat (car x) extra " ("
11686 (file-name-nondirectory (nth 1 x)) ")")
11687 (cdr x))
11688 (cons (concat (car x) extra) (cdr x))))
11689 org-refile-target-table))
11690 (completion-ignore-case t)
11691 cdef
11692 (prompt (concat prompt
11693 (or (and (car org-refile-history)
11694 (concat " (default " (car org-refile-history) ")"))
11695 (and (assoc cbnex tbl) (setq cdef cbnex)
11696 (concat " (default " cbnex ")"))) ": "))
11697 pa answ parent-target child parent old-hist)
11698 (setq old-hist org-refile-history)
11699 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11700 nil 'org-refile-history (or cdef (car org-refile-history))))
11701 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11702 (org-refile-check-position pa)
11703 (if pa
11704 (progn
11705 (when (or (not org-refile-history)
11706 (not (eq old-hist org-refile-history))
11707 (not (equal (car pa) (car org-refile-history))))
11708 (setq org-refile-history
11709 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11710 org-refile-history
11711 (cdr org-refile-history))))
11712 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11713 (pop org-refile-history)))
11715 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11716 (progn
11717 (setq parent (match-string 1 answ)
11718 child (match-string 2 answ))
11719 (setq parent-target (or (assoc parent tbl)
11720 (assoc (concat parent "/") tbl)))
11721 (when (and parent-target
11722 (or (eq new-nodes t)
11723 (and (eq new-nodes 'confirm)
11724 (y-or-n-p (format "Create new node \"%s\"? "
11725 child)))))
11726 (org-refile-new-child parent-target child)))
11727 (user-error "Invalid target location")))))
11729 (declare-function org-string-nw-p "org-macs" (s))
11730 (defun org-refile-check-position (refile-pointer)
11731 "Check if the refile pointer matches the headline to which it points."
11732 (let* ((file (nth 1 refile-pointer))
11733 (re (nth 2 refile-pointer))
11734 (pos (nth 3 refile-pointer))
11735 buffer)
11736 (if (and (not (markerp pos)) (not file))
11737 (user-error "Please save the buffer to a file before refiling")
11738 (when (org-string-nw-p re)
11739 (setq buffer (if (markerp pos)
11740 (marker-buffer pos)
11741 (or (find-buffer-visiting file)
11742 (find-file-noselect file))))
11743 (with-current-buffer buffer
11744 (save-excursion
11745 (save-restriction
11746 (widen)
11747 (goto-char pos)
11748 (beginning-of-line 1)
11749 (unless (org-looking-at-p re)
11750 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11752 (defun org-refile-new-child (parent-target child)
11753 "Use refile target PARENT-TARGET to add new CHILD below it."
11754 (unless parent-target
11755 (error "Cannot find parent for new node"))
11756 (let ((file (nth 1 parent-target))
11757 (pos (nth 3 parent-target))
11758 level)
11759 (with-current-buffer (or (find-buffer-visiting file)
11760 (find-file-noselect file))
11761 (save-excursion
11762 (save-restriction
11763 (widen)
11764 (if pos
11765 (goto-char pos)
11766 (goto-char (point-max))
11767 (if (not (bolp)) (newline)))
11768 (when (looking-at org-outline-regexp)
11769 (setq level (funcall outline-level))
11770 (org-end-of-subtree t t))
11771 (org-back-over-empty-lines)
11772 (insert "\n" (make-string
11773 (if pos (org-get-valid-level level 1) 1) ?*)
11774 " " child "\n")
11775 (beginning-of-line 0)
11776 (list (concat (car parent-target) "/" child) file "" (point)))))))
11778 (defun org-olpath-completing-read (prompt collection &rest args)
11779 "Read an outline path like a file name."
11780 (let ((thetable collection)
11781 (org-completion-use-ido nil) ; does not work with ido.
11782 (org-completion-use-iswitchb nil)) ; or iswitchb
11783 (apply
11784 'org-icompleting-read prompt
11785 (lambda (string predicate &optional flag)
11786 (let (rtn r f (l (length string)))
11787 (cond
11788 ((eq flag nil)
11789 ;; try completion
11790 (try-completion string thetable))
11791 ((eq flag t)
11792 ;; all-completions
11793 (setq rtn (all-completions string thetable predicate))
11794 (mapcar
11795 (lambda (x)
11796 (setq r (substring x l))
11797 (if (string-match " ([^)]*)$" x)
11798 (setq f (match-string 0 x))
11799 (setq f ""))
11800 (if (string-match "/" r)
11801 (concat string (substring r 0 (match-end 0)) f)
11803 rtn))
11804 ((eq flag 'lambda)
11805 ;; exact match?
11806 (assoc string thetable)))))
11807 args)))
11809 ;;;; Dynamic blocks
11811 (defun org-find-dblock (name)
11812 "Find the first dynamic block with name NAME in the buffer.
11813 If not found, stay at current position and return nil."
11814 (let ((case-fold-search t) pos)
11815 (save-excursion
11816 (goto-char (point-min))
11817 (setq pos (and (re-search-forward
11818 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11819 (match-beginning 0))))
11820 (if pos (goto-char pos))
11821 pos))
11823 (defconst org-dblock-start-re
11824 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11825 "Matches the start line of a dynamic block, with parameters.")
11827 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11828 "Matches the end of a dynamic block.")
11830 (defun org-create-dblock (plist)
11831 "Create a dynamic block section, with parameters taken from PLIST.
11832 PLIST must contain a :name entry which is used as name of the block."
11833 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11834 (end-of-line 1)
11835 (newline))
11836 (let ((col (current-column))
11837 (name (plist-get plist :name)))
11838 (insert "#+BEGIN: " name)
11839 (while plist
11840 (if (eq (car plist) :name)
11841 (setq plist (cddr plist))
11842 (insert " " (prin1-to-string (pop plist)))))
11843 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11844 (beginning-of-line -2)))
11846 (defun org-prepare-dblock ()
11847 "Prepare dynamic block for refresh.
11848 This empties the block, puts the cursor at the insert position and returns
11849 the property list including an extra property :name with the block name."
11850 (unless (looking-at org-dblock-start-re)
11851 (user-error "Not at a dynamic block"))
11852 (let* ((begdel (1+ (match-end 0)))
11853 (name (org-no-properties (match-string 1)))
11854 (params (append (list :name name)
11855 (read (concat "(" (match-string 3) ")")))))
11856 (save-excursion
11857 (beginning-of-line 1)
11858 (skip-chars-forward " \t")
11859 (setq params (plist-put params :indentation-column (current-column))))
11860 (unless (re-search-forward org-dblock-end-re nil t)
11861 (error "Dynamic block not terminated"))
11862 (setq params
11863 (append params
11864 (list :content (buffer-substring
11865 begdel (match-beginning 0)))))
11866 (delete-region begdel (match-beginning 0))
11867 (goto-char begdel)
11868 (open-line 1)
11869 params))
11871 (defun org-map-dblocks (&optional command)
11872 "Apply COMMAND to all dynamic blocks in the current buffer.
11873 If COMMAND is not given, use `org-update-dblock'."
11874 (let ((cmd (or command 'org-update-dblock)))
11875 (save-excursion
11876 (goto-char (point-min))
11877 (while (re-search-forward org-dblock-start-re nil t)
11878 (goto-char (match-beginning 0))
11879 (save-excursion
11880 (condition-case nil
11881 (funcall cmd)
11882 (error (message "Error during update of dynamic block"))))
11883 (unless (re-search-forward org-dblock-end-re nil t)
11884 (error "Dynamic block not terminated"))))))
11886 (defun org-dblock-update (&optional arg)
11887 "User command for updating dynamic blocks.
11888 Update the dynamic block at point. With prefix ARG, update all dynamic
11889 blocks in the buffer."
11890 (interactive "P")
11891 (if arg
11892 (org-update-all-dblocks)
11893 (or (looking-at org-dblock-start-re)
11894 (org-beginning-of-dblock))
11895 (org-update-dblock)))
11897 (defun org-update-dblock ()
11898 "Update the dynamic block at point.
11899 This means to empty the block, parse for parameters and then call
11900 the correct writing function."
11901 (interactive)
11902 (save-window-excursion
11903 (let* ((pos (point))
11904 (line (org-current-line))
11905 (params (org-prepare-dblock))
11906 (name (plist-get params :name))
11907 (indent (plist-get params :indentation-column))
11908 (cmd (intern (concat "org-dblock-write:" name))))
11909 (message "Updating dynamic block `%s' at line %d..." name line)
11910 (funcall cmd params)
11911 (message "Updating dynamic block `%s' at line %d...done" name line)
11912 (goto-char pos)
11913 (when (and indent (> indent 0))
11914 (setq indent (make-string indent ?\ ))
11915 (save-excursion
11916 (org-beginning-of-dblock)
11917 (forward-line 1)
11918 (while (not (looking-at org-dblock-end-re))
11919 (insert indent)
11920 (beginning-of-line 2))
11921 (when (looking-at org-dblock-end-re)
11922 (and (looking-at "[ \t]+")
11923 (replace-match ""))
11924 (insert indent)))))))
11926 (defun org-beginning-of-dblock ()
11927 "Find the beginning of the dynamic block at point.
11928 Error if there is no such block at point."
11929 (let ((pos (point))
11930 beg)
11931 (end-of-line 1)
11932 (if (and (re-search-backward org-dblock-start-re nil t)
11933 (setq beg (match-beginning 0))
11934 (re-search-forward org-dblock-end-re nil t)
11935 (> (match-end 0) pos))
11936 (goto-char beg)
11937 (goto-char pos)
11938 (error "Not in a dynamic block"))))
11940 (defun org-update-all-dblocks ()
11941 "Update all dynamic blocks in the buffer.
11942 This function can be used in a hook."
11943 (interactive)
11944 (when (derived-mode-p 'org-mode)
11945 (org-map-dblocks 'org-update-dblock)))
11948 ;;;; Completion
11950 (declare-function org-export-backend-name "org-export" (cl-x))
11951 (declare-function org-export-backend-options "org-export" (cl-x))
11952 (defun org-get-export-keywords ()
11953 "Return a list of all currently understood export keywords.
11954 Export keywords include options, block names, attributes and
11955 keywords relative to each registered export back-end."
11956 (let (keywords)
11957 (dolist (backend
11958 (org-bound-and-true-p org-export--registered-backends)
11959 (delq nil keywords))
11960 ;; Back-end name (for keywords, like #+LATEX:)
11961 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11962 (dolist (option-entry (org-export-backend-options backend))
11963 ;; Back-end options.
11964 (push (nth 1 option-entry) keywords)))))
11966 (defconst org-options-keywords
11967 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11968 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11969 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11970 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11971 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11973 (defcustom org-structure-template-alist
11974 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11975 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11976 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11977 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11978 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11979 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11980 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11981 "<literal style=\"latex\">\n?\n</literal>")
11982 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11983 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11984 "<literal style=\"html\">\n?\n</literal>")
11985 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11986 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11987 ("A" "#+ASCII: " "")
11988 ("i" "#+INDEX: ?" "#+INDEX: ?")
11989 ("I" "#+INCLUDE: %file ?"
11990 "<include file=%file markup=\"?\">"))
11991 "Structure completion elements.
11992 This is a list of abbreviation keys and values. The value gets inserted
11993 if you type `<' followed by the key and then press the completion key,
11994 usually `M-TAB'. %file will be replaced by a file name after prompting
11995 for the file using completion. The cursor will be placed at the position
11996 of the `?` in the template.
11997 There are two templates for each key, the first uses the original Org syntax,
11998 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11999 the default when the /org-mtags.el/ module has been loaded. See also the
12000 variable `org-mtags-prefer-muse-templates'."
12001 :group 'org-completion
12002 :type '(repeat
12003 (list
12004 (string :tag "Key")
12005 (string :tag "Template")
12006 (string :tag "Muse Template"))))
12008 (defun org-try-structure-completion ()
12009 "Try to complete a structure template before point.
12010 This looks for strings like \"<e\" on an otherwise empty line and
12011 expands them."
12012 (let ((l (buffer-substring (point-at-bol) (point)))
12014 (when (and (looking-at "[ \t]*$")
12015 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12016 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12017 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12018 (match-beginning 1)) a)
12019 t)))
12021 (defun org-complete-expand-structure-template (start cell)
12022 "Expand a structure template."
12023 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12024 (rpl (nth (if musep 2 1) cell))
12025 (ind ""))
12026 (delete-region start (point))
12027 (when (string-match "\\`#\\+" rpl)
12028 (cond
12029 ((bolp))
12030 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12031 (setq ind (buffer-substring (point-at-bol) (point))))
12032 (t (newline))))
12033 (setq start (point))
12034 (if (string-match "%file" rpl)
12035 (setq rpl (replace-match
12036 (concat
12037 "\""
12038 (save-match-data
12039 (abbreviate-file-name (read-file-name "Include file: ")))
12040 "\"")
12041 t t rpl)))
12042 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12043 (concat "\n" ind)))
12044 (insert rpl)
12045 (if (re-search-backward "\\?" start t) (delete-char 1))))
12047 ;;;; TODO, DEADLINE, Comments
12049 (defun org-toggle-comment ()
12050 "Change the COMMENT state of an entry."
12051 (interactive)
12052 (save-excursion
12053 (org-back-to-heading)
12054 (let (case-fold-search)
12055 (cond
12056 ((looking-at (format org-heading-keyword-regexp-format
12057 org-comment-string))
12058 (goto-char (match-end 1))
12059 (looking-at (concat " +" org-comment-string))
12060 (replace-match "" t t)
12061 (when (eolp) (insert " ")))
12062 ((looking-at org-outline-regexp)
12063 (goto-char (match-end 0))
12064 (insert org-comment-string " "))))))
12066 (defvar org-last-todo-state-is-todo nil
12067 "This is non-nil when the last TODO state change led to a TODO state.
12068 If the last change removed the TODO tag or switched to DONE, then
12069 this is nil.")
12071 (defvar org-setting-tags nil) ; dynamically skipped
12073 (defvar org-todo-setup-filter-hook nil
12074 "Hook for functions that pre-filter todo specs.
12075 Each function takes a todo spec and returns either nil or the spec
12076 transformed into canonical form." )
12078 (defvar org-todo-get-default-hook nil
12079 "Hook for functions that get a default item for todo.
12080 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12081 nil or a string to be used for the todo mark." )
12083 (defvar org-agenda-headline-snapshot-before-repeat)
12085 (defun org-current-effective-time ()
12086 "Return current time adjusted for `org-extend-today-until' variable."
12087 (let* ((ct (org-current-time))
12088 (dct (decode-time ct))
12089 (ct1
12090 (cond
12091 (org-use-last-clock-out-time-as-effective-time
12092 (or (org-clock-get-last-clock-out-time) ct))
12093 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12094 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12095 (t ct))))
12096 ct1))
12098 (defun org-todo-yesterday (&optional arg)
12099 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12100 (interactive "P")
12101 (if (eq major-mode 'org-agenda-mode)
12102 (apply 'org-agenda-todo-yesterday arg)
12103 (let* ((hour (third (decode-time
12104 (org-current-time))))
12105 (org-extend-today-until (1+ hour)))
12106 (org-todo arg))))
12108 (defvar org-block-entry-blocking ""
12109 "First entry preventing the TODO state change.")
12111 (defun org-todo (&optional arg)
12112 "Change the TODO state of an item.
12113 The state of an item is given by a keyword at the start of the heading,
12114 like
12115 *** TODO Write paper
12116 *** DONE Call mom
12118 The different keywords are specified in the variable `org-todo-keywords'.
12119 By default the available states are \"TODO\" and \"DONE\".
12120 So for this example: when the item starts with TODO, it is changed to DONE.
12121 When it starts with DONE, the DONE is removed. And when neither TODO nor
12122 DONE are present, add TODO at the beginning of the heading.
12124 With \\[universal-argument] prefix arg, use completion to determine the new \
12125 state.
12126 With numeric prefix arg, switch to that state.
12127 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12128 keywords (nextset).
12129 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12130 With a numeric prefix arg of 0, inhibit note taking for the change.
12132 For calling through lisp, arg is also interpreted in the following way:
12133 'none -> empty state
12134 \"\"(empty string) -> switch to empty state
12135 'done -> switch to DONE
12136 'nextset -> switch to the next set of keywords
12137 'previousset -> switch to the previous set of keywords
12138 \"WAITING\" -> switch to the specified keyword, but only if it
12139 really is a member of `org-todo-keywords'."
12140 (interactive "P")
12141 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12142 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12143 'region-start-level 'region))
12144 org-loop-over-headlines-in-active-region)
12145 (org-map-entries
12146 `(org-todo ,arg)
12147 org-loop-over-headlines-in-active-region
12148 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12149 (if (equal arg '(16)) (setq arg 'nextset))
12150 (let ((org-blocker-hook org-blocker-hook)
12151 commentp
12152 case-fold-search)
12153 (when (equal arg '(64))
12154 (setq arg nil org-blocker-hook nil))
12155 (when (and org-blocker-hook
12156 (or org-inhibit-blocking
12157 (org-entry-get nil "NOBLOCKING")))
12158 (setq org-blocker-hook nil))
12159 (save-excursion
12160 (catch 'exit
12161 (org-back-to-heading t)
12162 (when (looking-at (concat "^\\*+ " org-comment-string))
12163 (org-toggle-comment)
12164 (setq commentp t))
12165 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12166 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12167 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12168 (let* ((match-data (match-data))
12169 (startpos (point-at-bol))
12170 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12171 (org-log-done org-log-done)
12172 (org-log-repeat org-log-repeat)
12173 (org-todo-log-states org-todo-log-states)
12174 (org-inhibit-logging
12175 (if (equal arg 0)
12176 (progn (setq arg nil) 'note) org-inhibit-logging))
12177 (this (match-string 1))
12178 (hl-pos (match-beginning 0))
12179 (head (org-get-todo-sequence-head this))
12180 (ass (assoc head org-todo-kwd-alist))
12181 (interpret (nth 1 ass))
12182 (done-word (nth 3 ass))
12183 (final-done-word (nth 4 ass))
12184 (org-last-state (or this ""))
12185 (completion-ignore-case t)
12186 (member (member this org-todo-keywords-1))
12187 (tail (cdr member))
12188 (org-state (cond
12189 ((and org-todo-key-trigger
12190 (or (and (equal arg '(4))
12191 (eq org-use-fast-todo-selection 'prefix))
12192 (and (not arg) org-use-fast-todo-selection
12193 (not (eq org-use-fast-todo-selection
12194 'prefix)))))
12195 ;; Use fast selection
12196 (org-fast-todo-selection))
12197 ((and (equal arg '(4))
12198 (or (not org-use-fast-todo-selection)
12199 (not org-todo-key-trigger)))
12200 ;; Read a state with completion
12201 (org-icompleting-read
12202 "State: " (mapcar 'list org-todo-keywords-1)
12203 nil t))
12204 ((eq arg 'right)
12205 (if this
12206 (if tail (car tail) nil)
12207 (car org-todo-keywords-1)))
12208 ((eq arg 'left)
12209 (if (equal member org-todo-keywords-1)
12211 (if this
12212 (nth (- (length org-todo-keywords-1)
12213 (length tail) 2)
12214 org-todo-keywords-1)
12215 (org-last org-todo-keywords-1))))
12216 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12217 (setq arg nil))) ; hack to fall back to cycling
12218 (arg
12219 ;; user or caller requests a specific state
12220 (cond
12221 ((equal arg "") nil)
12222 ((eq arg 'none) nil)
12223 ((eq arg 'done) (or done-word (car org-done-keywords)))
12224 ((eq arg 'nextset)
12225 (or (car (cdr (member head org-todo-heads)))
12226 (car org-todo-heads)))
12227 ((eq arg 'previousset)
12228 (let ((org-todo-heads (reverse org-todo-heads)))
12229 (or (car (cdr (member head org-todo-heads)))
12230 (car org-todo-heads))))
12231 ((car (member arg org-todo-keywords-1)))
12232 ((stringp arg)
12233 (user-error "State `%s' not valid in this file" arg))
12234 ((nth (1- (prefix-numeric-value arg))
12235 org-todo-keywords-1))))
12236 ((null member) (or head (car org-todo-keywords-1)))
12237 ((equal this final-done-word) nil) ;; -> make empty
12238 ((null tail) nil) ;; -> first entry
12239 ((memq interpret '(type priority))
12240 (if (eq this-command last-command)
12241 (car tail)
12242 (if (> (length tail) 0)
12243 (or done-word (car org-done-keywords))
12244 nil)))
12246 (car tail))))
12247 (org-state (or
12248 (run-hook-with-args-until-success
12249 'org-todo-get-default-hook org-state org-last-state)
12250 org-state))
12251 (next (if org-state (concat " " org-state " ") " "))
12252 (change-plist (list :type 'todo-state-change :from this :to org-state
12253 :position startpos))
12254 dolog now-done-p)
12255 (when org-blocker-hook
12256 (setq org-last-todo-state-is-todo
12257 (not (member this org-done-keywords)))
12258 (unless (save-excursion
12259 (save-match-data
12260 (org-with-wide-buffer
12261 (run-hook-with-args-until-failure
12262 'org-blocker-hook change-plist))))
12263 (if (org-called-interactively-p 'interactive)
12264 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12265 this org-state org-block-entry-blocking)
12266 ;; fail silently
12267 (message "TODO state change from %s to %s blocked (by \"%s\")"
12268 this org-state org-block-entry-blocking)
12269 (throw 'exit nil))))
12270 (store-match-data match-data)
12271 (replace-match next t t)
12272 (unless (pos-visible-in-window-p hl-pos)
12273 (message "TODO state changed to %s" (org-trim next)))
12274 (unless head
12275 (setq head (org-get-todo-sequence-head org-state)
12276 ass (assoc head org-todo-kwd-alist)
12277 interpret (nth 1 ass)
12278 done-word (nth 3 ass)
12279 final-done-word (nth 4 ass)))
12280 (when (memq arg '(nextset previousset))
12281 (message "Keyword-Set %d/%d: %s"
12282 (- (length org-todo-sets) -1
12283 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12284 (length org-todo-sets)
12285 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12286 (setq org-last-todo-state-is-todo
12287 (not (member org-state org-done-keywords)))
12288 (setq now-done-p (and (member org-state org-done-keywords)
12289 (not (member this org-done-keywords))))
12290 (and logging (org-local-logging logging))
12291 (when (and (or org-todo-log-states org-log-done)
12292 (not (eq org-inhibit-logging t))
12293 (not (memq arg '(nextset previousset))))
12294 ;; we need to look at recording a time and note
12295 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12296 (nth 2 (assoc this org-todo-log-states))))
12297 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12298 (setq dolog 'time))
12299 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12300 (and org-state
12301 (member org-state org-not-done-keywords)
12302 (not (member this org-not-done-keywords))))
12303 ;; This is now a todo state and was not one before
12304 ;; If there was a CLOSED time stamp, get rid of it.
12305 (org-add-planning-info nil nil 'closed))
12306 (when (and now-done-p org-log-done)
12307 ;; It is now done, and it was not done before
12308 (org-add-planning-info 'closed (org-current-effective-time))
12309 (if (and (not dolog) (eq 'note org-log-done))
12310 (org-add-log-setup 'done org-state this 'findpos 'note)))
12311 (when (and org-state dolog)
12312 ;; This is a non-nil state, and we need to log it
12313 (org-add-log-setup 'state org-state this 'findpos dolog)))
12314 ;; Fixup tag positioning
12315 (org-todo-trigger-tag-changes org-state)
12316 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12317 (when org-provide-todo-statistics
12318 (org-update-parent-todo-statistics))
12319 (run-hooks 'org-after-todo-state-change-hook)
12320 (if (and arg (not (member org-state org-done-keywords)))
12321 (setq head (org-get-todo-sequence-head org-state)))
12322 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12323 ;; Do we need to trigger a repeat?
12324 (when now-done-p
12325 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12326 ;; This is for the agenda, take a snapshot of the headline.
12327 (save-match-data
12328 (setq org-agenda-headline-snapshot-before-repeat
12329 (org-get-heading))))
12330 (org-auto-repeat-maybe org-state))
12331 ;; Fixup cursor location if close to the keyword
12332 (if (and (outline-on-heading-p)
12333 (not (bolp))
12334 (save-excursion (beginning-of-line 1)
12335 (looking-at org-todo-line-regexp))
12336 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12337 (progn
12338 (goto-char (or (match-end 2) (match-end 1)))
12339 (and (looking-at " ") (just-one-space))))
12340 (when org-trigger-hook
12341 (save-excursion
12342 (run-hook-with-args 'org-trigger-hook change-plist)))
12343 (when commentp (org-toggle-comment))))))))
12345 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12346 "Block turning an entry into a TODO, using the hierarchy.
12347 This checks whether the current task should be blocked from state
12348 changes. Such blocking occurs when:
12350 1. The task has children which are not all in a completed state.
12352 2. A task has a parent with the property :ORDERED:, and there
12353 are siblings prior to the current task with incomplete
12354 status.
12356 3. The parent of the task is blocked because it has siblings that should
12357 be done first, or is child of a block grandparent TODO entry."
12359 (if (not org-enforce-todo-dependencies)
12360 t ; if locally turned off don't block
12361 (catch 'dont-block
12362 ;; If this is not a todo state change, or if this entry is already DONE,
12363 ;; do not block
12364 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12365 (member (plist-get change-plist :from)
12366 (cons 'done org-done-keywords))
12367 (member (plist-get change-plist :to)
12368 (cons 'todo org-not-done-keywords))
12369 (not (plist-get change-plist :to)))
12370 (throw 'dont-block t))
12371 ;; If this task has children, and any are undone, it's blocked
12372 (save-excursion
12373 (org-back-to-heading t)
12374 (let ((this-level (funcall outline-level)))
12375 (outline-next-heading)
12376 (let ((child-level (funcall outline-level)))
12377 (while (and (not (eobp))
12378 (> child-level this-level))
12379 ;; this todo has children, check whether they are all
12380 ;; completed
12381 (if (and (not (org-entry-is-done-p))
12382 (org-entry-is-todo-p))
12383 (progn (setq org-block-entry-blocking (org-get-heading))
12384 (throw 'dont-block nil)))
12385 (outline-next-heading)
12386 (setq child-level (funcall outline-level))))))
12387 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12388 ;; any previous siblings are undone, it's blocked
12389 (save-excursion
12390 (org-back-to-heading t)
12391 (let* ((pos (point))
12392 (parent-pos (and (org-up-heading-safe) (point))))
12393 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12394 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12395 (forward-line 1)
12396 (re-search-forward org-not-done-heading-regexp pos t))
12397 (setq org-block-entry-blocking (match-string 0))
12398 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12399 ;; Search further up the hierarchy, to see if an ancestor is blocked
12400 (while t
12401 (goto-char parent-pos)
12402 (if (not (looking-at org-not-done-heading-regexp))
12403 (throw 'dont-block t)) ; do not block, parent is not a TODO
12404 (setq pos (point))
12405 (setq parent-pos (and (org-up-heading-safe) (point)))
12406 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12407 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12408 (forward-line 1)
12409 (re-search-forward org-not-done-heading-regexp pos t)
12410 (setq org-block-entry-blocking (org-get-heading)))
12411 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12413 (defcustom org-track-ordered-property-with-tag nil
12414 "Should the ORDERED property also be shown as a tag?
12415 The ORDERED property decides if an entry should require subtasks to be
12416 completed in sequence. Since a property is not very visible, setting
12417 this option means that toggling the ORDERED property with the command
12418 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12419 not relevant for the behavior, but it makes things more visible.
12421 Note that toggling the tag with tags commands will not change the property
12422 and therefore not influence behavior!
12424 This can be t, meaning the tag ORDERED should be used, It can also be a
12425 string to select a different tag for this task."
12426 :group 'org-todo
12427 :type '(choice
12428 (const :tag "No tracking" nil)
12429 (const :tag "Track with ORDERED tag" t)
12430 (string :tag "Use other tag")))
12432 (defun org-toggle-ordered-property ()
12433 "Toggle the ORDERED property of the current entry.
12434 For better visibility, you can track the value of this property with a tag.
12435 See variable `org-track-ordered-property-with-tag'."
12436 (interactive)
12437 (let* ((t1 org-track-ordered-property-with-tag)
12438 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12439 (save-excursion
12440 (org-back-to-heading)
12441 (if (org-entry-get nil "ORDERED")
12442 (progn
12443 (org-delete-property "ORDERED")
12444 (and tag (org-toggle-tag tag 'off))
12445 (message "Subtasks can be completed in arbitrary order"))
12446 (org-entry-put nil "ORDERED" "t")
12447 (and tag (org-toggle-tag tag 'on))
12448 (message "Subtasks must be completed in sequence")))))
12450 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12451 (defun org-block-todo-from-checkboxes (change-plist)
12452 "Block turning an entry into a TODO, using checkboxes.
12453 This checks whether the current task should be blocked from state
12454 changes because there are unchecked boxes in this entry."
12455 (if (not org-enforce-todo-checkbox-dependencies)
12456 t ; if locally turned off don't block
12457 (catch 'dont-block
12458 ;; If this is not a todo state change, or if this entry is already DONE,
12459 ;; do not block
12460 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12461 (member (plist-get change-plist :from)
12462 (cons 'done org-done-keywords))
12463 (member (plist-get change-plist :to)
12464 (cons 'todo org-not-done-keywords))
12465 (not (plist-get change-plist :to)))
12466 (throw 'dont-block t))
12467 ;; If this task has checkboxes that are not checked, it's blocked
12468 (save-excursion
12469 (org-back-to-heading t)
12470 (let ((beg (point)) end)
12471 (outline-next-heading)
12472 (setq end (point))
12473 (goto-char beg)
12474 (if (org-list-search-forward
12475 (concat (org-item-beginning-re)
12476 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12477 "\\[[- ]\\]")
12478 end t)
12479 (progn
12480 (if (boundp 'org-blocked-by-checkboxes)
12481 (setq org-blocked-by-checkboxes t))
12482 (throw 'dont-block nil)))))
12483 t))) ; do not block
12485 (defun org-entry-blocked-p ()
12486 "Is the current entry blocked?"
12487 (org-with-silent-modifications
12488 (if (org-entry-get nil "NOBLOCKING")
12489 nil ;; Never block this entry
12490 (not (run-hook-with-args-until-failure
12491 'org-blocker-hook
12492 (list :type 'todo-state-change
12493 :position (point)
12494 :from 'todo
12495 :to 'done))))))
12497 (defun org-update-statistics-cookies (all)
12498 "Update the statistics cookie, either from TODO or from checkboxes.
12499 This should be called with the cursor in a line with a statistics cookie."
12500 (interactive "P")
12501 (if all
12502 (progn
12503 (org-update-checkbox-count 'all)
12504 (org-map-entries 'org-update-parent-todo-statistics))
12505 (if (not (org-at-heading-p))
12506 (org-update-checkbox-count)
12507 (let ((pos (point-marker))
12508 end l1 l2)
12509 (ignore-errors (org-back-to-heading t))
12510 (if (not (org-at-heading-p))
12511 (org-update-checkbox-count)
12512 (setq l1 (org-outline-level))
12513 (setq end (save-excursion
12514 (outline-next-heading)
12515 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12516 (point)))
12517 (if (and (save-excursion
12518 (re-search-forward
12519 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12520 (not (save-excursion (re-search-forward
12521 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12522 (org-update-checkbox-count)
12523 (if (and l2 (> l2 l1))
12524 (progn
12525 (goto-char end)
12526 (org-update-parent-todo-statistics))
12527 (goto-char pos)
12528 (beginning-of-line 1)
12529 (while (re-search-forward
12530 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12531 (point-at-eol) t)
12532 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12533 (goto-char pos)
12534 (move-marker pos nil)))))
12536 (defvar org-entry-property-inherited-from) ;; defined below
12537 (defun org-update-parent-todo-statistics ()
12538 "Update any statistics cookie in the parent of the current headline.
12539 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12540 the entire subtree and this will travel up the hierarchy and update
12541 statistics everywhere."
12542 (let* ((prop (save-excursion (org-up-heading-safe)
12543 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12544 (recursive (or (not org-hierarchical-todo-statistics)
12545 (and prop (string-match "\\<recursive\\>" prop))))
12546 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12548 (first t)
12549 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12550 level ltoggle l1 new ndel
12551 (cnt-all 0) (cnt-done 0) is-percent kwd
12552 checkbox-beg ov ovs ove cookie-present)
12553 (catch 'exit
12554 (save-excursion
12555 (beginning-of-line 1)
12556 (setq ltoggle (funcall outline-level))
12557 ;; Three situations are to consider:
12559 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12560 ;; to the top-level ancestor on the headline;
12562 ;; 2. If parent has "recursive" property, repeat up to the
12563 ;; headline setting that property, taking inheritance into
12564 ;; account;
12566 ;; 3. Else, move up to direct parent and proceed only once.
12567 (while (and (setq level (org-up-heading-safe))
12568 (or recursive first)
12569 (>= (point) lim))
12570 (setq first nil cookie-present nil)
12571 (unless (and level
12572 (not (string-match
12573 "\\<checkbox\\>"
12574 (downcase (or (org-entry-get nil "COOKIE_DATA")
12575 "")))))
12576 (throw 'exit nil))
12577 (while (re-search-forward box-re (point-at-eol) t)
12578 (setq cnt-all 0 cnt-done 0 cookie-present t)
12579 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12580 (save-match-data
12581 (unless (outline-next-heading) (throw 'exit nil))
12582 (while (and (looking-at org-complex-heading-regexp)
12583 (> (setq l1 (length (match-string 1))) level))
12584 (setq kwd (and (or recursive (= l1 ltoggle))
12585 (match-string 2)))
12586 (if (or (eq org-provide-todo-statistics 'all-headlines)
12587 (and (listp org-provide-todo-statistics)
12588 (or (member kwd org-provide-todo-statistics)
12589 (member kwd org-done-keywords))))
12590 (setq cnt-all (1+ cnt-all))
12591 (if (eq org-provide-todo-statistics t)
12592 (and kwd (setq cnt-all (1+ cnt-all)))))
12593 (and (member kwd org-done-keywords)
12594 (setq cnt-done (1+ cnt-done)))
12595 (outline-next-heading)))
12596 (setq new
12597 (if is-percent
12598 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12599 (format "[%d/%d]" cnt-done cnt-all))
12600 ndel (- (match-end 0) checkbox-beg))
12601 ;; handle overlays when updating cookie from column view
12602 (when (setq ov (car (overlays-at checkbox-beg)))
12603 (setq ovs (overlay-start ov) ove (overlay-end ov))
12604 (delete-overlay ov))
12605 (goto-char checkbox-beg)
12606 (insert new)
12607 (delete-region (point) (+ (point) ndel))
12608 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12609 (when ov (move-overlay ov ovs ove)))
12610 (when cookie-present
12611 (run-hook-with-args 'org-after-todo-statistics-hook
12612 cnt-done (- cnt-all cnt-done))))))
12613 (run-hooks 'org-todo-statistics-hook)))
12615 (defvar org-after-todo-statistics-hook nil
12616 "Hook that is called after a TODO statistics cookie has been updated.
12617 Each function is called with two arguments: the number of not-done entries
12618 and the number of done entries.
12620 For example, the following function, when added to this hook, will switch
12621 an entry to DONE when all children are done, and back to TODO when new
12622 entries are set to a TODO status. Note that this hook is only called
12623 when there is a statistics cookie in the headline!
12625 (defun org-summary-todo (n-done n-not-done)
12626 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12627 (let (org-log-done org-log-states) ; turn off logging
12628 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12631 (defvar org-todo-statistics-hook nil
12632 "Hook that is run whenever Org thinks TODO statistics should be updated.
12633 This hook runs even if there is no statistics cookie present, in which case
12634 `org-after-todo-statistics-hook' would not run.")
12636 (defun org-todo-trigger-tag-changes (state)
12637 "Apply the changes defined in `org-todo-state-tags-triggers'."
12638 (let ((l org-todo-state-tags-triggers)
12639 changes)
12640 (when (or (not state) (equal state ""))
12641 (setq changes (append changes (cdr (assoc "" l)))))
12642 (when (and (stringp state) (> (length state) 0))
12643 (setq changes (append changes (cdr (assoc state l)))))
12644 (when (member state org-not-done-keywords)
12645 (setq changes (append changes (cdr (assoc 'todo l)))))
12646 (when (member state org-done-keywords)
12647 (setq changes (append changes (cdr (assoc 'done l)))))
12648 (dolist (c changes)
12649 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12651 (defun org-local-logging (value)
12652 "Get logging settings from a property VALUE."
12653 (let* (words w a)
12654 ;; directly set the variables, they are already local.
12655 (setq org-log-done nil
12656 org-log-repeat nil
12657 org-todo-log-states nil)
12658 (setq words (org-split-string value))
12659 (while (setq w (pop words))
12660 (cond
12661 ((setq a (assoc w org-startup-options))
12662 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12663 (set (nth 1 a) (nth 2 a))))
12664 ((setq a (org-extract-log-state-settings w))
12665 (and (member (car a) org-todo-keywords-1)
12666 (push a org-todo-log-states)))))))
12668 (defun org-get-todo-sequence-head (kwd)
12669 "Return the head of the TODO sequence to which KWD belongs.
12670 If KWD is not set, check if there is a text property remembering the
12671 right sequence."
12672 (let (p)
12673 (cond
12674 ((not kwd)
12675 (or (get-text-property (point-at-bol) 'org-todo-head)
12676 (progn
12677 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12678 nil (point-at-eol)))
12679 (get-text-property p 'org-todo-head))))
12680 ((not (member kwd org-todo-keywords-1))
12681 (car org-todo-keywords-1))
12682 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12684 (defun org-fast-todo-selection ()
12685 "Fast TODO keyword selection with single keys.
12686 Returns the new TODO keyword, or nil if no state change should occur."
12687 (let* ((fulltable org-todo-key-alist)
12688 (done-keywords org-done-keywords) ;; needed for the faces.
12689 (maxlen (apply 'max (mapcar
12690 (lambda (x)
12691 (if (stringp (car x)) (string-width (car x)) 0))
12692 fulltable)))
12693 (expert nil)
12694 (fwidth (+ maxlen 3 1 3))
12695 (ncol (/ (- (window-width) 4) fwidth))
12696 tg cnt e c tbl
12697 groups ingroup)
12698 (save-excursion
12699 (save-window-excursion
12700 (if expert
12701 (set-buffer (get-buffer-create " *Org todo*"))
12702 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12703 (erase-buffer)
12704 (org-set-local 'org-done-keywords done-keywords)
12705 (setq tbl fulltable cnt 0)
12706 (while (setq e (pop tbl))
12707 (cond
12708 ((equal e '(:startgroup))
12709 (push '() groups) (setq ingroup t)
12710 (when (not (= cnt 0))
12711 (setq cnt 0)
12712 (insert "\n"))
12713 (insert "{ "))
12714 ((equal e '(:endgroup))
12715 (setq ingroup nil cnt 0)
12716 (insert "}\n"))
12717 ((equal e '(:newline))
12718 (when (not (= cnt 0))
12719 (setq cnt 0)
12720 (insert "\n")
12721 (setq e (car tbl))
12722 (while (equal (car tbl) '(:newline))
12723 (insert "\n")
12724 (setq tbl (cdr tbl)))))
12726 (setq tg (car e) c (cdr e))
12727 (if ingroup (push tg (car groups)))
12728 (setq tg (org-add-props tg nil 'face
12729 (org-get-todo-face tg)))
12730 (if (and (= cnt 0) (not ingroup)) (insert " "))
12731 (insert "[" c "] " tg (make-string
12732 (- fwidth 4 (length tg)) ?\ ))
12733 (when (= (setq cnt (1+ cnt)) ncol)
12734 (insert "\n")
12735 (if ingroup (insert " "))
12736 (setq cnt 0)))))
12737 (insert "\n")
12738 (goto-char (point-min))
12739 (if (not expert) (org-fit-window-to-buffer))
12740 (message "[a-z..]:Set [SPC]:clear")
12741 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12742 (cond
12743 ((or (= c ?\C-g)
12744 (and (= c ?q) (not (rassoc c fulltable))))
12745 (setq quit-flag t))
12746 ((= c ?\ ) nil)
12747 ((setq e (rassoc c fulltable) tg (car e))
12749 (t (setq quit-flag t)))))))
12751 (defun org-entry-is-todo-p ()
12752 (member (org-get-todo-state) org-not-done-keywords))
12754 (defun org-entry-is-done-p ()
12755 (member (org-get-todo-state) org-done-keywords))
12757 (defun org-get-todo-state ()
12758 "Return the TODO keyword of the current subtree."
12759 (save-excursion
12760 (org-back-to-heading t)
12761 (and (looking-at org-todo-line-regexp)
12762 (match-end 2)
12763 (match-string 2))))
12765 (defun org-at-date-range-p (&optional inactive-ok)
12766 "Is the cursor inside a date range?"
12767 (interactive)
12768 (save-excursion
12769 (catch 'exit
12770 (let ((pos (point)))
12771 (skip-chars-backward "^[<\r\n")
12772 (skip-chars-backward "<[")
12773 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12774 (>= (match-end 0) pos)
12775 (throw 'exit t))
12776 (skip-chars-backward "^<[\r\n")
12777 (skip-chars-backward "<[")
12778 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12779 (>= (match-end 0) pos)
12780 (throw 'exit t)))
12781 nil)))
12783 (defun org-get-repeat (&optional tagline)
12784 "Check if there is a deadline/schedule with repeater in this entry."
12785 (save-match-data
12786 (save-excursion
12787 (org-back-to-heading t)
12788 (and (re-search-forward (if tagline
12789 (concat tagline "\\s-*" org-repeat-re)
12790 org-repeat-re)
12791 (org-entry-end-position) t)
12792 (match-string-no-properties 1)))))
12794 (defvar org-last-changed-timestamp)
12795 (defvar org-last-inserted-timestamp)
12796 (defvar org-log-post-message)
12797 (defvar org-log-note-purpose)
12798 (defvar org-log-note-how)
12799 (defvar org-log-note-extra)
12800 (defun org-auto-repeat-maybe (done-word)
12801 "Check if the current headline contains a repeated deadline/schedule.
12802 If yes, set TODO state back to what it was and change the base date
12803 of repeating deadline/scheduled time stamps to new date.
12804 This function is run automatically after each state change to a DONE state."
12805 ;; last-state is dynamically scoped into this function
12806 (let* ((repeat (org-get-repeat))
12807 (aa (assoc org-last-state org-todo-kwd-alist))
12808 (interpret (nth 1 aa))
12809 (head (nth 2 aa))
12810 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12811 (msg "Entry repeats: ")
12812 (org-log-done nil)
12813 (org-todo-log-states nil)
12814 re type n what ts time to-state)
12815 (when repeat
12816 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12817 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12818 org-todo-repeat-to-state))
12819 (unless (and to-state (member to-state org-todo-keywords-1))
12820 (setq to-state (if (eq interpret 'type) org-last-state head)))
12821 (org-todo to-state)
12822 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12823 (org-entry-put nil "LAST_REPEAT" (format-time-string
12824 (org-time-stamp-format t t))))
12825 (when org-log-repeat
12826 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12827 (memq 'org-add-log-note post-command-hook))
12828 ;; OK, we are already setup for some record
12829 (if (eq org-log-repeat 'note)
12830 ;; make sure we take a note, not only a time stamp
12831 (setq org-log-note-how 'note))
12832 ;; Set up for taking a record
12833 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12834 org-last-state
12835 'findpos org-log-repeat)))
12836 (org-back-to-heading t)
12837 (org-add-planning-info nil nil 'closed)
12838 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12839 org-deadline-time-regexp "\\)\\|\\("
12840 org-ts-regexp "\\)"))
12841 (while (re-search-forward
12842 re (save-excursion (outline-next-heading) (point)) t)
12843 (setq type (if (match-end 1) org-scheduled-string
12844 (if (match-end 3) org-deadline-string "Plain:"))
12845 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12846 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12847 (setq n (string-to-number (match-string 2 ts))
12848 what (match-string 3 ts))
12849 (if (equal what "w") (setq n (* n 7) what "d"))
12850 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12851 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12852 ;; Preparation, see if we need to modify the start date for the change
12853 (when (match-end 1)
12854 (setq time (save-match-data (org-time-string-to-time ts)))
12855 (cond
12856 ((equal (match-string 1 ts) ".")
12857 ;; Shift starting date to today
12858 (org-timestamp-change
12859 (- (org-today) (time-to-days time))
12860 'day))
12861 ((equal (match-string 1 ts) "+")
12862 (let ((nshiftmax 10) (nshift 0))
12863 (while (or (= nshift 0)
12864 (<= (time-to-days time)
12865 (time-to-days (current-time))))
12866 (when (= (incf nshift) nshiftmax)
12867 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12868 (error "Abort")))
12869 (org-timestamp-change n (cdr (assoc what whata)))
12870 (org-at-timestamp-p t)
12871 (setq ts (match-string 1))
12872 (setq time (save-match-data (org-time-string-to-time ts)))))
12873 (org-timestamp-change (- n) (cdr (assoc what whata)))
12874 ;; rematch, so that we have everything in place for the real shift
12875 (org-at-timestamp-p t)
12876 (setq ts (match-string 1))
12877 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12878 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12879 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12880 (setq org-log-post-message msg)
12881 (message "%s" msg))))
12883 (defun org-show-todo-tree (arg)
12884 "Make a compact tree which shows all headlines marked with TODO.
12885 The tree will show the lines where the regexp matches, and all higher
12886 headlines above the match.
12887 With a \\[universal-argument] prefix, prompt for a regexp to match.
12888 With a numeric prefix N, construct a sparse tree for the Nth element
12889 of `org-todo-keywords-1'."
12890 (interactive "P")
12891 (let ((case-fold-search nil)
12892 (kwd-re
12893 (cond ((null arg) org-not-done-regexp)
12894 ((equal arg '(4))
12895 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12896 (mapcar 'list org-todo-keywords-1))))
12897 (concat "\\("
12898 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12899 "\\)\\>")))
12900 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12901 (regexp-quote (nth (1- (prefix-numeric-value arg))
12902 org-todo-keywords-1)))
12903 (t (user-error "Invalid prefix argument: %s" arg)))))
12904 (message "%d TODO entries found"
12905 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12907 (defun org-deadline (arg &optional time)
12908 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12909 With one universal prefix argument, remove any deadline from the item.
12910 With two universal prefix arguments, prompt for a warning delay.
12911 With argument TIME, set the deadline at the corresponding date. TIME
12912 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12913 (interactive "P")
12914 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12915 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12916 'region-start-level 'region))
12917 org-loop-over-headlines-in-active-region)
12918 (org-map-entries
12919 `(org-deadline ',arg ,time)
12920 org-loop-over-headlines-in-active-region
12921 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12922 (let* ((old-date (org-entry-get nil "DEADLINE"))
12923 (old-date-time (if old-date (org-time-string-to-time old-date)))
12924 (repeater (and old-date
12925 (string-match
12926 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12927 old-date)
12928 (match-string 1 old-date))))
12929 (cond
12930 ((equal arg '(4))
12931 (when (and old-date org-log-redeadline)
12932 (org-add-log-setup 'deldeadline nil old-date 'findpos
12933 org-log-redeadline))
12934 (org-remove-timestamp-with-keyword org-deadline-string)
12935 (message "Item no longer has a deadline."))
12936 ((equal arg '(16))
12937 (save-excursion
12938 (if (re-search-forward
12939 org-deadline-time-regexp
12940 (save-excursion (outline-next-heading) (point)) t)
12941 (let* ((rpl0 (match-string 1))
12942 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12943 (replace-match
12944 (concat org-deadline-string
12945 " <" rpl
12946 (format " -%dd"
12947 (abs
12948 (- (time-to-days
12949 (save-match-data
12950 (org-read-date nil t nil "Warn starting from" old-date-time)))
12951 (time-to-days old-date-time))))
12952 ">") t t))
12953 (user-error "No deadline information to update"))))
12955 (org-add-planning-info 'deadline time 'closed)
12956 (when (and old-date org-log-redeadline
12957 (not (equal old-date
12958 (substring org-last-inserted-timestamp 1 -1))))
12959 (org-add-log-setup 'redeadline nil old-date 'findpos
12960 org-log-redeadline))
12961 (when repeater
12962 (save-excursion
12963 (org-back-to-heading t)
12964 (when (re-search-forward (concat org-deadline-string " "
12965 org-last-inserted-timestamp)
12966 (save-excursion
12967 (outline-next-heading) (point)) t)
12968 (goto-char (1- (match-end 0)))
12969 (insert " " repeater)
12970 (setq org-last-inserted-timestamp
12971 (concat (substring org-last-inserted-timestamp 0 -1)
12972 " " repeater
12973 (substring org-last-inserted-timestamp -1))))))
12974 (message "Deadline on %s" org-last-inserted-timestamp))))))
12976 (defun org-schedule (arg &optional time)
12977 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12978 With one universal prefix argument, remove any scheduling date from the item.
12979 With two universal prefix arguments, prompt for a delay cookie.
12980 With argument TIME, scheduled at the corresponding date. TIME can
12981 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12982 (interactive "P")
12983 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12984 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12985 'region-start-level 'region))
12986 org-loop-over-headlines-in-active-region)
12987 (org-map-entries
12988 `(org-schedule ',arg ,time)
12989 org-loop-over-headlines-in-active-region
12990 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12991 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12992 (old-date-time (if old-date (org-time-string-to-time old-date)))
12993 (repeater (and old-date
12994 (string-match
12995 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12996 old-date)
12997 (match-string 1 old-date))))
12998 (cond
12999 ((equal arg '(4))
13000 (progn
13001 (when (and old-date org-log-reschedule)
13002 (org-add-log-setup 'delschedule nil old-date 'findpos
13003 org-log-reschedule))
13004 (org-remove-timestamp-with-keyword org-scheduled-string)
13005 (message "Item is no longer scheduled.")))
13006 ((equal arg '(16))
13007 (save-excursion
13008 (if (re-search-forward
13009 org-scheduled-time-regexp
13010 (save-excursion (outline-next-heading) (point)) t)
13011 (let* ((rpl0 (match-string 1))
13012 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13013 (replace-match
13014 (concat org-scheduled-string
13015 " <" rpl
13016 (format " -%dd"
13017 (abs
13018 (- (time-to-days
13019 (save-match-data
13020 (org-read-date nil t nil "Delay until" old-date-time)))
13021 (time-to-days old-date-time))))
13022 ">") t t))
13023 (user-error "No scheduled information to update"))))
13025 (org-add-planning-info 'scheduled time 'closed)
13026 (when (and old-date org-log-reschedule
13027 (not (equal old-date
13028 (substring org-last-inserted-timestamp 1 -1))))
13029 (org-add-log-setup 'reschedule nil old-date 'findpos
13030 org-log-reschedule))
13031 (when repeater
13032 (save-excursion
13033 (org-back-to-heading t)
13034 (when (re-search-forward (concat org-scheduled-string " "
13035 org-last-inserted-timestamp)
13036 (save-excursion
13037 (outline-next-heading) (point)) t)
13038 (goto-char (1- (match-end 0)))
13039 (insert " " repeater)
13040 (setq org-last-inserted-timestamp
13041 (concat (substring org-last-inserted-timestamp 0 -1)
13042 " " repeater
13043 (substring org-last-inserted-timestamp -1))))))
13044 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13046 (defun org-get-scheduled-time (pom &optional inherit)
13047 "Get the scheduled time as a time tuple, of a format suitable
13048 for calling org-schedule with, or if there is no scheduling,
13049 returns nil."
13050 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13051 (when time
13052 (apply 'encode-time (org-parse-time-string time)))))
13054 (defun org-get-deadline-time (pom &optional inherit)
13055 "Get the deadline as a time tuple, of a format suitable for
13056 calling org-deadline with, or if there is no scheduling, returns
13057 nil."
13058 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13059 (when time
13060 (apply 'encode-time (org-parse-time-string time)))))
13062 (defun org-remove-timestamp-with-keyword (keyword)
13063 "Remove all time stamps with KEYWORD in the current entry."
13064 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13065 beg)
13066 (save-excursion
13067 (org-back-to-heading t)
13068 (setq beg (point))
13069 (outline-next-heading)
13070 (while (re-search-backward re beg t)
13071 (replace-match "")
13072 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13073 (equal (char-before) ?\ ))
13074 (backward-delete-char 1)
13075 (if (string-match "^[ \t]*$" (buffer-substring
13076 (point-at-bol) (point-at-eol)))
13077 (delete-region (point-at-bol)
13078 (min (point-max) (1+ (point-at-eol))))))))))
13080 (defun org-add-planning-info (what &optional time &rest remove)
13081 "Insert new timestamp with keyword in the line directly after the headline.
13082 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13083 If non is given, the user is prompted for a date.
13084 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13085 be removed."
13086 (interactive)
13087 (let (org-time-was-given org-end-time-was-given ts
13088 end default-time default-input)
13090 (catch 'exit
13091 (when (and (memq what '(scheduled deadline))
13092 (or (not time)
13093 (and (stringp time)
13094 (string-match "^[-+]+[0-9]" time))))
13095 ;; Try to get a default date/time from existing timestamp
13096 (save-excursion
13097 (org-back-to-heading t)
13098 (setq end (save-excursion (outline-next-heading) (point)))
13099 (when (re-search-forward (if (eq what 'scheduled)
13100 org-scheduled-time-regexp
13101 org-deadline-time-regexp)
13102 end t)
13103 (setq ts (match-string 1)
13104 default-time
13105 (apply 'encode-time (org-parse-time-string ts))
13106 default-input (and ts (org-get-compact-tod ts))))))
13107 (when what
13108 (setq time
13109 (if (stringp time)
13110 ;; This is a string (relative or absolute), set proper date
13111 (apply 'encode-time
13112 (org-read-date-analyze
13113 time default-time (decode-time default-time)))
13114 ;; If necessary, get the time from the user
13115 (or time (org-read-date nil 'to-time nil nil
13116 default-time default-input)))))
13118 (when (and org-insert-labeled-timestamps-at-point
13119 (member what '(scheduled deadline)))
13120 (insert
13121 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13122 (org-insert-time-stamp time org-time-was-given
13123 nil nil nil (list org-end-time-was-given))
13124 (setq what nil))
13125 (save-excursion
13126 (save-restriction
13127 (let (col list elt ts buffer-invisibility-spec)
13128 (org-back-to-heading t)
13129 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13130 (goto-char (match-end 1))
13131 (setq col (current-column))
13132 (goto-char (match-end 0))
13133 (if (eobp) (insert "\n") (forward-char 1))
13134 (when (and (not what)
13135 (not (looking-at
13136 (concat "[ \t]*"
13137 org-keyword-time-not-clock-regexp))))
13138 ;; Nothing to add, nothing to remove...... :-)
13139 (throw 'exit nil))
13140 (if (and (not (looking-at org-outline-regexp))
13141 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13142 "[^\r\n]*"))
13143 (not (equal (match-string 1) org-clock-string)))
13144 (narrow-to-region (match-beginning 0) (match-end 0))
13145 (insert-before-markers "\n")
13146 (backward-char 1)
13147 (narrow-to-region (point) (point))
13148 (and org-adapt-indentation (org-indent-to-column col)))
13149 ;; Check if we have to remove something.
13150 (setq list (cons what remove))
13151 (while list
13152 (setq elt (pop list))
13153 (when (or (and (eq elt 'scheduled)
13154 (re-search-forward org-scheduled-time-regexp nil t))
13155 (and (eq elt 'deadline)
13156 (re-search-forward org-deadline-time-regexp nil t))
13157 (and (eq elt 'closed)
13158 (re-search-forward org-closed-time-regexp nil t)))
13159 (replace-match "")
13160 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13161 (and (looking-at "[ \t]+") (replace-match ""))
13162 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13163 (when what
13164 (insert
13165 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13166 (cond ((eq what 'scheduled) org-scheduled-string)
13167 ((eq what 'deadline) org-deadline-string)
13168 ((eq what 'closed) org-closed-string))
13169 " ")
13170 (setq ts (org-insert-time-stamp
13171 time
13172 (or org-time-was-given
13173 (and (eq what 'closed) org-log-done-with-time))
13174 (eq what 'closed)
13175 nil nil (list org-end-time-was-given)))
13176 (insert
13177 (if (not (or (bolp) (eq (char-before) ?\ )
13178 (memq (char-after) '(32 10))
13179 (eobp))) " " ""))
13180 (end-of-line 1))
13181 (goto-char (point-min))
13182 (widen)
13183 (if (and (looking-at "[ \t]*\n")
13184 (equal (char-before) ?\n))
13185 (delete-region (1- (point)) (point-at-eol)))
13186 ts))))))
13188 (defvar org-log-note-marker (make-marker))
13189 (defvar org-log-note-purpose nil)
13190 (defvar org-log-note-state nil)
13191 (defvar org-log-note-previous-state nil)
13192 (defvar org-log-note-how nil)
13193 (defvar org-log-note-extra nil)
13194 (defvar org-log-note-window-configuration nil)
13195 (defvar org-log-note-return-to (make-marker))
13196 (defvar org-log-note-effective-time nil
13197 "Remembered current time so that dynamically scoped
13198 `org-extend-today-until' affects tha timestamps in state change
13199 log")
13201 (defvar org-log-post-message nil
13202 "Message to be displayed after a log note has been stored.
13203 The auto-repeater uses this.")
13205 (defun org-add-note ()
13206 "Add a note to the current entry.
13207 This is done in the same way as adding a state change note."
13208 (interactive)
13209 (org-add-log-setup 'note nil nil 'findpos nil))
13211 (defvar org-property-end-re)
13212 (defun org-add-log-setup (&optional purpose state prev-state
13213 findpos how extra)
13214 "Set up the post command hook to take a note.
13215 If this is about to TODO state change, the new state is expected in STATE.
13216 When FINDPOS is non-nil, find the correct position for the note in
13217 the current entry. If not, assume that it can be inserted at point.
13218 HOW is an indicator what kind of note should be created.
13219 EXTRA is additional text that will be inserted into the notes buffer."
13220 (let* ((org-log-into-drawer (org-log-into-drawer))
13221 (drawer (cond ((stringp org-log-into-drawer)
13222 org-log-into-drawer)
13223 (org-log-into-drawer "LOGBOOK"))))
13224 (save-restriction
13225 (save-excursion
13226 (when findpos
13227 (org-back-to-heading t)
13228 (narrow-to-region (point) (save-excursion
13229 (outline-next-heading) (point)))
13230 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13231 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13232 "[^\r\n]*\\)?"))
13233 (goto-char (match-end 0))
13234 (cond
13235 (drawer
13236 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13237 nil t)
13238 (progn
13239 (goto-char (match-end 0))
13240 (or org-log-states-order-reversed
13241 (and (re-search-forward org-property-end-re nil t)
13242 (goto-char (1- (match-beginning 0))))))
13243 (insert "\n:" drawer ":\n:END:")
13244 (beginning-of-line 0)
13245 (org-indent-line)
13246 (beginning-of-line 2)
13247 (org-indent-line)
13248 (end-of-line 0)))
13249 ((and org-log-state-notes-insert-after-drawers
13250 (save-excursion
13251 (forward-line) (looking-at org-drawer-regexp)))
13252 (forward-line)
13253 (while (looking-at org-drawer-regexp)
13254 (goto-char (match-end 0))
13255 (re-search-forward org-property-end-re (point-max) t)
13256 (forward-line))
13257 (forward-line -1)))
13258 (unless org-log-states-order-reversed
13259 (and (= (char-after) ?\n) (forward-char 1))
13260 (org-skip-over-state-notes)
13261 (skip-chars-backward " \t\n\r")))
13262 (move-marker org-log-note-marker (point))
13263 (setq org-log-note-purpose purpose
13264 org-log-note-state state
13265 org-log-note-previous-state prev-state
13266 org-log-note-how how
13267 org-log-note-extra extra
13268 org-log-note-effective-time (org-current-effective-time))
13269 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13271 (defun org-skip-over-state-notes ()
13272 "Skip past the list of State notes in an entry."
13273 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13274 (when (ignore-errors (goto-char (org-in-item-p)))
13275 (let* ((struct (org-list-struct))
13276 (prevs (org-list-prevs-alist struct)))
13277 (while (looking-at "[ \t]*- State")
13278 (goto-char (or (org-list-get-next-item (point) struct prevs)
13279 (org-list-get-item-end (point) struct)))))))
13281 (defun org-add-log-note (&optional purpose)
13282 "Pop up a window for taking a note, and add this note later at point."
13283 (remove-hook 'post-command-hook 'org-add-log-note)
13284 (setq org-log-note-window-configuration (current-window-configuration))
13285 (delete-other-windows)
13286 (move-marker org-log-note-return-to (point))
13287 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13288 (goto-char org-log-note-marker)
13289 (org-switch-to-buffer-other-window "*Org Note*")
13290 (erase-buffer)
13291 (if (memq org-log-note-how '(time state))
13292 (let (current-prefix-arg) (org-store-log-note))
13293 (let ((org-inhibit-startup t)) (org-mode))
13294 (insert (format "# Insert note for %s.
13295 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13296 (cond
13297 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13298 ((eq org-log-note-purpose 'done) "closed todo item")
13299 ((eq org-log-note-purpose 'state)
13300 (format "state change from \"%s\" to \"%s\""
13301 (or org-log-note-previous-state "")
13302 (or org-log-note-state "")))
13303 ((eq org-log-note-purpose 'reschedule)
13304 "rescheduling")
13305 ((eq org-log-note-purpose 'delschedule)
13306 "no longer scheduled")
13307 ((eq org-log-note-purpose 'redeadline)
13308 "changing deadline")
13309 ((eq org-log-note-purpose 'deldeadline)
13310 "removing deadline")
13311 ((eq org-log-note-purpose 'refile)
13312 "refiling")
13313 ((eq org-log-note-purpose 'note)
13314 "this entry")
13315 (t (error "This should not happen")))))
13316 (if org-log-note-extra (insert org-log-note-extra))
13317 (org-set-local 'org-finish-function 'org-store-log-note)
13318 (run-hooks 'org-log-buffer-setup-hook)))
13320 (defvar org-note-abort nil) ; dynamically scoped
13321 (defun org-store-log-note ()
13322 "Finish taking a log note, and insert it to where it belongs."
13323 (let ((txt (buffer-string)))
13324 (kill-buffer (current-buffer))
13325 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13326 lines ind bul)
13327 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13328 (setq txt (replace-match "" t t txt)))
13329 (if (string-match "\\s-+\\'" txt)
13330 (setq txt (replace-match "" t t txt)))
13331 (setq lines (org-split-string txt "\n"))
13332 (when (and note (string-match "\\S-" note))
13333 (setq note
13334 (org-replace-escapes
13335 note
13336 (list (cons "%u" (user-login-name))
13337 (cons "%U" user-full-name)
13338 (cons "%t" (format-time-string
13339 (org-time-stamp-format 'long 'inactive)
13340 org-log-note-effective-time))
13341 (cons "%T" (format-time-string
13342 (org-time-stamp-format 'long nil)
13343 org-log-note-effective-time))
13344 (cons "%d" (format-time-string
13345 (org-time-stamp-format nil 'inactive)
13346 org-log-note-effective-time))
13347 (cons "%D" (format-time-string
13348 (org-time-stamp-format nil nil)
13349 org-log-note-effective-time))
13350 (cons "%s" (if org-log-note-state
13351 (concat "\"" org-log-note-state "\"")
13352 ""))
13353 (cons "%S" (if org-log-note-previous-state
13354 (concat "\"" org-log-note-previous-state "\"")
13355 "\"\"")))))
13356 (if lines (setq note (concat note " \\\\")))
13357 (push note lines))
13358 (when (or current-prefix-arg org-note-abort)
13359 (when org-log-into-drawer
13360 (org-remove-empty-drawer-at org-log-note-marker))
13361 (setq lines nil))
13362 (when lines
13363 (with-current-buffer (marker-buffer org-log-note-marker)
13364 (save-excursion
13365 (goto-char org-log-note-marker)
13366 (move-marker org-log-note-marker nil)
13367 (end-of-line 1)
13368 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13369 (setq ind (save-excursion
13370 (if (ignore-errors (goto-char (org-in-item-p)))
13371 (let ((struct (org-list-struct)))
13372 (org-list-get-ind
13373 (org-list-get-top-point struct) struct))
13374 (skip-chars-backward " \r\t\n")
13375 (cond
13376 ((and (org-at-heading-p)
13377 org-adapt-indentation)
13378 (1+ (org-current-level)))
13379 ((org-at-heading-p) 0)
13380 (t (org-get-indentation))))))
13381 (setq bul (org-list-bullet-string "-"))
13382 (org-indent-line-to ind)
13383 (insert bul (pop lines))
13384 (let ((ind-body (+ (length bul) ind)))
13385 (while lines
13386 (insert "\n")
13387 (org-indent-line-to ind-body)
13388 (insert (pop lines))))
13389 (message "Note stored")
13390 (org-back-to-heading t)
13391 (org-cycle-hide-drawers 'children))
13392 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13393 ;; from within `org-add-log-note' because `buffer-undo-list'
13394 ;; is then modified outside of `org-with-remote-undo'.
13395 (when (eq this-command 'org-agenda-todo)
13396 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13397 ;; Don't add undo information when called from `org-agenda-todo'
13398 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13399 (set-window-configuration org-log-note-window-configuration)
13400 (with-current-buffer (marker-buffer org-log-note-return-to)
13401 (goto-char org-log-note-return-to))
13402 (move-marker org-log-note-return-to nil)
13403 (and org-log-post-message (message "%s" org-log-post-message))))
13405 (defun org-remove-empty-drawer-at (pos)
13406 "Remove an empty drawer at position POS.
13407 POS may also be a marker."
13408 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13409 (org-with-wide-buffer
13410 (goto-char pos)
13411 (let ((drawer (org-element-at-point)))
13412 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13413 (not (org-element-property :contents-begin drawer)))
13414 (delete-region (org-element-property :begin drawer)
13415 (progn (goto-char (org-element-property :end drawer))
13416 (skip-chars-backward " \r\t\n")
13417 (forward-line)
13418 (point))))))))
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))
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 (interactive "P")
14455 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14456 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14457 'region-start-level 'region))
14458 org-loop-over-headlines-in-active-region)
14459 (org-map-entries
14460 ;; We don't use ARG and JUST-ALIGN here these args are not
14461 ;; useful when looping over headlines
14462 `(org-set-tags)
14463 org-loop-over-headlines-in-active-region
14464 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14465 (let* ((re org-outline-regexp-bol)
14466 (current (unless arg (org-get-tags-string)))
14467 (col (current-column))
14468 (org-setting-tags t)
14469 table current-tags inherited-tags ; computed below when needed
14470 tags p0 c0 c1 rpl di tc level)
14471 (if arg
14472 (save-excursion
14473 (goto-char (point-min))
14474 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14475 (while (re-search-forward re nil t)
14476 (org-set-tags nil t)
14477 (end-of-line 1)))
14478 (message "All tags realigned to column %d" org-tags-column))
14479 (if just-align
14480 (setq tags current)
14481 ;; Get a new set of tags from the user
14482 (save-excursion
14483 (setq table (append org-tag-persistent-alist
14484 (or org-tag-alist (org-get-buffer-tags))
14485 (and
14486 org-complete-tags-always-offer-all-agenda-tags
14487 (org-global-tags-completion-table
14488 (org-agenda-files))))
14489 org-last-tags-completion-table table
14490 current-tags (org-split-string current ":")
14491 inherited-tags (nreverse
14492 (nthcdr (length current-tags)
14493 (nreverse (org-get-tags-at))))
14494 tags
14495 (if (or (eq t org-use-fast-tag-selection)
14496 (and org-use-fast-tag-selection
14497 (delq nil (mapcar 'cdr table))))
14498 (org-fast-tag-selection
14499 current-tags inherited-tags table
14500 (if org-fast-tag-selection-include-todo
14501 org-todo-key-alist))
14502 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14503 (org-trim
14504 (org-icompleting-read "Tags: "
14505 'org-tags-completion-function
14506 nil nil current 'org-tags-history))))))
14507 (while (string-match "[-+&]+" tags)
14508 ;; No boolean logic, just a list
14509 (setq tags (replace-match ":" t t tags))))
14511 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14513 (if org-tags-sort-function
14514 (setq tags (mapconcat 'identity
14515 (sort (org-split-string
14516 tags (org-re "[^[:alnum:]_@#%]+"))
14517 org-tags-sort-function) ":")))
14519 (if (string-match "\\`[\t ]*\\'" tags)
14520 (setq tags "")
14521 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14522 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14524 ;; Insert new tags at the correct column
14525 (beginning-of-line 1)
14526 (setq level (or (and (looking-at org-outline-regexp)
14527 (- (match-end 0) (point) 1))
14529 (cond
14530 ((and (equal current "") (equal tags "")))
14531 ((re-search-forward
14532 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14533 (point-at-eol) t)
14534 (if (equal tags "")
14535 (setq rpl "")
14536 (goto-char (match-beginning 0))
14537 (setq c0 (current-column)
14538 ;; compute offset for the case of org-indent-mode active
14539 di (if org-indent-mode
14540 (* (1- org-indent-indentation-per-level) (1- level))
14542 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14543 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14544 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14545 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14546 (replace-match rpl t t)
14547 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14548 tags)
14549 (t (error "Tags alignment failed")))
14550 (org-move-to-column col)
14551 (unless just-align
14552 (run-hooks 'org-after-tags-change-hook))))))
14554 (defun org-change-tag-in-region (beg end tag off)
14555 "Add or remove TAG for each entry in the region.
14556 This works in the agenda, and also in an org-mode buffer."
14557 (interactive
14558 (list (region-beginning) (region-end)
14559 (let ((org-last-tags-completion-table
14560 (if (derived-mode-p 'org-mode)
14561 (org-uniquify
14562 (delq nil (append (org-get-buffer-tags)
14563 (org-global-tags-completion-table))))
14564 (org-global-tags-completion-table))))
14565 (org-icompleting-read
14566 "Tag: " 'org-tags-completion-function nil nil nil
14567 'org-tags-history))
14568 (progn
14569 (message "[s]et or [r]emove? ")
14570 (equal (read-char-exclusive) ?r))))
14571 (if (fboundp 'deactivate-mark) (deactivate-mark))
14572 (let ((agendap (equal major-mode 'org-agenda-mode))
14573 l1 l2 m buf pos newhead (cnt 0))
14574 (goto-char end)
14575 (setq l2 (1- (org-current-line)))
14576 (goto-char beg)
14577 (setq l1 (org-current-line))
14578 (loop for l from l1 to l2 do
14579 (org-goto-line l)
14580 (setq m (get-text-property (point) 'org-hd-marker))
14581 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14582 (and agendap m))
14583 (setq buf (if agendap (marker-buffer m) (current-buffer))
14584 pos (if agendap m (point)))
14585 (with-current-buffer buf
14586 (save-excursion
14587 (save-restriction
14588 (goto-char pos)
14589 (setq cnt (1+ cnt))
14590 (org-toggle-tag tag (if off 'off 'on))
14591 (setq newhead (org-get-heading)))))
14592 (and agendap (org-agenda-change-all-lines newhead m))))
14593 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14595 (defun org-tags-completion-function (string predicate &optional flag)
14596 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14597 (confirm (lambda (x) (stringp (car x)))))
14598 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14599 (setq s1 (match-string 1 string)
14600 s2 (match-string 2 string))
14601 (setq s1 "" s2 string))
14602 (cond
14603 ((eq flag nil)
14604 ;; try completion
14605 (setq rtn (try-completion s2 ctable confirm))
14606 (if (stringp rtn)
14607 (setq rtn
14608 (concat s1 s2 (substring rtn (length s2))
14609 (if (and org-add-colon-after-tag-completion
14610 (assoc rtn ctable))
14611 ":" ""))))
14612 rtn)
14613 ((eq flag t)
14614 ;; all-completions
14615 (all-completions s2 ctable confirm))
14616 ((eq flag 'lambda)
14617 ;; exact match?
14618 (assoc s2 ctable)))))
14620 (defun org-fast-tag-insert (kwd tags face &optional end)
14621 "Insert KDW, and the TAGS, the latter with face FACE.
14622 Also insert END."
14623 (insert (format "%-12s" (concat kwd ":"))
14624 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14625 (or end "")))
14627 (defun org-fast-tag-show-exit (flag)
14628 (save-excursion
14629 (org-goto-line 3)
14630 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14631 (replace-match ""))
14632 (when flag
14633 (end-of-line 1)
14634 (org-move-to-column (- (window-width) 19) t)
14635 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14637 (defun org-set-current-tags-overlay (current prefix)
14638 "Add an overlay to CURRENT tag with PREFIX."
14639 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14640 (if (featurep 'xemacs)
14641 (org-overlay-display org-tags-overlay (concat prefix s)
14642 'secondary-selection)
14643 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14644 (org-overlay-display org-tags-overlay (concat prefix s)))))
14646 (defvar org-last-tag-selection-key nil)
14647 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14648 "Fast tag selection with single keys.
14649 CURRENT is the current list of tags in the headline, INHERITED is the
14650 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14651 possibly with grouping information. TODO-TABLE is a similar table with
14652 TODO keywords, should these have keys assigned to them.
14653 If the keys are nil, a-z are automatically assigned.
14654 Returns the new tags string, or nil to not change the current settings."
14655 (let* ((fulltable (append table todo-table))
14656 (maxlen (apply 'max (mapcar
14657 (lambda (x)
14658 (if (stringp (car x)) (string-width (car x)) 0))
14659 fulltable)))
14660 (buf (current-buffer))
14661 (expert (eq org-fast-tag-selection-single-key 'expert))
14662 (buffer-tags nil)
14663 (fwidth (+ maxlen 3 1 3))
14664 (ncol (/ (- (window-width) 4) fwidth))
14665 (i-face 'org-done)
14666 (c-face 'org-todo)
14667 tg cnt e c char c1 c2 ntable tbl rtn
14668 ov-start ov-end ov-prefix
14669 (exit-after-next org-fast-tag-selection-single-key)
14670 (done-keywords org-done-keywords)
14671 groups ingroup)
14672 (save-excursion
14673 (beginning-of-line 1)
14674 (if (looking-at
14675 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14676 (setq ov-start (match-beginning 1)
14677 ov-end (match-end 1)
14678 ov-prefix "")
14679 (setq ov-start (1- (point-at-eol))
14680 ov-end (1+ ov-start))
14681 (skip-chars-forward "^\n\r")
14682 (setq ov-prefix
14683 (concat
14684 (buffer-substring (1- (point)) (point))
14685 (if (> (current-column) org-tags-column)
14687 (make-string (- org-tags-column (current-column)) ?\ ))))))
14688 (move-overlay org-tags-overlay ov-start ov-end)
14689 (save-window-excursion
14690 (if expert
14691 (set-buffer (get-buffer-create " *Org tags*"))
14692 (delete-other-windows)
14693 (split-window-vertically)
14694 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14695 (erase-buffer)
14696 (org-set-local 'org-done-keywords done-keywords)
14697 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14698 (org-fast-tag-insert "Current" current c-face "\n\n")
14699 (org-fast-tag-show-exit exit-after-next)
14700 (org-set-current-tags-overlay current ov-prefix)
14701 (setq tbl fulltable char ?a cnt 0)
14702 (while (setq e (pop tbl))
14703 (cond
14704 ((equal (car e) :startgroup)
14705 (push '() groups) (setq ingroup t)
14706 (when (not (= cnt 0))
14707 (setq cnt 0)
14708 (insert "\n"))
14709 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14710 ((equal (car e) :endgroup)
14711 (setq ingroup nil cnt 0)
14712 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14713 ((equal e '(:newline))
14714 (when (not (= cnt 0))
14715 (setq cnt 0)
14716 (insert "\n")
14717 (setq e (car tbl))
14718 (while (equal (car tbl) '(:newline))
14719 (insert "\n")
14720 (setq tbl (cdr tbl)))))
14721 ((equal e '(:grouptags)) nil)
14723 (setq tg (copy-sequence (car e)) c2 nil)
14724 (if (cdr e)
14725 (setq c (cdr e))
14726 ;; automatically assign a character.
14727 (setq c1 (string-to-char
14728 (downcase (substring
14729 tg (if (= (string-to-char tg) ?@) 1 0)))))
14730 (if (or (rassoc c1 ntable) (rassoc c1 table))
14731 (while (or (rassoc char ntable) (rassoc char table))
14732 (setq char (1+ char)))
14733 (setq c2 c1))
14734 (setq c (or c2 char)))
14735 (if ingroup (push tg (car groups)))
14736 (setq tg (org-add-props tg nil 'face
14737 (cond
14738 ((not (assoc tg table))
14739 (org-get-todo-face tg))
14740 ((member tg current) c-face)
14741 ((member tg inherited) i-face))))
14742 (if (equal (caar tbl) :grouptags)
14743 (org-add-props tg nil 'face 'org-tag-group))
14744 (if (and (= cnt 0) (not ingroup)) (insert " "))
14745 (insert "[" c "] " tg (make-string
14746 (- fwidth 4 (length tg)) ?\ ))
14747 (push (cons tg c) ntable)
14748 (when (= (setq cnt (1+ cnt)) ncol)
14749 (insert "\n")
14750 (if ingroup (insert " "))
14751 (setq cnt 0)))))
14752 (setq ntable (nreverse ntable))
14753 (insert "\n")
14754 (goto-char (point-min))
14755 (if (not expert) (org-fit-window-to-buffer))
14756 (setq rtn
14757 (catch 'exit
14758 (while t
14759 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14760 (if (not groups) "no " "")
14761 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14762 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14763 (setq org-last-tag-selection-key c)
14764 (cond
14765 ((= c ?\r) (throw 'exit t))
14766 ((= c ?!)
14767 (setq groups (not groups))
14768 (goto-char (point-min))
14769 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14770 ((= c ?\C-c)
14771 (if (not expert)
14772 (org-fast-tag-show-exit
14773 (setq exit-after-next (not exit-after-next)))
14774 (setq expert nil)
14775 (delete-other-windows)
14776 (set-window-buffer (split-window-vertically) " *Org tags*")
14777 (org-switch-to-buffer-other-window " *Org tags*")
14778 (org-fit-window-to-buffer)))
14779 ((or (= c ?\C-g)
14780 (and (= c ?q) (not (rassoc c ntable))))
14781 (org-detach-overlay org-tags-overlay)
14782 (setq quit-flag t))
14783 ((= c ?\ )
14784 (setq current nil)
14785 (if exit-after-next (setq exit-after-next 'now)))
14786 ((= c ?\t)
14787 (condition-case nil
14788 (setq tg (org-icompleting-read
14789 "Tag: "
14790 (or buffer-tags
14791 (with-current-buffer buf
14792 (org-get-buffer-tags)))))
14793 (quit (setq tg "")))
14794 (when (string-match "\\S-" tg)
14795 (add-to-list 'buffer-tags (list tg))
14796 (if (member tg current)
14797 (setq current (delete tg current))
14798 (push tg current)))
14799 (if exit-after-next (setq exit-after-next 'now)))
14800 ((setq e (rassoc c todo-table) tg (car e))
14801 (with-current-buffer buf
14802 (save-excursion (org-todo tg)))
14803 (if exit-after-next (setq exit-after-next 'now)))
14804 ((setq e (rassoc c ntable) tg (car e))
14805 (if (member tg current)
14806 (setq current (delete tg current))
14807 (loop for g in groups do
14808 (if (member tg g)
14809 (mapc (lambda (x)
14810 (setq current (delete x current)))
14811 g)))
14812 (push tg current))
14813 (if exit-after-next (setq exit-after-next 'now))))
14815 ;; Create a sorted list
14816 (setq current
14817 (sort current
14818 (lambda (a b)
14819 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14820 (if (eq exit-after-next 'now) (throw 'exit t))
14821 (goto-char (point-min))
14822 (beginning-of-line 2)
14823 (delete-region (point) (point-at-eol))
14824 (org-fast-tag-insert "Current" current c-face)
14825 (org-set-current-tags-overlay current ov-prefix)
14826 (while (re-search-forward
14827 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14828 (setq tg (match-string 1))
14829 (add-text-properties
14830 (match-beginning 1) (match-end 1)
14831 (list 'face
14832 (cond
14833 ((member tg current) c-face)
14834 ((member tg inherited) i-face)
14835 (t (get-text-property (match-beginning 1) 'face))))))
14836 (goto-char (point-min)))))
14837 (org-detach-overlay org-tags-overlay)
14838 (if rtn
14839 (mapconcat 'identity current ":")
14840 nil))))
14842 (defun org-get-tags-string ()
14843 "Get the TAGS string in the current headline."
14844 (unless (org-at-heading-p t)
14845 (user-error "Not on a heading"))
14846 (save-excursion
14847 (beginning-of-line 1)
14848 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14849 (org-match-string-no-properties 1)
14850 "")))
14852 (defun org-get-tags ()
14853 "Get the list of tags specified in the current headline."
14854 (org-split-string (org-get-tags-string) ":"))
14856 (defun org-get-buffer-tags ()
14857 "Get a table of all tags used in the buffer, for completion."
14858 (let (tags)
14859 (save-excursion
14860 (goto-char (point-min))
14861 (while (re-search-forward
14862 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14863 (when (equal (char-after (point-at-bol 0)) ?*)
14864 (mapc (lambda (x) (add-to-list 'tags x))
14865 (org-split-string (org-match-string-no-properties 1) ":")))))
14866 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14867 (mapcar 'list tags)))
14869 ;;;; The mapping API
14871 (defun org-map-entries (func &optional match scope &rest skip)
14872 "Call FUNC at each headline selected by MATCH in SCOPE.
14874 FUNC is a function or a lisp form. The function will be called without
14875 arguments, with the cursor positioned at the beginning of the headline.
14876 The return values of all calls to the function will be collected and
14877 returned as a list.
14879 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14880 does not need to preserve point. After evaluation, the cursor will be
14881 moved to the end of the line (presumably of the headline of the
14882 processed entry) and search continues from there. Under some
14883 circumstances, this may not produce the wanted results. For example,
14884 if you have removed (e.g. archived) the current (sub)tree it could
14885 mean that the next entry will be skipped entirely. In such cases, you
14886 can specify the position from where search should continue by making
14887 FUNC set the variable `org-map-continue-from' to the desired buffer
14888 position.
14890 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14891 Only headlines that are matched by this query will be considered during
14892 the iteration. When MATCH is nil or t, all headlines will be
14893 visited by the iteration.
14895 SCOPE determines the scope of this command. It can be any of:
14897 nil The current buffer, respecting the restriction if any
14898 tree The subtree started with the entry at point
14899 region The entries within the active region, if any
14900 region-start-level
14901 The entries within the active region, but only those at
14902 the same level than the first one.
14903 file The current buffer, without restriction
14904 file-with-archives
14905 The current buffer, and any archives associated with it
14906 agenda All agenda files
14907 agenda-with-archives
14908 All agenda files with any archive files associated with them
14909 \(file1 file2 ...)
14910 If this is a list, all files in the list will be scanned
14912 The remaining args are treated as settings for the skipping facilities of
14913 the scanner. The following items can be given here:
14915 archive skip trees with the archive tag
14916 comment skip trees with the COMMENT keyword
14917 function or Emacs Lisp form:
14918 will be used as value for `org-agenda-skip-function', so
14919 whenever the function returns a position, FUNC will not be
14920 called for that entry and search will continue from the
14921 position returned
14923 If your function needs to retrieve the tags including inherited tags
14924 at the *current* entry, you can use the value of the variable
14925 `org-scanner-tags' which will be much faster than getting the value
14926 with `org-get-tags-at'. If your function gets properties with
14927 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14928 to t around the call to `org-entry-properties' to get the same speedup.
14929 Note that if your function moves around to retrieve tags and properties at
14930 a *different* entry, you cannot use these techniques."
14931 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14932 (not (org-region-active-p)))
14933 (let* ((org-agenda-archives-mode nil) ; just to make sure
14934 (org-agenda-skip-archived-trees (memq 'archive skip))
14935 (org-agenda-skip-comment-trees (memq 'comment skip))
14936 (org-agenda-skip-function
14937 (car (org-delete-all '(comment archive) skip)))
14938 (org-tags-match-list-sublevels t)
14939 (start-level (eq scope 'region-start-level))
14940 matcher file res
14941 org-todo-keywords-for-agenda
14942 org-done-keywords-for-agenda
14943 org-todo-keyword-alist-for-agenda
14944 org-tag-alist-for-agenda
14945 todo-only)
14947 (cond
14948 ((eq match t) (setq matcher t))
14949 ((eq match nil) (setq matcher t))
14950 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14952 (save-window-excursion
14953 (save-restriction
14954 (cond ((eq scope 'tree)
14955 (org-back-to-heading t)
14956 (org-narrow-to-subtree)
14957 (setq scope nil))
14958 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14959 (org-region-active-p))
14960 ;; If needed, set start-level to a string like "2"
14961 (when start-level
14962 (save-excursion
14963 (goto-char (region-beginning))
14964 (unless (org-at-heading-p) (outline-next-heading))
14965 (setq start-level (org-current-level))))
14966 (narrow-to-region (region-beginning)
14967 (save-excursion
14968 (goto-char (region-end))
14969 (unless (and (bolp) (org-at-heading-p))
14970 (outline-next-heading))
14971 (point)))
14972 (setq scope nil)))
14974 (if (not scope)
14975 (progn
14976 (org-agenda-prepare-buffers
14977 (list (buffer-file-name (current-buffer))))
14978 (setq res (org-scan-tags func matcher todo-only start-level)))
14979 ;; Get the right scope
14980 (cond
14981 ((and scope (listp scope) (symbolp (car scope)))
14982 (setq scope (eval scope)))
14983 ((eq scope 'agenda)
14984 (setq scope (org-agenda-files t)))
14985 ((eq scope 'agenda-with-archives)
14986 (setq scope (org-agenda-files t))
14987 (setq scope (org-add-archive-files scope)))
14988 ((eq scope 'file)
14989 (setq scope (list (buffer-file-name))))
14990 ((eq scope 'file-with-archives)
14991 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14992 (org-agenda-prepare-buffers scope)
14993 (while (setq file (pop scope))
14994 (with-current-buffer (org-find-base-buffer-visiting file)
14995 (save-excursion
14996 (save-restriction
14997 (widen)
14998 (goto-char (point-min))
14999 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15000 res)))
15002 ;;;; Properties
15004 ;;; Setting and retrieving properties
15006 (defconst org-special-properties
15007 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15008 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15009 "The special properties valid in Org-mode.
15011 These are properties that are not defined in the property drawer,
15012 but in some other way.")
15014 (defconst org-default-properties
15015 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15016 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15017 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15018 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15019 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15020 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15021 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15022 "Some properties that are used by Org-mode for various purposes.
15023 Being in this list makes sure that they are offered for completion.")
15025 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15026 "Regular expression matching the first line of a property drawer.")
15028 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15029 "Regular expression matching the last line of a property drawer.")
15031 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15032 "Regular expression matching the first line of a property drawer.")
15034 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15035 "Regular expression matching the first line of a property drawer.")
15037 (defconst org-property-drawer-re
15038 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
15039 org-property-end-re "\\)\n?")
15040 "Matches an entire property drawer.")
15042 (defconst org-clock-drawer-re
15043 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
15044 org-property-end-re "\\)\n?")
15045 "Matches an entire clock drawer.")
15047 (defun org-property-action ()
15048 "Do an action on properties."
15049 (interactive)
15050 (let (c)
15051 (org-at-property-p)
15052 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15053 (setq c (read-char-exclusive))
15054 (cond
15055 ((equal c ?s)
15056 (call-interactively 'org-set-property))
15057 ((equal c ?d)
15058 (call-interactively 'org-delete-property))
15059 ((equal c ?D)
15060 (call-interactively 'org-delete-property-globally))
15061 ((equal c ?c)
15062 (call-interactively 'org-compute-property-at-point))
15063 (t (user-error "No such property action %c" c)))))
15065 (defun org-inc-effort ()
15066 "Increment the value of the effort property in the current entry."
15067 (interactive)
15068 (org-set-effort nil t))
15070 (defvar org-clock-effort) ;; Defined in org-clock.el
15071 (defvar org-clock-current-task) ;; Defined in org-clock.el
15072 (defun org-set-effort (&optional value increment)
15073 "Set the effort property of the current entry.
15074 With numerical prefix arg, use the nth allowed value, 0 stands for the
15075 10th allowed value.
15077 When INCREMENT is non-nil, set the property to the next allowed value."
15078 (interactive "P")
15079 (if (equal value 0) (setq value 10))
15080 (let* ((completion-ignore-case t)
15081 (prop org-effort-property)
15082 (cur (org-entry-get nil prop))
15083 (allowed (org-property-get-allowed-values nil prop 'table))
15084 (existing (mapcar 'list (org-property-values prop)))
15085 (heading (nth 4 (org-heading-components)))
15087 (val (cond
15088 ((stringp value) value)
15089 ((and allowed (integerp value))
15090 (or (car (nth (1- value) allowed))
15091 (car (org-last allowed))))
15092 ((and allowed increment)
15093 (or (caadr (member (list cur) allowed))
15094 (user-error "Allowed effort values are not set")))
15095 (allowed
15096 (message "Select 1-9,0, [RET%s]: %s"
15097 (if cur (concat "=" cur) "")
15098 (mapconcat 'car allowed " "))
15099 (setq rpl (read-char-exclusive))
15100 (if (equal rpl ?\r)
15102 (setq rpl (- rpl ?0))
15103 (if (equal rpl 0) (setq rpl 10))
15104 (if (and (> rpl 0) (<= rpl (length allowed)))
15105 (car (nth (1- rpl) allowed))
15106 (org-completing-read "Effort: " allowed nil))))
15108 (let (org-completion-use-ido org-completion-use-iswitchb)
15109 (org-completing-read
15110 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15111 (concat "[" cur "]") "")
15112 ": ")
15113 existing nil nil "" nil cur))))))
15114 (unless (equal (org-entry-get nil prop) val)
15115 (org-entry-put nil prop val))
15116 (save-excursion
15117 (org-back-to-heading t)
15118 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15119 (when (string= heading org-clock-current-task)
15120 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15121 (org-clock-update-mode-line))
15122 (message "%s is now %s" prop val)))
15124 (defun org-at-property-p ()
15125 "Is cursor inside a property drawer?"
15126 (save-excursion
15127 (when (equal 'node-property (car (org-element-at-point)))
15128 (beginning-of-line 1)
15129 (looking-at org-property-re))))
15131 (defun org-get-property-block (&optional beg end force)
15132 "Return the (beg . end) range of the body of the property drawer.
15133 BEG and END are the beginning and end of the current subtree, or of
15134 the part before the first headline. If they are not given, they will
15135 be found. If the drawer does not exist and FORCE is non-nil, create
15136 the drawer."
15137 (catch 'exit
15138 (save-excursion
15139 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15140 (progn (org-back-to-heading t) (point))))
15141 (end (or end (and (not (outline-next-heading)) (point-max))
15142 (point))))
15143 (goto-char beg)
15144 (if (re-search-forward org-property-start-re end t)
15145 (setq beg (1+ (match-end 0)))
15146 (if force
15147 (save-excursion
15148 (org-insert-property-drawer)
15149 (setq end (progn (outline-next-heading) (point))))
15150 (throw 'exit nil))
15151 (goto-char beg)
15152 (if (re-search-forward org-property-start-re end t)
15153 (setq beg (1+ (match-end 0)))))
15154 (if (re-search-forward org-property-end-re end t)
15155 (setq end (match-beginning 0))
15156 (or force (throw 'exit nil))
15157 (goto-char beg)
15158 (setq end beg)
15159 (org-indent-line)
15160 (insert ":END:\n"))
15161 (cons beg end)))))
15163 (defun org-entry-properties (&optional pom which specific)
15164 "Get all properties of the entry at point-or-marker POM.
15165 This includes the TODO keyword, the tags, time strings for deadline,
15166 scheduled, and clocking, and any additional properties defined in the
15167 entry. The return value is an alist, keys may occur multiple times
15168 if the property key was used several times.
15169 POM may also be nil, in which case the current entry is used.
15170 If WHICH is nil or `all', get all properties. If WHICH is
15171 `special' or `standard', only get that subclass. If WHICH
15172 is a string only get exactly this property. SPECIFIC can be a string, the
15173 specific property we are interested in. Specifying it can speed
15174 things up because then unnecessary parsing is avoided."
15175 (setq which (or which 'all))
15176 (org-with-point-at pom
15177 (let ((clockstr (substring org-clock-string 0 -1))
15178 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15179 (case-fold-search nil)
15180 beg end range props sum-props key key1 value string clocksum clocksumt)
15181 (save-excursion
15182 (when (condition-case nil
15183 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15184 (error nil))
15185 (setq beg (point))
15186 (setq sum-props (get-text-property (point) 'org-summaries))
15187 (setq clocksum (get-text-property (point) :org-clock-minutes)
15188 clocksumt (get-text-property (point) :org-clock-minutes-today))
15189 (outline-next-heading)
15190 (setq end (point))
15191 (when (memq which '(all special))
15192 ;; Get the special properties, like TODO and tags
15193 (goto-char beg)
15194 (when (and (or (not specific) (string= specific "TODO"))
15195 (looking-at org-todo-line-regexp) (match-end 2))
15196 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15197 (when (and (or (not specific) (string= specific "PRIORITY"))
15198 (looking-at org-priority-regexp))
15199 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15200 (when (or (not specific) (string= specific "FILE"))
15201 (push (cons "FILE" buffer-file-name) props))
15202 (when (and (or (not specific) (string= specific "TAGS"))
15203 (setq value (org-get-tags-string))
15204 (string-match "\\S-" value))
15205 (push (cons "TAGS" value) props))
15206 (when (and (or (not specific) (string= specific "ALLTAGS"))
15207 (setq value (org-get-tags-at)))
15208 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15209 ":"))
15210 props))
15211 (when (or (not specific) (string= specific "BLOCKED"))
15212 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15213 (when (or (not specific)
15214 (member specific
15215 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15216 "TIMESTAMP" "TIMESTAMP_IA")))
15217 (catch 'match
15218 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15219 (setq key (if (match-end 1)
15220 (substring (org-match-string-no-properties 1)
15221 0 -1))
15222 string (if (equal key clockstr)
15223 (org-trim
15224 (buffer-substring-no-properties
15225 (match-beginning 3) (goto-char
15226 (point-at-eol))))
15227 (substring (org-match-string-no-properties 3)
15228 1 -1)))
15229 ;; Get the correct property name from the key. This is
15230 ;; necessary if the user has configured time keywords.
15231 (setq key1 (concat key ":"))
15232 (cond
15233 ((not key)
15234 (setq key
15235 (if (= (char-after (match-beginning 3)) ?\[)
15236 "TIMESTAMP_IA" "TIMESTAMP")))
15237 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15238 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15239 ((equal key1 org-closed-string) (setq key "CLOSED"))
15240 ((equal key1 org-clock-string) (setq key "CLOCK")))
15241 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15242 (progn
15243 (push (cons key string) props)
15244 ;; no need to search further if match is found
15245 (throw 'match t))
15246 (when (or (equal key "CLOCK") (not (assoc key props)))
15247 (push (cons key string) props)))))))
15249 (when (memq which '(all standard))
15250 ;; Get the standard properties, like :PROP: ...
15251 (setq range (org-get-property-block beg end))
15252 (when range
15253 (goto-char (car range))
15254 (while (re-search-forward org-property-re
15255 (cdr range) t)
15256 (setq key (org-match-string-no-properties 2)
15257 value (org-trim (or (org-match-string-no-properties 3) "")))
15258 (unless (member key excluded)
15259 (push (cons key (or value "")) props)))))
15260 (if clocksum
15261 (push (cons "CLOCKSUM"
15262 (org-columns-number-to-string (/ (float clocksum) 60.)
15263 'add_times))
15264 props))
15265 (if clocksumt
15266 (push (cons "CLOCKSUM_T"
15267 (org-columns-number-to-string (/ (float clocksumt) 60.)
15268 'add_times))
15269 props))
15270 (unless (assoc "CATEGORY" props)
15271 (push (cons "CATEGORY" (org-get-category)) props))
15272 (append sum-props (nreverse props)))))))
15274 (defun org-entry-get (pom property &optional inherit literal-nil)
15275 "Get value of PROPERTY for entry or content at point-or-marker POM.
15276 If INHERIT is non-nil and the entry does not have the property,
15277 then also check higher levels of the hierarchy.
15278 If INHERIT is the symbol `selective', use inheritance only if the setting
15279 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15280 If the property is present but empty, the return value is the empty string.
15281 If the property is not present at all, nil is returned.
15283 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15284 do not interpret it as the list atom nil. This is used for inheritance
15285 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15286 (org-with-point-at pom
15287 (if (and inherit (if (eq inherit 'selective)
15288 (org-property-inherit-p property)
15290 (org-entry-get-with-inheritance property literal-nil)
15291 (if (member property org-special-properties)
15292 ;; We need a special property. Use `org-entry-properties' to
15293 ;; retrieve it, but specify the wanted property
15294 (cdr (assoc property (org-entry-properties nil 'special property)))
15295 (let ((range (org-get-property-block)))
15296 (when (and range (not (eq (car range) (cdr range))))
15297 (let* ((props (list (or (assoc property org-file-properties)
15298 (assoc property org-global-properties)
15299 (assoc property org-global-properties-fixed))))
15300 (ap (lambda (key)
15301 (when (re-search-forward
15302 (org-re-property key) (cdr range) t)
15303 (setq props
15304 (org-update-property-plist
15306 (if (match-end 3)
15307 (org-match-string-no-properties 3) "")
15308 props)))))
15309 val)
15310 (goto-char (car range))
15311 (funcall ap property)
15312 (goto-char (car range))
15313 (while (funcall ap (concat property "+")))
15314 (setq val (cdr (assoc property props)))
15315 (when val (if literal-nil val (org-not-nil val))))))))))
15317 (defun org-property-or-variable-value (var &optional inherit)
15318 "Check if there is a property fixing the value of VAR.
15319 If yes, return this value. If not, return the current value of the variable."
15320 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15321 (if (and prop (stringp prop) (string-match "\\S-" prop))
15322 (read prop)
15323 (symbol-value var))))
15325 (defun org-entry-delete (pom property)
15326 "Delete the property PROPERTY from entry at point-or-marker POM."
15327 (unless (member property org-special-properties)
15328 (org-with-point-at pom
15329 (let ((range (org-get-property-block)))
15330 (if (and range
15331 (goto-char (car range))
15332 (re-search-forward
15333 (org-re-property property)
15334 (cdr range) t))
15335 (progn
15336 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15337 (org-remove-empty-drawer-at (car range))
15339 nil)))))
15341 ;; Multi-values properties are properties that contain multiple values
15342 ;; These values are assumed to be single words, separated by whitespace.
15343 (defun org-entry-add-to-multivalued-property (pom property value)
15344 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15345 (let* ((old (org-entry-get pom property))
15346 (values (and old (org-split-string old "[ \t]"))))
15347 (setq value (org-entry-protect-space value))
15348 (unless (member value values)
15349 (setq values (append values (list value)))
15350 (org-entry-put pom property
15351 (mapconcat 'identity values " ")))))
15353 (defun org-entry-remove-from-multivalued-property (pom property value)
15354 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15355 (let* ((old (org-entry-get pom property))
15356 (values (and old (org-split-string old "[ \t]"))))
15357 (setq value (org-entry-protect-space value))
15358 (when (member value values)
15359 (setq values (delete value values))
15360 (org-entry-put pom property
15361 (mapconcat 'identity values " ")))))
15363 (defun org-entry-member-in-multivalued-property (pom property value)
15364 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15365 (let* ((old (org-entry-get pom property))
15366 (values (and old (org-split-string old "[ \t]"))))
15367 (setq value (org-entry-protect-space value))
15368 (member value values)))
15370 (defun org-entry-get-multivalued-property (pom property)
15371 "Return a list of values in a multivalued property."
15372 (let* ((value (org-entry-get pom property))
15373 (values (and value (org-split-string value "[ \t]"))))
15374 (mapcar 'org-entry-restore-space values)))
15376 (defun org-entry-put-multivalued-property (pom property &rest values)
15377 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15378 VALUES should be a list of strings. Spaces will be protected."
15379 (org-entry-put pom property
15380 (mapconcat 'org-entry-protect-space values " "))
15381 (let* ((value (org-entry-get pom property))
15382 (values (and value (org-split-string value "[ \t]"))))
15383 (mapcar 'org-entry-restore-space values)))
15385 (defun org-entry-protect-space (s)
15386 "Protect spaces and newline in string S."
15387 (while (string-match " " s)
15388 (setq s (replace-match "%20" t t s)))
15389 (while (string-match "\n" s)
15390 (setq s (replace-match "%0A" t t s)))
15393 (defun org-entry-restore-space (s)
15394 "Restore spaces and newline in string S."
15395 (while (string-match "%20" s)
15396 (setq s (replace-match " " t t s)))
15397 (while (string-match "%0A" s)
15398 (setq s (replace-match "\n" t t s)))
15401 (defvar org-entry-property-inherited-from (make-marker)
15402 "Marker pointing to the entry from where a property was inherited.
15403 Each call to `org-entry-get-with-inheritance' will set this marker to the
15404 location of the entry where the inheritance search matched. If there was
15405 no match, the marker will point nowhere.
15406 Note that also `org-entry-get' calls this function, if the INHERIT flag
15407 is set.")
15409 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15410 "Get PROPERTY of entry or content at point, search higher levels if needed.
15411 The search will stop at the first ancestor which has the property defined.
15412 If the value found is \"nil\", return nil to show that the property
15413 should be considered as undefined (this is the meaning of nil here).
15414 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15415 (move-marker org-entry-property-inherited-from nil)
15416 (let (tmp)
15417 (save-excursion
15418 (save-restriction
15419 (widen)
15420 (catch 'ex
15421 (while t
15422 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15423 (or (ignore-errors (org-back-to-heading t))
15424 (goto-char (point-min)))
15425 (move-marker org-entry-property-inherited-from (point))
15426 (throw 'ex tmp))
15427 (or (ignore-errors (org-up-heading-safe))
15428 (throw 'ex nil))))))
15429 (setq tmp (or tmp
15430 (cdr (assoc property org-file-properties))
15431 (cdr (assoc property org-global-properties))
15432 (cdr (assoc property org-global-properties-fixed))))
15433 (if literal-nil tmp (org-not-nil tmp))))
15435 (defvar org-property-changed-functions nil
15436 "Hook called when the value of a property has changed.
15437 Each hook function should accept two arguments, the name of the property
15438 and the new value.")
15440 (defun org-entry-put (pom property value)
15441 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15442 (org-with-point-at pom
15443 (org-back-to-heading t)
15444 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15445 range)
15446 (cond
15447 ((equal property "TODO")
15448 (when (and (stringp value) (string-match "\\S-" value)
15449 (not (member value org-todo-keywords-1)))
15450 (user-error "\"%s\" is not a valid TODO state" value))
15451 (if (or (not value)
15452 (not (string-match "\\S-" value)))
15453 (setq value 'none))
15454 (org-todo value)
15455 (org-set-tags nil 'align))
15456 ((equal property "PRIORITY")
15457 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15458 (string-to-char value) ?\ ))
15459 (org-set-tags nil 'align))
15460 ((equal property "CLOCKSUM")
15461 (if (not (re-search-forward
15462 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15463 (error "Cannot find a clock log")
15464 (goto-char (- (match-end 1) 2))
15465 (cond
15466 ((eq value 'earlier) (org-timestamp-down))
15467 ((eq value 'later) (org-timestamp-up)))
15468 (org-clock-sum-current-item)))
15469 ((equal property "SCHEDULED")
15470 (if (re-search-forward org-scheduled-time-regexp end t)
15471 (cond
15472 ((eq value 'earlier) (org-timestamp-change -1 'day))
15473 ((eq value 'later) (org-timestamp-change 1 'day))
15474 (t (call-interactively 'org-schedule)))
15475 (call-interactively 'org-schedule)))
15476 ((equal property "DEADLINE")
15477 (if (re-search-forward org-deadline-time-regexp end t)
15478 (cond
15479 ((eq value 'earlier) (org-timestamp-change -1 'day))
15480 ((eq value 'later) (org-timestamp-change 1 'day))
15481 (t (call-interactively 'org-deadline)))
15482 (call-interactively 'org-deadline)))
15483 ((member property org-special-properties)
15484 (error "The %s property can not yet be set with `org-entry-put'"
15485 property))
15486 (t ; a non-special property
15487 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15488 (setq range (org-get-property-block beg end 'force))
15489 (goto-char (car range))
15490 (if (re-search-forward
15491 (org-re-property property) (cdr range) t)
15492 (progn
15493 (delete-region (match-beginning 0) (match-end 0))
15494 (goto-char (match-beginning 0)))
15495 (goto-char (cdr range))
15496 (insert "\n")
15497 (backward-char 1)
15498 (org-indent-line))
15499 (insert ":" property ":")
15500 (and value (insert " " value))
15501 (org-indent-line)))))
15502 (run-hook-with-args 'org-property-changed-functions property value)))
15504 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15505 "Get all property keys in the current buffer.
15506 With INCLUDE-SPECIALS, also list the special properties that reflect things
15507 like tags and TODO state.
15508 With INCLUDE-DEFAULTS, also include properties that has special meaning
15509 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15510 and others.
15511 With INCLUDE-COLUMNS, also include property names given in COLUMN
15512 formats in the current buffer."
15513 (let (rtn range cfmt s p)
15514 (save-excursion
15515 (save-restriction
15516 (widen)
15517 (goto-char (point-min))
15518 (while (re-search-forward org-property-start-re nil t)
15519 (setq range (org-get-property-block))
15520 (goto-char (car range))
15521 (while (re-search-forward org-property-re
15522 (cdr range) t)
15523 (add-to-list 'rtn (org-match-string-no-properties 2)))
15524 (outline-next-heading))))
15526 (when include-specials
15527 (setq rtn (append org-special-properties rtn)))
15529 (when include-defaults
15530 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15531 (add-to-list 'rtn org-effort-property))
15533 (when include-columns
15534 (save-excursion
15535 (save-restriction
15536 (widen)
15537 (goto-char (point-min))
15538 (while (re-search-forward
15539 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15540 nil t)
15541 (setq cfmt (match-string 2) s 0)
15542 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15543 cfmt s)
15544 (setq s (match-end 0)
15545 p (match-string 1 cfmt))
15546 (unless (or (equal p "ITEM")
15547 (member p org-special-properties))
15548 (add-to-list 'rtn (match-string 1 cfmt))))))))
15550 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15552 (defun org-property-values (key)
15553 "Return a list of all values of property KEY in the current buffer."
15554 (save-excursion
15555 (save-restriction
15556 (widen)
15557 (goto-char (point-min))
15558 (let ((re (org-re-property key))
15559 values)
15560 (while (re-search-forward re nil t)
15561 (add-to-list 'values (org-trim (match-string 3))))
15562 (delete "" values)))))
15564 (defun org-insert-property-drawer ()
15565 "Insert a property drawer into the current entry."
15566 (org-back-to-heading t)
15567 (looking-at org-outline-regexp)
15568 (let ((indent (if org-adapt-indentation
15569 (- (match-end 0) (match-beginning 0))
15571 (beg (point))
15572 (re (concat "^[ \t]*" org-keyword-time-regexp))
15573 end hiddenp)
15574 (outline-next-heading)
15575 (setq end (point))
15576 (goto-char beg)
15577 (while (re-search-forward re end t))
15578 (setq hiddenp (outline-invisible-p))
15579 (end-of-line 1)
15580 (and (equal (char-after) ?\n) (forward-char 1))
15581 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15582 (if (member (match-string 1) '("CLOCK:" ":END:"))
15583 ;; just skip this line
15584 (beginning-of-line 2)
15585 ;; Drawer start, find the end
15586 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15587 (beginning-of-line 1)))
15588 (org-skip-over-state-notes)
15589 (skip-chars-backward " \t\n\r")
15590 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15591 (forward-char 1))
15592 (goto-char (point-at-eol))
15593 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15594 (beginning-of-line 0)
15595 (org-indent-to-column indent)
15596 (beginning-of-line 2)
15597 (org-indent-to-column indent)
15598 (beginning-of-line 0)
15599 (if hiddenp
15600 (save-excursion
15601 (org-back-to-heading t)
15602 (hide-entry))
15603 (org-flag-drawer t))))
15605 (defun org-insert-drawer (&optional arg drawer)
15606 "Insert a drawer at point.
15608 Optional argument DRAWER, when non-nil, is a string representing
15609 drawer's name. Otherwise, the user is prompted for a name.
15611 If a region is active, insert the drawer around that region
15612 instead.
15614 Point is left between drawer's boundaries."
15615 (interactive "P")
15616 (let* ((drawer (if arg "PROPERTIES"
15617 (or drawer (read-from-minibuffer "Drawer: ")))))
15618 (cond
15619 ;; With C-u, fall back on `org-insert-property-drawer'
15620 (arg (org-insert-property-drawer))
15622 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15623 (user-error "Invalid drawer name"))
15624 ;; With an active region, insert a drawer at point.
15625 ((not (org-region-active-p))
15626 (progn
15627 (unless (bolp) (insert "\n"))
15628 (insert (format ":%s:\n\n:END:\n" drawer))
15629 (forward-line -2)))
15630 ;; Otherwise, insert the drawer at point
15632 (let ((rbeg (region-beginning))
15633 (rend (copy-marker (region-end))))
15634 (unwind-protect
15635 (progn
15636 (goto-char rbeg)
15637 (beginning-of-line)
15638 (when (save-excursion
15639 (re-search-forward org-outline-regexp-bol rend t))
15640 (user-error "Drawers cannot contain headlines"))
15641 ;; Position point at the beginning of the first
15642 ;; non-blank line in region. Insert drawer's opening
15643 ;; there, then indent it.
15644 (org-skip-whitespace)
15645 (beginning-of-line)
15646 (insert ":" drawer ":\n")
15647 (forward-line -1)
15648 (indent-for-tab-command)
15649 ;; Move point to the beginning of the first blank line
15650 ;; after the last non-blank line in region. Insert
15651 ;; drawer's closing, then indent it.
15652 (goto-char rend)
15653 (skip-chars-backward " \r\t\n")
15654 (insert "\n:END:")
15655 (deactivate-mark t)
15656 (indent-for-tab-command)
15657 (unless (eolp) (insert "\n")))
15658 ;; Clear marker, whatever the outcome of insertion is.
15659 (set-marker rend nil)))))))
15661 (defvar org-property-set-functions-alist nil
15662 "Property set function alist.
15663 Each entry should have the following format:
15665 (PROPERTY . READ-FUNCTION)
15667 The read function will be called with the same argument as
15668 `org-completing-read'.")
15670 (defun org-set-property-function (property)
15671 "Get the function that should be used to set PROPERTY.
15672 This is computed according to `org-property-set-functions-alist'."
15673 (or (cdr (assoc property org-property-set-functions-alist))
15674 'org-completing-read))
15676 (defun org-read-property-value (property)
15677 "Read PROPERTY value from user."
15678 (let* ((completion-ignore-case t)
15679 (allowed (org-property-get-allowed-values nil property 'table))
15680 (cur (org-entry-get nil property))
15681 (prompt (concat property " value"
15682 (if (and cur (string-match "\\S-" cur))
15683 (concat " [" cur "]") "") ": "))
15684 (set-function (org-set-property-function property))
15685 (val (if allowed
15686 (funcall set-function prompt allowed nil
15687 (not (get-text-property 0 'org-unrestricted
15688 (caar allowed))))
15689 (let (org-completion-use-ido org-completion-use-iswitchb)
15690 (funcall set-function prompt
15691 (mapcar 'list (org-property-values property))
15692 nil nil "" nil cur)))))
15693 (if (equal val "")
15695 val)))
15697 (defvar org-last-set-property nil)
15698 (defvar org-last-set-property-value nil)
15699 (defun org-read-property-name ()
15700 "Read a property name."
15701 (let* ((completion-ignore-case t)
15702 (keys (org-buffer-property-keys nil t t))
15703 (default-prop (or (save-excursion
15704 (save-match-data
15705 (beginning-of-line)
15706 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15707 (null (string= (match-string 1) "END"))
15708 (match-string 1))))
15709 org-last-set-property))
15710 (property (org-icompleting-read
15711 (concat "Property"
15712 (if default-prop (concat " [" default-prop "]") "")
15713 ": ")
15714 (mapcar 'list keys)
15715 nil nil nil nil
15716 default-prop)))
15717 (if (member property keys)
15718 property
15719 (or (cdr (assoc (downcase property)
15720 (mapcar (lambda (x) (cons (downcase x) x))
15721 keys)))
15722 property))))
15724 (defun org-set-property-and-value (use-last)
15725 "Allow to set [PROPERTY]: [value] direction from prompt.
15726 When use-default, don't even ask, just use the last
15727 \"[PROPERTY]: [value]\" string from the history."
15728 (interactive "P")
15729 (let* ((completion-ignore-case t)
15730 (pv (or (and use-last org-last-set-property-value)
15731 (org-completing-read
15732 "Enter a \"[Property]: [value]\" pair: "
15733 nil nil nil nil nil
15734 org-last-set-property-value)))
15735 prop val)
15736 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15737 (setq prop (match-string 1 pv)
15738 val (match-string 2 pv))
15739 (org-set-property prop val))))
15741 (defun org-set-property (property value)
15742 "In the current entry, set PROPERTY to VALUE.
15743 When called interactively, this will prompt for a property name, offering
15744 completion on existing and default properties. And then it will prompt
15745 for a value, offering completion either on allowed values (via an inherited
15746 xxx_ALL property) or on existing values in other instances of this property
15747 in the current file."
15748 (interactive (list nil nil))
15749 (let* ((property (or property (org-read-property-name)))
15750 (value (or value (org-read-property-value property)))
15751 (fn (cdr (assoc property org-properties-postprocess-alist))))
15752 (setq org-last-set-property property)
15753 (setq org-last-set-property-value (concat property ": " value))
15754 ;; Possibly postprocess the inserted value:
15755 (when fn (setq value (funcall fn value)))
15756 (unless (equal (org-entry-get nil property) value)
15757 (org-entry-put nil property value))))
15759 (defun org-delete-property (property)
15760 "In the current entry, delete PROPERTY."
15761 (interactive
15762 (let* ((completion-ignore-case t)
15763 (prop (org-icompleting-read "Property: "
15764 (org-entry-properties nil 'standard))))
15765 (list prop)))
15766 (message "Property %s %s" property
15767 (if (org-entry-delete nil property)
15768 "deleted"
15769 "was not present in the entry")))
15771 (defun org-delete-property-globally (property)
15772 "Remove PROPERTY globally, from all entries."
15773 (interactive
15774 (let* ((completion-ignore-case t)
15775 (prop (org-icompleting-read
15776 "Globally remove property: "
15777 (mapcar 'list (org-buffer-property-keys)))))
15778 (list prop)))
15779 (save-excursion
15780 (save-restriction
15781 (widen)
15782 (goto-char (point-min))
15783 (let ((cnt 0))
15784 (while (re-search-forward
15785 (org-re-property property)
15786 nil t)
15787 (setq cnt (1+ cnt))
15788 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15789 (message "Property \"%s\" removed from %d entries" property cnt)))))
15791 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15793 (defun org-compute-property-at-point ()
15794 "Compute the property at point.
15795 This looks for an enclosing column format, extracts the operator and
15796 then applies it to the property in the column format's scope."
15797 (interactive)
15798 (unless (org-at-property-p)
15799 (user-error "Not at a property"))
15800 (let ((prop (org-match-string-no-properties 2)))
15801 (org-columns-get-format-and-top-level)
15802 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15803 (user-error "No operator defined for property %s" prop))
15804 (org-columns-compute prop)))
15806 (defvar org-property-allowed-value-functions nil
15807 "Hook for functions supplying allowed values for a specific property.
15808 The functions must take a single argument, the name of the property, and
15809 return a flat list of allowed values. If \":ETC\" is one of
15810 the values, this means that these values are intended as defaults for
15811 completion, but that other values should be allowed too.
15812 The functions must return nil if they are not responsible for this
15813 property.")
15815 (defun org-property-get-allowed-values (pom property &optional table)
15816 "Get allowed values for the property PROPERTY.
15817 When TABLE is non-nil, return an alist that can directly be used for
15818 completion."
15819 (let (vals)
15820 (cond
15821 ((equal property "TODO")
15822 (setq vals (org-with-point-at pom
15823 (append org-todo-keywords-1 '("")))))
15824 ((equal property "PRIORITY")
15825 (let ((n org-lowest-priority))
15826 (while (>= n org-highest-priority)
15827 (push (char-to-string n) vals)
15828 (setq n (1- n)))))
15829 ((member property org-special-properties))
15830 ((setq vals (run-hook-with-args-until-success
15831 'org-property-allowed-value-functions property)))
15833 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15834 (when (and vals (string-match "\\S-" vals))
15835 (setq vals (car (read-from-string (concat "(" vals ")"))))
15836 (setq vals (mapcar (lambda (x)
15837 (cond ((stringp x) x)
15838 ((numberp x) (number-to-string x))
15839 ((symbolp x) (symbol-name x))
15840 (t "???")))
15841 vals)))))
15842 (when (member ":ETC" vals)
15843 (setq vals (remove ":ETC" vals))
15844 (org-add-props (car vals) '(org-unrestricted t)))
15845 (if table (mapcar 'list vals) vals)))
15847 (defun org-property-previous-allowed-value (&optional previous)
15848 "Switch to the next allowed value for this property."
15849 (interactive)
15850 (org-property-next-allowed-value t))
15852 (defun org-property-next-allowed-value (&optional previous)
15853 "Switch to the next allowed value for this property."
15854 (interactive)
15855 (unless (org-at-property-p)
15856 (user-error "Not at a property"))
15857 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15858 (key (match-string 2))
15859 (value (match-string 3))
15860 (allowed (or (org-property-get-allowed-values (point) key)
15861 (and (member value '("[ ]" "[-]" "[X]"))
15862 '("[ ]" "[X]"))))
15863 (heading (save-match-data (nth 4 (org-heading-components))))
15864 nval)
15865 (unless allowed
15866 (user-error "Allowed values for this property have not been defined"))
15867 (if previous (setq allowed (reverse allowed)))
15868 (if (member value allowed)
15869 (setq nval (car (cdr (member value allowed)))))
15870 (setq nval (or nval (car allowed)))
15871 (if (equal nval value)
15872 (user-error "Only one allowed value for this property"))
15873 (org-at-property-p)
15874 (replace-match (concat " :" key ": " nval) t t)
15875 (org-indent-line)
15876 (beginning-of-line 1)
15877 (skip-chars-forward " \t")
15878 (when (equal prop org-effort-property)
15879 (save-excursion
15880 (org-back-to-heading t)
15881 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15882 (when (string= org-clock-current-task heading)
15883 (setq org-clock-effort nval)
15884 (org-clock-update-mode-line)))
15885 (run-hook-with-args 'org-property-changed-functions key nval)))
15887 (defun org-find-olp (path &optional this-buffer)
15888 "Return a marker pointing to the entry at outline path OLP.
15889 If anything goes wrong, throw an error.
15890 You can wrap this call to catch the error like this:
15892 (condition-case msg
15893 (org-mobile-locate-entry (match-string 4))
15894 (error (nth 1 msg)))
15896 The return value will then be either a string with the error message,
15897 or a marker if everything is OK.
15899 If THIS-BUFFER is set, the outline path does not contain a file,
15900 only headings."
15901 (let* ((file (if this-buffer buffer-file-name (pop path)))
15902 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15903 (level 1)
15904 (lmin 1)
15905 (lmax 1)
15906 limit re end found pos heading cnt flevel)
15907 (unless buffer (error "File not found :%s" file))
15908 (with-current-buffer buffer
15909 (save-excursion
15910 (save-restriction
15911 (widen)
15912 (setq limit (point-max))
15913 (goto-char (point-min))
15914 (while (setq heading (pop path))
15915 (setq re (format org-complex-heading-regexp-format
15916 (regexp-quote heading)))
15917 (setq cnt 0 pos (point))
15918 (while (re-search-forward re end t)
15919 (setq level (- (match-end 1) (match-beginning 1)))
15920 (if (and (>= level lmin) (<= level lmax))
15921 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15922 (when (= cnt 0) (error "Heading not found on level %d: %s"
15923 lmax heading))
15924 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15925 lmax heading))
15926 (goto-char found)
15927 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15928 (setq end (save-excursion (org-end-of-subtree t t))))
15929 (when (org-at-heading-p)
15930 (point-marker)))))))
15932 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15933 "Find node HEADING in BUFFER.
15934 Return a marker to the heading if it was found, or nil if not.
15935 If POS-ONLY is set, return just the position instead of a marker.
15937 The heading text must match exact, but it may have a TODO keyword,
15938 a priority cookie and tags in the standard locations."
15939 (with-current-buffer (or buffer (current-buffer))
15940 (save-excursion
15941 (save-restriction
15942 (widen)
15943 (goto-char (point-min))
15944 (let (case-fold-search)
15945 (if (re-search-forward
15946 (format org-complex-heading-regexp-format
15947 (regexp-quote heading)) nil t)
15948 (if pos-only
15949 (match-beginning 0)
15950 (move-marker (make-marker) (match-beginning 0)))))))))
15952 (defun org-find-exact-heading-in-directory (heading &optional dir)
15953 "Find Org node headline HEADING in all .org files in directory DIR.
15954 When the target headline is found, return a marker to this location."
15955 (let ((files (directory-files (or dir default-directory)
15956 nil "\\`[^.#].*\\.org\\'"))
15957 file visiting m buffer)
15958 (catch 'found
15959 (while (setq file (pop files))
15960 (message "trying %s" file)
15961 (setq visiting (org-find-base-buffer-visiting file))
15962 (setq buffer (or visiting (find-file-noselect file)))
15963 (setq m (org-find-exact-headline-in-buffer
15964 heading buffer))
15965 (when (and (not m) (not visiting)) (kill-buffer buffer))
15966 (and m (throw 'found m))))))
15968 (defun org-find-entry-with-id (ident)
15969 "Locate the entry that contains the ID property with exact value IDENT.
15970 IDENT can be a string, a symbol or a number, this function will search for
15971 the string representation of it.
15972 Return the position where this entry starts, or nil if there is no such entry."
15973 (interactive "sID: ")
15974 (let ((id (cond
15975 ((stringp ident) ident)
15976 ((symbol-name ident) (symbol-name ident))
15977 ((numberp ident) (number-to-string ident))
15978 (t (error "IDENT %s must be a string, symbol or number" ident))))
15979 (case-fold-search nil))
15980 (save-excursion
15981 (save-restriction
15982 (widen)
15983 (goto-char (point-min))
15984 (when (re-search-forward
15985 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15986 nil t)
15987 (org-back-to-heading t)
15988 (point))))))
15990 ;;;; Timestamps
15992 (defvar org-last-changed-timestamp nil)
15993 (defvar org-last-inserted-timestamp nil
15994 "The last time stamp inserted with `org-insert-time-stamp'.")
15995 (defvar org-time-was-given) ; dynamically scoped parameter
15996 (defvar org-end-time-was-given) ; dynamically scoped parameter
15997 (defvar org-ts-what) ; dynamically scoped parameter
15999 (defun org-time-stamp (arg &optional inactive)
16000 "Prompt for a date/time and insert a time stamp.
16001 If the user specifies a time like HH:MM or if this command is
16002 called with at least one prefix argument, the time stamp contains
16003 the date and the time. Otherwise, only the date is be included.
16005 All parts of a date not specified by the user is filled in from
16006 the current date/time. So if you just press return without
16007 typing anything, the time stamp will represent the current
16008 date/time.
16010 If there is already a timestamp at the cursor, it will be
16011 modified.
16013 With two universal prefix arguments, insert an active timestamp
16014 with the current time without prompting the user.
16016 When called from lisp, the timestamp is inactive if INACTIVE is
16017 non-nil."
16018 (interactive "P")
16019 (let* ((ts nil)
16020 (default-time
16021 ;; Default time is either today, or, when entering a range,
16022 ;; the range start.
16023 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16024 (save-excursion
16025 (re-search-backward
16026 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16027 (- (point) 20) t)))
16028 (apply 'encode-time (org-parse-time-string (match-string 1)))
16029 (current-time)))
16030 (default-input (and ts (org-get-compact-tod ts)))
16031 (repeater (save-excursion
16032 (save-match-data
16033 (beginning-of-line)
16034 (when (re-search-forward
16035 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16036 (save-excursion (progn (end-of-line) (point))) t)
16037 (match-string 0)))))
16038 org-time-was-given org-end-time-was-given time)
16039 (cond
16040 ((and (org-at-timestamp-p t)
16041 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16042 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16043 (insert "--")
16044 (setq time (let ((this-command this-command))
16045 (org-read-date arg 'totime nil nil
16046 default-time default-input inactive)))
16047 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16048 ((org-at-timestamp-p t)
16049 (setq time (let ((this-command this-command))
16050 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16051 (when (org-at-timestamp-p t) ; just to get the match data
16052 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16053 (replace-match "")
16054 (setq org-last-changed-timestamp
16055 (org-insert-time-stamp
16056 time (or org-time-was-given arg)
16057 inactive nil nil (list org-end-time-was-given)))
16058 (when repeater (goto-char (1- (point))) (insert " " repeater)
16059 (setq org-last-changed-timestamp
16060 (concat (substring org-last-inserted-timestamp 0 -1)
16061 " " repeater ">"))))
16062 (message "Timestamp updated"))
16063 ((equal arg '(16))
16064 (org-insert-time-stamp (current-time) t inactive))
16066 (setq time (let ((this-command this-command))
16067 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16068 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16069 nil nil (list org-end-time-was-given))))))
16071 ;; FIXME: can we use this for something else, like computing time differences?
16072 (defun org-get-compact-tod (s)
16073 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16074 (let* ((t1 (match-string 1 s))
16075 (h1 (string-to-number (match-string 2 s)))
16076 (m1 (string-to-number (match-string 3 s)))
16077 (t2 (and (match-end 4) (match-string 5 s)))
16078 (h2 (and t2 (string-to-number (match-string 6 s))))
16079 (m2 (and t2 (string-to-number (match-string 7 s))))
16080 dh dm)
16081 (if (not t2)
16083 (setq dh (- h2 h1) dm (- m2 m1))
16084 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16085 (concat t1 "+" (number-to-string dh)
16086 (and (/= 0 dm) (format ":%02d" dm)))))))
16088 (defun org-time-stamp-inactive (&optional arg)
16089 "Insert an inactive time stamp.
16090 An inactive time stamp is enclosed in square brackets instead of angle
16091 brackets. It is inactive in the sense that it does not trigger agenda entries,
16092 does not link to the calendar and cannot be changed with the S-cursor keys.
16093 So these are more for recording a certain time/date."
16094 (interactive "P")
16095 (org-time-stamp arg 'inactive))
16097 (defvar org-date-ovl (make-overlay 1 1))
16098 (overlay-put org-date-ovl 'face 'org-date-selected)
16099 (org-detach-overlay org-date-ovl)
16101 (defvar org-ans1) ; dynamically scoped parameter
16102 (defvar org-ans2) ; dynamically scoped parameter
16104 (defvar org-plain-time-of-day-regexp) ; defined below
16106 (defvar org-overriding-default-time nil) ; dynamically scoped
16107 (defvar org-read-date-overlay nil)
16108 (defvar org-dcst nil) ; dynamically scoped
16109 (defvar org-read-date-history nil)
16110 (defvar org-read-date-final-answer nil)
16111 (defvar org-read-date-analyze-futurep nil)
16112 (defvar org-read-date-analyze-forced-year nil)
16113 (defvar org-read-date-inactive)
16115 (defvar org-read-date-minibuffer-local-map
16116 (let* ((org-replace-disputed-keys nil)
16117 (map (make-sparse-keymap)))
16118 (set-keymap-parent map minibuffer-local-map)
16119 (org-defkey map (kbd ".")
16120 (lambda () (interactive)
16121 ;; Are we at the beginning of the prompt?
16122 (if (looking-back "^[^:]+: ")
16123 (org-eval-in-calendar '(calendar-goto-today))
16124 (insert "."))))
16125 (org-defkey map (kbd "C-.")
16126 (lambda () (interactive)
16127 (org-eval-in-calendar '(calendar-goto-today))))
16128 (org-defkey map [(meta shift left)]
16129 (lambda () (interactive)
16130 (org-eval-in-calendar '(calendar-backward-month 1))))
16131 (org-defkey map [(meta shift right)]
16132 (lambda () (interactive)
16133 (org-eval-in-calendar '(calendar-forward-month 1))))
16134 (org-defkey map [(meta shift up)]
16135 (lambda () (interactive)
16136 (org-eval-in-calendar '(calendar-backward-year 1))))
16137 (org-defkey map [(meta shift down)]
16138 (lambda () (interactive)
16139 (org-eval-in-calendar '(calendar-forward-year 1))))
16140 (org-defkey map [?\e (shift left)]
16141 (lambda () (interactive)
16142 (org-eval-in-calendar '(calendar-backward-month 1))))
16143 (org-defkey map [?\e (shift right)]
16144 (lambda () (interactive)
16145 (org-eval-in-calendar '(calendar-forward-month 1))))
16146 (org-defkey map [?\e (shift up)]
16147 (lambda () (interactive)
16148 (org-eval-in-calendar '(calendar-backward-year 1))))
16149 (org-defkey map [?\e (shift down)]
16150 (lambda () (interactive)
16151 (org-eval-in-calendar '(calendar-forward-year 1))))
16152 (org-defkey map [(shift up)]
16153 (lambda () (interactive)
16154 (org-eval-in-calendar '(calendar-backward-week 1))))
16155 (org-defkey map [(shift down)]
16156 (lambda () (interactive)
16157 (org-eval-in-calendar '(calendar-forward-week 1))))
16158 (org-defkey map [(shift left)]
16159 (lambda () (interactive)
16160 (org-eval-in-calendar '(calendar-backward-day 1))))
16161 (org-defkey map [(shift right)]
16162 (lambda () (interactive)
16163 (org-eval-in-calendar '(calendar-forward-day 1))))
16164 (org-defkey map "!"
16165 (lambda () (interactive)
16166 (org-eval-in-calendar '(diary-view-entries))
16167 (message "")))
16168 (org-defkey map ">"
16169 (lambda () (interactive)
16170 (org-eval-in-calendar '(scroll-calendar-left 1))))
16171 (org-defkey map "<"
16172 (lambda () (interactive)
16173 (org-eval-in-calendar '(scroll-calendar-right 1))))
16174 (org-defkey map "\C-v"
16175 (lambda () (interactive)
16176 (org-eval-in-calendar
16177 '(calendar-scroll-left-three-months 1))))
16178 (org-defkey map "\M-v"
16179 (lambda () (interactive)
16180 (org-eval-in-calendar
16181 '(calendar-scroll-right-three-months 1))))
16182 map)
16183 "Keymap for minibuffer commands when using `org-read-date'.")
16185 (defun org-read-date (&optional org-with-time to-time from-string prompt
16186 default-time default-input inactive)
16187 "Read a date, possibly a time, and make things smooth for the user.
16188 The prompt will suggest to enter an ISO date, but you can also enter anything
16189 which will at least partially be understood by `parse-time-string'.
16190 Unrecognized parts of the date will default to the current day, month, year,
16191 hour and minute. If this command is called to replace a timestamp at point,
16192 or to enter the second timestamp of a range, the default time is taken
16193 from the existing stamp. Furthermore, the command prefers the future,
16194 so if you are giving a date where the year is not given, and the day-month
16195 combination is already past in the current year, it will assume you
16196 mean next year. For details, see the manual. A few examples:
16198 3-2-5 --> 2003-02-05
16199 feb 15 --> currentyear-02-15
16200 2/15 --> currentyear-02-15
16201 sep 12 9 --> 2009-09-12
16202 12:45 --> today 12:45
16203 22 sept 0:34 --> currentyear-09-22 0:34
16204 12 --> currentyear-currentmonth-12
16205 Fri --> nearest Friday after today
16206 -Tue --> last Tuesday
16207 etc.
16209 Furthermore you can specify a relative date by giving, as the *first* thing
16210 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16211 change in days weeks, months, years.
16212 With a single plus or minus, the date is relative to today. With a double
16213 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16214 +4d --> four days from today
16215 +4 --> same as above
16216 +2w --> two weeks from today
16217 ++5 --> five days from default date
16219 The function understands only English month and weekday abbreviations.
16221 While prompting, a calendar is popped up - you can also select the
16222 date with the mouse (button 1). The calendar shows a period of three
16223 months. To scroll it to other months, use the keys `>' and `<'.
16224 If you don't like the calendar, turn it off with
16225 \(setq org-read-date-popup-calendar nil)
16227 With optional argument TO-TIME, the date will immediately be converted
16228 to an internal time.
16229 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16230 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16231 still enter a time, and this function will inform the calling routine
16232 about this change. The calling routine may then choose to change the
16233 format used to insert the time stamp into the buffer to include the time.
16234 With optional argument FROM-STRING, read from this string instead from
16235 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16236 the time/date that is used for everything that is not specified by the
16237 user."
16238 (require 'parse-time)
16239 (let* ((org-time-stamp-rounding-minutes
16240 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16241 (org-dcst org-display-custom-times)
16242 (ct (org-current-time))
16243 (org-def (or org-overriding-default-time default-time ct))
16244 (org-defdecode (decode-time org-def))
16245 (dummy (progn
16246 (when (< (nth 2 org-defdecode) org-extend-today-until)
16247 (setcar (nthcdr 2 org-defdecode) -1)
16248 (setcar (nthcdr 1 org-defdecode) 59)
16249 (setq org-def (apply 'encode-time org-defdecode)
16250 org-defdecode (decode-time org-def)))))
16251 (mouse-autoselect-window nil) ; Don't let the mouse jump
16252 (calendar-frame-setup nil)
16253 (calendar-setup nil)
16254 (calendar-move-hook nil)
16255 (calendar-view-diary-initially-flag nil)
16256 (calendar-view-holidays-initially-flag nil)
16257 (timestr (format-time-string
16258 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16259 (prompt (concat (if prompt (concat prompt " ") "")
16260 (format "Date+time [%s]: " timestr)))
16261 ans (org-ans0 "") org-ans1 org-ans2 final)
16263 (cond
16264 (from-string (setq ans from-string))
16265 (org-read-date-popup-calendar
16266 (save-excursion
16267 (save-window-excursion
16268 (calendar)
16269 (org-eval-in-calendar '(setq cursor-type nil) t)
16270 (unwind-protect
16271 (progn
16272 (calendar-forward-day (- (time-to-days org-def)
16273 (calendar-absolute-from-gregorian
16274 (calendar-current-date))))
16275 (org-eval-in-calendar nil t)
16276 (let* ((old-map (current-local-map))
16277 (map (copy-keymap calendar-mode-map))
16278 (minibuffer-local-map
16279 (copy-keymap org-read-date-minibuffer-local-map)))
16280 (org-defkey map (kbd "RET") 'org-calendar-select)
16281 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16282 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16283 (unwind-protect
16284 (progn
16285 (use-local-map map)
16286 (setq org-read-date-inactive inactive)
16287 (add-hook 'post-command-hook 'org-read-date-display)
16288 (setq org-ans0 (read-string prompt default-input
16289 'org-read-date-history nil))
16290 ;; org-ans0: from prompt
16291 ;; org-ans1: from mouse click
16292 ;; org-ans2: from calendar motion
16293 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16294 (remove-hook 'post-command-hook 'org-read-date-display)
16295 (use-local-map old-map)
16296 (when org-read-date-overlay
16297 (delete-overlay org-read-date-overlay)
16298 (setq org-read-date-overlay nil)))))
16299 (bury-buffer "*Calendar*")))))
16301 (t ; Naked prompt only
16302 (unwind-protect
16303 (setq ans (read-string prompt default-input
16304 'org-read-date-history timestr))
16305 (when org-read-date-overlay
16306 (delete-overlay org-read-date-overlay)
16307 (setq org-read-date-overlay nil)))))
16309 (setq final (org-read-date-analyze ans org-def org-defdecode))
16311 (when org-read-date-analyze-forced-year
16312 (message "Year was forced into %s"
16313 (if org-read-date-force-compatible-dates
16314 "compatible range (1970-2037)"
16315 "range representable on this machine"))
16316 (ding))
16318 ;; One round trip to get rid of 34th of August and stuff like that....
16319 (setq final (decode-time (apply 'encode-time final)))
16321 (setq org-read-date-final-answer ans)
16323 (if to-time
16324 (apply 'encode-time final)
16325 (if (and (boundp 'org-time-was-given) org-time-was-given)
16326 (format "%04d-%02d-%02d %02d:%02d"
16327 (nth 5 final) (nth 4 final) (nth 3 final)
16328 (nth 2 final) (nth 1 final))
16329 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16331 (defvar org-def)
16332 (defvar org-defdecode)
16333 (defvar org-with-time)
16334 (defun org-read-date-display ()
16335 "Display the current date prompt interpretation in the minibuffer."
16336 (when org-read-date-display-live
16337 (when org-read-date-overlay
16338 (delete-overlay org-read-date-overlay))
16339 (when (minibufferp (current-buffer))
16340 (save-excursion
16341 (end-of-line 1)
16342 (while (not (equal (buffer-substring
16343 (max (point-min) (- (point) 4)) (point))
16344 " "))
16345 (insert " ")))
16346 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16347 " " (or org-ans1 org-ans2)))
16348 (org-end-time-was-given nil)
16349 (f (org-read-date-analyze ans org-def org-defdecode))
16350 (fmts (if org-dcst
16351 org-time-stamp-custom-formats
16352 org-time-stamp-formats))
16353 (fmt (if (or org-with-time
16354 (and (boundp 'org-time-was-given) org-time-was-given))
16355 (cdr fmts)
16356 (car fmts)))
16357 (txt (format-time-string fmt (apply 'encode-time f)))
16358 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16359 (txt (concat "=> " txt)))
16360 (when (and org-end-time-was-given
16361 (string-match org-plain-time-of-day-regexp txt))
16362 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16363 org-end-time-was-given
16364 (substring txt (match-end 0)))))
16365 (when org-read-date-analyze-futurep
16366 (setq txt (concat txt " (=>F)")))
16367 (setq org-read-date-overlay
16368 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16369 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16371 (defun org-read-date-analyze (ans org-def org-defdecode)
16372 "Analyze the combined answer of the date prompt."
16373 ;; FIXME: cleanup and comment
16374 (let ((nowdecode (decode-time (current-time)))
16375 delta deltan deltaw deltadef year month day
16376 hour minute second wday pm h2 m2 tl wday1
16377 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16378 (setq org-read-date-analyze-futurep nil
16379 org-read-date-analyze-forced-year nil)
16380 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16381 (setq ans "+0"))
16383 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16384 (setq ans (replace-match "" t t ans)
16385 deltan (car delta)
16386 deltaw (nth 1 delta)
16387 deltadef (nth 2 delta)))
16389 ;; Check if there is an iso week date in there. If yes, store the
16390 ;; info and postpone interpreting it until the rest of the parsing
16391 ;; is done.
16392 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16393 (setq iso-year (if (match-end 1)
16394 (org-small-year-to-year
16395 (string-to-number (match-string 1 ans))))
16396 iso-weekday (if (match-end 3)
16397 (string-to-number (match-string 3 ans)))
16398 iso-week (string-to-number (match-string 2 ans)))
16399 (setq ans (replace-match "" t t ans)))
16401 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16402 (when (string-match
16403 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16404 (setq year (if (match-end 2)
16405 (string-to-number (match-string 2 ans))
16406 (progn (setq kill-year t)
16407 (string-to-number (format-time-string "%Y"))))
16408 month (string-to-number (match-string 3 ans))
16409 day (string-to-number (match-string 4 ans)))
16410 (if (< year 100) (setq year (+ 2000 year)))
16411 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16412 t nil ans)))
16414 ;; Help matching dotted european dates
16415 (when (string-match
16416 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16417 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16418 (setq kill-year t)
16419 (string-to-number (format-time-string "%Y")))
16420 day (string-to-number (match-string 1 ans))
16421 month (string-to-number (match-string 2 ans))
16422 ans (replace-match (format "%04d-%02d-%02d" year month day)
16423 t nil ans)))
16425 ;; Help matching american dates, like 5/30 or 5/30/7
16426 (when (string-match
16427 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16428 (setq year (if (match-end 4)
16429 (string-to-number (match-string 4 ans))
16430 (progn (setq kill-year t)
16431 (string-to-number (format-time-string "%Y"))))
16432 month (string-to-number (match-string 1 ans))
16433 day (string-to-number (match-string 2 ans)))
16434 (if (< year 100) (setq year (+ 2000 year)))
16435 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16436 t nil ans)))
16437 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16438 ;; If there is a time with am/pm, and *no* time without it, we convert
16439 ;; so that matching will be successful.
16440 (loop for i from 1 to 2 do ; twice, for end time as well
16441 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16442 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16443 (setq hour (string-to-number (match-string 1 ans))
16444 minute (if (match-end 3)
16445 (string-to-number (match-string 3 ans))
16447 pm (equal ?p
16448 (string-to-char (downcase (match-string 4 ans)))))
16449 (if (and (= hour 12) (not pm))
16450 (setq hour 0)
16451 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16452 (setq ans (replace-match (format "%02d:%02d" hour minute)
16453 t t ans))))
16455 ;; Check if a time range is given as a duration
16456 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16457 (setq hour (string-to-number (match-string 1 ans))
16458 h2 (+ hour (string-to-number (match-string 3 ans)))
16459 minute (string-to-number (match-string 2 ans))
16460 m2 (+ minute (if (match-end 5) (string-to-number
16461 (match-string 5 ans))0)))
16462 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16463 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16464 t t ans)))
16466 ;; Check if there is a time range
16467 (when (boundp 'org-end-time-was-given)
16468 (setq org-time-was-given nil)
16469 (when (and (string-match org-plain-time-of-day-regexp ans)
16470 (match-end 8))
16471 (setq org-end-time-was-given (match-string 8 ans))
16472 (setq ans (concat (substring ans 0 (match-beginning 7))
16473 (substring ans (match-end 7))))))
16475 (setq tl (parse-time-string ans)
16476 day (or (nth 3 tl) (nth 3 org-defdecode))
16477 month (or (nth 4 tl)
16478 (if (and org-read-date-prefer-future
16479 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16480 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16481 (nth 4 org-defdecode)))
16482 year (or (and (not kill-year) (nth 5 tl))
16483 (if (and org-read-date-prefer-future
16484 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16485 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16486 (nth 5 org-defdecode)))
16487 hour (or (nth 2 tl) (nth 2 org-defdecode))
16488 minute (or (nth 1 tl) (nth 1 org-defdecode))
16489 second (or (nth 0 tl) 0)
16490 wday (nth 6 tl))
16492 (when (and (eq org-read-date-prefer-future 'time)
16493 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16494 (equal day (nth 3 nowdecode))
16495 (equal month (nth 4 nowdecode))
16496 (equal year (nth 5 nowdecode))
16497 (nth 2 tl)
16498 (or (< (nth 2 tl) (nth 2 nowdecode))
16499 (and (= (nth 2 tl) (nth 2 nowdecode))
16500 (nth 1 tl)
16501 (< (nth 1 tl) (nth 1 nowdecode)))))
16502 (setq day (1+ day)
16503 futurep t))
16505 ;; Special date definitions below
16506 (cond
16507 (iso-week
16508 ;; There was an iso week
16509 (require 'cal-iso)
16510 (setq futurep nil)
16511 (setq year (or iso-year year)
16512 day (or iso-weekday wday 1)
16513 wday nil ; to make sure that the trigger below does not match
16514 iso-date (calendar-gregorian-from-absolute
16515 (calendar-absolute-from-iso
16516 (list iso-week day year))))
16517 ; FIXME: Should we also push ISO weeks into the future?
16518 ; (when (and org-read-date-prefer-future
16519 ; (not iso-year)
16520 ; (< (calendar-absolute-from-gregorian iso-date)
16521 ; (time-to-days (current-time))))
16522 ; (setq year (1+ year)
16523 ; iso-date (calendar-gregorian-from-absolute
16524 ; (calendar-absolute-from-iso
16525 ; (list iso-week day year)))))
16526 (setq month (car iso-date)
16527 year (nth 2 iso-date)
16528 day (nth 1 iso-date)))
16529 (deltan
16530 (setq futurep nil)
16531 (unless deltadef
16532 (let ((now (decode-time (current-time))))
16533 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16534 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16535 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16536 ((equal deltaw "m") (setq month (+ month deltan)))
16537 ((equal deltaw "y") (setq year (+ year deltan)))))
16538 ((and wday (not (nth 3 tl)))
16539 ;; Weekday was given, but no day, so pick that day in the week
16540 ;; on or after the derived date.
16541 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16542 (unless (equal wday wday1)
16543 (setq day (+ day (% (- wday wday1 -7) 7))))))
16544 (if (and (boundp 'org-time-was-given)
16545 (nth 2 tl))
16546 (setq org-time-was-given t))
16547 (if (< year 100) (setq year (+ 2000 year)))
16548 ;; Check of the date is representable
16549 (if org-read-date-force-compatible-dates
16550 (progn
16551 (if (< year 1970)
16552 (setq year 1970 org-read-date-analyze-forced-year t))
16553 (if (> year 2037)
16554 (setq year 2037 org-read-date-analyze-forced-year t)))
16555 (condition-case nil
16556 (ignore (encode-time second minute hour day month year))
16557 (error
16558 (setq year (nth 5 org-defdecode))
16559 (setq org-read-date-analyze-forced-year t))))
16560 (setq org-read-date-analyze-futurep futurep)
16561 (list second minute hour day month year)))
16563 (defvar parse-time-weekdays)
16564 (defun org-read-date-get-relative (s today default)
16565 "Check string S for special relative date string.
16566 TODAY and DEFAULT are internal times, for today and for a default.
16567 Return shift list (N what def-flag)
16568 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16569 N is the number of WHATs to shift.
16570 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16571 the DEFAULT date rather than TODAY."
16572 (require 'parse-time)
16573 (when (and
16574 (string-match
16575 (concat
16576 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16577 "\\([0-9]+\\)?"
16578 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16579 "\\([ \t]\\|$\\)") s)
16580 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16581 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16582 (string-to-char (substring (match-string 1 s) -1))
16583 ?+))
16584 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16585 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16586 (what (if (match-end 3) (match-string 3 s) "d"))
16587 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16588 (date (if rel default today))
16589 (wday (nth 6 (decode-time date)))
16590 delta)
16591 (if wday1
16592 (progn
16593 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16594 (if (= delta 0) (setq delta 7))
16595 (if (= dir ?-)
16596 (progn
16597 (setq delta (- delta 7))
16598 (if (= delta 0) (setq delta -7))))
16599 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16600 (list delta "d" rel))
16601 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16603 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16604 "Turn a user-specified date into the internal representation.
16605 The internal representation needed by the calendar is (month day year).
16606 This is a wrapper to handle the brain-dead convention in calendar that
16607 user function argument order change dependent on argument order."
16608 (if (boundp 'calendar-date-style)
16609 (cond
16610 ((eq calendar-date-style 'american)
16611 (list arg1 arg2 arg3))
16612 ((eq calendar-date-style 'european)
16613 (list arg2 arg1 arg3))
16614 ((eq calendar-date-style 'iso)
16615 (list arg2 arg3 arg1)))
16616 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16617 (if (org-bound-and-true-p european-calendar-style)
16618 (list arg2 arg1 arg3)
16619 (list arg1 arg2 arg3)))))
16621 (defun org-eval-in-calendar (form &optional keepdate)
16622 "Eval FORM in the calendar window and return to current window.
16623 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16624 otherwise stick to the current value of `org-ans2'."
16625 (let ((sf (selected-frame))
16626 (sw (selected-window)))
16627 (select-window (get-buffer-window "*Calendar*" t))
16628 (eval form)
16629 (when (and (not keepdate) (calendar-cursor-to-date))
16630 (let* ((date (calendar-cursor-to-date))
16631 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16632 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16633 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16634 (select-window sw)
16635 (org-select-frame-set-input-focus sf)))
16637 (defun org-calendar-select ()
16638 "Return to `org-read-date' with the date currently selected.
16639 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16640 (interactive)
16641 (when (calendar-cursor-to-date)
16642 (let* ((date (calendar-cursor-to-date))
16643 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16644 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16645 (if (active-minibuffer-window) (exit-minibuffer))))
16647 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16648 "Insert a date stamp for the date given by the internal TIME.
16649 WITH-HM means use the stamp format that includes the time of the day.
16650 INACTIVE means use square brackets instead of angular ones, so that the
16651 stamp will not contribute to the agenda.
16652 PRE and POST are optional strings to be inserted before and after the
16653 stamp.
16654 The command returns the inserted time stamp."
16655 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16656 stamp)
16657 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16658 (insert-before-markers (or pre ""))
16659 (when (listp extra)
16660 (setq extra (car extra))
16661 (if (and (stringp extra)
16662 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16663 (setq extra (format "-%02d:%02d"
16664 (string-to-number (match-string 1 extra))
16665 (string-to-number (match-string 2 extra))))
16666 (setq extra nil)))
16667 (when extra
16668 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16669 (insert-before-markers (setq stamp (format-time-string fmt time)))
16670 (insert-before-markers (or post ""))
16671 (setq org-last-inserted-timestamp stamp)))
16673 (defun org-toggle-time-stamp-overlays ()
16674 "Toggle the use of custom time stamp formats."
16675 (interactive)
16676 (setq org-display-custom-times (not org-display-custom-times))
16677 (unless org-display-custom-times
16678 (let ((p (point-min)) (bmp (buffer-modified-p)))
16679 (while (setq p (next-single-property-change p 'display))
16680 (if (and (get-text-property p 'display)
16681 (eq (get-text-property p 'face) 'org-date))
16682 (remove-text-properties
16683 p (setq p (next-single-property-change p 'display))
16684 '(display t))))
16685 (set-buffer-modified-p bmp)))
16686 (if (featurep 'xemacs)
16687 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16688 (org-restart-font-lock)
16689 (setq org-table-may-need-update t)
16690 (if org-display-custom-times
16691 (message "Time stamps are overlaid with custom format")
16692 (message "Time stamp overlays removed")))
16694 (defun org-display-custom-time (beg end)
16695 "Overlay modified time stamp format over timestamp between BEG and END."
16696 (let* ((ts (buffer-substring beg end))
16697 t1 w1 with-hm tf time str w2 (off 0))
16698 (save-match-data
16699 (setq t1 (org-parse-time-string ts t))
16700 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16701 (setq off (- (match-end 0) (match-beginning 0)))))
16702 (setq end (- end off))
16703 (setq w1 (- end beg)
16704 with-hm (and (nth 1 t1) (nth 2 t1))
16705 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16706 time (org-fix-decoded-time t1)
16707 str (org-add-props
16708 (format-time-string
16709 (substring tf 1 -1) (apply 'encode-time time))
16710 nil 'mouse-face 'highlight)
16711 w2 (length str))
16712 (if (not (= w2 w1))
16713 (add-text-properties (1+ beg) (+ 2 beg)
16714 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16715 (if (featurep 'xemacs)
16716 (progn
16717 (put-text-property beg end 'invisible t)
16718 (put-text-property beg end 'end-glyph (make-glyph str)))
16719 (put-text-property beg end 'display str))))
16721 (defun org-translate-time (string)
16722 "Translate all timestamps in STRING to custom format.
16723 But do this only if the variable `org-display-custom-times' is set."
16724 (when org-display-custom-times
16725 (save-match-data
16726 (let* ((start 0)
16727 (re org-ts-regexp-both)
16728 t1 with-hm inactive tf time str beg end)
16729 (while (setq start (string-match re string start))
16730 (setq beg (match-beginning 0)
16731 end (match-end 0)
16732 t1 (save-match-data
16733 (org-parse-time-string (substring string beg end) t))
16734 with-hm (and (nth 1 t1) (nth 2 t1))
16735 inactive (equal (substring string beg (1+ beg)) "[")
16736 tf (funcall (if with-hm 'cdr 'car)
16737 org-time-stamp-custom-formats)
16738 time (org-fix-decoded-time t1)
16739 str (format-time-string
16740 (concat
16741 (if inactive "[" "<") (substring tf 1 -1)
16742 (if inactive "]" ">"))
16743 (apply 'encode-time time))
16744 string (replace-match str t t string)
16745 start (+ start (length str)))))))
16746 string)
16748 (defun org-fix-decoded-time (time)
16749 "Set 0 instead of nil for the first 6 elements of time.
16750 Don't touch the rest."
16751 (let ((n 0))
16752 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16754 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16756 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16757 "Difference between TIMESTAMP-STRING and now in days.
16758 If SECONDS is non-nil, return the difference in seconds."
16759 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16760 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16761 (funcall fdiff (current-time)))))
16763 (defun org-deadline-close (timestamp-string &optional ndays)
16764 "Is the time in TIMESTAMP-STRING close to the current date?"
16765 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16766 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16767 (not (org-entry-is-done-p))))
16769 (defun org-get-wdays (ts &optional delay zero-delay)
16770 "Get the deadline lead time appropriate for timestring TS.
16771 When DELAY is non-nil, get the delay time for scheduled items
16772 instead of the deadline lead time. When ZERO-DELAY is non-nil
16773 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16774 don't try to find the delay cookie in the scheduled timestamp."
16775 (let ((tv (if delay org-scheduled-delay-days
16776 org-deadline-warning-days)))
16777 (cond
16778 ((or (and delay (< tv 0))
16779 (and delay zero-delay (<= tv 0))
16780 (and (not delay) (<= tv 0)))
16781 ;; Enforce this value no matter what
16782 (- tv))
16783 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16784 ;; lead time is specified.
16785 (floor (* (string-to-number (match-string 1 ts))
16786 (cdr (assoc (match-string 2 ts)
16787 '(("d" . 1) ("w" . 7)
16788 ("m" . 30.4) ("y" . 365.25)
16789 ("h" . 0.041667)))))))
16790 ;; go for the default.
16791 (t tv))))
16793 (defun org-calendar-select-mouse (ev)
16794 "Return to `org-read-date' with the date currently selected.
16795 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16796 (interactive "e")
16797 (mouse-set-point ev)
16798 (when (calendar-cursor-to-date)
16799 (let* ((date (calendar-cursor-to-date))
16800 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16801 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16802 (if (active-minibuffer-window) (exit-minibuffer))))
16804 (defun org-check-deadlines (ndays)
16805 "Check if there are any deadlines due or past due.
16806 A deadline is considered due if it happens within `org-deadline-warning-days'
16807 days from today's date. If the deadline appears in an entry marked DONE,
16808 it is not shown. The prefix arg NDAYS can be used to test that many
16809 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16810 (interactive "P")
16811 (let* ((org-warn-days
16812 (cond
16813 ((equal ndays '(4)) 100000)
16814 (ndays (prefix-numeric-value ndays))
16815 (t (abs org-deadline-warning-days))))
16816 (case-fold-search nil)
16817 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16818 (callback
16819 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16821 (message "%d deadlines past-due or due within %d days"
16822 (org-occur regexp nil callback)
16823 org-warn-days)))
16825 (defsubst org-re-timestamp (type)
16826 "Return a regexp for timestamp TYPE.
16827 Allowed values for TYPE are:
16829 all: all timestamps
16830 active: only active timestamps (<...>)
16831 inactive: only inactive timestamps ([...])
16832 scheduled: only scheduled timestamps
16833 deadline: only deadline timestamps
16834 closed: only closed time-stamps
16836 When TYPE is nil, fall back on returning a regexp that matches
16837 both scheduled and deadline timestamps."
16838 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16839 ((eq type 'active) org-ts-regexp)
16840 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16841 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16842 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16843 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16844 ((eq type 'scheduled-or-deadline)
16845 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16847 (defun org-check-before-date (date)
16848 "Check if there are deadlines or scheduled entries before DATE."
16849 (interactive (list (org-read-date)))
16850 (let ((case-fold-search nil)
16851 (regexp (org-re-timestamp org-ts-type))
16852 (callback
16853 (lambda () (time-less-p
16854 (org-time-string-to-time (match-string 1))
16855 (org-time-string-to-time date)))))
16856 (message "%d entries before %s"
16857 (org-occur regexp nil callback) date)))
16859 (defun org-check-after-date (date)
16860 "Check if there are deadlines or scheduled entries after DATE."
16861 (interactive (list (org-read-date)))
16862 (let ((case-fold-search nil)
16863 (regexp (org-re-timestamp org-ts-type))
16864 (callback
16865 (lambda () (not
16866 (time-less-p
16867 (org-time-string-to-time (match-string 1))
16868 (org-time-string-to-time date))))))
16869 (message "%d entries after %s"
16870 (org-occur regexp nil callback) date)))
16872 (defun org-check-dates-range (start-date end-date)
16873 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16874 (interactive (list (org-read-date nil nil nil "Range starts")
16875 (org-read-date nil nil nil "Range end")))
16876 (let ((case-fold-search nil)
16877 (regexp (org-re-timestamp org-ts-type))
16878 (callback
16879 (lambda ()
16880 (let ((match (match-string 1)))
16881 (and
16882 (not (time-less-p
16883 (org-time-string-to-time match)
16884 (org-time-string-to-time start-date)))
16885 (time-less-p
16886 (org-time-string-to-time match)
16887 (org-time-string-to-time end-date)))))))
16888 (message "%d entries between %s and %s"
16889 (org-occur regexp nil callback) start-date end-date)))
16891 (defun org-evaluate-time-range (&optional to-buffer)
16892 "Evaluate a time range by computing the difference between start and end.
16893 Normally the result is just printed in the echo area, but with prefix arg
16894 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16895 If the time range is actually in a table, the result is inserted into the
16896 next column.
16897 For time difference computation, a year is assumed to be exactly 365
16898 days in order to avoid rounding problems."
16899 (interactive "P")
16901 (org-clock-update-time-maybe)
16902 (save-excursion
16903 (unless (org-at-date-range-p t)
16904 (goto-char (point-at-bol))
16905 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16906 (if (not (org-at-date-range-p t))
16907 (user-error "Not at a time-stamp range, and none found in current line")))
16908 (let* ((ts1 (match-string 1))
16909 (ts2 (match-string 2))
16910 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16911 (match-end (match-end 0))
16912 (time1 (org-time-string-to-time ts1))
16913 (time2 (org-time-string-to-time ts2))
16914 (t1 (org-float-time time1))
16915 (t2 (org-float-time time2))
16916 (diff (abs (- t2 t1)))
16917 (negative (< (- t2 t1) 0))
16918 ;; (ys (floor (* 365 24 60 60)))
16919 (ds (* 24 60 60))
16920 (hs (* 60 60))
16921 (fy "%dy %dd %02d:%02d")
16922 (fy1 "%dy %dd")
16923 (fd "%dd %02d:%02d")
16924 (fd1 "%dd")
16925 (fh "%02d:%02d")
16926 y d h m align)
16927 (if havetime
16928 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16930 d (floor (/ diff ds)) diff (mod diff ds)
16931 h (floor (/ diff hs)) diff (mod diff hs)
16932 m (floor (/ diff 60)))
16933 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16935 d (floor (+ (/ diff ds) 0.5))
16936 h 0 m 0))
16937 (if (not to-buffer)
16938 (message "%s" (org-make-tdiff-string y d h m))
16939 (if (org-at-table-p)
16940 (progn
16941 (goto-char match-end)
16942 (setq align t)
16943 (and (looking-at " *|") (goto-char (match-end 0))))
16944 (goto-char match-end))
16945 (if (looking-at
16946 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16947 (replace-match ""))
16948 (if negative (insert " -"))
16949 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16950 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16951 (insert " " (format fh h m))))
16952 (if align (org-table-align))
16953 (message "Time difference inserted")))))
16955 (defun org-make-tdiff-string (y d h m)
16956 (let ((fmt "")
16957 (l nil))
16958 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16959 l (push y l)))
16960 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16961 l (push d l)))
16962 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16963 l (push h l)))
16964 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16965 l (push m l)))
16966 (apply 'format fmt (nreverse l))))
16968 (defun org-time-string-to-time (s &optional buffer pos)
16969 "Convert a timestamp string into internal time."
16970 (condition-case errdata
16971 (apply 'encode-time (org-parse-time-string s))
16972 (error (error "Bad timestamp `%s'%s\nError was: %s"
16973 s (if (not (and buffer pos))
16975 (format " at %d in buffer `%s'" pos buffer))
16976 (cdr errdata)))))
16978 (defun org-time-string-to-seconds (s)
16979 "Convert a timestamp string to a number of seconds."
16980 (org-float-time (org-time-string-to-time s)))
16982 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16983 "Convert a time stamp to an absolute day number.
16984 If there is a specifier for a cyclic time stamp, get the closest
16985 date to DAYNR.
16986 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16987 The variable `date' is bound by the calendar when this is called."
16988 (cond
16989 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16990 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16991 daynr
16992 (+ daynr 1000)))
16993 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16994 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16995 (time-to-days (current-time))) (match-string 0 s)
16996 prefer show-all))
16997 (t (time-to-days
16998 (condition-case errdata
16999 (apply 'encode-time (org-parse-time-string s))
17000 (error (error "Bad timestamp `%s'%s\nError was: %s"
17001 s (if (not (and buffer pos))
17003 (format " at %d in buffer `%s'" pos buffer))
17004 (cdr errdata))))))))
17006 (defun org-days-to-iso-week (days)
17007 "Return the iso week number."
17008 (require 'cal-iso)
17009 (car (calendar-iso-from-absolute days)))
17011 (defun org-small-year-to-year (year)
17012 "Convert 2-digit years into 4-digit years.
17013 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17014 The year 2000 cannot be abbreviated. Any year larger than 99
17015 is returned unchanged."
17016 (if (< year 38)
17017 (setq year (+ 2000 year))
17018 (if (< year 100)
17019 (setq year (+ 1900 year))))
17020 year)
17022 (defun org-time-from-absolute (d)
17023 "Return the time corresponding to date D.
17024 D may be an absolute day number, or a calendar-type list (month day year)."
17025 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17026 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17028 (defun org-calendar-holiday ()
17029 "List of holidays, for Diary display in Org-mode."
17030 (require 'holidays)
17031 (let ((hl (funcall
17032 (if (fboundp 'calendar-check-holidays)
17033 'calendar-check-holidays 'check-calendar-holidays) date)))
17034 (if hl (mapconcat 'identity hl "; "))))
17036 (defun org-diary-sexp-entry (sexp entry date)
17037 "Process a SEXP diary ENTRY for DATE."
17038 (require 'diary-lib)
17039 (let ((result (if calendar-debug-sexp
17040 (let ((stack-trace-on-error t))
17041 (eval (car (read-from-string sexp))))
17042 (condition-case nil
17043 (eval (car (read-from-string sexp)))
17044 (error
17045 (beep)
17046 (message "Bad sexp at line %d in %s: %s"
17047 (org-current-line)
17048 (buffer-file-name) sexp)
17049 (sleep-for 2))))))
17050 (cond ((stringp result) (split-string result "; "))
17051 ((and (consp result)
17052 (not (consp (cdr result)))
17053 (stringp (cdr result))) (cdr result))
17054 ((and (consp result)
17055 (stringp (car result))) result)
17056 (result entry))))
17058 (defun org-diary-to-ical-string (frombuf)
17059 "Get iCalendar entries from diary entries in buffer FROMBUF.
17060 This uses the icalendar.el library."
17061 (let* ((tmpdir (if (featurep 'xemacs)
17062 (temp-directory)
17063 temporary-file-directory))
17064 (tmpfile (make-temp-name
17065 (expand-file-name "orgics" tmpdir)))
17066 buf rtn b e)
17067 (with-current-buffer frombuf
17068 (icalendar-export-region (point-min) (point-max) tmpfile)
17069 (setq buf (find-buffer-visiting tmpfile))
17070 (set-buffer buf)
17071 (goto-char (point-min))
17072 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17073 (setq b (match-beginning 0)))
17074 (goto-char (point-max))
17075 (if (re-search-backward "^END:VEVENT" nil t)
17076 (setq e (match-end 0)))
17077 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17078 (kill-buffer buf)
17079 (delete-file tmpfile)
17080 rtn))
17082 (defun org-closest-date (start current change prefer show-all)
17083 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17084 When PREFER is `past', return a date that is either CURRENT or past.
17085 When PREFER is `future', return a date that is either CURRENT or future.
17086 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17087 ;; Make the proper lists from the dates
17088 (catch 'exit
17089 (let ((a1 '(("h" . hour)
17090 ("d" . day)
17091 ("w" . week)
17092 ("m" . month)
17093 ("y" . year)))
17094 (shour (nth 2 (org-parse-time-string start)))
17095 dn dw sday cday n1 n2 n0
17096 d m y y1 y2 date1 date2 nmonths nm ny m2)
17098 (setq start (org-date-to-gregorian start)
17099 current (org-date-to-gregorian
17100 (if show-all
17101 current
17102 (time-to-days (current-time))))
17103 sday (calendar-absolute-from-gregorian start)
17104 cday (calendar-absolute-from-gregorian current))
17106 (if (<= cday sday) (throw 'exit sday))
17108 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17109 (setq dn (string-to-number (match-string 1 change))
17110 dw (cdr (assoc (match-string 2 change) a1)))
17111 (user-error "Invalid change specifier: %s" change))
17112 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17113 (cond
17114 ((eq dw 'hour)
17115 (let ((missing-hours
17116 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17117 dn)))
17118 (setq n1 (if (zerop missing-hours) cday
17119 (- cday (1+ (floor (/ missing-hours 24)))))
17120 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17121 ((eq dw 'day)
17122 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17123 n2 (+ n1 dn)))
17124 ((eq dw 'year)
17125 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17126 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17127 (setq date1 (list m d y1)
17128 n1 (calendar-absolute-from-gregorian date1)
17129 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17130 n2 (calendar-absolute-from-gregorian date2)))
17131 ((eq dw 'month)
17132 ;; approx number of month between the two dates
17133 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17134 ;; How often does dn fit in there?
17135 (setq d (nth 1 start) m (car start) y (nth 2 start)
17136 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17137 m (+ m nm)
17138 ny (floor (/ m 12))
17139 y (+ y ny)
17140 m (- m (* ny 12)))
17141 (while (> m 12) (setq m (- m 12) y (1+ y)))
17142 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17143 (setq m2 (+ m dn) y2 y)
17144 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17145 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17146 (while (<= n2 cday)
17147 (setq n1 n2 m m2 y y2)
17148 (setq m2 (+ m dn) y2 y)
17149 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17150 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17151 ;; Make sure n1 is the earlier date
17152 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17153 (if show-all
17154 (cond
17155 ((eq prefer 'past) (if (= cday n2) n2 n1))
17156 ((eq prefer 'future) (if (= cday n1) n1 n2))
17157 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17158 (cond
17159 ((eq prefer 'past) (if (= cday n2) n2 n1))
17160 ((eq prefer 'future) (if (= cday n1) n1 n2))
17161 (t (if (= cday n1) n1 n2)))))))
17163 (defun org-date-to-gregorian (date)
17164 "Turn any specification of DATE into a Gregorian date for the calendar."
17165 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17166 ((and (listp date) (= (length date) 3)) date)
17167 ((stringp date)
17168 (setq date (org-parse-time-string date))
17169 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17170 ((listp date)
17171 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17173 (defun org-parse-time-string (s &optional nodefault)
17174 "Parse the standard Org-mode time string.
17175 This should be a lot faster than the normal `parse-time-string'.
17176 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17177 hour and minute fields will be nil if not given."
17178 (cond ((string-match org-ts-regexp0 s)
17179 (list 0
17180 (if (or (match-beginning 8) (not nodefault))
17181 (string-to-number (or (match-string 8 s) "0")))
17182 (if (or (match-beginning 7) (not nodefault))
17183 (string-to-number (or (match-string 7 s) "0")))
17184 (string-to-number (match-string 4 s))
17185 (string-to-number (match-string 3 s))
17186 (string-to-number (match-string 2 s))
17187 nil nil nil))
17188 ((string-match "^<[^>]+>$" s)
17189 (decode-time (seconds-to-time (org-matcher-time s))))
17190 (t (error "Not a standard Org-mode time string: %s" s))))
17192 (defun org-timestamp-up (&optional arg)
17193 "Increase the date item at the cursor by one.
17194 If the cursor is on the year, change the year. If it is on the month,
17195 the day or the time, change that.
17196 With prefix ARG, change by that many units."
17197 (interactive "p")
17198 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17200 (defun org-timestamp-down (&optional arg)
17201 "Decrease the date item at the cursor by one.
17202 If the cursor is on the year, change the year. If it is on the month,
17203 the day or the time, change that.
17204 With prefix ARG, change by that many units."
17205 (interactive "p")
17206 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17208 (defun org-timestamp-up-day (&optional arg)
17209 "Increase the date in the time stamp by one day.
17210 With prefix ARG, change that many days."
17211 (interactive "p")
17212 (if (and (not (org-at-timestamp-p t))
17213 (org-at-heading-p))
17214 (org-todo 'up)
17215 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17217 (defun org-timestamp-down-day (&optional arg)
17218 "Decrease the date in the time stamp by one day.
17219 With prefix ARG, change that many days."
17220 (interactive "p")
17221 (if (and (not (org-at-timestamp-p t))
17222 (org-at-heading-p))
17223 (org-todo 'down)
17224 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17226 (defun org-at-timestamp-p (&optional inactive-ok)
17227 "Determine if the cursor is in or at a timestamp."
17228 (interactive)
17229 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17230 (pos (point))
17231 (ans (or (looking-at tsr)
17232 (save-excursion
17233 (skip-chars-backward "^[<\n\r\t")
17234 (if (> (point) (point-min)) (backward-char 1))
17235 (and (looking-at tsr)
17236 (> (- (match-end 0) pos) -1))))))
17237 (and ans
17238 (boundp 'org-ts-what)
17239 (setq org-ts-what
17240 (cond
17241 ((= pos (match-beginning 0)) 'bracket)
17242 ;; Point is considered to be "on the bracket" whether
17243 ;; it's really on it or right after it.
17244 ((= pos (1- (match-end 0))) 'bracket)
17245 ((= pos (match-end 0)) 'after)
17246 ((org-pos-in-match-range pos 2) 'year)
17247 ((org-pos-in-match-range pos 3) 'month)
17248 ((org-pos-in-match-range pos 7) 'hour)
17249 ((org-pos-in-match-range pos 8) 'minute)
17250 ((or (org-pos-in-match-range pos 4)
17251 (org-pos-in-match-range pos 5)) 'day)
17252 ((and (> pos (or (match-end 8) (match-end 5)))
17253 (< pos (match-end 0)))
17254 (- pos (or (match-end 8) (match-end 5))))
17255 (t 'day))))
17256 ans))
17258 (defun org-toggle-timestamp-type ()
17259 "Toggle the type (<active> or [inactive]) of a time stamp."
17260 (interactive)
17261 (when (org-at-timestamp-p t)
17262 (let ((beg (match-beginning 0)) (end (match-end 0))
17263 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17264 (save-excursion
17265 (goto-char beg)
17266 (while (re-search-forward "[][<>]" end t)
17267 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17268 t t)))
17269 (message "Timestamp is now %sactive"
17270 (if (equal (char-after beg) ?<) "" "in")))))
17272 (defun org-at-clock-log-p nil
17273 "Is the cursor on the clock log line?"
17274 (save-excursion
17275 (move-beginning-of-line 1)
17276 (looking-at "^[ \t]*CLOCK:")))
17278 (defvar org-clock-history) ; defined in org-clock.el
17279 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17280 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17281 "Change the date in the time stamp at point.
17282 The date will be changed by N times WHAT. WHAT can be `day', `month',
17283 `year', `minute', `second'. If WHAT is not given, the cursor position
17284 in the timestamp determines what will be changed.
17285 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17286 (let ((origin (point)) origin-cat
17287 with-hm inactive
17288 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17289 org-ts-what
17290 extra rem
17291 ts time time0 fixnext clrgx)
17292 (if (not (org-at-timestamp-p t))
17293 (user-error "Not at a timestamp"))
17294 (if (and (not what) (eq org-ts-what 'bracket))
17295 (org-toggle-timestamp-type)
17296 ;; Point isn't on brackets. Remember the part of the time-stamp
17297 ;; the point was in. Indeed, size of time-stamps may change,
17298 ;; but point must be kept in the same category nonetheless.
17299 (setq origin-cat org-ts-what)
17300 (if (and (not what) (not (eq org-ts-what 'day))
17301 org-display-custom-times
17302 (get-text-property (point) 'display)
17303 (not (get-text-property (1- (point)) 'display)))
17304 (setq org-ts-what 'day))
17305 (setq org-ts-what (or what org-ts-what)
17306 inactive (= (char-after (match-beginning 0)) ?\[)
17307 ts (match-string 0))
17308 (replace-match "")
17309 (when (string-match
17310 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17312 (setq extra (match-string 1 ts))
17313 (if suppress-tmp-delay
17314 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17315 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17316 (setq with-hm t))
17317 (setq time0 (org-parse-time-string ts))
17318 (when (and updown
17319 (eq org-ts-what 'minute)
17320 (not current-prefix-arg))
17321 ;; This looks like s-up and s-down. Change by one rounding step.
17322 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17323 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17324 (setcar (cdr time0) (+ (nth 1 time0)
17325 (if (> n 0) (- rem) (- dm rem))))))
17326 (setq time
17327 (encode-time (or (car time0) 0)
17328 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17329 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17330 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17331 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17332 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17333 (nthcdr 6 time0)))
17334 (when (and (member org-ts-what '(hour minute))
17335 extra
17336 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17337 (setq extra (org-modify-ts-extra
17338 extra
17339 (if (eq org-ts-what 'hour) 2 5)
17340 n dm)))
17341 (when (integerp org-ts-what)
17342 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17343 (if (eq what 'calendar)
17344 (let ((cal-date (org-get-date-from-calendar)))
17345 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17346 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17347 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17348 (setcar time0 (or (car time0) 0))
17349 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17350 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17351 (setq time (apply 'encode-time time0))))
17352 ;; Insert the new time-stamp, and ensure point stays in the same
17353 ;; category as before (i.e. not after the last position in that
17354 ;; category).
17355 (let ((pos (point)))
17356 ;; Stay before inserted string. `save-excursion' is of no use.
17357 (setq org-last-changed-timestamp
17358 (org-insert-time-stamp time with-hm inactive nil nil extra))
17359 (goto-char pos))
17360 (save-match-data
17361 (looking-at org-ts-regexp3)
17362 (goto-char (cond
17363 ;; `day' category ends before `hour' if any, or at
17364 ;; the end of the day name.
17365 ((eq origin-cat 'day)
17366 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17367 ((eq origin-cat 'hour) (min (match-end 7) origin))
17368 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17369 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17370 ;; `year' and `month' have both fixed size: point
17371 ;; couldn't have moved into another part.
17372 (t origin))))
17373 ;; Update clock if on a CLOCK line.
17374 (org-clock-update-time-maybe)
17375 ;; Maybe adjust the closest clock in `org-clock-history'
17376 (when org-clock-adjust-closest
17377 (if (not (and (org-at-clock-log-p)
17378 (< 1 (length (delq nil (mapcar 'marker-position
17379 org-clock-history))))))
17380 (message "No clock to adjust")
17381 (cond ((save-excursion ; fix previous clock?
17382 (re-search-backward org-ts-regexp0 nil t)
17383 (org-looking-back (concat org-clock-string " \\[")))
17384 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17385 ((save-excursion ; fix next clock?
17386 (re-search-backward org-ts-regexp0 nil t)
17387 (looking-at (concat org-ts-regexp0 "\\] =>")))
17388 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17389 (save-window-excursion
17390 ;; Find closest clock to point, adjust the previous/next one in history
17391 (let* ((p (save-excursion (org-back-to-heading t)))
17392 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17393 (clfixnth
17394 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17395 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17396 (if (not clfixpos)
17397 (message "No clock to adjust")
17398 (save-excursion
17399 (org-goto-marker-or-bmk clfixpos)
17400 (org-show-subtree)
17401 (when (re-search-forward clrgx nil t)
17402 (goto-char (match-beginning 1))
17403 (let (org-clock-adjust-closest)
17404 (org-timestamp-change n org-ts-what updown))
17405 (message "Clock adjusted in %s for heading: %s"
17406 (file-name-nondirectory (buffer-file-name))
17407 (org-get-heading t t)))))))))
17408 ;; Try to recenter the calendar window, if any.
17409 (if (and org-calendar-follow-timestamp-change
17410 (get-buffer-window "*Calendar*" t)
17411 (memq org-ts-what '(day month year)))
17412 (org-recenter-calendar (time-to-days time))))))
17414 (defun org-modify-ts-extra (s pos n dm)
17415 "Change the different parts of the lead-time and repeat fields in timestamp."
17416 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17417 ng h m new rem)
17418 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17419 (cond
17420 ((or (org-pos-in-match-range pos 2)
17421 (org-pos-in-match-range pos 3))
17422 (setq m (string-to-number (match-string 3 s))
17423 h (string-to-number (match-string 2 s)))
17424 (if (org-pos-in-match-range pos 2)
17425 (setq h (+ h n))
17426 (setq n (* dm (org-no-warnings (signum n))))
17427 (when (not (= 0 (setq rem (% m dm))))
17428 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17429 (setq m (+ m n)))
17430 (if (< m 0) (setq m (+ m 60) h (1- h)))
17431 (if (> m 59) (setq m (- m 60) h (1+ h)))
17432 (setq h (min 24 (max 0 h)))
17433 (setq ng 1 new (format "-%02d:%02d" h m)))
17434 ((org-pos-in-match-range pos 6)
17435 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17436 ((org-pos-in-match-range pos 5)
17437 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17439 ((org-pos-in-match-range pos 9)
17440 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17441 ((org-pos-in-match-range pos 8)
17442 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17444 (when ng
17445 (setq s (concat
17446 (substring s 0 (match-beginning ng))
17448 (substring s (match-end ng))))))
17451 (defun org-recenter-calendar (date)
17452 "If the calendar is visible, recenter it to DATE."
17453 (let ((cwin (get-buffer-window "*Calendar*" t)))
17454 (when cwin
17455 (let ((calendar-move-hook nil))
17456 (with-selected-window cwin
17457 (calendar-goto-date (if (listp date) date
17458 (calendar-gregorian-from-absolute date))))))))
17460 (defun org-goto-calendar (&optional arg)
17461 "Go to the Emacs calendar at the current date.
17462 If there is a time stamp in the current line, go to that date.
17463 A prefix ARG can be used to force the current date."
17464 (interactive "P")
17465 (let ((tsr org-ts-regexp) diff
17466 (calendar-move-hook nil)
17467 (calendar-view-holidays-initially-flag nil)
17468 (calendar-view-diary-initially-flag nil))
17469 (if (or (org-at-timestamp-p)
17470 (save-excursion
17471 (beginning-of-line 1)
17472 (looking-at (concat ".*" tsr))))
17473 (let ((d1 (time-to-days (current-time)))
17474 (d2 (time-to-days
17475 (org-time-string-to-time (match-string 1)))))
17476 (setq diff (- d2 d1))))
17477 (calendar)
17478 (calendar-goto-today)
17479 (if (and diff (not arg)) (calendar-forward-day diff))))
17481 (defun org-get-date-from-calendar ()
17482 "Return a list (month day year) of date at point in calendar."
17483 (with-current-buffer "*Calendar*"
17484 (save-match-data
17485 (calendar-cursor-to-date))))
17487 (defun org-date-from-calendar ()
17488 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17489 If there is already a time stamp at the cursor position, update it."
17490 (interactive)
17491 (if (org-at-timestamp-p t)
17492 (org-timestamp-change 0 'calendar)
17493 (let ((cal-date (org-get-date-from-calendar)))
17494 (org-insert-time-stamp
17495 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17497 (defcustom org-effort-durations
17498 `(("h" . 60)
17499 ("d" . ,(* 60 8))
17500 ("w" . ,(* 60 8 5))
17501 ("m" . ,(* 60 8 5 4))
17502 ("y" . ,(* 60 8 5 40)))
17503 "Conversion factor to minutes for an effort modifier.
17505 Each entry has the form (MODIFIER . MINUTES).
17507 In an effort string, a number followed by MODIFIER is multiplied
17508 by the specified number of MINUTES to obtain an effort in
17509 minutes.
17511 For example, if the value of this variable is ((\"hours\" . 60)), then an
17512 effort string \"2hours\" is equivalent to 120 minutes."
17513 :group 'org-agenda
17514 :version "24.1"
17515 :type '(alist :key-type (string :tag "Modifier")
17516 :value-type (number :tag "Minutes")))
17518 (defun org-minutes-to-clocksum-string (m)
17519 "Format number of minutes as a clocksum string.
17520 The format is determined by `org-time-clocksum-format',
17521 `org-time-clocksum-use-fractional' and
17522 `org-time-clocksum-fractional-format' and
17523 `org-time-clocksum-use-effort-durations'."
17524 (let ((clocksum "")
17525 (m (round m)) ; Don't allow fractions of minutes
17526 h d w mo y fmt n)
17527 (setq h (if org-time-clocksum-use-effort-durations
17528 (cdr (assoc "h" org-effort-durations)) 60)
17529 d (if org-time-clocksum-use-effort-durations
17530 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17531 w (if org-time-clocksum-use-effort-durations
17532 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17533 mo (if org-time-clocksum-use-effort-durations
17534 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17535 y (if org-time-clocksum-use-effort-durations
17536 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17537 ;; fractional format
17538 (if org-time-clocksum-use-fractional
17539 (cond
17540 ;; single format string
17541 ((stringp org-time-clocksum-fractional-format)
17542 (format org-time-clocksum-fractional-format (/ m (float h))))
17543 ;; choice of fractional formats for different time units
17544 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17545 (> (/ (truncate m) (* y d h)) 0))
17546 (format fmt (/ m (* y d (float h)))))
17547 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17548 (> (/ (truncate m) (* mo d h)) 0))
17549 (format fmt (/ m (* mo d (float h)))))
17550 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17551 (> (/ (truncate m) (* w d h)) 0))
17552 (format fmt (/ m (* w d (float h)))))
17553 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17554 (> (/ (truncate m) (* d h)) 0))
17555 (format fmt (/ m (* d (float h)))))
17556 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17557 (> (/ (truncate m) h) 0))
17558 (format fmt (/ m (float h))))
17559 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17560 (format fmt m))
17561 ;; fall back to smallest time unit with a format
17562 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17563 (format fmt (/ m (float h))))
17564 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17565 (format fmt (/ m (* d (float h)))))
17566 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17567 (format fmt (/ m (* w d (float h)))))
17568 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17569 (format fmt (/ m (* mo d (float h)))))
17570 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17571 (format fmt (/ m (* y d (float h))))))
17572 ;; standard (non-fractional) format, with single format string
17573 (if (stringp org-time-clocksum-format)
17574 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17575 ;; separate formats components
17576 (and (setq fmt (plist-get org-time-clocksum-format :years))
17577 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17578 (plist-get org-time-clocksum-format :require-years))
17579 (setq clocksum (concat clocksum (format fmt n))
17580 m (- m (* n y d h))))
17581 (and (setq fmt (plist-get org-time-clocksum-format :months))
17582 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17583 (plist-get org-time-clocksum-format :require-months))
17584 (setq clocksum (concat clocksum (format fmt n))
17585 m (- m (* n mo d h))))
17586 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17587 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17588 (plist-get org-time-clocksum-format :require-weeks))
17589 (setq clocksum (concat clocksum (format fmt n))
17590 m (- m (* n w d h))))
17591 (and (setq fmt (plist-get org-time-clocksum-format :days))
17592 (or (> (setq n (/ (truncate m) (* d h))) 0)
17593 (plist-get org-time-clocksum-format :require-days))
17594 (setq clocksum (concat clocksum (format fmt n))
17595 m (- m (* n d h))))
17596 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17597 (or (> (setq n (/ (truncate m) h)) 0)
17598 (plist-get org-time-clocksum-format :require-hours))
17599 (setq clocksum (concat clocksum (format fmt n))
17600 m (- m (* n h))))
17601 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17602 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17603 (setq clocksum (concat clocksum (format fmt m))))
17604 ;; return formatted time duration
17605 clocksum))))
17607 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17608 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17609 "Org mode version 8.0")
17611 (defun org-hours-to-clocksum-string (n)
17612 (org-minutes-to-clocksum-string (* n 60)))
17614 (defun org-hh:mm-string-to-minutes (s)
17615 "Convert a string H:MM to a number of minutes.
17616 If the string is just a number, interpret it as minutes.
17617 In fact, the first hh:mm or number in the string will be taken,
17618 there can be extra stuff in the string.
17619 If no number is found, the return value is 0."
17620 (cond
17621 ((integerp s) s)
17622 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17623 (+ (* (string-to-number (match-string 1 s)) 60)
17624 (string-to-number (match-string 2 s))))
17625 ((string-match "\\([0-9]+\\)" s)
17626 (string-to-number (match-string 1 s)))
17627 (t 0)))
17629 (defcustom org-image-actual-width t
17630 "Should we use the actual width of images when inlining them?
17632 When set to `t', always use the image width.
17634 When set to a number, use imagemagick (when available) to set
17635 the image's width to this value.
17637 When set to a number in a list, try to get the width from any
17638 #+ATTR.* keyword if it matches a width specification like
17640 #+ATTR_HTML: :width 300px
17642 and fall back on that number if none is found.
17644 When set to nil, try to get the width from an #+ATTR.* keyword
17645 and fall back on the original width if none is found.
17647 This requires Emacs >= 24.1, build with imagemagick support."
17648 :group 'org-appearance
17649 :version "24.4"
17650 :package-version '(Org . "8.0")
17651 :type '(choice
17652 (const :tag "Use the image width" t)
17653 (integer :tag "Use a number of pixels")
17654 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17655 (const :tag "Use #+ATTR* or don't resize" nil)))
17657 (defcustom org-agenda-inhibit-startup nil
17658 "Inhibit startup when preparing agenda buffers.
17659 When this variable is `t' (the default), the initialization of
17660 the Org agenda buffers is inhibited: e.g. the visibility state
17661 is not set, the tables are not re-aligned, etc."
17662 :type 'boolean
17663 :version "24.3"
17664 :group 'org-agenda)
17666 (defcustom org-agenda-ignore-drawer-properties nil
17667 "Avoid updating text properties when building the agenda.
17668 Properties are used to prepare buffers for effort estimates, appointments,
17669 and subtree-local categories.
17670 If you don't use these in the agenda, you can add them to this list and
17671 agenda building will be a bit faster.
17672 The value is a list, with zero or more of the symbols `effort', `appt',
17673 or `category'."
17674 :type '(set :greedy t
17675 (const effort)
17676 (const appt)
17677 (const category))
17678 :version "24.3"
17679 :group 'org-agenda)
17681 (defun org-duration-string-to-minutes (s &optional output-to-string)
17682 "Convert a duration string S to minutes.
17684 A bare number is interpreted as minutes, modifiers can be set by
17685 customizing `org-effort-durations' (which see).
17687 Entries containing a colon are interpreted as H:MM by
17688 `org-hh:mm-string-to-minutes'."
17689 (let ((result 0)
17690 (re (concat "\\([0-9.]+\\) *\\("
17691 (regexp-opt (mapcar 'car org-effort-durations))
17692 "\\)")))
17693 (while (string-match re s)
17694 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17695 (string-to-number (match-string 1 s))))
17696 (setq s (replace-match "" nil t s)))
17697 (setq result (floor result))
17698 (incf result (org-hh:mm-string-to-minutes s))
17699 (if output-to-string (number-to-string result) result)))
17701 ;;;; Files
17703 (defun org-save-all-org-buffers ()
17704 "Save all Org-mode buffers without user confirmation."
17705 (interactive)
17706 (message "Saving all Org-mode buffers...")
17707 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17708 (when (featurep 'org-id) (org-id-locations-save))
17709 (message "Saving all Org-mode buffers... done"))
17711 (defun org-revert-all-org-buffers ()
17712 "Revert all Org-mode buffers.
17713 Prompt for confirmation when there are unsaved changes.
17714 Be sure you know what you are doing before letting this function
17715 overwrite your changes.
17717 This function is useful in a setup where one tracks org files
17718 with a version control system, to revert on one machine after pulling
17719 changes from another. I believe the procedure must be like this:
17721 1. M-x org-save-all-org-buffers
17722 2. Pull changes from the other machine, resolve conflicts
17723 3. M-x org-revert-all-org-buffers"
17724 (interactive)
17725 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17726 (user-error "Abort"))
17727 (save-excursion
17728 (save-window-excursion
17729 (mapc
17730 (lambda (b)
17731 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17732 (with-current-buffer b buffer-file-name))
17733 (org-pop-to-buffer-same-window b)
17734 (revert-buffer t 'no-confirm)))
17735 (buffer-list))
17736 (when (and (featurep 'org-id) org-id-track-globally)
17737 (org-id-locations-load)))))
17739 ;;;; Agenda files
17741 ;;;###autoload
17742 (defun org-switchb (&optional arg)
17743 "Switch between Org buffers.
17744 With one prefix argument, restrict available buffers to files.
17745 With two prefix arguments, restrict available buffers to agenda files.
17747 Defaults to `iswitchb' for buffer name completion.
17748 Set `org-completion-use-ido' to make it use ido instead."
17749 (interactive "P")
17750 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17751 ((equal arg '(16)) (org-buffer-list 'agenda))
17752 (t (org-buffer-list))))
17753 (org-completion-use-iswitchb org-completion-use-iswitchb)
17754 (org-completion-use-ido org-completion-use-ido))
17755 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17756 (setq org-completion-use-iswitchb t))
17757 (org-pop-to-buffer-same-window
17758 (org-icompleting-read "Org buffer: "
17759 (mapcar 'list (mapcar 'buffer-name blist))
17760 nil t))))
17762 ;;; Define some older names previously used for this functionality
17763 ;;;###autoload
17764 (defalias 'org-ido-switchb 'org-switchb)
17765 ;;;###autoload
17766 (defalias 'org-iswitchb 'org-switchb)
17768 (defun org-buffer-list (&optional predicate exclude-tmp)
17769 "Return a list of Org buffers.
17770 PREDICATE can be `export', `files' or `agenda'.
17772 export restrict the list to Export buffers.
17773 files restrict the list to buffers visiting Org files.
17774 agenda restrict the list to buffers visiting agenda files.
17776 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17777 (let* ((bfn nil)
17778 (agenda-files (and (eq predicate 'agenda)
17779 (mapcar 'file-truename (org-agenda-files t))))
17780 (filter
17781 (cond
17782 ((eq predicate 'files)
17783 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17784 ((eq predicate 'export)
17785 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17786 ((eq predicate 'agenda)
17787 (lambda (b)
17788 (with-current-buffer b
17789 (and (derived-mode-p 'org-mode)
17790 (setq bfn (buffer-file-name b))
17791 (member (file-truename bfn) agenda-files)))))
17792 (t (lambda (b) (with-current-buffer b
17793 (or (derived-mode-p 'org-mode)
17794 (string-match "\*Org .*Export"
17795 (buffer-name b)))))))))
17796 (delq nil
17797 (mapcar
17798 (lambda(b)
17799 (if (and (funcall filter b)
17800 (or (not exclude-tmp)
17801 (not (string-match "tmp" (buffer-name b)))))
17803 nil))
17804 (buffer-list)))))
17806 (defun org-agenda-files (&optional unrestricted archives)
17807 "Get the list of agenda files.
17808 Optional UNRESTRICTED means return the full list even if a restriction
17809 is currently in place.
17810 When ARCHIVES is t, include all archive files that are really being
17811 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17812 `org-agenda-archives-mode' is t."
17813 (let ((files
17814 (cond
17815 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17816 ((stringp org-agenda-files) (org-read-agenda-file-list))
17817 ((listp org-agenda-files) org-agenda-files)
17818 (t (error "Invalid value of `org-agenda-files'")))))
17819 (setq files (apply 'append
17820 (mapcar (lambda (f)
17821 (if (file-directory-p f)
17822 (directory-files
17823 f t org-agenda-file-regexp)
17824 (list f)))
17825 files)))
17826 (when org-agenda-skip-unavailable-files
17827 (setq files (delq nil
17828 (mapcar (function
17829 (lambda (file)
17830 (and (file-readable-p file) file)))
17831 files))))
17832 (when (or (eq archives t)
17833 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17834 (setq files (org-add-archive-files files)))
17835 files))
17837 (defun org-agenda-file-p (&optional file)
17838 "Return non-nil, if FILE is an agenda file.
17839 If FILE is omitted, use the file associated with the current
17840 buffer."
17841 (member (or file (buffer-file-name))
17842 (org-agenda-files t)))
17844 (defun org-edit-agenda-file-list ()
17845 "Edit the list of agenda files.
17846 Depending on setup, this either uses customize to edit the variable
17847 `org-agenda-files', or it visits the file that is holding the list. In the
17848 latter case, the buffer is set up in a way that saving it automatically kills
17849 the buffer and restores the previous window configuration."
17850 (interactive)
17851 (if (stringp org-agenda-files)
17852 (let ((cw (current-window-configuration)))
17853 (find-file org-agenda-files)
17854 (org-set-local 'org-window-configuration cw)
17855 (org-add-hook 'after-save-hook
17856 (lambda ()
17857 (set-window-configuration
17858 (prog1 org-window-configuration
17859 (kill-buffer (current-buffer))))
17860 (org-install-agenda-files-menu)
17861 (message "New agenda file list installed"))
17862 nil 'local)
17863 (message "%s" (substitute-command-keys
17864 "Edit list and finish with \\[save-buffer]")))
17865 (customize-variable 'org-agenda-files)))
17867 (defun org-store-new-agenda-file-list (list)
17868 "Set new value for the agenda file list and save it correctly."
17869 (if (stringp org-agenda-files)
17870 (let ((fe (org-read-agenda-file-list t)) b u)
17871 (while (setq b (find-buffer-visiting org-agenda-files))
17872 (kill-buffer b))
17873 (with-temp-file org-agenda-files
17874 (insert
17875 (mapconcat
17876 (lambda (f) ;; Keep un-expanded entries.
17877 (if (setq u (assoc f fe))
17878 (cdr u)
17880 list "\n")
17881 "\n")))
17882 (let ((org-mode-hook nil) (org-inhibit-startup t)
17883 (org-insert-mode-line-in-empty-file nil))
17884 (setq org-agenda-files list)
17885 (customize-save-variable 'org-agenda-files org-agenda-files))))
17887 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17888 "Read the list of agenda files from a file.
17889 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17890 filenames, used by `org-store-new-agenda-file-list' to write back
17891 un-expanded file names."
17892 (when (file-directory-p org-agenda-files)
17893 (error "`org-agenda-files' cannot be a single directory"))
17894 (when (stringp org-agenda-files)
17895 (with-temp-buffer
17896 (insert-file-contents org-agenda-files)
17897 (mapcar
17898 (lambda (f)
17899 (let ((e (expand-file-name (substitute-in-file-name f)
17900 org-directory)))
17901 (if pair-with-expansion
17902 (cons e f)
17903 e)))
17904 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17906 ;;;###autoload
17907 (defun org-cycle-agenda-files ()
17908 "Cycle through the files in `org-agenda-files'.
17909 If the current buffer visits an agenda file, find the next one in the list.
17910 If the current buffer does not, find the first agenda file."
17911 (interactive)
17912 (let* ((fs (org-agenda-files t))
17913 (files (append fs (list (car fs))))
17914 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17915 file)
17916 (unless files (user-error "No agenda files"))
17917 (catch 'exit
17918 (while (setq file (pop files))
17919 (if (equal (file-truename file) tcf)
17920 (when (car files)
17921 (find-file (car files))
17922 (throw 'exit t))))
17923 (find-file (car fs)))
17924 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17926 (defun org-agenda-file-to-front (&optional to-end)
17927 "Move/add the current file to the top of the agenda file list.
17928 If the file is not present in the list, it is added to the front. If it is
17929 present, it is moved there. With optional argument TO-END, add/move to the
17930 end of the list."
17931 (interactive "P")
17932 (let ((org-agenda-skip-unavailable-files nil)
17933 (file-alist (mapcar (lambda (x)
17934 (cons (file-truename x) x))
17935 (org-agenda-files t)))
17936 (ctf (file-truename
17937 (or buffer-file-name
17938 (user-error "Please save the current buffer to a file"))))
17939 x had)
17940 (setq x (assoc ctf file-alist) had x)
17942 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17943 (if to-end
17944 (setq file-alist (append (delq x file-alist) (list x)))
17945 (setq file-alist (cons x (delq x file-alist))))
17946 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17947 (org-install-agenda-files-menu)
17948 (message "File %s to %s of agenda file list"
17949 (if had "moved" "added") (if to-end "end" "front"))))
17951 (defun org-remove-file (&optional file)
17952 "Remove current file from the list of files in variable `org-agenda-files'.
17953 These are the files which are being checked for agenda entries.
17954 Optional argument FILE means use this file instead of the current."
17955 (interactive)
17956 (let* ((org-agenda-skip-unavailable-files nil)
17957 (file (or file buffer-file-name
17958 (user-error "Current buffer does not visit a file")))
17959 (true-file (file-truename file))
17960 (afile (abbreviate-file-name file))
17961 (files (delq nil (mapcar
17962 (lambda (x)
17963 (if (equal true-file
17964 (file-truename x))
17965 nil x))
17966 (org-agenda-files t)))))
17967 (if (not (= (length files) (length (org-agenda-files t))))
17968 (progn
17969 (org-store-new-agenda-file-list files)
17970 (org-install-agenda-files-menu)
17971 (message "Removed file: %s" afile))
17972 (message "File was not in list: %s (not removed)" afile))))
17974 (defun org-file-menu-entry (file)
17975 (vector file (list 'find-file file) t))
17977 (defun org-check-agenda-file (file)
17978 "Make sure FILE exists. If not, ask user what to do."
17979 (when (not (file-exists-p file))
17980 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17981 (abbreviate-file-name file))
17982 (let ((r (downcase (read-char-exclusive))))
17983 (cond
17984 ((equal r ?r)
17985 (org-remove-file file)
17986 (throw 'nextfile t))
17987 (t (error "Abort"))))))
17989 (defun org-get-agenda-file-buffer (file)
17990 "Get a buffer visiting FILE. If the buffer needs to be created, add
17991 it to the list of buffers which might be released later."
17992 (let ((buf (org-find-base-buffer-visiting file)))
17993 (if buf
17994 buf ; just return it
17995 ;; Make a new buffer and remember it
17996 (setq buf (find-file-noselect file))
17997 (if buf (push buf org-agenda-new-buffers))
17998 buf)))
18000 (defun org-release-buffers (blist)
18001 "Release all buffers in list, asking the user for confirmation when needed.
18002 When a buffer is unmodified, it is just killed. When modified, it is saved
18003 \(if the user agrees) and then killed."
18004 (let (buf file)
18005 (while (setq buf (pop blist))
18006 (setq file (buffer-file-name buf))
18007 (when (and (buffer-modified-p buf)
18008 file
18009 (y-or-n-p (format "Save file %s? " file)))
18010 (with-current-buffer buf (save-buffer)))
18011 (kill-buffer buf))))
18013 (defun org-agenda-prepare-buffers (files)
18014 "Create buffers for all agenda files, protect archived trees and comments."
18015 (interactive)
18016 (let ((pa '(:org-archived t))
18017 (pc '(:org-comment t))
18018 (pall '(:org-archived t :org-comment t))
18019 (inhibit-read-only t)
18020 (org-inhibit-startup org-agenda-inhibit-startup)
18021 (rea (concat ":" org-archive-tag ":"))
18022 file re)
18023 (setq org-tag-alist-for-agenda nil
18024 org-tag-groups-alist-for-agenda nil)
18025 (save-excursion
18026 (save-restriction
18027 (while (setq file (pop files))
18028 (catch 'nextfile
18029 (if (bufferp file)
18030 (set-buffer file)
18031 (org-check-agenda-file file)
18032 (set-buffer (org-get-agenda-file-buffer file)))
18033 (widen)
18034 (org-set-regexps-and-options-for-tags)
18035 (goto-char (point-min))
18036 (let ((case-fold-search t))
18037 (when (search-forward "#+setupfile" nil t)
18038 ;; Don't set all regexps and options systematically as
18039 ;; this is only run for setting agenda tags from setup
18040 ;; file
18041 (org-set-regexps-and-options)))
18042 (or (memq 'category org-agenda-ignore-drawer-properties)
18043 (org-refresh-category-properties))
18044 (or (memq 'effort org-agenda-ignore-drawer-properties)
18045 (org-refresh-properties org-effort-property 'org-effort))
18046 (or (memq 'appt org-agenda-ignore-drawer-properties)
18047 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18048 (setq org-todo-keywords-for-agenda
18049 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18050 (setq org-done-keywords-for-agenda
18051 (append org-done-keywords-for-agenda org-done-keywords))
18052 (setq org-todo-keyword-alist-for-agenda
18053 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18054 (setq org-tag-alist-for-agenda
18055 (org-uniquify
18056 (append org-tag-alist-for-agenda
18057 org-tag-alist
18058 org-tag-persistent-alist)))
18059 (if org-group-tags
18060 (setq org-tag-groups-alist-for-agenda
18061 (org-uniquify-alist
18062 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18063 (org-with-silent-modifications
18064 (save-excursion
18065 (remove-text-properties (point-min) (point-max) pall)
18066 (when org-agenda-skip-archived-trees
18067 (goto-char (point-min))
18068 (while (re-search-forward rea nil t)
18069 (if (org-at-heading-p t)
18070 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18071 (goto-char (point-min))
18072 (setq re (format org-heading-keyword-regexp-format
18073 org-comment-string))
18074 (while (re-search-forward re nil t)
18075 (add-text-properties
18076 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18077 (setq org-todo-keywords-for-agenda
18078 (org-uniquify org-todo-keywords-for-agenda))
18079 (setq org-todo-keyword-alist-for-agenda
18080 (org-uniquify org-todo-keyword-alist-for-agenda))))
18083 ;;;; CDLaTeX minor mode
18085 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18086 "Keymap for the minor `org-cdlatex-mode'.")
18088 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18089 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18090 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18091 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18092 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18094 (defvar org-cdlatex-texmathp-advice-is-done nil
18095 "Flag remembering if we have applied the advice to texmathp already.")
18097 (define-minor-mode org-cdlatex-mode
18098 "Toggle the minor `org-cdlatex-mode'.
18099 This mode supports entering LaTeX environment and math in LaTeX fragments
18100 in Org-mode.
18101 \\{org-cdlatex-mode-map}"
18102 nil " OCDL" nil
18103 (when org-cdlatex-mode
18104 (require 'cdlatex)
18105 (run-hooks 'cdlatex-mode-hook)
18106 (cdlatex-compute-tables))
18107 (unless org-cdlatex-texmathp-advice-is-done
18108 (setq org-cdlatex-texmathp-advice-is-done t)
18109 (defadvice texmathp (around org-math-always-on activate)
18110 "Always return t in org-mode buffers.
18111 This is because we want to insert math symbols without dollars even outside
18112 the LaTeX math segments. If Orgmode thinks that point is actually inside
18113 an embedded LaTeX fragment, let texmathp do its job.
18114 \\[org-cdlatex-mode-map]"
18115 (interactive)
18116 (let (p)
18117 (cond
18118 ((not (derived-mode-p 'org-mode)) ad-do-it)
18119 ((eq this-command 'cdlatex-math-symbol)
18120 (setq ad-return-value t
18121 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18123 (let ((p (org-inside-LaTeX-fragment-p)))
18124 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18125 (setq ad-return-value t
18126 texmathp-why '("Org-mode embedded math" . 0))
18127 (if p ad-do-it)))))))))
18129 (defun turn-on-org-cdlatex ()
18130 "Unconditionally turn on `org-cdlatex-mode'."
18131 (org-cdlatex-mode 1))
18133 (defun org-try-cdlatex-tab ()
18134 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18135 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18136 - inside a LaTeX fragment, or
18137 - after the first word in a line, where an abbreviation expansion could
18138 insert a LaTeX environment."
18139 (when org-cdlatex-mode
18140 (cond
18141 ;; Before any word on the line: No expansion possible.
18142 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18143 ;; Just after first word on the line: Expand it. Make sure it
18144 ;; cannot happen on headlines, though.
18145 ((save-excursion
18146 (skip-chars-backward "a-zA-Z0-9*")
18147 (skip-chars-backward " \t")
18148 (and (bolp) (not (org-at-heading-p))))
18149 (cdlatex-tab) t)
18150 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18152 (defun org-cdlatex-underscore-caret (&optional arg)
18153 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18154 Revert to the normal definition outside of these fragments."
18155 (interactive "P")
18156 (if (org-inside-LaTeX-fragment-p)
18157 (call-interactively 'cdlatex-sub-superscript)
18158 (let (org-cdlatex-mode)
18159 (call-interactively (key-binding (vector last-input-event))))))
18161 (defun org-cdlatex-math-modify (&optional arg)
18162 "Execute `cdlatex-math-modify' in LaTeX fragments.
18163 Revert to the normal definition outside of these fragments."
18164 (interactive "P")
18165 (if (org-inside-LaTeX-fragment-p)
18166 (call-interactively 'cdlatex-math-modify)
18167 (let (org-cdlatex-mode)
18168 (call-interactively (key-binding (vector last-input-event))))))
18172 ;;;; LaTeX fragments
18174 (defvar org-latex-regexps
18175 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18176 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18177 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18178 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18179 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18180 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18181 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18182 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18183 "Regular expressions for matching embedded LaTeX.")
18185 (defun org-inside-LaTeX-fragment-p ()
18186 "Test if point is inside a LaTeX fragment.
18187 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18188 sequence appearing also before point.
18189 Even though the matchers for math are configurable, this function assumes
18190 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18191 delimiters are skipped when they have been removed by customization.
18192 The return value is nil, or a cons cell with the delimiter and the
18193 position of this delimiter.
18195 This function does a reasonably good job, but can locally be fooled by
18196 for example currency specifications. For example it will assume being in
18197 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18198 fragments that are properly closed, but during editing, we have to live
18199 with the uncertainty caused by missing closing delimiters. This function
18200 looks only before point, not after."
18201 (catch 'exit
18202 (let ((pos (point))
18203 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18204 (lim (progn
18205 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18206 (point)))
18207 dd-on str (start 0) m re)
18208 (goto-char pos)
18209 (when dodollar
18210 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18211 re (nth 1 (assoc "$" org-latex-regexps)))
18212 (while (string-match re str start)
18213 (cond
18214 ((= (match-end 0) (length str))
18215 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18216 ((= (match-end 0) (- (length str) 5))
18217 (throw 'exit nil))
18218 (t (setq start (match-end 0))))))
18219 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18220 (goto-char pos)
18221 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18222 (and (match-beginning 2) (throw 'exit nil))
18223 ;; count $$
18224 (while (re-search-backward "\\$\\$" lim t)
18225 (setq dd-on (not dd-on)))
18226 (goto-char pos)
18227 (if dd-on (cons "$$" m))))))
18229 (defun org-inside-latex-macro-p ()
18230 "Is point inside a LaTeX macro or its arguments?"
18231 (save-match-data
18232 (org-in-regexp
18233 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18235 (defvar org-latex-fragment-image-overlays nil
18236 "List of overlays carrying the images of latex fragments.")
18237 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18239 (defun org-remove-latex-fragment-image-overlays ()
18240 "Remove all overlays with LaTeX fragment images in current buffer."
18241 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18242 (setq org-latex-fragment-image-overlays nil))
18244 (defun org-preview-latex-fragment (&optional subtree)
18245 "Preview the LaTeX fragment at point, or all locally or globally.
18246 If the cursor is in a LaTeX fragment, create the image and overlay
18247 it over the source code. If there is no fragment at point, display
18248 all fragments in the current text, from one headline to the next. With
18249 prefix SUBTREE, display all fragments in the current subtree. With a
18250 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18251 the cursor is before the first headline,
18252 display all fragments in the buffer.
18253 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18254 (interactive "P")
18255 (unless buffer-file-name
18256 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18257 (when (display-graphic-p)
18258 (org-remove-latex-fragment-image-overlays)
18259 (save-excursion
18260 (save-restriction
18261 (let (beg end at msg)
18262 (cond
18263 ((or (equal subtree '(16))
18264 (not (save-excursion
18265 (re-search-backward org-outline-regexp-bol nil t))))
18266 (setq beg (point-min) end (point-max)
18267 msg "Creating images for buffer...%s"))
18268 ((equal subtree '(4))
18269 (org-back-to-heading)
18270 (setq beg (point) end (org-end-of-subtree t)
18271 msg "Creating images for subtree...%s"))
18273 (if (setq at (org-inside-LaTeX-fragment-p))
18274 (goto-char (max (point-min) (- (cdr at) 2)))
18275 (org-back-to-heading))
18276 (setq beg (point) end (progn (outline-next-heading) (point))
18277 msg (if at "Creating image...%s"
18278 "Creating images for entry...%s"))))
18279 (message msg "")
18280 (narrow-to-region beg end)
18281 (goto-char beg)
18282 (org-format-latex
18283 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18284 (file-name-nondirectory
18285 buffer-file-name)))
18286 default-directory 'overlays msg at 'forbuffer
18287 org-latex-create-formula-image-program)
18288 (message msg "done. Use `C-c C-c' to remove images."))))))
18290 (defun org-format-latex (prefix &optional dir overlays msg at
18291 forbuffer processing-type)
18292 "Replace LaTeX fragments with links to an image, and produce images.
18293 Some of the options can be changed using the variable
18294 `org-format-latex-options'."
18295 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18296 (let* ((prefixnodir (file-name-nondirectory prefix))
18297 (absprefix (expand-file-name prefix dir))
18298 (todir (file-name-directory absprefix))
18299 (opt org-format-latex-options)
18300 (optnew org-format-latex-options)
18301 (matchers (plist-get opt :matchers))
18302 (re-list org-latex-regexps)
18303 (cnt 0) txt hash link beg end re e checkdir
18304 string
18305 m n block-type block linkfile movefile ov)
18306 ;; Check the different regular expressions
18307 (while (setq e (pop re-list))
18308 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18309 block (if block-type "\n\n" ""))
18310 (when (member m matchers)
18311 (goto-char (point-min))
18312 (while (re-search-forward re nil t)
18313 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18314 (or (not overlays)
18315 (not (eq (get-char-property (match-beginning n)
18316 'org-overlay-type)
18317 'org-latex-overlay))))
18318 (cond
18319 ((eq processing-type 'verbatim))
18320 ((eq processing-type 'mathjax)
18321 ;; Prepare for MathJax processing.
18322 (setq string (match-string n))
18323 (when (member m '("$" "$1"))
18324 (save-excursion
18325 (delete-region (match-beginning n) (match-end n))
18326 (goto-char (match-beginning n))
18327 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18328 ((or (eq processing-type 'dvipng)
18329 (eq processing-type 'imagemagick))
18330 ;; Process to an image.
18331 (setq txt (match-string n)
18332 beg (match-beginning n) end (match-end n)
18333 cnt (1+ cnt))
18334 (let ((face (face-at-point))
18335 (fg (plist-get opt :foreground))
18336 (bg (plist-get opt :background))
18337 ;; Ensure full list is printed.
18338 print-length print-level)
18339 (when forbuffer
18340 ;; Get the colors from the face at point.
18341 (goto-char beg)
18342 (when (eq fg 'auto)
18343 (setq fg (face-attribute face :foreground nil 'default)))
18344 (when (eq bg 'auto)
18345 (setq bg (face-attribute face :background nil 'default)))
18346 (setq optnew (copy-sequence opt))
18347 (plist-put optnew :foreground fg)
18348 (plist-put optnew :background bg))
18349 (setq hash (sha1 (prin1-to-string
18350 (list org-format-latex-header
18351 org-latex-default-packages-alist
18352 org-latex-packages-alist
18353 org-format-latex-options
18354 forbuffer txt fg bg)))
18355 linkfile (format "%s_%s.png" prefix hash)
18356 movefile (format "%s_%s.png" absprefix hash)))
18357 (setq link (concat block "[[file:" linkfile "]]" block))
18358 (if msg (message msg cnt))
18359 (goto-char beg)
18360 (unless checkdir ; Ensure the directory exists.
18361 (setq checkdir t)
18362 (or (file-directory-p todir) (make-directory todir t)))
18363 (unless (file-exists-p movefile)
18364 (org-create-formula-image
18365 txt movefile optnew forbuffer processing-type))
18366 (if overlays
18367 (progn
18368 (mapc (lambda (o)
18369 (if (eq (overlay-get o 'org-overlay-type)
18370 'org-latex-overlay)
18371 (delete-overlay o)))
18372 (overlays-in beg end))
18373 (setq ov (make-overlay beg end))
18374 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18375 (if (featurep 'xemacs)
18376 (progn
18377 (overlay-put ov 'invisible t)
18378 (overlay-put
18379 ov 'end-glyph
18380 (make-glyph (vector 'png :file movefile))))
18381 (overlay-put
18382 ov 'display
18383 (list 'image :type 'png :file movefile :ascent 'center)))
18384 (push ov org-latex-fragment-image-overlays)
18385 (goto-char end))
18386 (delete-region beg end)
18387 (insert (org-add-props link
18388 (list 'org-latex-src
18389 (replace-regexp-in-string
18390 "\"" "" txt)
18391 'org-latex-src-embed-type
18392 (if block-type 'paragraph 'character))))))
18393 ((eq processing-type 'mathml)
18394 ;; Process to MathML
18395 (unless (save-match-data (org-format-latex-mathml-available-p))
18396 (user-error "LaTeX to MathML converter not configured"))
18397 (setq txt (match-string n)
18398 beg (match-beginning n) end (match-end n)
18399 cnt (1+ cnt))
18400 (if msg (message msg cnt))
18401 (goto-char beg)
18402 (delete-region beg end)
18403 (insert (org-format-latex-as-mathml
18404 txt block-type prefix dir)))
18406 (error "Unknown conversion type %s for LaTeX fragments"
18407 processing-type)))))))))
18409 (defun org-create-math-formula (latex-frag &optional mathml-file)
18410 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18411 Use `org-latex-to-mathml-convert-command'. If the conversion is
18412 sucessful, return the portion between \"<math...> </math>\"
18413 elements otherwise return nil. When MATHML-FILE is specified,
18414 write the results in to that file. When invoked as an
18415 interactive command, prompt for LATEX-FRAG, with initial value
18416 set to the current active region and echo the results for user
18417 inspection."
18418 (interactive (list (let ((frag (when (org-region-active-p)
18419 (buffer-substring-no-properties
18420 (region-beginning) (region-end)))))
18421 (read-string "LaTeX Fragment: " frag nil frag))))
18422 (unless latex-frag (error "Invalid LaTeX fragment"))
18423 (let* ((tmp-in-file (file-relative-name
18424 (make-temp-name (expand-file-name "ltxmathml-in"))))
18425 (ignore (write-region latex-frag nil tmp-in-file))
18426 (tmp-out-file (file-relative-name
18427 (make-temp-name (expand-file-name "ltxmathml-out"))))
18428 (cmd (format-spec
18429 org-latex-to-mathml-convert-command
18430 `((?j . ,(shell-quote-argument
18431 (expand-file-name org-latex-to-mathml-jar-file)))
18432 (?I . ,(shell-quote-argument tmp-in-file))
18433 (?o . ,(shell-quote-argument tmp-out-file)))))
18434 mathml shell-command-output)
18435 (when (org-called-interactively-p 'any)
18436 (unless (org-format-latex-mathml-available-p)
18437 (user-error "LaTeX to MathML converter not configured")))
18438 (message "Running %s" cmd)
18439 (setq shell-command-output (shell-command-to-string cmd))
18440 (setq mathml
18441 (when (file-readable-p tmp-out-file)
18442 (with-current-buffer (find-file-noselect tmp-out-file t)
18443 (goto-char (point-min))
18444 (when (re-search-forward
18445 (concat
18446 (regexp-quote
18447 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18448 "\\(.\\|\n\\)*"
18449 (regexp-quote "</math>")) nil t)
18450 (prog1 (match-string 0) (kill-buffer))))))
18451 (cond
18452 (mathml
18453 (setq mathml
18454 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18455 (when mathml-file
18456 (write-region mathml nil mathml-file))
18457 (when (org-called-interactively-p 'any)
18458 (message mathml)))
18459 ((message "LaTeX to MathML conversion failed")
18460 (message shell-command-output)))
18461 (delete-file tmp-in-file)
18462 (when (file-exists-p tmp-out-file)
18463 (delete-file tmp-out-file))
18464 mathml))
18466 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18467 prefix &optional dir)
18468 "Use `org-create-math-formula' but check local cache first."
18469 (let* ((absprefix (expand-file-name prefix dir))
18470 (print-length nil) (print-level nil)
18471 (formula-id (concat
18472 "formula-"
18473 (sha1
18474 (prin1-to-string
18475 (list latex-frag
18476 org-latex-to-mathml-convert-command)))))
18477 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18478 (formula-cache-dir (file-name-directory formula-cache)))
18480 (unless (file-directory-p formula-cache-dir)
18481 (make-directory formula-cache-dir t))
18483 (unless (file-exists-p formula-cache)
18484 (org-create-math-formula latex-frag formula-cache))
18486 (if (file-exists-p formula-cache)
18487 ;; Successful conversion. Return the link to MathML file.
18488 (org-add-props
18489 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18490 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18491 'org-latex-src-embed-type (if latex-frag-type
18492 'paragraph 'character)))
18493 ;; Failed conversion. Return the LaTeX fragment verbatim
18494 latex-frag)))
18496 (defun org-create-formula-image (string tofile options buffer &optional type)
18497 "Create an image from LaTeX source using dvipng or convert.
18498 This function calls either `org-create-formula-image-with-dvipng'
18499 or `org-create-formula-image-with-imagemagick' depending on the
18500 value of `org-latex-create-formula-image-program' or on the value
18501 of the optional TYPE variable.
18503 Note: ultimately these two function should be combined as they
18504 share a good deal of logic."
18505 (org-check-external-command
18506 "latex" "needed to convert LaTeX fragments to images")
18507 (funcall
18508 (case (or type org-latex-create-formula-image-program)
18509 ('dvipng
18510 (org-check-external-command
18511 "dvipng" "needed to convert LaTeX fragments to images")
18512 #'org-create-formula-image-with-dvipng)
18513 ('imagemagick
18514 (org-check-external-command
18515 "convert" "you need to install imagemagick")
18516 #'org-create-formula-image-with-imagemagick)
18517 (t (error
18518 "Invalid value of `org-latex-create-formula-image-program'")))
18519 string tofile options buffer))
18521 (declare-function org-export-get-backend "ox" (name))
18522 (declare-function org-export--get-global-options "ox" (&optional backend))
18523 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18524 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18525 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18526 (defun org-create-formula--latex-header ()
18527 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18528 (let ((info (org-combine-plists (org-export--get-global-options
18529 (org-export-get-backend 'latex))
18530 (org-export--get-inbuffer-options
18531 (org-export-get-backend 'latex)))))
18532 (org-latex-guess-babel-language
18533 (org-latex-guess-inputenc
18534 (org-splice-latex-header
18535 org-format-latex-header
18536 org-latex-default-packages-alist
18537 org-latex-packages-alist t
18538 (plist-get info :latex-header)))
18539 info)))
18541 ;; This function borrows from Ganesh Swami's latex2png.el
18542 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18543 "This calls dvipng."
18544 (require 'ox-latex)
18545 (let* ((tmpdir (if (featurep 'xemacs)
18546 (temp-directory)
18547 temporary-file-directory))
18548 (texfilebase (make-temp-name
18549 (expand-file-name "orgtex" tmpdir)))
18550 (texfile (concat texfilebase ".tex"))
18551 (dvifile (concat texfilebase ".dvi"))
18552 (pngfile (concat texfilebase ".png"))
18553 (fnh (if (featurep 'xemacs)
18554 (font-height (face-font 'default))
18555 (face-attribute 'default :height nil)))
18556 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18557 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18558 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18559 "Black"))
18560 (bg (or (plist-get options (if buffer :background :html-background))
18561 "Transparent")))
18562 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18563 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18564 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18565 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18566 (let ((latex-header (org-create-formula--latex-header)))
18567 (with-temp-file texfile
18568 (insert latex-header)
18569 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18570 (let ((dir default-directory))
18571 (condition-case nil
18572 (progn
18573 (cd tmpdir)
18574 (call-process "latex" nil nil nil texfile))
18575 (error nil))
18576 (cd dir))
18577 (if (not (file-exists-p dvifile))
18578 (progn (message "Failed to create dvi file from %s" texfile) nil)
18579 (condition-case nil
18580 (if (featurep 'xemacs)
18581 (call-process "dvipng" nil nil nil
18582 "-fg" fg "-bg" bg
18583 "-T" "tight"
18584 "-o" pngfile
18585 dvifile)
18586 (call-process "dvipng" nil nil nil
18587 "-fg" fg "-bg" bg
18588 "-D" dpi
18589 ;;"-x" scale "-y" scale
18590 "-T" "tight"
18591 "-o" pngfile
18592 dvifile))
18593 (error nil))
18594 (if (not (file-exists-p pngfile))
18595 (if org-format-latex-signal-error
18596 (error "Failed to create png file from %s" texfile)
18597 (message "Failed to create png file from %s" texfile)
18598 nil)
18599 ;; Use the requested file name and clean up
18600 (copy-file pngfile tofile 'replace)
18601 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18602 (if (file-exists-p (concat texfilebase e))
18603 (delete-file (concat texfilebase e))))
18604 pngfile))))
18606 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18607 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18608 "This calls convert, which is included into imagemagick."
18609 (require 'ox-latex)
18610 (let* ((tmpdir (if (featurep 'xemacs)
18611 (temp-directory)
18612 temporary-file-directory))
18613 (texfilebase (make-temp-name
18614 (expand-file-name "orgtex" tmpdir)))
18615 (texfile (concat texfilebase ".tex"))
18616 (pdffile (concat texfilebase ".pdf"))
18617 (pngfile (concat texfilebase ".png"))
18618 (fnh (if (featurep 'xemacs)
18619 (font-height (face-font 'default))
18620 (face-attribute 'default :height nil)))
18621 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18622 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18623 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18624 "black"))
18625 (bg (or (plist-get options (if buffer :background :html-background))
18626 "white")))
18627 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18628 (setq fg (org-latex-color-format fg)))
18629 (if (eq bg 'default) (setq bg (org-latex-color :background))
18630 (setq bg (org-latex-color-format
18631 (if (string= bg "Transparent") "white" bg))))
18632 (let ((latex-header (org-create-formula--latex-header)))
18633 (with-temp-file texfile
18634 (insert latex-header)
18635 (insert "\n\\begin{document}\n"
18636 "\\definecolor{fg}{rgb}{" fg "}\n"
18637 "\\definecolor{bg}{rgb}{" bg "}\n"
18638 "\n\\pagecolor{bg}\n"
18639 "\n{\\color{fg}\n"
18640 string
18641 "\n}\n"
18642 "\n\\end{document}\n")))
18643 (org-latex-compile texfile t)
18644 (if (not (file-exists-p pdffile))
18645 (progn (message "Failed to create pdf file from %s" texfile) nil)
18646 (condition-case nil
18647 (if (featurep 'xemacs)
18648 (call-process "convert" nil nil nil
18649 "-density" "96"
18650 "-trim"
18651 "-antialias"
18652 pdffile
18653 "-quality" "100"
18654 ;; "-sharpen" "0x1.0"
18655 pngfile)
18656 (call-process "convert" nil nil nil
18657 "-density" dpi
18658 "-trim"
18659 "-antialias"
18660 pdffile
18661 "-quality" "100"
18662 ;; "-sharpen" "0x1.0"
18663 pngfile))
18664 (error nil))
18665 (if (not (file-exists-p pngfile))
18666 (if org-format-latex-signal-error
18667 (error "Failed to create png file from %s" texfile)
18668 (message "Failed to create png file from %s" texfile)
18669 nil)
18670 ;; Use the requested file name and clean up
18671 (copy-file pngfile tofile 'replace)
18672 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18673 (if (file-exists-p (concat texfilebase e))
18674 (delete-file (concat texfilebase e))))
18675 pngfile))))
18677 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18678 "Fill a LaTeX header template TPL.
18679 In the template, the following place holders will be recognized:
18681 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18682 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18683 [PACKAGES] \\usepackage statements for PKG
18684 [NO-PACKAGES] do not include PKG
18685 [EXTRA] the string EXTRA
18686 [NO-EXTRA] do not include EXTRA
18688 For backward compatibility, if both the positive and the negative place
18689 holder is missing, the positive one (without the \"NO-\") will be
18690 assumed to be present at the end of the template.
18691 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18692 EXTRA is a string.
18693 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18694 (let (rpl (end ""))
18695 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18696 (setq rpl (if (or (match-end 1) (not def-pkg))
18697 "" (org-latex-packages-to-string def-pkg snippets-p t))
18698 tpl (replace-match rpl t t tpl))
18699 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18701 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18702 (setq rpl (if (or (match-end 1) (not pkg))
18703 "" (org-latex-packages-to-string pkg snippets-p t))
18704 tpl (replace-match rpl t t tpl))
18705 (if pkg (setq end
18706 (concat end "\n"
18707 (org-latex-packages-to-string pkg snippets-p)))))
18709 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18710 (setq rpl (if (or (match-end 1) (not extra))
18711 "" (concat extra "\n"))
18712 tpl (replace-match rpl t t tpl))
18713 (if (and extra (string-match "\\S-" extra))
18714 (setq end (concat end "\n" extra))))
18716 (if (string-match "\\S-" end)
18717 (concat tpl "\n" end)
18718 tpl)))
18720 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18721 "Turn an alist of packages into a string with the \\usepackage macros."
18722 (setq pkg (mapconcat (lambda(p)
18723 (cond
18724 ((stringp p) p)
18725 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18726 (format "%% Package %s omitted" (cadr p)))
18727 ((equal "" (car p))
18728 (format "\\usepackage{%s}" (cadr p)))
18730 (format "\\usepackage[%s]{%s}"
18731 (car p) (cadr p)))))
18733 "\n"))
18734 (if newline (concat pkg "\n") pkg))
18736 (defun org-dvipng-color (attr)
18737 "Return a RGB color specification for dvipng."
18738 (apply 'format "rgb %s %s %s"
18739 (mapcar 'org-normalize-color
18740 (if (featurep 'xemacs)
18741 (color-rgb-components
18742 (face-property 'default
18743 (cond ((eq attr :foreground) 'foreground)
18744 ((eq attr :background) 'background))))
18745 (color-values (face-attribute 'default attr nil))))))
18747 (defun org-dvipng-color-format (color-name)
18748 "Convert COLOR-NAME to a RGB color value for dvipng."
18749 (apply 'format "rgb %s %s %s"
18750 (mapcar 'org-normalize-color
18751 (color-values color-name))))
18753 (defun org-latex-color (attr)
18754 "Return a RGB color for the LaTeX color package."
18755 (apply 'format "%s,%s,%s"
18756 (mapcar 'org-normalize-color
18757 (if (featurep 'xemacs)
18758 (color-rgb-components
18759 (face-property 'default
18760 (cond ((eq attr :foreground) 'foreground)
18761 ((eq attr :background) 'background))))
18762 (color-values (face-attribute 'default attr nil))))))
18764 (defun org-latex-color-format (color-name)
18765 "Convert COLOR-NAME to a RGB color value."
18766 (apply 'format "%s,%s,%s"
18767 (mapcar 'org-normalize-color
18768 (color-values color-name))))
18770 (defun org-normalize-color (value)
18771 "Return string to be used as color value for an RGB component."
18772 (format "%g" (/ value 65535.0)))
18776 ;; Image display
18778 (defvar org-inline-image-overlays nil)
18779 (make-variable-buffer-local 'org-inline-image-overlays)
18781 (defun org-toggle-inline-images (&optional include-linked)
18782 "Toggle the display of inline images.
18783 INCLUDE-LINKED is passed to `org-display-inline-images'."
18784 (interactive "P")
18785 (if org-inline-image-overlays
18786 (progn
18787 (org-remove-inline-images)
18788 (message "Inline image display turned off"))
18789 (org-display-inline-images include-linked)
18790 (if (and (org-called-interactively-p)
18791 org-inline-image-overlays)
18792 (message "%d images displayed inline"
18793 (length org-inline-image-overlays))
18794 (message "No images to display inline"))))
18796 (defun org-redisplay-inline-images ()
18797 "Refresh the display of inline images."
18798 (interactive)
18799 (if (not org-inline-image-overlays)
18800 (org-toggle-inline-images)
18801 (org-toggle-inline-images)
18802 (org-toggle-inline-images)))
18804 (defun org-display-inline-images (&optional include-linked refresh beg end)
18805 "Display inline images.
18807 An inline image is a link which follows either of these
18808 conventions:
18810 1. Its path is a file with an extension matching return value
18811 from `image-file-name-regexp' and it has no contents.
18813 2. Its description consists in a single link of the previous
18814 type.
18816 When optional argument INCLUDE-LINKED is non-nil, also links with
18817 a text description part will be inlined. This can be nice for
18818 a quick look at those images, but it does not reflect what
18819 exported files will look like.
18821 When optional argument REFRESH is non-nil, refresh existing
18822 images between BEG and END. This will create new image displays
18823 only if necessary. BEG and END default to the buffer
18824 boundaries."
18825 (interactive "P")
18826 (when (display-graphic-p)
18827 (unless refresh
18828 (org-remove-inline-images)
18829 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18830 (org-with-wide-buffer
18831 (goto-char (or beg (point-min)))
18832 (let ((case-fold-search t)
18833 (file-extension-re (org-image-file-name-regexp)))
18834 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18835 (let ((link (save-match-data (org-element-context))))
18836 ;; Check if we're at an inline image.
18837 (when (and (equal (org-element-property :type link) "file")
18838 (or include-linked
18839 (not (org-element-property :contents-begin link)))
18840 (let ((parent (org-element-property :parent link)))
18841 (or (not (eq (org-element-type parent) 'link))
18842 (not (cdr (org-element-contents parent)))))
18843 (org-string-match-p file-extension-re
18844 (org-element-property :path link)))
18845 (let ((file (expand-file-name (org-element-property :path link))))
18846 (when (file-exists-p file)
18847 (let ((width
18848 ;; Apply `org-image-actual-width' specifications.
18849 (cond
18850 ((not (image-type-available-p 'imagemagick)) nil)
18851 ((eq org-image-actual-width t) nil)
18852 ((listp org-image-actual-width)
18854 ;; First try to find a width among
18855 ;; attributes associated to the paragraph
18856 ;; containing link.
18857 (let ((paragraph
18858 (let ((e link))
18859 (while (and (setq e (org-element-property
18860 :parent e))
18861 (not (eq (org-element-type e)
18862 'paragraph))))
18863 e)))
18864 (when paragraph
18865 (save-excursion
18866 (goto-char (org-element-property :begin paragraph))
18867 (when (save-match-data
18868 (re-search-forward
18869 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18870 (org-element-property
18871 :post-affiliated paragraph)
18873 (string-to-number (match-string 1))))))
18874 ;; Otherwise, fall-back to provided number.
18875 (car org-image-actual-width)))
18876 ((numberp org-image-actual-width)
18877 org-image-actual-width)))
18878 (old (get-char-property-and-overlay
18879 (org-element-property :begin link)
18880 'org-image-overlay)))
18881 (if (and (car-safe old) refresh)
18882 (image-refresh (overlay-get (cdr old) 'display))
18883 (let ((image (save-match-data
18884 (create-image file
18885 (and width 'imagemagick)
18887 :width width))))
18888 (when image
18889 (let* ((link
18890 ;; If inline image is the description
18891 ;; of another link, be sure to
18892 ;; consider the latter as the one to
18893 ;; apply the overlay on.
18894 (let ((parent
18895 (org-element-property :parent link)))
18896 (if (eq (org-element-type parent) 'link)
18897 parent
18898 link)))
18899 (ov (make-overlay
18900 (org-element-property :begin link)
18901 (progn
18902 (goto-char
18903 (org-element-property :end link))
18904 (skip-chars-backward " \t")
18905 (point)))))
18906 (overlay-put ov 'display image)
18907 (overlay-put ov 'face 'default)
18908 (overlay-put ov 'org-image-overlay t)
18909 (overlay-put
18910 ov 'modification-hooks
18911 (list 'org-display-inline-remove-overlay))
18912 (push ov org-inline-image-overlays)))))))))))))))
18914 (define-obsolete-function-alias
18915 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18917 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18918 "Remove inline-display overlay if a corresponding region is modified."
18919 (let ((inhibit-modification-hooks t))
18920 (when (and ov after)
18921 (delete ov org-inline-image-overlays)
18922 (delete-overlay ov))))
18924 (defun org-remove-inline-images ()
18925 "Remove inline display of images."
18926 (interactive)
18927 (mapc 'delete-overlay org-inline-image-overlays)
18928 (setq org-inline-image-overlays nil))
18930 ;;;; Key bindings
18932 ;; Outline functions from `outline-mode-prefix-map'
18933 ;; that can be remapped in Org:
18934 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18935 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18936 (define-key org-mode-map [remap outline-forward-same-level]
18937 'org-forward-heading-same-level)
18938 (define-key org-mode-map [remap outline-backward-same-level]
18939 'org-backward-heading-same-level)
18940 (define-key org-mode-map [remap show-branches]
18941 'org-kill-note-or-show-branches)
18942 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18943 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18944 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18946 ;; Outline functions from `outline-mode-prefix-map' that can not
18947 ;; be remapped in Org:
18949 ;; - the column "key binding" shows whether the Outline function is still
18950 ;; available in Org mode on the same key that it has been bound to in
18951 ;; Outline mode:
18952 ;; - "overridden": key used for a different functionality in Org mode
18953 ;; - else: key still bound to the same Outline function in Org mode
18955 ;; | Outline function | key binding | Org replacement |
18956 ;; |------------------------------------+-------------+-----------------------|
18957 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18958 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18959 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18960 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18961 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18962 ;; | `show-entry' | overridden | no replacement |
18963 ;; | `show-children' | `C-c C-i' | visibility cycling |
18964 ;; | `show-branches' | `C-c C-k' | still same function |
18965 ;; | `show-subtree' | overridden | visibility cycling |
18966 ;; | `show-all' | overridden | no replacement |
18967 ;; | `hide-subtree' | overridden | visibility cycling |
18968 ;; | `hide-body' | overridden | no replacement |
18969 ;; | `hide-entry' | overridden | visibility cycling |
18970 ;; | `hide-leaves' | overridden | no replacement |
18971 ;; | `hide-sublevels' | overridden | no replacement |
18972 ;; | `hide-other' | overridden | no replacement |
18974 ;; Make `C-c C-x' a prefix key
18975 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18977 ;; TAB key with modifiers
18978 (org-defkey org-mode-map "\C-i" 'org-cycle)
18979 (org-defkey org-mode-map [(tab)] 'org-cycle)
18980 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18981 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18982 ;; The following line is necessary under Suse GNU/Linux
18983 (unless (featurep 'xemacs)
18984 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18985 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18986 (define-key org-mode-map [backtab] 'org-shifttab)
18988 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18989 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18990 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18992 ;; Cursor keys with modifiers
18993 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18994 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18995 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18996 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18998 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18999 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19000 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19001 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19003 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19004 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19005 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19006 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19008 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19009 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19010 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19011 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19013 ;; Babel keys
19014 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19015 (mapc (lambda (pair)
19016 (define-key org-babel-map (car pair) (cdr pair)))
19017 org-babel-key-bindings)
19019 ;;; Extra keys for tty access.
19020 ;; We only set them when really needed because otherwise the
19021 ;; menus don't show the simple keys
19023 (when (or org-use-extra-keys
19024 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19025 (not window-system))
19026 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19027 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19028 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19029 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19030 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19031 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19032 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19033 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19034 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19035 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19036 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19037 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19038 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19039 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19040 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19041 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19042 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19043 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19044 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19045 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19046 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19047 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19048 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19049 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19050 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19051 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19052 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19053 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19055 ;; All the other keys
19057 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19058 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19059 (if (boundp 'narrow-map)
19060 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19061 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19062 (if (boundp 'narrow-map)
19063 (org-defkey narrow-map "b" 'org-narrow-to-block)
19064 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19065 (if (boundp 'narrow-map)
19066 (org-defkey narrow-map "e" 'org-narrow-to-element)
19067 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19068 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19069 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19070 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19071 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19072 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19073 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19074 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19075 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19076 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19077 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19078 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19079 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19080 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19081 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19082 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19083 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19084 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19085 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19086 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19087 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19088 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19089 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19090 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19091 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19092 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19093 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19094 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19095 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19096 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19097 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19098 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19099 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19100 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19101 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19102 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19103 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19104 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19105 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19106 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19107 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19108 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19109 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19110 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19111 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19112 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19113 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19114 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19115 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19116 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19117 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19118 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19119 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19120 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19121 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19122 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19123 (org-defkey org-mode-map "\C-c^" 'org-sort)
19124 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19125 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19126 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19127 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19128 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19129 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19130 (org-defkey org-mode-map "\C-m" 'org-return)
19131 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19132 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19133 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19134 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19135 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19136 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19137 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19138 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19139 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19140 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19141 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19142 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19143 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19144 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19145 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19146 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19147 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19148 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19149 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19150 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19151 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19152 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19153 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19155 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19156 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19157 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19159 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19160 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19161 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19162 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19163 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19164 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19165 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19166 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19167 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19168 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19169 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19170 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19171 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19172 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19173 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19174 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19175 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19176 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19177 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19178 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19179 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19180 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19181 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19183 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19184 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19185 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19186 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19187 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19189 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19191 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19193 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19194 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19196 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19199 (when (featurep 'xemacs)
19200 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19203 (defconst org-speed-commands-default
19205 ("Outline Navigation")
19206 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19207 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19208 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19209 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19210 ("F" . org-next-block)
19211 ("B" . org-previous-block)
19212 ("u" . (org-speed-move-safe 'outline-up-heading))
19213 ("j" . org-goto)
19214 ("g" . (org-refile t))
19215 ("Outline Visibility")
19216 ("c" . org-cycle)
19217 ("C" . org-shifttab)
19218 (" " . org-display-outline-path)
19219 ("s" . org-narrow-to-subtree)
19220 ("=" . org-columns)
19221 ("Outline Structure Editing")
19222 ("U" . org-shiftmetaup)
19223 ("D" . org-shiftmetadown)
19224 ("r" . org-metaright)
19225 ("l" . org-metaleft)
19226 ("R" . org-shiftmetaright)
19227 ("L" . org-shiftmetaleft)
19228 ("i" . (progn (forward-char 1) (call-interactively
19229 'org-insert-heading-respect-content)))
19230 ("^" . org-sort)
19231 ("w" . org-refile)
19232 ("a" . org-archive-subtree-default-with-confirmation)
19233 ("@" . org-mark-subtree)
19234 ("#" . org-toggle-comment)
19235 ("Clock Commands")
19236 ("I" . org-clock-in)
19237 ("O" . org-clock-out)
19238 ("Meta Data Editing")
19239 ("t" . org-todo)
19240 ("," . (org-priority))
19241 ("0" . (org-priority ?\ ))
19242 ("1" . (org-priority ?A))
19243 ("2" . (org-priority ?B))
19244 ("3" . (org-priority ?C))
19245 (":" . org-set-tags-command)
19246 ("e" . org-set-effort)
19247 ("E" . org-inc-effort)
19248 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19249 (org-entry-put (point) "APPT_WARNTIME" m)))
19250 ("Agenda Views etc")
19251 ("v" . org-agenda)
19252 ("/" . org-sparse-tree)
19253 ("Misc")
19254 ("o" . org-open-at-point)
19255 ("?" . org-speed-command-help)
19256 ("<" . (org-agenda-set-restriction-lock 'subtree))
19257 (">" . (org-agenda-remove-restriction-lock))
19259 "The default speed commands.")
19261 (defun org-print-speed-command (e)
19262 (if (> (length (car e)) 1)
19263 (progn
19264 (princ "\n")
19265 (princ (car e))
19266 (princ "\n")
19267 (princ (make-string (length (car e)) ?-))
19268 (princ "\n"))
19269 (princ (car e))
19270 (princ " ")
19271 (if (symbolp (cdr e))
19272 (princ (symbol-name (cdr e)))
19273 (prin1 (cdr e)))
19274 (princ "\n")))
19276 (defun org-speed-command-help ()
19277 "Show the available speed commands."
19278 (interactive)
19279 (if (not org-use-speed-commands)
19280 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19281 (with-output-to-temp-buffer "*Help*"
19282 (princ "User-defined Speed commands\n===========================\n")
19283 (mapc 'org-print-speed-command org-speed-commands-user)
19284 (princ "\n")
19285 (princ "Built-in Speed commands\n=======================\n")
19286 (mapc 'org-print-speed-command org-speed-commands-default))
19287 (with-current-buffer "*Help*"
19288 (setq truncate-lines t))))
19290 (defun org-speed-move-safe (cmd)
19291 "Execute CMD, but make sure that the cursor always ends up in a headline.
19292 If not, return to the original position and throw an error."
19293 (interactive)
19294 (let ((pos (point)))
19295 (call-interactively cmd)
19296 (unless (and (bolp) (org-at-heading-p))
19297 (goto-char pos)
19298 (error "Boundary reached while executing %s" cmd))))
19300 (defvar org-self-insert-command-undo-counter 0)
19302 (defvar org-table-auto-blank-field) ; defined in org-table.el
19303 (defvar org-speed-command nil)
19305 (define-obsolete-function-alias
19306 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19308 (defun org-speed-command-activate (keys)
19309 "Hook for activating single-letter speed commands.
19310 `org-speed-commands-default' specifies a minimal command set.
19311 Use `org-speed-commands-user' for further customization."
19312 (when (or (and (bolp) (looking-at org-outline-regexp))
19313 (and (functionp org-use-speed-commands)
19314 (funcall org-use-speed-commands)))
19315 (cdr (assoc keys (append org-speed-commands-user
19316 org-speed-commands-default)))))
19318 (define-obsolete-function-alias
19319 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19321 (defun org-babel-speed-command-activate (keys)
19322 "Hook for activating single-letter code block commands."
19323 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19324 (cdr (assoc keys org-babel-key-bindings))))
19326 (defcustom org-speed-command-hook
19327 '(org-speed-command-default-hook org-babel-speed-command-hook)
19328 "Hook for activating speed commands at strategic locations.
19329 Hook functions are called in sequence until a valid handler is
19330 found.
19332 Each hook takes a single argument, a user-pressed command key
19333 which is also a `self-insert-command' from the global map.
19335 Within the hook, examine the cursor position and the command key
19336 and return nil or a valid handler as appropriate. Handler could
19337 be one of an interactive command, a function, or a form.
19339 Set `org-use-speed-commands' to non-nil value to enable this
19340 hook. The default setting is `org-speed-command-activate'."
19341 :group 'org-structure
19342 :version "24.1"
19343 :type 'hook)
19345 (defun org-self-insert-command (N)
19346 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19347 If the cursor is in a table looking at whitespace, the whitespace is
19348 overwritten, and the table is not marked as requiring realignment."
19349 (interactive "p")
19350 (org-check-before-invisible-edit 'insert)
19351 (cond
19352 ((and org-use-speed-commands
19353 (setq org-speed-command
19354 (run-hook-with-args-until-success
19355 'org-speed-command-hook (this-command-keys))))
19356 (cond
19357 ((commandp org-speed-command)
19358 (setq this-command org-speed-command)
19359 (call-interactively org-speed-command))
19360 ((functionp org-speed-command)
19361 (funcall org-speed-command))
19362 ((and org-speed-command (listp org-speed-command))
19363 (eval org-speed-command))
19364 (t (let (org-use-speed-commands)
19365 (call-interactively 'org-self-insert-command)))))
19366 ((and
19367 (org-table-p)
19368 (progn
19369 ;; check if we blank the field, and if that triggers align
19370 (and (featurep 'org-table) org-table-auto-blank-field
19371 (member last-command
19372 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19373 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19374 ;; got extra space, this field does not determine column width
19375 (let (org-table-may-need-update) (org-table-blank-field))
19376 ;; no extra space, this field may determine column width
19377 (org-table-blank-field)))
19379 (eq N 1)
19380 (looking-at "[^|\n]* |"))
19381 (let (org-table-may-need-update)
19382 (goto-char (1- (match-end 0)))
19383 (backward-delete-char 1)
19384 (goto-char (match-beginning 0))
19385 (self-insert-command N)))
19387 (setq org-table-may-need-update t)
19388 (self-insert-command N)
19389 (org-fix-tags-on-the-fly)
19390 (if org-self-insert-cluster-for-undo
19391 (if (not (eq last-command 'org-self-insert-command))
19392 (setq org-self-insert-command-undo-counter 1)
19393 (if (>= org-self-insert-command-undo-counter 20)
19394 (setq org-self-insert-command-undo-counter 1)
19395 (and (> org-self-insert-command-undo-counter 0)
19396 buffer-undo-list (listp buffer-undo-list)
19397 (not (cadr buffer-undo-list)) ; remove nil entry
19398 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19399 (setq org-self-insert-command-undo-counter
19400 (1+ org-self-insert-command-undo-counter))))))))
19402 (defun org-check-before-invisible-edit (kind)
19403 "Check is editing if kind KIND would be dangerous with invisible text around.
19404 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19405 ;; First, try to get out of here as quickly as possible, to reduce overhead
19406 (if (and org-catch-invisible-edits
19407 (or (not (boundp 'visible-mode)) (not visible-mode))
19408 (or (get-char-property (point) 'invisible)
19409 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19410 ;; OK, we need to take a closer look
19411 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19412 (invisible-before-point (if (bobp) nil (get-char-property
19413 (1- (point)) 'invisible)))
19414 (border-and-ok-direction
19416 ;; Check if we are acting predictably before invisible text
19417 (and invisible-at-point (not invisible-before-point)
19418 (memq kind '(insert delete-backward)))
19419 ;; Check if we are acting predictably after invisible text
19420 ;; This works not well, and I have turned it off. It seems
19421 ;; better to always show and stop after invisible text.
19422 ;; (and (not invisible-at-point) invisible-before-point
19423 ;; (memq kind '(insert delete)))
19425 (when (or (memq invisible-at-point '(outline org-hide-block t))
19426 (memq invisible-before-point '(outline org-hide-block t)))
19427 (if (eq org-catch-invisible-edits 'error)
19428 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19429 (if (and org-custom-properties-overlays
19430 (y-or-n-p "Display invisible properties in this buffer? "))
19431 (org-toggle-custom-properties-visibility)
19432 ;; Make the area visible
19433 (save-excursion
19434 (if invisible-before-point
19435 (goto-char (previous-single-char-property-change
19436 (point) 'invisible)))
19437 (org-cycle))
19438 (cond
19439 ((eq org-catch-invisible-edits 'show)
19440 ;; That's it, we do the edit after showing
19441 (message
19442 "Unfolding invisible region around point before editing")
19443 (sit-for 1))
19444 ((and (eq org-catch-invisible-edits 'smart)
19445 border-and-ok-direction)
19446 (message "Unfolding invisible region around point before editing"))
19448 ;; Don't do the edit, make the user repeat it in full visibility
19449 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19451 (defun org-fix-tags-on-the-fly ()
19452 (when (and (equal (char-after (point-at-bol)) ?*)
19453 (org-at-heading-p))
19454 (org-align-tags-here org-tags-column)))
19456 (defun org-delete-backward-char (N)
19457 "Like `delete-backward-char', insert whitespace at field end in tables.
19458 When deleting backwards, in tables this function will insert whitespace in
19459 front of the next \"|\" separator, to keep the table aligned. The table will
19460 still be marked for re-alignment if the field did fill the entire column,
19461 because, in this case the deletion might narrow the column."
19462 (interactive "p")
19463 (save-match-data
19464 (org-check-before-invisible-edit 'delete-backward)
19465 (if (and (org-table-p)
19466 (eq N 1)
19467 (string-match "|" (buffer-substring (point-at-bol) (point)))
19468 (looking-at ".*?|"))
19469 (let ((pos (point))
19470 (noalign (looking-at "[^|\n\r]* |"))
19471 (c org-table-may-need-update))
19472 (backward-delete-char N)
19473 (if (not overwrite-mode)
19474 (progn
19475 (skip-chars-forward "^|")
19476 (insert " ")
19477 (goto-char (1- pos))))
19478 ;; noalign: if there were two spaces at the end, this field
19479 ;; does not determine the width of the column.
19480 (if noalign (setq org-table-may-need-update c)))
19481 (backward-delete-char N)
19482 (org-fix-tags-on-the-fly))))
19484 (defun org-delete-char (N)
19485 "Like `delete-char', but insert whitespace at field end in tables.
19486 When deleting characters, in tables this function will insert whitespace in
19487 front of the next \"|\" separator, to keep the table aligned. The table will
19488 still be marked for re-alignment if the field did fill the entire column,
19489 because, in this case the deletion might narrow the column."
19490 (interactive "p")
19491 (save-match-data
19492 (org-check-before-invisible-edit 'delete)
19493 (if (and (org-table-p)
19494 (not (bolp))
19495 (not (= (char-after) ?|))
19496 (eq N 1))
19497 (if (looking-at ".*?|")
19498 (let ((pos (point))
19499 (noalign (looking-at "[^|\n\r]* |"))
19500 (c org-table-may-need-update))
19501 (replace-match
19502 (concat (substring (match-string 0) 1 -1) " |") nil t)
19503 (goto-char pos)
19504 ;; noalign: if there were two spaces at the end, this field
19505 ;; does not determine the width of the column.
19506 (if noalign (setq org-table-may-need-update c)))
19507 (delete-char N))
19508 (delete-char N)
19509 (org-fix-tags-on-the-fly))))
19511 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19512 (put 'org-self-insert-command 'delete-selection t)
19513 (put 'orgtbl-self-insert-command 'delete-selection t)
19514 (put 'org-delete-char 'delete-selection 'supersede)
19515 (put 'org-delete-backward-char 'delete-selection 'supersede)
19516 (put 'org-yank 'delete-selection 'yank)
19518 ;; Make `flyspell-mode' delay after some commands
19519 (put 'org-self-insert-command 'flyspell-delayed t)
19520 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19521 (put 'org-delete-char 'flyspell-delayed t)
19522 (put 'org-delete-backward-char 'flyspell-delayed t)
19524 ;; Make pabbrev-mode expand after org-mode commands
19525 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19526 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19528 ;; How to do this: Measure non-white length of current string
19529 ;; If equal to column width, we should realign.
19531 (defun org-remap (map &rest commands)
19532 "In MAP, remap the functions given in COMMANDS.
19533 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19534 (let (new old)
19535 (while commands
19536 (setq old (pop commands) new (pop commands))
19537 (if (fboundp 'command-remapping)
19538 (org-defkey map (vector 'remap old) new)
19539 (substitute-key-definition old new map global-map)))))
19541 (defun org-transpose-words ()
19542 "Transpose words for Org.
19543 This uses the `org-mode-transpose-word-syntax-table' syntax
19544 table, which interprets characters in `org-emphasis-alist' as
19545 word constituants."
19546 (interactive)
19547 (with-syntax-table org-mode-transpose-word-syntax-table
19548 (call-interactively 'transpose-words)))
19549 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19551 (when (eq org-enable-table-editor 'optimized)
19552 ;; If the user wants maximum table support, we need to hijack
19553 ;; some standard editing functions
19554 (org-remap org-mode-map
19555 'self-insert-command 'org-self-insert-command
19556 'delete-char 'org-delete-char
19557 'delete-backward-char 'org-delete-backward-char)
19558 (org-defkey org-mode-map "|" 'org-force-self-insert))
19560 (defvar org-ctrl-c-ctrl-c-hook nil
19561 "Hook for functions attaching themselves to `C-c C-c'.
19563 This can be used to add additional functionality to the C-c C-c
19564 key which executes context-dependent commands. This hook is run
19565 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19566 run after the last test.
19568 Each function will be called with no arguments. The function
19569 must check if the context is appropriate for it to act. If yes,
19570 it should do its thing and then return a non-nil value. If the
19571 context is wrong, just do nothing and return nil.")
19573 (defvar org-ctrl-c-ctrl-c-final-hook nil
19574 "Hook for functions attaching themselves to `C-c C-c'.
19576 This can be used to add additional functionality to the C-c C-c
19577 key which executes context-dependent commands. This hook is run
19578 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19579 before the first test.
19581 Each function will be called with no arguments. The function
19582 must check if the context is appropriate for it to act. If yes,
19583 it should do its thing and then return a non-nil value. If the
19584 context is wrong, just do nothing and return nil.")
19586 (defvar org-tab-first-hook nil
19587 "Hook for functions to attach themselves to TAB.
19588 See `org-ctrl-c-ctrl-c-hook' for more information.
19589 This hook runs as the first action when TAB is pressed, even before
19590 `org-cycle' messes around with the `outline-regexp' to cater for
19591 inline tasks and plain list item folding.
19592 If any function in this hook returns t, any other actions that
19593 would have been caused by TAB (such as table field motion or visibility
19594 cycling) will not occur.")
19596 (defvar org-tab-after-check-for-table-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 it has been established that the cursor is not in a
19600 table, but before checking if the cursor is in a headline or if global cycling
19601 should be done.
19602 If any function in this hook returns t, not other actions like visibility
19603 cycling will be done.")
19605 (defvar org-tab-after-check-for-cycling-hook nil
19606 "Hook for functions to attach themselves to TAB.
19607 See `org-ctrl-c-ctrl-c-hook' for more information.
19608 This hook runs after it has been established that not table field motion and
19609 not visibility should be done because of current context. This is probably
19610 the place where a package like yasnippets can hook in.")
19612 (defvar org-tab-before-tab-emulation-hook nil
19613 "Hook for functions to attach themselves to TAB.
19614 See `org-ctrl-c-ctrl-c-hook' for more information.
19615 This hook runs after every other options for TAB have been exhausted, but
19616 before indentation and \t insertion takes place.")
19618 (defvar org-metaleft-hook nil
19619 "Hook for functions attaching themselves to `M-left'.
19620 See `org-ctrl-c-ctrl-c-hook' for more information.")
19621 (defvar org-metaright-hook nil
19622 "Hook for functions attaching themselves to `M-right'.
19623 See `org-ctrl-c-ctrl-c-hook' for more information.")
19624 (defvar org-metaup-hook nil
19625 "Hook for functions attaching themselves to `M-up'.
19626 See `org-ctrl-c-ctrl-c-hook' for more information.")
19627 (defvar org-metadown-hook nil
19628 "Hook for functions attaching themselves to `M-down'.
19629 See `org-ctrl-c-ctrl-c-hook' for more information.")
19630 (defvar org-shiftmetaleft-hook nil
19631 "Hook for functions attaching themselves to `M-S-left'.
19632 See `org-ctrl-c-ctrl-c-hook' for more information.")
19633 (defvar org-shiftmetaright-hook nil
19634 "Hook for functions attaching themselves to `M-S-right'.
19635 See `org-ctrl-c-ctrl-c-hook' for more information.")
19636 (defvar org-shiftmetaup-hook nil
19637 "Hook for functions attaching themselves to `M-S-up'.
19638 See `org-ctrl-c-ctrl-c-hook' for more information.")
19639 (defvar org-shiftmetadown-hook nil
19640 "Hook for functions attaching themselves to `M-S-down'.
19641 See `org-ctrl-c-ctrl-c-hook' for more information.")
19642 (defvar org-metareturn-hook nil
19643 "Hook for functions attaching themselves to `M-RET'.
19644 See `org-ctrl-c-ctrl-c-hook' for more information.")
19645 (defvar org-shiftup-hook nil
19646 "Hook for functions attaching themselves to `S-up'.
19647 See `org-ctrl-c-ctrl-c-hook' for more information.")
19648 (defvar org-shiftup-final-hook nil
19649 "Hook for functions attaching themselves to `S-up'.
19650 This one runs after all other options except shift-select have been excluded.
19651 See `org-ctrl-c-ctrl-c-hook' for more information.")
19652 (defvar org-shiftdown-hook nil
19653 "Hook for functions attaching themselves to `S-down'.
19654 See `org-ctrl-c-ctrl-c-hook' for more information.")
19655 (defvar org-shiftdown-final-hook nil
19656 "Hook for functions attaching themselves to `S-down'.
19657 This one runs after all other options except shift-select have been excluded.
19658 See `org-ctrl-c-ctrl-c-hook' for more information.")
19659 (defvar org-shiftleft-hook nil
19660 "Hook for functions attaching themselves to `S-left'.
19661 See `org-ctrl-c-ctrl-c-hook' for more information.")
19662 (defvar org-shiftleft-final-hook nil
19663 "Hook for functions attaching themselves to `S-left'.
19664 This one runs after all other options except shift-select have been excluded.
19665 See `org-ctrl-c-ctrl-c-hook' for more information.")
19666 (defvar org-shiftright-hook nil
19667 "Hook for functions attaching themselves to `S-right'.
19668 See `org-ctrl-c-ctrl-c-hook' for more information.")
19669 (defvar org-shiftright-final-hook nil
19670 "Hook for functions attaching themselves to `S-right'.
19671 This one runs after all other options except shift-select have been excluded.
19672 See `org-ctrl-c-ctrl-c-hook' for more information.")
19674 (defun org-modifier-cursor-error ()
19675 "Throw an error, a modified cursor command was applied in wrong context."
19676 (user-error "This command is active in special context like tables, headlines or items"))
19678 (defun org-shiftselect-error ()
19679 "Throw an error because Shift-Cursor command was applied in wrong context."
19680 (if (and (boundp 'shift-select-mode) shift-select-mode)
19681 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19682 (user-error "This command works only in special context like headlines or timestamps")))
19684 (defun org-call-for-shift-select (cmd)
19685 (let ((this-command-keys-shift-translated t))
19686 (call-interactively cmd)))
19688 (defun org-shifttab (&optional arg)
19689 "Global visibility cycling or move to previous table field.
19690 Call `org-table-previous-field' within a table.
19691 When ARG is nil, cycle globally through visibility states.
19692 When ARG is a numeric prefix, show contents of this level."
19693 (interactive "P")
19694 (cond
19695 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19696 ((integerp arg)
19697 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19698 (message "Content view to level: %d" arg)
19699 (org-content (prefix-numeric-value arg2))
19700 (org-cycle-show-empty-lines t)
19701 (setq org-cycle-global-status 'overview)))
19702 (t (call-interactively 'org-global-cycle))))
19704 (defun org-shiftmetaleft ()
19705 "Promote subtree or delete table column.
19706 Calls `org-promote-subtree', `org-outdent-item-tree', or
19707 `org-table-delete-column', depending on context. See the
19708 individual commands for more information."
19709 (interactive)
19710 (cond
19711 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19712 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19713 ((org-at-heading-p) (call-interactively 'org-promote-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-outdent-item-tree))
19718 (t (org-modifier-cursor-error))))
19720 (defun org-shiftmetaright ()
19721 "Demote subtree or insert table column.
19722 Calls `org-demote-subtree', `org-indent-item-tree', or
19723 `org-table-insert-column', depending on context. See the
19724 individual commands for more information."
19725 (interactive)
19726 (cond
19727 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19728 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19729 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19730 ((if (not (org-region-active-p)) (org-at-item-p)
19731 (save-excursion (goto-char (region-beginning))
19732 (org-at-item-p)))
19733 (call-interactively 'org-indent-item-tree))
19734 (t (org-modifier-cursor-error))))
19736 (defun org-shiftmetaup (&optional arg)
19737 "Move subtree up or kill table row.
19738 Calls `org-move-subtree-up' or `org-table-kill-row' or
19739 `org-move-item-up' or `org-timestamp-up', depending on context.
19740 See the individual commands for more information."
19741 (interactive "P")
19742 (cond
19743 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19744 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19745 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19746 ((org-at-item-p) (call-interactively 'org-move-item-up))
19747 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19748 (call-interactively 'org-timestamp-up)))
19749 (t (call-interactively 'org-drag-line-backward))))
19751 (defun org-shiftmetadown (&optional arg)
19752 "Move subtree down or insert table row.
19753 Calls `org-move-subtree-down' or `org-table-insert-row' or
19754 `org-move-item-down' or `org-timestamp-up', depending on context.
19755 See the individual commands for more information."
19756 (interactive "P")
19757 (cond
19758 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19759 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19760 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19761 ((org-at-item-p) (call-interactively 'org-move-item-down))
19762 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19763 (call-interactively 'org-timestamp-down)))
19764 (t (call-interactively 'org-drag-line-forward))))
19766 (defsubst org-hidden-tree-error ()
19767 (user-error
19768 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19770 (defun org-metaleft (&optional arg)
19771 "Promote heading or move table column to left.
19772 Calls `org-do-promote' or `org-table-move-column', depending on context.
19773 With no specific context, calls the Emacs default `backward-word'.
19774 See the individual commands for more information."
19775 (interactive "P")
19776 (cond
19777 ((run-hook-with-args-until-success 'org-metaleft-hook))
19778 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19779 ((org-with-limited-levels
19780 (or (org-at-heading-p)
19781 (and (org-region-active-p)
19782 (save-excursion
19783 (goto-char (region-beginning))
19784 (org-at-heading-p)))))
19785 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19786 (call-interactively 'org-do-promote))
19787 ;; At an inline task.
19788 ((org-at-heading-p)
19789 (call-interactively 'org-inlinetask-promote))
19790 ((or (org-at-item-p)
19791 (and (org-region-active-p)
19792 (save-excursion
19793 (goto-char (region-beginning))
19794 (org-at-item-p))))
19795 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19796 (call-interactively 'org-outdent-item))
19797 (t (call-interactively 'backward-word))))
19799 (defun org-metaright (&optional arg)
19800 "Demote a subtree, a list item or move table column to right.
19801 In front of a drawer or a block keyword, indent it correctly.
19802 With no specific context, calls the Emacs default `forward-word'.
19803 See the individual commands for more information."
19804 (interactive "P")
19805 (cond
19806 ((run-hook-with-args-until-success 'org-metaright-hook))
19807 ((org-at-table-p) (call-interactively 'org-table-move-column))
19808 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19809 ((org-at-block-p) (call-interactively 'org-indent-block))
19810 ((org-with-limited-levels
19811 (or (org-at-heading-p)
19812 (and (org-region-active-p)
19813 (save-excursion
19814 (goto-char (region-beginning))
19815 (org-at-heading-p)))))
19816 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19817 (call-interactively 'org-do-demote))
19818 ;; At an inline task.
19819 ((org-at-heading-p)
19820 (call-interactively 'org-inlinetask-demote))
19821 ((or (org-at-item-p)
19822 (and (org-region-active-p)
19823 (save-excursion
19824 (goto-char (region-beginning))
19825 (org-at-item-p))))
19826 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19827 (call-interactively 'org-indent-item))
19828 (t (call-interactively 'forward-word))))
19830 (defun org-check-for-hidden (what)
19831 "Check if there are hidden headlines/items in the current visual line.
19832 WHAT can be either `headlines' or `items'. If the current line is
19833 an outline or item heading and it has a folded subtree below it,
19834 this function returns t, nil otherwise."
19835 (let ((re (cond
19836 ((eq what 'headlines) org-outline-regexp-bol)
19837 ((eq what 'items) (org-item-beginning-re))
19838 (t (error "This should not happen"))))
19839 beg end)
19840 (save-excursion
19841 (catch 'exit
19842 (unless (org-region-active-p)
19843 (setq beg (point-at-bol))
19844 (beginning-of-line 2)
19845 (while (and (not (eobp)) ;; this is like `next-line'
19846 (get-char-property (1- (point)) 'invisible))
19847 (beginning-of-line 2))
19848 (setq end (point))
19849 (goto-char beg)
19850 (goto-char (point-at-eol))
19851 (setq end (max end (point)))
19852 (while (re-search-forward re end t)
19853 (if (get-char-property (match-beginning 0) 'invisible)
19854 (throw 'exit t))))
19855 nil))))
19857 (defun org-metaup (&optional arg)
19858 "Move subtree up or move table row up.
19859 Calls `org-move-subtree-up' or `org-table-move-row' or
19860 `org-move-item-up', depending on context. See the individual commands
19861 for more information."
19862 (interactive "P")
19863 (cond
19864 ((run-hook-with-args-until-success 'org-metaup-hook))
19865 ((org-region-active-p)
19866 (let* ((a (min (region-beginning) (region-end)))
19867 (b (1- (max (region-beginning) (region-end))))
19868 (c (save-excursion (goto-char a)
19869 (move-beginning-of-line 0)))
19870 (d (save-excursion (goto-char a)
19871 (move-end-of-line 0) (point))))
19872 (transpose-regions a b c d)
19873 (goto-char c)))
19874 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19875 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19876 ((org-at-item-p) (call-interactively 'org-move-item-up))
19877 (t (org-drag-element-backward))))
19879 (defun org-metadown (&optional arg)
19880 "Move subtree down or move table row down.
19881 Calls `org-move-subtree-down' or `org-table-move-row' or
19882 `org-move-item-down', depending on context. See the individual
19883 commands for more information."
19884 (interactive "P")
19885 (cond
19886 ((run-hook-with-args-until-success 'org-metadown-hook))
19887 ((org-region-active-p)
19888 (let* ((a (min (region-beginning) (region-end)))
19889 (b (max (region-beginning) (region-end)))
19890 (c (save-excursion (goto-char b)
19891 (move-beginning-of-line 1)))
19892 (d (save-excursion (goto-char b)
19893 (move-end-of-line 1) (1+ (point)))))
19894 (transpose-regions a b c d)
19895 (goto-char d)))
19896 ((org-at-table-p) (call-interactively 'org-table-move-row))
19897 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19898 ((org-at-item-p) (call-interactively 'org-move-item-down))
19899 (t (org-drag-element-forward))))
19901 (defun org-shiftup (&optional arg)
19902 "Increase item in timestamp or increase priority of current headline.
19903 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19904 depending on context. See the individual commands for more information."
19905 (interactive "P")
19906 (cond
19907 ((run-hook-with-args-until-success 'org-shiftup-hook))
19908 ((and org-support-shift-select (org-region-active-p))
19909 (org-call-for-shift-select 'previous-line))
19910 ((org-at-timestamp-p t)
19911 (call-interactively (if org-edit-timestamp-down-means-later
19912 'org-timestamp-down 'org-timestamp-up)))
19913 ((and (not (eq org-support-shift-select 'always))
19914 org-enable-priority-commands
19915 (org-at-heading-p))
19916 (call-interactively 'org-priority-up))
19917 ((and (not org-support-shift-select) (org-at-item-p))
19918 (call-interactively 'org-previous-item))
19919 ((org-clocktable-try-shift 'up arg))
19920 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19921 (org-support-shift-select
19922 (org-call-for-shift-select 'previous-line))
19923 (t (org-shiftselect-error))))
19925 (defun org-shiftdown (&optional arg)
19926 "Decrease item in timestamp or decrease priority of current headline.
19927 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19928 depending on context. See the individual commands for more information."
19929 (interactive "P")
19930 (cond
19931 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19932 ((and org-support-shift-select (org-region-active-p))
19933 (org-call-for-shift-select 'next-line))
19934 ((org-at-timestamp-p t)
19935 (call-interactively (if org-edit-timestamp-down-means-later
19936 'org-timestamp-up 'org-timestamp-down)))
19937 ((and (not (eq org-support-shift-select 'always))
19938 org-enable-priority-commands
19939 (org-at-heading-p))
19940 (call-interactively 'org-priority-down))
19941 ((and (not org-support-shift-select) (org-at-item-p))
19942 (call-interactively 'org-next-item))
19943 ((org-clocktable-try-shift 'down arg))
19944 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19945 (org-support-shift-select
19946 (org-call-for-shift-select 'next-line))
19947 (t (org-shiftselect-error))))
19949 (defun org-shiftright (&optional arg)
19950 "Cycle the thing at point or in the current line, depending on context.
19951 Depending on context, this does one of the following:
19953 - switch a timestamp at point one day into the future
19954 - on a headline, switch to the next TODO keyword.
19955 - on an item, switch entire list to the next bullet type
19956 - on a property line, switch to the next allowed value
19957 - on a clocktable definition line, move time block into the future"
19958 (interactive "P")
19959 (cond
19960 ((run-hook-with-args-until-success 'org-shiftright-hook))
19961 ((and org-support-shift-select (org-region-active-p))
19962 (org-call-for-shift-select 'forward-char))
19963 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19964 ((and (not (eq org-support-shift-select 'always))
19965 (org-at-heading-p))
19966 (let ((org-inhibit-logging
19967 (not org-treat-S-cursor-todo-selection-as-state-change))
19968 (org-inhibit-blocking
19969 (not org-treat-S-cursor-todo-selection-as-state-change)))
19970 (org-call-with-arg 'org-todo 'right)))
19971 ((or (and org-support-shift-select
19972 (not (eq org-support-shift-select 'always))
19973 (org-at-item-bullet-p))
19974 (and (not org-support-shift-select) (org-at-item-p)))
19975 (org-call-with-arg 'org-cycle-list-bullet nil))
19976 ((and (not (eq org-support-shift-select 'always))
19977 (org-at-property-p))
19978 (call-interactively 'org-property-next-allowed-value))
19979 ((org-clocktable-try-shift 'right arg))
19980 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19981 (org-support-shift-select
19982 (org-call-for-shift-select 'forward-char))
19983 (t (org-shiftselect-error))))
19985 (defun org-shiftleft (&optional arg)
19986 "Cycle the thing at point or in the current line, depending on context.
19987 Depending on context, this does one of the following:
19989 - switch a timestamp at point one day into the past
19990 - on a headline, switch to the previous TODO keyword.
19991 - on an item, switch entire list to the previous bullet type
19992 - on a property line, switch to the previous allowed value
19993 - on a clocktable definition line, move time block into the past"
19994 (interactive "P")
19995 (cond
19996 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19997 ((and org-support-shift-select (org-region-active-p))
19998 (org-call-for-shift-select 'backward-char))
19999 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20000 ((and (not (eq org-support-shift-select 'always))
20001 (org-at-heading-p))
20002 (let ((org-inhibit-logging
20003 (not org-treat-S-cursor-todo-selection-as-state-change))
20004 (org-inhibit-blocking
20005 (not org-treat-S-cursor-todo-selection-as-state-change)))
20006 (org-call-with-arg 'org-todo 'left)))
20007 ((or (and org-support-shift-select
20008 (not (eq org-support-shift-select 'always))
20009 (org-at-item-bullet-p))
20010 (and (not org-support-shift-select) (org-at-item-p)))
20011 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20012 ((and (not (eq org-support-shift-select 'always))
20013 (org-at-property-p))
20014 (call-interactively 'org-property-previous-allowed-value))
20015 ((org-clocktable-try-shift 'left arg))
20016 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20017 (org-support-shift-select
20018 (org-call-for-shift-select 'backward-char))
20019 (t (org-shiftselect-error))))
20021 (defun org-shiftcontrolright ()
20022 "Switch to next TODO set."
20023 (interactive)
20024 (cond
20025 ((and org-support-shift-select (org-region-active-p))
20026 (org-call-for-shift-select 'forward-word))
20027 ((and (not (eq org-support-shift-select 'always))
20028 (org-at-heading-p))
20029 (org-call-with-arg 'org-todo 'nextset))
20030 (org-support-shift-select
20031 (org-call-for-shift-select 'forward-word))
20032 (t (org-shiftselect-error))))
20034 (defun org-shiftcontrolleft ()
20035 "Switch to previous TODO set."
20036 (interactive)
20037 (cond
20038 ((and org-support-shift-select (org-region-active-p))
20039 (org-call-for-shift-select 'backward-word))
20040 ((and (not (eq org-support-shift-select 'always))
20041 (org-at-heading-p))
20042 (org-call-with-arg 'org-todo 'previousset))
20043 (org-support-shift-select
20044 (org-call-for-shift-select 'backward-word))
20045 (t (org-shiftselect-error))))
20047 (defun org-shiftcontrolup (&optional n)
20048 "Change timestamps synchronously up in CLOCK log lines.
20049 Optional argument N tells to change by that many units."
20050 (interactive "P")
20051 (cond ((and (not org-support-shift-select)
20052 (org-at-clock-log-p)
20053 (org-at-timestamp-p t))
20054 (org-clock-timestamps-up n))
20055 (t (org-shiftselect-error))))
20057 (defun org-shiftcontroldown (&optional n)
20058 "Change timestamps synchronously down in CLOCK log lines.
20059 Optional argument N tells to change by that many units."
20060 (interactive "P")
20061 (cond ((and (not org-support-shift-select)
20062 (org-at-clock-log-p)
20063 (org-at-timestamp-p t))
20064 (org-clock-timestamps-down n))
20065 (t (org-shiftselect-error))))
20067 (defun org-ctrl-c-ret ()
20068 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20069 (interactive)
20070 (cond
20071 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20072 (t (call-interactively 'org-insert-heading))))
20074 (defun org-find-visible ()
20075 (let ((s (point)))
20076 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20077 (get-char-property s 'invisible)))
20079 (defun org-find-invisible ()
20080 (let ((s (point)))
20081 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20082 (not (get-char-property s 'invisible))))
20085 (defun org-copy-visible (beg end)
20086 "Copy the visible parts of the region."
20087 (interactive "r")
20088 (let (snippets s)
20089 (save-excursion
20090 (save-restriction
20091 (narrow-to-region beg end)
20092 (setq s (goto-char (point-min)))
20093 (while (not (= (point) (point-max)))
20094 (goto-char (org-find-invisible))
20095 (push (buffer-substring s (point)) snippets)
20096 (setq s (goto-char (org-find-visible))))))
20097 (kill-new (apply 'concat (nreverse snippets)))))
20099 (defun org-copy-special ()
20100 "Copy region in table or copy current subtree.
20101 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20102 See the individual commands for more information."
20103 (interactive)
20104 (call-interactively
20105 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20107 (defun org-cut-special ()
20108 "Cut region in table or cut current subtree.
20109 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20110 See the individual commands for more information."
20111 (interactive)
20112 (call-interactively
20113 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20115 (defun org-paste-special (arg)
20116 "Paste rectangular region into table, or past subtree relative to level.
20117 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20118 See the individual commands for more information."
20119 (interactive "P")
20120 (if (org-at-table-p)
20121 (org-table-paste-rectangle)
20122 (org-paste-subtree arg)))
20124 (defsubst org-in-fixed-width-region-p ()
20125 "Is point in a fixed-width region?"
20126 (save-match-data
20127 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20129 (defun org-edit-special (&optional arg)
20130 "Call a special editor for the element at point.
20131 When at a table, call the formula editor with `org-table-edit-formulas'.
20132 When in a source code block, call `org-edit-src-code'.
20133 When in a fixed-width region, call `org-edit-fixed-width-region'.
20134 When at an #+INCLUDE keyword, visit the included file.
20135 On a link, call `ffap' to visit the link at point.
20136 Otherwise, return a user error."
20137 (interactive "P")
20138 (let ((element (org-element-at-point)))
20139 (assert (not buffer-read-only) nil
20140 "Buffer is read-only: %s" (buffer-name))
20141 (case (org-element-type element)
20142 (src-block
20143 (if (not arg) (org-edit-src-code)
20144 (let* ((info (org-babel-get-src-block-info))
20145 (lang (nth 0 info))
20146 (params (nth 2 info))
20147 (session (cdr (assq :session params))))
20148 (if (not session) (org-edit-src-code)
20149 ;; At a src-block with a session and function called with
20150 ;; an ARG: switch to the buffer related to the inferior
20151 ;; process.
20152 (switch-to-buffer
20153 (funcall (intern (concat "org-babel-prep-session:" lang))
20154 session params))))))
20155 (keyword
20156 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20157 (find-file
20158 (org-remove-double-quotes
20159 (car (org-split-string (org-element-property :value element)))))
20160 (user-error "No special environment to edit here")))
20161 (table
20162 (if (eq (org-element-property :type element) 'table.el)
20163 (org-edit-src-code)
20164 (call-interactively 'org-table-edit-formulas)))
20165 ;; Only Org tables contain `table-row' type elements.
20166 (table-row (call-interactively 'org-table-edit-formulas))
20167 ((example-block export-block) (org-edit-src-code))
20168 (fixed-width (org-edit-fixed-width-region))
20169 (otherwise
20170 ;; No notable element at point. Though, we may be at a link,
20171 ;; which is an object. Thus, scan deeper.
20172 (if (eq (org-element-type (org-element-context element)) 'link)
20173 (call-interactively 'ffap)
20174 (user-error "No special environment to edit here"))))))
20176 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20177 (defun org-ctrl-c-ctrl-c (&optional arg)
20178 "Set tags in headline, or update according to changed information at point.
20180 This command does many different things, depending on context:
20182 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20183 this is what we do.
20185 - If the cursor is on a statistics cookie, update it.
20187 - If the cursor is in a headline, prompt for tags and insert them
20188 into the current line, aligned to `org-tags-column'. When called
20189 with prefix arg, realign all tags in the current buffer.
20191 - If the cursor is in one of the special #+KEYWORD lines, this
20192 triggers scanning the buffer for these lines and updating the
20193 information.
20195 - If the cursor is inside a table, realign the table. This command
20196 works even if the automatic table editor has been turned off.
20198 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20199 the entire table.
20201 - If the cursor is at a footnote reference or definition, jump to
20202 the corresponding definition or references, respectively.
20204 - If the cursor is a the beginning of a dynamic block, update it.
20206 - If the current buffer is a capture buffer, close note and file it.
20208 - If the cursor is on a <<<target>>>, update radio targets and
20209 corresponding links in this buffer.
20211 - If the cursor is on a numbered item in a plain list, renumber the
20212 ordered list.
20214 - If the cursor is on a checkbox, toggle it.
20216 - If the cursor is on a code block, evaluate it. The variable
20217 `org-confirm-babel-evaluate' can be used to control prompting
20218 before code block evaluation, by default every code block
20219 evaluation requires confirmation. Code block evaluation can be
20220 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20221 (interactive "P")
20222 (cond
20223 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20224 org-occur-highlights
20225 org-latex-fragment-image-overlays)
20226 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20227 (org-remove-occur-highlights)
20228 (org-remove-latex-fragment-image-overlays)
20229 (message "Temporary highlights/overlays removed from current buffer"))
20230 ((and (local-variable-p 'org-finish-function (current-buffer))
20231 (fboundp org-finish-function))
20232 (funcall org-finish-function))
20233 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20235 (let* ((context (org-element-context)) (type (org-element-type context)))
20236 ;; Test if point is within a blank line.
20237 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20238 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20239 (user-error "C-c C-c can do nothing useful at this location"))
20240 ;; When at a link, act according to the parent instead.
20241 (when (eq type 'link)
20242 (setq context (org-element-property :parent context))
20243 (setq type (org-element-type context)))
20244 ;; For convenience: at the first line of a paragraph on the
20245 ;; same line as an item, apply function on that item instead.
20246 (when (eq type 'paragraph)
20247 (let ((parent (org-element-property :parent context)))
20248 (when (and (eq (org-element-type parent) 'item)
20249 (= (point-at-bol) (org-element-property :begin parent)))
20250 (setq context parent type 'item))))
20251 ;; Act according to type of element or object at point.
20252 (case type
20253 (clock (org-clock-update-time-maybe))
20254 (dynamic-block
20255 (save-excursion
20256 (goto-char (org-element-property :post-affiliated context))
20257 (org-update-dblock)))
20258 (footnote-definition
20259 (goto-char (org-element-property :post-affiliated context))
20260 (call-interactively 'org-footnote-action))
20261 (footnote-reference (call-interactively 'org-footnote-action))
20262 ((headline inlinetask)
20263 (save-excursion (goto-char (org-element-property :begin context))
20264 (call-interactively 'org-set-tags)))
20265 (item
20266 ;; At an item: a double C-u set checkbox to "[-]"
20267 ;; unconditionally, whereas a single one will toggle its
20268 ;; presence. Without an universal argument, if the item
20269 ;; has a checkbox, toggle it. Otherwise repair the list.
20270 (let* ((box (org-element-property :checkbox context))
20271 (struct (org-element-property :structure context))
20272 (old-struct (copy-tree struct))
20273 (parents (org-list-parents-alist struct))
20274 (prevs (org-list-prevs-alist struct))
20275 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20276 (org-list-set-checkbox
20277 (org-element-property :begin context) struct
20278 (cond ((equal arg '(16)) "[-]")
20279 ((and (not box) (equal arg '(4))) "[ ]")
20280 ((or (not box) (equal arg '(4))) nil)
20281 ((eq box 'on) "[ ]")
20282 (t "[X]")))
20283 ;; Mimic `org-list-write-struct' but with grabbing
20284 ;; a return value from `org-list-struct-fix-box'.
20285 (org-list-struct-fix-ind struct parents 2)
20286 (org-list-struct-fix-item-end struct)
20287 (org-list-struct-fix-bul struct prevs)
20288 (org-list-struct-fix-ind struct parents)
20289 (let ((block-item
20290 (org-list-struct-fix-box struct parents prevs orderedp)))
20291 (if (and box (equal struct old-struct))
20292 (if (equal arg '(16))
20293 (message "Checkboxes already reset")
20294 (user-error "Cannot toggle this checkbox: %s"
20295 (if (eq box 'on)
20296 "all subitems checked"
20297 "unchecked subitems")))
20298 (org-list-struct-apply-struct struct old-struct)
20299 (org-update-checkbox-count-maybe))
20300 (when block-item
20301 (message "Checkboxes were removed due to empty box at line %d"
20302 (org-current-line block-item))))))
20303 (keyword
20304 (let ((org-inhibit-startup-visibility-stuff t)
20305 (org-startup-align-all-tables nil))
20306 (when (boundp 'org-table-coordinate-overlays)
20307 (mapc 'delete-overlay org-table-coordinate-overlays)
20308 (setq org-table-coordinate-overlays nil))
20309 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20310 (message "Local setup has been refreshed"))
20311 (plain-list
20312 ;; At a plain list, with a double C-u argument, set
20313 ;; checkboxes of each item to "[-]", whereas a single one
20314 ;; will toggle their presence according to the state of the
20315 ;; first item in the list. Without an argument, repair the
20316 ;; list.
20317 (let* ((begin (org-element-property :contents-begin context))
20318 (beginm (move-marker (make-marker) begin))
20319 (struct (org-element-property :structure context))
20320 (old-struct (copy-tree struct))
20321 (first-box (save-excursion
20322 (goto-char begin)
20323 (looking-at org-list-full-item-re)
20324 (match-string-no-properties 3)))
20325 (new-box (cond ((equal arg '(16)) "[-]")
20326 ((equal arg '(4)) (unless first-box "[ ]"))
20327 ((equal first-box "[X]") "[ ]")
20328 (t "[X]"))))
20329 (cond
20330 (arg
20331 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20332 (org-list-get-all-items
20333 begin struct (org-list-prevs-alist struct))))
20334 ((and first-box (eq (point) begin))
20335 ;; For convenience, when point is at bol on the first
20336 ;; item of the list and no argument is provided, simply
20337 ;; toggle checkbox of that item, if any.
20338 (org-list-set-checkbox begin struct new-box)))
20339 (org-list-write-struct
20340 struct (org-list-parents-alist struct) old-struct)
20341 (org-update-checkbox-count-maybe)
20342 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20343 ((property-drawer node-property)
20344 (call-interactively 'org-property-action))
20345 ((radio-target target)
20346 (call-interactively 'org-update-radio-target-regexp))
20347 (statistics-cookie
20348 (call-interactively 'org-update-statistics-cookies))
20349 ((table table-cell table-row)
20350 ;; At a table, recalculate every field and align it. Also
20351 ;; send the table if necessary. If the table has
20352 ;; a `table.el' type, just give up. At a table row or
20353 ;; cell, maybe recalculate line but always align table.
20354 (if (eq (org-element-property :type context) 'table.el)
20355 (message "Use C-c ' to edit table.el tables")
20356 (let ((org-enable-table-editor t))
20357 (if (or (eq type 'table)
20358 ;; Check if point is at a TBLFM line.
20359 (and (eq type 'table-row)
20360 (= (point) (org-element-property :end context))))
20361 (save-excursion
20362 (if (org-at-TBLFM-p)
20363 (progn (require 'org-table)
20364 (org-table-calc-current-TBLFM))
20365 (goto-char (org-element-property :contents-begin context))
20366 (org-call-with-arg 'org-table-recalculate (or arg t))
20367 (orgtbl-send-table 'maybe)))
20368 (org-table-maybe-eval-formula)
20369 (cond (arg (call-interactively 'org-table-recalculate))
20370 ((org-table-maybe-recalculate-line))
20371 (t (org-table-align)))))))
20372 (timestamp (org-timestamp-change 0 'day))
20373 (otherwise
20374 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20375 (user-error
20376 "C-c C-c can do nothing useful at this location")))))))))
20378 (defun org-mode-restart ()
20379 "Restart Org-mode, to scan again for special lines.
20380 Also updates the keyword regular expressions."
20381 (interactive)
20382 (org-mode)
20383 (message "Org-mode restarted"))
20385 (defun org-kill-note-or-show-branches ()
20386 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20387 (interactive)
20388 (if (not org-finish-function)
20389 (progn
20390 (hide-subtree)
20391 (call-interactively 'show-branches))
20392 (let ((org-note-abort t))
20393 (funcall org-finish-function))))
20395 (defun org-open-line (n)
20396 "Insert a new row in tables, call `open-line' elsewhere.
20397 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20398 (interactive "*p")
20399 (cond
20400 ((not org-special-ctrl-o)
20401 (open-line n))
20402 ((org-at-table-p)
20403 (org-table-insert-row))
20405 (open-line n))))
20407 (defun org-return (&optional indent)
20408 "Goto next table row or insert a newline.
20409 Calls `org-table-next-row' or `newline', depending on context.
20410 See the individual commands for more information."
20411 (interactive)
20412 (let (org-ts-what)
20413 (cond
20414 ((or (bobp) (org-in-src-block-p))
20415 (if indent (newline-and-indent) (newline)))
20416 ((org-at-table-p)
20417 (org-table-justify-field-maybe)
20418 (call-interactively 'org-table-next-row))
20419 ;; when `newline-and-indent' is called within a list, make sure
20420 ;; text moved stays inside the item.
20421 ((and (org-in-item-p) indent)
20422 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20423 (progn
20424 (save-match-data (newline))
20425 (org-indent-line-to (length (match-string 0))))
20426 (let ((ind (org-get-indentation)))
20427 (newline)
20428 (if (org-looking-back org-list-end-re)
20429 (org-indent-line)
20430 (org-indent-line-to ind)))))
20431 ((and org-return-follows-link
20432 (org-at-timestamp-p t)
20433 (not (eq org-ts-what 'after)))
20434 (org-follow-timestamp-link))
20435 ((and org-return-follows-link
20436 (let ((tprop (get-text-property (point) 'face)))
20437 (or (eq tprop 'org-link)
20438 (and (listp tprop) (memq 'org-link tprop)))))
20439 (call-interactively 'org-open-at-point))
20440 ((and (org-at-heading-p)
20441 (looking-at
20442 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20443 (org-show-entry)
20444 (end-of-line 1)
20445 (newline))
20446 (t (if indent (newline-and-indent) (newline))))))
20448 (defun org-return-indent ()
20449 "Goto next table row or insert a newline and indent.
20450 Calls `org-table-next-row' or `newline-and-indent', depending on
20451 context. See the individual commands for more information."
20452 (interactive)
20453 (org-return t))
20455 (defun org-ctrl-c-star ()
20456 "Compute table, or change heading status of lines.
20457 Calls `org-table-recalculate' or `org-toggle-heading',
20458 depending on context."
20459 (interactive)
20460 (cond
20461 ((org-at-table-p)
20462 (call-interactively 'org-table-recalculate))
20464 ;; Convert all lines in region to list items
20465 (call-interactively 'org-toggle-heading))))
20467 (defun org-ctrl-c-minus ()
20468 "Insert separator line in table or modify bullet status of line.
20469 Also turns a plain line or a region of lines into list items.
20470 Calls `org-table-insert-hline', `org-toggle-item', or
20471 `org-cycle-list-bullet', depending on context."
20472 (interactive)
20473 (cond
20474 ((org-at-table-p)
20475 (call-interactively 'org-table-insert-hline))
20476 ((org-region-active-p)
20477 (call-interactively 'org-toggle-item))
20478 ((org-in-item-p)
20479 (call-interactively 'org-cycle-list-bullet))
20481 (call-interactively 'org-toggle-item))))
20483 (defun org-toggle-item (arg)
20484 "Convert headings or normal lines to items, items to normal lines.
20485 If there is no active region, only the current line is considered.
20487 If the first non blank line in the region is a headline, convert
20488 all headlines to items, shifting text accordingly.
20490 If it is an item, convert all items to normal lines.
20492 If it is normal text, change region into a list of items.
20493 With a prefix argument ARG, change the region in a single item."
20494 (interactive "P")
20495 (let ((shift-text
20496 (function
20497 ;; Shift text in current section to IND, from point to END.
20498 ;; The function leaves point to END line.
20499 (lambda (ind end)
20500 (let ((min-i 1000) (end (copy-marker end)))
20501 ;; First determine the minimum indentation (MIN-I) of
20502 ;; the text.
20503 (save-excursion
20504 (catch 'exit
20505 (while (< (point) end)
20506 (let ((i (org-get-indentation)))
20507 (cond
20508 ;; Skip blank lines and inline tasks.
20509 ((looking-at "^[ \t]*$"))
20510 ((looking-at org-outline-regexp-bol))
20511 ;; We can't find less than 0 indentation.
20512 ((zerop i) (throw 'exit (setq min-i 0)))
20513 ((< i min-i) (setq min-i i))))
20514 (forward-line))))
20515 ;; Then indent each line so that a line indented to
20516 ;; MIN-I becomes indented to IND. Ignore blank lines
20517 ;; and inline tasks in the process.
20518 (let ((delta (- ind min-i)))
20519 (while (< (point) end)
20520 (unless (or (looking-at "^[ \t]*$")
20521 (looking-at org-outline-regexp-bol))
20522 (org-indent-line-to (+ (org-get-indentation) delta)))
20523 (forward-line)))))))
20524 (skip-blanks
20525 (function
20526 ;; Return beginning of first non-blank line, starting from
20527 ;; line at POS.
20528 (lambda (pos)
20529 (save-excursion
20530 (goto-char pos)
20531 (skip-chars-forward " \r\t\n")
20532 (point-at-bol)))))
20533 beg end)
20534 ;; Determine boundaries of changes.
20535 (if (org-region-active-p)
20536 (setq beg (funcall skip-blanks (region-beginning))
20537 end (copy-marker (region-end)))
20538 (setq beg (funcall skip-blanks (point-at-bol))
20539 end (copy-marker (point-at-eol))))
20540 ;; Depending on the starting line, choose an action on the text
20541 ;; between BEG and END.
20542 (org-with-limited-levels
20543 (save-excursion
20544 (goto-char beg)
20545 (cond
20546 ;; Case 1. Start at an item: de-itemize. Note that it only
20547 ;; happens when a region is active: `org-ctrl-c-minus'
20548 ;; would call `org-cycle-list-bullet' otherwise.
20549 ((org-at-item-p)
20550 (while (< (point) end)
20551 (when (org-at-item-p)
20552 (skip-chars-forward " \t")
20553 (delete-region (point) (match-end 0)))
20554 (forward-line)))
20555 ;; Case 2. Start at an heading: convert to items.
20556 ((org-at-heading-p)
20557 (let* ((bul (org-list-bullet-string "-"))
20558 (bul-len (length bul))
20559 ;; Indentation of the first heading. It should be
20560 ;; relative to the indentation of its parent, if any.
20561 (start-ind (save-excursion
20562 (cond
20563 ((not org-adapt-indentation) 0)
20564 ((not (outline-previous-heading)) 0)
20565 (t (length (match-string 0))))))
20566 ;; Level of first heading. Further headings will be
20567 ;; compared to it to determine hierarchy in the list.
20568 (ref-level (org-reduced-level (org-outline-level))))
20569 (while (< (point) end)
20570 (let* ((level (org-reduced-level (org-outline-level)))
20571 (delta (max 0 (- level ref-level))))
20572 ;; If current headline is less indented than the first
20573 ;; one, set it as reference, in order to preserve
20574 ;; subtrees.
20575 (when (< level ref-level) (setq ref-level level))
20576 (replace-match bul t t)
20577 (org-indent-line-to (+ start-ind (* delta bul-len)))
20578 ;; Ensure all text down to END (or SECTION-END) belongs
20579 ;; to the newly created item.
20580 (let ((section-end (save-excursion
20581 (or (outline-next-heading) (point)))))
20582 (forward-line)
20583 (funcall shift-text
20584 (+ start-ind (* (1+ delta) bul-len))
20585 (min end section-end)))))))
20586 ;; Case 3. Normal line with ARG: make the first line of region
20587 ;; an item, and shift indentation of others lines to
20588 ;; set them as item's body.
20589 (arg (let* ((bul (org-list-bullet-string "-"))
20590 (bul-len (length bul))
20591 (ref-ind (org-get-indentation)))
20592 (skip-chars-forward " \t")
20593 (insert bul)
20594 (forward-line)
20595 (while (< (point) end)
20596 ;; Ensure that lines less indented than first one
20597 ;; still get included in item body.
20598 (funcall shift-text
20599 (+ ref-ind bul-len)
20600 (min end (save-excursion (or (outline-next-heading)
20601 (point)))))
20602 (forward-line))))
20603 ;; Case 4. Normal line without ARG: turn each non-item line
20604 ;; into an item.
20606 (while (< (point) end)
20607 (unless (or (org-at-heading-p) (org-at-item-p))
20608 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20609 (replace-match
20610 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20611 (forward-line))))))))
20613 (defun org-toggle-heading (&optional nstars)
20614 "Convert headings to normal text, or items or text to headings.
20615 If there is no active region, only convert the current line.
20617 With a \\[universal-argument] prefix, convert the whole list at
20618 point into heading.
20620 In a region:
20622 - If the first non blank line is a headline, remove the stars
20623 from all headlines in the region.
20625 - If it is a normal line, turn each and every normal line (i.e.,
20626 not an heading or an item) in the region into headings. If you
20627 want to convert only the first line of this region, use one
20628 universal prefix argument.
20630 - If it is a plain list item, turn all plain list items into headings.
20632 When converting a line into a heading, the number of stars is chosen
20633 such that the lines become children of the current entry. However,
20634 when a numeric prefix argument is given, its value determines the
20635 number of stars to add."
20636 (interactive "P")
20637 (let ((skip-blanks
20638 (function
20639 ;; Return beginning of first non-blank line, starting from
20640 ;; line at POS.
20641 (lambda (pos)
20642 (save-excursion
20643 (goto-char pos)
20644 (while (org-at-comment-p) (forward-line))
20645 (skip-chars-forward " \r\t\n")
20646 (point-at-bol)))))
20647 beg end toggled)
20648 ;; Determine boundaries of changes. If a universal prefix has
20649 ;; been given, put the list in a region. If region ends at a bol,
20650 ;; do not consider the last line to be in the region.
20652 (when (and current-prefix-arg (org-at-item-p))
20653 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20654 (org-mark-element))
20656 (if (org-region-active-p)
20657 (setq beg (funcall skip-blanks (region-beginning))
20658 end (copy-marker (save-excursion
20659 (goto-char (region-end))
20660 (if (bolp) (point) (point-at-eol)))))
20661 (setq beg (funcall skip-blanks (point-at-bol))
20662 end (copy-marker (point-at-eol))))
20663 ;; Ensure inline tasks don't count as headings.
20664 (org-with-limited-levels
20665 (save-excursion
20666 (goto-char beg)
20667 (cond
20668 ;; Case 1. Started at an heading: de-star headings.
20669 ((org-at-heading-p)
20670 (while (< (point) end)
20671 (when (org-at-heading-p t)
20672 (looking-at org-outline-regexp) (replace-match "")
20673 (setq toggled t))
20674 (forward-line)))
20675 ;; Case 2. Started at an item: change items into headlines.
20676 ;; One star will be added by `org-list-to-subtree'.
20677 ((org-at-item-p)
20678 (let* ((stars (make-string
20679 ;; subtract the star that will be added again by
20680 ;; `org-list-to-subtree'
20681 (if (numberp nstars) (1- nstars)
20682 (or (org-current-level) 0))
20683 ?*))
20684 (add-stars
20685 (cond (nstars "") ; stars from prefix only
20686 ((equal stars "") "") ; before first heading
20687 (org-odd-levels-only "*") ; inside heading, odd
20688 (t "")))) ; inside heading, oddeven
20689 (while (< (point) end)
20690 (when (org-at-item-p)
20691 ;; Pay attention to cases when region ends before list.
20692 (let* ((struct (org-list-struct))
20693 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20694 (save-restriction
20695 (narrow-to-region (point) list-end)
20696 (insert
20697 (org-list-to-subtree
20698 (org-list-parse-list t)
20699 '(:istart (concat stars add-stars (funcall get-stars depth))
20700 :icount (concat stars add-stars (funcall get-stars depth)))))))
20701 (setq toggled t))
20702 (forward-line))))
20703 ;; Case 3. Started at normal text: make every line an heading,
20704 ;; skipping headlines and items.
20705 (t (let* ((stars
20706 (make-string
20707 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20708 (add-stars
20709 (cond (nstars "") ; stars from prefix only
20710 ((equal stars "") "*") ; before first heading
20711 (org-odd-levels-only "**") ; inside heading, odd
20712 (t "*"))) ; inside heading, oddeven
20713 (rpl (concat stars add-stars " "))
20714 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20715 (while (< (point) (if (equal nstars '(4)) lend end))
20716 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20717 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20718 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20719 (forward-line)))))))
20720 (unless toggled (message "Cannot toggle heading from here"))))
20722 (defun org-meta-return (&optional arg)
20723 "Insert a new heading or wrap a region in a table.
20724 Calls `org-insert-heading' or `org-table-wrap-region', depending
20725 on context. See the individual commands for more information."
20726 (interactive "P")
20727 (org-check-before-invisible-edit 'insert)
20728 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20729 (let* ((element (org-element-at-point))
20730 (type (org-element-type element)))
20731 (when (eq type 'table-row)
20732 (setq element (org-element-property :parent element))
20733 (setq type 'table))
20734 (if (and (eq type 'table)
20735 (eq (org-element-property :type element) 'org)
20736 (>= (point) (org-element-property :contents-begin element))
20737 (< (point) (org-element-property :contents-end element)))
20738 (call-interactively 'org-table-wrap-region)
20739 (call-interactively 'org-insert-heading)))))
20741 ;;; Menu entries
20743 (defsubst org-in-subtree-not-table-p ()
20744 "Are we in a subtree and not in a table?"
20745 (and (not (org-before-first-heading-p))
20746 (not (org-at-table-p))))
20748 ;; Define the Org-mode menus
20749 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20750 '("Tbl"
20751 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20752 ["Next Field" org-cycle (org-at-table-p)]
20753 ["Previous Field" org-shifttab (org-at-table-p)]
20754 ["Next Row" org-return (org-at-table-p)]
20755 "--"
20756 ["Blank Field" org-table-blank-field (org-at-table-p)]
20757 ["Edit Field" org-table-edit-field (org-at-table-p)]
20758 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20759 "--"
20760 ("Column"
20761 ["Move Column Left" org-metaleft (org-at-table-p)]
20762 ["Move Column Right" org-metaright (org-at-table-p)]
20763 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20764 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20765 ("Row"
20766 ["Move Row Up" org-metaup (org-at-table-p)]
20767 ["Move Row Down" org-metadown (org-at-table-p)]
20768 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20769 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20770 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20771 "--"
20772 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20773 ("Rectangle"
20774 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20775 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20776 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20777 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20778 "--"
20779 ("Calculate"
20780 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20781 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20782 ["Edit Formulas" org-edit-special (org-at-table-p)]
20783 "--"
20784 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20785 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20786 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20787 "--"
20788 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20789 "--"
20790 ["Sum Column/Rectangle" org-table-sum
20791 (or (org-at-table-p) (org-region-active-p))]
20792 ["Which Column?" org-table-current-column (org-at-table-p)])
20793 ["Debug Formulas"
20794 org-table-toggle-formula-debugger
20795 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20796 ["Show Col/Row Numbers"
20797 org-table-toggle-coordinate-overlays
20798 :style toggle
20799 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20800 "--"
20801 ["Create" org-table-create (and (not (org-at-table-p))
20802 org-enable-table-editor)]
20803 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20804 ["Import from File" org-table-import (not (org-at-table-p))]
20805 ["Export to File" org-table-export (org-at-table-p)]
20806 "--"
20807 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20809 (easy-menu-define org-org-menu org-mode-map "Org menu"
20810 '("Org"
20811 ("Show/Hide"
20812 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20813 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20814 ["Sparse Tree..." org-sparse-tree t]
20815 ["Reveal Context" org-reveal t]
20816 ["Show All" show-all t]
20817 "--"
20818 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20819 "--"
20820 ["New Heading" org-insert-heading t]
20821 ("Navigate Headings"
20822 ["Up" outline-up-heading t]
20823 ["Next" outline-next-visible-heading t]
20824 ["Previous" outline-previous-visible-heading t]
20825 ["Next Same Level" outline-forward-same-level t]
20826 ["Previous Same Level" outline-backward-same-level t]
20827 "--"
20828 ["Jump" org-goto t])
20829 ("Edit Structure"
20830 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20831 "--"
20832 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20833 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20834 "--"
20835 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20836 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20837 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20838 "--"
20839 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20840 "--"
20841 ["Copy visible text" org-copy-visible t]
20842 "--"
20843 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20844 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20845 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20846 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20847 "--"
20848 ["Sort Region/Children" org-sort t]
20849 "--"
20850 ["Convert to odd levels" org-convert-to-odd-levels t]
20851 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20852 ("Editing"
20853 ["Emphasis..." org-emphasize t]
20854 ["Edit Source Example" org-edit-special t]
20855 "--"
20856 ["Footnote new/jump" org-footnote-action t]
20857 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20858 ("Archive"
20859 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20860 "--"
20861 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20862 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20863 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20865 "--"
20866 ("Hyperlinks"
20867 ["Store Link (Global)" org-store-link t]
20868 ["Find existing link to here" org-occur-link-in-agenda-files t]
20869 ["Insert Link" org-insert-link t]
20870 ["Follow Link" org-open-at-point t]
20871 "--"
20872 ["Next link" org-next-link t]
20873 ["Previous link" org-previous-link t]
20874 "--"
20875 ["Descriptive Links"
20876 org-toggle-link-display
20877 :style radio
20878 :selected org-descriptive-links
20880 ["Literal Links"
20881 org-toggle-link-display
20882 :style radio
20883 :selected (not org-descriptive-links)])
20884 "--"
20885 ("TODO Lists"
20886 ["TODO/DONE/-" org-todo t]
20887 ("Select keyword"
20888 ["Next keyword" org-shiftright (org-at-heading-p)]
20889 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20890 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20891 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20892 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20893 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20894 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20895 "--"
20896 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20897 :selected org-enforce-todo-dependencies :style toggle :active t]
20898 "Settings for tree at point"
20899 ["Do Children sequentially" org-toggle-ordered-property :style radio
20900 :selected (org-entry-get nil "ORDERED")
20901 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20902 ["Do Children parallel" org-toggle-ordered-property :style radio
20903 :selected (not (org-entry-get nil "ORDERED"))
20904 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20905 "--"
20906 ["Set Priority" org-priority t]
20907 ["Priority Up" org-shiftup t]
20908 ["Priority Down" org-shiftdown t]
20909 "--"
20910 ["Get news from all feeds" org-feed-update-all t]
20911 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20912 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20913 ("TAGS and Properties"
20914 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20915 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20916 "--"
20917 ["Set property" org-set-property (not (org-before-first-heading-p))]
20918 ["Column view of properties" org-columns t]
20919 ["Insert Column View DBlock" org-insert-columns-dblock t])
20920 ("Dates and Scheduling"
20921 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20922 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20923 ("Change Date"
20924 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20925 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20926 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20927 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20928 ["Compute Time Range" org-evaluate-time-range t]
20929 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20930 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20931 "--"
20932 ["Custom time format" org-toggle-time-stamp-overlays
20933 :style radio :selected org-display-custom-times]
20934 "--"
20935 ["Goto Calendar" org-goto-calendar t]
20936 ["Date from Calendar" org-date-from-calendar t]
20937 "--"
20938 ["Start/Restart Timer" org-timer-start t]
20939 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20940 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20941 ["Insert Timer String" org-timer t]
20942 ["Insert Timer Item" org-timer-item t])
20943 ("Logging work"
20944 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20945 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20946 ["Clock out" org-clock-out t]
20947 ["Clock cancel" org-clock-cancel t]
20948 "--"
20949 ["Mark as default task" org-clock-mark-default-task t]
20950 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20951 ["Goto running clock" org-clock-goto t]
20952 "--"
20953 ["Display times" org-clock-display t]
20954 ["Create clock table" org-clock-report t]
20955 "--"
20956 ["Record DONE time"
20957 (progn (setq org-log-done (not org-log-done))
20958 (message "Switching to %s will %s record a timestamp"
20959 (car org-done-keywords)
20960 (if org-log-done "automatically" "not")))
20961 :style toggle :selected org-log-done])
20962 "--"
20963 ["Agenda Command..." org-agenda t]
20964 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20965 ("File List for Agenda")
20966 ("Special views current file"
20967 ["TODO Tree" org-show-todo-tree t]
20968 ["Check Deadlines" org-check-deadlines t]
20969 ["Timeline" org-timeline t]
20970 ["Tags/Property tree" org-match-sparse-tree t])
20971 "--"
20972 ["Export/Publish..." org-export-dispatch t]
20973 ("LaTeX"
20974 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20975 :selected org-cdlatex-mode]
20976 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20977 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20978 ["Modify math symbol" org-cdlatex-math-modify
20979 (org-inside-LaTeX-fragment-p)]
20980 ["Insert citation" org-reftex-citation t]
20981 "--"
20982 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20983 "--"
20984 ("MobileOrg"
20985 ["Push Files and Views" org-mobile-push t]
20986 ["Get Captured and Flagged" org-mobile-pull t]
20987 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20988 "--"
20989 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20990 "--"
20991 ("Documentation"
20992 ["Show Version" org-version t]
20993 ["Info Documentation" org-info t])
20994 ("Customize"
20995 ["Browse Org Group" org-customize t]
20996 "--"
20997 ["Expand This Menu" org-create-customize-menu
20998 (fboundp 'customize-menu-create)])
20999 ["Send bug report" org-submit-bug-report t]
21000 "--"
21001 ("Refresh/Reload"
21002 ["Refresh setup current buffer" org-mode-restart t]
21003 ["Reload Org (after update)" org-reload t]
21004 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21007 (defun org-info (&optional node)
21008 "Read documentation for Org-mode in the info system.
21009 With optional NODE, go directly to that node."
21010 (interactive)
21011 (info (format "(org)%s" (or node ""))))
21013 ;;;###autoload
21014 (defun org-submit-bug-report ()
21015 "Submit a bug report on Org-mode via mail.
21017 Don't hesitate to report any problems or inaccurate documentation.
21019 If you don't have setup sending mail from (X)Emacs, please copy the
21020 output buffer into your mail program, as it gives us important
21021 information about your Org-mode version and configuration."
21022 (interactive)
21023 (require 'reporter)
21024 (org-load-modules-maybe)
21025 (org-require-autoloaded-modules)
21026 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21027 (reporter-submit-bug-report
21028 "emacs-orgmode@gnu.org"
21029 (org-version nil 'full)
21030 (let (list)
21031 (save-window-excursion
21032 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21033 (delete-other-windows)
21034 (erase-buffer)
21035 (insert "You are about to submit a bug report to the Org-mode mailing list.
21037 We would like to add your full Org-mode and Outline configuration to the
21038 bug report. This greatly simplifies the work of the maintainer and
21039 other experts on the mailing list.
21041 HOWEVER, some variables you have customized may contain private
21042 information. The names of customers, colleagues, or friends, might
21043 appear in the form of file names, tags, todo states, or search strings.
21044 If you answer yes to the prompt, you might want to check and remove
21045 such private information before sending the email.")
21046 (add-text-properties (point-min) (point-max) '(face org-warning))
21047 (when (yes-or-no-p "Include your Org-mode configuration ")
21048 (mapatoms
21049 (lambda (v)
21050 (and (boundp v)
21051 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21052 (or (and (symbol-value v)
21053 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21054 (and
21055 (get v 'custom-type) (get v 'standard-value)
21056 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21057 (push v list)))))
21058 (kill-buffer (get-buffer "*Warn about privacy*"))
21059 list))
21060 nil nil
21061 "Remember to cover the basics, that is, what you expected to happen and
21062 what in fact did happen. You don't know how to make a good report? See
21064 http://orgmode.org/manual/Feedback.html#Feedback
21066 Your bug report will be posted to the Org-mode mailing list.
21067 ------------------------------------------------------------------------")
21068 (save-excursion
21069 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21070 (replace-match "\\1Bug: \\3 [\\2]")))))
21073 (defun org-install-agenda-files-menu ()
21074 (let ((bl (buffer-list)))
21075 (save-excursion
21076 (while bl
21077 (set-buffer (pop bl))
21078 (if (derived-mode-p 'org-mode) (setq bl nil)))
21079 (when (derived-mode-p 'org-mode)
21080 (easy-menu-change
21081 '("Org") "File List for Agenda"
21082 (append
21083 (list
21084 ["Edit File List" (org-edit-agenda-file-list) t]
21085 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21086 ["Remove Current File from List" org-remove-file t]
21087 ["Cycle through agenda files" org-cycle-agenda-files t]
21088 ["Occur in all agenda files" org-occur-in-agenda-files t]
21089 "--")
21090 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21092 ;;;; Documentation
21094 (defun org-require-autoloaded-modules ()
21095 (interactive)
21096 (mapc 'require
21097 '(org-agenda org-archive org-attach org-clock org-colview org-id
21098 org-remember org-table org-timer)))
21100 ;;;###autoload
21101 (defun org-reload (&optional uncompiled)
21102 "Reload all org lisp files.
21103 With prefix arg UNCOMPILED, load the uncompiled versions."
21104 (interactive "P")
21105 (require 'loadhist)
21106 (let* ((org-dir (org-find-library-dir "org"))
21107 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21108 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21109 (remove-re (mapconcat 'identity
21110 (mapcar (lambda (f) (concat "^" f "$"))
21111 (list (if (featurep 'xemacs)
21112 "org-colview"
21113 "org-colview-xemacs")
21114 "org" "org-loaddefs" "org-version"))
21115 "\\|"))
21116 (feats (delete-dups
21117 (mapcar 'file-name-sans-extension
21118 (mapcar 'file-name-nondirectory
21119 (delq nil
21120 (mapcar 'feature-file
21121 features))))))
21122 (lfeat (append
21123 (sort
21124 (setq feats
21125 (delq nil (mapcar
21126 (lambda (f)
21127 (if (and (string-match feature-re f)
21128 (not (string-match remove-re f)))
21129 f nil))
21130 feats)))
21131 'string-lessp)
21132 (list "org-version" "org")))
21133 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21134 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21135 load-uncore load-misses)
21136 (setq load-misses
21137 (delq 't
21138 (mapcar (lambda (f)
21139 (or (org-load-noerror-mustsuffix (concat org-dir f))
21140 (and (string= org-dir contrib-dir)
21141 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21142 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21143 (add-to-list 'load-uncore f 'append)
21146 lfeat)))
21147 (if load-uncore
21148 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21149 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21150 (if load-misses
21151 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21152 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21153 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21155 ;;;###autoload
21156 (defun org-customize ()
21157 "Call the customize function with org as argument."
21158 (interactive)
21159 (org-load-modules-maybe)
21160 (org-require-autoloaded-modules)
21161 (customize-browse 'org))
21163 (defun org-create-customize-menu ()
21164 "Create a full customization menu for Org-mode, insert it into the menu."
21165 (interactive)
21166 (org-load-modules-maybe)
21167 (org-require-autoloaded-modules)
21168 (if (fboundp 'customize-menu-create)
21169 (progn
21170 (easy-menu-change
21171 '("Org") "Customize"
21172 `(["Browse Org group" org-customize t]
21173 "--"
21174 ,(customize-menu-create 'org)
21175 ["Set" Custom-set t]
21176 ["Save" Custom-save t]
21177 ["Reset to Current" Custom-reset-current t]
21178 ["Reset to Saved" Custom-reset-saved t]
21179 ["Reset to Standard Settings" Custom-reset-standard t]))
21180 (message "\"Org\"-menu now contains full customization menu"))
21181 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21183 ;;;; Miscellaneous stuff
21185 ;;; Generally useful functions
21187 (defun org-get-at-bol (property)
21188 "Get text property PROPERTY at beginning of line."
21189 (get-text-property (point-at-bol) property))
21191 (defun org-find-text-property-in-string (prop s)
21192 "Return the first non-nil value of property PROP in string S."
21193 (or (get-text-property 0 prop s)
21194 (get-text-property (or (next-single-property-change 0 prop s) 0)
21195 prop s)))
21197 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21198 "Display the given MESSAGE as a warning."
21199 (if (fboundp 'display-warning)
21200 (display-warning 'org message
21201 (if (featurep 'xemacs) 'warning :warning))
21202 (let ((buf (get-buffer-create "*Org warnings*")))
21203 (with-current-buffer buf
21204 (goto-char (point-max))
21205 (insert "Warning (Org): " message)
21206 (unless (bolp)
21207 (newline)))
21208 (display-buffer buf)
21209 (sit-for 0))))
21211 (defun org-eval (form)
21212 "Eval FORM and return result."
21213 (condition-case error
21214 (eval form)
21215 (error (format "%%![Error: %s]" error))))
21217 (defun org-in-clocktable-p ()
21218 "Check if the cursor is in a clocktable."
21219 (let ((pos (point)) start)
21220 (save-excursion
21221 (end-of-line 1)
21222 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21223 (setq start (match-beginning 0))
21224 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21225 (>= (match-end 0) pos)
21226 start))))
21228 (defun org-in-commented-line ()
21229 "Is point in a line starting with `#'?"
21230 (equal (char-after (point-at-bol)) ?#))
21232 (defun org-in-indented-comment-line ()
21233 "Is point in a line starting with `#' after some white space?"
21234 (save-excursion
21235 (save-match-data
21236 (goto-char (point-at-bol))
21237 (looking-at "[ \t]*#"))))
21239 (defun org-in-verbatim-emphasis ()
21240 (save-match-data
21241 (and (org-in-regexp org-emph-re 2)
21242 (>= (point) (match-beginning 3))
21243 (<= (point) (match-end 4))
21244 (member (match-string 3) '("=" "~")))))
21246 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21247 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21248 (if (and marker (marker-buffer marker)
21249 (buffer-live-p (marker-buffer marker)))
21250 (progn
21251 (org-pop-to-buffer-same-window (marker-buffer marker))
21252 (if (or (> marker (point-max)) (< marker (point-min)))
21253 (widen))
21254 (goto-char marker)
21255 (org-show-context 'org-goto))
21256 (if bookmark
21257 (bookmark-jump bookmark)
21258 (error "Cannot find location"))))
21260 (defun org-quote-csv-field (s)
21261 "Quote field for inclusion in CSV material."
21262 (if (string-match "[\",]" s)
21263 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21266 (defun org-force-self-insert (N)
21267 "Needed to enforce self-insert under remapping."
21268 (interactive "p")
21269 (self-insert-command N))
21271 (defun org-string-width (s)
21272 "Compute width of string, ignoring invisible characters.
21273 This ignores character with invisibility property `org-link', and also
21274 characters with property `org-cwidth', because these will become invisible
21275 upon the next fontification round."
21276 (let (b l)
21277 (when (or (eq t buffer-invisibility-spec)
21278 (assq 'org-link buffer-invisibility-spec))
21279 (while (setq b (text-property-any 0 (length s)
21280 'invisible 'org-link s))
21281 (setq s (concat (substring s 0 b)
21282 (substring s (or (next-single-property-change
21283 b 'invisible s) (length s)))))))
21284 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21285 (setq s (concat (substring s 0 b)
21286 (substring s (or (next-single-property-change
21287 b 'org-cwidth s) (length s))))))
21288 (setq l (string-width s) b -1)
21289 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21290 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21293 (defun org-shorten-string (s maxlength)
21294 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21295 If the string is shorter or has length MAXLENGTH, just return the
21296 original string. If it is longer, the functions finds a space in the
21297 string, breaks this string off at that locations and adds three dots
21298 as ellipsis. Including the ellipsis, the string will not be longer
21299 than MAXLENGTH. If finding a good breaking point in the string does
21300 not work, the string is just chopped off in the middle of a word
21301 if necessary."
21302 (if (<= (length s) maxlength)
21304 (let* ((n (max (- maxlength 4) 1))
21305 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21306 (if (string-match re s)
21307 (concat (match-string 1 s) "...")
21308 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21310 (defun org-get-indentation (&optional line)
21311 "Get the indentation of the current line, interpreting tabs.
21312 When LINE is given, assume it represents a line and compute its indentation."
21313 (if line
21314 (if (string-match "^ *" (org-remove-tabs line))
21315 (match-end 0))
21316 (save-excursion
21317 (beginning-of-line 1)
21318 (skip-chars-forward " \t")
21319 (current-column))))
21321 (defun org-get-string-indentation (s)
21322 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21323 (let ((n -1) (i 0) (w tab-width) c)
21324 (catch 'exit
21325 (while (< (setq n (1+ n)) (length s))
21326 (setq c (aref s n))
21327 (cond ((= c ?\ ) (setq i (1+ i)))
21328 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21329 (t (throw 'exit t)))))
21332 (defun org-remove-tabs (s &optional width)
21333 "Replace tabulators in S with spaces.
21334 Assumes that s is a single line, starting in column 0."
21335 (setq width (or width tab-width))
21336 (while (string-match "\t" s)
21337 (setq s (replace-match
21338 (make-string
21339 (- (* width (/ (+ (match-beginning 0) width) width))
21340 (match-beginning 0)) ?\ )
21341 t t s)))
21344 (defun org-fix-indentation (line ind)
21345 "Fix indentation in LINE.
21346 IND is a cons cell with target and minimum indentation.
21347 If the current indentation in LINE is smaller than the minimum,
21348 leave it alone. If it is larger than ind, set it to the target."
21349 (let* ((l (org-remove-tabs line))
21350 (i (org-get-indentation l))
21351 (i1 (car ind)) (i2 (cdr ind)))
21352 (if (>= i i2) (setq l (substring line i2)))
21353 (if (> i1 0)
21354 (concat (make-string i1 ?\ ) l)
21355 l)))
21357 (defun org-remove-indentation (code &optional n)
21358 "Remove the maximum common indentation from the lines in CODE.
21359 N may optionally be the number of spaces to remove."
21360 (with-temp-buffer
21361 (insert code)
21362 (org-do-remove-indentation n)
21363 (buffer-string)))
21365 (defun org-do-remove-indentation (&optional n)
21366 "Remove the maximum common indentation from the buffer."
21367 (untabify (point-min) (point-max))
21368 (let ((min 10000) re)
21369 (if n
21370 (setq min n)
21371 (goto-char (point-min))
21372 (while (re-search-forward "^ *[^ \n]" nil t)
21373 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21374 (unless (or (= min 0) (= min 10000))
21375 (setq re (format "^ \\{%d\\}" min))
21376 (goto-char (point-min))
21377 (while (re-search-forward re nil t)
21378 (replace-match "")
21379 (end-of-line 1))
21380 min)))
21382 (defun org-fill-template (template alist)
21383 "Find each %key of ALIST in TEMPLATE and replace it."
21384 (let ((case-fold-search nil)
21385 entry key value)
21386 (setq alist (sort (copy-sequence alist)
21387 (lambda (a b) (< (length (car a)) (length (car b))))))
21388 (while (setq entry (pop alist))
21389 (setq template
21390 (replace-regexp-in-string
21391 (concat "%" (regexp-quote (car entry)))
21392 (or (cdr entry) "") template t t)))
21393 template))
21395 (defun org-base-buffer (buffer)
21396 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21397 (if (not buffer)
21398 buffer
21399 (or (buffer-base-buffer buffer)
21400 buffer)))
21402 (defun org-trim (s)
21403 "Remove whitespace at beginning and end of string."
21404 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21405 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21408 (defun org-wrap (string &optional width lines)
21409 "Wrap string to either a number of lines, or a width in characters.
21410 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21411 that costs. If there is a word longer than WIDTH, the text is actually
21412 wrapped to the length of that word.
21413 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21414 many lines, whatever width that takes.
21415 The return value is a list of lines, without newlines at the end."
21416 (let* ((words (org-split-string string "[ \t\n]+"))
21417 (maxword (apply 'max (mapcar 'org-string-width words)))
21418 w ll)
21419 (cond (width
21420 (org-do-wrap words (max maxword width)))
21421 (lines
21422 (setq w maxword)
21423 (setq ll (org-do-wrap words maxword))
21424 (if (<= (length ll) lines)
21426 (setq ll words)
21427 (while (> (length ll) lines)
21428 (setq w (1+ w))
21429 (setq ll (org-do-wrap words w)))
21430 ll))
21431 (t (error "Cannot wrap this")))))
21433 (defun org-do-wrap (words width)
21434 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21435 (let (lines line)
21436 (while words
21437 (setq line (pop words))
21438 (while (and words (< (+ (length line) (length (car words))) width))
21439 (setq line (concat line " " (pop words))))
21440 (setq lines (push line lines)))
21441 (nreverse lines)))
21443 (defun org-split-string (string &optional separators)
21444 "Splits STRING into substrings at SEPARATORS.
21445 No empty strings are returned if there are matches at the beginning
21446 and end of string."
21447 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21448 (start 0)
21449 notfirst
21450 (list nil))
21451 (while (and (string-match rexp string
21452 (if (and notfirst
21453 (= start (match-beginning 0))
21454 (< start (length string)))
21455 (1+ start) start))
21456 (< (match-beginning 0) (length string)))
21457 (setq notfirst t)
21458 (or (eq (match-beginning 0) 0)
21459 (and (eq (match-beginning 0) (match-end 0))
21460 (eq (match-beginning 0) start))
21461 (setq list
21462 (cons (substring string start (match-beginning 0))
21463 list)))
21464 (setq start (match-end 0)))
21465 (or (eq start (length string))
21466 (setq list
21467 (cons (substring string start)
21468 list)))
21469 (nreverse list)))
21471 (defun org-quote-vert (s)
21472 "Replace \"|\" with \"\\vert\"."
21473 (while (string-match "|" s)
21474 (setq s (replace-match "\\vert" t t s)))
21477 (defun org-uuidgen-p (s)
21478 "Is S an ID created by UUIDGEN?"
21479 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21481 (defun org-in-src-block-p (&optional inside)
21482 "Whether point is in a code source block.
21483 When INSIDE is non-nil, don't consider we are within a src block
21484 when point is at #+BEGIN_SRC or #+END_SRC."
21485 (let ((case-fold-search t) ov)
21486 (or (and (setq ov (overlays-at (point)))
21487 (memq 'org-block-background
21488 (overlay-properties (car ov))))
21489 (and (not inside)
21490 (save-match-data
21491 (save-excursion
21492 (beginning-of-line)
21493 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21495 (defun org-context ()
21496 "Return a list of contexts of the current cursor position.
21497 If several contexts apply, all are returned.
21498 Each context entry is a list with a symbol naming the context, and
21499 two positions indicating start and end of the context. Possible
21500 contexts are:
21502 :headline anywhere in a headline
21503 :headline-stars on the leading stars in a headline
21504 :todo-keyword on a TODO keyword (including DONE) in a headline
21505 :tags on the TAGS in a headline
21506 :priority on the priority cookie in a headline
21507 :item on the first line of a plain list item
21508 :item-bullet on the bullet/number of a plain list item
21509 :checkbox on the checkbox in a plain list item
21510 :table in an org-mode table
21511 :table-special on a special filed in a table
21512 :table-table in a table.el table
21513 :clocktable in a clocktable
21514 :src-block in a source block
21515 :link on a hyperlink
21516 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21517 :target on a <<target>>
21518 :radio-target on a <<<radio-target>>>
21519 :latex-fragment on a LaTeX fragment
21520 :latex-preview on a LaTeX fragment with overlaid preview image
21522 This function expects the position to be visible because it uses font-lock
21523 faces as a help to recognize the following contexts: :table-special, :link,
21524 and :keyword."
21525 (let* ((f (get-text-property (point) 'face))
21526 (faces (if (listp f) f (list f)))
21527 (case-fold-search t)
21528 (p (point)) clist o)
21529 ;; First the large context
21530 (cond
21531 ((org-at-heading-p t)
21532 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21533 (when (progn
21534 (beginning-of-line 1)
21535 (looking-at org-todo-line-tags-regexp))
21536 (push (org-point-in-group p 1 :headline-stars) clist)
21537 (push (org-point-in-group p 2 :todo-keyword) clist)
21538 (push (org-point-in-group p 4 :tags) clist))
21539 (goto-char p)
21540 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21541 (if (looking-at "\\[#[A-Z0-9]\\]")
21542 (push (org-point-in-group p 0 :priority) clist)))
21544 ((org-at-item-p)
21545 (push (org-point-in-group p 2 :item-bullet) clist)
21546 (push (list :item (point-at-bol)
21547 (save-excursion (org-end-of-item) (point)))
21548 clist)
21549 (and (org-at-item-checkbox-p)
21550 (push (org-point-in-group p 0 :checkbox) clist)))
21552 ((org-at-table-p)
21553 (push (list :table (org-table-begin) (org-table-end)) clist)
21554 (if (memq 'org-formula faces)
21555 (push (list :table-special
21556 (previous-single-property-change p 'face)
21557 (next-single-property-change p 'face)) clist)))
21558 ((org-at-table-p 'any)
21559 (push (list :table-table) clist)))
21560 (goto-char p)
21562 (let ((case-fold-search t))
21563 ;; New the "medium" contexts: clocktables, source blocks
21564 (cond ((org-in-clocktable-p)
21565 (push (list :clocktable
21566 (and (or (looking-at "#\\+BEGIN: clocktable")
21567 (search-backward "#+BEGIN: clocktable" nil t))
21568 (match-beginning 0))
21569 (and (re-search-forward "#\\+END:?" nil t)
21570 (match-end 0))) clist))
21571 ((org-in-src-block-p)
21572 (push (list :src-block
21573 (and (or (looking-at "#\\+BEGIN_SRC")
21574 (search-backward "#+BEGIN_SRC" nil t))
21575 (match-beginning 0))
21576 (and (search-forward "#+END_SRC" nil t)
21577 (match-beginning 0))) clist))))
21578 (goto-char p)
21580 ;; Now the small context
21581 (cond
21582 ((org-at-timestamp-p)
21583 (push (org-point-in-group p 0 :timestamp) clist))
21584 ((memq 'org-link faces)
21585 (push (list :link
21586 (previous-single-property-change p 'face)
21587 (next-single-property-change p 'face)) clist))
21588 ((memq 'org-special-keyword faces)
21589 (push (list :keyword
21590 (previous-single-property-change p 'face)
21591 (next-single-property-change p 'face)) clist))
21592 ((org-at-target-p)
21593 (push (org-point-in-group p 0 :target) clist)
21594 (goto-char (1- (match-beginning 0)))
21595 (if (looking-at org-radio-target-regexp)
21596 (push (org-point-in-group p 0 :radio-target) clist))
21597 (goto-char p))
21598 ((setq o (car (delq nil
21599 (mapcar
21600 (lambda (x)
21601 (if (memq x org-latex-fragment-image-overlays) x))
21602 (overlays-at (point))))))
21603 (push (list :latex-fragment
21604 (overlay-start o) (overlay-end o)) clist)
21605 (push (list :latex-preview
21606 (overlay-start o) (overlay-end o)) clist))
21607 ((org-inside-LaTeX-fragment-p)
21608 ;; FIXME: positions wrong.
21609 (push (list :latex-fragment (point) (point)) clist)))
21611 (setq clist (nreverse (delq nil clist)))
21612 clist))
21614 ;; FIXME: Compare with at-regexp-p Do we need both?
21615 (defun org-in-regexp (re &optional nlines visually)
21616 "Check if point is inside a match of regexp.
21617 Normally only the current line is checked, but you can include NLINES extra
21618 lines both before and after point into the search.
21619 If VISUALLY is set, require that the cursor is not after the match but
21620 really on, so that the block visually is on the match."
21621 (catch 'exit
21622 (let ((pos (point))
21623 (eol (point-at-eol (+ 1 (or nlines 0))))
21624 (inc (if visually 1 0)))
21625 (save-excursion
21626 (beginning-of-line (- 1 (or nlines 0)))
21627 (while (re-search-forward re eol t)
21628 (if (and (<= (match-beginning 0) pos)
21629 (>= (+ inc (match-end 0)) pos))
21630 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21632 (defun org-at-regexp-p (regexp)
21633 "Is point inside a match of REGEXP in the current line?"
21634 (catch 'exit
21635 (save-excursion
21636 (let ((pos (point)) (end (point-at-eol)))
21637 (beginning-of-line 1)
21638 (while (re-search-forward regexp end t)
21639 (if (and (<= (match-beginning 0) pos)
21640 (>= (match-end 0) pos))
21641 (throw 'exit t)))
21642 nil))))
21644 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21645 "Non-nil when point is between matches of START-RE and END-RE.
21647 Also return a non-nil value when point is on one of the matches.
21649 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21650 buffer positions. Default values are the positions of headlines
21651 surrounding the point.
21653 The functions returns a cons cell whose car (resp. cdr) is the
21654 position before START-RE (resp. after END-RE)."
21655 (save-match-data
21656 (let ((pos (point))
21657 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21658 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21659 beg end)
21660 (save-excursion
21661 ;; Point is on a block when on START-RE or if START-RE can be
21662 ;; found before it...
21663 (and (or (org-at-regexp-p start-re)
21664 (re-search-backward start-re limit-up t))
21665 (setq beg (match-beginning 0))
21666 ;; ... and END-RE after it...
21667 (goto-char (match-end 0))
21668 (re-search-forward end-re limit-down t)
21669 (> (setq end (match-end 0)) pos)
21670 ;; ... without another START-RE in-between.
21671 (goto-char (match-beginning 0))
21672 (not (re-search-backward start-re (1+ beg) t))
21673 ;; Return value.
21674 (cons beg end))))))
21676 (defun org-in-block-p (names)
21677 "Non-nil when point belongs to a block whose name belongs to NAMES.
21679 NAMES is a list of strings containing names of blocks.
21681 Return first block name matched, or nil. Beware that in case of
21682 nested blocks, the returned name may not belong to the closest
21683 block from point."
21684 (save-match-data
21685 (catch 'exit
21686 (let ((case-fold-search t)
21687 (lim-up (save-excursion (outline-previous-heading)))
21688 (lim-down (save-excursion (outline-next-heading))))
21689 (mapc (lambda (name)
21690 (let ((n (regexp-quote name)))
21691 (when (org-between-regexps-p
21692 (concat "^[ \t]*#\\+begin_" n)
21693 (concat "^[ \t]*#\\+end_" n)
21694 lim-up lim-down)
21695 (throw 'exit n))))
21696 names))
21697 nil)))
21699 (defun org-in-drawer-p ()
21700 "Non-nil if point is within a drawer.
21701 If point is within a drawer, return it, as parsed data."
21702 (let ((element (save-match-data (org-element-at-point))))
21703 (while (and element (not (memq (org-element-type element)
21704 '(drawer property-drawer))))
21705 (setq element (org-element-property :parent element)))
21706 element))
21708 (defun org-occur-in-agenda-files (regexp &optional nlines)
21709 "Call `multi-occur' with buffers for all agenda files."
21710 (interactive "sOrg-files matching: \np")
21711 (let* ((files (org-agenda-files))
21712 (tnames (mapcar 'file-truename files))
21713 (extra org-agenda-text-search-extra-files)
21715 (when (eq (car extra) 'agenda-archives)
21716 (setq extra (cdr extra))
21717 (setq files (org-add-archive-files files)))
21718 (while (setq f (pop extra))
21719 (unless (member (file-truename f) tnames)
21720 (add-to-list 'files f 'append)
21721 (add-to-list 'tnames (file-truename f) 'append)))
21722 (multi-occur
21723 (mapcar (lambda (x)
21724 (with-current-buffer
21725 (or (get-file-buffer x) (find-file-noselect x))
21726 (widen)
21727 (current-buffer)))
21728 files)
21729 regexp)))
21731 (if (boundp 'occur-mode-find-occurrence-hook)
21732 ;; Emacs 23
21733 (add-hook 'occur-mode-find-occurrence-hook
21734 (lambda ()
21735 (when (derived-mode-p 'org-mode)
21736 (org-reveal))))
21737 ;; Emacs 22
21738 (defadvice occur-mode-goto-occurrence
21739 (after org-occur-reveal activate)
21740 (and (derived-mode-p 'org-mode) (org-reveal)))
21741 (defadvice occur-mode-goto-occurrence-other-window
21742 (after org-occur-reveal activate)
21743 (and (derived-mode-p 'org-mode) (org-reveal)))
21744 (defadvice occur-mode-display-occurrence
21745 (after org-occur-reveal activate)
21746 (when (derived-mode-p 'org-mode)
21747 (let ((pos (occur-mode-find-occurrence)))
21748 (with-current-buffer (marker-buffer pos)
21749 (save-excursion
21750 (goto-char pos)
21751 (org-reveal)))))))
21753 (defun org-occur-link-in-agenda-files ()
21754 "Create a link and search for it in the agendas.
21755 The link is not stored in `org-stored-links', it is just created
21756 for the search purpose."
21757 (interactive)
21758 (let ((link (condition-case nil
21759 (org-store-link nil)
21760 (error "Unable to create a link to here"))))
21761 (org-occur-in-agenda-files (regexp-quote link))))
21763 (defun org-reverse-string (string)
21764 "Return the reverse of STRING."
21765 (apply 'string (reverse (string-to-list string))))
21767 (defsubst org-uniquify (list)
21768 "Non-destructively remove duplicate elements from LIST."
21769 (let ((res (copy-sequence list))) (delete-dups res)))
21771 (defun org-uniquify-alist (alist)
21772 "Merge elements of ALIST with the same key.
21774 For example, in this alist:
21776 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21777 => '((a 1 3) (b 2))
21779 merge (a 1) and (a 3) into (a 1 3).
21781 The function returns the new ALIST."
21782 (let (rtn)
21783 (mapc
21784 (lambda (e)
21785 (let (n)
21786 (if (not (assoc (car e) rtn))
21787 (push e rtn)
21788 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21789 (setq rtn (assq-delete-all (car e) rtn))
21790 (push n rtn))))
21791 alist)
21792 rtn))
21794 (defun org-delete-all (elts list)
21795 "Remove all elements in ELTS from LIST."
21796 (while elts
21797 (setq list (delete (pop elts) list)))
21798 list)
21800 (defun org-count (cl-item cl-seq)
21801 "Count the number of occurrences of ITEM in SEQ.
21802 Taken from `count' in cl-seq.el with all keyword arguments removed."
21803 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21804 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21805 (while (< cl-start cl-end)
21806 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21807 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21808 (setq cl-start (1+ cl-start)))
21809 cl-count))
21811 (defun org-remove-if (predicate seq)
21812 "Remove everything from SEQ that fulfills PREDICATE."
21813 (let (res e)
21814 (while seq
21815 (setq e (pop seq))
21816 (if (not (funcall predicate e)) (push e res)))
21817 (nreverse res)))
21819 (defun org-remove-if-not (predicate seq)
21820 "Remove everything from SEQ that does not fulfill PREDICATE."
21821 (let (res e)
21822 (while seq
21823 (setq e (pop seq))
21824 (if (funcall predicate e) (push e res)))
21825 (nreverse res)))
21827 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21828 "Reduce two-argument FUNCTION across SEQ.
21829 Taken from `reduce' in cl-seq.el with all keyword arguments but
21830 \":initial-value\" removed."
21831 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21832 (cadr (memq :initial-value cl-keys)))
21833 (cl-seq (pop cl-seq))
21834 (t (funcall cl-func)))))
21835 (while cl-seq
21836 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21837 cl-accum))
21839 (defun org-every (pred seq)
21840 "Return true if PREDICATE is true of every element of SEQ.
21841 Adapted from `every' in cl.el."
21842 (catch 'org-every
21843 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21846 (defun org-some (pred seq)
21847 "Return true if PREDICATE is true of any element of SEQ.
21848 Adapted from `some' in cl.el."
21849 (catch 'org-some
21850 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21851 nil))
21853 (defun org-back-over-empty-lines ()
21854 "Move backwards over whitespace, to the beginning of the first empty line.
21855 Returns the number of empty lines passed."
21856 (let ((pos (point)))
21857 (if (cdr (assoc 'heading org-blank-before-new-entry))
21858 (skip-chars-backward " \t\n\r")
21859 (unless (eobp)
21860 (forward-line -1)))
21861 (beginning-of-line 2)
21862 (goto-char (min (point) pos))
21863 (count-lines (point) pos)))
21865 (defun org-skip-whitespace ()
21866 (skip-chars-forward " \t\n\r"))
21868 (defun org-point-in-group (point group &optional context)
21869 "Check if POINT is in match-group GROUP.
21870 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21871 match. If the match group does not exist or point is not inside it,
21872 return nil."
21873 (and (match-beginning group)
21874 (>= point (match-beginning group))
21875 (<= point (match-end group))
21876 (if context
21877 (list context (match-beginning group) (match-end group))
21878 t)))
21880 (defun org-switch-to-buffer-other-window (&rest args)
21881 "Switch to buffer in a second window on the current frame.
21882 In particular, do not allow pop-up frames.
21883 Returns the newly created buffer."
21884 (org-no-popups
21885 (apply 'switch-to-buffer-other-window args)))
21887 (defun org-combine-plists (&rest plists)
21888 "Create a single property list from all plists in PLISTS.
21889 The process starts by copying the first list, and then setting properties
21890 from the other lists. Settings in the last list are the most significant
21891 ones and overrule settings in the other lists."
21892 (let ((rtn (copy-sequence (pop plists)))
21893 p v ls)
21894 (while plists
21895 (setq ls (pop plists))
21896 (while ls
21897 (setq p (pop ls) v (pop ls))
21898 (setq rtn (plist-put rtn p v))))
21899 rtn))
21901 (defun org-replace-escapes (string table)
21902 "Replace %-escapes in STRING with values in TABLE.
21903 TABLE is an association list with keys like \"%a\" and string values.
21904 The sequences in STRING may contain normal field width and padding information,
21905 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21906 so values can contain further %-escapes if they are define later in TABLE."
21907 (let ((tbl (copy-alist table))
21908 (case-fold-search nil)
21909 (pchg 0)
21910 e re rpl)
21911 (while (setq e (pop tbl))
21912 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21913 (when (and (cdr e) (string-match re (cdr e)))
21914 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21915 (safe "SREF"))
21916 (add-text-properties 0 3 (list 'sref sref) safe)
21917 (setcdr e (replace-match safe t t (cdr e)))))
21918 (while (string-match re string)
21919 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21920 (cdr e)))
21921 (setq string (replace-match rpl t t string))))
21922 (while (setq pchg (next-property-change pchg string))
21923 (let ((sref (get-text-property pchg 'sref string)))
21924 (when (and sref (string-match "SREF" string pchg))
21925 (setq string (replace-match sref t t string)))))
21926 string))
21928 (defun org-sublist (list start end)
21929 "Return a section of LIST, from START to END.
21930 Counting starts at 1."
21931 (let (rtn (c start))
21932 (setq list (nthcdr (1- start) list))
21933 (while (and list (<= c end))
21934 (push (pop list) rtn)
21935 (setq c (1+ c)))
21936 (nreverse rtn)))
21938 (defun org-find-base-buffer-visiting (file)
21939 "Like `find-buffer-visiting' but always return the base buffer and
21940 not an indirect buffer."
21941 (let ((buf (or (get-file-buffer file)
21942 (find-buffer-visiting file))))
21943 (if buf
21944 (or (buffer-base-buffer buf) buf)
21945 nil)))
21947 (defun org-image-file-name-regexp (&optional extensions)
21948 "Return regexp matching the file names of images.
21949 If EXTENSIONS is given, only match these."
21950 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21951 (image-file-name-regexp)
21952 (let ((image-file-name-extensions
21953 (or extensions
21954 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21955 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21956 (concat "\\."
21957 (regexp-opt (nconc (mapcar 'upcase
21958 image-file-name-extensions)
21959 image-file-name-extensions)
21961 "\\'"))))
21963 (defun org-file-image-p (file &optional extensions)
21964 "Return non-nil if FILE is an image."
21965 (save-match-data
21966 (string-match (org-image-file-name-regexp extensions) file)))
21968 (defun org-get-cursor-date (&optional with-time)
21969 "Return the date at cursor in as a time.
21970 This works in the calendar and in the agenda, anywhere else it just
21971 returns the current time.
21972 If WITH-TIME is non-nil, returns the time of the event at point (in
21973 the agenda) or the current time of the day."
21974 (let (date day defd tp tm hod mod)
21975 (when with-time
21976 (setq tp (get-text-property (point) 'time))
21977 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21978 (setq hod (string-to-number (match-string 1 tp))
21979 mod (string-to-number (match-string 2 tp))))
21980 (or tp (setq hod (nth 2 (decode-time (current-time)))
21981 mod (nth 1 (decode-time (current-time))))))
21982 (cond
21983 ((eq major-mode 'calendar-mode)
21984 (setq date (calendar-cursor-to-date)
21985 defd (encode-time 0 (or mod 0) (or hod 0)
21986 (nth 1 date) (nth 0 date) (nth 2 date))))
21987 ((eq major-mode 'org-agenda-mode)
21988 (setq day (get-text-property (point) 'day))
21989 (if day
21990 (setq date (calendar-gregorian-from-absolute day)
21991 defd (encode-time 0 (or mod 0) (or hod 0)
21992 (nth 1 date) (nth 0 date) (nth 2 date))))))
21993 (or defd (current-time))))
21995 (defun org-mark-subtree (&optional up)
21996 "Mark the current subtree.
21997 This puts point at the start of the current subtree, and mark at
21998 the end. If a numeric prefix UP is given, move up into the
21999 hierarchy of headlines by UP levels before marking the subtree."
22000 (interactive "P")
22001 (org-with-limited-levels
22002 (cond ((org-at-heading-p) (beginning-of-line))
22003 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22004 (t (outline-previous-visible-heading 1))))
22005 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22006 (if (org-called-interactively-p 'any)
22007 (call-interactively 'org-mark-element)
22008 (org-mark-element)))
22011 ;;; Indentation
22013 (defun org-indent-line ()
22014 "Indent line depending on context."
22015 (interactive)
22016 (let* ((pos (point))
22017 (itemp (org-at-item-p))
22018 (case-fold-search t)
22019 (org-drawer-regexp (or org-drawer-regexp "\000"))
22020 (inline-task-p (and (featurep 'org-inlinetask)
22021 (org-inlinetask-in-task-p)))
22022 (inline-re (and inline-task-p
22023 (org-inlinetask-outline-regexp)))
22024 column)
22025 (if (and orgstruct-is-++ (eq pos (point)))
22026 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22027 (indent-according-to-mode))
22028 (beginning-of-line 1)
22029 (cond
22030 ;; Headings
22031 ((looking-at org-outline-regexp) (setq column 0))
22032 ;; Footnote definition
22033 ((looking-at org-footnote-definition-re) (setq column 0))
22034 ;; Literal examples
22035 ((looking-at "[ \t]*:\\( \\|$\\)")
22036 (setq column (org-get-indentation))) ; do nothing
22037 ;; Lists
22038 ((ignore-errors (goto-char (org-in-item-p)))
22039 (setq column (if itemp
22040 (org-get-indentation)
22041 (org-list-item-body-column (point))))
22042 (goto-char pos))
22043 ;; Drawers
22044 ((and (looking-at "[ \t]*:END:")
22045 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22046 (save-excursion
22047 (goto-char (1- (match-beginning 1)))
22048 (setq column (current-column))))
22049 ;; Special blocks
22050 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22051 (save-excursion
22052 (re-search-backward
22053 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22054 (setq column (org-get-indentation (match-string 0))))
22055 ((and (not (looking-at "[ \t]*#\\+begin_"))
22056 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22057 (save-excursion
22058 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22059 (setq column
22060 (cond ((equal (downcase (match-string 1)) "src")
22061 ;; src blocks: let `org-edit-src-exit' handle them
22062 (org-get-indentation))
22063 ((equal (downcase (match-string 1)) "example")
22064 (max (org-get-indentation)
22065 (org-get-indentation (match-string 0))))
22067 (org-get-indentation (match-string 0))))))
22068 ;; This line has nothing special, look at the previous relevant
22069 ;; line to compute indentation
22071 (beginning-of-line 0)
22072 (while (and (not (bobp))
22073 (not (looking-at org-table-line-regexp))
22074 (not (looking-at org-drawer-regexp))
22075 ;; When point started in an inline task, do not move
22076 ;; above task starting line.
22077 (not (and inline-task-p (looking-at inline-re)))
22078 ;; Skip drawers, blocks, empty lines, verbatim,
22079 ;; comments, tables, footnotes definitions, lists,
22080 ;; inline tasks.
22081 (or (and (looking-at "[ \t]*:END:")
22082 (re-search-backward org-drawer-regexp nil t))
22083 (and (looking-at "[ \t]*#\\+end_")
22084 (re-search-backward "[ \t]*#\\+begin_"nil t))
22085 (looking-at "[ \t]*[\n:#|]")
22086 (looking-at org-footnote-definition-re)
22087 (and (not inline-task-p)
22088 (featurep 'org-inlinetask)
22089 (org-inlinetask-in-task-p)
22090 (or (org-inlinetask-goto-beginning) t))))
22091 (beginning-of-line 0))
22092 (cond
22093 ;; There was a list item above.
22094 ((ignore-errors (goto-char (org-in-item-p)))
22095 (goto-char (org-list-get-top-point (org-list-struct)))
22096 (setq column (org-get-indentation)))
22097 ;; There was an heading above.
22098 ((looking-at "\\*+[ \t]+")
22099 (if (not org-adapt-indentation)
22100 (setq column 0)
22101 (goto-char (match-end 0))
22102 (setq column (current-column))))
22103 ;; A drawer had started and is unfinished
22104 ((looking-at org-drawer-regexp)
22105 (goto-char (1- (match-beginning 1)))
22106 (setq column (current-column)))
22107 ;; Else, nothing noticeable found: get indentation and go on.
22108 (t (setq column (org-get-indentation))))))
22109 ;; Now apply indentation and move cursor accordingly
22110 (goto-char pos)
22111 (if (<= (current-column) (current-indentation))
22112 (org-indent-line-to column)
22113 (save-excursion (org-indent-line-to column)))
22114 ;; Special polishing for properties, see `org-property-format'
22115 (setq column (current-column))
22116 (beginning-of-line 1)
22117 (if (looking-at org-property-re)
22118 (replace-match (concat (match-string 4)
22119 (format org-property-format
22120 (match-string 1) (match-string 3)))
22121 t t))
22122 (org-move-to-column column))))
22124 (defun org-indent-drawer ()
22125 "Indent the drawer at point."
22126 (interactive)
22127 (let ((p (point))
22128 (e (and (save-excursion (re-search-forward ":END:" nil t))
22129 (match-end 0)))
22130 (folded
22131 (save-excursion
22132 (end-of-line)
22133 (when (overlays-at (point))
22134 (member 'invisible (overlay-properties
22135 (car (overlays-at (point)))))))))
22136 (when folded (org-cycle))
22137 (indent-for-tab-command)
22138 (while (and (move-beginning-of-line 2) (< (point) e))
22139 (indent-for-tab-command))
22140 (goto-char p)
22141 (when folded (org-cycle)))
22142 (message "Drawer at point indented"))
22144 (defun org-indent-block ()
22145 "Indent the block at point."
22146 (interactive)
22147 (let ((p (point))
22148 (case-fold-search t)
22149 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22150 (match-end 0)))
22151 (folded
22152 (save-excursion
22153 (end-of-line)
22154 (when (overlays-at (point))
22155 (member 'invisible (overlay-properties
22156 (car (overlays-at (point)))))))))
22157 (when folded (org-cycle))
22158 (indent-for-tab-command)
22159 (while (and (move-beginning-of-line 2) (< (point) e))
22160 (indent-for-tab-command))
22161 (goto-char p)
22162 (when folded (org-cycle)))
22163 (message "Block at point indented"))
22165 (defun org-indent-region (start end)
22166 "Indent region."
22167 (interactive "r")
22168 (save-excursion
22169 (let ((line-end (org-current-line end)))
22170 (goto-char start)
22171 (while (< (org-current-line) line-end)
22172 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22173 (t (call-interactively 'org-indent-line)))
22174 (move-beginning-of-line 2)))))
22177 ;;; Filling
22179 ;; We use our own fill-paragraph and auto-fill functions.
22181 ;; `org-fill-paragraph' relies on adaptive filling and context
22182 ;; checking. Appropriate `fill-prefix' is computed with
22183 ;; `org-adaptive-fill-function'.
22185 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22186 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22187 ;; `org-adaptive-fill-function' value. Internally,
22188 ;; `org-comment-line-break-function' breaks the line.
22190 ;; `org-setup-filling' installs filling and auto-filling related
22191 ;; variables during `org-mode' initialization.
22193 (defvar org-element-paragraph-separate) ; org-element.el
22194 (defun org-setup-filling ()
22195 (require 'org-element)
22196 ;; Prevent auto-fill from inserting unwanted new items.
22197 (when (boundp 'fill-nobreak-predicate)
22198 (org-set-local
22199 'fill-nobreak-predicate
22200 (org-uniquify
22201 (append fill-nobreak-predicate
22202 '(org-fill-line-break-nobreak-p
22203 org-fill-paragraph-with-timestamp-nobreak-p)))))
22204 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22205 (org-set-local 'paragraph-start paragraph-ending)
22206 (org-set-local 'paragraph-separate paragraph-ending))
22207 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22208 (org-set-local 'auto-fill-inhibit-regexp nil)
22209 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22210 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22211 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22213 (defun org-fill-line-break-nobreak-p ()
22214 "Non-nil when a new line at point would create an Org line break."
22215 (save-excursion
22216 (skip-chars-backward "[ \t]")
22217 (skip-chars-backward "\\\\")
22218 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22220 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22221 "Non-nil when a new line at point would split a timestamp."
22222 (and (org-at-timestamp-p t)
22223 (not (looking-at org-ts-regexp-both))))
22225 (declare-function message-in-body-p "message" ())
22226 (defvar orgtbl-line-start-regexp) ; From org-table.el
22227 (defun org-adaptive-fill-function ()
22228 "Compute a fill prefix for the current line.
22229 Return fill prefix, as a string, or nil if current line isn't
22230 meant to be filled. For convenience, if `adaptive-fill-regexp'
22231 matches in paragraphs or comments, use it."
22232 (catch 'exit
22233 (when (derived-mode-p 'message-mode)
22234 (save-excursion
22235 (beginning-of-line)
22236 (cond ((or (not (message-in-body-p))
22237 (looking-at orgtbl-line-start-regexp))
22238 (throw 'exit nil))
22239 ((looking-at message-cite-prefix-regexp)
22240 (throw 'exit (match-string-no-properties 0)))
22241 ((looking-at org-outline-regexp)
22242 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22243 (org-with-wide-buffer
22244 (let* ((p (line-beginning-position))
22245 (element (save-excursion
22246 (beginning-of-line)
22247 (or (ignore-errors (org-element-at-point))
22248 (user-error "An element cannot be parsed line %d"
22249 (line-number-at-pos (point))))))
22250 (type (org-element-type element))
22251 (post-affiliated (org-element-property :post-affiliated element)))
22252 (unless (and post-affiliated (< p post-affiliated))
22253 (case type
22254 (comment
22255 (save-excursion
22256 (beginning-of-line)
22257 (looking-at "[ \t]*")
22258 (concat (match-string 0) "# ")))
22259 (footnote-definition "")
22260 ((item plain-list)
22261 (make-string (org-list-item-body-column
22262 (or post-affiliated
22263 (org-element-property :begin element)))
22264 ? ))
22265 (paragraph
22266 ;; Fill prefix is usually the same as the current line,
22267 ;; unless the paragraph is at the beginning of an item.
22268 (let ((parent (org-element-property :parent element)))
22269 (save-excursion
22270 (beginning-of-line)
22271 (cond ((eq (org-element-type parent) 'item)
22272 (make-string (org-list-item-body-column
22273 (org-element-property :begin parent))
22274 ? ))
22275 ((and adaptive-fill-regexp
22276 ;; Locally disable
22277 ;; `adaptive-fill-function' to let
22278 ;; `fill-context-prefix' handle
22279 ;; `adaptive-fill-regexp' variable.
22280 (let (adaptive-fill-function)
22281 (fill-context-prefix
22282 post-affiliated
22283 (org-element-property :end element)))))
22284 ((looking-at "[ \t]+") (match-string 0))
22285 (t "")))))
22286 (comment-block
22287 ;; Only fill contents if P is within block boundaries.
22288 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22289 (forward-line)
22290 (point)))
22291 (cend (save-excursion
22292 (goto-char (org-element-property :end element))
22293 (skip-chars-backward " \r\t\n")
22294 (line-beginning-position))))
22295 (when (and (>= p cbeg) (< p cend))
22296 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22297 (match-string 0)
22298 ""))))))))))
22300 (declare-function message-goto-body "message" ())
22301 (defvar message-cite-prefix-regexp) ; From message.el
22302 (defun org-fill-paragraph (&optional justify)
22303 "Fill element at point, when applicable.
22305 This function only applies to comment blocks, comments, example
22306 blocks and paragraphs. Also, as a special case, re-align table
22307 when point is at one.
22309 If JUSTIFY is non-nil (interactively, with prefix argument),
22310 justify as well. If `sentence-end-double-space' is non-nil, then
22311 period followed by one space does not end a sentence, so don't
22312 break a line there. The variable `fill-column' controls the
22313 width for filling.
22315 For convenience, when point is at a plain list, an item or
22316 a footnote definition, try to fill the first paragraph within."
22317 (interactive)
22318 (if (and (derived-mode-p 'message-mode)
22319 (or (not (message-in-body-p))
22320 (save-excursion (move-beginning-of-line 1)
22321 (looking-at message-cite-prefix-regexp))))
22322 ;; First ensure filling is correct in message-mode.
22323 (let ((fill-paragraph-function
22324 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22325 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22326 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22327 (paragraph-separate
22328 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22329 (fill-paragraph nil))
22330 (with-syntax-table org-mode-transpose-word-syntax-table
22331 ;; Move to end of line in order to get the first paragraph
22332 ;; within a plain list or a footnote definition.
22333 (let ((element (save-excursion
22334 (end-of-line)
22335 (or (ignore-errors (org-element-at-point))
22336 (user-error "An element cannot be parsed line %d"
22337 (line-number-at-pos (point)))))))
22338 ;; First check if point is in a blank line at the beginning of
22339 ;; the buffer. In that case, ignore filling.
22340 (case (org-element-type element)
22341 ;; Use major mode filling function is src blocks.
22342 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22343 ;; Align Org tables, leave table.el tables as-is.
22344 (table-row (org-table-align) t)
22345 (table
22346 (when (eq (org-element-property :type element) 'org)
22347 (save-excursion
22348 (goto-char (org-element-property :post-affiliated element))
22349 (org-table-align)))
22351 (paragraph
22352 ;; Paragraphs may contain `line-break' type objects.
22353 (let ((beg (max (point-min)
22354 (org-element-property :contents-begin element)))
22355 (end (min (point-max)
22356 (org-element-property :contents-end element))))
22357 ;; Do nothing if point is at an affiliated keyword.
22358 (if (< (line-end-position) beg) t
22359 (when (derived-mode-p 'message-mode)
22360 ;; In `message-mode', do not fill following citation
22361 ;; in current paragraph nor text before message body.
22362 (let ((body-start (save-excursion (message-goto-body))))
22363 (when body-start (setq beg (max body-start beg))))
22364 (when (save-excursion
22365 (re-search-forward
22366 (concat "^" message-cite-prefix-regexp) end t))
22367 (setq end (match-beginning 0))))
22368 ;; Fill paragraph, taking line breaks into account.
22369 ;; For that, slice the paragraph using line breaks as
22370 ;; separators, and fill the parts in reverse order to
22371 ;; avoid messing with markers.
22372 (save-excursion
22373 (goto-char end)
22374 (mapc
22375 (lambda (pos)
22376 (fill-region-as-paragraph pos (point) justify)
22377 (goto-char pos))
22378 ;; Find the list of ending positions for line breaks
22379 ;; in the current paragraph. Add paragraph
22380 ;; beginning to include first slice.
22381 (nreverse
22382 (cons beg
22383 (org-element-map
22384 (org-element--parse-objects
22385 beg end nil (org-element-restriction 'paragraph))
22386 'line-break
22387 (lambda (lb) (org-element-property :end lb)))))))
22388 t)))
22389 ;; Contents of `comment-block' type elements should be
22390 ;; filled as plain text, but only if point is within block
22391 ;; markers.
22392 (comment-block
22393 (let* ((case-fold-search t)
22394 (beg (save-excursion
22395 (goto-char (org-element-property :begin element))
22396 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22397 (forward-line)
22398 (point)))
22399 (end (save-excursion
22400 (goto-char (org-element-property :end element))
22401 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22402 (line-beginning-position))))
22403 (if (or (< (point) beg) (> (point) end)) t
22404 (fill-region-as-paragraph
22405 (save-excursion (end-of-line)
22406 (re-search-backward "^[ \t]*$" beg 'move)
22407 (line-beginning-position))
22408 (save-excursion (beginning-of-line)
22409 (re-search-forward "^[ \t]*$" end 'move)
22410 (line-beginning-position))
22411 justify))))
22412 ;; Fill comments.
22413 (comment
22414 (let ((begin (org-element-property :post-affiliated element))
22415 (end (org-element-property :end element)))
22416 (when (and (>= (point) begin) (<= (point) end))
22417 (let ((begin (save-excursion
22418 (end-of-line)
22419 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22420 (progn (forward-line) (point))
22421 begin)))
22422 (end (save-excursion
22423 (end-of-line)
22424 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22425 (1- (line-beginning-position))
22426 (skip-chars-backward " \r\t\n")
22427 (line-end-position)))))
22428 ;; Do not fill comments when at a blank line.
22429 (when (> end begin)
22430 (let ((fill-prefix
22431 (save-excursion
22432 (beginning-of-line)
22433 (looking-at "[ \t]*#")
22434 (let ((comment-prefix (match-string 0)))
22435 (goto-char (match-end 0))
22436 (if (looking-at adaptive-fill-regexp)
22437 (concat comment-prefix (match-string 0))
22438 (concat comment-prefix " "))))))
22439 (save-excursion
22440 (fill-region-as-paragraph begin end justify))))))
22442 ;; Ignore every other element.
22443 (otherwise t))))))
22445 (defun org-auto-fill-function ()
22446 "Auto-fill function."
22447 ;; Check if auto-filling is meaningful.
22448 (let ((fc (current-fill-column)))
22449 (when (and fc (> (current-column) fc))
22450 (let* ((fill-prefix (org-adaptive-fill-function))
22451 ;; Enforce empty fill prefix, if required. Otherwise, it
22452 ;; will be computed again.
22453 (adaptive-fill-mode (not (equal fill-prefix ""))))
22454 (when fill-prefix (do-auto-fill))))))
22456 (defun org-comment-line-break-function (&optional soft)
22457 "Break line at point and indent, continuing comment if within one.
22458 The inserted newline is marked hard if variable
22459 `use-hard-newlines' is true, unless optional argument SOFT is
22460 non-nil."
22461 (if soft (insert-and-inherit ?\n) (newline 1))
22462 (save-excursion (forward-char -1) (delete-horizontal-space))
22463 (delete-horizontal-space)
22464 (indent-to-left-margin)
22465 (insert-before-markers-and-inherit fill-prefix))
22468 ;;; Comments
22470 ;; Org comments syntax is quite complex. It requires the entire line
22471 ;; to be just a comment. Also, even with the right syntax at the
22472 ;; beginning of line, some some elements (i.e. verse-block or
22473 ;; example-block) don't accept comments. Usual Emacs comment commands
22474 ;; cannot cope with those requirements. Therefore, Org replaces them.
22476 ;; Org still relies on `comment-dwim', but cannot trust
22477 ;; `comment-only-p'. So, `comment-region-function' and
22478 ;; `uncomment-region-function' both point
22479 ;; to`org-comment-or-uncomment-region'. Eventually,
22480 ;; `org-insert-comment' takes care of insertion of comments at the
22481 ;; beginning of line.
22483 ;; `org-setup-comments-handling' install comments related variables
22484 ;; during `org-mode' initialization.
22486 (defun org-setup-comments-handling ()
22487 (interactive)
22488 (org-set-local 'comment-use-syntax nil)
22489 (org-set-local 'comment-start "# ")
22490 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22491 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22492 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22493 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22495 (defun org-insert-comment ()
22496 "Insert an empty comment above current line.
22497 If the line is empty, insert comment at its beginning."
22498 (if (org-in-src-block-p t)
22499 (progn
22500 (require 'ob-core)
22501 (org-babel-do-in-edit-buffer
22502 (call-interactively #'comment-dwim)))
22503 (beginning-of-line)
22504 (if (looking-at "\\s-*$")
22505 (delete-region (point) (point-at-eol))
22506 (open-line 1))
22507 (org-indent-line)
22508 (insert "# ")))
22510 (defvar comment-empty-lines) ; From newcomment.el.
22511 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22512 "Comment or uncomment each non-blank line in the region.
22513 Uncomment each non-blank line between BEG and END if it only
22514 contains commented lines. Otherwise, comment them."
22515 (let* ((pt (point-marker))
22516 (head (and (org-in-src-block-p t)
22517 (require 'ob-core)
22518 (org-babel-where-is-src-block-head)))
22519 (foot (and head
22520 (save-excursion
22521 (goto-char head)
22522 (looking-at org-babel-src-block-regexp)
22523 (goto-char (match-end 0))
22524 (point-at-bol)))))
22525 (if (and head foot
22526 (> beg head)
22527 (< end foot))
22528 (org-babel-do-in-edit-buffer
22529 (call-interactively #'comment-dwim))
22530 (save-restriction
22531 ;; Restrict region
22532 (narrow-to-region (save-excursion (goto-char beg)
22533 (skip-chars-forward " \r\t\n" end)
22534 (line-beginning-position))
22535 (save-excursion (goto-char end)
22536 (skip-chars-backward " \r\t\n" beg)
22537 (line-end-position)))
22538 (let ((uncommentp
22539 ;; UNCOMMENTP is non-nil when every non blank line between
22540 ;; BEG and END is a comment.
22541 (save-excursion
22542 (goto-char (point-min))
22543 (while (and (not (eobp))
22544 (let ((element (org-element-at-point)))
22545 (and (eq (org-element-type element) 'comment)
22546 (goto-char (min (point-max)
22547 (org-element-property
22548 :end element)))))))
22549 (eobp))))
22550 (if uncommentp
22551 ;; Only blank lines and comments in region: uncomment it.
22552 (save-excursion
22553 (goto-char (point-min))
22554 (while (not (eobp))
22555 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22556 (replace-match "" nil nil nil 1))
22557 (forward-line)))
22558 ;; Comment each line in region.
22559 (let ((min-indent (point-max)))
22560 ;; First find the minimum indentation across all lines.
22561 (save-excursion
22562 (goto-char (point-min))
22563 (while (and (not (eobp)) (not (zerop min-indent)))
22564 (unless (looking-at "[ \t]*$")
22565 (setq min-indent (min min-indent (current-indentation))))
22566 (forward-line)))
22567 ;; Then loop over all lines.
22568 (save-excursion
22569 (goto-char (point-min))
22570 (while (not (eobp))
22571 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22572 ;; Don't get fooled by invisible text (e.g. link path)
22573 ;; when moving to column MIN-INDENT.
22574 (let ((buffer-invisibility-spec nil))
22575 (org-move-to-column min-indent t))
22576 (insert comment-start))
22577 (forward-line))))))))))
22580 ;;; Planning
22582 ;; This section contains tools to operate on timestamp objects, as
22583 ;; returned by, e.g. `org-element-context'.
22585 (defun org-timestamp-has-time-p (timestamp)
22586 "Non-nil when TIMESTAMP has a time specified."
22587 (org-element-property :hour-start timestamp))
22589 (defun org-timestamp-format (timestamp format &optional end utc)
22590 "Format a TIMESTAMP element into a string.
22592 FORMAT is a format specifier to be passed to
22593 `format-time-string'.
22595 When optional argument END is non-nil, use end of date-range or
22596 time-range, if possible.
22598 When optional argument UTC is non-nil, time will be expressed as
22599 Universal Time."
22600 (format-time-string
22601 format
22602 (apply 'encode-time
22603 (cons 0
22604 (mapcar
22605 (lambda (prop) (or (org-element-property prop timestamp) 0))
22606 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22607 '(:minute-start :hour-start :day-start :month-start
22608 :year-start)))))
22609 utc))
22611 (defun org-timestamp-split-range (timestamp &optional end)
22612 "Extract a timestamp object from a date or time range.
22614 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22615 the end of the range. Otherwise, extract its start.
22617 Return a new timestamp object sharing the same parent as
22618 TIMESTAMP."
22619 (let ((type (org-element-property :type timestamp)))
22620 (if (memq type '(active inactive diary)) timestamp
22621 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22622 ;; Set new type.
22623 (org-element-put-property
22624 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22625 ;; Copy start properties over end properties if END is
22626 ;; non-nil. Otherwise, copy end properties over `start' ones.
22627 (let ((p-alist '((:minute-start . :minute-end)
22628 (:hour-start . :hour-end)
22629 (:day-start . :day-end)
22630 (:month-start . :month-end)
22631 (:year-start . :year-end))))
22632 (dolist (p-cell p-alist)
22633 (org-element-put-property
22634 split-ts
22635 (funcall (if end 'car 'cdr) p-cell)
22636 (org-element-property
22637 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22638 ;; Eventually refresh `:raw-value'.
22639 (org-element-put-property split-ts :raw-value nil)
22640 (org-element-put-property
22641 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22643 (defun org-timestamp-translate (timestamp &optional boundary)
22644 "Apply `org-translate-time' on a TIMESTAMP object.
22645 When optional argument BOUNDARY is non-nil, it is either the
22646 symbol `start' or `end'. In this case, only translate the
22647 starting or ending part of TIMESTAMP if it is a date or time
22648 range. Otherwise, translate both parts."
22649 (if (and (not boundary)
22650 (memq (org-element-property :type timestamp)
22651 '(active-range inactive-range)))
22652 (concat
22653 (org-translate-time
22654 (org-element-property :raw-value
22655 (org-timestamp-split-range timestamp)))
22656 "--"
22657 (org-translate-time
22658 (org-element-property :raw-value
22659 (org-timestamp-split-range timestamp t))))
22660 (org-translate-time
22661 (org-element-property
22662 :raw-value
22663 (if (not boundary) timestamp
22664 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22668 ;;; Other stuff.
22670 (defun org-toggle-fixed-width-section (arg)
22671 "Toggle the fixed-width export.
22672 If there is no active region, the QUOTE keyword at the current headline is
22673 inserted or removed. When present, it causes the text between this headline
22674 and the next to be exported as fixed-width text, and unmodified.
22675 If there is an active region, this command adds or removes a colon as the
22676 first character of this line. If the first character of a line is a colon,
22677 this line is also exported in fixed-width font."
22678 (interactive "P")
22679 (let* ((cc 0)
22680 (regionp (org-region-active-p))
22681 (beg (if regionp (region-beginning) (point)))
22682 (end (if regionp (region-end)))
22683 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22684 (case-fold-search nil)
22685 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22686 off)
22687 (if regionp
22688 (save-excursion
22689 (goto-char beg)
22690 (setq cc (current-column))
22691 (beginning-of-line 1)
22692 (setq off (looking-at re))
22693 (while (> nlines 0)
22694 (setq nlines (1- nlines))
22695 (beginning-of-line 1)
22696 (cond
22697 (arg
22698 (org-move-to-column cc t)
22699 (insert ": \n")
22700 (forward-line -1))
22701 ((and off (looking-at re))
22702 (replace-match "" t t nil 1))
22703 ((not off) (org-move-to-column cc t) (insert ": ")))
22704 (forward-line 1)))
22705 (save-excursion
22706 (org-back-to-heading)
22707 (cond
22708 ((looking-at (format org-heading-keyword-regexp-format
22709 org-quote-string))
22710 (goto-char (match-end 1))
22711 (looking-at (concat " +" org-quote-string))
22712 (replace-match "" t t)
22713 (when (eolp) (insert " ")))
22714 ((looking-at org-outline-regexp)
22715 (goto-char (match-end 0))
22716 (insert org-quote-string " ")))))))
22718 (defun org-reftex-citation ()
22719 "Use reftex-citation to insert a citation into the buffer.
22720 This looks for a line like
22722 #+BIBLIOGRAPHY: foo plain option:-d
22724 and derives from it that foo.bib is the bibliography file relevant
22725 for this document. It then installs the necessary environment for RefTeX
22726 to work in this buffer and calls `reftex-citation' to insert a citation
22727 into the buffer.
22729 Export of such citations to both LaTeX and HTML is handled by the contributed
22730 package ox-bibtex by Taru Karttunen."
22731 (interactive)
22732 (let ((reftex-docstruct-symbol 'rds)
22733 (reftex-cite-format "\\cite{%l}")
22734 rds bib)
22735 (save-excursion
22736 (save-restriction
22737 (widen)
22738 (let ((case-fold-search t)
22739 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22740 (if (not (save-excursion
22741 (or (re-search-forward re nil t)
22742 (re-search-backward re nil t))))
22743 (error "No bibliography defined in file")
22744 (setq bib (concat (match-string 1) ".bib")
22745 rds (list (list 'bib bib)))))))
22746 (call-interactively 'reftex-citation)))
22748 ;;;; Functions extending outline functionality
22750 (defun org-beginning-of-line (&optional arg)
22751 "Go to the beginning of the current line. If that is invisible, continue
22752 to a visible line beginning. This makes the function of C-a more intuitive.
22753 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22754 first attempt, and only move to after the tags when the cursor is already
22755 beyond the end of the headline."
22756 (interactive "P")
22757 (let ((pos (point))
22758 (special (if (consp org-special-ctrl-a/e)
22759 (car org-special-ctrl-a/e)
22760 org-special-ctrl-a/e))
22761 deactivate-mark refpos)
22762 (if (org-bound-and-true-p visual-line-mode)
22763 (beginning-of-visual-line 1)
22764 (beginning-of-line 1))
22765 (if (and arg (fboundp 'move-beginning-of-line))
22766 (call-interactively 'move-beginning-of-line)
22767 (if (bobp)
22769 (backward-char 1)
22770 (if (org-truely-invisible-p)
22771 (while (and (not (bobp)) (org-truely-invisible-p))
22772 (backward-char 1)
22773 (beginning-of-line 1))
22774 (forward-char 1))))
22775 (when special
22776 (cond
22777 ((and (looking-at org-complex-heading-regexp)
22778 (= (char-after (match-end 1)) ?\ ))
22779 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22780 (point-at-eol)))
22781 (goto-char
22782 (if (eq special t)
22783 (cond ((> pos refpos) refpos)
22784 ((= pos (point)) refpos)
22785 (t (point)))
22786 (cond ((> pos (point)) (point))
22787 ((not (eq last-command this-command)) (point))
22788 (t refpos)))))
22789 ((org-at-item-p)
22790 ;; Being at an item and not looking at an the item means point
22791 ;; was previously moved to beginning of a visual line, which
22792 ;; doesn't contain the item. Therefore, do nothing special,
22793 ;; just stay here.
22794 (when (looking-at org-list-full-item-re)
22795 ;; Set special position at first white space character after
22796 ;; bullet, and check-box, if any.
22797 (let ((after-bullet
22798 (let ((box (match-end 3)))
22799 (if (not box) (match-end 1)
22800 (let ((after (char-after box)))
22801 (if (and after (= after ? )) (1+ box) box))))))
22802 ;; Special case: Move point to special position when
22803 ;; currently after it or at beginning of line.
22804 (if (eq special t)
22805 (when (or (> pos after-bullet) (= (point) pos))
22806 (goto-char after-bullet))
22807 ;; Reversed case: Move point to special position when
22808 ;; point was already at beginning of line and command is
22809 ;; repeated.
22810 (when (and (= (point) pos) (eq last-command this-command))
22811 (goto-char after-bullet))))))))
22812 (org-no-warnings
22813 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22814 (setq disable-point-adjustment
22815 (or (not (invisible-p (point)))
22816 (not (invisible-p (max (point-min) (1- (point))))))))
22818 (defun org-end-of-line (&optional arg)
22819 "Go to the end of the line.
22820 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22821 tags on the first attempt, and only move to after the tags when
22822 the cursor is already beyond the end of the headline."
22823 (interactive "P")
22824 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22825 org-special-ctrl-a/e))
22826 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22827 'end-of-visual-line)
22828 ((fboundp 'move-end-of-line) 'move-end-of-line)
22829 (t 'end-of-line)))
22830 deactivate-mark)
22831 (if (or (not special) arg) (call-interactively move-fun)
22832 (let* ((element (save-excursion (beginning-of-line)
22833 (org-element-at-point)))
22834 (type (org-element-type element)))
22835 (cond
22836 ((memq type '(headline inlinetask))
22837 (let ((pos (point)))
22838 (beginning-of-line 1)
22839 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22840 (if (eq special t)
22841 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22842 (goto-char (match-beginning 1))
22843 (goto-char (match-end 0)))
22844 (if (or (< pos (match-end 0))
22845 (not (eq this-command last-command)))
22846 (goto-char (match-end 0))
22847 (goto-char (match-beginning 1))))
22848 (call-interactively move-fun))))
22849 ((outline-invisible-p (line-end-position))
22850 ;; If element is hidden, `move-end-of-line' would put point
22851 ;; after it. Use `end-of-line' to stay on current line.
22852 (call-interactively 'end-of-line))
22853 (t (call-interactively move-fun)))))
22854 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22855 (setq disable-point-adjustment
22856 (or (not (invisible-p (point)))
22857 (not (invisible-p (max (point-min) (1- (point))))))))
22859 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22860 (define-key org-mode-map "\C-e" 'org-end-of-line)
22862 (defun org-backward-sentence (&optional arg)
22863 "Go to beginning of sentence, or beginning of table field.
22864 This will call `backward-sentence' or `org-table-beginning-of-field',
22865 depending on context."
22866 (interactive "P")
22867 (cond
22868 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22869 (t (call-interactively 'backward-sentence))))
22871 (defun org-forward-sentence (&optional arg)
22872 "Go to end of sentence, or end of table field.
22873 This will call `forward-sentence' or `org-table-end-of-field',
22874 depending on context."
22875 (interactive "P")
22876 (cond
22877 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22878 (t (call-interactively 'forward-sentence))))
22880 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22881 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22883 (defun org-kill-line (&optional arg)
22884 "Kill line, to tags or end of line."
22885 (interactive "P")
22886 (cond
22887 ((or (not org-special-ctrl-k)
22888 (bolp)
22889 (not (org-at-heading-p)))
22890 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22891 org-ctrl-k-protect-subtree)
22892 (if (or (eq org-ctrl-k-protect-subtree 'error)
22893 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22894 (user-error "C-k aborted as it would kill a hidden subtree")))
22895 (call-interactively
22896 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22897 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22898 (kill-region (point) (match-beginning 1))
22899 (org-set-tags nil t))
22900 (t (kill-region (point) (point-at-eol)))))
22902 (define-key org-mode-map "\C-k" 'org-kill-line)
22904 (defun org-yank (&optional arg)
22905 "Yank. If the kill is a subtree, treat it specially.
22906 This command will look at the current kill and check if is a single
22907 subtree, or a series of subtrees[1]. If it passes the test, and if the
22908 cursor is at the beginning of a line or after the stars of a currently
22909 empty headline, then the yank is handled specially. How exactly depends
22910 on the value of the following variables, both set by default.
22912 org-yank-folded-subtrees
22913 When set, the subtree(s) will be folded after insertion, but only
22914 if doing so would now swallow text after the yanked text.
22916 org-yank-adjusted-subtrees
22917 When set, the subtree will be promoted or demoted in order to
22918 fit into the local outline tree structure, which means that the level
22919 will be adjusted so that it becomes the smaller one of the two
22920 *visible* surrounding headings.
22922 Any prefix to this command will cause `yank' to be called directly with
22923 no special treatment. In particular, a simple \\[universal-argument] prefix \
22924 will just
22925 plainly yank the text as it is.
22927 \[1] The test checks if the first non-white line is a heading
22928 and if there are no other headings with fewer stars."
22929 (interactive "P")
22930 (org-yank-generic 'yank arg))
22932 (defun org-yank-generic (command arg)
22933 "Perform some yank-like command.
22935 This function implements the behavior described in the `org-yank'
22936 documentation. However, it has been generalized to work for any
22937 interactive command with similar behavior."
22939 ;; pretend to be command COMMAND
22940 (setq this-command command)
22942 (if arg
22943 (call-interactively command)
22945 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22946 (and (org-kill-is-subtree-p)
22947 (or (bolp)
22948 (and (looking-at "[ \t]*$")
22949 (string-match
22950 "\\`\\*+\\'"
22951 (buffer-substring (point-at-bol) (point)))))))
22952 swallowp)
22953 (cond
22954 ((and subtreep org-yank-folded-subtrees)
22955 (let ((beg (point))
22956 end)
22957 (if (and subtreep org-yank-adjusted-subtrees)
22958 (org-paste-subtree nil nil 'for-yank)
22959 (call-interactively command))
22961 (setq end (point))
22962 (goto-char beg)
22963 (when (and (bolp) subtreep
22964 (not (setq swallowp
22965 (org-yank-folding-would-swallow-text beg end))))
22966 (org-with-limited-levels
22967 (or (looking-at org-outline-regexp)
22968 (re-search-forward org-outline-regexp-bol end t))
22969 (while (and (< (point) end) (looking-at org-outline-regexp))
22970 (hide-subtree)
22971 (org-cycle-show-empty-lines 'folded)
22972 (condition-case nil
22973 (outline-forward-same-level 1)
22974 (error (goto-char end))))))
22975 (when swallowp
22976 (message
22977 "Inserted text not folded because that would swallow text"))
22979 (goto-char end)
22980 (skip-chars-forward " \t\n\r")
22981 (beginning-of-line 1)
22982 (push-mark beg 'nomsg)))
22983 ((and subtreep org-yank-adjusted-subtrees)
22984 (let ((beg (point-at-bol)))
22985 (org-paste-subtree nil nil 'for-yank)
22986 (push-mark beg 'nomsg)))
22988 (call-interactively command))))))
22990 (defun org-yank-folding-would-swallow-text (beg end)
22991 "Would hide-subtree at BEG swallow any text after END?"
22992 (let (level)
22993 (org-with-limited-levels
22994 (save-excursion
22995 (goto-char beg)
22996 (when (or (looking-at org-outline-regexp)
22997 (re-search-forward org-outline-regexp-bol end t))
22998 (setq level (org-outline-level)))
22999 (goto-char end)
23000 (skip-chars-forward " \t\r\n\v\f")
23001 (if (or (eobp)
23002 (and (bolp) (looking-at org-outline-regexp)
23003 (<= (org-outline-level) level)))
23004 nil ; Nothing would be swallowed
23005 t))))) ; something would swallow
23007 (define-key org-mode-map "\C-y" 'org-yank)
23009 (defun org-truely-invisible-p ()
23010 "Check if point is at a character currently not visible.
23011 This version does not only check the character property, but also
23012 `visible-mode'."
23013 ;; Early versions of noutline don't have `outline-invisible-p'.
23014 (if (org-bound-and-true-p visible-mode)
23016 (outline-invisible-p)))
23018 (defun org-invisible-p2 ()
23019 "Check if point is at a character currently not visible."
23020 (save-excursion
23021 (if (and (eolp) (not (bobp))) (backward-char 1))
23022 ;; Early versions of noutline don't have `outline-invisible-p'.
23023 (outline-invisible-p)))
23025 (defun org-back-to-heading (&optional invisible-ok)
23026 "Call `outline-back-to-heading', but provide a better error message."
23027 (condition-case nil
23028 (outline-back-to-heading invisible-ok)
23029 (error (error "Before first headline at position %d in buffer %s"
23030 (point) (current-buffer)))))
23032 (defun org-before-first-heading-p ()
23033 "Before first heading?"
23034 (save-excursion
23035 (end-of-line)
23036 (null (re-search-backward org-outline-regexp-bol nil t))))
23038 (defun org-at-heading-p (&optional ignored)
23039 (outline-on-heading-p t))
23040 ;; Compatibility alias with Org versions < 7.8.03
23041 (defalias 'org-on-heading-p 'org-at-heading-p)
23043 (defun org-at-comment-p nil
23044 "Is cursor in a line starting with a # character?"
23045 (save-excursion
23046 (beginning-of-line)
23047 (looking-at "^#")))
23049 (defun org-at-drawer-p nil
23050 "Is cursor at a drawer keyword?"
23051 (save-excursion
23052 (move-beginning-of-line 1)
23053 (looking-at org-drawer-regexp)))
23055 (defun org-at-block-p nil
23056 "Is cursor at a block keyword?"
23057 (save-excursion
23058 (move-beginning-of-line 1)
23059 (looking-at org-block-regexp)))
23061 (defun org-point-at-end-of-empty-headline ()
23062 "If point is at the end of an empty headline, return t, else nil.
23063 If the heading only contains a TODO keyword, it is still still considered
23064 empty."
23065 (and (looking-at "[ \t]*$")
23066 (when org-todo-line-regexp
23067 (save-excursion
23068 (beginning-of-line 1)
23069 (let ((case-fold-search nil))
23070 (looking-at org-todo-line-regexp)
23071 (string= (match-string 3) ""))))))
23073 (defun org-at-heading-or-item-p ()
23074 (or (org-at-heading-p) (org-at-item-p)))
23076 (defun org-at-target-p ()
23077 (or (org-in-regexp org-radio-target-regexp)
23078 (org-in-regexp org-target-regexp)))
23079 ;; Compatibility alias with Org versions < 7.8.03
23080 (defalias 'org-on-target-p 'org-at-target-p)
23082 (defun org-up-heading-all (arg)
23083 "Move to the heading line of which the present line is a subheading.
23084 This function considers both visible and invisible heading lines.
23085 With argument, move up ARG levels."
23086 (if (fboundp 'outline-up-heading-all)
23087 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23088 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23090 (defun org-up-heading-safe ()
23091 "Move to the heading line of which the present line is a subheading.
23092 This version will not throw an error. It will return the level of the
23093 headline found, or nil if no higher level is found.
23095 Also, this function will be a lot faster than `outline-up-heading',
23096 because it relies on stars being the outline starters. This can really
23097 make a significant difference in outlines with very many siblings."
23098 (let (start-level re)
23099 (org-back-to-heading t)
23100 (setq start-level (funcall outline-level))
23101 (if (equal start-level 1)
23103 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23104 (if (re-search-backward re nil t)
23105 (funcall outline-level)))))
23107 (defun org-first-sibling-p ()
23108 "Is this heading the first child of its parents?"
23109 (interactive)
23110 (let ((re org-outline-regexp-bol)
23111 level l)
23112 (unless (org-at-heading-p t)
23113 (user-error "Not at a heading"))
23114 (setq level (funcall outline-level))
23115 (save-excursion
23116 (if (not (re-search-backward re nil t))
23118 (setq l (funcall outline-level))
23119 (< l level)))))
23121 (defun org-goto-sibling (&optional previous)
23122 "Goto the next sibling, even if it is invisible.
23123 When PREVIOUS is set, go to the previous sibling instead. Returns t
23124 when a sibling was found. When none is found, return nil and don't
23125 move point."
23126 (let ((fun (if previous 're-search-backward 're-search-forward))
23127 (pos (point))
23128 (re org-outline-regexp-bol)
23129 level l)
23130 (when (condition-case nil (org-back-to-heading t) (error nil))
23131 (setq level (funcall outline-level))
23132 (catch 'exit
23133 (or previous (forward-char 1))
23134 (while (funcall fun re nil t)
23135 (setq l (funcall outline-level))
23136 (when (< l level) (goto-char pos) (throw 'exit nil))
23137 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23138 (goto-char pos)
23139 nil))))
23141 (defun org-show-siblings ()
23142 "Show all siblings of the current headline."
23143 (save-excursion
23144 (while (org-goto-sibling) (org-flag-heading nil)))
23145 (save-excursion
23146 (while (org-goto-sibling 'previous)
23147 (org-flag-heading nil))))
23149 (defun org-goto-first-child ()
23150 "Goto the first child, even if it is invisible.
23151 Return t when a child was found. Otherwise don't move point and
23152 return nil."
23153 (let (level (pos (point)) (re org-outline-regexp-bol))
23154 (when (condition-case nil (org-back-to-heading t) (error nil))
23155 (setq level (outline-level))
23156 (forward-char 1)
23157 (if (and (re-search-forward re nil t) (> (outline-level) level))
23158 (progn (goto-char (match-beginning 0)) t)
23159 (goto-char pos) nil))))
23161 (defun org-show-hidden-entry ()
23162 "Show an entry where even the heading is hidden."
23163 (save-excursion
23164 (org-show-entry)))
23166 (defun org-flag-heading (flag &optional entry)
23167 "Flag the current heading. FLAG non-nil means make invisible.
23168 When ENTRY is non-nil, show the entire entry."
23169 (save-excursion
23170 (org-back-to-heading t)
23171 ;; Check if we should show the entire entry
23172 (if entry
23173 (progn
23174 (org-show-entry)
23175 (save-excursion
23176 (and (outline-next-heading)
23177 (org-flag-heading nil))))
23178 (outline-flag-region (max (point-min) (1- (point)))
23179 (save-excursion (outline-end-of-heading) (point))
23180 flag))))
23182 (defun org-get-next-sibling ()
23183 "Move to next heading of the same level, and return point.
23184 If there is no such heading, return nil.
23185 This is like outline-next-sibling, but invisible headings are ok."
23186 (let ((level (funcall outline-level)))
23187 (outline-next-heading)
23188 (while (and (not (eobp)) (> (funcall outline-level) level))
23189 (outline-next-heading))
23190 (if (or (eobp) (< (funcall outline-level) level))
23192 (point))))
23194 (defun org-get-last-sibling ()
23195 "Move to previous heading of the same level, and return point.
23196 If there is no such heading, return nil."
23197 (let ((opoint (point))
23198 (level (funcall outline-level)))
23199 (outline-previous-heading)
23200 (when (and (/= (point) opoint) (outline-on-heading-p t))
23201 (while (and (> (funcall outline-level) level)
23202 (not (bobp)))
23203 (outline-previous-heading))
23204 (if (< (funcall outline-level) level)
23206 (point)))))
23208 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23209 "Goto to the end of a subtree."
23210 ;; This contains an exact copy of the original function, but it uses
23211 ;; `org-back-to-heading', to make it work also in invisible
23212 ;; trees. And is uses an invisible-ok argument.
23213 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23214 ;; Furthermore, when used inside Org, finding the end of a large subtree
23215 ;; with many children and grandchildren etc, this can be much faster
23216 ;; than the outline version.
23217 (org-back-to-heading invisible-ok)
23218 (let ((first t)
23219 (level (funcall outline-level)))
23220 (if (and (derived-mode-p 'org-mode) (< level 1000))
23221 ;; A true heading (not a plain list item), in Org-mode
23222 ;; This means we can easily find the end by looking
23223 ;; only for the right number of stars. Using a regexp to do
23224 ;; this is so much faster than using a Lisp loop.
23225 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23226 (forward-char 1)
23227 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23228 ;; something else, do it the slow way
23229 (while (and (not (eobp))
23230 (or first (> (funcall outline-level) level)))
23231 (setq first nil)
23232 (outline-next-heading)))
23233 (unless to-heading
23234 (if (memq (preceding-char) '(?\n ?\^M))
23235 (progn
23236 ;; Go to end of line before heading
23237 (forward-char -1)
23238 (if (memq (preceding-char) '(?\n ?\^M))
23239 ;; leave blank line before heading
23240 (forward-char -1))))))
23241 (point))
23243 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23244 "Use Org version in org-mode, for dramatic speed-up."
23245 (if (derived-mode-p 'org-mode)
23246 (progn
23247 (org-end-of-subtree nil t)
23248 (unless (eobp) (backward-char 1)))
23249 ad-do-it))
23251 (defun org-end-of-meta-data-and-drawers ()
23252 "Jump to the first text after meta data and drawers in the current entry.
23253 This will move over empty lines, lines with planning time stamps,
23254 clocking lines, and drawers."
23255 (org-back-to-heading t)
23256 (let ((end (save-excursion (outline-next-heading) (point)))
23257 (re (concat "\\(" org-drawer-regexp "\\)"
23258 "\\|" "[ \t]*" org-keyword-time-regexp)))
23259 (forward-line 1)
23260 (while (re-search-forward re end t)
23261 (if (not (match-end 1))
23262 ;; empty or planning line
23263 (forward-line 1)
23264 ;; a drawer, find the end
23265 (re-search-forward "^[ \t]*:END:" end 'move)
23266 (forward-line 1)))
23267 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23268 (point)))
23270 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23271 "Move forward to the ARG'th subheading at same level as this one.
23272 Stop at the first and last subheadings of a superior heading.
23273 Normally this only looks at visible headings, but when INVISIBLE-OK is
23274 non-nil it will also look at invisible ones."
23275 (interactive "p")
23276 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23277 (if (and arg (< arg 0))
23278 (goto-char (point-min))
23279 (outline-next-heading))
23280 (org-at-heading-p)
23281 (let ((level (- (match-end 0) (match-beginning 0) 1))
23282 (f (if (and arg (< arg 0))
23283 're-search-backward
23284 're-search-forward))
23285 (count (if arg (abs arg) 1))
23286 (result (point)))
23287 (while (and (prog1 (> count 0)
23288 (forward-char (if (and arg (< arg 0)) -1 1)))
23289 (funcall f org-outline-regexp-bol nil 'move))
23290 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23291 (cond ((< l level) (setq count 0))
23292 ((and (= l level)
23293 (or invisible-ok
23294 (progn
23295 (goto-char (line-beginning-position))
23296 (not (outline-invisible-p)))))
23297 (setq count (1- count))
23298 (when (eq l level)
23299 (setq result (point)))))))
23300 (goto-char result))
23301 (beginning-of-line 1)))
23303 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23304 "Move backward to the ARG'th subheading at same level as this one.
23305 Stop at the first and last subheadings of a superior heading."
23306 (interactive "p")
23307 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23309 (defun org-next-block (arg &optional backward block-regexp)
23310 "Jump to the next block.
23311 With a prefix argument ARG, jump forward ARG many source blocks.
23312 When BACKWARD is non-nil, jump to the previous block.
23313 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23314 (interactive "p")
23315 (let ((re (or block-regexp org-block-regexp))
23316 (re-search-fn (or (and backward 're-search-backward)
23317 're-search-forward)))
23318 (if (looking-at re) (forward-char 1))
23319 (condition-case nil
23320 (funcall re-search-fn re nil nil arg)
23321 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23322 (goto-char (match-beginning 0)) (org-show-context)))
23324 (defun org-previous-block (arg &optional block-regexp)
23325 "Jump to the previous block.
23326 With a prefix argument ARG, jump backward ARG many source blocks.
23327 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23328 (interactive "p")
23329 (org-next-block arg t block-regexp))
23331 (defun org-forward-paragraph ()
23332 "Move forward to beginning of next paragraph or equivalent.
23334 The function moves point to the beginning of the next visible
23335 structural element, which can be a paragraph, a table, a list
23336 item, etc. It also provides some special moves for convenience:
23338 - On an affiliated keyword, jump to the beginning of the
23339 relative element.
23340 - On an item or a footnote definition, move to the second
23341 element inside, if any.
23342 - On a table or a property drawer, jump after it.
23343 - On a verse or source block, stop after blank lines."
23344 (interactive)
23345 (when (eobp) (user-error "Cannot move further down"))
23346 (let* ((deactivate-mark nil)
23347 (element (org-element-at-point))
23348 (type (org-element-type element))
23349 (post-affiliated (org-element-property :post-affiliated element))
23350 (contents-begin (org-element-property :contents-begin element))
23351 (contents-end (org-element-property :contents-end element))
23352 (end (let ((end (org-element-property :end element)) (parent element))
23353 (while (and (setq parent (org-element-property :parent parent))
23354 (= (org-element-property :contents-end parent) end))
23355 (setq end (org-element-property :end parent)))
23356 end)))
23357 (cond ((not element)
23358 (skip-chars-forward " \r\t\n")
23359 (or (eobp) (beginning-of-line)))
23360 ;; On affiliated keywords, move to element's beginning.
23361 ((and post-affiliated (< (point) post-affiliated))
23362 (goto-char post-affiliated))
23363 ;; At a table row, move to the end of the table. Similarly,
23364 ;; at a node property, move to the end of the property
23365 ;; drawer.
23366 ((memq type '(node-property table-row))
23367 (goto-char (org-element-property
23368 :end (org-element-property :parent element))))
23369 ((memq type '(property-drawer table)) (goto-char end))
23370 ;; Consider blank lines as separators in verse and source
23371 ;; blocks to ease editing.
23372 ((memq type '(src-block verse-block))
23373 (when (eq type 'src-block)
23374 (setq contents-end
23375 (save-excursion (goto-char end)
23376 (skip-chars-backward " \r\t\n")
23377 (line-beginning-position))))
23378 (beginning-of-line)
23379 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23380 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23381 (goto-char end)
23382 (skip-chars-forward " \r\t\n")
23383 (if (= (point) contents-end) (goto-char end)
23384 (beginning-of-line))))
23385 ;; With no contents, just skip element.
23386 ((not contents-begin) (goto-char end))
23387 ;; If contents are invisible, skip the element altogether.
23388 ((outline-invisible-p (line-end-position))
23389 (case type
23390 (headline
23391 (org-with-limited-levels (outline-next-visible-heading 1)))
23392 ;; At a plain list, make sure we move to the next item
23393 ;; instead of skipping the whole list.
23394 (plain-list (forward-char)
23395 (org-forward-paragraph))
23396 (otherwise (goto-char end))))
23397 ((>= (point) contents-end) (goto-char end))
23398 ((>= (point) contents-begin)
23399 ;; This can only happen on paragraphs and plain lists.
23400 (case type
23401 (paragraph (goto-char end))
23402 ;; At a plain list, try to move to second element in
23403 ;; first item, if possible.
23404 (plain-list (end-of-line)
23405 (org-forward-paragraph))))
23406 ;; When contents start on the middle of a line (e.g. in
23407 ;; items and footnote definitions), try to reach first
23408 ;; element starting after current line.
23409 ((> (line-end-position) contents-begin)
23410 (end-of-line)
23411 (org-forward-paragraph))
23412 (t (goto-char contents-begin)))))
23414 (defun org-backward-paragraph ()
23415 "Move backward to start of previous paragraph or equivalent.
23417 The function moves point to the beginning of the current
23418 structural element, which can be a paragraph, a table, a list
23419 item, etc., or to the beginning of the previous visible one if
23420 point is already there. It also provides some special moves for
23421 convenience:
23423 - On an affiliated keyword, jump to the first one.
23424 - On a table or a property drawer, move to its beginning.
23425 - On a verse or source block, stop before blank lines."
23426 (interactive)
23427 (when (bobp) (user-error "Cannot move further up"))
23428 (let* ((deactivate-mark nil)
23429 (element (org-element-at-point))
23430 (type (org-element-type element))
23431 (contents-begin (org-element-property :contents-begin element))
23432 (contents-end (org-element-property :contents-end element))
23433 (post-affiliated (org-element-property :post-affiliated element))
23434 (begin (org-element-property :begin element)))
23435 (cond
23436 ((not element) (goto-char (point-min)))
23437 ((= (point) begin)
23438 (backward-char)
23439 (org-backward-paragraph))
23440 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23441 ((memq type '(node-property table-row))
23442 (goto-char (org-element-property
23443 :post-affiliated (org-element-property :parent element))))
23444 ((memq type '(property-drawer table)) (goto-char begin))
23445 ((memq type '(src-block verse-block))
23446 (when (eq type 'src-block)
23447 (setq contents-begin
23448 (save-excursion (goto-char begin) (forward-line) (point))))
23449 (if (= (point) contents-begin) (goto-char post-affiliated)
23450 ;; Inside a verse block, see blank lines as paragraph
23451 ;; separators.
23452 (let ((origin (point)))
23453 (skip-chars-backward " \r\t\n" contents-begin)
23454 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23455 (skip-chars-forward " \r\t\n" origin)
23456 (if (= (point) origin) (goto-char contents-begin)
23457 (beginning-of-line))))))
23458 ((not contents-begin) (goto-char (or post-affiliated begin)))
23459 ((eq type 'paragraph)
23460 (goto-char contents-begin)
23461 ;; When at first paragraph in an item or a footnote definition,
23462 ;; move directly to beginning of line.
23463 (let ((parent-contents
23464 (org-element-property
23465 :contents-begin (org-element-property :parent element))))
23466 (when (and parent-contents (= parent-contents contents-begin))
23467 (beginning-of-line))))
23468 ;; At the end of a greater element, move to the beginning of the
23469 ;; last element within.
23470 ((>= (point) contents-end)
23471 (goto-char (1- contents-end))
23472 (org-backward-paragraph))
23473 (t (goto-char (or post-affiliated begin))))
23474 ;; Ensure we never leave point invisible.
23475 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23477 (defun org-forward-element ()
23478 "Move forward by one element.
23479 Move to the next element at the same level, when possible."
23480 (interactive)
23481 (cond ((eobp) (user-error "Cannot move further down"))
23482 ((org-with-limited-levels (org-at-heading-p))
23483 (let ((origin (point)))
23484 (goto-char (org-end-of-subtree nil t))
23485 (unless (org-with-limited-levels (org-at-heading-p))
23486 (goto-char origin)
23487 (user-error "Cannot move further down"))))
23489 (let* ((elem (org-element-at-point))
23490 (end (org-element-property :end elem))
23491 (parent (org-element-property :parent elem)))
23492 (cond ((and parent (= (org-element-property :contents-end parent) end))
23493 (goto-char (org-element-property :end parent)))
23494 ((integer-or-marker-p end) (goto-char end))
23495 (t (message "No element at point")))))))
23497 (defun org-backward-element ()
23498 "Move backward by one element.
23499 Move to the previous element at the same level, when possible."
23500 (interactive)
23501 (cond ((bobp) (user-error "Cannot move further up"))
23502 ((org-with-limited-levels (org-at-heading-p))
23503 ;; At a headline, move to the previous one, if any, or stay
23504 ;; here.
23505 (let ((origin (point)))
23506 (org-with-limited-levels (org-backward-heading-same-level 1))
23507 ;; When current headline has no sibling above, move to its
23508 ;; parent.
23509 (when (= (point) origin)
23510 (or (org-with-limited-levels (org-up-heading-safe))
23511 (progn (goto-char origin)
23512 (user-error "Cannot move further up"))))))
23514 (let* ((trail (org-element-at-point 'keep-trail))
23515 (elem (car trail))
23516 (prev-elem (nth 1 trail))
23517 (beg (org-element-property :begin elem)))
23518 (cond
23519 ;; Move to beginning of current element if point isn't
23520 ;; there already.
23521 ((null beg) (message "No element at point"))
23522 ((/= (point) beg) (goto-char beg))
23523 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23524 ((org-before-first-heading-p) (goto-char (point-min)))
23525 (t (org-back-to-heading)))))))
23527 (defun org-up-element ()
23528 "Move to upper element."
23529 (interactive)
23530 (if (org-with-limited-levels (org-at-heading-p))
23531 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23532 (let* ((elem (org-element-at-point))
23533 (parent (org-element-property :parent elem)))
23534 (if parent (goto-char (org-element-property :begin parent))
23535 (if (org-with-limited-levels (org-before-first-heading-p))
23536 (user-error "No surrounding element")
23537 (org-with-limited-levels (org-back-to-heading)))))))
23539 (defvar org-element-greater-elements)
23540 (defun org-down-element ()
23541 "Move to inner element."
23542 (interactive)
23543 (let ((element (org-element-at-point)))
23544 (cond
23545 ((memq (org-element-type element) '(plain-list table))
23546 (goto-char (org-element-property :contents-begin element))
23547 (forward-char))
23548 ((memq (org-element-type element) org-element-greater-elements)
23549 ;; If contents are hidden, first disclose them.
23550 (when (outline-invisible-p (line-end-position)) (org-cycle))
23551 (goto-char (or (org-element-property :contents-begin element)
23552 (user-error "No content for this element"))))
23553 (t (user-error "No inner element")))))
23555 (defun org-drag-element-backward ()
23556 "Move backward element at point."
23557 (interactive)
23558 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23559 (let* ((trail (org-element-at-point 'keep-trail))
23560 (elem (car trail))
23561 (prev-elem (nth 1 trail)))
23562 ;; Error out if no previous element or previous element is
23563 ;; a parent of the current one.
23564 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23565 (user-error "Cannot drag element backward")
23566 (let ((pos (point)))
23567 (org-element-swap-A-B prev-elem elem)
23568 (goto-char (+ (org-element-property :begin prev-elem)
23569 (- pos (org-element-property :begin elem)))))))))
23571 (defun org-drag-element-forward ()
23572 "Move forward element at point."
23573 (interactive)
23574 (let* ((pos (point))
23575 (elem (org-element-at-point)))
23576 (when (= (point-max) (org-element-property :end elem))
23577 (user-error "Cannot drag element forward"))
23578 (goto-char (org-element-property :end elem))
23579 (let ((next-elem (org-element-at-point)))
23580 (when (or (org-element-nested-p elem next-elem)
23581 (and (eq (org-element-type next-elem) 'headline)
23582 (not (eq (org-element-type elem) 'headline))))
23583 (goto-char pos)
23584 (user-error "Cannot drag element forward"))
23585 ;; Compute new position of point: it's shifted by NEXT-ELEM
23586 ;; body's length (without final blanks) and by the length of
23587 ;; blanks between ELEM and NEXT-ELEM.
23588 (let ((size-next (- (save-excursion
23589 (goto-char (org-element-property :end next-elem))
23590 (skip-chars-backward " \r\t\n")
23591 (forward-line)
23592 ;; Small correction if buffer doesn't end
23593 ;; with a newline character.
23594 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23595 (org-element-property :begin next-elem)))
23596 (size-blank (- (org-element-property :end elem)
23597 (save-excursion
23598 (goto-char (org-element-property :end elem))
23599 (skip-chars-backward " \r\t\n")
23600 (forward-line)
23601 (point)))))
23602 (org-element-swap-A-B elem next-elem)
23603 (goto-char (+ pos size-next size-blank))))))
23605 (defun org-drag-line-forward (arg)
23606 "Drag the line at point ARG lines forward."
23607 (interactive "p")
23608 (dotimes (n (abs arg))
23609 (let ((c (current-column)))
23610 (if (< 0 arg)
23611 (progn
23612 (beginning-of-line 2)
23613 (transpose-lines 1)
23614 (beginning-of-line 0))
23615 (transpose-lines 1)
23616 (beginning-of-line -1))
23617 (org-move-to-column c))))
23619 (defun org-drag-line-backward (arg)
23620 "Drag the line at point ARG lines backward."
23621 (interactive "p")
23622 (org-drag-line-forward (- arg)))
23624 (defun org-mark-element ()
23625 "Put point at beginning of this element, mark at end.
23627 Interactively, if this command is repeated or (in Transient Mark
23628 mode) if the mark is active, it marks the next element after the
23629 ones already marked."
23630 (interactive)
23631 (let (deactivate-mark)
23632 (if (and (org-called-interactively-p 'any)
23633 (or (and (eq last-command this-command) (mark t))
23634 (and transient-mark-mode mark-active)))
23635 (set-mark
23636 (save-excursion
23637 (goto-char (mark))
23638 (goto-char (org-element-property :end (org-element-at-point)))))
23639 (let ((element (org-element-at-point)))
23640 (end-of-line)
23641 (push-mark (org-element-property :end element) t t)
23642 (goto-char (org-element-property :begin element))))))
23644 (defun org-narrow-to-element ()
23645 "Narrow buffer to current element."
23646 (interactive)
23647 (let ((elem (org-element-at-point)))
23648 (cond
23649 ((eq (car elem) 'headline)
23650 (narrow-to-region
23651 (org-element-property :begin elem)
23652 (org-element-property :end elem)))
23653 ((memq (car elem) org-element-greater-elements)
23654 (narrow-to-region
23655 (org-element-property :contents-begin elem)
23656 (org-element-property :contents-end elem)))
23658 (narrow-to-region
23659 (org-element-property :begin elem)
23660 (org-element-property :end elem))))))
23662 (defun org-transpose-element ()
23663 "Transpose current and previous elements, keeping blank lines between.
23664 Point is moved after both elements."
23665 (interactive)
23666 (org-skip-whitespace)
23667 (let ((end (org-element-property :end (org-element-at-point))))
23668 (org-drag-element-backward)
23669 (goto-char end)))
23671 (defun org-unindent-buffer ()
23672 "Un-indent the visible part of the buffer.
23673 Relative indentation (between items, inside blocks, etc.) isn't
23674 modified."
23675 (interactive)
23676 (unless (eq major-mode 'org-mode)
23677 (user-error "Cannot un-indent a buffer not in Org mode"))
23678 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23679 unindent-tree ; For byte-compiler.
23680 (unindent-tree
23681 (function
23682 (lambda (contents)
23683 (mapc
23684 (lambda (element)
23685 (if (memq (org-element-type element) '(headline section))
23686 (funcall unindent-tree (org-element-contents element))
23687 (save-excursion
23688 (save-restriction
23689 (narrow-to-region
23690 (org-element-property :begin element)
23691 (org-element-property :end element))
23692 (org-do-remove-indentation)))))
23693 (reverse contents))))))
23694 (funcall unindent-tree (org-element-contents parse-tree))))
23696 (defun org-show-subtree ()
23697 "Show everything after this heading at deeper levels."
23698 (interactive)
23699 (outline-flag-region
23700 (point)
23701 (save-excursion
23702 (org-end-of-subtree t t))
23703 nil))
23705 (defun org-show-entry ()
23706 "Show the body directly following this heading.
23707 Show the heading too, if it is currently invisible."
23708 (interactive)
23709 (save-excursion
23710 (condition-case nil
23711 (progn
23712 (org-back-to-heading t)
23713 (outline-flag-region
23714 (max (point-min) (1- (point)))
23715 (save-excursion
23716 (if (re-search-forward
23717 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23718 (match-beginning 1)
23719 (point-max)))
23720 nil)
23721 (org-cycle-hide-drawers 'children))
23722 (error nil))))
23724 (defun org-make-options-regexp (kwds &optional extra)
23725 "Make a regular expression for keyword lines."
23726 (concat
23727 "^#\\+\\("
23728 (mapconcat 'regexp-quote kwds "\\|")
23729 (if extra (concat "\\|" extra))
23730 "\\):[ \t]*\\(.*\\)"))
23732 ;; Make isearch reveal the necessary context
23733 (defun org-isearch-end ()
23734 "Reveal context after isearch exits."
23735 (when isearch-success ; only if search was successful
23736 (if (featurep 'xemacs)
23737 ;; Under XEmacs, the hook is run in the correct place,
23738 ;; we directly show the context.
23739 (org-show-context 'isearch)
23740 ;; In Emacs the hook runs *before* restoring the overlays.
23741 ;; So we have to use a one-time post-command-hook to do this.
23742 ;; (Emacs 22 has a special variable, see function `org-mode')
23743 (unless (and (boundp 'isearch-mode-end-hook-quit)
23744 isearch-mode-end-hook-quit)
23745 ;; Only when the isearch was not quitted.
23746 (org-add-hook 'post-command-hook 'org-isearch-post-command
23747 'append 'local)))
23748 (org-fix-ellipsis-at-bol)))
23750 (defun org-isearch-post-command ()
23751 "Remove self from hook, and show context."
23752 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23753 (org-show-context 'isearch))
23756 ;;;; Integration with and fixes for other packages
23758 ;;; Imenu support
23760 (defvar org-imenu-markers nil
23761 "All markers currently used by Imenu.")
23762 (make-variable-buffer-local 'org-imenu-markers)
23764 (defun org-imenu-new-marker (&optional pos)
23765 "Return a new marker for use by Imenu, and remember the marker."
23766 (let ((m (make-marker)))
23767 (move-marker m (or pos (point)))
23768 (push m org-imenu-markers)
23771 (defun org-imenu-get-tree ()
23772 "Produce the index for Imenu."
23773 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23774 (setq org-imenu-markers nil)
23775 (let* ((n org-imenu-depth)
23776 (re (concat "^" (org-get-limited-outline-regexp)))
23777 (subs (make-vector (1+ n) nil))
23778 (last-level 0)
23779 m level head0 head)
23780 (save-excursion
23781 (save-restriction
23782 (widen)
23783 (goto-char (point-max))
23784 (while (re-search-backward re nil t)
23785 (setq level (org-reduced-level (funcall outline-level)))
23786 (when (and (<= level n)
23787 (looking-at org-complex-heading-regexp)
23788 (setq head0 (org-match-string-no-properties 4)))
23789 (setq head (org-link-display-format head0)
23790 m (org-imenu-new-marker))
23791 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23792 (if (>= level last-level)
23793 (push (cons head m) (aref subs level))
23794 (push (cons head (aref subs (1+ level))) (aref subs level))
23795 (loop for i from (1+ level) to n do (aset subs i nil)))
23796 (setq last-level level)))))
23797 (aref subs 1)))
23799 (eval-after-load "imenu"
23800 '(progn
23801 (add-hook 'imenu-after-jump-hook
23802 (lambda ()
23803 (if (derived-mode-p 'org-mode)
23804 (org-show-context 'org-goto))))))
23806 (defun org-link-display-format (link)
23807 "Replace a link with its the description.
23808 If there is no description, use the link target."
23809 (save-match-data
23810 (if (string-match org-bracket-link-analytic-regexp link)
23811 (replace-match (if (match-end 5)
23812 (match-string 5 link)
23813 (concat (match-string 1 link)
23814 (match-string 3 link)))
23815 nil t link)
23816 link)))
23818 (defun org-toggle-link-display ()
23819 "Toggle the literal or descriptive display of links."
23820 (interactive)
23821 (if org-descriptive-links
23822 (progn (org-remove-from-invisibility-spec '(org-link))
23823 (org-restart-font-lock)
23824 (setq org-descriptive-links nil))
23825 (progn (add-to-invisibility-spec '(org-link))
23826 (org-restart-font-lock)
23827 (setq org-descriptive-links t))))
23829 ;; Speedbar support
23831 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23832 "Overlay marking the agenda restriction line in speedbar.")
23833 (overlay-put org-speedbar-restriction-lock-overlay
23834 'face 'org-agenda-restriction-lock)
23835 (overlay-put org-speedbar-restriction-lock-overlay
23836 'help-echo "Agendas are currently limited to this item.")
23837 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23839 (defun org-speedbar-set-agenda-restriction ()
23840 "Restrict future agenda commands to the location at point in speedbar.
23841 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23842 (interactive)
23843 (require 'org-agenda)
23844 (let (p m tp np dir txt)
23845 (cond
23846 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23847 'org-imenu t))
23848 (setq m (get-text-property p 'org-imenu-marker))
23849 (with-current-buffer (marker-buffer m)
23850 (goto-char m)
23851 (org-agenda-set-restriction-lock 'subtree)))
23852 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23853 'speedbar-function 'speedbar-find-file))
23854 (setq tp (previous-single-property-change
23855 (1+ p) 'speedbar-function)
23856 np (next-single-property-change
23857 tp 'speedbar-function)
23858 dir (speedbar-line-directory)
23859 txt (buffer-substring-no-properties (or tp (point-min))
23860 (or np (point-max))))
23861 (with-current-buffer (find-file-noselect
23862 (let ((default-directory dir))
23863 (expand-file-name txt)))
23864 (unless (derived-mode-p 'org-mode)
23865 (user-error "Cannot restrict to non-Org-mode file"))
23866 (org-agenda-set-restriction-lock 'file)))
23867 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23868 (move-overlay org-speedbar-restriction-lock-overlay
23869 (point-at-bol) (point-at-eol))
23870 (setq current-prefix-arg nil)
23871 (org-agenda-maybe-redo)))
23873 (defvar speedbar-file-key-map)
23874 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23875 (eval-after-load "speedbar"
23876 '(progn
23877 (speedbar-add-supported-extension ".org")
23878 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23879 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23880 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23881 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23882 (add-hook 'speedbar-visiting-tag-hook
23883 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23885 ;;; Fixes and Hacks for problems with other packages
23887 ;; Make flyspell not check words in links, to not mess up our keymap
23888 (defvar org-element-affiliated-keywords) ; From org-element.el
23889 (defvar org-element-block-name-alist) ; From org-element.el
23890 (defun org-mode-flyspell-verify ()
23891 "Don't let flyspell put overlays at active buttons, or on
23892 {todo,all-time,additional-option-like}-keywords."
23893 (require 'org-element) ; For `org-element-affiliated-keywords'
23894 (let ((pos (max (1- (point)) (point-min)))
23895 (word (thing-at-point 'word)))
23896 (and (not (get-text-property pos 'keymap))
23897 (not (get-text-property pos 'org-no-flyspell))
23898 (not (member word org-todo-keywords-1))
23899 (not (member word org-all-time-keywords))
23900 (not (member word org-options-keywords))
23901 (not (member word (mapcar 'car org-startup-options)))
23902 (not (member-ignore-case word org-element-affiliated-keywords))
23903 (not (member-ignore-case word (org-get-export-keywords)))
23904 (not (member-ignore-case
23905 word (mapcar 'car org-element-block-name-alist)))
23906 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23907 (not (org-in-src-block-p)))))
23909 (defun org-remove-flyspell-overlays-in (beg end)
23910 "Remove flyspell overlays in region."
23911 (and (org-bound-and-true-p flyspell-mode)
23912 (fboundp 'flyspell-delete-region-overlays)
23913 (flyspell-delete-region-overlays beg end))
23914 (add-text-properties beg end '(org-no-flyspell t)))
23916 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23917 (eval-after-load "bookmark"
23918 '(if (boundp 'bookmark-after-jump-hook)
23919 ;; We can use the hook
23920 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23921 ;; Hook not available, use advice
23922 (defadvice bookmark-jump (after org-make-visible activate)
23923 "Make the position visible."
23924 (org-bookmark-jump-unhide))))
23926 ;; Make sure saveplace shows the location if it was hidden
23927 (eval-after-load "saveplace"
23928 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23929 "Make the position visible."
23930 (org-bookmark-jump-unhide)))
23932 ;; Make sure ecb shows the location if it was hidden
23933 (eval-after-load "ecb"
23934 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23935 "Make hierarchy visible when jumping into location from ECB tree buffer."
23936 (if (derived-mode-p 'org-mode)
23937 (org-show-context))))
23939 (defun org-bookmark-jump-unhide ()
23940 "Unhide the current position, to show the bookmark location."
23941 (and (derived-mode-p 'org-mode)
23942 (or (outline-invisible-p)
23943 (save-excursion (goto-char (max (point-min) (1- (point))))
23944 (outline-invisible-p)))
23945 (org-show-context 'bookmark-jump)))
23947 ;; Make session.el ignore our circular variable
23948 (defvar session-globals-exclude)
23949 (eval-after-load "session"
23950 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23952 ;;;; Finish up
23954 (provide 'org)
23956 (run-hooks 'org-load-hook)
23958 ;;; org.el ends here