org.el: Fix a variable name error
[org-mode.git] / lisp / org.el
blob8c0fe35476d86abfae28f569b374b7c62ba4a6da
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-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (setq exported-file
202 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
203 (message "%s %s"
204 (if compile
205 (progn (byte-compile-file exported-file 'load)
206 "Compiled and loaded")
207 (progn (load-file exported-file) "Loaded"))
208 exported-file)))
210 (defcustom org-babel-load-languages '((emacs-lisp . t))
211 "Languages which can be evaluated in Org-mode buffers.
212 This list can be used to load support for any of the languages
213 below, note that each language will depend on a different set of
214 system executables and/or Emacs modes. When a language is
215 \"loaded\", then code blocks in that language can be evaluated
216 with `org-babel-execute-src-block' bound by default to C-c
217 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
218 be set to remove code block evaluation from the C-c C-c
219 keybinding. By default only Emacs Lisp (which has no
220 requirements) is loaded."
221 :group 'org-babel
222 :set 'org-babel-do-load-languages
223 :version "24.1"
224 :type '(alist :tag "Babel Languages"
225 :key-type
226 (choice
227 (const :tag "Awk" awk)
228 (const :tag "C" C)
229 (const :tag "R" R)
230 (const :tag "Asymptote" asymptote)
231 (const :tag "Calc" calc)
232 (const :tag "Clojure" clojure)
233 (const :tag "CSS" css)
234 (const :tag "Ditaa" ditaa)
235 (const :tag "Dot" dot)
236 (const :tag "Emacs Lisp" emacs-lisp)
237 (const :tag "Fortran" fortran)
238 (const :tag "Gnuplot" gnuplot)
239 (const :tag "Haskell" haskell)
240 (const :tag "IO" io)
241 (const :tag "Java" java)
242 (const :tag "Javascript" js)
243 (const :tag "LaTeX" latex)
244 (const :tag "Ledger" ledger)
245 (const :tag "Lilypond" lilypond)
246 (const :tag "Lisp" lisp)
247 (const :tag "Makefile" makefile)
248 (const :tag "Maxima" maxima)
249 (const :tag "Matlab" matlab)
250 (const :tag "Mscgen" mscgen)
251 (const :tag "Ocaml" ocaml)
252 (const :tag "Octave" octave)
253 (const :tag "Org" org)
254 (const :tag "Perl" perl)
255 (const :tag "Pico Lisp" picolisp)
256 (const :tag "PlantUML" plantuml)
257 (const :tag "Python" python)
258 (const :tag "Ruby" ruby)
259 (const :tag "Sass" sass)
260 (const :tag "Scala" scala)
261 (const :tag "Scheme" scheme)
262 (const :tag "Screen" screen)
263 (const :tag "Shell Script" sh)
264 (const :tag "Shen" shen)
265 (const :tag "Sql" sql)
266 (const :tag "Sqlite" sqlite))
267 :value-type (boolean :tag "Activate" :value t)))
269 ;;;; Customization variables
270 (defcustom org-clone-delete-id nil
271 "Remove ID property of clones of a subtree.
272 When non-nil, clones of a subtree don't inherit the ID property.
273 Otherwise they inherit the ID property with a new unique
274 identifier."
275 :type 'boolean
276 :version "24.1"
277 :group 'org-id)
279 ;;; Version
280 (org-check-version)
282 ;;;###autoload
283 (defun org-version (&optional here full message)
284 "Show the org-mode version in the echo area.
285 With prefix argument HERE, insert it at point.
286 When FULL is non-nil, use a verbose version string.
287 When MESSAGE is non-nil, display a message with the version."
288 (interactive "P")
289 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
290 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
291 (load-suffixes (list ".el"))
292 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
293 (org-trash (or
294 (and (fboundp 'org-release) (fboundp 'org-git-version))
295 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
296 (load-suffixes save-load-suffixes)
297 (org-version (org-release))
298 (git-version (org-git-version))
299 (version (format "Org-mode version %s (%s @ %s)"
300 org-version
301 git-version
302 (if org-install-dir
303 (if (string= org-dir org-install-dir)
304 org-install-dir
305 (concat "mixed installation! " org-install-dir " and " org-dir))
306 "org-loaddefs.el can not be found!")))
307 (version1 (if full version org-version)))
308 (if (org-called-interactively-p 'interactive)
309 (if here
310 (insert version)
311 (message version))
312 (if message (message version1))
313 version1)))
315 (defconst org-version (org-version))
317 ;;; Compatibility constants
319 ;;; The custom variables
321 (defgroup org nil
322 "Outline-based notes management and organizer."
323 :tag "Org"
324 :group 'outlines
325 :group 'calendar)
327 (defcustom org-mode-hook nil
328 "Mode hook for Org-mode, run after the mode was turned on."
329 :group 'org
330 :type 'hook)
332 (defcustom org-load-hook nil
333 "Hook that is run after org.el has been loaded."
334 :group 'org
335 :type 'hook)
337 (defcustom org-log-buffer-setup-hook nil
338 "Hook that is run after an Org log buffer is created."
339 :group 'org
340 :version "24.1"
341 :type 'hook)
343 (defvar org-modules) ; defined below
344 (defvar org-modules-loaded nil
345 "Have the modules been loaded already?")
347 (defun org-load-modules-maybe (&optional force)
348 "Load all extensions listed in `org-modules'."
349 (when (or force (not org-modules-loaded))
350 (mapc (lambda (ext)
351 (condition-case nil (require ext)
352 (error (message "Problems while trying to load feature `%s'" ext))))
353 org-modules)
354 (setq org-modules-loaded t)))
356 (defun org-set-modules (var value)
357 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
358 (set var value)
359 (when (featurep 'org)
360 (org-load-modules-maybe 'force)))
362 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
363 "Modules that should always be loaded together with org.el.
365 If a description starts with <C>, the file is not part of Emacs
366 and loading it will require that you have downloaded and properly
367 installed the Org mode distribution.
369 You can also use this system to load external packages (i.e. neither Org
370 core modules, nor modules from the CONTRIB directory). Just add symbols
371 to the end of the list. If the package is called org-xyz.el, then you need
372 to add the symbol `xyz', and the package must have a call to:
374 \(provide 'org-xyz)
376 For export specific modules, see also `org-export-backends'."
377 :group 'org
378 :set 'org-set-modules
379 :version "24.4"
380 :package-version '(Org . "8.0")
381 :type
382 '(set :greedy t
383 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
384 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
385 (const :tag " crypt: Encryption of subtrees" org-crypt)
386 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
387 (const :tag " docview: Links to doc-view buffers" org-docview)
388 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
389 (const :tag " habit: Track your consistency with habits" org-habit)
390 (const :tag " id: Global IDs for identifying entries" org-id)
391 (const :tag " info: Links to Info nodes" org-info)
392 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
393 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
394 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
395 (const :tag " mouse: Additional mouse support" org-mouse)
396 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
397 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
398 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
400 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
401 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
402 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
403 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
404 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
405 (const :tag "C collector: Collect properties into tables" org-collector)
406 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
407 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
408 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
409 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
410 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
411 (const :tag "C eval: Include command output as text" org-eval)
412 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
413 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
414 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
415 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
416 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
417 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
418 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
419 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
420 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export--registered-backends) ; From ox.el.
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (declare-function org-export-backend-name "ox" (backend))
442 (defcustom org-export-backends '(ascii html icalendar latex)
443 "List of export back-ends that should be always available.
445 If a description starts with <C>, the file is not part of Emacs
446 and loading it will require that you have downloaded and properly
447 installed the Org mode distribution.
449 Unlike to `org-modules', libraries in this list will not be
450 loaded along with Org, but only once the export framework is
451 needed.
453 This variable needs to be set before org.el is loaded. If you
454 need to make a change while Emacs is running, use the customize
455 interface or run the following code, where VAL stands for the new
456 value of the variable, after updating it:
458 \(progn
459 \(setq org-export--registered-backends
460 \(org-remove-if-not
461 \(lambda (backend)
462 \(let ((name (org-export-backend-name backend)))
463 \(or (memq name val)
464 \(catch 'parentp
465 \(dolist (b val)
466 \(and (org-export-derived-backend-p b name)
467 \(throw 'parentp t)))))))
468 org-export--registered-backends))
469 \(let ((new-list (mapcar 'org-export-backend-name
470 org-export--registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default 'org-export-backends new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export--registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (let ((name (org-export-backend-name backend)))
495 (or (memq name val)
496 (catch 'parentp
497 (dolist (b val)
498 (and (org-export-derived-backend-p b name)
499 (throw 'parentp t)))))))
500 org-export--registered-backends))
501 ;; Now build NEW-LIST of both new back-ends and required
502 ;; parents.
503 (let ((new-list (mapcar 'org-export-backend-name
504 org-export--registered-backends)))
505 (dolist (backend val)
506 (cond
507 ((not (load (format "ox-%s" backend) t t))
508 (message "Problems while trying to load export back-end `%s'"
509 backend))
510 ((not (memq backend new-list)) (push backend new-list))))
511 ;; Set VAR to that list with fixed dependencies.
512 (set-default var new-list))))
513 :type '(set :greedy t
514 (const :tag " ascii Export buffer to ASCII format" ascii)
515 (const :tag " beamer Export buffer to Beamer presentation" beamer)
516 (const :tag " html Export buffer to HTML format" html)
517 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
518 (const :tag " latex Export buffer to LaTeX format" latex)
519 (const :tag " man Export buffer to MAN format" man)
520 (const :tag " md Export buffer to Markdown format" md)
521 (const :tag " odt Export buffer to ODT format" odt)
522 (const :tag " org Export buffer to Org format" org)
523 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
524 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
525 (const :tag "C deck Export buffer to deck.js presentations" deck)
526 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
527 (const :tag "C groff Export buffer to Groff format" groff)
528 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
529 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
530 (const :tag "C s5 Export buffer to s5 presentations" s5)
531 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
533 (eval-after-load 'ox
534 '(mapc
535 (lambda (backend)
536 (condition-case nil (require (intern (format "ox-%s" backend)))
537 (error (message "Problems while trying to load export back-end `%s'"
538 backend))))
539 org-export-backends))
541 (defcustom org-support-shift-select nil
542 "Non-nil means make shift-cursor commands select text when possible.
544 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
545 start selecting a region, or enlarge regions started in this way.
546 In Org-mode, in special contexts, these same keys are used for
547 other purposes, important enough to compete with shift selection.
548 Org tries to balance these needs by supporting `shift-select-mode'
549 outside these special contexts, under control of this variable.
551 The default of this variable is nil, to avoid confusing behavior. Shifted
552 cursor keys will then execute Org commands in the following contexts:
553 - on a headline, changing TODO state (left/right) and priority (up/down)
554 - on a time stamp, changing the time
555 - in a plain list item, changing the bullet type
556 - in a property definition line, switching between allowed values
557 - in the BEGIN line of a clock table (changing the time block).
558 Outside these contexts, the commands will throw an error.
560 When this variable is t and the cursor is not in a special
561 context, Org-mode will support shift-selection for making and
562 enlarging regions. To make this more effective, the bullet
563 cycling will no longer happen anywhere in an item line, but only
564 if the cursor is exactly on the bullet.
566 If you set this variable to the symbol `always', then the keys
567 will not be special in headlines, property lines, and item lines,
568 to make shift selection work there as well. If this is what you
569 want, you can use the following alternative commands: `C-c C-t'
570 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
571 can be used to switch TODO sets, `C-c -' to cycle item bullet
572 types, and properties can be edited by hand or in column view.
574 However, when the cursor is on a timestamp, shift-cursor commands
575 will still edit the time stamp - this is just too good to give up.
577 XEmacs user should have this variable set to nil, because
578 `shift-select-mode' is in Emacs 23 or later only."
579 :group 'org
580 :type '(choice
581 (const :tag "Never" nil)
582 (const :tag "When outside special context" t)
583 (const :tag "Everywhere except timestamps" always)))
585 (defcustom org-loop-over-headlines-in-active-region nil
586 "Shall some commands act upon headlines in the active region?
588 When set to `t', some commands will be performed in all headlines
589 within the active region.
591 When set to `start-level', some commands will be performed in all
592 headlines within the active region, provided that these headlines
593 are of the same level than the first one.
595 When set to a string, those commands will be performed on the
596 matching headlines within the active region. Such string must be
597 a tags/property/todo match as it is used in the agenda tags view.
599 The list of commands is: `org-schedule', `org-deadline',
600 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
601 `org-archive-to-archive-sibling'. The archiving commands skip
602 already archived entries."
603 :type '(choice (const :tag "Don't loop" nil)
604 (const :tag "All headlines in active region" t)
605 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
606 (string :tag "Tags/Property/Todo matcher"))
607 :version "24.1"
608 :group 'org-todo
609 :group 'org-archive)
611 (defgroup org-startup nil
612 "Options concerning startup of Org-mode."
613 :tag "Org Startup"
614 :group 'org)
616 (defcustom org-startup-folded t
617 "Non-nil means entering Org-mode will switch to OVERVIEW.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: fold (or `overview', this is equivalent)
622 #+STARTUP: nofold (or `showall', this is equivalent)
623 #+STARTUP: content
624 #+STARTUP: showeverything
626 By default, this option is ignored when Org opens agenda files
627 for the first time. If you want the agenda to honor the startup
628 option, set `org-agenda-inhibit-startup' to nil."
629 :group 'org-startup
630 :type '(choice
631 (const :tag "nofold: show all" nil)
632 (const :tag "fold: overview" t)
633 (const :tag "content: all headlines" content)
634 (const :tag "show everything, even drawers" showeverything)))
636 (defcustom org-startup-truncated t
637 "Non-nil means entering Org-mode will set `truncate-lines'.
638 This is useful since some lines containing links can be very long and
639 uninteresting. Also tables look terrible when wrapped."
640 :group 'org-startup
641 :type 'boolean)
643 (defcustom org-startup-indented nil
644 "Non-nil means turn on `org-indent-mode' on startup.
645 This can also be configured on a per-file basis by adding one of
646 the following lines anywhere in the buffer:
648 #+STARTUP: indent
649 #+STARTUP: noindent"
650 :group 'org-structure
651 :type '(choice
652 (const :tag "Not" nil)
653 (const :tag "Globally (slow on startup in large files)" t)))
655 (defcustom org-use-sub-superscripts t
656 "Non-nil means interpret \"_\" and \"^\" for display.
657 When this option is turned on, you can use TeX-like syntax for sub- and
658 superscripts. Several characters after \"_\" or \"^\" will be
659 considered as a single item - so grouping with {} is normally not
660 needed. For example, the following things will be parsed as single
661 sub- or superscripts.
663 10^24 or 10^tau several digits will be considered 1 item.
664 10^-12 or 10^-tau a leading sign with digits or a word
665 x^2-y^3 will be read as x^2 - y^3, because items are
666 terminated by almost any nonword/nondigit char.
667 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
669 Still, ambiguity is possible - so when in doubt use {} to enclose
670 the sub/superscript. If you set this variable to the symbol
671 `{}', the braces are *required* in order to trigger
672 interpretations as sub/superscript. This can be helpful in
673 documents that need \"_\" frequently in plain text."
674 :group 'org-startup
675 :version "24.1"
676 :type '(choice
677 (const :tag "Always interpret" t)
678 (const :tag "Only with braces" {})
679 (const :tag "Never interpret" nil)))
681 (defcustom org-startup-with-beamer-mode nil
682 "Non-nil means turn on `org-beamer-mode' on startup.
683 This can also be configured on a per-file basis by adding one of
684 the following lines anywhere in the buffer:
686 #+STARTUP: beamer"
687 :group 'org-startup
688 :version "24.1"
689 :type 'boolean)
691 (defcustom org-startup-align-all-tables nil
692 "Non-nil means align all tables when visiting a file.
693 This is useful when the column width in tables is forced with <N> cookies
694 in table fields. Such tables will look correct only after the first re-align.
695 This can also be configured on a per-file basis by adding one of
696 the following lines anywhere in the buffer:
697 #+STARTUP: align
698 #+STARTUP: noalign"
699 :group 'org-startup
700 :type 'boolean)
702 (defcustom org-startup-with-inline-images nil
703 "Non-nil means show inline images when loading a new Org file.
704 This can also be configured on a per-file basis by adding one of
705 the following lines anywhere in the buffer:
706 #+STARTUP: inlineimages
707 #+STARTUP: noinlineimages"
708 :group 'org-startup
709 :version "24.1"
710 :type 'boolean)
712 (defcustom org-startup-with-latex-preview nil
713 "Non-nil means preview LaTeX fragments when loading a new Org file.
715 This can also be configured on a per-file basis by adding one of
716 the followinglines anywhere in the buffer:
717 #+STARTUP: latexpreview
718 #+STARTUP: nolatexpreview"
719 :group 'org-startup
720 :version "24.4"
721 :package-version '(Org . "8.0")
722 :type 'boolean)
724 (defcustom org-insert-mode-line-in-empty-file nil
725 "Non-nil means insert the first line setting Org-mode in empty files.
726 When the function `org-mode' is called interactively in an empty file, this
727 normally means that the file name does not automatically trigger Org-mode.
728 To ensure that the file will always be in Org-mode in the future, a
729 line enforcing Org-mode will be inserted into the buffer, if this option
730 has been set."
731 :group 'org-startup
732 :type 'boolean)
734 (defcustom org-replace-disputed-keys nil
735 "Non-nil means use alternative key bindings for some keys.
736 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
737 These keys are also used by other packages like shift-selection-mode'
738 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
739 If you want to use Org-mode together with one of these other modes,
740 or more generally if you would like to move some Org-mode commands to
741 other keys, set this variable and configure the keys with the variable
742 `org-disputed-keys'.
744 This option is only relevant at load-time of Org-mode, and must be set
745 *before* org.el is loaded. Changing it requires a restart of Emacs to
746 become effective."
747 :group 'org-startup
748 :type 'boolean)
750 (defcustom org-use-extra-keys nil
751 "Non-nil means use extra key sequence definitions for certain commands.
752 This happens automatically if you run XEmacs or if `window-system'
753 is nil. This variable lets you do the same manually. You must
754 set it before loading org.
756 Example: on Carbon Emacs 22 running graphically, with an external
757 keyboard on a Powerbook, the default way of setting M-left might
758 not work for either Alt or ESC. Setting this variable will make
759 it work for ESC."
760 :group 'org-startup
761 :type 'boolean)
763 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
765 (defcustom org-disputed-keys
766 '(([(shift up)] . [(meta p)])
767 ([(shift down)] . [(meta n)])
768 ([(shift left)] . [(meta -)])
769 ([(shift right)] . [(meta +)])
770 ([(control shift right)] . [(meta shift +)])
771 ([(control shift left)] . [(meta shift -)]))
772 "Keys for which Org-mode and other modes compete.
773 This is an alist, cars are the default keys, second element specifies
774 the alternative to use when `org-replace-disputed-keys' is t.
776 Keys can be specified in any syntax supported by `define-key'.
777 The value of this option takes effect only at Org-mode's startup,
778 therefore you'll have to restart Emacs to apply it after changing."
779 :group 'org-startup
780 :type 'alist)
782 (defun org-key (key)
783 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
784 Or return the original if not disputed.
785 Also apply the translations defined in `org-xemacs-key-equivalents'."
786 (when org-replace-disputed-keys
787 (let* ((nkey (key-description key))
788 (x (org-find-if (lambda (x)
789 (equal (key-description (car x)) nkey))
790 org-disputed-keys)))
791 (setq key (if x (cdr x) key))))
792 (when (featurep 'xemacs)
793 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
794 key)
796 (defun org-find-if (predicate seq)
797 (catch 'exit
798 (while seq
799 (if (funcall predicate (car seq))
800 (throw 'exit (car seq))
801 (pop seq)))))
803 (defun org-defkey (keymap key def)
804 "Define a key, possibly translated, as returned by `org-key'."
805 (define-key keymap (org-key key) def))
807 (defcustom org-ellipsis nil
808 "The ellipsis to use in the Org-mode outline.
809 When nil, just use the standard three dots. When a string, use that instead,
810 When a face, use the standard 3 dots, but with the specified face.
811 The change affects only Org-mode (which will then use its own display table).
812 Changing this requires executing `M-x org-mode' in a buffer to become
813 effective."
814 :group 'org-startup
815 :type '(choice (const :tag "Default" nil)
816 (face :tag "Face" :value org-warning)
817 (string :tag "String" :value "...#")))
819 (defvar org-display-table nil
820 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
822 (defgroup org-keywords nil
823 "Keywords in Org-mode."
824 :tag "Org Keywords"
825 :group 'org)
827 (defcustom org-deadline-string "DEADLINE:"
828 "String to mark deadline entries.
829 A deadline is this string, followed by a time stamp. Should be a word,
830 terminated by a colon. You can insert a schedule keyword and
831 a timestamp with \\[org-deadline].
832 Changes become only effective after restarting Emacs."
833 :group 'org-keywords
834 :type 'string)
836 (defcustom org-scheduled-string "SCHEDULED:"
837 "String to mark scheduled TODO entries.
838 A schedule is this string, followed by a time stamp. Should be a word,
839 terminated by a colon. You can insert a schedule keyword and
840 a timestamp with \\[org-schedule].
841 Changes become only effective after restarting Emacs."
842 :group 'org-keywords
843 :type 'string)
845 (defcustom org-closed-string "CLOSED:"
846 "String used as the prefix for timestamps logging closing a TODO entry."
847 :group 'org-keywords
848 :type 'string)
850 (defcustom org-clock-string "CLOCK:"
851 "String used as prefix for timestamps clocking work hours on an item."
852 :group 'org-keywords
853 :type 'string)
855 (defcustom org-closed-keep-when-no-todo nil
856 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
857 :group 'org-todo
858 :group 'org-keywords
859 :version "24.4"
860 :package-version '(Org . "8.0")
861 :type 'boolean)
863 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
864 org-scheduled-string "\\|"
865 org-deadline-string "\\|"
866 org-closed-string "\\|"
867 org-clock-string "\\)")
868 "Matches a line with planning or clock info.")
870 (defcustom org-comment-string "COMMENT"
871 "Entries starting with this keyword will never be exported.
872 An entry can be toggled between COMMENT and normal with
873 \\[org-toggle-comment].
874 Changes become only effective after restarting Emacs."
875 :group 'org-keywords
876 :type 'string)
878 (defcustom org-quote-string "QUOTE"
879 "Entries starting with this keyword will be exported in fixed-width font.
880 Quoting applies only to the text in the entry following the headline, and does
881 not extend beyond the next headline, even if that is lower level.
882 An entry can be toggled between QUOTE and normal with
883 \\[org-toggle-fixed-width-section]."
884 :group 'org-keywords
885 :type 'string)
887 (defconst org-repeat-re
888 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
889 "Regular expression for specifying repeated events.
890 After a match, group 1 contains the repeat expression.")
892 (defgroup org-structure nil
893 "Options concerning the general structure of Org-mode files."
894 :tag "Org Structure"
895 :group 'org)
897 (defgroup org-reveal-location nil
898 "Options about how to make context of a location visible."
899 :tag "Org Reveal Location"
900 :group 'org-structure)
902 (defconst org-context-choice
903 '(choice
904 (const :tag "Always" t)
905 (const :tag "Never" nil)
906 (repeat :greedy t :tag "Individual contexts"
907 (cons
908 (choice :tag "Context"
909 (const agenda)
910 (const org-goto)
911 (const occur-tree)
912 (const tags-tree)
913 (const link-search)
914 (const mark-goto)
915 (const bookmark-jump)
916 (const isearch)
917 (const default))
918 (boolean))))
919 "Contexts for the reveal options.")
921 (defcustom org-show-hierarchy-above '((default . t))
922 "Non-nil means show full hierarchy when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the hierarchy of headings
925 above the exposed location is shown.
926 Turning this off for example for sparse trees makes them very compact.
927 Instead of t, this can also be an alist specifying this option for different
928 contexts. Valid contexts are
929 agenda when exposing an entry from the agenda
930 org-goto when using the command `org-goto' on key C-c C-j
931 occur-tree when using the command `org-occur' on key C-c /
932 tags-tree when constructing a sparse tree based on tags matches
933 link-search when exposing search matches associated with a link
934 mark-goto when exposing the jump goal of a mark
935 bookmark-jump when exposing a bookmark location
936 isearch when exiting from an incremental search
937 default default for all contexts not set explicitly"
938 :group 'org-reveal-location
939 :type org-context-choice)
941 (defcustom org-show-following-heading '((default . nil))
942 "Non-nil means show following heading when revealing a location.
943 Org-mode often shows locations in an org-mode file which might have
944 been invisible before. When this is set, the heading following the
945 match is shown.
946 Turning this off for example for sparse trees makes them very compact,
947 but makes it harder to edit the location of the match. In such a case,
948 use the command \\[org-reveal] to show more context.
949 Instead of t, this can also be an alist specifying this option for different
950 contexts. See `org-show-hierarchy-above' for valid contexts."
951 :group 'org-reveal-location
952 :type org-context-choice)
954 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
955 "Non-nil means show all sibling heading when revealing a location.
956 Org-mode often shows locations in an org-mode file which might have
957 been invisible before. When this is set, the sibling of the current entry
958 heading are all made visible. If `org-show-hierarchy-above' is t,
959 the same happens on each level of the hierarchy above the current entry.
961 By default this is on for the isearch context, off for all other contexts.
962 Turning this off for example for sparse trees makes them very compact,
963 but makes it harder to edit the location of the match. In such a case,
964 use the command \\[org-reveal] to show more context.
965 Instead of t, this can also be an alist specifying this option for different
966 contexts. See `org-show-hierarchy-above' for valid contexts."
967 :group 'org-reveal-location
968 :type org-context-choice
969 :version "24.4"
970 :package-version '(Org . "8.0"))
972 (defcustom org-show-entry-below '((default . nil))
973 "Non-nil means show the entry below a headline when revealing a location.
974 Org-mode often shows locations in an org-mode file which might have
975 been invisible before. When this is set, the text below the headline that is
976 exposed is also shown.
978 By default this is off for all contexts.
979 Instead of t, this can also be an alist specifying this option for different
980 contexts. See `org-show-hierarchy-above' for valid contexts."
981 :group 'org-reveal-location
982 :type org-context-choice)
984 (defcustom org-indirect-buffer-display 'other-window
985 "How should indirect tree buffers be displayed?
986 This applies to indirect buffers created with the commands
987 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
988 Valid values are:
989 current-window Display in the current window
990 other-window Just display in another window.
991 dedicated-frame Create one new frame, and re-use it each time.
992 new-frame Make a new frame each time. Note that in this case
993 previously-made indirect buffers are kept, and you need to
994 kill these buffers yourself."
995 :group 'org-structure
996 :group 'org-agenda-windows
997 :type '(choice
998 (const :tag "In current window" current-window)
999 (const :tag "In current frame, other window" other-window)
1000 (const :tag "Each time a new frame" new-frame)
1001 (const :tag "One dedicated frame" dedicated-frame)))
1003 (defcustom org-use-speed-commands nil
1004 "Non-nil means activate single letter commands at beginning of a headline.
1005 This may also be a function to test for appropriate locations where speed
1006 commands should be active."
1007 :group 'org-structure
1008 :type '(choice
1009 (const :tag "Never" nil)
1010 (const :tag "At beginning of headline stars" t)
1011 (function)))
1013 (defcustom org-speed-commands-user nil
1014 "Alist of additional speed commands.
1015 This list will be checked before `org-speed-commands-default'
1016 when the variable `org-use-speed-commands' is non-nil
1017 and when the cursor is at the beginning of a headline.
1018 The car if each entry is a string with a single letter, which must
1019 be assigned to `self-insert-command' in the global map.
1020 The cdr is either a command to be called interactively, a function
1021 to be called, or a form to be evaluated.
1022 An entry that is just a list with a single string will be interpreted
1023 as a descriptive headline that will be added when listing the speed
1024 commands in the Help buffer using the `?' speed command."
1025 :group 'org-structure
1026 :type '(repeat :value ("k" . ignore)
1027 (choice :value ("k" . ignore)
1028 (list :tag "Descriptive Headline" (string :tag "Headline"))
1029 (cons :tag "Letter and Command"
1030 (string :tag "Command letter")
1031 (choice
1032 (function)
1033 (sexp))))))
1035 (defcustom org-bookmark-names-plist
1036 '(:last-capture "org-capture-last-stored"
1037 :last-refile "org-refile-last-stored"
1038 :last-capture-marker "org-capture-last-stored-marker")
1039 "Names for bookmarks automatically set by some Org commands.
1040 This can provide strings as names for a number of bookmakrs Org sets
1041 automatically. The following keys are currently implemented:
1042 :last-capture
1043 :last-capture-marker
1044 :last-refile
1045 When a key does not show up in the property list, the corresponding bookmark
1046 is not set."
1047 :group 'org-structure
1048 :type 'plist)
1050 (defgroup org-cycle nil
1051 "Options concerning visibility cycling in Org-mode."
1052 :tag "Org Cycle"
1053 :group 'org-structure)
1055 (defcustom org-cycle-skip-children-state-if-no-children t
1056 "Non-nil means skip CHILDREN state in entries that don't have any."
1057 :group 'org-cycle
1058 :type 'boolean)
1060 (defcustom org-cycle-max-level nil
1061 "Maximum level which should still be subject to visibility cycling.
1062 Levels higher than this will, for cycling, be treated as text, not a headline.
1063 When `org-odd-levels-only' is set, a value of N in this variable actually
1064 means 2N-1 stars as the limiting headline.
1065 When nil, cycle all levels.
1066 Note that the limiting level of cycling is also influenced by
1067 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1068 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1069 than its value."
1070 :group 'org-cycle
1071 :type '(choice
1072 (const :tag "No limit" nil)
1073 (integer :tag "Maximum level")))
1075 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1076 "Names of drawers. Drawers are not opened by cycling on the headline above.
1077 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1078 this:
1079 :DRAWERNAME:
1080 .....
1081 :END:
1082 The drawer \"PROPERTIES\" is special for capturing properties through
1083 the property API.
1085 Drawers can be defined on the per-file basis with a line like:
1087 #+DRAWERS: HIDDEN STATE PROPERTIES"
1088 :group 'org-structure
1089 :group 'org-cycle
1090 :type '(repeat (string :tag "Drawer Name")))
1092 (defcustom org-hide-block-startup nil
1093 "Non-nil means entering Org-mode will fold all blocks.
1094 This can also be set in on a per-file basis with
1096 #+STARTUP: hideblocks
1097 #+STARTUP: showblocks"
1098 :group 'org-startup
1099 :group 'org-cycle
1100 :type 'boolean)
1102 (defcustom org-cycle-global-at-bob nil
1103 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1104 This makes it possible to do global cycling without having to use S-TAB or
1105 \\[universal-argument] TAB. For this special case to work, the first line
1106 of the buffer must not be a headline -- it may be empty or some other text.
1107 When used in this way, `org-cycle-hook' is disabled temporarily to make
1108 sure the cursor stays at the beginning of the buffer. When this option is
1109 nil, don't do anything special at the beginning of the buffer."
1110 :group 'org-cycle
1111 :type 'boolean)
1113 (defcustom org-cycle-level-after-item/entry-creation t
1114 "Non-nil means cycle entry level or item indentation in new empty entries.
1116 When the cursor is at the end of an empty headline, i.e., with only stars
1117 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1118 and then all possible ancestor states, before returning to the original state.
1119 This makes data entry extremely fast: M-RET to create a new headline,
1120 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1122 When the cursor is at the end of an empty plain list item, one TAB will
1123 make it a subitem, two or more tabs will back up to make this an item
1124 higher up in the item hierarchy."
1125 :group 'org-cycle
1126 :type 'boolean)
1128 (defcustom org-cycle-emulate-tab t
1129 "Where should `org-cycle' emulate TAB.
1130 nil Never
1131 white Only in completely white lines
1132 whitestart Only at the beginning of lines, before the first non-white char
1133 t Everywhere except in headlines
1134 exc-hl-bol Everywhere except at the start of a headline
1135 If TAB is used in a place where it does not emulate TAB, the current subtree
1136 visibility is cycled."
1137 :group 'org-cycle
1138 :type '(choice (const :tag "Never" nil)
1139 (const :tag "Only in completely white lines" white)
1140 (const :tag "Before first char in a line" whitestart)
1141 (const :tag "Everywhere except in headlines" t)
1142 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1144 (defcustom org-cycle-separator-lines 2
1145 "Number of empty lines needed to keep an empty line between collapsed trees.
1146 If you leave an empty line between the end of a subtree and the following
1147 headline, this empty line is hidden when the subtree is folded.
1148 Org-mode will leave (exactly) one empty line visible if the number of
1149 empty lines is equal or larger to the number given in this variable.
1150 So the default 2 means at least 2 empty lines after the end of a subtree
1151 are needed to produce free space between a collapsed subtree and the
1152 following headline.
1154 If the number is negative, and the number of empty lines is at least -N,
1155 all empty lines are shown.
1157 Special case: when 0, never leave empty lines in collapsed view."
1158 :group 'org-cycle
1159 :type 'integer)
1160 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1162 (defcustom org-pre-cycle-hook nil
1163 "Hook that is run before visibility cycling is happening.
1164 The function(s) in this hook must accept a single argument which indicates
1165 the new state that will be set right after running this hook. The
1166 argument is a symbol. Before a global state change, it can have the values
1167 `overview', `content', or `all'. Before a local state change, it can have
1168 the values `folded', `children', or `subtree'."
1169 :group 'org-cycle
1170 :type 'hook)
1172 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1173 org-cycle-hide-drawers
1174 org-cycle-hide-inline-tasks
1175 org-cycle-show-empty-lines
1176 org-optimize-window-after-visibility-change)
1177 "Hook that is run after `org-cycle' has changed the buffer visibility.
1178 The function(s) in this hook must accept a single argument which indicates
1179 the new state that was set by the most recent `org-cycle' command. The
1180 argument is a symbol. After a global state change, it can have the values
1181 `overview', `contents', or `all'. After a local state change, it can have
1182 the values `folded', `children', or `subtree'."
1183 :group 'org-cycle
1184 :type 'hook)
1186 (defgroup org-edit-structure nil
1187 "Options concerning structure editing in Org-mode."
1188 :tag "Org Edit Structure"
1189 :group 'org-structure)
1191 (defcustom org-odd-levels-only nil
1192 "Non-nil means skip even levels and only use odd levels for the outline.
1193 This has the effect that two stars are being added/taken away in
1194 promotion/demotion commands. It also influences how levels are
1195 handled by the exporters.
1196 Changing it requires restart of `font-lock-mode' to become effective
1197 for fontification also in regions already fontified.
1198 You may also set this on a per-file basis by adding one of the following
1199 lines to the buffer:
1201 #+STARTUP: odd
1202 #+STARTUP: oddeven"
1203 :group 'org-edit-structure
1204 :group 'org-appearance
1205 :type 'boolean)
1207 (defcustom org-adapt-indentation t
1208 "Non-nil means adapt indentation to outline node level.
1210 When this variable is set, Org assumes that you write outlines by
1211 indenting text in each node to align with the headline (after the stars).
1212 The following issues are influenced by this variable:
1214 - When this is set and the *entire* text in an entry is indented, the
1215 indentation is increased by one space in a demotion command, and
1216 decreased by one in a promotion command. If any line in the entry
1217 body starts with text at column 0, indentation is not changed at all.
1219 - Property drawers and planning information is inserted indented when
1220 this variable s set. When nil, they will not be indented.
1222 - TAB indents a line relative to context. The lines below a headline
1223 will be indented when this variable is set.
1225 Note that this is all about true indentation, by adding and removing
1226 space characters. See also `org-indent.el' which does level-dependent
1227 indentation in a virtual way, i.e. at display time in Emacs."
1228 :group 'org-edit-structure
1229 :type 'boolean)
1231 (defcustom org-special-ctrl-a/e nil
1232 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1234 When t, `C-a' will bring back the cursor to the beginning of the
1235 headline text, i.e. after the stars and after a possible TODO
1236 keyword. In an item, this will be the position after bullet and
1237 check-box, if any. When the cursor is already at that position,
1238 another `C-a' will bring it to the beginning of the line.
1240 `C-e' will jump to the end of the headline, ignoring the presence
1241 of tags in the headline. A second `C-e' will then jump to the
1242 true end of the line, after any tags. This also means that, when
1243 this variable is non-nil, `C-e' also will never jump beyond the
1244 end of the heading of a folded section, i.e. not after the
1245 ellipses.
1247 When set to the symbol `reversed', the first `C-a' or `C-e' works
1248 normally, going to the true line boundary first. Only a directly
1249 following, identical keypress will bring the cursor to the
1250 special positions.
1252 This may also be a cons cell where the behavior for `C-a' and
1253 `C-e' is set separately."
1254 :group 'org-edit-structure
1255 :type '(choice
1256 (const :tag "off" nil)
1257 (const :tag "on: after stars/bullet and before tags first" t)
1258 (const :tag "reversed: true line boundary first" reversed)
1259 (cons :tag "Set C-a and C-e separately"
1260 (choice :tag "Special C-a"
1261 (const :tag "off" nil)
1262 (const :tag "on: after stars/bullet first" t)
1263 (const :tag "reversed: before stars/bullet first" reversed))
1264 (choice :tag "Special C-e"
1265 (const :tag "off" nil)
1266 (const :tag "on: before tags first" t)
1267 (const :tag "reversed: after tags first" reversed)))))
1268 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1270 (defcustom org-special-ctrl-k nil
1271 "Non-nil means `C-k' will behave specially in headlines.
1272 When nil, `C-k' will call the default `kill-line' command.
1273 When t, the following will happen while the cursor is in the headline:
1275 - When the cursor is at the beginning of a headline, kill the entire
1276 line and possible the folded subtree below the line.
1277 - When in the middle of the headline text, kill the headline up to the tags.
1278 - When after the headline text, kill the tags."
1279 :group 'org-edit-structure
1280 :type 'boolean)
1282 (defcustom org-ctrl-k-protect-subtree nil
1283 "Non-nil means, do not delete a hidden subtree with C-k.
1284 When set to the symbol `error', simply throw an error when C-k is
1285 used to kill (part-of) a headline that has hidden text behind it.
1286 Any other non-nil value will result in a query to the user, if it is
1287 OK to kill that hidden subtree. When nil, kill without remorse."
1288 :group 'org-edit-structure
1289 :version "24.1"
1290 :type '(choice
1291 (const :tag "Do not protect hidden subtrees" nil)
1292 (const :tag "Protect hidden subtrees with a security query" t)
1293 (const :tag "Never kill a hidden subtree with C-k" error)))
1295 (defcustom org-special-ctrl-o t
1296 "Non-nil means, make `C-o' insert a row in tables."
1297 :group 'org-edit-structure
1298 :type 'boolean)
1300 (defcustom org-catch-invisible-edits nil
1301 "Check if in invisible region before inserting or deleting a character.
1302 Valid values are:
1304 nil Do not check, so just do invisible edits.
1305 error Throw an error and do nothing.
1306 show Make point visible, and do the requested edit.
1307 show-and-error Make point visible, then throw an error and abort the edit.
1308 smart Make point visible, and do insertion/deletion if it is
1309 adjacent to visible text and the change feels predictable.
1310 Never delete a previously invisible character or add in the
1311 middle or right after an invisible region. Basically, this
1312 allows insertion and backward-delete right before ellipses.
1313 FIXME: maybe in this case we should not even show?"
1314 :group 'org-edit-structure
1315 :version "24.1"
1316 :type '(choice
1317 (const :tag "Do not check" nil)
1318 (const :tag "Throw error when trying to edit" error)
1319 (const :tag "Unhide, but do not do the edit" show-and-error)
1320 (const :tag "Show invisible part and do the edit" show)
1321 (const :tag "Be smart and do the right thing" smart)))
1323 (defcustom org-yank-folded-subtrees t
1324 "Non-nil means when yanking subtrees, fold them.
1325 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1326 it starts with a heading and all other headings in it are either children
1327 or siblings, then fold all the subtrees. However, do this only if no
1328 text after the yank would be swallowed into a folded tree by this action."
1329 :group 'org-edit-structure
1330 :type 'boolean)
1332 (defcustom org-yank-adjusted-subtrees nil
1333 "Non-nil means when yanking subtrees, adjust the level.
1334 With this setting, `org-paste-subtree' is used to insert the subtree, see
1335 this function for details."
1336 :group 'org-edit-structure
1337 :type 'boolean)
1339 (defcustom org-M-RET-may-split-line '((default . t))
1340 "Non-nil means M-RET will split the line at the cursor position.
1341 When nil, it will go to the end of the line before making a
1342 new line.
1343 You may also set this option in a different way for different
1344 contexts. Valid contexts are:
1346 headline when creating a new headline
1347 item when creating a new item
1348 table in a table field
1349 default the value to be used for all contexts not explicitly
1350 customized"
1351 :group 'org-structure
1352 :group 'org-table
1353 :type '(choice
1354 (const :tag "Always" t)
1355 (const :tag "Never" nil)
1356 (repeat :greedy t :tag "Individual contexts"
1357 (cons
1358 (choice :tag "Context"
1359 (const headline)
1360 (const item)
1361 (const table)
1362 (const default))
1363 (boolean)))))
1366 (defcustom org-insert-heading-respect-content nil
1367 "Non-nil means insert new headings after the current subtree.
1368 When nil, the new heading is created directly after the current line.
1369 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1370 this variable on for the duration of the command."
1371 :group 'org-structure
1372 :type 'boolean)
1374 (defcustom org-blank-before-new-entry '((heading . auto)
1375 (plain-list-item . auto))
1376 "Should `org-insert-heading' leave a blank line before new heading/item?
1377 The value is an alist, with `heading' and `plain-list-item' as CAR,
1378 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1379 which case Org will look at the surrounding headings/items and try to
1380 make an intelligent decision whether to insert a blank line or not.
1382 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1383 the setting here is ignored and no empty line is inserted to avoid breaking
1384 the list structure."
1385 :group 'org-edit-structure
1386 :type '(list
1387 (cons (const heading)
1388 (choice (const :tag "Never" nil)
1389 (const :tag "Always" t)
1390 (const :tag "Auto" auto)))
1391 (cons (const plain-list-item)
1392 (choice (const :tag "Never" nil)
1393 (const :tag "Always" t)
1394 (const :tag "Auto" auto)))))
1396 (defcustom org-insert-heading-hook nil
1397 "Hook being run after inserting a new heading."
1398 :group 'org-edit-structure
1399 :type 'hook)
1401 (defcustom org-enable-fixed-width-editor t
1402 "Non-nil means lines starting with \":\" are treated as fixed-width.
1403 This currently only means they are never auto-wrapped.
1404 When nil, such lines will be treated like ordinary lines.
1405 See also the QUOTE keyword."
1406 :group 'org-edit-structure
1407 :type 'boolean)
1409 (defcustom org-goto-auto-isearch t
1410 "Non-nil means typing characters in `org-goto' starts incremental search.
1411 When nil, you can use these keybindings to navigate the buffer:
1413 q Quit the org-goto interface
1414 n Go to the next visible heading
1415 p Go to the previous visible heading
1416 f Go one heading forward on same level
1417 b Go one heading backward on same level
1418 u Go one heading up"
1419 :group 'org-edit-structure
1420 :type 'boolean)
1422 (defgroup org-sparse-trees nil
1423 "Options concerning sparse trees in Org-mode."
1424 :tag "Org Sparse Trees"
1425 :group 'org-structure)
1427 (defcustom org-highlight-sparse-tree-matches t
1428 "Non-nil means highlight all matches that define a sparse tree.
1429 The highlights will automatically disappear the next time the buffer is
1430 changed by an edit command."
1431 :group 'org-sparse-trees
1432 :type 'boolean)
1434 (defcustom org-remove-highlights-with-change t
1435 "Non-nil means any change to the buffer will remove temporary highlights.
1436 Such highlights are created by `org-occur' and `org-clock-display'.
1437 When nil, `C-c C-c needs to be used to get rid of the highlights.
1438 The highlights created by `org-preview-latex-fragment' always need
1439 `C-c C-c' to be removed."
1440 :group 'org-sparse-trees
1441 :group 'org-time
1442 :type 'boolean)
1445 (defcustom org-occur-hook '(org-first-headline-recenter)
1446 "Hook that is run after `org-occur' has constructed a sparse tree.
1447 This can be used to recenter the window to show as much of the structure
1448 as possible."
1449 :group 'org-sparse-trees
1450 :type 'hook)
1452 (defgroup org-imenu-and-speedbar nil
1453 "Options concerning imenu and speedbar in Org-mode."
1454 :tag "Org Imenu and Speedbar"
1455 :group 'org-structure)
1457 (defcustom org-imenu-depth 2
1458 "The maximum level for Imenu access to Org-mode headlines.
1459 This also applied for speedbar access."
1460 :group 'org-imenu-and-speedbar
1461 :type 'integer)
1463 (defgroup org-table nil
1464 "Options concerning tables in Org-mode."
1465 :tag "Org Table"
1466 :group 'org)
1468 (defcustom org-enable-table-editor 'optimized
1469 "Non-nil means lines starting with \"|\" are handled by the table editor.
1470 When nil, such lines will be treated like ordinary lines.
1472 When equal to the symbol `optimized', the table editor will be optimized to
1473 do the following:
1474 - Automatic overwrite mode in front of whitespace in table fields.
1475 This makes the structure of the table stay in tact as long as the edited
1476 field does not exceed the column width.
1477 - Minimize the number of realigns. Normally, the table is aligned each time
1478 TAB or RET are pressed to move to another field. With optimization this
1479 happens only if changes to a field might have changed the column width.
1480 Optimization requires replacing the functions `self-insert-command',
1481 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1482 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1483 very good at guessing when a re-align will be necessary, but you can always
1484 force one with \\[org-ctrl-c-ctrl-c].
1486 If you would like to use the optimized version in Org-mode, but the
1487 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1489 This variable can be used to turn on and off the table editor during a session,
1490 but in order to toggle optimization, a restart is required.
1492 See also the variable `org-table-auto-blank-field'."
1493 :group 'org-table
1494 :type '(choice
1495 (const :tag "off" nil)
1496 (const :tag "on" t)
1497 (const :tag "on, optimized" optimized)))
1499 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1500 (version<= emacs-version "24.1"))
1501 "Non-nil means cluster self-insert commands for undo when possible.
1502 If this is set, then, like in the Emacs command loop, 20 consecutive
1503 characters will be undone together.
1504 This is configurable, because there is some impact on typing performance."
1505 :group 'org-table
1506 :type 'boolean)
1508 (defcustom org-table-tab-recognizes-table.el t
1509 "Non-nil means TAB will automatically notice a table.el table.
1510 When it sees such a table, it moves point into it and - if necessary -
1511 calls `table-recognize-table'."
1512 :group 'org-table-editing
1513 :type 'boolean)
1515 (defgroup org-link nil
1516 "Options concerning links in Org-mode."
1517 :tag "Org Link"
1518 :group 'org)
1520 (defvar org-link-abbrev-alist-local nil
1521 "Buffer-local version of `org-link-abbrev-alist', which see.
1522 The value of this is taken from the #+LINK lines.")
1523 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1525 (defcustom org-link-abbrev-alist nil
1526 "Alist of link abbreviations.
1527 The car of each element is a string, to be replaced at the start of a link.
1528 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1529 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1531 [[linkkey:tag][description]]
1533 The 'linkkey' must be a word word, starting with a letter, followed
1534 by letters, numbers, '-' or '_'.
1536 If REPLACE is a string, the tag will simply be appended to create the link.
1537 If the string contains \"%s\", the tag will be inserted there. If the string
1538 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1539 at that point (see the function `url-hexify-string'). If the string contains
1540 the specifier \"%(my-function)\", then the custom function `my-function' will
1541 be invoked: this function takes the tag as its only argument and must return
1542 a string.
1544 REPLACE may also be a function that will be called with the tag as the
1545 only argument to create the link, which should be returned as a string.
1547 See the manual for examples."
1548 :group 'org-link
1549 :type '(repeat
1550 (cons
1551 (string :tag "Protocol")
1552 (choice
1553 (string :tag "Format")
1554 (function)))))
1556 (defcustom org-descriptive-links t
1557 "Non-nil means Org will display descriptive links.
1558 E.g. [[http://orgmode.org][Org website]] will be displayed as
1559 \"Org Website\", hiding the link itself and just displaying its
1560 description. When set to `nil', Org will display the full links
1561 literally.
1563 You can interactively set the value of this variable by calling
1564 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1565 :group 'org-link
1566 :type 'boolean)
1568 (defcustom org-link-file-path-type 'adaptive
1569 "How the path name in file links should be stored.
1570 Valid values are:
1572 relative Relative to the current directory, i.e. the directory of the file
1573 into which the link is being inserted.
1574 absolute Absolute path, if possible with ~ for home directory.
1575 noabbrev Absolute path, no abbreviation of home directory.
1576 adaptive Use relative path for files in the current directory and sub-
1577 directories of it. For other files, use an absolute path."
1578 :group 'org-link
1579 :type '(choice
1580 (const relative)
1581 (const absolute)
1582 (const noabbrev)
1583 (const adaptive)))
1585 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1586 "Types of links that should be activated in Org-mode files.
1587 This is a list of symbols, each leading to the activation of a certain link
1588 type. In principle, it does not hurt to turn on most link types - there may
1589 be a small gain when turning off unused link types. The types are:
1591 bracket The recommended [[link][description]] or [[link]] links with hiding.
1592 angle Links in angular brackets that may contain whitespace like
1593 <bbdb:Carsten Dominik>.
1594 plain Plain links in normal text, no whitespace, like http://google.com.
1595 radio Text that is matched by a radio target, see manual for details.
1596 tag Tag settings in a headline (link to tag search).
1597 date Time stamps (link to calendar).
1598 footnote Footnote labels.
1600 Changing this variable requires a restart of Emacs to become effective."
1601 :group 'org-link
1602 :type '(set :greedy t
1603 (const :tag "Double bracket links" bracket)
1604 (const :tag "Angular bracket links" angle)
1605 (const :tag "Plain text links" plain)
1606 (const :tag "Radio target matches" radio)
1607 (const :tag "Tags" tag)
1608 (const :tag "Timestamps" date)
1609 (const :tag "Footnotes" footnote)))
1611 (defcustom org-make-link-description-function nil
1612 "Function to use for generating link descriptions from links.
1613 When nil, the link location will be used. This function must take
1614 two parameters: the first one is the link, the second one is the
1615 description generated by `org-insert-link'. The function should
1616 return the description to use."
1617 :group 'org-link
1618 :type '(choice (const nil) (function)))
1620 (defgroup org-link-store nil
1621 "Options concerning storing links in Org-mode."
1622 :tag "Org Store Link"
1623 :group 'org-link)
1625 (defcustom org-url-hexify-p t
1626 "When non-nil, hexify URL when creating a link."
1627 :type 'boolean
1628 :version "24.3"
1629 :group 'org-link-store)
1631 (defcustom org-email-link-description-format "Email %c: %.30s"
1632 "Format of the description part of a link to an email or usenet message.
1633 The following %-escapes will be replaced by corresponding information:
1635 %F full \"From\" field
1636 %f name, taken from \"From\" field, address if no name
1637 %T full \"To\" field
1638 %t first name in \"To\" field, address if no name
1639 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1640 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1641 %s subject
1642 %d date
1643 %m message-id.
1645 You may use normal field width specification between the % and the letter.
1646 This is for example useful to limit the length of the subject.
1648 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1649 :group 'org-link-store
1650 :type 'string)
1652 (defcustom org-from-is-user-regexp
1653 (let (r1 r2)
1654 (when (and user-mail-address (not (string= user-mail-address "")))
1655 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1656 (when (and user-full-name (not (string= user-full-name "")))
1657 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1658 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1659 "Regexp matched against the \"From:\" header of an email or usenet message.
1660 It should match if the message is from the user him/herself."
1661 :group 'org-link-store
1662 :type 'regexp)
1664 (defcustom org-context-in-file-links t
1665 "Non-nil means file links from `org-store-link' contain context.
1666 A search string will be added to the file name with :: as separator and
1667 used to find the context when the link is activated by the command
1668 `org-open-at-point'. When this option is t, the entire active region
1669 will be placed in the search string of the file link. If set to a
1670 positive integer, only the first n lines of context will be stored.
1672 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1673 negates this setting for the duration of the command."
1674 :group 'org-link-store
1675 :type '(choice boolean integer))
1677 (defcustom org-keep-stored-link-after-insertion nil
1678 "Non-nil means keep link in list for entire session.
1680 The command `org-store-link' adds a link pointing to the current
1681 location to an internal list. These links accumulate during a session.
1682 The command `org-insert-link' can be used to insert links into any
1683 Org-mode file (offering completion for all stored links). When this
1684 option is nil, every link which has been inserted once using \\[org-insert-link]
1685 will be removed from the list, to make completing the unused links
1686 more efficient."
1687 :group 'org-link-store
1688 :type 'boolean)
1690 (defgroup org-link-follow nil
1691 "Options concerning following links in Org-mode."
1692 :tag "Org Follow Link"
1693 :group 'org-link)
1695 (defcustom org-link-translation-function nil
1696 "Function to translate links with different syntax to Org syntax.
1697 This can be used to translate links created for example by the Planner
1698 or emacs-wiki packages to Org syntax.
1699 The function must accept two parameters, a TYPE containing the link
1700 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1701 which is everything after the link protocol. It should return a cons
1702 with possibly modified values of type and path.
1703 Org contains a function for this, so if you set this variable to
1704 `org-translate-link-from-planner', you should be able follow many
1705 links created by planner."
1706 :group 'org-link-follow
1707 :type '(choice (const nil) (function)))
1709 (defcustom org-follow-link-hook nil
1710 "Hook that is run after a link has been followed."
1711 :group 'org-link-follow
1712 :type 'hook)
1714 (defcustom org-tab-follows-link nil
1715 "Non-nil means on links TAB will follow the link.
1716 Needs to be set before org.el is loaded.
1717 This really should not be used, it does not make sense, and the
1718 implementation is bad."
1719 :group 'org-link-follow
1720 :type 'boolean)
1722 (defcustom org-return-follows-link nil
1723 "Non-nil means on links RET will follow the link.
1724 In tables, the special behavior of RET has precedence."
1725 :group 'org-link-follow
1726 :type 'boolean)
1728 (defcustom org-mouse-1-follows-link
1729 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1730 "Non-nil means mouse-1 on a link will follow the link.
1731 A longer mouse click will still set point. Does not work on XEmacs.
1732 Needs to be set before org.el is loaded."
1733 :group 'org-link-follow
1734 :version "24.4"
1735 :package-version '(Org . "8.3")
1736 :type '(choice
1737 (const :tag "A double click follows the link" 'double)
1738 (const :tag "Unconditionally follow the link with mouse-1" t)
1739 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1741 (defcustom org-mark-ring-length 4
1742 "Number of different positions to be recorded in the ring.
1743 Changing this requires a restart of Emacs to work correctly."
1744 :group 'org-link-follow
1745 :type 'integer)
1747 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1748 "Non-nil means internal links in Org files must exactly match a headline.
1749 When nil, the link search tries to match a phrase with all words
1750 in the search text."
1751 :group 'org-link-follow
1752 :version "24.1"
1753 :type '(choice
1754 (const :tag "Use fuzzy text search" nil)
1755 (const :tag "Match only exact headline" t)
1756 (const :tag "Match exact headline or query to create it"
1757 query-to-create)))
1759 (defcustom org-link-frame-setup
1760 '((vm . vm-visit-folder-other-frame)
1761 (vm-imap . vm-visit-imap-folder-other-frame)
1762 (gnus . org-gnus-no-new-news)
1763 (file . find-file-other-window)
1764 (wl . wl-other-frame))
1765 "Setup the frame configuration for following links.
1766 When following a link with Emacs, it may often be useful to display
1767 this link in another window or frame. This variable can be used to
1768 set this up for the different types of links.
1769 For VM, use any of
1770 `vm-visit-folder'
1771 `vm-visit-folder-other-window'
1772 `vm-visit-folder-other-frame'
1773 For Gnus, use any of
1774 `gnus'
1775 `gnus-other-frame'
1776 `org-gnus-no-new-news'
1777 For FILE, use any of
1778 `find-file'
1779 `find-file-other-window'
1780 `find-file-other-frame'
1781 For Wanderlust use any of
1782 `wl'
1783 `wl-other-frame'
1784 For the calendar, use the variable `calendar-setup'.
1785 For BBDB, it is currently only possible to display the matches in
1786 another window."
1787 :group 'org-link-follow
1788 :type '(list
1789 (cons (const vm)
1790 (choice
1791 (const vm-visit-folder)
1792 (const vm-visit-folder-other-window)
1793 (const vm-visit-folder-other-frame)))
1794 (cons (const vm-imap)
1795 (choice
1796 (const vm-visit-imap-folder)
1797 (const vm-visit-imap-folder-other-window)
1798 (const vm-visit-imap-folder-other-frame)))
1799 (cons (const gnus)
1800 (choice
1801 (const gnus)
1802 (const gnus-other-frame)
1803 (const org-gnus-no-new-news)))
1804 (cons (const file)
1805 (choice
1806 (const find-file)
1807 (const find-file-other-window)
1808 (const find-file-other-frame)))
1809 (cons (const wl)
1810 (choice
1811 (const wl)
1812 (const wl-other-frame)))))
1814 (defcustom org-display-internal-link-with-indirect-buffer nil
1815 "Non-nil means use indirect buffer to display infile links.
1816 Activating internal links (from one location in a file to another location
1817 in the same file) normally just jumps to the location. When the link is
1818 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1819 is displayed in
1820 another window. When this option is set, the other window actually displays
1821 an indirect buffer clone of the current buffer, to avoid any visibility
1822 changes to the current buffer."
1823 :group 'org-link-follow
1824 :type 'boolean)
1826 (defcustom org-open-non-existing-files nil
1827 "Non-nil means `org-open-file' will open non-existing files.
1828 When nil, an error will be generated.
1829 This variable applies only to external applications because they
1830 might choke on non-existing files. If the link is to a file that
1831 will be opened in Emacs, the variable is ignored."
1832 :group 'org-link-follow
1833 :type 'boolean)
1835 (defcustom org-open-directory-means-index-dot-org nil
1836 "Non-nil means a link to a directory really means to index.org.
1837 When nil, following a directory link will run dired or open a finder/explorer
1838 window on that directory."
1839 :group 'org-link-follow
1840 :type 'boolean)
1842 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1843 "Function and arguments to call for following mailto links.
1844 This is a list with the first element being a Lisp function, and the
1845 remaining elements being arguments to the function. In string arguments,
1846 %a will be replaced by the address, and %s will be replaced by the subject
1847 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1848 :group 'org-link-follow
1849 :type '(choice
1850 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1851 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1852 (const :tag "message-mail" (message-mail "%a" "%s"))
1853 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1855 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1856 "Non-nil means ask for confirmation before executing shell links.
1857 Shell links can be dangerous: just think about a link
1859 [[shell:rm -rf ~/*][Google Search]]
1861 This link would show up in your Org-mode document as \"Google Search\",
1862 but really it would remove your entire home directory.
1863 Therefore we advise against setting this variable to nil.
1864 Just change it to `y-or-n-p' if you want to confirm with a
1865 single keystroke rather than having to type \"yes\"."
1866 :group 'org-link-follow
1867 :type '(choice
1868 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1869 (const :tag "with y-or-n (faster)" y-or-n-p)
1870 (const :tag "no confirmation (dangerous)" nil)))
1871 (put 'org-confirm-shell-link-function
1872 'safe-local-variable
1873 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1875 (defcustom org-confirm-shell-link-not-regexp ""
1876 "A regexp to skip confirmation for shell links."
1877 :group 'org-link-follow
1878 :version "24.1"
1879 :type 'regexp)
1881 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1882 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1883 Elisp links can be dangerous: just think about a link
1885 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1887 This link would show up in your Org-mode document as \"Google Search\",
1888 but really it would remove your entire home directory.
1889 Therefore we advise against setting this variable to nil.
1890 Just change it to `y-or-n-p' if you want to confirm with a
1891 single keystroke rather than having to type \"yes\"."
1892 :group 'org-link-follow
1893 :type '(choice
1894 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1895 (const :tag "with y-or-n (faster)" y-or-n-p)
1896 (const :tag "no confirmation (dangerous)" nil)))
1897 (put 'org-confirm-shell-link-function
1898 'safe-local-variable
1899 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1901 (defcustom org-confirm-elisp-link-not-regexp ""
1902 "A regexp to skip confirmation for Elisp links."
1903 :group 'org-link-follow
1904 :version "24.1"
1905 :type 'regexp)
1907 (defconst org-file-apps-defaults-gnu
1908 '((remote . emacs)
1909 (system . mailcap)
1910 (t . mailcap))
1911 "Default file applications on a UNIX or GNU/Linux system.
1912 See `org-file-apps'.")
1914 (defconst org-file-apps-defaults-macosx
1915 '((remote . emacs)
1916 (t . "open %s")
1917 (system . "open %s")
1918 ("ps.gz" . "gv %s")
1919 ("eps.gz" . "gv %s")
1920 ("dvi" . "xdvi %s")
1921 ("fig" . "xfig %s"))
1922 "Default file applications on a MacOS X system.
1923 The system \"open\" is known as a default, but we use X11 applications
1924 for some files for which the OS does not have a good default.
1925 See `org-file-apps'.")
1927 (defconst org-file-apps-defaults-windowsnt
1928 (list
1929 '(remote . emacs)
1930 (cons t
1931 (list (if (featurep 'xemacs)
1932 'mswindows-shell-execute
1933 'w32-shell-execute)
1934 "open" 'file))
1935 (cons 'system
1936 (list (if (featurep 'xemacs)
1937 'mswindows-shell-execute
1938 'w32-shell-execute)
1939 "open" 'file)))
1940 "Default file applications on a Windows NT system.
1941 The system \"open\" is used for most files.
1942 See `org-file-apps'.")
1944 (defcustom org-file-apps
1945 '((auto-mode . emacs)
1946 ("\\.mm\\'" . default)
1947 ("\\.x?html?\\'" . default)
1948 ("\\.pdf\\'" . default))
1949 "External applications for opening `file:path' items in a document.
1950 Org-mode uses system defaults for different file types, but
1951 you can use this variable to set the application for a given file
1952 extension. The entries in this list are cons cells where the car identifies
1953 files and the cdr the corresponding command. Possible values for the
1954 file identifier are
1955 \"string\" A string as a file identifier can be interpreted in different
1956 ways, depending on its contents:
1958 - Alphanumeric characters only:
1959 Match links with this file extension.
1960 Example: (\"pdf\" . \"evince %s\")
1961 to open PDFs with evince.
1963 - Regular expression: Match links where the
1964 filename matches the regexp. If you want to
1965 use groups here, use shy groups.
1967 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1968 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1969 to open *.html and *.xhtml with firefox.
1971 - Regular expression which contains (non-shy) groups:
1972 Match links where the whole link, including \"::\", and
1973 anything after that, matches the regexp.
1974 In a custom command string, %1, %2, etc. are replaced with
1975 the parts of the link that were matched by the groups.
1976 For backwards compatibility, if a command string is given
1977 that does not use any of the group matches, this case is
1978 handled identically to the second one (i.e. match against
1979 file name only).
1980 In a custom lisp form, you can access the group matches with
1981 (match-string n link).
1983 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1984 to open [[file:document.pdf::5]] with evince at page 5.
1986 `directory' Matches a directory
1987 `remote' Matches a remote file, accessible through tramp or efs.
1988 Remote files most likely should be visited through Emacs
1989 because external applications cannot handle such paths.
1990 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1991 so all files Emacs knows how to handle. Using this with
1992 command `emacs' will open most files in Emacs. Beware that this
1993 will also open html files inside Emacs, unless you add
1994 (\"html\" . default) to the list as well.
1995 t Default for files not matched by any of the other options.
1996 `system' The system command to open files, like `open' on Windows
1997 and Mac OS X, and mailcap under GNU/Linux. This is the command
1998 that will be selected if you call `C-c C-o' with a double
1999 \\[universal-argument] \\[universal-argument] prefix.
2001 Possible values for the command are:
2002 `emacs' The file will be visited by the current Emacs process.
2003 `default' Use the default application for this file type, which is the
2004 association for t in the list, most likely in the system-specific
2005 part.
2006 This can be used to overrule an unwanted setting in the
2007 system-specific variable.
2008 `system' Use the system command for opening files, like \"open\".
2009 This command is specified by the entry whose car is `system'.
2010 Most likely, the system-specific version of this variable
2011 does define this command, but you can overrule/replace it
2012 here.
2013 string A command to be executed by a shell; %s will be replaced
2014 by the path to the file.
2015 sexp A Lisp form which will be evaluated. The file path will
2016 be available in the Lisp variable `file'.
2017 For more examples, see the system specific constants
2018 `org-file-apps-defaults-macosx'
2019 `org-file-apps-defaults-windowsnt'
2020 `org-file-apps-defaults-gnu'."
2021 :group 'org-link-follow
2022 :type '(repeat
2023 (cons (choice :value ""
2024 (string :tag "Extension")
2025 (const :tag "System command to open files" system)
2026 (const :tag "Default for unrecognized files" t)
2027 (const :tag "Remote file" remote)
2028 (const :tag "Links to a directory" directory)
2029 (const :tag "Any files that have Emacs modes"
2030 auto-mode))
2031 (choice :value ""
2032 (const :tag "Visit with Emacs" emacs)
2033 (const :tag "Use default" default)
2034 (const :tag "Use the system command" system)
2035 (string :tag "Command")
2036 (sexp :tag "Lisp form")))))
2038 (defcustom org-doi-server-url "http://dx.doi.org/"
2039 "The URL of the DOI server."
2040 :type 'string
2041 :version "24.3"
2042 :group 'org-link-follow)
2044 (defgroup org-refile nil
2045 "Options concerning refiling entries in Org-mode."
2046 :tag "Org Refile"
2047 :group 'org)
2049 (defcustom org-directory "~/org"
2050 "Directory with org files.
2051 This is just a default location to look for Org files. There is no need
2052 at all to put your files into this directory. It is only used in the
2053 following situations:
2055 1. When a capture template specifies a target file that is not an
2056 absolute path. The path will then be interpreted relative to
2057 `org-directory'
2058 2. When a capture note is filed away in an interactive way (when exiting the
2059 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2060 with `org-directory' as the default path."
2061 :group 'org-refile
2062 :group 'org-capture
2063 :type 'directory)
2065 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2066 "Default target for storing notes.
2067 Used as a fall back file for org-capture.el, for templates that
2068 do not specify a target file."
2069 :group 'org-refile
2070 :group 'org-capture
2071 :type '(choice
2072 (const :tag "Default from remember-data-file" nil)
2073 file))
2075 (defcustom org-goto-interface 'outline
2076 "The default interface to be used for `org-goto'.
2077 Allowed values are:
2078 outline The interface shows an outline of the relevant file
2079 and the correct heading is found by moving through
2080 the outline or by searching with incremental search.
2081 outline-path-completion Headlines in the current buffer are offered via
2082 completion. This is the interface also used by
2083 the refile command."
2084 :group 'org-refile
2085 :type '(choice
2086 (const :tag "Outline" outline)
2087 (const :tag "Outline-path-completion" outline-path-completion)))
2089 (defcustom org-goto-max-level 5
2090 "Maximum target level when running `org-goto' with refile interface."
2091 :group 'org-refile
2092 :type 'integer)
2094 (defcustom org-reverse-note-order nil
2095 "Non-nil means store new notes at the beginning of a file or entry.
2096 When nil, new notes will be filed to the end of a file or entry.
2097 This can also be a list with cons cells of regular expressions that
2098 are matched against file names, and values."
2099 :group 'org-capture
2100 :group 'org-refile
2101 :type '(choice
2102 (const :tag "Reverse always" t)
2103 (const :tag "Reverse never" nil)
2104 (repeat :tag "By file name regexp"
2105 (cons regexp boolean))))
2107 (defcustom org-log-refile nil
2108 "Information to record when a task is refiled.
2110 Possible values are:
2112 nil Don't add anything
2113 time Add a time stamp to the task
2114 note Prompt for a note and add it with template `org-log-note-headings'
2116 This option can also be set with on a per-file-basis with
2118 #+STARTUP: nologrefile
2119 #+STARTUP: logrefile
2120 #+STARTUP: lognoterefile
2122 You can have local logging settings for a subtree by setting the LOGGING
2123 property to one or more of these keywords.
2125 When bulk-refiling from the agenda, the value `note' is forbidden and
2126 will temporarily be changed to `time'."
2127 :group 'org-refile
2128 :group 'org-progress
2129 :version "24.1"
2130 :type '(choice
2131 (const :tag "No logging" nil)
2132 (const :tag "Record timestamp" time)
2133 (const :tag "Record timestamp with note." note)))
2135 (defcustom org-refile-targets nil
2136 "Targets for refiling entries with \\[org-refile].
2137 This is a list of cons cells. Each cell contains:
2138 - a specification of the files to be considered, either a list of files,
2139 or a symbol whose function or variable value will be used to retrieve
2140 a file name or a list of file names. If you use `org-agenda-files' for
2141 that, all agenda files will be scanned for targets. Nil means consider
2142 headings in the current buffer.
2143 - A specification of how to find candidate refile targets. This may be
2144 any of:
2145 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2146 This tag has to be present in all target headlines, inheritance will
2147 not be considered.
2148 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2149 todo keyword.
2150 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2151 headlines that are refiling targets.
2152 - a cons cell (:level . N). Any headline of level N is considered a target.
2153 Note that, when `org-odd-levels-only' is set, level corresponds to
2154 order in hierarchy, not to the number of stars.
2155 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2156 Note that, when `org-odd-levels-only' is set, level corresponds to
2157 order in hierarchy, not to the number of stars.
2159 Each element of this list generates a set of possible targets.
2160 The union of these sets is presented (with completion) to
2161 the user by `org-refile'.
2163 You can set the variable `org-refile-target-verify-function' to a function
2164 to verify each headline found by the simple criteria above.
2166 When this variable is nil, all top-level headlines in the current buffer
2167 are used, equivalent to the value `((nil . (:level . 1))'."
2168 :group 'org-refile
2169 :type '(repeat
2170 (cons
2171 (choice :value org-agenda-files
2172 (const :tag "All agenda files" org-agenda-files)
2173 (const :tag "Current buffer" nil)
2174 (function) (variable) (file))
2175 (choice :tag "Identify target headline by"
2176 (cons :tag "Specific tag" (const :value :tag) (string))
2177 (cons :tag "TODO keyword" (const :value :todo) (string))
2178 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2179 (cons :tag "Level number" (const :value :level) (integer))
2180 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2182 (defcustom org-refile-target-verify-function nil
2183 "Function to verify if the headline at point should be a refile target.
2184 The function will be called without arguments, with point at the
2185 beginning of the headline. It should return t and leave point
2186 where it is if the headline is a valid target for refiling.
2188 If the target should not be selected, the function must return nil.
2189 In addition to this, it may move point to a place from where the search
2190 should be continued. For example, the function may decide that the entire
2191 subtree of the current entry should be excluded and move point to the end
2192 of the subtree."
2193 :group 'org-refile
2194 :type '(choice
2195 (const nil)
2196 (function)))
2198 (defcustom org-refile-use-cache nil
2199 "Non-nil means cache refile targets to speed up the process.
2200 The cache for a particular file will be updated automatically when
2201 the buffer has been killed, or when any of the marker used for flagging
2202 refile targets no longer points at a live buffer.
2203 If you have added new entries to a buffer that might themselves be targets,
2204 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2205 find that easier, `C-u C-u C-u C-c C-w'."
2206 :group 'org-refile
2207 :version "24.1"
2208 :type 'boolean)
2210 (defcustom org-refile-use-outline-path nil
2211 "Non-nil means provide refile targets as paths.
2212 So a level 3 headline will be available as level1/level2/level3.
2214 When the value is `file', also include the file name (without directory)
2215 into the path. In this case, you can also stop the completion after
2216 the file name, to get entries inserted as top level in the file.
2218 When `full-file-path', include the full file path."
2219 :group 'org-refile
2220 :type '(choice
2221 (const :tag "Not" nil)
2222 (const :tag "Yes" t)
2223 (const :tag "Start with file name" file)
2224 (const :tag "Start with full file path" full-file-path)))
2226 (defcustom org-outline-path-complete-in-steps t
2227 "Non-nil means complete the outline path in hierarchical steps.
2228 When Org-mode uses the refile interface to select an outline path
2229 \(see variable `org-refile-use-outline-path'), the completion of
2230 the path can be done is a single go, or if can be done in steps down
2231 the headline hierarchy. Going in steps is probably the best if you
2232 do not use a special completion package like `ido' or `icicles'.
2233 However, when using these packages, going in one step can be very
2234 fast, while still showing the whole path to the entry."
2235 :group 'org-refile
2236 :type 'boolean)
2238 (defcustom org-refile-allow-creating-parent-nodes nil
2239 "Non-nil means allow to create new nodes as refile targets.
2240 New nodes are then created by adding \"/new node name\" to the completion
2241 of an existing node. When the value of this variable is `confirm',
2242 new node creation must be confirmed by the user (recommended)
2243 When nil, the completion must match an existing entry.
2245 Note that, if the new heading is not seen by the criteria
2246 listed in `org-refile-targets', multiple instances of the same
2247 heading would be created by trying again to file under the new
2248 heading."
2249 :group 'org-refile
2250 :type '(choice
2251 (const :tag "Never" nil)
2252 (const :tag "Always" t)
2253 (const :tag "Prompt for confirmation" confirm)))
2255 (defcustom org-refile-active-region-within-subtree nil
2256 "Non-nil means also refile active region within a subtree.
2258 By default `org-refile' doesn't allow refiling regions if they
2259 don't contain a set of subtrees, but it might be convenient to
2260 do so sometimes: in that case, the first line of the region is
2261 converted to a headline before refiling."
2262 :group 'org-refile
2263 :version "24.1"
2264 :type 'boolean)
2266 (defgroup org-todo nil
2267 "Options concerning TODO items in Org-mode."
2268 :tag "Org TODO"
2269 :group 'org)
2271 (defgroup org-progress nil
2272 "Options concerning Progress logging in Org-mode."
2273 :tag "Org Progress"
2274 :group 'org-time)
2276 (defvar org-todo-interpretation-widgets
2277 '((:tag "Sequence (cycling hits every state)" sequence)
2278 (:tag "Type (cycling directly to DONE)" type))
2279 "The available interpretation symbols for customizing `org-todo-keywords'.
2280 Interested libraries should add to this list.")
2282 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2283 "List of TODO entry keyword sequences and their interpretation.
2284 \\<org-mode-map>This is a list of sequences.
2286 Each sequence starts with a symbol, either `sequence' or `type',
2287 indicating if the keywords should be interpreted as a sequence of
2288 action steps, or as different types of TODO items. The first
2289 keywords are states requiring action - these states will select a headline
2290 for inclusion into the global TODO list Org-mode produces. If one of
2291 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2292 signify that no further action is necessary. If \"|\" is not found,
2293 the last keyword is treated as the only DONE state of the sequence.
2295 The command \\[org-todo] cycles an entry through these states, and one
2296 additional state where no keyword is present. For details about this
2297 cycling, see the manual.
2299 TODO keywords and interpretation can also be set on a per-file basis with
2300 the special #+SEQ_TODO and #+TYP_TODO lines.
2302 Each keyword can optionally specify a character for fast state selection
2303 \(in combination with the variable `org-use-fast-todo-selection')
2304 and specifiers for state change logging, using the same syntax that
2305 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2306 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2307 indicates to record a time stamp each time this state is selected.
2309 Each keyword may also specify if a timestamp or a note should be
2310 recorded when entering or leaving the state, by adding additional
2311 characters in the parenthesis after the keyword. This looks like this:
2312 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2313 record only the time of the state change. With X and Y being either
2314 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2315 Y when leaving the state if and only if the *target* state does not
2316 define X. You may omit any of the fast-selection key or X or /Y,
2317 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2319 For backward compatibility, this variable may also be just a list
2320 of keywords. In this case the interpretation (sequence or type) will be
2321 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2322 :group 'org-todo
2323 :group 'org-keywords
2324 :type '(choice
2325 (repeat :tag "Old syntax, just keywords"
2326 (string :tag "Keyword"))
2327 (repeat :tag "New syntax"
2328 (cons
2329 (choice
2330 :tag "Interpretation"
2331 ;;Quick and dirty way to see
2332 ;;`org-todo-interpretations'. This takes the
2333 ;;place of item arguments
2334 :convert-widget
2335 (lambda (widget)
2336 (widget-put widget
2337 :args (mapcar
2338 #'(lambda (x)
2339 (widget-convert
2340 (cons 'const x)))
2341 org-todo-interpretation-widgets))
2342 widget))
2343 (repeat
2344 (string :tag "Keyword"))))))
2346 (defvar org-todo-keywords-1 nil
2347 "All TODO and DONE keywords active in a buffer.")
2348 (make-variable-buffer-local 'org-todo-keywords-1)
2349 (defvar org-todo-keywords-for-agenda nil)
2350 (defvar org-done-keywords-for-agenda nil)
2351 (defvar org-drawers-for-agenda nil)
2352 (defvar org-todo-keyword-alist-for-agenda nil)
2353 (defvar org-tag-alist-for-agenda nil
2354 "Alist of all tags from all agenda files.")
2355 (defvar org-tag-groups-alist-for-agenda nil
2356 "Alist of all groups tags from all current agenda files.")
2357 (defvar org-tag-groups-alist nil)
2358 (make-variable-buffer-local 'org-tag-groups-alist)
2359 (defvar org-agenda-contributing-files nil)
2360 (defvar org-not-done-keywords nil)
2361 (make-variable-buffer-local 'org-not-done-keywords)
2362 (defvar org-done-keywords nil)
2363 (make-variable-buffer-local 'org-done-keywords)
2364 (defvar org-todo-heads nil)
2365 (make-variable-buffer-local 'org-todo-heads)
2366 (defvar org-todo-sets nil)
2367 (make-variable-buffer-local 'org-todo-sets)
2368 (defvar org-todo-log-states nil)
2369 (make-variable-buffer-local 'org-todo-log-states)
2370 (defvar org-todo-kwd-alist nil)
2371 (make-variable-buffer-local 'org-todo-kwd-alist)
2372 (defvar org-todo-key-alist nil)
2373 (make-variable-buffer-local 'org-todo-key-alist)
2374 (defvar org-todo-key-trigger nil)
2375 (make-variable-buffer-local 'org-todo-key-trigger)
2377 (defcustom org-todo-interpretation 'sequence
2378 "Controls how TODO keywords are interpreted.
2379 This variable is in principle obsolete and is only used for
2380 backward compatibility, if the interpretation of todo keywords is
2381 not given already in `org-todo-keywords'. See that variable for
2382 more information."
2383 :group 'org-todo
2384 :group 'org-keywords
2385 :type '(choice (const sequence)
2386 (const type)))
2388 (defcustom org-use-fast-todo-selection t
2389 "Non-nil means use the fast todo selection scheme with C-c C-t.
2390 This variable describes if and under what circumstances the cycling
2391 mechanism for TODO keywords will be replaced by a single-key, direct
2392 selection scheme.
2394 When nil, fast selection is never used.
2396 When the symbol `prefix', it will be used when `org-todo' is called
2397 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2398 `C-u t' in an agenda buffer.
2400 When t, fast selection is used by default. In this case, the prefix
2401 argument forces cycling instead.
2403 In all cases, the special interface is only used if access keys have
2404 actually been assigned by the user, i.e. if keywords in the configuration
2405 are followed by a letter in parenthesis, like TODO(t)."
2406 :group 'org-todo
2407 :type '(choice
2408 (const :tag "Never" nil)
2409 (const :tag "By default" t)
2410 (const :tag "Only with C-u C-c C-t" prefix)))
2412 (defcustom org-provide-todo-statistics t
2413 "Non-nil means update todo statistics after insert and toggle.
2414 ALL-HEADLINES means update todo statistics by including headlines
2415 with no TODO keyword as well, counting them as not done.
2416 A list of TODO keywords means the same, but skip keywords that are
2417 not in this list.
2419 When this is set, todo statistics is updated in the parent of the
2420 current entry each time a todo state is changed."
2421 :group 'org-todo
2422 :type '(choice
2423 (const :tag "Yes, only for TODO entries" t)
2424 (const :tag "Yes, including all entries" 'all-headlines)
2425 (repeat :tag "Yes, for TODOs in this list"
2426 (string :tag "TODO keyword"))
2427 (other :tag "No TODO statistics" nil)))
2429 (defcustom org-hierarchical-todo-statistics t
2430 "Non-nil means TODO statistics covers just direct children.
2431 When nil, all entries in the subtree are considered.
2432 This has only an effect if `org-provide-todo-statistics' is set.
2433 To set this to nil for only a single subtree, use a COOKIE_DATA
2434 property and include the word \"recursive\" into the value."
2435 :group 'org-todo
2436 :type 'boolean)
2438 (defcustom org-after-todo-state-change-hook nil
2439 "Hook which is run after the state of a TODO item was changed.
2440 The new state (a string with a TODO keyword, or nil) is available in the
2441 Lisp variable `org-state'."
2442 :group 'org-todo
2443 :type 'hook)
2445 (defvar org-blocker-hook nil
2446 "Hook for functions that are allowed to block a state change.
2448 Functions in this hook should not modify the buffer.
2449 Each function gets as its single argument a property list,
2450 see `org-trigger-hook' for more information about this list.
2452 If any of the functions in this hook returns nil, the state change
2453 is blocked.")
2455 (defvar org-trigger-hook nil
2456 "Hook for functions that are triggered by a state change.
2458 Each function gets as its single argument a property list with at
2459 least the following elements:
2461 (:type type-of-change :position pos-at-entry-start
2462 :from old-state :to new-state)
2464 Depending on the type, more properties may be present.
2466 This mechanism is currently implemented for:
2468 TODO state changes
2469 ------------------
2470 :type todo-state-change
2471 :from previous state (keyword as a string), or nil, or a symbol
2472 'todo' or 'done', to indicate the general type of state.
2473 :to new state, like in :from")
2475 (defcustom org-enforce-todo-dependencies nil
2476 "Non-nil means undone TODO entries will block switching the parent to DONE.
2477 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2478 be blocked if any prior sibling is not yet done.
2479 Finally, if the parent is blocked because of ordered siblings of its own,
2480 the child will also be blocked."
2481 :set (lambda (var val)
2482 (set var val)
2483 (if val
2484 (add-hook 'org-blocker-hook
2485 'org-block-todo-from-children-or-siblings-or-parent)
2486 (remove-hook 'org-blocker-hook
2487 'org-block-todo-from-children-or-siblings-or-parent)))
2488 :group 'org-todo
2489 :type 'boolean)
2491 (defcustom org-enforce-todo-checkbox-dependencies nil
2492 "Non-nil means unchecked boxes will block switching the parent to DONE.
2493 When this is nil, checkboxes have no influence on switching TODO states.
2494 When non-nil, you first need to check off all check boxes before the TODO
2495 entry can be switched to DONE.
2496 This variable needs to be set before org.el is loaded, and you need to
2497 restart Emacs after a change to make the change effective. The only way
2498 to change is while Emacs is running is through the customize interface."
2499 :set (lambda (var val)
2500 (set var val)
2501 (if val
2502 (add-hook 'org-blocker-hook
2503 'org-block-todo-from-checkboxes)
2504 (remove-hook 'org-blocker-hook
2505 'org-block-todo-from-checkboxes)))
2506 :group 'org-todo
2507 :type 'boolean)
2509 (defcustom org-treat-insert-todo-heading-as-state-change nil
2510 "Non-nil means inserting a TODO heading is treated as state change.
2511 So when the command \\[org-insert-todo-heading] is used, state change
2512 logging will apply if appropriate. When nil, the new TODO item will
2513 be inserted directly, and no logging will take place."
2514 :group 'org-todo
2515 :type 'boolean)
2517 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2518 "Non-nil means switching TODO states with S-cursor counts as state change.
2519 This is the default behavior. However, setting this to nil allows a
2520 convenient way to select a TODO state and bypass any logging associated
2521 with that."
2522 :group 'org-todo
2523 :type 'boolean)
2525 (defcustom org-todo-state-tags-triggers nil
2526 "Tag changes that should be triggered by TODO state changes.
2527 This is a list. Each entry is
2529 (state-change (tag . flag) .......)
2531 State-change can be a string with a state, and empty string to indicate the
2532 state that has no TODO keyword, or it can be one of the symbols `todo'
2533 or `done', meaning any not-done or done state, respectively."
2534 :group 'org-todo
2535 :group 'org-tags
2536 :type '(repeat
2537 (cons (choice :tag "When changing to"
2538 (const :tag "Not-done state" todo)
2539 (const :tag "Done state" done)
2540 (string :tag "State"))
2541 (repeat
2542 (cons :tag "Tag action"
2543 (string :tag "Tag")
2544 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2546 (defcustom org-log-done nil
2547 "Information to record when a task moves to the DONE state.
2549 Possible values are:
2551 nil Don't add anything, just change the keyword
2552 time Add a time stamp to the task
2553 note Prompt for a note and add it with template `org-log-note-headings'
2555 This option can also be set with on a per-file-basis with
2557 #+STARTUP: nologdone
2558 #+STARTUP: logdone
2559 #+STARTUP: lognotedone
2561 You can have local logging settings for a subtree by setting the LOGGING
2562 property to one or more of these keywords."
2563 :group 'org-todo
2564 :group 'org-progress
2565 :type '(choice
2566 (const :tag "No logging" nil)
2567 (const :tag "Record CLOSED timestamp" time)
2568 (const :tag "Record CLOSED timestamp with note." note)))
2570 ;; Normalize old uses of org-log-done.
2571 (cond
2572 ((eq org-log-done t) (setq org-log-done 'time))
2573 ((and (listp org-log-done) (memq 'done org-log-done))
2574 (setq org-log-done 'note)))
2576 (defcustom org-log-reschedule nil
2577 "Information to record when the scheduling date of a tasks is modified.
2579 Possible values are:
2581 nil Don't add anything, just change the date
2582 time Add a time stamp to the task
2583 note Prompt for a note and add it with template `org-log-note-headings'
2585 This option can also be set with on a per-file-basis with
2587 #+STARTUP: nologreschedule
2588 #+STARTUP: logreschedule
2589 #+STARTUP: lognotereschedule"
2590 :group 'org-todo
2591 :group 'org-progress
2592 :type '(choice
2593 (const :tag "No logging" nil)
2594 (const :tag "Record timestamp" time)
2595 (const :tag "Record timestamp with note." note)))
2597 (defcustom org-log-redeadline nil
2598 "Information to record when the deadline date of a tasks is modified.
2600 Possible values are:
2602 nil Don't add anything, just change the date
2603 time Add a time stamp to the task
2604 note Prompt for a note and add it with template `org-log-note-headings'
2606 This option can also be set with on a per-file-basis with
2608 #+STARTUP: nologredeadline
2609 #+STARTUP: logredeadline
2610 #+STARTUP: lognoteredeadline
2612 You can have local logging settings for a subtree by setting the LOGGING
2613 property to one or more of these keywords."
2614 :group 'org-todo
2615 :group 'org-progress
2616 :type '(choice
2617 (const :tag "No logging" nil)
2618 (const :tag "Record timestamp" time)
2619 (const :tag "Record timestamp with note." note)))
2621 (defcustom org-log-note-clock-out nil
2622 "Non-nil means record a note when clocking out of an item.
2623 This can also be configured on a per-file basis by adding one of
2624 the following lines anywhere in the buffer:
2626 #+STARTUP: lognoteclock-out
2627 #+STARTUP: nolognoteclock-out"
2628 :group 'org-todo
2629 :group 'org-progress
2630 :type 'boolean)
2632 (defcustom org-log-done-with-time t
2633 "Non-nil means the CLOSED time stamp will contain date and time.
2634 When nil, only the date will be recorded."
2635 :group 'org-progress
2636 :type 'boolean)
2638 (defcustom org-log-note-headings
2639 '((done . "CLOSING NOTE %t")
2640 (state . "State %-12s from %-12S %t")
2641 (note . "Note taken on %t")
2642 (reschedule . "Rescheduled from %S on %t")
2643 (delschedule . "Not scheduled, was %S on %t")
2644 (redeadline . "New deadline from %S on %t")
2645 (deldeadline . "Removed deadline, was %S on %t")
2646 (refile . "Refiled on %t")
2647 (clock-out . ""))
2648 "Headings for notes added to entries.
2649 The value is an alist, with the car being a symbol indicating the note
2650 context, and the cdr is the heading to be used. The heading may also be the
2651 empty string.
2652 %t in the heading will be replaced by a time stamp.
2653 %T will be an active time stamp instead the default inactive one
2654 %d will be replaced by a short-format time stamp.
2655 %D will be replaced by an active short-format time stamp.
2656 %s will be replaced by the new TODO state, in double quotes.
2657 %S will be replaced by the old TODO state, in double quotes.
2658 %u will be replaced by the user name.
2659 %U will be replaced by the full user name.
2661 In fact, it is not a good idea to change the `state' entry, because
2662 agenda log mode depends on the format of these entries."
2663 :group 'org-todo
2664 :group 'org-progress
2665 :type '(list :greedy t
2666 (cons (const :tag "Heading when closing an item" done) string)
2667 (cons (const :tag
2668 "Heading when changing todo state (todo sequence only)"
2669 state) string)
2670 (cons (const :tag "Heading when just taking a note" note) string)
2671 (cons (const :tag "Heading when rescheduling" reschedule) string)
2672 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2673 (cons (const :tag "Heading when changing deadline" redeadline) string)
2674 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2675 (cons (const :tag "Heading when refiling" refile) string)
2676 (cons (const :tag "Heading when clocking out" clock-out) string)))
2678 (unless (assq 'note org-log-note-headings)
2679 (push '(note . "%t") org-log-note-headings))
2681 (defcustom org-log-into-drawer nil
2682 "Non-nil means insert state change notes and time stamps into a drawer.
2683 When nil, state changes notes will be inserted after the headline and
2684 any scheduling and clock lines, but not inside a drawer.
2686 The value of this variable should be the name of the drawer to use.
2687 LOGBOOK is proposed as the default drawer for this purpose, you can
2688 also set this to a string to define the drawer of your choice.
2690 A value of t is also allowed, representing \"LOGBOOK\".
2692 A value of t or nil can also be set with on a per-file-basis with
2694 #+STARTUP: logdrawer
2695 #+STARTUP: nologdrawer
2697 If this variable is set, `org-log-state-notes-insert-after-drawers'
2698 will be ignored.
2700 You can set the property LOG_INTO_DRAWER to overrule this setting for
2701 a subtree."
2702 :group 'org-todo
2703 :group 'org-progress
2704 :type '(choice
2705 (const :tag "Not into a drawer" nil)
2706 (const :tag "LOGBOOK" t)
2707 (string :tag "Other")))
2709 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2711 (defun org-log-into-drawer ()
2712 "Return the value of `org-log-into-drawer', but let properties overrule.
2713 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2714 used instead of the default value."
2715 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2716 (cond
2717 ((not p) org-log-into-drawer)
2718 ((equal p "nil") nil)
2719 ((equal p "t") "LOGBOOK")
2720 (t p))))
2722 (defcustom org-log-state-notes-insert-after-drawers nil
2723 "Non-nil means insert state change notes after any drawers in entry.
2724 Only the drawers that *immediately* follow the headline and the
2725 deadline/scheduled line are skipped.
2726 When nil, insert notes right after the heading and perhaps the line
2727 with deadline/scheduling if present.
2729 This variable will have no effect if `org-log-into-drawer' is
2730 set."
2731 :group 'org-todo
2732 :group 'org-progress
2733 :type 'boolean)
2735 (defcustom org-log-states-order-reversed t
2736 "Non-nil means the latest state note will be directly after heading.
2737 When nil, the state change notes will be ordered according to time.
2739 This option can also be set with on a per-file-basis with
2741 #+STARTUP: logstatesreversed
2742 #+STARTUP: nologstatesreversed"
2743 :group 'org-todo
2744 :group 'org-progress
2745 :type 'boolean)
2747 (defcustom org-todo-repeat-to-state nil
2748 "The TODO state to which a repeater should return the repeating task.
2749 By default this is the first task in a TODO sequence, or the previous state
2750 in a TODO_TYP set. But you can specify another task here.
2751 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2752 :group 'org-todo
2753 :version "24.1"
2754 :type '(choice (const :tag "Head of sequence" nil)
2755 (string :tag "Specific state")))
2757 (defcustom org-log-repeat 'time
2758 "Non-nil means record moving through the DONE state when triggering repeat.
2759 An auto-repeating task is immediately switched back to TODO when
2760 marked DONE. If you are not logging state changes (by adding \"@\"
2761 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2762 record a closing note, there will be no record of the task moving
2763 through DONE. This variable forces taking a note anyway.
2765 nil Don't force a record
2766 time Record a time stamp
2767 note Prompt for a note and add it with template `org-log-note-headings'
2769 This option can also be set with on a per-file-basis with
2771 #+STARTUP: nologrepeat
2772 #+STARTUP: logrepeat
2773 #+STARTUP: lognoterepeat
2775 You can have local logging settings for a subtree by setting the LOGGING
2776 property to one or more of these keywords."
2777 :group 'org-todo
2778 :group 'org-progress
2779 :type '(choice
2780 (const :tag "Don't force a record" nil)
2781 (const :tag "Force recording the DONE state" time)
2782 (const :tag "Force recording a note with the DONE state" note)))
2785 (defgroup org-priorities nil
2786 "Priorities in Org-mode."
2787 :tag "Org Priorities"
2788 :group 'org-todo)
2790 (defcustom org-enable-priority-commands t
2791 "Non-nil means priority commands are active.
2792 When nil, these commands will be disabled, so that you never accidentally
2793 set a priority."
2794 :group 'org-priorities
2795 :type 'boolean)
2797 (defcustom org-highest-priority ?A
2798 "The highest priority of TODO items. A character like ?A, ?B etc.
2799 Must have a smaller ASCII number than `org-lowest-priority'."
2800 :group 'org-priorities
2801 :type 'character)
2803 (defcustom org-lowest-priority ?C
2804 "The lowest priority of TODO items. A character like ?A, ?B etc.
2805 Must have a larger ASCII number than `org-highest-priority'."
2806 :group 'org-priorities
2807 :type 'character)
2809 (defcustom org-default-priority ?B
2810 "The default priority of TODO items.
2811 This is the priority an item gets if no explicit priority is given.
2812 When starting to cycle on an empty priority the first step in the cycle
2813 depends on `org-priority-start-cycle-with-default'. The resulting first
2814 step priority must not exceed the range from `org-highest-priority' to
2815 `org-lowest-priority' which means that `org-default-priority' has to be
2816 in this range exclusive or inclusive the range boundaries. Else the
2817 first step refuses to set the default and the second will fall back
2818 to (depending on the command used) the highest or lowest priority."
2819 :group 'org-priorities
2820 :type 'character)
2822 (defcustom org-priority-start-cycle-with-default t
2823 "Non-nil means start with default priority when starting to cycle.
2824 When this is nil, the first step in the cycle will be (depending on the
2825 command used) one higher or lower than the default priority.
2826 See also `org-default-priority'."
2827 :group 'org-priorities
2828 :type 'boolean)
2830 (defcustom org-get-priority-function nil
2831 "Function to extract the priority from a string.
2832 The string is normally the headline. If this is nil Org computes the
2833 priority from the priority cookie like [#A] in the headline. It returns
2834 an integer, increasing by 1000 for each priority level.
2835 The user can set a different function here, which should take a string
2836 as an argument and return the numeric priority."
2837 :group 'org-priorities
2838 :version "24.1"
2839 :type '(choice
2840 (const nil)
2841 (function)))
2843 (defgroup org-time nil
2844 "Options concerning time stamps and deadlines in Org-mode."
2845 :tag "Org Time"
2846 :group 'org)
2848 (defcustom org-insert-labeled-timestamps-at-point nil
2849 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2850 When nil, these labeled time stamps are forces into the second line of an
2851 entry, just after the headline. When scheduling from the global TODO list,
2852 the time stamp will always be forced into the second line."
2853 :group 'org-time
2854 :type 'boolean)
2856 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2857 "Formats for `format-time-string' which are used for time stamps.
2858 It is not recommended to change this constant.")
2860 (defcustom org-time-stamp-rounding-minutes '(0 5)
2861 "Number of minutes to round time stamps to.
2862 These are two values, the first applies when first creating a time stamp.
2863 The second applies when changing it with the commands `S-up' and `S-down'.
2864 When changing the time stamp, this means that it will change in steps
2865 of N minutes, as given by the second value.
2867 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2868 numbers should be factors of 60, so for example 5, 10, 15.
2870 When this is larger than 1, you can still force an exact time stamp by using
2871 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2872 and by using a prefix arg to `S-up/down' to specify the exact number
2873 of minutes to shift."
2874 :group 'org-time
2875 :get #'(lambda (var) ; Make sure both elements are there
2876 (if (integerp (default-value var))
2877 (list (default-value var) 5)
2878 (default-value var)))
2879 :type '(list
2880 (integer :tag "when inserting times")
2881 (integer :tag "when modifying times")))
2883 ;; Normalize old customizations of this variable.
2884 (when (integerp org-time-stamp-rounding-minutes)
2885 (setq org-time-stamp-rounding-minutes
2886 (list org-time-stamp-rounding-minutes
2887 org-time-stamp-rounding-minutes)))
2889 (defcustom org-display-custom-times nil
2890 "Non-nil means overlay custom formats over all time stamps.
2891 The formats are defined through the variable `org-time-stamp-custom-formats'.
2892 To turn this on on a per-file basis, insert anywhere in the file:
2893 #+STARTUP: customtime"
2894 :group 'org-time
2895 :set 'set-default
2896 :type 'sexp)
2897 (make-variable-buffer-local 'org-display-custom-times)
2899 (defcustom org-time-stamp-custom-formats
2900 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2901 "Custom formats for time stamps. See `format-time-string' for the syntax.
2902 These are overlaid over the default ISO format if the variable
2903 `org-display-custom-times' is set. Time like %H:%M should be at the
2904 end of the second format. The custom formats are also honored by export
2905 commands, if custom time display is turned on at the time of export."
2906 :group 'org-time
2907 :type 'sexp)
2909 (defun org-time-stamp-format (&optional long inactive)
2910 "Get the right format for a time string."
2911 (let ((f (if long (cdr org-time-stamp-formats)
2912 (car org-time-stamp-formats))))
2913 (if inactive
2914 (concat "[" (substring f 1 -1) "]")
2915 f)))
2917 (defcustom org-time-clocksum-format
2918 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2919 "The format string used when creating CLOCKSUM lines.
2920 This is also used when Org mode generates a time duration.
2922 The value can be a single format string containing two
2923 %-sequences, which will be filled with the number of hours and
2924 minutes in that order.
2926 Alternatively, the value can be a plist associating any of the
2927 keys :years, :months, :weeks, :days, :hours or :minutes with
2928 format strings. The time duration is formatted using only the
2929 time components that are needed and concatenating the results.
2930 If a time unit in absent, it falls back to the next smallest
2931 unit.
2933 The keys :require-years, :require-months, :require-days,
2934 :require-weeks, :require-hours, :require-minutes are also
2935 meaningful. A non-nil value for these keys indicates that the
2936 corresponding time component should always be included, even if
2937 its value is 0.
2940 For example,
2942 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2943 :require-minutes t)
2945 means durations longer than a day will be expressed in days,
2946 hours and minutes, and durations less than a day will always be
2947 expressed in hours and minutes (even for durations less than an
2948 hour).
2950 The value
2952 \(:days \"%dd\" :minutes \"%dm\")
2954 means durations longer than a day will be expressed in days and
2955 minutes, and durations less than a day will be expressed entirely
2956 in minutes (even for durations longer than an hour)."
2957 :group 'org-time
2958 :group 'org-clock
2959 :version "24.4"
2960 :package-version '(Org . "8.0")
2961 :type '(choice (string :tag "Format string")
2962 (set :tag "Plist"
2963 (group :inline t (const :tag "Years" :years)
2964 (string :tag "Format string"))
2965 (group :inline t
2966 (const :tag "Always show years" :require-years)
2967 (const t))
2968 (group :inline t (const :tag "Months" :months)
2969 (string :tag "Format string"))
2970 (group :inline t
2971 (const :tag "Always show months" :require-months)
2972 (const t))
2973 (group :inline t (const :tag "Weeks" :weeks)
2974 (string :tag "Format string"))
2975 (group :inline t
2976 (const :tag "Always show weeks" :require-weeks)
2977 (const t))
2978 (group :inline t (const :tag "Days" :days)
2979 (string :tag "Format string"))
2980 (group :inline t
2981 (const :tag "Always show days" :require-days)
2982 (const t))
2983 (group :inline t (const :tag "Hours" :hours)
2984 (string :tag "Format string"))
2985 (group :inline t
2986 (const :tag "Always show hours" :require-hours)
2987 (const t))
2988 (group :inline t (const :tag "Minutes" :minutes)
2989 (string :tag "Format string"))
2990 (group :inline t
2991 (const :tag "Always show minutes" :require-minutes)
2992 (const t)))))
2994 (defcustom org-time-clocksum-use-fractional nil
2995 "When non-nil, \\[org-clock-display] uses fractional times.
2996 See `org-time-clocksum-format' for more on time clock formats."
2997 :group 'org-time
2998 :group 'org-clock
2999 :version "24.3"
3000 :type 'boolean)
3002 (defcustom org-time-clocksum-use-effort-durations nil
3003 "When non-nil, \\[org-clock-display] uses effort durations.
3004 E.g. by default, one day is considered to be a 8 hours effort,
3005 so a task that has been clocked for 16 hours will be displayed
3006 as during 2 days in the clock display or in the clocktable.
3008 See `org-effort-durations' on how to set effort durations
3009 and `org-time-clocksum-format' for more on time clock formats."
3010 :group 'org-time
3011 :group 'org-clock
3012 :version "24.4"
3013 :package-version '(Org . "8.0")
3014 :type 'boolean)
3016 (defcustom org-time-clocksum-fractional-format "%.2f"
3017 "The format string used when creating CLOCKSUM lines,
3018 or when Org mode generates a time duration, if
3019 `org-time-clocksum-use-fractional' is enabled.
3021 The value can be a single format string containing one
3022 %-sequence, which will be filled with the number of hours as
3023 a float.
3025 Alternatively, the value can be a plist associating any of the
3026 keys :years, :months, :weeks, :days, :hours or :minutes with
3027 a format string. The time duration is formatted using the
3028 largest time unit which gives a non-zero integer part. If all
3029 specified formats have zero integer part, the smallest time unit
3030 is used."
3031 :group 'org-time
3032 :type '(choice (string :tag "Format string")
3033 (set (group :inline t (const :tag "Years" :years)
3034 (string :tag "Format string"))
3035 (group :inline t (const :tag "Months" :months)
3036 (string :tag "Format string"))
3037 (group :inline t (const :tag "Weeks" :weeks)
3038 (string :tag "Format string"))
3039 (group :inline t (const :tag "Days" :days)
3040 (string :tag "Format string"))
3041 (group :inline t (const :tag "Hours" :hours)
3042 (string :tag "Format string"))
3043 (group :inline t (const :tag "Minutes" :minutes)
3044 (string :tag "Format string")))))
3046 (defcustom org-deadline-warning-days 14
3047 "Number of days before expiration during which a deadline becomes active.
3048 This variable governs the display in sparse trees and in the agenda.
3049 When 0 or negative, it means use this number (the absolute value of it)
3050 even if a deadline has a different individual lead time specified.
3052 Custom commands can set this variable in the options section."
3053 :group 'org-time
3054 :group 'org-agenda-daily/weekly
3055 :type 'integer)
3057 (defcustom org-scheduled-delay-days 0
3058 "Number of days before a scheduled item becomes active.
3059 This variable governs the display in sparse trees and in the agenda.
3060 The default value (i.e. 0) means: don't delay scheduled item.
3061 When negative, it means use this number (the absolute value of it)
3062 even if a scheduled item has a different individual delay time
3063 specified.
3065 Custom commands can set this variable in the options section."
3066 :group 'org-time
3067 :group 'org-agenda-daily/weekly
3068 :version "24.4"
3069 :package-version '(Org . "8.0")
3070 :type 'integer)
3072 (defcustom org-read-date-prefer-future t
3073 "Non-nil means assume future for incomplete date input from user.
3074 This affects the following situations:
3075 1. The user gives a month but not a year.
3076 For example, if it is April and you enter \"feb 2\", this will be read
3077 as Feb 2, *next* year. \"May 5\", however, will be this year.
3078 2. The user gives a day, but no month.
3079 For example, if today is the 15th, and you enter \"3\", Org-mode will
3080 read this as the third of *next* month. However, if you enter \"17\",
3081 it will be considered as *this* month.
3083 If you set this variable to the symbol `time', then also the following
3084 will work:
3086 3. If the user gives a time.
3087 If the time is before now, it will be interpreted as tomorrow.
3089 Currently none of this works for ISO week specifications.
3091 When this option is nil, the current day, month and year will always be
3092 used as defaults.
3094 See also `org-agenda-jump-prefer-future'."
3095 :group 'org-time
3096 :type '(choice
3097 (const :tag "Never" nil)
3098 (const :tag "Check month and day" t)
3099 (const :tag "Check month, day, and time" time)))
3101 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3102 "Should the agenda jump command prefer the future for incomplete dates?
3103 The default is to do the same as configured in `org-read-date-prefer-future'.
3104 But you can also set a deviating value here.
3105 This may t or nil, or the symbol `org-read-date-prefer-future'."
3106 :group 'org-agenda
3107 :group 'org-time
3108 :version "24.1"
3109 :type '(choice
3110 (const :tag "Use org-read-date-prefer-future"
3111 org-read-date-prefer-future)
3112 (const :tag "Never" nil)
3113 (const :tag "Always" t)))
3115 (defcustom org-read-date-force-compatible-dates t
3116 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3118 Depending on the system Emacs is running on, certain dates cannot
3119 be represented with the type used internally to represent time.
3120 Dates between 1970-1-1 and 2038-1-1 can always be represented
3121 correctly. Some systems allow for earlier dates, some for later,
3122 some for both. One way to find out it to insert any date into an
3123 Org buffer, putting the cursor on the year and hitting S-up and
3124 S-down to test the range.
3126 When this variable is set to t, the date/time prompt will not let
3127 you specify dates outside the 1970-2037 range, so it is certain that
3128 these dates will work in whatever version of Emacs you are
3129 running, and also that you can move a file from one Emacs implementation
3130 to another. WHenever Org is forcing the year for you, it will display
3131 a message and beep.
3133 When this variable is nil, Org will check if the date is
3134 representable in the specific Emacs implementation you are using.
3135 If not, it will force a year, usually the current year, and beep
3136 to remind you. Currently this setting is not recommended because
3137 the likelihood that you will open your Org files in an Emacs that
3138 has limited date range is not negligible.
3140 A workaround for this problem is to use diary sexp dates for time
3141 stamps outside of this range."
3142 :group 'org-time
3143 :version "24.1"
3144 :type 'boolean)
3146 (defcustom org-read-date-display-live t
3147 "Non-nil means display current interpretation of date prompt live.
3148 This display will be in an overlay, in the minibuffer."
3149 :group 'org-time
3150 :type 'boolean)
3152 (defcustom org-read-date-popup-calendar t
3153 "Non-nil means pop up a calendar when prompting for a date.
3154 In the calendar, the date can be selected with mouse-1. However, the
3155 minibuffer will also be active, and you can simply enter the date as well.
3156 When nil, only the minibuffer will be available."
3157 :group 'org-time
3158 :type 'boolean)
3159 (org-defvaralias 'org-popup-calendar-for-date-prompt
3160 'org-read-date-popup-calendar)
3162 (make-obsolete-variable
3163 'org-read-date-minibuffer-setup-hook
3164 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3165 (defcustom org-read-date-minibuffer-setup-hook nil
3166 "Hook to be used to set up keys for the date/time interface.
3167 Add key definitions to `minibuffer-local-map', which will be a
3168 temporary copy.
3170 WARNING: This option is obsolete, you should use
3171 `org-read-date-minibuffer-local-map' to set up keys."
3172 :group 'org-time
3173 :type 'hook)
3175 (defcustom org-extend-today-until 0
3176 "The hour when your day really ends. Must be an integer.
3177 This has influence for the following applications:
3178 - When switching the agenda to \"today\". It it is still earlier than
3179 the time given here, the day recognized as TODAY is actually yesterday.
3180 - When a date is read from the user and it is still before the time given
3181 here, the current date and time will be assumed to be yesterday, 23:59.
3182 Also, timestamps inserted in capture templates follow this rule.
3184 IMPORTANT: This is a feature whose implementation is and likely will
3185 remain incomplete. Really, it is only here because past midnight seems to
3186 be the favorite working time of John Wiegley :-)"
3187 :group 'org-time
3188 :type 'integer)
3190 (defcustom org-use-effective-time nil
3191 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3192 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3193 \"effective time\" of any timestamps between midnight and 8am will be
3194 23:59 of the previous day."
3195 :group 'org-time
3196 :version "24.1"
3197 :type 'boolean)
3199 (defcustom org-use-last-clock-out-time-as-effective-time nil
3200 "When non-nil, use the last clock out time for `org-todo'.
3201 Note that this option has precedence over the combined use of
3202 `org-use-effective-time' and `org-extend-today-until'."
3203 :group 'org-time
3204 :version "24.4"
3205 :package-version '(Org . "8.0")
3206 :type 'boolean)
3208 (defcustom org-edit-timestamp-down-means-later nil
3209 "Non-nil means S-down will increase the time in a time stamp.
3210 When nil, S-up will increase."
3211 :group 'org-time
3212 :type 'boolean)
3214 (defcustom org-calendar-follow-timestamp-change t
3215 "Non-nil means make the calendar window follow timestamp changes.
3216 When a timestamp is modified and the calendar window is visible, it will be
3217 moved to the new date."
3218 :group 'org-time
3219 :type 'boolean)
3221 (defgroup org-tags nil
3222 "Options concerning tags in Org-mode."
3223 :tag "Org Tags"
3224 :group 'org)
3226 (defcustom org-tag-alist nil
3227 "List of tags allowed in Org-mode files.
3228 When this list is nil, Org-mode will base TAG input on what is already in the
3229 buffer.
3230 The value of this variable is an alist, the car of each entry must be a
3231 keyword as a string, the cdr may be a character that is used to select
3232 that tag through the fast-tag-selection interface.
3233 See the manual for details."
3234 :group 'org-tags
3235 :type '(repeat
3236 (choice
3237 (cons (string :tag "Tag name")
3238 (character :tag "Access char"))
3239 (list :tag "Start radio group"
3240 (const :startgroup)
3241 (option (string :tag "Group description")))
3242 (list :tag "Group tags delimiter"
3243 (const :grouptags))
3244 (list :tag "End radio group"
3245 (const :endgroup)
3246 (option (string :tag "Group description")))
3247 (const :tag "New line" (:newline)))))
3249 (defcustom org-tag-persistent-alist nil
3250 "List of tags that will always appear in all Org-mode files.
3251 This is in addition to any in buffer settings or customizations
3252 of `org-tag-alist'.
3253 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3254 The value of this variable is an alist, the car of each entry must be a
3255 keyword as a string, the cdr may be a character that is used to select
3256 that tag through the fast-tag-selection interface.
3257 See the manual for details.
3258 To disable these tags on a per-file basis, insert anywhere in the file:
3259 #+STARTUP: noptag"
3260 :group 'org-tags
3261 :type '(repeat
3262 (choice
3263 (cons (string :tag "Tag name")
3264 (character :tag "Access char"))
3265 (const :tag "Start radio group" (:startgroup))
3266 (const :tag "Group tags delimiter" (:grouptags))
3267 (const :tag "End radio group" (:endgroup))
3268 (const :tag "New line" (:newline)))))
3270 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3271 "If non-nil, always offer completion for all tags of all agenda files.
3272 Instead of customizing this variable directly, you might want to
3273 set it locally for capture buffers, because there no list of
3274 tags in that file can be created dynamically (there are none).
3276 (add-hook 'org-capture-mode-hook
3277 (lambda ()
3278 (set (make-local-variable
3279 'org-complete-tags-always-offer-all-agenda-tags)
3280 t)))"
3281 :group 'org-tags
3282 :version "24.1"
3283 :type 'boolean)
3285 (defvar org-file-tags nil
3286 "List of tags that can be inherited by all entries in the file.
3287 The tags will be inherited if the variable `org-use-tag-inheritance'
3288 says they should be.
3289 This variable is populated from #+FILETAGS lines.")
3291 (defcustom org-use-fast-tag-selection 'auto
3292 "Non-nil means use fast tag selection scheme.
3293 This is a special interface to select and deselect tags with single keys.
3294 When nil, fast selection is never used.
3295 When the symbol `auto', fast selection is used if and only if selection
3296 characters for tags have been configured, either through the variable
3297 `org-tag-alist' or through a #+TAGS line in the buffer.
3298 When t, fast selection is always used and selection keys are assigned
3299 automatically if necessary."
3300 :group 'org-tags
3301 :type '(choice
3302 (const :tag "Always" t)
3303 (const :tag "Never" nil)
3304 (const :tag "When selection characters are configured" auto)))
3306 (defcustom org-fast-tag-selection-single-key nil
3307 "Non-nil means fast tag selection exits after first change.
3308 When nil, you have to press RET to exit it.
3309 During fast tag selection, you can toggle this flag with `C-c'.
3310 This variable can also have the value `expert'. In this case, the window
3311 displaying the tags menu is not even shown, until you press C-c again."
3312 :group 'org-tags
3313 :type '(choice
3314 (const :tag "No" nil)
3315 (const :tag "Yes" t)
3316 (const :tag "Expert" expert)))
3318 (defvar org-fast-tag-selection-include-todo nil
3319 "Non-nil means fast tags selection interface will also offer TODO states.
3320 This is an undocumented feature, you should not rely on it.")
3322 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3323 "The column to which tags should be indented in a headline.
3324 If this number is positive, it specifies the column. If it is negative,
3325 it means that the tags should be flushright to that column. For example,
3326 -80 works well for a normal 80 character screen.
3327 When 0, place tags directly after headline text, with only one space in
3328 between."
3329 :group 'org-tags
3330 :type 'integer)
3332 (defcustom org-auto-align-tags t
3333 "Non-nil keeps tags aligned when modifying headlines.
3334 Some operations (i.e. demoting) change the length of a headline and
3335 therefore shift the tags around. With this option turned on, after
3336 each such operation the tags are again aligned to `org-tags-column'."
3337 :group 'org-tags
3338 :type 'boolean)
3340 (defcustom org-use-tag-inheritance t
3341 "Non-nil means tags in levels apply also for sublevels.
3342 When nil, only the tags directly given in a specific line apply there.
3343 This may also be a list of tags that should be inherited, or a regexp that
3344 matches tags that should be inherited. Additional control is possible
3345 with the variable `org-tags-exclude-from-inheritance' which gives an
3346 explicit list of tags to be excluded from inheritance, even if the value of
3347 `org-use-tag-inheritance' would select it for inheritance.
3349 If this option is t, a match early-on in a tree can lead to a large
3350 number of matches in the subtree when constructing the agenda or creating
3351 a sparse tree. If you only want to see the first match in a tree during
3352 a search, check out the variable `org-tags-match-list-sublevels'."
3353 :group 'org-tags
3354 :type '(choice
3355 (const :tag "Not" nil)
3356 (const :tag "Always" t)
3357 (repeat :tag "Specific tags" (string :tag "Tag"))
3358 (regexp :tag "Tags matched by regexp")))
3360 (defcustom org-tags-exclude-from-inheritance nil
3361 "List of tags that should never be inherited.
3362 This is a way to exclude a few tags from inheritance. For way to do
3363 the opposite, to actively allow inheritance for selected tags,
3364 see the variable `org-use-tag-inheritance'."
3365 :group 'org-tags
3366 :type '(repeat (string :tag "Tag")))
3368 (defun org-tag-inherit-p (tag)
3369 "Check if TAG is one that should be inherited."
3370 (cond
3371 ((member tag org-tags-exclude-from-inheritance) nil)
3372 ((eq org-use-tag-inheritance t) t)
3373 ((not org-use-tag-inheritance) nil)
3374 ((stringp org-use-tag-inheritance)
3375 (string-match org-use-tag-inheritance tag))
3376 ((listp org-use-tag-inheritance)
3377 (member tag org-use-tag-inheritance))
3378 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3380 (defcustom org-tags-match-list-sublevels t
3381 "Non-nil means list also sublevels of headlines matching a search.
3382 This variable applies to tags/property searches, and also to stuck
3383 projects because this search is based on a tags match as well.
3385 When set to the symbol `indented', sublevels are indented with
3386 leading dots.
3388 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3389 the sublevels of a headline matching a tag search often also match
3390 the same search. Listing all of them can create very long lists.
3391 Setting this variable to nil causes subtrees of a match to be skipped.
3393 This variable is semi-obsolete and probably should always be true. It
3394 is better to limit inheritance to certain tags using the variables
3395 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3396 :group 'org-tags
3397 :type '(choice
3398 (const :tag "No, don't list them" nil)
3399 (const :tag "Yes, do list them" t)
3400 (const :tag "List them, indented with leading dots" indented)))
3402 (defcustom org-tags-sort-function nil
3403 "When set, tags are sorted using this function as a comparator."
3404 :group 'org-tags
3405 :type '(choice
3406 (const :tag "No sorting" nil)
3407 (const :tag "Alphabetical" string<)
3408 (const :tag "Reverse alphabetical" string>)
3409 (function :tag "Custom function" nil)))
3411 (defvar org-tags-history nil
3412 "History of minibuffer reads for tags.")
3413 (defvar org-last-tags-completion-table nil
3414 "The last used completion table for tags.")
3415 (defvar org-after-tags-change-hook nil
3416 "Hook that is run after the tags in a line have changed.")
3418 (defgroup org-properties nil
3419 "Options concerning properties in Org-mode."
3420 :tag "Org Properties"
3421 :group 'org)
3423 (defcustom org-property-format "%-10s %s"
3424 "How property key/value pairs should be formatted by `indent-line'.
3425 When `indent-line' hits a property definition, it will format the line
3426 according to this format, mainly to make sure that the values are
3427 lined-up with respect to each other."
3428 :group 'org-properties
3429 :type 'string)
3431 (defcustom org-properties-postprocess-alist nil
3432 "Alist of properties and functions to adjust inserted values.
3433 Elements of this alist must be of the form
3435 ([string] [function])
3437 where [string] must be a property name and [function] must be a
3438 lambda expression: this lambda expression must take one argument,
3439 the value to adjust, and return the new value as a string.
3441 For example, this element will allow the property \"Remaining\"
3442 to be updated wrt the relation between the \"Effort\" property
3443 and the clock summary:
3445 ((\"Remaining\" (lambda(value)
3446 (let ((clocksum (org-clock-sum-current-item))
3447 (effort (org-duration-string-to-minutes
3448 (org-entry-get (point) \"Effort\"))))
3449 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3450 :group 'org-properties
3451 :version "24.1"
3452 :type '(alist :key-type (string :tag "Property")
3453 :value-type (function :tag "Function")))
3455 (defcustom org-use-property-inheritance nil
3456 "Non-nil means properties apply also for sublevels.
3458 This setting is chiefly used during property searches. Turning it on can
3459 cause significant overhead when doing a search, which is why it is not
3460 on by default.
3462 When nil, only the properties directly given in the current entry count.
3463 When t, every property is inherited. The value may also be a list of
3464 properties that should have inheritance, or a regular expression matching
3465 properties that should be inherited.
3467 However, note that some special properties use inheritance under special
3468 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3469 and the properties ending in \"_ALL\" when they are used as descriptor
3470 for valid values of a property.
3472 Note for programmers:
3473 When querying an entry with `org-entry-get', you can control if inheritance
3474 should be used. By default, `org-entry-get' looks only at the local
3475 properties. You can request inheritance by setting the inherit argument
3476 to t (to force inheritance) or to `selective' (to respect the setting
3477 in this variable)."
3478 :group 'org-properties
3479 :type '(choice
3480 (const :tag "Not" nil)
3481 (const :tag "Always" t)
3482 (repeat :tag "Specific properties" (string :tag "Property"))
3483 (regexp :tag "Properties matched by regexp")))
3485 (defun org-property-inherit-p (property)
3486 "Check if PROPERTY is one that should be inherited."
3487 (cond
3488 ((eq org-use-property-inheritance t) t)
3489 ((not org-use-property-inheritance) nil)
3490 ((stringp org-use-property-inheritance)
3491 (string-match org-use-property-inheritance property))
3492 ((listp org-use-property-inheritance)
3493 (member property org-use-property-inheritance))
3494 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3496 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3497 "The default column format, if no other format has been defined.
3498 This variable can be set on the per-file basis by inserting a line
3500 #+COLUMNS: %25ITEM ....."
3501 :group 'org-properties
3502 :type 'string)
3504 (defcustom org-columns-ellipses ".."
3505 "The ellipses to be used when a field in column view is truncated.
3506 When this is the empty string, as many characters as possible are shown,
3507 but then there will be no visual indication that the field has been truncated.
3508 When this is a string of length N, the last N characters of a truncated
3509 field are replaced by this string. If the column is narrower than the
3510 ellipses string, only part of the ellipses string will be shown."
3511 :group 'org-properties
3512 :type 'string)
3514 (defcustom org-columns-modify-value-for-display-function nil
3515 "Function that modifies values for display in column view.
3516 For example, it can be used to cut out a certain part from a time stamp.
3517 The function must take 2 arguments:
3519 column-title The title of the column (*not* the property name)
3520 value The value that should be modified.
3522 The function should return the value that should be displayed,
3523 or nil if the normal value should be used."
3524 :group 'org-properties
3525 :type '(choice (const nil) (function)))
3527 (defcustom org-effort-property "Effort"
3528 "The property that is being used to keep track of effort estimates.
3529 Effort estimates given in this property need to have the format H:MM."
3530 :group 'org-properties
3531 :group 'org-progress
3532 :type '(string :tag "Property"))
3534 (defconst org-global-properties-fixed
3535 '(("VISIBILITY_ALL" . "folded children content all")
3536 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3537 "List of property/value pairs that can be inherited by any entry.
3539 These are fixed values, for the preset properties. The user variable
3540 that can be used to add to this list is `org-global-properties'.
3542 The entries in this list are cons cells where the car is a property
3543 name and cdr is a string with the value. If the value represents
3544 multiple items like an \"_ALL\" property, separate the items by
3545 spaces.")
3547 (defcustom org-global-properties nil
3548 "List of property/value pairs that can be inherited by any entry.
3550 This list will be combined with the constant `org-global-properties-fixed'.
3552 The entries in this list are cons cells where the car is a property
3553 name and cdr is a string with the value.
3555 You can set buffer-local values for the same purpose in the variable
3556 `org-file-properties' this by adding lines like
3558 #+PROPERTY: NAME VALUE"
3559 :group 'org-properties
3560 :type '(repeat
3561 (cons (string :tag "Property")
3562 (string :tag "Value"))))
3564 (defvar org-file-properties nil
3565 "List of property/value pairs that can be inherited by any entry.
3566 Valid for the current buffer.
3567 This variable is populated from #+PROPERTY lines.")
3568 (make-variable-buffer-local 'org-file-properties)
3570 (defgroup org-agenda nil
3571 "Options concerning agenda views in Org-mode."
3572 :tag "Org Agenda"
3573 :group 'org)
3575 (defvar org-category nil
3576 "Variable used by org files to set a category for agenda display.
3577 Such files should use a file variable to set it, for example
3579 # -*- mode: org; org-category: \"ELisp\"
3581 or contain a special line
3583 #+CATEGORY: ELisp
3585 If the file does not specify a category, then file's base name
3586 is used instead.")
3587 (make-variable-buffer-local 'org-category)
3588 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3590 (defcustom org-agenda-files nil
3591 "The files to be used for agenda display.
3592 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3593 \\[org-remove-file]. You can also use customize to edit the list.
3595 If an entry is a directory, all files in that directory that are matched by
3596 `org-agenda-file-regexp' will be part of the file list.
3598 If the value of the variable is not a list but a single file name, then
3599 the list of agenda files is actually stored and maintained in that file, one
3600 agenda file per line. In this file paths can be given relative to
3601 `org-directory'. Tilde expansion and environment variable substitution
3602 are also made."
3603 :group 'org-agenda
3604 :type '(choice
3605 (repeat :tag "List of files and directories" file)
3606 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3608 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3609 "Regular expression to match files for `org-agenda-files'.
3610 If any element in the list in that variable contains a directory instead
3611 of a normal file, all files in that directory that are matched by this
3612 regular expression will be included."
3613 :group 'org-agenda
3614 :type 'regexp)
3616 (defcustom org-agenda-text-search-extra-files nil
3617 "List of extra files to be searched by text search commands.
3618 These files will be searched in addition to the agenda files by the
3619 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3620 Note that these files will only be searched for text search commands,
3621 not for the other agenda views like todo lists, tag searches or the weekly
3622 agenda. This variable is intended to list notes and possibly archive files
3623 that should also be searched by these two commands.
3624 In fact, if the first element in the list is the symbol `agenda-archives',
3625 then all archive files of all agenda files will be added to the search
3626 scope."
3627 :group 'org-agenda
3628 :type '(set :greedy t
3629 (const :tag "Agenda Archives" agenda-archives)
3630 (repeat :inline t (file))))
3632 (org-defvaralias 'org-agenda-multi-occur-extra-files
3633 'org-agenda-text-search-extra-files)
3635 (defcustom org-agenda-skip-unavailable-files nil
3636 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3637 A nil value means to remove them, after a query, from the list."
3638 :group 'org-agenda
3639 :type 'boolean)
3641 (defcustom org-calendar-to-agenda-key [?c]
3642 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3643 The command `org-calendar-goto-agenda' will be bound to this key. The
3644 default is the character `c' because then `c' can be used to switch back and
3645 forth between agenda and calendar."
3646 :group 'org-agenda
3647 :type 'sexp)
3649 (defcustom org-calendar-insert-diary-entry-key [?i]
3650 "The key to be installed in `calendar-mode-map' for adding diary entries.
3651 This option is irrelevant until `org-agenda-diary-file' has been configured
3652 to point to an Org-mode file. When that is the case, the command
3653 `org-agenda-diary-entry' will be bound to the key given here, by default
3654 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3655 if you want to continue doing this, you need to change this to a different
3656 key."
3657 :group 'org-agenda
3658 :type 'sexp)
3660 (defcustom org-agenda-diary-file 'diary-file
3661 "File to which to add new entries with the `i' key in agenda and calendar.
3662 When this is the symbol `diary-file', the functionality in the Emacs
3663 calendar will be used to add entries to the `diary-file'. But when this
3664 points to a file, `org-agenda-diary-entry' will be used instead."
3665 :group 'org-agenda
3666 :type '(choice
3667 (const :tag "The standard Emacs diary file" diary-file)
3668 (file :tag "Special Org file diary entries")))
3670 (eval-after-load "calendar"
3671 '(progn
3672 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3673 'org-calendar-goto-agenda)
3674 (add-hook 'calendar-mode-hook
3675 (lambda ()
3676 (unless (eq org-agenda-diary-file 'diary-file)
3677 (define-key calendar-mode-map
3678 org-calendar-insert-diary-entry-key
3679 'org-agenda-diary-entry))))))
3681 (defgroup org-latex nil
3682 "Options for embedding LaTeX code into Org-mode."
3683 :tag "Org LaTeX"
3684 :group 'org)
3686 (defcustom org-format-latex-options
3687 '(:foreground default :background default :scale 1.0
3688 :html-foreground "Black" :html-background "Transparent"
3689 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3690 "Options for creating images from LaTeX fragments.
3691 This is a property list with the following properties:
3692 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3693 `default' means use the foreground of the default face.
3694 `auto' means use the foreground from the text face.
3695 :background the background color, or \"Transparent\".
3696 `default' means use the background of the default face.
3697 `auto' means use the background from the text face.
3698 :scale a scaling factor for the size of the images, to get more pixels
3699 :html-foreground, :html-background, :html-scale
3700 the same numbers for HTML export.
3701 :matchers a list indicating which matchers should be used to
3702 find LaTeX fragments. Valid members of this list are:
3703 \"begin\" find environments
3704 \"$1\" find single characters surrounded by $.$
3705 \"$\" find math expressions surrounded by $...$
3706 \"$$\" find math expressions surrounded by $$....$$
3707 \"\\(\" find math expressions surrounded by \\(...\\)
3708 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3709 :group 'org-latex
3710 :type 'plist)
3712 (defcustom org-format-latex-signal-error t
3713 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3714 When nil, just push out a message."
3715 :group 'org-latex
3716 :version "24.1"
3717 :type 'boolean)
3719 (defcustom org-latex-to-mathml-jar-file nil
3720 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3721 Use this to specify additional executable file say a jar file.
3723 When using MathToWeb as the converter, specify the full-path to
3724 your mathtoweb.jar file."
3725 :group 'org-latex
3726 :version "24.1"
3727 :type '(choice
3728 (const :tag "None" nil)
3729 (file :tag "JAR file" :must-match t)))
3731 (defcustom org-latex-to-mathml-convert-command nil
3732 "Command to convert LaTeX fragments to MathML.
3733 Replace format-specifiers in the command as noted below and use
3734 `shell-command' to convert LaTeX to MathML.
3735 %j: Executable file in fully expanded form as specified by
3736 `org-latex-to-mathml-jar-file'.
3737 %I: Input LaTeX file in fully expanded form
3738 %o: Output MathML file
3739 This command is used by `org-create-math-formula'.
3741 When using MathToWeb as the converter, set this to
3742 \"java -jar %j -unicode -force -df %o %I\"."
3743 :group 'org-latex
3744 :version "24.1"
3745 :type '(choice
3746 (const :tag "None" nil)
3747 (string :tag "\nShell command")))
3749 (defcustom org-latex-create-formula-image-program 'dvipng
3750 "Program to convert LaTeX fragments with.
3752 dvipng Process the LaTeX fragments to dvi file, then convert
3753 dvi files to png files using dvipng.
3754 This will also include processing of non-math environments.
3755 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3756 to convert pdf files to png files"
3757 :group 'org-latex
3758 :version "24.1"
3759 :type '(choice
3760 (const :tag "dvipng" dvipng)
3761 (const :tag "imagemagick" imagemagick)))
3763 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3764 "Path to store latex preview images.
3765 A relative path here creates many directories relative to the
3766 processed org files paths. An absolute path puts all preview
3767 images at the same place."
3768 :group 'org-latex
3769 :version "24.3"
3770 :type 'string)
3772 (defun org-format-latex-mathml-available-p ()
3773 "Return t if `org-latex-to-mathml-convert-command' is usable."
3774 (save-match-data
3775 (when (and (boundp 'org-latex-to-mathml-convert-command)
3776 org-latex-to-mathml-convert-command)
3777 (let ((executable (car (split-string
3778 org-latex-to-mathml-convert-command))))
3779 (when (executable-find executable)
3780 (if (string-match
3781 "%j" org-latex-to-mathml-convert-command)
3782 (file-readable-p org-latex-to-mathml-jar-file)
3783 t))))))
3785 (defcustom org-format-latex-header "\\documentclass{article}
3786 \\usepackage[usenames]{color}
3787 \[PACKAGES]
3788 \[DEFAULT-PACKAGES]
3789 \\pagestyle{empty} % do not remove
3790 % The settings below are copied from fullpage.sty
3791 \\setlength{\\textwidth}{\\paperwidth}
3792 \\addtolength{\\textwidth}{-3cm}
3793 \\setlength{\\oddsidemargin}{1.5cm}
3794 \\addtolength{\\oddsidemargin}{-2.54cm}
3795 \\setlength{\\evensidemargin}{\\oddsidemargin}
3796 \\setlength{\\textheight}{\\paperheight}
3797 \\addtolength{\\textheight}{-\\headheight}
3798 \\addtolength{\\textheight}{-\\headsep}
3799 \\addtolength{\\textheight}{-\\footskip}
3800 \\addtolength{\\textheight}{-3cm}
3801 \\setlength{\\topmargin}{1.5cm}
3802 \\addtolength{\\topmargin}{-2.54cm}"
3803 "The document header used for processing LaTeX fragments.
3804 It is imperative that this header make sure that no page number
3805 appears on the page. The package defined in the variables
3806 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3807 will either replace the placeholder \"[PACKAGES]\" in this
3808 header, or they will be appended."
3809 :group 'org-latex
3810 :type 'string)
3812 (defun org-set-packages-alist (var val)
3813 "Set the packages alist and make sure it has 3 elements per entry."
3814 (set var (mapcar (lambda (x)
3815 (if (and (consp x) (= (length x) 2))
3816 (list (car x) (nth 1 x) t)
3818 val)))
3820 (defun org-get-packages-alist (var)
3821 "Get the packages alist and make sure it has 3 elements per entry."
3822 (mapcar (lambda (x)
3823 (if (and (consp x) (= (length x) 2))
3824 (list (car x) (nth 1 x) t)
3826 (default-value var)))
3828 (defcustom org-latex-default-packages-alist
3829 '(("AUTO" "inputenc" t)
3830 ("T1" "fontenc" t)
3831 ("" "fixltx2e" nil)
3832 ("" "graphicx" t)
3833 ("" "longtable" nil)
3834 ("" "float" nil)
3835 ("" "wrapfig" nil)
3836 ("" "rotating" nil)
3837 ("normalem" "ulem" t)
3838 ("" "amsmath" t)
3839 ("" "textcomp" t)
3840 ("" "marvosym" t)
3841 ("" "wasysym" t)
3842 ("" "amssymb" t)
3843 ("" "hyperref" nil)
3844 "\\tolerance=1000")
3845 "Alist of default packages to be inserted in the header.
3847 Change this only if one of the packages here causes an
3848 incompatibility with another package you are using.
3850 The packages in this list are needed by one part or another of
3851 Org mode to function properly:
3853 - inputenc, fontenc: for basic font and character selection
3854 - fixltx2e: Important patches of LaTeX itself
3855 - graphicx: for including images
3856 - longtable: For multipage tables
3857 - float, wrapfig: for figure placement
3858 - rotating: for sideways figures and tables
3859 - ulem: for underline and strike-through
3860 - amsmath: for subscript and superscript and math environments
3861 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3862 for interpreting the entities in `org-entities'. You can skip
3863 some of these packages if you don't use any of their symbols.
3864 - hyperref: for cross references
3866 Therefore you should not modify this variable unless you know
3867 what you are doing. The one reason to change it anyway is that
3868 you might be loading some other package that conflicts with one
3869 of the default packages. Each cell is of the format
3870 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3871 the package also needs to be included when compiling LaTeX
3872 snippets into images for inclusion into non-LaTeX output."
3873 :group 'org-latex
3874 :group 'org-export-latex
3875 :set 'org-set-packages-alist
3876 :get 'org-get-packages-alist
3877 :version "24.1"
3878 :type '(repeat
3879 (choice
3880 (list :tag "options/package pair"
3881 (string :tag "options")
3882 (string :tag "package")
3883 (boolean :tag "Snippet"))
3884 (string :tag "A line of LaTeX"))))
3886 (defcustom org-latex-packages-alist nil
3887 "Alist of packages to be inserted in every LaTeX header.
3889 These will be inserted after `org-latex-default-packages-alist'.
3890 Each cell is of the format:
3892 \(\"options\" \"package\" snippet-flag)
3894 SNIPPET-FLAG, when t, indicates that this package is also needed
3895 when turning LaTeX snippets into images for inclusion into
3896 non-LaTeX output.
3898 Make sure that you only list packages here which:
3900 - you want in every file
3901 - do not conflict with the setup in `org-format-latex-header'.
3902 - do not conflict with the default packages in
3903 `org-latex-default-packages-alist'."
3904 :group 'org-latex
3905 :group 'org-export-latex
3906 :set 'org-set-packages-alist
3907 :get 'org-get-packages-alist
3908 :type '(repeat
3909 (choice
3910 (list :tag "options/package pair"
3911 (string :tag "options")
3912 (string :tag "package")
3913 (boolean :tag "Snippet"))
3914 (string :tag "A line of LaTeX"))))
3916 (defgroup org-appearance nil
3917 "Settings for Org-mode appearance."
3918 :tag "Org Appearance"
3919 :group 'org)
3921 (defcustom org-level-color-stars-only nil
3922 "Non-nil means fontify only the stars in each headline.
3923 When nil, the entire headline is fontified.
3924 Changing it requires restart of `font-lock-mode' to become effective
3925 also in regions already fontified."
3926 :group 'org-appearance
3927 :type 'boolean)
3929 (defcustom org-hide-leading-stars nil
3930 "Non-nil means hide the first N-1 stars in a headline.
3931 This works by using the face `org-hide' for these stars. This
3932 face is white for a light background, and black for a dark
3933 background. You may have to customize the face `org-hide' to
3934 make this work.
3935 Changing it requires restart of `font-lock-mode' to become effective
3936 also in regions already fontified.
3937 You may also set this on a per-file basis by adding one of the following
3938 lines to the buffer:
3940 #+STARTUP: hidestars
3941 #+STARTUP: showstars"
3942 :group 'org-appearance
3943 :type 'boolean)
3945 (defcustom org-hidden-keywords nil
3946 "List of symbols corresponding to keywords to be hidden the org buffer.
3947 For example, a value '(title) for this list will make the document's title
3948 appear in the buffer without the initial #+TITLE: keyword."
3949 :group 'org-appearance
3950 :version "24.1"
3951 :type '(set (const :tag "#+AUTHOR" author)
3952 (const :tag "#+DATE" date)
3953 (const :tag "#+EMAIL" email)
3954 (const :tag "#+TITLE" title)))
3956 (defcustom org-custom-properties nil
3957 "List of properties (as strings) with a special meaning.
3958 The default use of these custom properties is to let the user
3959 hide them with `org-toggle-custom-properties-visibility'."
3960 :group 'org-properties
3961 :group 'org-appearance
3962 :version "24.3"
3963 :type '(repeat (string :tag "Property Name")))
3965 (defcustom org-fontify-done-headline nil
3966 "Non-nil means change the face of a headline if it is marked DONE.
3967 Normally, only the TODO/DONE keyword indicates the state of a headline.
3968 When this is non-nil, the headline after the keyword is set to the
3969 `org-headline-done' as an additional indication."
3970 :group 'org-appearance
3971 :type 'boolean)
3973 (defcustom org-fontify-emphasized-text t
3974 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3975 Changing this variable requires a restart of Emacs to take effect."
3976 :group 'org-appearance
3977 :type 'boolean)
3979 (defcustom org-fontify-whole-heading-line nil
3980 "Non-nil means fontify the whole line for headings.
3981 This is useful when setting a background color for the
3982 org-level-* faces."
3983 :group 'org-appearance
3984 :type 'boolean)
3986 (defcustom org-highlight-latex-and-related nil
3987 "Non-nil means highlight LaTeX related syntax in the buffer.
3988 When non nil, the value should be a list containing any of the
3989 following symbols:
3990 `latex' Highlight LaTeX snippets and environments.
3991 `script' Highlight subscript and superscript.
3992 `entities' Highlight entities."
3993 :group 'org-appearance
3994 :version "24.4"
3995 :package-version '(Org . "8.0")
3996 :type '(choice
3997 (const :tag "No highlighting" nil)
3998 (set :greedy t :tag "Highlight"
3999 (const :tag "LaTeX snippets and environments" latex)
4000 (const :tag "Subscript and superscript" script)
4001 (const :tag "Entities" entities))))
4003 (defcustom org-hide-emphasis-markers nil
4004 "Non-nil mean font-lock should hide the emphasis marker characters."
4005 :group 'org-appearance
4006 :type 'boolean)
4008 (defcustom org-pretty-entities nil
4009 "Non-nil means show entities as UTF8 characters.
4010 When nil, the \\name form remains in the buffer."
4011 :group 'org-appearance
4012 :version "24.1"
4013 :type 'boolean)
4015 (defcustom org-pretty-entities-include-sub-superscripts t
4016 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4017 :group 'org-appearance
4018 :version "24.1"
4019 :type 'boolean)
4021 (defvar org-emph-re nil
4022 "Regular expression for matching emphasis.
4023 After a match, the match groups contain these elements:
4024 0 The match of the full regular expression, including the characters
4025 before and after the proper match
4026 1 The character before the proper match, or empty at beginning of line
4027 2 The proper match, including the leading and trailing markers
4028 3 The leading marker like * or /, indicating the type of highlighting
4029 4 The text between the emphasis markers, not including the markers
4030 5 The character after the match, empty at the end of a line")
4031 (defvar org-verbatim-re nil
4032 "Regular expression for matching verbatim text.")
4033 (defvar org-emphasis-regexp-components) ; defined just below
4034 (defvar org-emphasis-alist) ; defined just below
4035 (defun org-set-emph-re (var val)
4036 "Set variable and compute the emphasis regular expression."
4037 (set var val)
4038 (when (and (boundp 'org-emphasis-alist)
4039 (boundp 'org-emphasis-regexp-components)
4040 org-emphasis-alist org-emphasis-regexp-components)
4041 (let* ((e org-emphasis-regexp-components)
4042 (pre (car e))
4043 (post (nth 1 e))
4044 (border (nth 2 e))
4045 (body (nth 3 e))
4046 (nl (nth 4 e))
4047 (body1 (concat body "*?"))
4048 (markers (mapconcat 'car org-emphasis-alist ""))
4049 (vmarkers (mapconcat
4050 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4051 org-emphasis-alist "")))
4052 ;; make sure special characters appear at the right position in the class
4053 (if (string-match "\\^" markers)
4054 (setq markers (concat (replace-match "" t t markers) "^")))
4055 (if (string-match "-" markers)
4056 (setq markers (concat (replace-match "" t t markers) "-")))
4057 (if (string-match "\\^" vmarkers)
4058 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4059 (if (string-match "-" vmarkers)
4060 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4061 (if (> nl 0)
4062 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4063 (int-to-string nl) "\\}")))
4064 ;; Make the regexp
4065 (setq org-emph-re
4066 (concat "\\([" pre "]\\|^\\)"
4067 "\\("
4068 "\\([" markers "]\\)"
4069 "\\("
4070 "[^" border "]\\|"
4071 "[^" border "]"
4072 body1
4073 "[^" border "]"
4074 "\\)"
4075 "\\3\\)"
4076 "\\([" post "]\\|$\\)"))
4077 (setq org-verbatim-re
4078 (concat "\\([" pre "]\\|^\\)"
4079 "\\("
4080 "\\([" vmarkers "]\\)"
4081 "\\("
4082 "[^" border "]\\|"
4083 "[^" border "]"
4084 body1
4085 "[^" border "]"
4086 "\\)"
4087 "\\3\\)"
4088 "\\([" post "]\\|$\\)")))))
4090 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4091 ;; set this option proved cumbersome. See this message/thread:
4092 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4093 (defvar org-emphasis-regexp-components
4094 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4095 "Components used to build the regular expression for emphasis.
4096 This is a list with five entries. Terminology: In an emphasis string
4097 like \" *strong word* \", we call the initial space PREMATCH, the final
4098 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4099 and \"trong wor\" is the body. The different components in this variable
4100 specify what is allowed/forbidden in each part:
4102 pre Chars allowed as prematch. Beginning of line will be allowed too.
4103 post Chars allowed as postmatch. End of line will be allowed too.
4104 border The chars *forbidden* as border characters.
4105 body-regexp A regexp like \".\" to match a body character. Don't use
4106 non-shy groups here, and don't allow newline here.
4107 newline The maximum number of newlines allowed in an emphasis exp.
4109 You need to reload Org or to restart Emacs after customizing this.")
4111 (defcustom org-emphasis-alist
4112 `(("*" bold)
4113 ("/" italic)
4114 ("_" underline)
4115 ("=" org-code verbatim)
4116 ("~" org-verbatim verbatim)
4117 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4118 "Alist of characters and faces to emphasize text.
4119 Text starting and ending with a special character will be emphasized,
4120 for example *bold*, _underlined_ and /italic/. This variable sets the
4121 marker characters and the face to be used by font-lock for highlighting
4122 in Org-mode Emacs buffers.
4124 You need to reload Org or to restart Emacs after customizing this."
4125 :group 'org-appearance
4126 :set 'org-set-emph-re
4127 :version "24.4"
4128 :package-version '(Org . "8.0")
4129 :type '(repeat
4130 (list
4131 (string :tag "Marker character")
4132 (choice
4133 (face :tag "Font-lock-face")
4134 (plist :tag "Face property list"))
4135 (option (const verbatim)))))
4137 (defvar org-protecting-blocks
4138 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4139 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4140 This is needed for font-lock setup.")
4142 ;;; Miscellaneous options
4144 (defgroup org-completion nil
4145 "Completion in Org-mode."
4146 :tag "Org Completion"
4147 :group 'org)
4149 (defcustom org-completion-use-ido nil
4150 "Non-nil means use ido completion wherever possible.
4151 Note that `ido-mode' must be active for this variable to be relevant.
4152 If you decide to turn this variable on, you might well want to turn off
4153 `org-outline-path-complete-in-steps'.
4154 See also `org-completion-use-iswitchb'."
4155 :group 'org-completion
4156 :type 'boolean)
4158 (defcustom org-completion-use-iswitchb nil
4159 "Non-nil means use iswitchb completion wherever possible.
4160 Note that `iswitchb-mode' must be active for this variable to be relevant.
4161 If you decide to turn this variable on, you might well want to turn off
4162 `org-outline-path-complete-in-steps'.
4163 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4164 :group 'org-completion
4165 :type 'boolean)
4167 (defcustom org-completion-fallback-command 'hippie-expand
4168 "The expansion command called by \\[pcomplete] in normal context.
4169 Normal means, no org-mode-specific context."
4170 :group 'org-completion
4171 :type 'function)
4173 ;;; Functions and variables from their packages
4174 ;; Declared here to avoid compiler warnings
4176 ;; XEmacs only
4177 (defvar outline-mode-menu-heading)
4178 (defvar outline-mode-menu-show)
4179 (defvar outline-mode-menu-hide)
4180 (defvar zmacs-regions) ; XEmacs regions
4182 ;; Emacs only
4183 (defvar mark-active)
4185 ;; Various packages
4186 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4187 (declare-function calendar-forward-day "cal-move" (arg))
4188 (declare-function calendar-goto-date "cal-move" (date))
4189 (declare-function calendar-goto-today "cal-move" ())
4190 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4191 (defvar calc-embedded-close-formula)
4192 (defvar calc-embedded-open-formula)
4193 (declare-function cdlatex-tab "ext:cdlatex" ())
4194 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4195 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4196 (defvar font-lock-unfontify-region-function)
4197 (declare-function iswitchb-read-buffer "iswitchb"
4198 (prompt &optional default require-match start matches-set))
4199 (defvar iswitchb-temp-buflist)
4200 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4201 (defvar org-agenda-tags-todo-honor-ignore-options)
4202 (declare-function org-agenda-skip "org-agenda" ())
4203 (declare-function
4204 org-agenda-format-item "org-agenda"
4205 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4206 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4207 (declare-function org-agenda-change-all-lines "org-agenda"
4208 (newhead hdmarker &optional fixface just-this))
4209 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4210 (declare-function org-agenda-maybe-redo "org-agenda" ())
4211 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4212 (beg end))
4213 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4214 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4215 "org-agenda" (&optional end))
4216 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4217 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4218 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4219 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4220 (declare-function org-indent-mode "org-indent" (&optional arg))
4221 (declare-function parse-time-string "parse-time" (string))
4222 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4223 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4224 (defvar remember-data-file)
4225 (defvar texmathp-why)
4226 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4227 (declare-function table--at-cell-p "table" (position &optional object at-column))
4229 (defvar org-latex-regexps)
4231 ;;; Autoload and prepare some org modules
4233 ;; Some table stuff that needs to be defined here, because it is used
4234 ;; by the functions setting up org-mode or checking for table context.
4236 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4237 "Detect an org-type or table-type table.")
4238 (defconst org-table-line-regexp "^[ \t]*|"
4239 "Detect an org-type table line.")
4240 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4241 "Detect an org-type table line.")
4242 (defconst org-table-hline-regexp "^[ \t]*|-"
4243 "Detect an org-type table hline.")
4244 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4245 "Detect a table-type table hline.")
4246 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4247 "Detect the first line outside a table when searching from within it.
4248 This works for both table types.")
4250 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4251 "Detect a #+TBLFM line.")
4253 ;;;###autoload
4254 (defun turn-on-orgtbl ()
4255 "Unconditionally turn on `orgtbl-mode'."
4256 (require 'org-table)
4257 (orgtbl-mode 1))
4259 (defun org-at-table-p (&optional table-type)
4260 "Return t if the cursor is inside an org-type table.
4261 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4262 (if org-enable-table-editor
4263 (save-excursion
4264 (beginning-of-line 1)
4265 (looking-at (if table-type org-table-any-line-regexp
4266 org-table-line-regexp)))
4267 nil))
4268 (defsubst org-table-p () (org-at-table-p))
4270 (defun org-at-table.el-p ()
4271 "Return t if and only if we are at a table.el table."
4272 (and (org-at-table-p 'any)
4273 (save-excursion
4274 (goto-char (org-table-begin 'any))
4275 (looking-at org-table1-hline-regexp))))
4277 (defun org-table-recognize-table.el ()
4278 "If there is a table.el table nearby, recognize it and move into it."
4279 (if org-table-tab-recognizes-table.el
4280 (if (org-at-table.el-p)
4281 (progn
4282 (beginning-of-line 1)
4283 (if (looking-at org-table-dataline-regexp)
4285 (if (looking-at org-table1-hline-regexp)
4286 (progn
4287 (beginning-of-line 2)
4288 (if (looking-at org-table-any-border-regexp)
4289 (beginning-of-line -1)))))
4290 (if (re-search-forward "|" (org-table-end t) t)
4291 (progn
4292 (require 'table)
4293 (if (table--at-cell-p (point))
4295 (message "recognizing table.el table...")
4296 (table-recognize-table)
4297 (message "recognizing table.el table...done")))
4298 (error "This should not happen"))
4300 nil)
4301 nil))
4303 (defun org-at-table-hline-p ()
4304 "Return t if the cursor is inside a hline in a table."
4305 (if org-enable-table-editor
4306 (save-excursion
4307 (beginning-of-line 1)
4308 (looking-at org-table-hline-regexp))
4309 nil))
4311 (defun org-table-map-tables (function &optional quietly)
4312 "Apply FUNCTION to the start of all tables in the buffer."
4313 (save-excursion
4314 (save-restriction
4315 (widen)
4316 (goto-char (point-min))
4317 (while (re-search-forward org-table-any-line-regexp nil t)
4318 (unless quietly
4319 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4320 (beginning-of-line 1)
4321 (when (and (looking-at org-table-line-regexp)
4322 ;; Exclude tables in src/example/verbatim/clocktable blocks
4323 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4324 (save-excursion (funcall function))
4325 (or (looking-at org-table-line-regexp)
4326 (forward-char 1)))
4327 (re-search-forward org-table-any-border-regexp nil 1))))
4328 (unless quietly (message "Mapping tables: done")))
4330 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4331 (declare-function org-clock-update-mode-line "org-clock" ())
4332 (declare-function org-resolve-clocks "org-clock"
4333 (&optional also-non-dangling-p prompt last-valid))
4335 (defun org-at-TBLFM-p (&optional pos)
4336 "Return t when point (or POS) is in #+TBLFM line."
4337 (save-excursion
4338 (let ((pos pos)))
4339 (goto-char (or pos (point)))
4340 (beginning-of-line 1)
4341 (looking-at org-TBLFM-regexp)))
4343 (defvar org-clock-start-time)
4344 (defvar org-clock-marker (make-marker)
4345 "Marker recording the last clock-in.")
4346 (defvar org-clock-hd-marker (make-marker)
4347 "Marker recording the last clock-in, but the headline position.")
4348 (defvar org-clock-heading ""
4349 "The heading of the current clock entry.")
4350 (defun org-clock-is-active ()
4351 "Return the buffer where the clock is currently running.
4352 Return nil if no clock is running."
4353 (marker-buffer org-clock-marker))
4355 (defun org-check-running-clock ()
4356 "Check if the current buffer contains the running clock.
4357 If yes, offer to stop it and to save the buffer with the changes."
4358 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4359 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4360 (buffer-name))))
4361 (org-clock-out)
4362 (when (y-or-n-p "Save changed buffer?")
4363 (save-buffer))))
4365 (defun org-clocktable-try-shift (dir n)
4366 "Check if this line starts a clock table, if yes, shift the time block."
4367 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4368 (org-clocktable-shift dir n)))
4370 ;;;###autoload
4371 (defun org-clock-persistence-insinuate ()
4372 "Set up hooks for clock persistence."
4373 (require 'org-clock)
4374 (add-hook 'org-mode-hook 'org-clock-load)
4375 (add-hook 'kill-emacs-hook 'org-clock-save))
4377 ;; Define the variable already here, to make sure we have it.
4378 (defvar org-indent-mode nil
4379 "Non-nil if Org-Indent mode is enabled.
4380 Use the command `org-indent-mode' to change this variable.")
4382 ;; Autoload archiving code
4383 ;; The stuff that is needed for cycling and tags has to be defined here.
4385 (defgroup org-archive nil
4386 "Options concerning archiving in Org-mode."
4387 :tag "Org Archive"
4388 :group 'org-structure)
4390 (defcustom org-archive-location "%s_archive::"
4391 "The location where subtrees should be archived.
4393 The value of this variable is a string, consisting of two parts,
4394 separated by a double-colon. The first part is a filename and
4395 the second part is a headline.
4397 When the filename is omitted, archiving happens in the same file.
4398 %s in the filename will be replaced by the current file
4399 name (without the directory part). Archiving to a different file
4400 is useful to keep archived entries from contributing to the
4401 Org-mode Agenda.
4403 The archived entries will be filed as subtrees of the specified
4404 headline. When the headline is omitted, the subtrees are simply
4405 filed away at the end of the file, as top-level entries. Also in
4406 the heading you can use %s to represent the file name, this can be
4407 useful when using the same archive for a number of different files.
4409 Here are a few examples:
4410 \"%s_archive::\"
4411 If the current file is Projects.org, archive in file
4412 Projects.org_archive, as top-level trees. This is the default.
4414 \"::* Archived Tasks\"
4415 Archive in the current file, under the top-level headline
4416 \"* Archived Tasks\".
4418 \"~/org/archive.org::\"
4419 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4421 \"~/org/archive.org::* From %s\"
4422 Archive in file ~/org/archive.org (absolute path), under headlines
4423 \"From FILENAME\" where file name is the current file name.
4425 \"~/org/datetree.org::datetree/* Finished Tasks\"
4426 The \"datetree/\" string is special, signifying to archive
4427 items to the datetree. Items are placed in either the CLOSED
4428 date of the item, or the current date if there is no CLOSED date.
4429 The heading will be a subentry to the current date. There doesn't
4430 need to be a heading, but there always needs to be a slash after
4431 datetree. For example, to store archived items directly in the
4432 datetree, use \"~/org/datetree.org::datetree/\".
4434 \"basement::** Finished Tasks\"
4435 Archive in file ./basement (relative path), as level 3 trees
4436 below the level 2 heading \"** Finished Tasks\".
4438 You may set this option on a per-file basis by adding to the buffer a
4439 line like
4441 #+ARCHIVE: basement::** Finished Tasks
4443 You may also define it locally for a subtree by setting an ARCHIVE property
4444 in the entry. If such a property is found in an entry, or anywhere up
4445 the hierarchy, it will be used."
4446 :group 'org-archive
4447 :type 'string)
4449 (defcustom org-archive-tag "ARCHIVE"
4450 "The tag that marks a subtree as archived.
4451 An archived subtree does not open during visibility cycling, and does
4452 not contribute to the agenda listings.
4453 After changing this, font-lock must be restarted in the relevant buffers to
4454 get the proper fontification."
4455 :group 'org-archive
4456 :group 'org-keywords
4457 :type 'string)
4459 (defcustom org-agenda-skip-archived-trees t
4460 "Non-nil means the agenda will skip any items located in archived trees.
4461 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4462 variable is no longer recommended, you should leave it at the value t.
4463 Instead, use the key `v' to cycle the archives-mode in the agenda."
4464 :group 'org-archive
4465 :group 'org-agenda-skip
4466 :type 'boolean)
4468 (defcustom org-columns-skip-archived-trees t
4469 "Non-nil means ignore archived trees when creating column view."
4470 :group 'org-archive
4471 :group 'org-properties
4472 :type 'boolean)
4474 (defcustom org-cycle-open-archived-trees nil
4475 "Non-nil means `org-cycle' will open archived trees.
4476 An archived tree is a tree marked with the tag ARCHIVE.
4477 When nil, archived trees will stay folded. You can still open them with
4478 normal outline commands like `show-all', but not with the cycling commands."
4479 :group 'org-archive
4480 :group 'org-cycle
4481 :type 'boolean)
4483 (defcustom org-sparse-tree-open-archived-trees nil
4484 "Non-nil means sparse tree construction shows matches in archived trees.
4485 When nil, matches in these trees are highlighted, but the trees are kept in
4486 collapsed state."
4487 :group 'org-archive
4488 :group 'org-sparse-trees
4489 :type 'boolean)
4491 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4492 "The default date type when building a sparse tree.
4493 When this is nil, a date is a scheduled or a deadline timestamp.
4494 Otherwise, these types are allowed:
4496 all: all timestamps
4497 active: only active timestamps (<...>)
4498 inactive: only inactive timestamps (<...)
4499 scheduled: only scheduled timestamps
4500 deadline: only deadline timestamps"
4501 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4502 (const :tag "All timestamps" all)
4503 (const :tag "Only active timestamps" active)
4504 (const :tag "Only inactive timestamps" inactive)
4505 (const :tag "Only scheduled timestamps" scheduled)
4506 (const :tag "Only deadline timestamps" deadline)
4507 (const :tag "Only closed timestamps" closed))
4508 :version "24.3"
4509 :group 'org-sparse-trees)
4511 (defun org-cycle-hide-archived-subtrees (state)
4512 "Re-hide all archived subtrees after a visibility state change."
4513 (when (and (not org-cycle-open-archived-trees)
4514 (not (memq state '(overview folded))))
4515 (save-excursion
4516 (let* ((globalp (memq state '(contents all)))
4517 (beg (if globalp (point-min) (point)))
4518 (end (if globalp (point-max) (org-end-of-subtree t))))
4519 (org-hide-archived-subtrees beg end)
4520 (goto-char beg)
4521 (if (looking-at (concat ".*:" org-archive-tag ":"))
4522 (message "%s" (substitute-command-keys
4523 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4525 (defun org-force-cycle-archived ()
4526 "Cycle subtree even if it is archived."
4527 (interactive)
4528 (setq this-command 'org-cycle)
4529 (let ((org-cycle-open-archived-trees t))
4530 (call-interactively 'org-cycle)))
4532 (defun org-hide-archived-subtrees (beg end)
4533 "Re-hide all archived subtrees after a visibility state change."
4534 (save-excursion
4535 (let* ((re (concat ":" org-archive-tag ":")))
4536 (goto-char beg)
4537 (while (re-search-forward re end t)
4538 (when (org-at-heading-p)
4539 (org-flag-subtree t)
4540 (org-end-of-subtree t))))))
4542 (declare-function outline-end-of-heading "outline" ())
4543 (declare-function outline-flag-region "outline" (from to flag))
4544 (defun org-flag-subtree (flag)
4545 (save-excursion
4546 (org-back-to-heading t)
4547 (outline-end-of-heading)
4548 (outline-flag-region (point)
4549 (progn (org-end-of-subtree t) (point))
4550 flag)))
4552 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4554 ;; Declare Column View Code
4556 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4557 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4558 (declare-function org-columns-compute "org-colview" (property))
4560 ;; Declare ID code
4562 (declare-function org-id-store-link "org-id")
4563 (declare-function org-id-locations-load "org-id")
4564 (declare-function org-id-locations-save "org-id")
4565 (defvar org-id-track-globally)
4567 ;;; Variables for pre-computed regular expressions, all buffer local
4569 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4570 "Matches first line of a hidden block.")
4571 (make-variable-buffer-local 'org-drawer-regexp)
4572 (defvar org-todo-regexp nil
4573 "Matches any of the TODO state keywords.")
4574 (make-variable-buffer-local 'org-todo-regexp)
4575 (defvar org-not-done-regexp nil
4576 "Matches any of the TODO state keywords except the last one.")
4577 (make-variable-buffer-local 'org-not-done-regexp)
4578 (defvar org-not-done-heading-regexp nil
4579 "Matches a TODO headline that is not done.")
4580 (make-variable-buffer-local 'org-not-done-regexp)
4581 (defvar org-todo-line-regexp nil
4582 "Matches a headline and puts TODO state into group 2 if present.")
4583 (make-variable-buffer-local 'org-todo-line-regexp)
4584 (defvar org-complex-heading-regexp nil
4585 "Matches a headline and puts everything into groups:
4586 group 1: the stars
4587 group 2: The todo keyword, maybe
4588 group 3: Priority cookie
4589 group 4: True headline
4590 group 5: Tags")
4591 (make-variable-buffer-local 'org-complex-heading-regexp)
4592 (defvar org-complex-heading-regexp-format nil
4593 "Printf format to make regexp to match an exact headline.
4594 This regexp will match the headline of any node which has the
4595 exact headline text that is put into the format, but may have any
4596 TODO state, priority and tags.")
4597 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4598 (defvar org-todo-line-tags-regexp nil
4599 "Matches a headline and puts TODO state into group 2 if present.
4600 Also put tags into group 4 if tags are present.")
4601 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4602 (defvar org-ds-keyword-length 12
4603 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4604 (make-variable-buffer-local 'org-ds-keyword-length)
4605 (defvar org-deadline-regexp nil
4606 "Matches the DEADLINE keyword.")
4607 (make-variable-buffer-local 'org-deadline-regexp)
4608 (defvar org-deadline-time-regexp nil
4609 "Matches the DEADLINE keyword together with a time stamp.")
4610 (make-variable-buffer-local 'org-deadline-time-regexp)
4611 (defvar org-deadline-time-hour-regexp nil
4612 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4613 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4614 (defvar org-deadline-line-regexp nil
4615 "Matches the DEADLINE keyword and the rest of the line.")
4616 (make-variable-buffer-local 'org-deadline-line-regexp)
4617 (defvar org-scheduled-regexp nil
4618 "Matches the SCHEDULED keyword.")
4619 (make-variable-buffer-local 'org-scheduled-regexp)
4620 (defvar org-scheduled-time-regexp nil
4621 "Matches the SCHEDULED keyword together with a time stamp.")
4622 (make-variable-buffer-local 'org-scheduled-time-regexp)
4623 (defvar org-scheduled-time-hour-regexp nil
4624 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4625 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4626 (defvar org-closed-time-regexp nil
4627 "Matches the CLOSED keyword together with a time stamp.")
4628 (make-variable-buffer-local 'org-closed-time-regexp)
4630 (defvar org-keyword-time-regexp nil
4631 "Matches any of the 4 keywords, together with the time stamp.")
4632 (make-variable-buffer-local 'org-keyword-time-regexp)
4633 (defvar org-keyword-time-not-clock-regexp nil
4634 "Matches any of the 3 keywords, together with the time stamp.")
4635 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4636 (defvar org-maybe-keyword-time-regexp nil
4637 "Matches a timestamp, possibly preceded by a keyword.")
4638 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4639 (defvar org-all-time-keywords nil
4640 "List of time keywords.")
4641 (make-variable-buffer-local 'org-all-time-keywords)
4643 (defconst org-plain-time-of-day-regexp
4644 (concat
4645 "\\(\\<[012]?[0-9]"
4646 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4647 "\\(--?"
4648 "\\(\\<[012]?[0-9]"
4649 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4650 "\\)?")
4651 "Regular expression to match a plain time or time range.
4652 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4653 groups carry important information:
4654 0 the full match
4655 1 the first time, range or not
4656 8 the second time, if it is a range.")
4658 (defconst org-plain-time-extension-regexp
4659 (concat
4660 "\\(\\<[012]?[0-9]"
4661 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4662 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4663 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4664 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4665 groups carry important information:
4666 0 the full match
4667 7 hours of duration
4668 9 minutes of duration")
4670 (defconst org-stamp-time-of-day-regexp
4671 (concat
4672 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4673 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4674 "\\(--?"
4675 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4676 "Regular expression to match a timestamp time or time range.
4677 After a match, the following groups carry important information:
4678 0 the full match
4679 1 date plus weekday, for back referencing to make sure both times are on the same day
4680 2 the first time, range or not
4681 4 the second time, if it is a range.")
4683 (defconst org-startup-options
4684 '(("fold" org-startup-folded t)
4685 ("overview" org-startup-folded t)
4686 ("nofold" org-startup-folded nil)
4687 ("showall" org-startup-folded nil)
4688 ("showeverything" org-startup-folded showeverything)
4689 ("content" org-startup-folded content)
4690 ("indent" org-startup-indented t)
4691 ("noindent" org-startup-indented nil)
4692 ("hidestars" org-hide-leading-stars t)
4693 ("showstars" org-hide-leading-stars nil)
4694 ("odd" org-odd-levels-only t)
4695 ("oddeven" org-odd-levels-only nil)
4696 ("align" org-startup-align-all-tables t)
4697 ("noalign" org-startup-align-all-tables nil)
4698 ("inlineimages" org-startup-with-inline-images t)
4699 ("noinlineimages" org-startup-with-inline-images nil)
4700 ("latexpreview" org-startup-with-latex-preview t)
4701 ("nolatexpreview" org-startup-with-latex-preview nil)
4702 ("customtime" org-display-custom-times t)
4703 ("logdone" org-log-done time)
4704 ("lognotedone" org-log-done note)
4705 ("nologdone" org-log-done nil)
4706 ("lognoteclock-out" org-log-note-clock-out t)
4707 ("nolognoteclock-out" org-log-note-clock-out nil)
4708 ("logrepeat" org-log-repeat state)
4709 ("lognoterepeat" org-log-repeat note)
4710 ("logdrawer" org-log-into-drawer t)
4711 ("nologdrawer" org-log-into-drawer nil)
4712 ("logstatesreversed" org-log-states-order-reversed t)
4713 ("nologstatesreversed" org-log-states-order-reversed nil)
4714 ("nologrepeat" org-log-repeat nil)
4715 ("logreschedule" org-log-reschedule time)
4716 ("lognotereschedule" org-log-reschedule note)
4717 ("nologreschedule" org-log-reschedule nil)
4718 ("logredeadline" org-log-redeadline time)
4719 ("lognoteredeadline" org-log-redeadline note)
4720 ("nologredeadline" org-log-redeadline nil)
4721 ("logrefile" org-log-refile time)
4722 ("lognoterefile" org-log-refile note)
4723 ("nologrefile" org-log-refile nil)
4724 ("fninline" org-footnote-define-inline t)
4725 ("nofninline" org-footnote-define-inline nil)
4726 ("fnlocal" org-footnote-section nil)
4727 ("fnauto" org-footnote-auto-label t)
4728 ("fnprompt" org-footnote-auto-label nil)
4729 ("fnconfirm" org-footnote-auto-label confirm)
4730 ("fnplain" org-footnote-auto-label plain)
4731 ("fnadjust" org-footnote-auto-adjust t)
4732 ("nofnadjust" org-footnote-auto-adjust nil)
4733 ("constcgs" constants-unit-system cgs)
4734 ("constSI" constants-unit-system SI)
4735 ("noptag" org-tag-persistent-alist nil)
4736 ("hideblocks" org-hide-block-startup t)
4737 ("nohideblocks" org-hide-block-startup nil)
4738 ("beamer" org-startup-with-beamer-mode t)
4739 ("entitiespretty" org-pretty-entities t)
4740 ("entitiesplain" org-pretty-entities nil))
4741 "Variable associated with STARTUP options for org-mode.
4742 Each element is a list of three items: the startup options (as written
4743 in the #+STARTUP line), the corresponding variable, and the value to set
4744 this variable to if the option is found. An optional forth element PUSH
4745 means to push this value onto the list in the variable.")
4747 (defun org-update-property-plist (key val props)
4748 "Update PROPS with KEY and VAL."
4749 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4750 (key (if appending (substring key 0 (- (length key) 1)) key))
4751 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4752 (previous (cdr (assoc key props))))
4753 (if appending
4754 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4755 (cons (cons key val) remainder))))
4757 (defconst org-block-regexp
4758 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4759 "Regular expression for hiding blocks.")
4760 (defconst org-heading-keyword-regexp-format
4761 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4762 "Printf format for a regexp matching a headline with some keyword.
4763 This regexp will match the headline of any node which has the
4764 exact keyword that is put into the format. The keyword isn't in
4765 any group by default, but the stars and the body are.")
4766 (defconst org-heading-keyword-maybe-regexp-format
4767 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4768 "Printf format for a regexp matching a headline, possibly with some keyword.
4769 This regexp can match any headline with the specified keyword, or
4770 without a keyword. The keyword isn't in any group by default,
4771 but the stars and the body are.")
4773 (defcustom org-group-tags t
4774 "When non-nil (the default), use group tags.
4775 This can be turned on/off through `org-toggle-tags-groups'."
4776 :group 'org-tags
4777 :group 'org-startup
4778 :type 'boolean)
4780 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4782 (defun org-toggle-tags-groups ()
4783 "Toggle support for group tags.
4784 Support for group tags is controlled by the option
4785 `org-group-tags', which is non-nil by default."
4786 (interactive)
4787 (setq org-group-tags (not org-group-tags))
4788 (cond ((and (derived-mode-p 'org-agenda-mode)
4789 org-group-tags)
4790 (org-agenda-redo))
4791 ((derived-mode-p 'org-mode)
4792 (let ((org-inhibit-startup t)) (org-mode))))
4793 (message "Groups tags support has been turned %s"
4794 (if org-group-tags "on" "off")))
4796 (defun org-set-regexps-and-options-for-tags ()
4797 "Precompute variables used for tags."
4798 (when (derived-mode-p 'org-mode)
4799 (org-set-local 'org-file-tags nil)
4800 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4801 (splitre "[ \t]+")
4802 (start 0)
4803 tags ftags key value)
4804 (save-excursion
4805 (save-restriction
4806 (widen)
4807 (goto-char (point-min))
4808 (while (re-search-forward re nil t)
4809 (setq key (upcase (org-match-string-no-properties 1))
4810 value (org-match-string-no-properties 2))
4811 (if (stringp value) (setq value (org-trim value)))
4812 (cond
4813 ((equal key "TAGS")
4814 (setq tags (append tags (if tags '("\\n") nil)
4815 (org-split-string value splitre))))
4816 ((equal key "FILETAGS")
4817 (when (string-match "\\S-" value)
4818 (setq ftags
4819 (append
4820 ftags
4821 (apply 'append
4822 (mapcar (lambda (x) (org-split-string x ":"))
4823 (org-split-string value)))))))))))
4824 ;; Process the file tags.
4825 (and ftags (org-set-local 'org-file-tags
4826 (mapcar 'org-add-prop-inherited ftags)))
4827 (org-set-local 'org-tag-groups-alist nil)
4828 ;; Process the tags.
4829 (when (and (not tags) org-tag-alist)
4830 (setq tags
4831 (mapcar
4832 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4833 ((eq (car tg) :endgroup) "}")
4834 ((eq (car tg) :grouptags) ":")
4835 ((eq (car tg) :newline) "\n")
4836 (t (concat (car tg)
4837 (if (characterp (cdr tg))
4838 (format "(%s)" (char-to-string (cdr tg))) "")))))
4839 org-tag-alist)))
4840 (let (e tgs g)
4841 (while (setq e (pop tags))
4842 (cond
4843 ((equal e "{")
4844 (progn (push '(:startgroup) tgs)
4845 (when (equal (nth 1 tags) ":")
4846 (push (list (replace-regexp-in-string
4847 "(.+)$" "" (nth 0 tags)))
4848 org-tag-groups-alist)
4849 (setq g 0))))
4850 ((equal e ":") (push '(:grouptags) tgs))
4851 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4852 ((equal e "\\n") (push '(:newline) tgs))
4853 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4854 (push (cons (match-string 1 e)
4855 (string-to-char (match-string 2 e))) tgs)
4856 (if (and g (> g 0))
4857 (setcar org-tag-groups-alist
4858 (append (car org-tag-groups-alist)
4859 (list (match-string 1 e)))))
4860 (if g (setq g (1+ g))))
4861 (t (push (list e) tgs)
4862 (if (and g (> g 0))
4863 (setcar org-tag-groups-alist
4864 (append (car org-tag-groups-alist) (list e))))
4865 (if g (setq g (1+ g))))))
4866 (org-set-local 'org-tag-alist nil)
4867 (while (setq e (pop tgs))
4868 (or (and (stringp (car e))
4869 (assoc (car e) org-tag-alist))
4870 (push e org-tag-alist)))
4871 ;; Return a list with tag variables
4872 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4874 (defvar org-ota nil)
4875 (defun org-set-regexps-and-options ()
4876 "Precompute regular expressions used in the current buffer."
4877 (when (derived-mode-p 'org-mode)
4878 (org-set-local 'org-todo-kwd-alist nil)
4879 (org-set-local 'org-todo-key-alist nil)
4880 (org-set-local 'org-todo-key-trigger nil)
4881 (org-set-local 'org-todo-keywords-1 nil)
4882 (org-set-local 'org-done-keywords nil)
4883 (org-set-local 'org-todo-heads nil)
4884 (org-set-local 'org-todo-sets nil)
4885 (org-set-local 'org-todo-log-states nil)
4886 (org-set-local 'org-file-properties nil)
4887 (let ((re (org-make-options-regexp
4888 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4889 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4890 "SETUPFILE" "OPTIONS")
4891 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4892 (splitre "[ \t]+")
4893 (scripts org-use-sub-superscripts)
4894 kwds kws0 kwsa key log value cat arch const links hw dws
4895 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4896 (start 0))
4897 (save-excursion
4898 (save-restriction
4899 (widen)
4900 (goto-char (point-min))
4901 (while
4902 (or (and
4903 ext-setup-or-nil
4904 (not org-ota)
4905 (let (ret)
4906 (with-temp-buffer
4907 (insert ext-setup-or-nil)
4908 (let ((major-mode 'org-mode) org-ota)
4909 (setq ret (save-match-data
4910 (org-set-regexps-and-options-for-tags)))))
4911 ;; Append setupfile tags to existing tags
4912 (setq org-ota t)
4913 (setq org-file-tags
4914 (delq nil (append org-file-tags (nth 0 ret)))
4915 org-tag-alist
4916 (delq nil (append org-tag-alist (nth 1 ret)))
4917 org-tag-groups-alist
4918 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4919 (and ext-setup-or-nil
4920 (string-match re ext-setup-or-nil start)
4921 (setq start (match-end 0)))
4922 (and (setq ext-setup-or-nil nil start 0)
4923 (re-search-forward re nil t)))
4924 (setq key (upcase (match-string 1 ext-setup-or-nil))
4925 value (org-match-string-no-properties 2 ext-setup-or-nil))
4926 (if (stringp value) (setq value (org-trim value)))
4927 (cond
4928 ((equal key "CATEGORY")
4929 (setq cat value))
4930 ((member key '("SEQ_TODO" "TODO"))
4931 (push (cons 'sequence (org-split-string value splitre)) kwds))
4932 ((equal key "TYP_TODO")
4933 (push (cons 'type (org-split-string value splitre)) kwds))
4934 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4935 ;; general TODO-like setup
4936 (push (cons (intern (downcase (match-string 1 key)))
4937 (org-split-string value splitre)) kwds))
4938 ((equal key "COLUMNS")
4939 (org-set-local 'org-columns-default-format value))
4940 ((equal key "LINK")
4941 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4942 (push (cons (match-string 1 value)
4943 (org-trim (match-string 2 value)))
4944 links)))
4945 ((equal key "PRIORITIES")
4946 (setq prio (org-split-string value " +")))
4947 ((equal key "PROPERTY")
4948 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4949 (setq props (org-update-property-plist (match-string 1 value)
4950 (match-string 2 value)
4951 props))))
4952 ((equal key "DRAWERS")
4953 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4954 ((equal key "CONSTANTS")
4955 (org-table-set-constants))
4956 ((equal key "STARTUP")
4957 (let ((opts (org-split-string value splitre))
4958 l var val)
4959 (while (setq l (pop opts))
4960 (when (setq l (assoc l org-startup-options))
4961 (setq var (nth 1 l) val (nth 2 l))
4962 (if (not (nth 3 l))
4963 (set (make-local-variable var) val)
4964 (if (not (listp (symbol-value var)))
4965 (set (make-local-variable var) nil))
4966 (set (make-local-variable var) (symbol-value var))
4967 (add-to-list var val))))))
4968 ((equal key "ARCHIVE")
4969 (setq arch value)
4970 (remove-text-properties 0 (length arch)
4971 '(face t fontified t) arch))
4972 ((equal key "OPTIONS")
4973 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4974 (setq scripts (read (match-string 2 value)))))
4975 ((and (equal key "SETUPFILE")
4976 ;; Prevent checking in Gnus messages
4977 (not buffer-read-only))
4978 (setq setup-contents (org-file-contents
4979 (expand-file-name
4980 (org-remove-double-quotes value))
4981 'noerror))
4982 (if (not ext-setup-or-nil)
4983 (setq ext-setup-or-nil setup-contents start 0)
4984 (setq ext-setup-or-nil
4985 (concat (substring ext-setup-or-nil 0 start)
4986 "\n" setup-contents "\n"
4987 (substring ext-setup-or-nil start)))))))
4988 ;; search for property blocks
4989 (goto-char (point-min))
4990 (while (re-search-forward org-block-regexp nil t)
4991 (when (equal "PROPERTY" (upcase (match-string 1)))
4992 (setq value (replace-regexp-in-string
4993 "[\n\r]" " " (match-string 4)))
4994 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4995 (setq props (org-update-property-plist (match-string 1 value)
4996 (match-string 2 value)
4997 props)))))))
4998 (org-set-local 'org-use-sub-superscripts scripts)
4999 (when cat
5000 (org-set-local 'org-category (intern cat))
5001 (push (cons "CATEGORY" cat) props))
5002 (when prio
5003 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5004 (setq prio (mapcar 'string-to-char prio))
5005 (org-set-local 'org-highest-priority (nth 0 prio))
5006 (org-set-local 'org-lowest-priority (nth 1 prio))
5007 (org-set-local 'org-default-priority (nth 2 prio)))
5008 (and props (org-set-local 'org-file-properties (nreverse props)))
5009 (and drawers (org-set-local 'org-drawers drawers))
5010 (and arch (org-set-local 'org-archive-location arch))
5011 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5012 ;; Process the TODO keywords
5013 (unless kwds
5014 ;; Use the global values as if they had been given locally.
5015 (setq kwds (default-value 'org-todo-keywords))
5016 (if (stringp (car kwds))
5017 (setq kwds (list (cons org-todo-interpretation
5018 (default-value 'org-todo-keywords)))))
5019 (setq kwds (reverse kwds)))
5020 (setq kwds (nreverse kwds))
5021 (let (inter kws kw)
5022 (while (setq kws (pop kwds))
5023 (let ((kws (or
5024 (run-hook-with-args-until-success
5025 'org-todo-setup-filter-hook kws)
5026 kws)))
5027 (setq inter (pop kws) sep (member "|" kws)
5028 kws0 (delete "|" (copy-sequence kws))
5029 kwsa nil
5030 kws1 (mapcar
5031 (lambda (x)
5032 ;; 1 2
5033 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5034 (progn
5035 (setq kw (match-string 1 x)
5036 key (and (match-end 2) (match-string 2 x))
5037 log (org-extract-log-state-settings x))
5038 (push (cons kw (and key (string-to-char key))) kwsa)
5039 (and log (push log org-todo-log-states))
5041 (error "Invalid TODO keyword %s" x)))
5042 kws0)
5043 kwsa (if kwsa (append '((:startgroup))
5044 (nreverse kwsa)
5045 '((:endgroup))))
5046 hw (car kws1)
5047 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5048 tail (list inter hw (car dws) (org-last dws))))
5049 (add-to-list 'org-todo-heads hw 'append)
5050 (push kws1 org-todo-sets)
5051 (setq org-done-keywords (append org-done-keywords dws nil))
5052 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5053 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5054 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5055 (setq org-todo-sets (nreverse org-todo-sets)
5056 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5057 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5058 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5059 ;; Compute the regular expressions and other local variables.
5060 ;; Using `org-outline-regexp-bol' would complicate them much,
5061 ;; because of the fixed white space at the end of that string.
5062 (if (not org-done-keywords)
5063 (setq org-done-keywords (and org-todo-keywords-1
5064 (list (org-last org-todo-keywords-1)))))
5065 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5066 (length org-scheduled-string)
5067 (length org-clock-string)
5068 (length org-closed-string)))
5069 org-drawer-regexp
5070 (concat "^[ \t]*:\\("
5071 (mapconcat 'regexp-quote org-drawers "\\|")
5072 "\\):[ \t]*$")
5073 org-not-done-keywords
5074 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5075 org-todo-regexp
5076 (concat "\\("
5077 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5078 "\\)")
5079 org-not-done-regexp
5080 (concat "\\("
5081 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5082 "\\)")
5083 org-not-done-heading-regexp
5084 (format org-heading-keyword-regexp-format org-not-done-regexp)
5085 org-todo-line-regexp
5086 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5087 org-complex-heading-regexp
5088 (concat "^\\(\\*+\\)"
5089 "\\(?: +" org-todo-regexp "\\)?"
5090 "\\(?: +\\(\\[#.\\]\\)\\)?"
5091 "\\(?: +\\(.*?\\)\\)??"
5092 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5093 "[ \t]*$")
5094 org-complex-heading-regexp-format
5095 (concat "^\\(\\*+\\)"
5096 "\\(?: +" org-todo-regexp "\\)?"
5097 "\\(?: +\\(\\[#.\\]\\)\\)?"
5098 "\\(?: +"
5099 ;; Stats cookies can be stuck to body.
5100 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5101 "\\(%s\\)"
5102 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5103 "\\)"
5104 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5105 "[ \t]*$")
5106 org-todo-line-tags-regexp
5107 (concat "^\\(\\*+\\)"
5108 "\\(?: +" org-todo-regexp "\\)?"
5109 "\\(?: +\\(.*?\\)\\)??"
5110 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5111 "[ \t]*$")
5112 org-deadline-regexp (concat "\\<" org-deadline-string)
5113 org-deadline-time-regexp
5114 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5115 org-deadline-time-hour-regexp
5116 (concat "\\<" org-deadline-string
5117 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5118 org-deadline-line-regexp
5119 (concat "\\<\\(" org-deadline-string "\\).*")
5120 org-scheduled-regexp
5121 (concat "\\<" org-scheduled-string)
5122 org-scheduled-time-regexp
5123 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5124 org-scheduled-time-hour-regexp
5125 (concat "\\<" org-scheduled-string
5126 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5127 org-closed-time-regexp
5128 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5129 org-keyword-time-regexp
5130 (concat "\\<\\(" org-scheduled-string
5131 "\\|" org-deadline-string
5132 "\\|" org-closed-string
5133 "\\|" org-clock-string "\\)"
5134 " *[[<]\\([^]>]+\\)[]>]")
5135 org-keyword-time-not-clock-regexp
5136 (concat "\\<\\(" org-scheduled-string
5137 "\\|" org-deadline-string
5138 "\\|" org-closed-string
5139 "\\)"
5140 " *[[<]\\([^]>]+\\)[]>]")
5141 org-maybe-keyword-time-regexp
5142 (concat "\\(\\<\\(" org-scheduled-string
5143 "\\|" org-deadline-string
5144 "\\|" org-closed-string
5145 "\\|" org-clock-string "\\)\\)?"
5146 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5147 org-all-time-keywords
5148 (mapcar (lambda (w) (substring w 0 -1))
5149 (list org-scheduled-string org-deadline-string
5150 org-clock-string org-closed-string)))
5151 (setq org-ota nil)
5152 (org-compute-latex-and-related-regexp))))
5154 (defun org-file-contents (file &optional noerror)
5155 "Return the contents of FILE, as a string."
5156 (if (or (not file)
5157 (not (file-readable-p file)))
5158 (if noerror
5159 (message "Cannot read file \"%s\"" file)
5160 (error "Cannot read file \"%s\"" file))
5161 (with-temp-buffer
5162 (insert-file-contents file)
5163 (buffer-string))))
5165 (defun org-extract-log-state-settings (x)
5166 "Extract the log state setting from a TODO keyword string.
5167 This will extract info from a string like \"WAIT(w@/!)\"."
5168 (let (kw key log1 log2)
5169 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5170 (setq kw (match-string 1 x)
5171 key (and (match-end 2) (match-string 2 x))
5172 log1 (and (match-end 3) (match-string 3 x))
5173 log2 (and (match-end 4) (match-string 4 x)))
5174 (and (or log1 log2)
5175 (list kw
5176 (and log1 (if (equal log1 "!") 'time 'note))
5177 (and log2 (if (equal log2 "!") 'time 'note)))))))
5179 (defun org-remove-keyword-keys (list)
5180 "Remove a pair of parenthesis at the end of each string in LIST."
5181 (mapcar (lambda (x)
5182 (if (string-match "(.*)$" x)
5183 (substring x 0 (match-beginning 0))
5185 list))
5187 (defun org-assign-fast-keys (alist)
5188 "Assign fast keys to a keyword-key alist.
5189 Respect keys that are already there."
5190 (let (new e (alt ?0))
5191 (while (setq e (pop alist))
5192 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5193 (cdr e)) ;; Key already assigned.
5194 (push e new)
5195 (let ((clist (string-to-list (downcase (car e))))
5196 (used (append new alist)))
5197 (when (= (car clist) ?@)
5198 (pop clist))
5199 (while (and clist (rassoc (car clist) used))
5200 (pop clist))
5201 (unless clist
5202 (while (rassoc alt used)
5203 (incf alt)))
5204 (push (cons (car e) (or (car clist) alt)) new))))
5205 (nreverse new)))
5207 ;;; Some variables used in various places
5209 (defvar org-window-configuration nil
5210 "Used in various places to store a window configuration.")
5211 (defvar org-selected-window nil
5212 "Used in various places to store a window configuration.")
5213 (defvar org-finish-function nil
5214 "Function to be called when `C-c C-c' is used.
5215 This is for getting out of special buffers like capture.")
5218 ;; FIXME: Occasionally check by commenting these, to make sure
5219 ;; no other functions uses these, forgetting to let-bind them.
5220 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5221 (defvar org-last-state)
5222 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5224 ;; Defined somewhere in this file, but used before definition.
5225 (defvar org-entities) ;; defined in org-entities.el
5226 (defvar org-struct-menu)
5227 (defvar org-org-menu)
5228 (defvar org-tbl-menu)
5230 ;;;; Define the Org-mode
5232 ;; We use a before-change function to check if a table might need
5233 ;; an update.
5234 (defvar org-table-may-need-update t
5235 "Indicates that a table might need an update.
5236 This variable is set by `org-before-change-function'.
5237 `org-table-align' sets it back to nil.")
5238 (defun org-before-change-function (beg end)
5239 "Every change indicates that a table might need an update."
5240 (setq org-table-may-need-update t))
5241 (defvar org-mode-map)
5242 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5243 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5244 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5245 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5246 (defvar org-table-buffer-is-an nil)
5248 (defvar bidi-paragraph-direction)
5249 (defvar buffer-face-mode-face)
5251 (require 'outline)
5252 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5253 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
5254 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5256 ;; Other stuff we need.
5257 (require 'time-date)
5258 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5259 (require 'easymenu)
5260 (require 'overlay)
5262 ;; (require 'org-macs) moved higher up in the file before it is first used
5263 (require 'org-entities)
5264 ;; (require 'org-compat) moved higher up in the file before it is first used
5265 (require 'org-faces)
5266 (require 'org-list)
5267 (require 'org-pcomplete)
5268 (require 'org-src)
5269 (require 'org-footnote)
5270 (require 'org-macro)
5272 ;; babel
5273 (require 'ob)
5275 ;;;###autoload
5276 (define-derived-mode org-mode outline-mode "Org"
5277 "Outline-based notes management and organizer, alias
5278 \"Carsten's outline-mode for keeping track of everything.\"
5280 Org-mode develops organizational tasks around a NOTES file which
5281 contains information about projects as plain text. Org-mode is
5282 implemented on top of outline-mode, which is ideal to keep the content
5283 of large files well structured. It supports ToDo items, deadlines and
5284 time stamps, which magically appear in the diary listing of the Emacs
5285 calendar. Tables are easily created with a built-in table editor.
5286 Plain text URL-like links connect to websites, emails (VM), Usenet
5287 messages (Gnus), BBDB entries, and any files related to the project.
5288 For printing and sharing of notes, an Org-mode file (or a part of it)
5289 can be exported as a structured ASCII or HTML file.
5291 The following commands are available:
5293 \\{org-mode-map}"
5295 ;; Get rid of Outline menus, they are not needed
5296 ;; Need to do this here because define-derived-mode sets up
5297 ;; the keymap so late. Still, it is a waste to call this each time
5298 ;; we switch another buffer into org-mode.
5299 (if (featurep 'xemacs)
5300 (when (boundp 'outline-mode-menu-heading)
5301 ;; Assume this is Greg's port, it uses easymenu
5302 (easy-menu-remove outline-mode-menu-heading)
5303 (easy-menu-remove outline-mode-menu-show)
5304 (easy-menu-remove outline-mode-menu-hide))
5305 (define-key org-mode-map [menu-bar headings] 'undefined)
5306 (define-key org-mode-map [menu-bar hide] 'undefined)
5307 (define-key org-mode-map [menu-bar show] 'undefined))
5309 (org-load-modules-maybe)
5310 (easy-menu-add org-org-menu)
5311 (easy-menu-add org-tbl-menu)
5312 (org-install-agenda-files-menu)
5313 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5314 (add-to-invisibility-spec '(org-cwidth))
5315 (add-to-invisibility-spec '(org-hide-block . t))
5316 (when (featurep 'xemacs)
5317 (org-set-local 'line-move-ignore-invisible t))
5318 (org-set-local 'outline-regexp org-outline-regexp)
5319 (org-set-local 'outline-level 'org-outline-level)
5320 (setq bidi-paragraph-direction 'left-to-right)
5321 (when (and org-ellipsis
5322 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5323 (fboundp 'make-glyph-code))
5324 (unless org-display-table
5325 (setq org-display-table (make-display-table)))
5326 (set-display-table-slot
5327 org-display-table 4
5328 (vconcat (mapcar
5329 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5330 org-ellipsis)))
5331 (if (stringp org-ellipsis) org-ellipsis "..."))))
5332 (setq buffer-display-table org-display-table))
5333 (org-set-regexps-and-options-for-tags)
5334 (org-set-regexps-and-options)
5335 (org-set-font-lock-defaults)
5336 (when (and org-tag-faces (not org-tags-special-faces-re))
5337 ;; tag faces set outside customize.... force initialization.
5338 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5339 ;; Calc embedded
5340 (org-set-local 'calc-embedded-open-mode "# ")
5341 ;; Modify a few syntax entries
5342 (modify-syntax-entry ?@ "w")
5343 (modify-syntax-entry ?\" "\"")
5344 (if org-startup-truncated (setq truncate-lines t))
5345 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5346 (org-set-local 'font-lock-unfontify-region-function
5347 'org-unfontify-region)
5348 ;; Activate before-change-function
5349 (org-set-local 'org-table-may-need-update t)
5350 (org-add-hook 'before-change-functions 'org-before-change-function nil
5351 'local)
5352 ;; Check for running clock before killing a buffer
5353 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5354 ;; Initialize macros templates.
5355 (org-macro-initialize-templates)
5356 ;; Initialize radio targets.
5357 (org-update-radio-target-regexp)
5358 ;; Indentation.
5359 (org-set-local 'indent-line-function 'org-indent-line)
5360 (org-set-local 'indent-region-function 'org-indent-region)
5361 ;; Filling and auto-filling.
5362 (org-setup-filling)
5363 ;; Comments.
5364 (org-setup-comments-handling)
5365 ;; Beginning/end of defun
5366 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5367 (org-set-local 'end-of-defun-function 'org-forward-element)
5368 ;; Next error for sparse trees
5369 (org-set-local 'next-error-function 'org-occur-next-match)
5370 ;; Make sure dependence stuff works reliably, even for users who set it
5371 ;; too late :-(
5372 (if org-enforce-todo-dependencies
5373 (add-hook 'org-blocker-hook
5374 'org-block-todo-from-children-or-siblings-or-parent)
5375 (remove-hook 'org-blocker-hook
5376 'org-block-todo-from-children-or-siblings-or-parent))
5377 (if org-enforce-todo-checkbox-dependencies
5378 (add-hook 'org-blocker-hook
5379 'org-block-todo-from-checkboxes)
5380 (remove-hook 'org-blocker-hook
5381 'org-block-todo-from-checkboxes))
5383 ;; Align options lines
5384 (org-set-local
5385 'align-mode-rules-list
5386 '((org-in-buffer-settings
5387 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5388 (modes . '(org-mode)))))
5390 ;; Imenu
5391 (org-set-local 'imenu-create-index-function
5392 'org-imenu-get-tree)
5394 ;; Make isearch reveal context
5395 (if (or (featurep 'xemacs)
5396 (not (boundp 'outline-isearch-open-invisible-function)))
5397 ;; Emacs 21 and XEmacs make use of the hook
5398 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5399 ;; Emacs 22 deals with this through a special variable
5400 (org-set-local 'outline-isearch-open-invisible-function
5401 (lambda (&rest ignore) (org-show-context 'isearch)))
5402 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5404 ;; Setup the pcomplete hooks
5405 (set (make-local-variable 'pcomplete-command-completion-function)
5406 'org-pcomplete-initial)
5407 (set (make-local-variable 'pcomplete-command-name-function)
5408 'org-command-at-point)
5409 (set (make-local-variable 'pcomplete-default-completion-function)
5410 'ignore)
5411 (set (make-local-variable 'pcomplete-parse-arguments-function)
5412 'org-parse-arguments)
5413 (set (make-local-variable 'pcomplete-termination-string) "")
5414 (when (>= emacs-major-version 23)
5415 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5417 ;; If empty file that did not turn on org-mode automatically, make it to.
5418 (if (and org-insert-mode-line-in-empty-file
5419 (org-called-interactively-p 'any)
5420 (= (point-min) (point-max)))
5421 (insert "# -*- mode: org -*-\n\n"))
5422 (unless org-inhibit-startup
5423 (org-unmodified
5424 (and org-startup-with-beamer-mode (org-beamer-mode))
5425 (when org-startup-align-all-tables
5426 (org-table-map-tables 'org-table-align 'quietly))
5427 (when org-startup-with-inline-images
5428 (org-display-inline-images))
5429 (when org-startup-with-latex-preview
5430 (org-preview-latex-fragment))
5431 (unless org-inhibit-startup-visibility-stuff
5432 (org-set-startup-visibility))))
5433 ;; Try to set org-hide correctly
5434 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5436 ;; Update `customize-package-emacs-version-alist'
5437 (add-to-list 'customize-package-emacs-version-alist
5438 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5439 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5440 ("8.0" . "24.4")))
5442 (defvar org-mode-transpose-word-syntax-table
5443 (let ((st (make-syntax-table)))
5444 (mapc (lambda(c) (modify-syntax-entry
5445 (string-to-char (car c)) "w p" st))
5446 org-emphasis-alist)
5447 st))
5449 (when (fboundp 'abbrev-table-put)
5450 (abbrev-table-put org-mode-abbrev-table
5451 :parents (list text-mode-abbrev-table)))
5453 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5455 (defsubst org-fix-ellipsis-at-bol ()
5456 (save-excursion (goto-char (window-start)) (recenter 0)))
5458 (defun org-find-invisible-foreground ()
5459 (let ((candidates (remove
5460 "unspecified-bg"
5461 (nconc
5462 (list (face-background 'default)
5463 (face-background 'org-default))
5464 (mapcar
5465 (lambda (alist)
5466 (when (boundp alist)
5467 (cdr (assoc 'background-color (symbol-value alist)))))
5468 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5469 (list (face-foreground 'org-hide))))))
5470 (car (remove nil candidates))))
5472 (defun org-current-time (&optional rounding-minutes past)
5473 "Current time, possibly rounded to ROUNDING-MINUTES.
5474 When ROUNDING-MINUTES is not an integer, fall back on the car of
5475 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5476 the rounding returns a past time."
5477 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5478 (car org-time-stamp-rounding-minutes)))
5479 (time (decode-time)) res)
5480 (if (< r 1)
5481 (current-time)
5482 (setq res
5483 (apply 'encode-time
5484 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5485 (nthcdr 2 time))))
5486 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5487 (seconds-to-time (- (org-float-time res) (* r 60)))
5488 res))))
5490 (defun org-today ()
5491 "Return today date, considering `org-extend-today-until'."
5492 (time-to-days
5493 (time-subtract (current-time)
5494 (list 0 (* 3600 org-extend-today-until) 0))))
5496 ;;;; Font-Lock stuff, including the activators
5498 (defvar org-mouse-map (make-sparse-keymap))
5499 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5500 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5501 (when org-mouse-1-follows-link
5502 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5503 (when org-tab-follows-link
5504 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5505 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5507 (require 'font-lock)
5509 (defconst org-non-link-chars "]\t\n\r<>")
5510 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5511 "shell" "elisp" "doi" "message"))
5512 (defvar org-link-types-re nil
5513 "Matches a link that has a url-like prefix like \"http:\"")
5514 (defvar org-link-re-with-space nil
5515 "Matches a link with spaces, optional angular brackets around it.")
5516 (defvar org-link-re-with-space2 nil
5517 "Matches a link with spaces, optional angular brackets around it.")
5518 (defvar org-link-re-with-space3 nil
5519 "Matches a link with spaces, only for internal part in bracket links.")
5520 (defvar org-angle-link-re nil
5521 "Matches link with angular brackets, spaces are allowed.")
5522 (defvar org-plain-link-re nil
5523 "Matches plain link, without spaces.")
5524 (defvar org-bracket-link-regexp nil
5525 "Matches a link in double brackets.")
5526 (defvar org-bracket-link-analytic-regexp nil
5527 "Regular expression used to analyze links.
5528 Here is what the match groups contain after a match:
5529 1: http:
5530 2: http
5531 3: path
5532 4: [desc]
5533 5: desc")
5534 (defvar org-bracket-link-analytic-regexp++ nil
5535 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5536 (defvar org-any-link-re nil
5537 "Regular expression matching any link.")
5539 (defconst org-match-sexp-depth 3
5540 "Number of stacked braces for sub/superscript matching.")
5542 (defun org-create-multibrace-regexp (left right n)
5543 "Create a regular expression which will match a balanced sexp.
5544 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5545 as single character strings.
5546 The regexp returned will match the entire expression including the
5547 delimiters. It will also define a single group which contains the
5548 match except for the outermost delimiters. The maximum depth of
5549 stacked delimiters is N. Escaping delimiters is not possible."
5550 (let* ((nothing (concat "[^" left right "]*?"))
5551 (or "\\|")
5552 (re nothing)
5553 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5554 (while (> n 1)
5555 (setq n (1- n)
5556 re (concat re or next)
5557 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5558 (concat left "\\(" re "\\)" right)))
5560 (defvar org-match-substring-regexp
5561 (concat
5562 "\\(\\S-\\)\\([_^]\\)\\("
5563 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5564 "\\|"
5565 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5566 "\\|"
5567 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5568 "The regular expression matching a sub- or superscript.")
5570 (defvar org-match-substring-with-braces-regexp
5571 (concat
5572 "\\(\\S-\\)\\([_^]\\)\\("
5573 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5574 "\\)")
5575 "The regular expression matching a sub- or superscript, forcing braces.")
5577 (defun org-make-link-regexps ()
5578 "Update the link regular expressions.
5579 This should be called after the variable `org-link-types' has changed."
5580 (setq org-link-types-re
5581 (concat
5582 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5583 org-link-re-with-space
5584 (concat
5585 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5586 "\\([^" org-non-link-chars " ]"
5587 "[^" org-non-link-chars "]*"
5588 "[^" org-non-link-chars " ]\\)>?")
5589 org-link-re-with-space2
5590 (concat
5591 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5592 "\\([^" org-non-link-chars " ]"
5593 "[^\t\n\r]*"
5594 "[^" org-non-link-chars " ]\\)>?")
5595 org-link-re-with-space3
5596 (concat
5597 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5598 "\\([^" org-non-link-chars " ]"
5599 "[^\t\n\r]*\\)")
5600 org-angle-link-re
5601 (concat
5602 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5603 "\\([^" org-non-link-chars " ]"
5604 "[^" org-non-link-chars "]*"
5605 "\\)>")
5606 org-plain-link-re
5607 (concat
5608 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5609 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5610 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5611 org-bracket-link-regexp
5612 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5613 org-bracket-link-analytic-regexp
5614 (concat
5615 "\\[\\["
5616 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5617 "\\([^]]+\\)"
5618 "\\]"
5619 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5620 "\\]")
5621 org-bracket-link-analytic-regexp++
5622 (concat
5623 "\\[\\["
5624 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5625 "\\([^]]+\\)"
5626 "\\]"
5627 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5628 "\\]")
5629 org-any-link-re
5630 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5631 org-angle-link-re "\\)\\|\\("
5632 org-plain-link-re "\\)")))
5634 (org-make-link-regexps)
5636 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5637 "Regular expression for fast time stamp matching.")
5638 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5639 "Regular expression for fast time stamp matching.")
5640 (defconst org-ts-regexp0
5641 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5642 "Regular expression matching time strings for analysis.
5643 This one does not require the space after the date, so it can be used
5644 on a string that terminates immediately after the date.")
5645 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5646 "Regular expression matching time strings for analysis.")
5647 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5648 "Regular expression matching time stamps, with groups.")
5649 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5650 "Regular expression matching time stamps (also [..]), with groups.")
5651 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5652 "Regular expression matching a time stamp range.")
5653 (defconst org-tr-regexp-both
5654 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5655 "Regular expression matching a time stamp range.")
5656 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5657 org-ts-regexp "\\)?")
5658 "Regular expression matching a time stamp or time stamp range.")
5659 (defconst org-tsr-regexp-both
5660 (concat org-ts-regexp-both "\\(--?-?"
5661 org-ts-regexp-both "\\)?")
5662 "Regular expression matching a time stamp or time stamp range.
5663 The time stamps may be either active or inactive.")
5665 (defvar org-emph-face nil)
5667 (defun org-do-emphasis-faces (limit)
5668 "Run through the buffer and add overlays to emphasized strings."
5669 (let (rtn a)
5670 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5671 (if (not (= (char-after (match-beginning 3))
5672 (char-after (match-beginning 4))))
5673 (progn
5674 (setq rtn t)
5675 (setq a (assoc (match-string 3) org-emphasis-alist))
5676 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5677 'face
5678 (nth 1 a))
5679 (and (nth 2 a)
5680 (org-remove-flyspell-overlays-in
5681 (match-beginning 0) (match-end 0)))
5682 (add-text-properties (match-beginning 2) (match-end 2)
5683 '(font-lock-multiline t org-emphasis t))
5684 (when org-hide-emphasis-markers
5685 (add-text-properties (match-end 4) (match-beginning 5)
5686 '(invisible org-link))
5687 (add-text-properties (match-beginning 3) (match-end 3)
5688 '(invisible org-link)))))
5689 (backward-char 1))
5690 rtn))
5692 (defun org-emphasize (&optional char)
5693 "Insert or change an emphasis, i.e. a font like bold or italic.
5694 If there is an active region, change that region to a new emphasis.
5695 If there is no region, just insert the marker characters and position
5696 the cursor between them.
5697 CHAR should be the marker character. If it is a space, it means to
5698 remove the emphasis of the selected region.
5699 If CHAR is not given (for example in an interactive call) it will be
5700 prompted for."
5701 (interactive)
5702 (let ((erc org-emphasis-regexp-components)
5703 (prompt "")
5704 (string "") beg end move c s)
5705 (if (org-region-active-p)
5706 (setq beg (region-beginning) end (region-end)
5707 string (buffer-substring beg end))
5708 (setq move t))
5710 (unless char
5711 (message "Emphasis marker or tag: [%s]"
5712 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5713 (setq char (read-char-exclusive)))
5714 (if (equal char ?\ )
5715 (setq s "" move nil)
5716 (unless (assoc (char-to-string char) org-emphasis-alist)
5717 (user-error "No such emphasis marker: \"%c\"" char))
5718 (setq s (char-to-string char)))
5719 (while (and (> (length string) 1)
5720 (equal (substring string 0 1) (substring string -1))
5721 (assoc (substring string 0 1) org-emphasis-alist))
5722 (setq string (substring string 1 -1)))
5723 (setq string (concat s string s))
5724 (if beg (delete-region beg end))
5725 (unless (or (bolp)
5726 (string-match (concat "[" (nth 0 erc) "\n]")
5727 (char-to-string (char-before (point)))))
5728 (insert " "))
5729 (unless (or (eobp)
5730 (string-match (concat "[" (nth 1 erc) "\n]")
5731 (char-to-string (char-after (point)))))
5732 (insert " ") (backward-char 1))
5733 (insert string)
5734 (and move (backward-char 1))))
5736 (defconst org-nonsticky-props
5737 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5739 (defsubst org-rear-nonsticky-at (pos)
5740 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5742 (defun org-activate-plain-links (limit)
5743 "Run through the buffer and add overlays to links."
5744 (let (f hl)
5745 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5746 (not (org-in-src-block-p)))
5747 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5748 (setq f (get-text-property (match-beginning 0) 'face))
5749 (setq hl (org-match-string-no-properties 0))
5750 (if (or (eq f 'org-tag)
5751 (and (listp f) (memq 'org-tag f)))
5753 (add-text-properties (match-beginning 0) (match-end 0)
5754 (list 'mouse-face 'highlight
5755 'face 'org-link
5756 'htmlize-link `(:uri ,hl)
5757 'keymap org-mouse-map))
5758 (org-rear-nonsticky-at (match-end 0)))
5759 t)))
5761 (defun org-activate-code (limit)
5762 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5763 (progn
5764 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5765 (remove-text-properties (match-beginning 0) (match-end 0)
5766 '(display t invisible t intangible t))
5767 t)))
5769 (defcustom org-src-fontify-natively nil
5770 "When non-nil, fontify code in code blocks."
5771 :type 'boolean
5772 :version "24.1"
5773 :group 'org-appearance
5774 :group 'org-babel)
5776 (defcustom org-allow-promoting-top-level-subtree nil
5777 "When non-nil, allow promoting a top level subtree.
5778 The leading star of the top level headline will be replaced
5779 by a #."
5780 :type 'boolean
5781 :version "24.1"
5782 :group 'org-appearance)
5784 (defun org-fontify-meta-lines-and-blocks (limit)
5785 (condition-case nil
5786 (org-fontify-meta-lines-and-blocks-1 limit)
5787 (error (message "org-mode fontification error"))))
5789 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5790 "Fontify #+ lines and blocks."
5791 (let ((case-fold-search t))
5792 (if (re-search-forward
5793 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5794 limit t)
5795 (let ((beg (match-beginning 0))
5796 (block-start (match-end 0))
5797 (block-end nil)
5798 (lang (match-string 7))
5799 (beg1 (line-beginning-position 2))
5800 (dc1 (downcase (match-string 2)))
5801 (dc3 (downcase (match-string 3)))
5802 end end1 quoting block-type ovl)
5803 (cond
5804 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5805 ;; a single line of backend-specific content
5806 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5807 (remove-text-properties (match-beginning 0) (match-end 0)
5808 '(display t invisible t intangible t))
5809 (add-text-properties (match-beginning 1) (match-end 3)
5810 '(font-lock-fontified t face org-meta-line))
5811 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5812 '(font-lock-fontified t face org-block))
5813 ; for backend-specific code
5815 ((and (match-end 4) (equal dc3 "+begin"))
5816 ;; Truly a block
5817 (setq block-type (downcase (match-string 5))
5818 quoting (member block-type org-protecting-blocks))
5819 (when (re-search-forward
5820 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5821 nil t) ;; on purpose, we look further than LIMIT
5822 (setq end (min (point-max) (match-end 0))
5823 end1 (min (point-max) (1- (match-beginning 0))))
5824 (setq block-end (match-beginning 0))
5825 (when quoting
5826 (remove-text-properties beg end
5827 '(display t invisible t intangible t)))
5828 (add-text-properties
5829 beg end
5830 '(font-lock-fontified t font-lock-multiline t))
5831 (add-text-properties beg beg1 '(face org-meta-line))
5832 (add-text-properties end1 (min (point-max) (1+ end))
5833 '(face org-meta-line)) ; for end_src
5834 (cond
5835 ((and lang (not (string= lang "")) org-src-fontify-natively)
5836 (org-src-font-lock-fontify-block lang block-start block-end)
5837 ;; remove old background overlays
5838 (mapc (lambda (ov)
5839 (if (eq (overlay-get ov 'face) 'org-block-background)
5840 (delete-overlay ov)))
5841 (overlays-at (/ (+ beg1 block-end) 2)))
5842 ;; add a background overlay
5843 (setq ovl (make-overlay beg1 block-end))
5844 (overlay-put ovl 'face 'org-block-background)
5845 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5846 (quoting
5847 (add-text-properties beg1 (min (point-max) (1+ end1))
5848 '(face org-block))) ; end of source block
5849 ((not org-fontify-quote-and-verse-blocks))
5850 ((string= block-type "quote")
5851 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5852 ((string= block-type "verse")
5853 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5854 (add-text-properties beg beg1 '(face org-block-begin-line))
5855 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5856 '(face org-block-end-line))
5858 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5859 (add-text-properties
5860 beg (match-end 3)
5861 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5862 '(font-lock-fontified t invisible t)
5863 '(font-lock-fontified t face org-document-info-keyword)))
5864 (add-text-properties
5865 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5866 (if (string-equal dc1 "+title:")
5867 '(font-lock-fontified t face org-document-title)
5868 '(font-lock-fontified t face org-document-info))))
5869 ((or (equal dc1 "+results")
5870 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5871 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5872 "+call:" "+header:" "+headers:" "+name:"))
5873 (and (match-end 4) (equal dc3 "+attr")))
5874 (add-text-properties
5875 beg (match-end 0)
5876 '(font-lock-fontified t face org-meta-line))
5878 ((member dc3 '(" " ""))
5879 (add-text-properties
5880 beg (match-end 0)
5881 '(font-lock-fontified t face font-lock-comment-face)))
5882 ((not (member (char-after beg) '(?\ ?\t)))
5883 ;; just any other in-buffer setting, but not indented
5884 (add-text-properties
5885 beg (match-end 0)
5886 '(font-lock-fontified t face org-meta-line))
5888 (t nil))))))
5890 (defun org-activate-angle-links (limit)
5891 "Run through the buffer and add overlays to links."
5892 (if (and (re-search-forward org-angle-link-re limit t)
5893 (not (org-in-src-block-p)))
5894 (progn
5895 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5896 (add-text-properties (match-beginning 0) (match-end 0)
5897 (list 'mouse-face 'highlight
5898 'keymap org-mouse-map))
5899 (org-rear-nonsticky-at (match-end 0))
5900 t)))
5902 (defun org-activate-footnote-links (limit)
5903 "Run through the buffer and add overlays to footnotes."
5904 (let ((fn (org-footnote-next-reference-or-definition limit)))
5905 (when fn
5906 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5907 (org-remove-flyspell-overlays-in beg end)
5908 (add-text-properties beg end
5909 (list 'mouse-face 'highlight
5910 'keymap org-mouse-map
5911 'help-echo
5912 (if (= (point-at-bol) beg)
5913 "Footnote definition"
5914 "Footnote reference")
5915 'font-lock-fontified t
5916 'font-lock-multiline t
5917 'face 'org-footnote))))))
5919 (defun org-activate-bracket-links (limit)
5920 "Run through the buffer and add overlays to bracketed links."
5921 (if (and (re-search-forward org-bracket-link-regexp limit t)
5922 (not (org-in-src-block-p)))
5923 (let* ((hl (org-match-string-no-properties 1))
5924 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5925 (ip (org-maybe-intangible
5926 (list 'invisible 'org-link
5927 'keymap org-mouse-map 'mouse-face 'highlight
5928 'font-lock-multiline t 'help-echo help
5929 'htmlize-link `(:uri ,hl))))
5930 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5931 'font-lock-multiline t 'help-echo help
5932 'htmlize-link `(:uri ,hl))))
5933 ;; We need to remove the invisible property here. Table narrowing
5934 ;; may have made some of this invisible.
5935 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5936 (remove-text-properties (match-beginning 0) (match-end 0)
5937 '(invisible nil))
5938 (if (match-end 3)
5939 (progn
5940 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5941 (org-rear-nonsticky-at (match-beginning 3))
5942 (add-text-properties (match-beginning 3) (match-end 3) vp)
5943 (org-rear-nonsticky-at (match-end 3))
5944 (add-text-properties (match-end 3) (match-end 0) ip)
5945 (org-rear-nonsticky-at (match-end 0)))
5946 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5947 (org-rear-nonsticky-at (match-beginning 1))
5948 (add-text-properties (match-beginning 1) (match-end 1) vp)
5949 (org-rear-nonsticky-at (match-end 1))
5950 (add-text-properties (match-end 1) (match-end 0) ip)
5951 (org-rear-nonsticky-at (match-end 0)))
5952 t)))
5954 (defun org-activate-dates (limit)
5955 "Run through the buffer and add overlays to dates."
5956 (if (and (re-search-forward org-tsr-regexp-both limit t)
5957 (not (equal (char-before (match-beginning 0)) 91)))
5958 (progn
5959 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5960 (add-text-properties (match-beginning 0) (match-end 0)
5961 (list 'mouse-face 'highlight
5962 'keymap org-mouse-map))
5963 (org-rear-nonsticky-at (match-end 0))
5964 (when org-display-custom-times
5965 (if (match-end 3)
5966 (org-display-custom-time (match-beginning 3) (match-end 3)))
5967 (org-display-custom-time (match-beginning 1) (match-end 1)))
5968 t)))
5970 (defvar org-target-link-regexp nil
5971 "Regular expression matching radio targets in plain text.")
5972 (make-variable-buffer-local 'org-target-link-regexp)
5973 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5974 "Regular expression matching a link target.")
5975 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5976 "Regular expression matching a radio target.")
5977 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5978 "Regular expression matching any target.")
5980 (defun org-activate-target-links (limit)
5981 "Run through the buffer and add overlays to target matches."
5982 (when org-target-link-regexp
5983 (let ((case-fold-search t))
5984 (if (re-search-forward org-target-link-regexp limit t)
5985 (progn
5986 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5987 (add-text-properties (match-beginning 0) (match-end 0)
5988 (list 'mouse-face 'highlight
5989 'keymap org-mouse-map
5990 'help-echo "Radio target link"
5991 'org-linked-text t))
5992 (org-rear-nonsticky-at (match-end 0))
5993 t)))))
5995 (defun org-update-radio-target-regexp ()
5996 "Find all radio targets in this file and update the regular expression."
5997 (interactive)
5998 (when (memq 'radio org-activate-links)
5999 (setq org-target-link-regexp
6000 (org-make-target-link-regexp (org-all-targets 'radio)))
6001 (org-restart-font-lock)))
6003 (defun org-hide-wide-columns (limit)
6004 (let (s e)
6005 (setq s (text-property-any (point) (or limit (point-max))
6006 'org-cwidth t))
6007 (when s
6008 (setq e (next-single-property-change s 'org-cwidth))
6009 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6010 (goto-char e)
6011 t)))
6013 (defvar org-latex-and-related-regexp nil
6014 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6015 (defvar org-match-substring-regexp)
6016 (defvar org-match-substring-with-braces-regexp)
6018 (defun org-compute-latex-and-related-regexp ()
6019 "Compute regular expression for LaTeX, entities and sub/superscript.
6020 Result depends on variable `org-highlight-latex-and-related'."
6021 (org-set-local
6022 'org-latex-and-related-regexp
6023 (let* ((re-sub
6024 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6025 ((eq org-use-sub-superscripts '{})
6026 (list org-match-substring-with-braces-regexp))
6027 (org-use-sub-superscripts (list org-match-substring-regexp))))
6028 (re-latex
6029 (when (memq 'latex org-highlight-latex-and-related)
6030 (let ((matchers (plist-get org-format-latex-options :matchers)))
6031 (delq nil
6032 (mapcar (lambda (x)
6033 (and (member (car x) matchers) (nth 1 x)))
6034 org-latex-regexps)))))
6035 (re-entities
6036 (when (memq 'entities org-highlight-latex-and-related)
6037 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6038 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6040 (defun org-do-latex-and-related (limit)
6041 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6042 LIMIT bounds the search for syntax to highlight. Stop at first
6043 highlighted object, if any. Return t if some highlighting was
6044 done, nil otherwise."
6045 (when (org-string-nw-p org-latex-and-related-regexp)
6046 (catch 'found
6047 (while (re-search-forward org-latex-and-related-regexp limit t)
6048 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6049 'face))
6050 '(org-code org-verbatim underline))
6051 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6052 '(?_ ?^))
6054 0)))
6055 (font-lock-prepend-text-property
6056 (+ offset (match-beginning 0)) (match-end 0)
6057 'face 'org-latex-and-related)
6058 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6059 '(font-lock-multiline t)))
6060 (throw 'found t)))
6061 nil)))
6063 (defun org-restart-font-lock ()
6064 "Restart `font-lock-mode', to force refontification."
6065 (when (and (boundp 'font-lock-mode) font-lock-mode)
6066 (font-lock-mode -1)
6067 (font-lock-mode 1)))
6069 (defun org-all-targets (&optional radio)
6070 "Return a list of all targets in this file.
6071 When optional argument RADIO is non-nil, only find radio
6072 targets."
6073 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6074 (save-excursion
6075 (goto-char (point-min))
6076 (while (re-search-forward re nil t)
6077 ;; Make sure point is really within the object.
6078 (backward-char)
6079 (let ((obj (org-element-context)))
6080 (when (memq (org-element-type obj) '(radio-target target))
6081 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6082 rtn)))
6084 (defun org-make-target-link-regexp (targets)
6085 "Make regular expression matching all strings in TARGETS.
6086 The regular expression finds the targets also if there is a line break
6087 between words."
6088 (and targets
6089 (concat
6090 "\\<\\("
6091 (mapconcat
6092 (lambda (x)
6093 (setq x (regexp-quote x))
6094 (while (string-match " +" x)
6095 (setq x (replace-match "\\s-+" t t x)))
6097 targets
6098 "\\|")
6099 "\\)\\>")))
6101 (defun org-activate-tags (limit)
6102 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6103 (progn
6104 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6105 (add-text-properties (match-beginning 1) (match-end 1)
6106 (list 'mouse-face 'highlight
6107 'keymap org-mouse-map))
6108 (org-rear-nonsticky-at (match-end 1))
6109 t)))
6111 (defun org-outline-level ()
6112 "Compute the outline level of the heading at point.
6113 If this is called at a normal headline, the level is the number of stars.
6114 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6115 (save-excursion
6116 (if (not (condition-case nil
6117 (org-back-to-heading t)
6118 (error nil)))
6120 (looking-at org-outline-regexp)
6121 (1- (- (match-end 0) (match-beginning 0))))))
6123 (defvar org-font-lock-keywords nil)
6125 (defsubst org-re-property (property &optional literal)
6126 "Return a regexp matching a PROPERTY line.
6127 Match group 3 will be set to the value if it exists."
6128 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6129 (if literal property (regexp-quote property))
6130 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6132 (defconst org-property-re
6133 (org-re-property ".*?" 'literal)
6134 "Regular expression matching a property line.
6135 There are four matching groups:
6136 1: :PROPKEY: including the leading and trailing colon,
6137 2: PROPKEY without the leading and trailing colon,
6138 3: PROPVAL without leading or trailing spaces,
6139 4: the indentation of the current line,
6140 5: trailing whitespace.")
6142 (defvar org-font-lock-hook nil
6143 "Functions to be called for special font lock stuff.")
6145 (defvar org-font-lock-set-keywords-hook nil
6146 "Functions that can manipulate `org-font-lock-extra-keywords'.
6147 This is called after `org-font-lock-extra-keywords' is defined, but before
6148 it is installed to be used by font lock. This can be useful if something
6149 needs to be inserted at a specific position in the font-lock sequence.")
6151 (defun org-font-lock-hook (limit)
6152 "Run `org-font-lock-hook' within LIMIT."
6153 (run-hook-with-args 'org-font-lock-hook limit))
6155 (defun org-set-font-lock-defaults ()
6156 "Set font lock defaults for the current buffer."
6157 (let* ((em org-fontify-emphasized-text)
6158 (lk org-activate-links)
6159 (org-font-lock-extra-keywords
6160 (list
6161 ;; Call the hook
6162 '(org-font-lock-hook)
6163 ;; Headlines
6164 `(,(if org-fontify-whole-heading-line
6165 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6166 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6167 (1 (org-get-level-face 1))
6168 (2 (org-get-level-face 2))
6169 (3 (org-get-level-face 3)))
6170 ;; Table lines
6171 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6172 (1 'org-table t))
6173 ;; Table internals
6174 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6175 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6176 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6177 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6178 ;; Drawers
6179 (list org-drawer-regexp '(0 'org-special-keyword t))
6180 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6181 ;; Properties
6182 (list org-property-re
6183 '(1 'org-special-keyword t)
6184 '(3 'org-property-value t))
6185 ;; Links
6186 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6187 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6188 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6189 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6190 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6191 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6192 (if (memq 'footnote lk) '(org-activate-footnote-links))
6193 ;; Targets.
6194 (list org-any-target-regexp '(0 'org-target t))
6195 ;; Diary sexps.
6196 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6197 ;; Macro
6198 '("{{{.+}}}" (0 'org-macro t))
6199 '(org-hide-wide-columns (0 nil append))
6200 ;; TODO keyword
6201 (list (format org-heading-keyword-regexp-format
6202 org-todo-regexp)
6203 '(2 (org-get-todo-face 2) t))
6204 ;; DONE
6205 (if org-fontify-done-headline
6206 (list (format org-heading-keyword-regexp-format
6207 (concat
6208 "\\(?:"
6209 (mapconcat 'regexp-quote org-done-keywords "\\|")
6210 "\\)"))
6211 '(2 'org-headline-done t))
6212 nil)
6213 ;; Priorities
6214 '(org-font-lock-add-priority-faces)
6215 ;; Tags
6216 '(org-font-lock-add-tag-faces)
6217 ;; Tags groups
6218 (if (and org-group-tags org-tag-groups-alist)
6219 (list (concat org-outline-regexp-bol ".+\\(:"
6220 (regexp-opt (mapcar 'car org-tag-groups-alist))
6221 ":\\).*$")
6222 '(1 'org-tag-group prepend)))
6223 ;; Special keywords
6224 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6225 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6226 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6227 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6228 ;; Emphasis
6229 (if em
6230 (if (featurep 'xemacs)
6231 '(org-do-emphasis-faces (0 nil append))
6232 '(org-do-emphasis-faces)))
6233 ;; Checkboxes
6234 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6235 1 'org-checkbox prepend)
6236 (if (cdr (assq 'checkbox org-list-automatic-rules))
6237 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6238 (0 (org-get-checkbox-statistics-face) t)))
6239 ;; Description list items
6240 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6241 1 'org-list-dt prepend)
6242 ;; ARCHIVEd headings
6243 (list (concat
6244 org-outline-regexp-bol
6245 "\\(.*:" org-archive-tag ":.*\\)")
6246 '(1 'org-archived prepend))
6247 ;; Specials
6248 '(org-do-latex-and-related)
6249 '(org-fontify-entities)
6250 '(org-raise-scripts)
6251 ;; Code
6252 '(org-activate-code (1 'org-code t))
6253 ;; COMMENT
6254 (list (format org-heading-keyword-regexp-format
6255 (concat "\\("
6256 org-comment-string "\\|" org-quote-string
6257 "\\)"))
6258 '(2 'org-special-keyword t))
6259 ;; Blocks and meta lines
6260 '(org-fontify-meta-lines-and-blocks))))
6261 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6262 (run-hooks 'org-font-lock-set-keywords-hook)
6263 ;; Now set the full font-lock-keywords
6264 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6265 (org-set-local 'font-lock-defaults
6266 '(org-font-lock-keywords t nil nil backward-paragraph))
6267 (kill-local-variable 'font-lock-keywords) nil))
6269 (defun org-toggle-pretty-entities ()
6270 "Toggle the composition display of entities as UTF8 characters."
6271 (interactive)
6272 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6273 (org-restart-font-lock)
6274 (if org-pretty-entities
6275 (message "Entities are now displayed as UTF8 characters")
6276 (save-restriction
6277 (widen)
6278 (org-decompose-region (point-min) (point-max))
6279 (message "Entities are now displayed as plain text"))))
6281 (defvar org-custom-properties-overlays nil
6282 "List of overlays used for custom properties.")
6283 (make-variable-buffer-local 'org-custom-properties-overlays)
6285 (defun org-toggle-custom-properties-visibility ()
6286 "Display or hide properties in `org-custom-properties'."
6287 (interactive)
6288 (if org-custom-properties-overlays
6289 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6290 (setq org-custom-properties-overlays nil))
6291 (unless (not org-custom-properties)
6292 (save-excursion
6293 (save-restriction
6294 (widen)
6295 (goto-char (point-min))
6296 (while (re-search-forward org-property-re nil t)
6297 (mapc (lambda(p)
6298 (when (equal p (substring (match-string 1) 1 -1))
6299 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6300 (overlay-put o 'invisible t)
6301 (overlay-put o 'org-custom-property t)
6302 (push o org-custom-properties-overlays))))
6303 org-custom-properties)))))))
6305 (defun org-fontify-entities (limit)
6306 "Find an entity to fontify."
6307 (let (ee)
6308 (when org-pretty-entities
6309 (catch 'match
6310 (while (re-search-forward
6311 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6312 limit t)
6313 (if (and (not (org-in-indented-comment-line))
6314 (setq ee (org-entity-get (match-string 1)))
6315 (= (length (nth 6 ee)) 1))
6316 (let*
6317 ((end (if (equal (match-string 2) "{}")
6318 (match-end 2)
6319 (match-end 1))))
6320 (add-text-properties
6321 (match-beginning 0) end
6322 (list 'font-lock-fontified t))
6323 (compose-region (match-beginning 0) end
6324 (nth 6 ee) nil)
6325 (backward-char 1)
6326 (throw 'match t))))
6327 nil))))
6329 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6330 "Fontify string S like in Org-mode."
6331 (with-temp-buffer
6332 (insert s)
6333 (let ((org-odd-levels-only odd-levels))
6334 (org-mode)
6335 (font-lock-fontify-buffer)
6336 (buffer-string))))
6338 (defvar org-m nil)
6339 (defvar org-l nil)
6340 (defvar org-f nil)
6341 (defun org-get-level-face (n)
6342 "Get the right face for match N in font-lock matching of headlines."
6343 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6344 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6345 (if org-cycle-level-faces
6346 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6347 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6348 (cond
6349 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6350 ((eq n 2) org-f)
6351 (t (if org-level-color-stars-only nil org-f))))
6354 (defun org-get-todo-face (kwd)
6355 "Get the right face for a TODO keyword KWD.
6356 If KWD is a number, get the corresponding match group."
6357 (if (numberp kwd) (setq kwd (match-string kwd)))
6358 (or (org-face-from-face-or-color
6359 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6360 (and (member kwd org-done-keywords) 'org-done)
6361 'org-todo))
6363 (defun org-face-from-face-or-color (context inherit face-or-color)
6364 "Create a face list that inherits INHERIT, but sets the foreground color.
6365 When FACE-OR-COLOR is not a string, just return it."
6366 (if (stringp face-or-color)
6367 (list :inherit inherit
6368 (cdr (assoc context org-faces-easy-properties))
6369 face-or-color)
6370 face-or-color))
6372 (defun org-font-lock-add-tag-faces (limit)
6373 "Add the special tag faces."
6374 (when (and org-tag-faces org-tags-special-faces-re)
6375 (while (re-search-forward org-tags-special-faces-re limit t)
6376 (add-text-properties (match-beginning 1) (match-end 1)
6377 (list 'face (org-get-tag-face 1)
6378 'font-lock-fontified t))
6379 (backward-char 1))))
6381 (defun org-font-lock-add-priority-faces (limit)
6382 "Add the special priority faces."
6383 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6384 (when (save-match-data (org-at-heading-p))
6385 (add-text-properties
6386 (match-beginning 0) (match-end 0)
6387 (list 'face (or (org-face-from-face-or-color
6388 'priority 'org-priority
6389 (cdr (assoc (char-after (match-beginning 1))
6390 org-priority-faces)))
6391 'org-priority)
6392 'font-lock-fontified t)))))
6394 (defun org-get-tag-face (kwd)
6395 "Get the right face for a TODO keyword KWD.
6396 If KWD is a number, get the corresponding match group."
6397 (if (numberp kwd) (setq kwd (match-string kwd)))
6398 (or (org-face-from-face-or-color
6399 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6400 'org-tag))
6402 (defun org-unfontify-region (beg end &optional maybe_loudly)
6403 "Remove fontification and activation overlays from links."
6404 (font-lock-default-unfontify-region beg end)
6405 (let* ((buffer-undo-list t)
6406 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6407 (inhibit-modification-hooks t)
6408 deactivate-mark buffer-file-name buffer-file-truename)
6409 (org-decompose-region beg end)
6410 (remove-text-properties beg end
6411 '(mouse-face t keymap t org-linked-text t
6412 invisible t intangible t
6413 org-no-flyspell t org-emphasis t))
6414 (org-remove-font-lock-display-properties beg end)))
6416 (defconst org-script-display '(((raise -0.3) (height 0.7))
6417 ((raise 0.3) (height 0.7))
6418 ((raise -0.5))
6419 ((raise 0.5)))
6420 "Display properties for showing superscripts and subscripts.")
6422 (defun org-remove-font-lock-display-properties (beg end)
6423 "Remove specific display properties that have been added by font lock.
6424 The will remove the raise properties that are used to show superscripts
6425 and subscripts."
6426 (let (next prop)
6427 (while (< beg end)
6428 (setq next (next-single-property-change beg 'display nil end)
6429 prop (get-text-property beg 'display))
6430 (if (member prop org-script-display)
6431 (put-text-property beg next 'display nil))
6432 (setq beg next))))
6434 (defun org-raise-scripts (limit)
6435 "Add raise properties to sub/superscripts."
6436 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6437 (if (re-search-forward
6438 (if (eq org-use-sub-superscripts t)
6439 org-match-substring-regexp
6440 org-match-substring-with-braces-regexp)
6441 limit t)
6442 (let* ((pos (point)) table-p comment-p
6443 (mpos (match-beginning 3))
6444 (emph-p (get-text-property mpos 'org-emphasis))
6445 (link-p (get-text-property mpos 'mouse-face))
6446 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6447 (goto-char (point-at-bol))
6448 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6449 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6450 (goto-char pos)
6451 ;; Handle a_b^c
6452 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6453 (if (or comment-p emph-p link-p keyw-p)
6455 (put-text-property (match-beginning 3) (match-end 0)
6456 'display
6457 (if (equal (char-after (match-beginning 2)) ?^)
6458 (nth (if table-p 3 1) org-script-display)
6459 (nth (if table-p 2 0) org-script-display)))
6460 (add-text-properties (match-beginning 2) (match-end 2)
6461 (list 'invisible t
6462 'org-dwidth t 'org-dwidth-n 1))
6463 (if (and (eq (char-after (match-beginning 3)) ?{)
6464 (eq (char-before (match-end 3)) ?}))
6465 (progn
6466 (add-text-properties
6467 (match-beginning 3) (1+ (match-beginning 3))
6468 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6469 (add-text-properties
6470 (1- (match-end 3)) (match-end 3)
6471 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6472 t)))))
6474 ;;;; Visibility cycling, including org-goto and indirect buffer
6476 ;;; Cycling
6478 (defvar org-cycle-global-status nil)
6479 (make-variable-buffer-local 'org-cycle-global-status)
6480 (put 'org-cycle-global-status 'org-state t)
6481 (defvar org-cycle-subtree-status nil)
6482 (make-variable-buffer-local 'org-cycle-subtree-status)
6483 (put 'org-cycle-subtree-status 'org-state t)
6485 (defvar org-inlinetask-min-level)
6487 (defun org-unlogged-message (&rest args)
6488 "Display a message, but avoid logging it in the *Messages* buffer."
6489 (let ((message-log-max nil))
6490 (apply 'message args)))
6492 ;;;###autoload
6493 (defun org-cycle (&optional arg)
6494 "TAB-action and visibility cycling for Org-mode.
6496 This is the command invoked in Org-mode by the TAB key. Its main purpose
6497 is outline visibility cycling, but it also invokes other actions
6498 in special contexts.
6500 - When this function is called with a prefix argument, rotate the entire
6501 buffer through 3 states (global cycling)
6502 1. OVERVIEW: Show only top-level headlines.
6503 2. CONTENTS: Show all headlines of all levels, but no body text.
6504 3. SHOW ALL: Show everything.
6505 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6506 determined by the variable `org-startup-folded', and by any VISIBILITY
6507 properties in the buffer.
6508 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6509 including any drawers.
6511 - When inside a table, re-align the table and move to the next field.
6513 - When point is at the beginning of a headline, rotate the subtree started
6514 by this line through 3 different states (local cycling)
6515 1. FOLDED: Only the main headline is shown.
6516 2. CHILDREN: The main headline and the direct children are shown.
6517 From this state, you can move to one of the children
6518 and zoom in further.
6519 3. SUBTREE: Show the entire subtree, including body text.
6520 If there is no subtree, switch directly from CHILDREN to FOLDED.
6522 - When point is at the beginning of an empty headline and the variable
6523 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6524 of the headline by demoting and promoting it to likely levels. This
6525 speeds up creation document structure by pressing TAB once or several
6526 times right after creating a new headline.
6528 - When there is a numeric prefix, go up to a heading with level ARG, do
6529 a `show-subtree' and return to the previous cursor position. If ARG
6530 is negative, go up that many levels.
6532 - When point is not at the beginning of a headline, execute the global
6533 binding for TAB, which is re-indenting the line. See the option
6534 `org-cycle-emulate-tab' for details.
6536 - Special case: if point is at the beginning of the buffer and there is
6537 no headline in line 1, this function will act as if called with prefix arg
6538 (C-u TAB, same as S-TAB) also when called without prefix arg.
6539 But only if also the variable `org-cycle-global-at-bob' is t."
6540 (interactive "P")
6541 (org-load-modules-maybe)
6542 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6543 (and org-cycle-level-after-item/entry-creation
6544 (or (org-cycle-level)
6545 (org-cycle-item-indentation))))
6546 (let* ((limit-level
6547 (or org-cycle-max-level
6548 (and (boundp 'org-inlinetask-min-level)
6549 org-inlinetask-min-level
6550 (1- org-inlinetask-min-level))))
6551 (nstars (and limit-level
6552 (if org-odd-levels-only
6553 (and limit-level (1- (* limit-level 2)))
6554 limit-level)))
6555 (org-outline-regexp
6556 (if (not (derived-mode-p 'org-mode))
6557 outline-regexp
6558 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6559 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6560 (not (looking-at org-outline-regexp))))
6561 (org-cycle-hook
6562 (if bob-special
6563 (delq 'org-optimize-window-after-visibility-change
6564 (copy-sequence org-cycle-hook))
6565 org-cycle-hook))
6566 (pos (point)))
6568 (if (or bob-special (equal arg '(4)))
6569 ;; special case: use global cycling
6570 (setq arg t))
6572 (cond
6574 ((equal arg '(16))
6575 (setq last-command 'dummy)
6576 (org-set-startup-visibility)
6577 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6579 ((equal arg '(64))
6580 (show-all)
6581 (org-unlogged-message "Entire buffer visible, including drawers"))
6583 ;; Table: enter it or move to the next field.
6584 ((org-at-table-p 'any)
6585 (if (org-at-table.el-p)
6586 (message "Use C-c ' to edit table.el tables")
6587 (if arg (org-table-edit-field t)
6588 (org-table-justify-field-maybe)
6589 (call-interactively 'org-table-next-field))))
6591 ((run-hook-with-args-until-success
6592 'org-tab-after-check-for-table-hook))
6594 ;; Global cycling: delegate to `org-cycle-internal-global'.
6595 ((eq arg t) (org-cycle-internal-global))
6597 ;; Drawers: delegate to `org-flag-drawer'.
6598 ((and org-drawers org-drawer-regexp
6599 (save-excursion
6600 (beginning-of-line 1)
6601 (looking-at org-drawer-regexp)))
6602 (org-flag-drawer ; toggle block visibility
6603 (not (get-char-property (match-end 0) 'invisible))))
6605 ;; Show-subtree, ARG levels up from here.
6606 ((integerp arg)
6607 (save-excursion
6608 (org-back-to-heading)
6609 (outline-up-heading (if (< arg 0) (- arg)
6610 (- (funcall outline-level) arg)))
6611 (org-show-subtree)))
6613 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6614 ((and (featurep 'org-inlinetask)
6615 (org-inlinetask-at-task-p)
6616 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6617 (org-inlinetask-toggle-visibility))
6619 ((org-try-cdlatex-tab))
6621 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6622 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6623 (save-excursion (beginning-of-line 1)
6624 (looking-at org-outline-regexp)))
6625 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6626 (org-cycle-internal-local))
6628 ;; From there: TAB emulation and template completion.
6629 (buffer-read-only (org-back-to-heading))
6631 ((run-hook-with-args-until-success
6632 'org-tab-after-check-for-cycling-hook))
6634 ((org-try-structure-completion))
6636 ((run-hook-with-args-until-success
6637 'org-tab-before-tab-emulation-hook))
6639 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6640 (or (not (bolp))
6641 (not (looking-at org-outline-regexp))))
6642 (call-interactively (global-key-binding "\t")))
6644 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6645 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6646 (or (and (eq org-cycle-emulate-tab 'white)
6647 (= (match-end 0) (point-at-eol)))
6648 (and (eq org-cycle-emulate-tab 'whitestart)
6649 (>= (match-end 0) pos))))
6651 (eq org-cycle-emulate-tab t))
6652 (call-interactively (global-key-binding "\t")))
6654 (t (save-excursion
6655 (org-back-to-heading)
6656 (org-cycle)))))))
6658 (defun org-cycle-internal-global ()
6659 "Do the global cycling action."
6660 ;; Hack to avoid display of messages for .org attachments in Gnus
6661 (let ((ga (string-match "\\*fontification" (buffer-name))))
6662 (cond
6663 ((and (eq last-command this-command)
6664 (eq org-cycle-global-status 'overview))
6665 ;; We just created the overview - now do table of contents
6666 ;; This can be slow in very large buffers, so indicate action
6667 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6668 (unless ga (org-unlogged-message "CONTENTS..."))
6669 (org-content)
6670 (unless ga (org-unlogged-message "CONTENTS...done"))
6671 (setq org-cycle-global-status 'contents)
6672 (run-hook-with-args 'org-cycle-hook 'contents))
6674 ((and (eq last-command this-command)
6675 (eq org-cycle-global-status 'contents))
6676 ;; We just showed the table of contents - now show everything
6677 (run-hook-with-args 'org-pre-cycle-hook 'all)
6678 (show-all)
6679 (unless ga (org-unlogged-message "SHOW ALL"))
6680 (setq org-cycle-global-status 'all)
6681 (run-hook-with-args 'org-cycle-hook 'all))
6684 ;; Default action: go to overview
6685 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6686 (org-overview)
6687 (unless ga (org-unlogged-message "OVERVIEW"))
6688 (setq org-cycle-global-status 'overview)
6689 (run-hook-with-args 'org-cycle-hook 'overview)))))
6691 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6693 (defun org-cycle-internal-local ()
6694 "Do the local cycling action."
6695 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6696 ;; First, determine end of headline (EOH), end of subtree or item
6697 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6698 (save-excursion
6699 (if (org-at-item-p)
6700 (progn
6701 (beginning-of-line)
6702 (setq struct (org-list-struct))
6703 (setq eoh (point-at-eol))
6704 (setq eos (org-list-get-item-end-before-blank (point) struct))
6705 (setq has-children (org-list-has-child-p (point) struct)))
6706 (org-back-to-heading)
6707 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6708 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6709 (setq has-children
6710 (or (save-excursion
6711 (let ((level (funcall outline-level)))
6712 (outline-next-heading)
6713 (and (org-at-heading-p t)
6714 (> (funcall outline-level) level))))
6715 (save-excursion
6716 (org-list-search-forward (org-item-beginning-re) eos t)))))
6717 ;; Determine end invisible part of buffer (EOL)
6718 (beginning-of-line 2)
6719 ;; XEmacs doesn't have `next-single-char-property-change'
6720 (if (featurep 'xemacs)
6721 (while (and (not (eobp)) ;; this is like `next-line'
6722 (get-char-property (1- (point)) 'invisible))
6723 (beginning-of-line 2))
6724 (while (and (not (eobp)) ;; this is like `next-line'
6725 (get-char-property (1- (point)) 'invisible))
6726 (goto-char (next-single-char-property-change (point) 'invisible))
6727 (and (eolp) (beginning-of-line 2))))
6728 (setq eol (point)))
6729 ;; Find out what to do next and set `this-command'
6730 (cond
6731 ((= eos eoh)
6732 ;; Nothing is hidden behind this heading
6733 (unless (org-before-first-heading-p)
6734 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6735 (org-unlogged-message "EMPTY ENTRY")
6736 (setq org-cycle-subtree-status nil)
6737 (save-excursion
6738 (goto-char eos)
6739 (outline-next-heading)
6740 (if (outline-invisible-p) (org-flag-heading nil))))
6741 ((and (or (>= eol eos)
6742 (not (string-match "\\S-" (buffer-substring eol eos))))
6743 (or has-children
6744 (not (setq children-skipped
6745 org-cycle-skip-children-state-if-no-children))))
6746 ;; Entire subtree is hidden in one line: children view
6747 (unless (org-before-first-heading-p)
6748 (run-hook-with-args 'org-pre-cycle-hook 'children))
6749 (if (org-at-item-p)
6750 (org-list-set-item-visibility (point-at-bol) struct 'children)
6751 (org-show-entry)
6752 (org-with-limited-levels (show-children))
6753 ;; FIXME: This slows down the func way too much.
6754 ;; How keep drawers hidden in subtree anyway?
6755 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6756 ;; (org-cycle-hide-drawers 'subtree))
6758 ;; Fold every list in subtree to top-level items.
6759 (when (eq org-cycle-include-plain-lists 'integrate)
6760 (save-excursion
6761 (org-back-to-heading)
6762 (while (org-list-search-forward (org-item-beginning-re) eos t)
6763 (beginning-of-line 1)
6764 (let* ((struct (org-list-struct))
6765 (prevs (org-list-prevs-alist struct))
6766 (end (org-list-get-bottom-point struct)))
6767 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6768 (org-list-get-all-items (point) struct prevs))
6769 (goto-char (if (< end eos) end eos)))))))
6770 (org-unlogged-message "CHILDREN")
6771 (save-excursion
6772 (goto-char eos)
6773 (outline-next-heading)
6774 (if (outline-invisible-p) (org-flag-heading nil)))
6775 (setq org-cycle-subtree-status 'children)
6776 (unless (org-before-first-heading-p)
6777 (run-hook-with-args 'org-cycle-hook 'children)))
6778 ((or children-skipped
6779 (and (eq last-command this-command)
6780 (eq org-cycle-subtree-status 'children)))
6781 ;; We just showed the children, or no children are there,
6782 ;; now show everything.
6783 (unless (org-before-first-heading-p)
6784 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6785 (outline-flag-region eoh eos nil)
6786 (org-unlogged-message
6787 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6788 (setq org-cycle-subtree-status 'subtree)
6789 (unless (org-before-first-heading-p)
6790 (run-hook-with-args 'org-cycle-hook 'subtree)))
6792 ;; Default action: hide the subtree.
6793 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6794 (outline-flag-region eoh eos t)
6795 (org-unlogged-message "FOLDED")
6796 (setq org-cycle-subtree-status 'folded)
6797 (unless (org-before-first-heading-p)
6798 (run-hook-with-args 'org-cycle-hook 'folded))))))
6800 ;;;###autoload
6801 (defun org-global-cycle (&optional arg)
6802 "Cycle the global visibility. For details see `org-cycle'.
6803 With \\[universal-argument] prefix arg, switch to startup visibility.
6804 With a numeric prefix, show all headlines up to that level."
6805 (interactive "P")
6806 (let ((org-cycle-include-plain-lists
6807 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6808 (cond
6809 ((integerp arg)
6810 (show-all)
6811 (hide-sublevels arg)
6812 (setq org-cycle-global-status 'contents))
6813 ((equal arg '(4))
6814 (org-set-startup-visibility)
6815 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6817 (org-cycle '(4))))))
6819 (defun org-set-startup-visibility ()
6820 "Set the visibility required by startup options and properties."
6821 (cond
6822 ((eq org-startup-folded t)
6823 (org-cycle '(4)))
6824 ((eq org-startup-folded 'content)
6825 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6826 (org-cycle '(4)) (org-cycle '(4)))))
6827 (unless (eq org-startup-folded 'showeverything)
6828 (if org-hide-block-startup (org-hide-block-all))
6829 (org-set-visibility-according-to-property 'no-cleanup)
6830 (org-cycle-hide-archived-subtrees 'all)
6831 (org-cycle-hide-drawers 'all)
6832 (org-cycle-show-empty-lines t)))
6834 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6835 "Switch subtree visibilities according to :VISIBILITY: property."
6836 (interactive)
6837 (let (org-show-entry-below state)
6838 (save-excursion
6839 (goto-char (point-min))
6840 (while (re-search-forward
6841 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6842 nil t)
6843 (setq state (match-string 1))
6844 (save-excursion
6845 (org-back-to-heading t)
6846 (hide-subtree)
6847 (org-reveal)
6848 (cond
6849 ((equal state '("fold" "folded"))
6850 (hide-subtree))
6851 ((equal state "children")
6852 (org-show-hidden-entry)
6853 (show-children))
6854 ((equal state "content")
6855 (save-excursion
6856 (save-restriction
6857 (org-narrow-to-subtree)
6858 (org-content))))
6859 ((member state '("all" "showall"))
6860 (show-subtree)))))
6861 (unless no-cleanup
6862 (org-cycle-hide-archived-subtrees 'all)
6863 (org-cycle-hide-drawers 'all)
6864 (org-cycle-show-empty-lines 'all)))))
6866 ;; This function uses outline-regexp instead of the more fundamental
6867 ;; org-outline-regexp so that org-cycle-global works outside of Org
6868 ;; buffers, where outline-regexp is needed.
6869 (defun org-overview ()
6870 "Switch to overview mode, showing only top-level headlines.
6871 Really, this shows all headlines with level equal or greater than the level
6872 of the first headline in the buffer. This is important, because if the
6873 first headline is not level one, then (hide-sublevels 1) gives confusing
6874 results."
6875 (interactive)
6876 (let ((pos (point))
6877 (level (save-excursion
6878 (goto-char (point-min))
6879 (if (re-search-forward (concat "^" outline-regexp) nil t)
6880 (progn
6881 (goto-char (match-beginning 0))
6882 (funcall outline-level))))))
6883 (and level (hide-sublevels level))
6884 (recenter '(4))
6885 (goto-char pos)))
6887 (defun org-content (&optional arg)
6888 "Show all headlines in the buffer, like a table of contents.
6889 With numerical argument N, show content up to level N."
6890 (interactive "P")
6891 (save-excursion
6892 ;; Visit all headings and show their offspring
6893 (and (integerp arg) (org-overview))
6894 (goto-char (point-max))
6895 (catch 'exit
6896 (while (and (progn (condition-case nil
6897 (outline-previous-visible-heading 1)
6898 (error (goto-char (point-min))))
6900 (looking-at org-outline-regexp))
6901 (if (integerp arg)
6902 (show-children (1- arg))
6903 (show-branches))
6904 (if (bobp) (throw 'exit nil))))))
6907 (defun org-optimize-window-after-visibility-change (state)
6908 "Adjust the window after a change in outline visibility.
6909 This function is the default value of the hook `org-cycle-hook'."
6910 (when (get-buffer-window (current-buffer))
6911 (cond
6912 ((eq state 'content) nil)
6913 ((eq state 'all) nil)
6914 ((eq state 'folded) nil)
6915 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6916 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6918 (defun org-remove-empty-overlays-at (pos)
6919 "Remove outline overlays that do not contain non-white stuff."
6920 (mapc
6921 (lambda (o)
6922 (and (eq 'outline (overlay-get o 'invisible))
6923 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6924 (overlay-end o))))
6925 (delete-overlay o)))
6926 (overlays-at pos)))
6928 (defun org-clean-visibility-after-subtree-move ()
6929 "Fix visibility issues after moving a subtree."
6930 ;; First, find a reasonable region to look at:
6931 ;; Start two siblings above, end three below
6932 (let* ((beg (save-excursion
6933 (and (org-get-last-sibling)
6934 (org-get-last-sibling))
6935 (point)))
6936 (end (save-excursion
6937 (and (org-get-next-sibling)
6938 (org-get-next-sibling)
6939 (org-get-next-sibling))
6940 (if (org-at-heading-p)
6941 (point-at-eol)
6942 (point))))
6943 (level (looking-at "\\*+"))
6944 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6945 (save-excursion
6946 (save-restriction
6947 (narrow-to-region beg end)
6948 (when re
6949 ;; Properly fold already folded siblings
6950 (goto-char (point-min))
6951 (while (re-search-forward re nil t)
6952 (if (and (not (outline-invisible-p))
6953 (save-excursion
6954 (goto-char (point-at-eol)) (outline-invisible-p)))
6955 (hide-entry))))
6956 (org-cycle-show-empty-lines 'overview)
6957 (org-cycle-hide-drawers 'overview)))))
6959 (defun org-cycle-show-empty-lines (state)
6960 "Show empty lines above all visible headlines.
6961 The region to be covered depends on STATE when called through
6962 `org-cycle-hook'. Lisp program can use t for STATE to get the
6963 entire buffer covered. Note that an empty line is only shown if there
6964 are at least `org-cycle-separator-lines' empty lines before the headline."
6965 (when (not (= org-cycle-separator-lines 0))
6966 (save-excursion
6967 (let* ((n (abs org-cycle-separator-lines))
6968 (re (cond
6969 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6970 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6971 (t (let ((ns (number-to-string (- n 2))))
6972 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6973 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6974 beg end b e)
6975 (cond
6976 ((memq state '(overview contents t))
6977 (setq beg (point-min) end (point-max)))
6978 ((memq state '(children folded))
6979 (setq beg (point) end (progn (org-end-of-subtree t t)
6980 (beginning-of-line 2)
6981 (point)))))
6982 (when beg
6983 (goto-char beg)
6984 (while (re-search-forward re end t)
6985 (unless (get-char-property (match-end 1) 'invisible)
6986 (setq e (match-end 1))
6987 (if (< org-cycle-separator-lines 0)
6988 (setq b (save-excursion
6989 (goto-char (match-beginning 0))
6990 (org-back-over-empty-lines)
6991 (if (save-excursion
6992 (goto-char (max (point-min) (1- (point))))
6993 (org-at-heading-p))
6994 (1- (point))
6995 (point))))
6996 (setq b (match-beginning 1)))
6997 (outline-flag-region b e nil)))))))
6998 ;; Never hide empty lines at the end of the file.
6999 (save-excursion
7000 (goto-char (point-max))
7001 (outline-previous-heading)
7002 (outline-end-of-heading)
7003 (if (and (looking-at "[ \t\n]+")
7004 (= (match-end 0) (point-max)))
7005 (outline-flag-region (point) (match-end 0) nil))))
7007 (defun org-show-empty-lines-in-parent ()
7008 "Move to the parent and re-show empty lines before visible headlines."
7009 (save-excursion
7010 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7011 (org-cycle-show-empty-lines context))))
7013 (defun org-files-list ()
7014 "Return `org-agenda-files' list, plus all open org-mode files.
7015 This is useful for operations that need to scan all of a user's
7016 open and agenda-wise Org files."
7017 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7018 (dolist (buf (buffer-list))
7019 (with-current-buffer buf
7020 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7021 (let ((file (expand-file-name (buffer-file-name))))
7022 (unless (member file files)
7023 (push file files))))))
7024 files))
7026 (defsubst org-entry-beginning-position ()
7027 "Return the beginning position of the current entry."
7028 (save-excursion (outline-back-to-heading t) (point)))
7030 (defsubst org-entry-end-position ()
7031 "Return the end position of the current entry."
7032 (save-excursion (outline-next-heading) (point)))
7034 (defun org-cycle-hide-drawers (state)
7035 "Re-hide all drawers after a visibility state change."
7036 (when (and (derived-mode-p 'org-mode)
7037 (not (memq state '(overview folded contents))))
7038 (save-excursion
7039 (let* ((globalp (memq state '(contents all)))
7040 (beg (if globalp (point-min) (point)))
7041 (end (if globalp (point-max)
7042 (if (eq state 'children)
7043 (save-excursion (outline-next-heading) (point))
7044 (org-end-of-subtree t)))))
7045 (goto-char beg)
7046 (while (re-search-forward org-drawer-regexp end t)
7047 (org-flag-drawer t))))))
7049 (defun org-cycle-hide-inline-tasks (state)
7050 "Re-hide inline tasks when switching to 'contents or 'children
7051 visibility state."
7052 (case state
7053 (contents
7054 (when (org-bound-and-true-p org-inlinetask-min-level)
7055 (hide-sublevels (1- org-inlinetask-min-level))))
7056 (children
7057 (when (featurep 'org-inlinetask)
7058 (save-excursion
7059 (while (and (outline-next-heading)
7060 (org-inlinetask-at-task-p))
7061 (org-inlinetask-toggle-visibility)
7062 (org-inlinetask-goto-end)))))))
7064 (defun org-flag-drawer (flag)
7065 "When FLAG is non-nil, hide the drawer we are within.
7066 Otherwise make it visible."
7067 (save-excursion
7068 (beginning-of-line 1)
7069 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7070 (let ((b (match-end 0)))
7071 (if (re-search-forward
7072 "^[ \t]*:END:"
7073 (save-excursion (outline-next-heading) (point)) t)
7074 (outline-flag-region b (point-at-eol) flag)
7075 (user-error ":END: line missing at position %s" b))))))
7077 (defun org-subtree-end-visible-p ()
7078 "Is the end of the current subtree visible?"
7079 (pos-visible-in-window-p
7080 (save-excursion (org-end-of-subtree t) (point))))
7082 (defun org-first-headline-recenter (&optional N)
7083 "Move cursor to the first headline and recenter the headline.
7084 Optional argument N means put the headline into the Nth line of the window."
7085 (goto-char (point-min))
7086 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7087 (beginning-of-line)
7088 (recenter (prefix-numeric-value N))))
7090 ;;; Saving and restoring visibility
7092 (defun org-outline-overlay-data (&optional use-markers)
7093 "Return a list of the locations of all outline overlays.
7094 These are overlays with the `invisible' property value `outline'.
7095 The return value is a list of cons cells, with start and stop
7096 positions for each overlay.
7097 If USE-MARKERS is set, return the positions as markers."
7098 (let (beg end)
7099 (save-excursion
7100 (save-restriction
7101 (widen)
7102 (delq nil
7103 (mapcar (lambda (o)
7104 (when (eq (overlay-get o 'invisible) 'outline)
7105 (setq beg (overlay-start o)
7106 end (overlay-end o))
7107 (and beg end (> end beg)
7108 (if use-markers
7109 (cons (move-marker (make-marker) beg)
7110 (move-marker (make-marker) end))
7111 (cons beg end)))))
7112 (overlays-in (point-min) (point-max))))))))
7114 (defun org-set-outline-overlay-data (data)
7115 "Create visibility overlays for all positions in DATA.
7116 DATA should have been made by `org-outline-overlay-data'."
7117 (let (o)
7118 (save-excursion
7119 (save-restriction
7120 (widen)
7121 (show-all)
7122 (mapc (lambda (c)
7123 (outline-flag-region (car c) (cdr c) t))
7124 data)))))
7126 ;;; Folding of blocks
7128 (defvar org-hide-block-overlays nil
7129 "Overlays hiding blocks.")
7130 (make-variable-buffer-local 'org-hide-block-overlays)
7132 (defun org-block-map (function &optional start end)
7133 "Call FUNCTION at the head of all source blocks in the current buffer.
7134 Optional arguments START and END can be used to limit the range."
7135 (let ((start (or start (point-min)))
7136 (end (or end (point-max))))
7137 (save-excursion
7138 (goto-char start)
7139 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7140 (save-excursion
7141 (save-match-data
7142 (goto-char (match-beginning 0))
7143 (funcall function)))))))
7145 (defun org-hide-block-toggle-all ()
7146 "Toggle the visibility of all blocks in the current buffer."
7147 (org-block-map #'org-hide-block-toggle))
7149 (defun org-hide-block-all ()
7150 "Fold all blocks in the current buffer."
7151 (interactive)
7152 (org-show-block-all)
7153 (org-block-map #'org-hide-block-toggle-maybe))
7155 (defun org-show-block-all ()
7156 "Unfold all blocks in the current buffer."
7157 (interactive)
7158 (mapc 'delete-overlay org-hide-block-overlays)
7159 (setq org-hide-block-overlays nil))
7161 (defun org-hide-block-toggle-maybe ()
7162 "Toggle visibility of block at point."
7163 (interactive)
7164 (let ((case-fold-search t))
7165 (if (save-excursion
7166 (beginning-of-line 1)
7167 (looking-at org-block-regexp))
7168 (progn (org-hide-block-toggle)
7169 t) ;; to signal that we took action
7170 nil))) ;; to signal that we did not
7172 (defun org-hide-block-toggle (&optional force)
7173 "Toggle the visibility of the current block."
7174 (interactive)
7175 (save-excursion
7176 (beginning-of-line)
7177 (if (re-search-forward org-block-regexp nil t)
7178 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7179 (end (match-end 0)) ;; end of entire body
7181 (if (memq t (mapcar (lambda (overlay)
7182 (eq (overlay-get overlay 'invisible)
7183 'org-hide-block))
7184 (overlays-at start)))
7185 (if (or (not force) (eq force 'off))
7186 (mapc (lambda (ov)
7187 (when (member ov org-hide-block-overlays)
7188 (setq org-hide-block-overlays
7189 (delq ov org-hide-block-overlays)))
7190 (when (eq (overlay-get ov 'invisible)
7191 'org-hide-block)
7192 (delete-overlay ov)))
7193 (overlays-at start)))
7194 (setq ov (make-overlay start end))
7195 (overlay-put ov 'invisible 'org-hide-block)
7196 ;; make the block accessible to isearch
7197 (overlay-put
7198 ov 'isearch-open-invisible
7199 (lambda (ov)
7200 (when (member ov org-hide-block-overlays)
7201 (setq org-hide-block-overlays
7202 (delq ov org-hide-block-overlays)))
7203 (when (eq (overlay-get ov 'invisible)
7204 'org-hide-block)
7205 (delete-overlay ov))))
7206 (push ov org-hide-block-overlays)))
7207 (user-error "Not looking at a source block"))))
7209 ;; org-tab-after-check-for-cycling-hook
7210 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7211 ;; Remove overlays when changing major mode
7212 (add-hook 'org-mode-hook
7213 (lambda () (org-add-hook 'change-major-mode-hook
7214 'org-show-block-all 'append 'local)))
7216 ;;; Org-goto
7218 (defvar org-goto-window-configuration nil)
7219 (defvar org-goto-marker nil)
7220 (defvar org-goto-map)
7221 (defun org-goto-map ()
7222 "Set the keymap `org-goto'."
7223 (setq org-goto-map
7224 (let ((map (make-sparse-keymap)))
7225 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7226 mouse-drag-region universal-argument org-occur))
7227 cmd)
7228 (while (setq cmd (pop cmds))
7229 (substitute-key-definition cmd cmd map global-map)))
7230 (suppress-keymap map)
7231 (org-defkey map "\C-m" 'org-goto-ret)
7232 (org-defkey map [(return)] 'org-goto-ret)
7233 (org-defkey map [(left)] 'org-goto-left)
7234 (org-defkey map [(right)] 'org-goto-right)
7235 (org-defkey map [(control ?g)] 'org-goto-quit)
7236 (org-defkey map "\C-i" 'org-cycle)
7237 (org-defkey map [(tab)] 'org-cycle)
7238 (org-defkey map [(down)] 'outline-next-visible-heading)
7239 (org-defkey map [(up)] 'outline-previous-visible-heading)
7240 (if org-goto-auto-isearch
7241 (if (fboundp 'define-key-after)
7242 (define-key-after map [t] 'org-goto-local-auto-isearch)
7243 nil)
7244 (org-defkey map "q" 'org-goto-quit)
7245 (org-defkey map "n" 'outline-next-visible-heading)
7246 (org-defkey map "p" 'outline-previous-visible-heading)
7247 (org-defkey map "f" 'outline-forward-same-level)
7248 (org-defkey map "b" 'outline-backward-same-level)
7249 (org-defkey map "u" 'outline-up-heading))
7250 (org-defkey map "/" 'org-occur)
7251 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7252 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7253 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7254 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7255 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7256 map)))
7258 (defconst org-goto-help
7259 "Browse buffer copy, to find location or copy text.%s
7260 RET=jump to location C-g=quit and return to previous location
7261 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7263 (defvar org-goto-start-pos) ; dynamically scoped parameter
7265 (defun org-goto (&optional alternative-interface)
7266 "Look up a different location in the current file, keeping current visibility.
7268 When you want look-up or go to a different location in a
7269 document, the fastest way is often to fold the entire buffer and
7270 then dive into the tree. This method has the disadvantage, that
7271 the previous location will be folded, which may not be what you
7272 want.
7274 This command works around this by showing a copy of the current
7275 buffer in an indirect buffer, in overview mode. You can dive
7276 into the tree in that copy, use org-occur and incremental search
7277 to find a location. When pressing RET or `Q', the command
7278 returns to the original buffer in which the visibility is still
7279 unchanged. After RET it will also jump to the location selected
7280 in the indirect buffer and expose the headline hierarchy above.
7282 With a prefix argument, use the alternative interface: e.g. if
7283 `org-goto-interface' is 'outline use 'outline-path-completion."
7284 (interactive "P")
7285 (org-goto-map)
7286 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7287 (org-refile-use-outline-path t)
7288 (org-refile-target-verify-function nil)
7289 (interface
7290 (if (not alternative-interface)
7291 org-goto-interface
7292 (if (eq org-goto-interface 'outline)
7293 'outline-path-completion
7294 'outline)))
7295 (org-goto-start-pos (point))
7296 (selected-point
7297 (if (eq interface 'outline)
7298 (car (org-get-location (current-buffer) org-goto-help))
7299 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7300 (org-refile-check-position pa)
7301 (nth 3 pa)))))
7302 (if selected-point
7303 (progn
7304 (org-mark-ring-push org-goto-start-pos)
7305 (goto-char selected-point)
7306 (if (or (outline-invisible-p) (org-invisible-p2))
7307 (org-show-context 'org-goto)))
7308 (message "Quit"))))
7310 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7311 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7312 (defvar org-goto-local-auto-isearch-map) ; defined below
7314 (defun org-get-location (buf help)
7315 "Let the user select a location in the Org-mode buffer BUF.
7316 This function uses a recursive edit. It returns the selected position
7317 or nil."
7318 (org-no-popups
7319 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7320 (isearch-hide-immediately nil)
7321 (isearch-search-fun-function
7322 (lambda () 'org-goto-local-search-headings))
7323 (org-goto-selected-point org-goto-exit-command))
7324 (save-excursion
7325 (save-window-excursion
7326 (delete-other-windows)
7327 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7328 (org-pop-to-buffer-same-window
7329 (condition-case nil
7330 (make-indirect-buffer (current-buffer) "*org-goto*")
7331 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7332 (with-output-to-temp-buffer "*Org Help*"
7333 (princ (format help (if org-goto-auto-isearch
7334 " Just type for auto-isearch."
7335 " n/p/f/b/u to navigate, q to quit."))))
7336 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7337 (setq buffer-read-only nil)
7338 (let ((org-startup-truncated t)
7339 (org-startup-folded nil)
7340 (org-startup-align-all-tables nil))
7341 (org-mode)
7342 (org-overview))
7343 (setq buffer-read-only t)
7344 (if (and (boundp 'org-goto-start-pos)
7345 (integer-or-marker-p org-goto-start-pos))
7346 (let ((org-show-hierarchy-above t)
7347 (org-show-siblings t)
7348 (org-show-following-heading t))
7349 (goto-char org-goto-start-pos)
7350 (and (outline-invisible-p) (org-show-context)))
7351 (goto-char (point-min)))
7352 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7353 (message "Select location and press RET")
7354 (use-local-map org-goto-map)
7355 (recursive-edit)))
7356 (kill-buffer "*org-goto*")
7357 (cons org-goto-selected-point org-goto-exit-command))))
7359 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7360 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7361 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7362 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7364 (defun org-goto-local-search-headings (string bound noerror)
7365 "Search and make sure that any matches are in headlines."
7366 (catch 'return
7367 (while (if isearch-forward
7368 (search-forward string bound noerror)
7369 (search-backward string bound noerror))
7370 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7371 (and (member :headline context)
7372 (not (member :tags context))))
7373 (throw 'return (point))))))
7375 (defun org-goto-local-auto-isearch ()
7376 "Start isearch."
7377 (interactive)
7378 (goto-char (point-min))
7379 (let ((keys (this-command-keys)))
7380 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7381 (isearch-mode t)
7382 (isearch-process-search-char (string-to-char keys)))))
7384 (defun org-goto-ret (&optional arg)
7385 "Finish `org-goto' by going to the new location."
7386 (interactive "P")
7387 (setq org-goto-selected-point (point)
7388 org-goto-exit-command 'return)
7389 (throw 'exit nil))
7391 (defun org-goto-left ()
7392 "Finish `org-goto' by going to the new location."
7393 (interactive)
7394 (if (org-at-heading-p)
7395 (progn
7396 (beginning-of-line 1)
7397 (setq org-goto-selected-point (point)
7398 org-goto-exit-command 'left)
7399 (throw 'exit nil))
7400 (user-error "Not on a heading")))
7402 (defun org-goto-right ()
7403 "Finish `org-goto' by going to the new location."
7404 (interactive)
7405 (if (org-at-heading-p)
7406 (progn
7407 (setq org-goto-selected-point (point)
7408 org-goto-exit-command 'right)
7409 (throw 'exit nil))
7410 (user-error "Not on a heading")))
7412 (defun org-goto-quit ()
7413 "Finish `org-goto' without cursor motion."
7414 (interactive)
7415 (setq org-goto-selected-point nil)
7416 (setq org-goto-exit-command 'quit)
7417 (throw 'exit nil))
7419 ;;; Indirect buffer display of subtrees
7421 (defvar org-indirect-dedicated-frame nil
7422 "This is the frame being used for indirect tree display.")
7423 (defvar org-last-indirect-buffer nil)
7425 (defun org-tree-to-indirect-buffer (&optional arg)
7426 "Create indirect buffer and narrow it to current subtree.
7427 With a numerical prefix ARG, go up to this level and then take that tree.
7428 If ARG is negative, go up that many levels.
7430 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7431 indirect buffer previously made with this command, to avoid proliferation of
7432 indirect buffers. However, when you call the command with a \
7433 \\[universal-argument] prefix, or
7434 when `org-indirect-buffer-display' is `new-frame', the last buffer
7435 is kept so that you can work with several indirect buffers at the same time.
7436 If `org-indirect-buffer-display' is `dedicated-frame', the \
7437 \\[universal-argument] prefix also
7438 requests that a new frame be made for the new buffer, so that the dedicated
7439 frame is not changed."
7440 (interactive "P")
7441 (let ((cbuf (current-buffer))
7442 (cwin (selected-window))
7443 (pos (point))
7444 beg end level heading ibuf)
7445 (save-excursion
7446 (org-back-to-heading t)
7447 (when (numberp arg)
7448 (setq level (org-outline-level))
7449 (if (< arg 0) (setq arg (+ level arg)))
7450 (while (> (setq level (org-outline-level)) arg)
7451 (org-up-heading-safe)))
7452 (setq beg (point)
7453 heading (org-get-heading))
7454 (org-end-of-subtree t t)
7455 (if (org-at-heading-p) (backward-char 1))
7456 (setq end (point)))
7457 (if (and (buffer-live-p org-last-indirect-buffer)
7458 (not (eq org-indirect-buffer-display 'new-frame))
7459 (not arg))
7460 (kill-buffer org-last-indirect-buffer))
7461 (setq ibuf (org-get-indirect-buffer cbuf)
7462 org-last-indirect-buffer ibuf)
7463 (cond
7464 ((or (eq org-indirect-buffer-display 'new-frame)
7465 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7466 (select-frame (make-frame))
7467 (delete-other-windows)
7468 (org-pop-to-buffer-same-window ibuf)
7469 (org-set-frame-title heading))
7470 ((eq org-indirect-buffer-display 'dedicated-frame)
7471 (raise-frame
7472 (select-frame (or (and org-indirect-dedicated-frame
7473 (frame-live-p org-indirect-dedicated-frame)
7474 org-indirect-dedicated-frame)
7475 (setq org-indirect-dedicated-frame (make-frame)))))
7476 (delete-other-windows)
7477 (org-pop-to-buffer-same-window ibuf)
7478 (org-set-frame-title (concat "Indirect: " heading)))
7479 ((eq org-indirect-buffer-display 'current-window)
7480 (org-pop-to-buffer-same-window ibuf))
7481 ((eq org-indirect-buffer-display 'other-window)
7482 (pop-to-buffer ibuf))
7483 (t (error "Invalid value")))
7484 (if (featurep 'xemacs)
7485 (save-excursion (org-mode) (turn-on-font-lock)))
7486 (narrow-to-region beg end)
7487 (show-all)
7488 (goto-char pos)
7489 (run-hook-with-args 'org-cycle-hook 'all)
7490 (and (window-live-p cwin) (select-window cwin))))
7492 (defun org-get-indirect-buffer (&optional buffer)
7493 (setq buffer (or buffer (current-buffer)))
7494 (let ((n 1) (base (buffer-name buffer)) bname)
7495 (while (buffer-live-p
7496 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7497 (setq n (1+ n)))
7498 (condition-case nil
7499 (make-indirect-buffer buffer bname 'clone)
7500 (error (make-indirect-buffer buffer bname)))))
7502 (defun org-set-frame-title (title)
7503 "Set the title of the current frame to the string TITLE."
7504 ;; FIXME: how to name a single frame in XEmacs???
7505 (unless (featurep 'xemacs)
7506 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7508 ;;;; Structure editing
7510 ;;; Inserting headlines
7512 (defun org-previous-line-empty-p (&optional next)
7513 "Is the previous line a blank line?
7514 When NEXT is non-nil, check the next line instead."
7515 (save-excursion
7516 (and (not (bobp))
7517 (or (beginning-of-line (if next 2 0)) t)
7518 (save-match-data
7519 (looking-at "[ \t]*$")))))
7521 (defun org-insert-heading (&optional arg invisible-ok)
7522 "Insert a new heading or item with same depth at point.
7523 If point is in a plain list and ARG is nil, create a new list item.
7524 With one universal prefix argument, insert a heading even in lists.
7525 With two universal prefix arguments, insert the heading at the end
7526 of the parent subtree.
7528 If point is at the beginning of a headline, insert a sibling before
7529 the current headline. If point is not at the beginning, split the line
7530 and create a new headline with the text in the current line after point
7531 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7533 If point is at the beginning of a normal line, turn this line into
7534 a heading.
7536 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7537 This is important for non-interactive uses of the command."
7538 (interactive "P")
7539 (if (org-called-interactively-p 'any) (org-reveal))
7540 (let ((itemp (org-in-item-p))
7541 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7542 (respect-content (or org-insert-heading-respect-content
7543 (equal arg '(16))))
7544 (initial-content "")
7545 (adjust-empty-lines t))
7547 (cond
7549 ((or (= (buffer-size) 0)
7550 (and (not (save-excursion
7551 (and (ignore-errors (org-back-to-heading invisible-ok))
7552 (org-at-heading-p))))
7553 (or arg (not itemp))))
7554 ;; At beginning of buffer or so high up that only a heading
7555 ;; makes sense.
7556 (insert
7557 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7558 (if (org-in-src-block-p) ",* " "* "))
7559 (run-hooks 'org-insert-heading-hook))
7561 ((and itemp (not (equal arg '(4))))
7562 ;; Insert an item
7563 (org-insert-item))
7566 ;; Insert a heading
7567 (save-restriction
7568 (widen)
7569 (let* ((level nil)
7570 (on-heading (org-at-heading-p))
7571 (empty-line-p (if on-heading
7572 (org-previous-line-empty-p)
7573 ;; We will decide later
7574 nil))
7575 ;; Get a level string to fall back on
7576 (fix-level
7577 (save-excursion
7578 (org-back-to-heading t)
7579 (if (org-previous-line-empty-p) (setq empty-line-p t))
7580 (looking-at org-outline-regexp)
7581 (make-string (1- (length (match-string 0))) ?*)))
7582 (stars
7583 (save-excursion
7584 (condition-case nil
7585 (progn
7586 (org-back-to-heading invisible-ok)
7587 (when (and (not on-heading)
7588 (featurep 'org-inlinetask)
7589 (integerp org-inlinetask-min-level)
7590 (>= (length (match-string 0))
7591 org-inlinetask-min-level))
7592 ;; Find a heading level before the inline task
7593 (while (and (setq level (org-up-heading-safe))
7594 (>= level org-inlinetask-min-level)))
7595 (if (org-at-heading-p)
7596 (org-back-to-heading invisible-ok)
7597 (error "This should not happen")))
7598 (unless (and (save-excursion
7599 (save-match-data
7600 (org-backward-heading-same-level
7601 1 invisible-ok))
7602 (= (point) (match-beginning 0)))
7603 (not (org-previous-line-empty-p t)))
7604 (setq empty-line-p (or empty-line-p
7605 (org-previous-line-empty-p))))
7606 (match-string 0))
7607 (error (or fix-level "* ")))))
7608 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7609 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7610 pos hide-previous previous-pos)
7612 ;; If we insert after content, move there and clean up whitespace
7613 (when respect-content
7614 (org-end-of-subtree nil t)
7615 (skip-chars-backward " \r\n")
7616 (and (looking-at "[ \t]+") (replace-match ""))
7617 (unless (eobp) (forward-char 1))
7618 (when (looking-at "^\\*")
7619 (unless (bobp) (backward-char 1))
7620 (insert "\n")))
7622 ;; If we are splitting, grab the text that should be moved to the new headline
7623 (when may-split
7624 (if (org-on-heading-p)
7625 ;; This is a heading, we split intelligently (keeping tags)
7626 (let ((pos (point)))
7627 (goto-char (point-at-bol))
7628 (unless (looking-at org-complex-heading-regexp)
7629 (error "This should not happen"))
7630 (when (and (match-beginning 4)
7631 (> pos (match-beginning 4))
7632 (< pos (match-end 4)))
7633 (setq initial-content (buffer-substring pos (match-end 4)))
7634 (goto-char pos)
7635 (delete-region (point) (match-end 4))
7636 (if (looking-at "[ \t]*$")
7637 (replace-match "")
7638 (insert (make-string (length initial-content) ?\ )))
7639 (setq initial-content (org-trim initial-content)))
7640 (goto-char pos))
7641 ;; a normal line
7642 (unless (bolp)
7643 (setq initial-content (buffer-substring (point) (point-at-eol)))
7644 (delete-region (point) (point-at-eol))
7645 (setq initial-content (org-trim initial-content)))))
7647 ;; If we are at the beginning of the line, insert before it. Else after
7648 (cond
7649 ((and (bolp) (looking-at "[ \t]*$")))
7650 ((and (bolp) (not (looking-at "[ \t]*$")))
7651 (open-line 1))
7653 (goto-char (point-at-eol))
7654 (insert "\n")))
7656 ;; Insert the new heading
7657 (insert stars)
7658 (just-one-space)
7659 (insert initial-content)
7660 (when adjust-empty-lines
7661 (if (or (not blank)
7662 (and blank (not (org-previous-line-empty-p))))
7663 (org-N-empty-lines-before-current (if blank 1 0))))
7664 (run-hooks 'org-insert-heading-hook)))))))
7666 (defun org-N-empty-lines-before-current (N)
7667 "Make the number of empty lines before current exactly N.
7668 So this will delete or add empty lines."
7669 (save-excursion
7670 (goto-char (point-at-bol))
7671 (if (looking-back "\\s-+" nil 'greedy)
7672 (replace-match ""))
7673 (or (bobp) (insert "\n"))
7674 (while (> N 0)
7675 (insert "\n")
7676 (setq N (1- N)))))
7678 (defun org-get-heading (&optional no-tags no-todo)
7679 "Return the heading of the current entry, without the stars.
7680 When NO-TAGS is non-nil, don't include tags.
7681 When NO-TODO is non-nil, don't include TODO keywords."
7682 (save-excursion
7683 (org-back-to-heading t)
7684 (cond
7685 ((and no-tags no-todo)
7686 (looking-at org-complex-heading-regexp)
7687 (match-string 4))
7688 (no-tags
7689 (looking-at (concat org-outline-regexp
7690 "\\(.*?\\)"
7691 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7692 (match-string 1))
7693 (no-todo
7694 (looking-at org-todo-line-regexp)
7695 (match-string 3))
7696 (t (looking-at org-heading-regexp)
7697 (match-string 2)))))
7699 (defvar orgstruct-mode) ; defined below
7701 (defun org-heading-components ()
7702 "Return the components of the current heading.
7703 This is a list with the following elements:
7704 - the level as an integer
7705 - the reduced level, different if `org-odd-levels-only' is set.
7706 - the TODO keyword, or nil
7707 - the priority character, like ?A, or nil if no priority is given
7708 - the headline text itself, or the tags string if no headline text
7709 - the tags string, or nil."
7710 (save-excursion
7711 (org-back-to-heading t)
7712 (if (let (case-fold-search)
7713 (looking-at
7714 (if orgstruct-mode
7715 org-heading-regexp
7716 org-complex-heading-regexp)))
7717 (if orgstruct-mode
7718 (list (length (match-string 1))
7719 (org-reduced-level (length (match-string 1)))
7722 (match-string 2)
7723 nil)
7724 (list (length (match-string 1))
7725 (org-reduced-level (length (match-string 1)))
7726 (org-match-string-no-properties 2)
7727 (and (match-end 3) (aref (match-string 3) 2))
7728 (org-match-string-no-properties 4)
7729 (org-match-string-no-properties 5))))))
7731 (defun org-get-entry ()
7732 "Get the entry text, after heading, entire subtree."
7733 (save-excursion
7734 (org-back-to-heading t)
7735 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7737 (defun org-insert-heading-after-current ()
7738 "Insert a new heading with same level as current, after current subtree."
7739 (interactive)
7740 (org-back-to-heading)
7741 (org-insert-heading)
7742 (org-move-subtree-down)
7743 (end-of-line 1))
7745 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7746 "Insert heading with `org-insert-heading-respect-content' set to t."
7747 (interactive "P")
7748 (let ((org-insert-heading-respect-content t))
7749 (org-insert-heading '(4) invisible-ok)))
7751 (defun org-insert-todo-heading-respect-content (&optional force-state)
7752 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7753 (interactive "P")
7754 (let ((org-insert-heading-respect-content t))
7755 (org-insert-todo-heading force-state '(4))))
7757 (defun org-insert-todo-heading (arg &optional force-heading)
7758 "Insert a new heading with the same level and TODO state as current heading.
7759 If the heading has no TODO state, or if the state is DONE, use the first
7760 state (TODO by default). Also one prefix arg, force first state. With two
7761 prefix args, force inserting at the end of the parent subtree."
7762 (interactive "P")
7763 (when (or force-heading (not (org-insert-item 'checkbox)))
7764 (org-insert-heading (or (and (equal arg '(16)) '(16))
7765 force-heading))
7766 (save-excursion
7767 (org-back-to-heading)
7768 (outline-previous-heading)
7769 (looking-at org-todo-line-regexp))
7770 (let*
7771 ((new-mark-x
7772 (if (or arg
7773 (not (match-beginning 2))
7774 (member (match-string 2) org-done-keywords))
7775 (car org-todo-keywords-1)
7776 (match-string 2)))
7777 (new-mark
7779 (run-hook-with-args-until-success
7780 'org-todo-get-default-hook new-mark-x nil)
7781 new-mark-x)))
7782 (beginning-of-line 1)
7783 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7784 (if org-treat-insert-todo-heading-as-state-change
7785 (org-todo new-mark)
7786 (insert new-mark " "))))
7787 (when org-provide-todo-statistics
7788 (org-update-parent-todo-statistics))))
7790 (defun org-insert-subheading (arg)
7791 "Insert a new subheading and demote it.
7792 Works for outline headings and for plain lists alike."
7793 (interactive "P")
7794 (org-insert-heading arg)
7795 (cond
7796 ((org-at-heading-p) (org-do-demote))
7797 ((org-at-item-p) (org-indent-item))))
7799 (defun org-insert-todo-subheading (arg)
7800 "Insert a new subheading with TODO keyword or checkbox and demote it.
7801 Works for outline headings and for plain lists alike."
7802 (interactive "P")
7803 (org-insert-todo-heading arg)
7804 (cond
7805 ((org-at-heading-p) (org-do-demote))
7806 ((org-at-item-p) (org-indent-item))))
7808 ;;; Promotion and Demotion
7810 (defvar org-after-demote-entry-hook nil
7811 "Hook run after an entry has been demoted.
7812 The cursor will be at the beginning of the entry.
7813 When a subtree is being demoted, the hook will be called for each node.")
7815 (defvar org-after-promote-entry-hook nil
7816 "Hook run after an entry has been promoted.
7817 The cursor will be at the beginning of the entry.
7818 When a subtree is being promoted, the hook will be called for each node.")
7820 (defun org-promote-subtree ()
7821 "Promote the entire subtree.
7822 See also `org-promote'."
7823 (interactive)
7824 (save-excursion
7825 (org-with-limited-levels (org-map-tree 'org-promote)))
7826 (org-fix-position-after-promote))
7828 (defun org-demote-subtree ()
7829 "Demote the entire subtree. See `org-demote'.
7830 See also `org-promote'."
7831 (interactive)
7832 (save-excursion
7833 (org-with-limited-levels (org-map-tree 'org-demote)))
7834 (org-fix-position-after-promote))
7837 (defun org-do-promote ()
7838 "Promote the current heading higher up the tree.
7839 If the region is active in `transient-mark-mode', promote all headings
7840 in the region."
7841 (interactive)
7842 (save-excursion
7843 (if (org-region-active-p)
7844 (org-map-region 'org-promote (region-beginning) (region-end))
7845 (org-promote)))
7846 (org-fix-position-after-promote))
7848 (defun org-do-demote ()
7849 "Demote the current heading lower down the tree.
7850 If the region is active in `transient-mark-mode', demote all headings
7851 in the region."
7852 (interactive)
7853 (save-excursion
7854 (if (org-region-active-p)
7855 (org-map-region 'org-demote (region-beginning) (region-end))
7856 (org-demote)))
7857 (org-fix-position-after-promote))
7859 (defun org-fix-position-after-promote ()
7860 "Make sure that after pro/demotion cursor position is right."
7861 (let ((pos (point)))
7862 (when (save-excursion
7863 (beginning-of-line 1)
7864 (looking-at org-todo-line-regexp)
7865 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7866 (cond ((eobp) (insert " "))
7867 ((eolp) (insert " "))
7868 ((equal (char-after) ?\ ) (forward-char 1))))))
7870 (defun org-current-level ()
7871 "Return the level of the current entry, or nil if before the first headline.
7872 The level is the number of stars at the beginning of the headline."
7873 (save-excursion
7874 (org-with-limited-levels
7875 (if (ignore-errors (org-back-to-heading t))
7876 (funcall outline-level)))))
7878 (defun org-get-previous-line-level ()
7879 "Return the outline depth of the last headline before the current line.
7880 Returns 0 for the first headline in the buffer, and nil if before the
7881 first headline."
7882 (let ((current-level (org-current-level))
7883 (prev-level (when (> (line-number-at-pos) 1)
7884 (save-excursion
7885 (beginning-of-line 0)
7886 (org-current-level)))))
7887 (cond ((null current-level) nil) ; Before first headline
7888 ((null prev-level) 0) ; At first headline
7889 (prev-level))))
7891 (defun org-reduced-level (l)
7892 "Compute the effective level of a heading.
7893 This takes into account the setting of `org-odd-levels-only'."
7894 (cond
7895 ((zerop l) 0)
7896 (org-odd-levels-only (1+ (floor (/ l 2))))
7897 (t l)))
7899 (defun org-level-increment ()
7900 "Return the number of stars that will be added or removed at a
7901 time to headlines when structure editing, based on the value of
7902 `org-odd-levels-only'."
7903 (if org-odd-levels-only 2 1))
7905 (defun org-get-valid-level (level &optional change)
7906 "Rectify a level change under the influence of `org-odd-levels-only'
7907 LEVEL is a current level, CHANGE is by how much the level should be
7908 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7909 even level numbers will become the next higher odd number."
7910 (if org-odd-levels-only
7911 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7912 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7913 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7914 (max 1 (+ level (or change 0)))))
7916 (if (boundp 'define-obsolete-function-alias)
7917 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7918 (define-obsolete-function-alias 'org-get-legal-level
7919 'org-get-valid-level)
7920 (define-obsolete-function-alias 'org-get-legal-level
7921 'org-get-valid-level "23.1")))
7923 (defun org-promote ()
7924 "Promote the current heading higher up the tree.
7925 If the region is active in `transient-mark-mode', promote all headings
7926 in the region."
7927 (org-back-to-heading t)
7928 (let* ((level (save-match-data (funcall outline-level)))
7929 (after-change-functions (remove 'flyspell-after-change-function
7930 after-change-functions))
7931 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7932 (diff (abs (- level (length up-head) -1))))
7933 (cond ((and (= level 1) org-called-with-limited-levels
7934 org-allow-promoting-top-level-subtree)
7935 (replace-match "# " nil t))
7936 ((= level 1)
7937 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7938 (t (replace-match up-head nil t)))
7939 ;; Fixup tag positioning
7940 (unless (= level 1)
7941 (and org-auto-align-tags (org-set-tags nil t))
7942 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7943 (run-hooks 'org-after-promote-entry-hook)))
7945 (defun org-demote ()
7946 "Demote the current heading lower down the tree.
7947 If the region is active in `transient-mark-mode', demote all headings
7948 in the region."
7949 (org-back-to-heading t)
7950 (let* ((level (save-match-data (funcall outline-level)))
7951 (after-change-functions (remove 'flyspell-after-change-function
7952 after-change-functions))
7953 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7954 (diff (abs (- level (length down-head) -1))))
7955 (replace-match down-head nil t)
7956 ;; Fixup tag positioning
7957 (and org-auto-align-tags (org-set-tags nil t))
7958 (if org-adapt-indentation (org-fixup-indentation diff))
7959 (run-hooks 'org-after-demote-entry-hook)))
7961 (defun org-cycle-level ()
7962 "Cycle the level of an empty headline through possible states.
7963 This goes first to child, then to parent, level, then up the hierarchy.
7964 After top level, it switches back to sibling level."
7965 (interactive)
7966 (let ((org-adapt-indentation nil))
7967 (when (org-point-at-end-of-empty-headline)
7968 (setq this-command 'org-cycle-level) ; Only needed for caching
7969 (let ((cur-level (org-current-level))
7970 (prev-level (org-get-previous-line-level)))
7971 (cond
7972 ;; If first headline in file, promote to top-level.
7973 ((= prev-level 0)
7974 (loop repeat (/ (- cur-level 1) (org-level-increment))
7975 do (org-do-promote)))
7976 ;; If same level as prev, demote one.
7977 ((= prev-level cur-level)
7978 (org-do-demote))
7979 ;; If parent is top-level, promote to top level if not already.
7980 ((= prev-level 1)
7981 (loop repeat (/ (- cur-level 1) (org-level-increment))
7982 do (org-do-promote)))
7983 ;; If top-level, return to prev-level.
7984 ((= cur-level 1)
7985 (loop repeat (/ (- prev-level 1) (org-level-increment))
7986 do (org-do-demote)))
7987 ;; If less than prev-level, promote one.
7988 ((< cur-level prev-level)
7989 (org-do-promote))
7990 ;; If deeper than prev-level, promote until higher than
7991 ;; prev-level.
7992 ((> cur-level prev-level)
7993 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7994 do (org-do-promote))))
7995 t))))
7997 (defun org-map-tree (fun)
7998 "Call FUN for every heading underneath the current one."
7999 (org-back-to-heading)
8000 (let ((level (funcall outline-level)))
8001 (save-excursion
8002 (funcall fun)
8003 (while (and (progn
8004 (outline-next-heading)
8005 (> (funcall outline-level) level))
8006 (not (eobp)))
8007 (funcall fun)))))
8009 (defun org-map-region (fun beg end)
8010 "Call FUN for every heading between BEG and END."
8011 (let ((org-ignore-region t))
8012 (save-excursion
8013 (setq end (copy-marker end))
8014 (goto-char beg)
8015 (if (and (re-search-forward org-outline-regexp-bol nil t)
8016 (< (point) end))
8017 (funcall fun))
8018 (while (and (progn
8019 (outline-next-heading)
8020 (< (point) end))
8021 (not (eobp)))
8022 (funcall fun)))))
8024 (defvar org-property-end-re) ; silence byte-compiler
8025 (defun org-fixup-indentation (diff)
8026 "Change the indentation in the current entry by DIFF.
8027 However, if any line in the current entry has no indentation, or if it
8028 would end up with no indentation after the change, nothing at all is done."
8029 (save-excursion
8030 (let ((end (save-excursion (outline-next-heading)
8031 (point-marker)))
8032 (prohibit (if (> diff 0)
8033 "^\\S-"
8034 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8035 col)
8036 (unless (save-excursion (end-of-line 1)
8037 (re-search-forward prohibit end t))
8038 (while (and (< (point) end)
8039 (re-search-forward "^[ \t]+" end t))
8040 (goto-char (match-end 0))
8041 (setq col (current-column))
8042 (if (< diff 0) (replace-match ""))
8043 (org-indent-to-column (+ diff col))))
8044 (move-marker end nil))))
8046 (defun org-convert-to-odd-levels ()
8047 "Convert an org-mode file with all levels allowed to one with odd levels.
8048 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8049 level 5 etc."
8050 (interactive)
8051 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8052 (let ((outline-level 'org-outline-level)
8053 (org-odd-levels-only nil) n)
8054 (save-excursion
8055 (goto-char (point-min))
8056 (while (re-search-forward "^\\*\\*+ " nil t)
8057 (setq n (- (length (match-string 0)) 2))
8058 (while (>= (setq n (1- n)) 0)
8059 (org-demote))
8060 (end-of-line 1))))))
8062 (defun org-convert-to-oddeven-levels ()
8063 "Convert an org-mode file with only odd levels to one with odd/even levels.
8064 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8065 file contains a section with an even level, conversion would
8066 destroy the structure of the file. An error is signaled in this
8067 case."
8068 (interactive)
8069 (goto-char (point-min))
8070 ;; First check if there are no even levels
8071 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8072 (org-show-context t)
8073 (error "Not all levels are odd in this file. Conversion not possible"))
8074 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8075 (let ((outline-regexp org-outline-regexp)
8076 (outline-level 'org-outline-level)
8077 (org-odd-levels-only nil) n)
8078 (save-excursion
8079 (goto-char (point-min))
8080 (while (re-search-forward "^\\*\\*+ " nil t)
8081 (setq n (/ (1- (length (match-string 0))) 2))
8082 (while (>= (setq n (1- n)) 0)
8083 (org-promote))
8084 (end-of-line 1))))))
8086 (defun org-tr-level (n)
8087 "Make N odd if required."
8088 (if org-odd-levels-only (1+ (/ n 2)) n))
8090 ;;; Vertical tree motion, cutting and pasting of subtrees
8092 (defun org-move-subtree-up (&optional arg)
8093 "Move the current subtree up past ARG headlines of the same level."
8094 (interactive "p")
8095 (org-move-subtree-down (- (prefix-numeric-value arg))))
8097 (defun org-move-subtree-down (&optional arg)
8098 "Move the current subtree down past ARG headlines of the same level."
8099 (interactive "p")
8100 (setq arg (prefix-numeric-value arg))
8101 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8102 'org-get-last-sibling))
8103 (ins-point (make-marker))
8104 (cnt (abs arg))
8105 (col (current-column))
8106 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8107 ;; Select the tree
8108 (org-back-to-heading)
8109 (setq beg0 (point))
8110 (save-excursion
8111 (setq ne-beg (org-back-over-empty-lines))
8112 (setq beg (point)))
8113 (save-match-data
8114 (save-excursion (outline-end-of-heading)
8115 (setq folded (outline-invisible-p)))
8116 (outline-end-of-subtree))
8117 (outline-next-heading)
8118 (setq ne-end (org-back-over-empty-lines))
8119 (setq end (point))
8120 (goto-char beg0)
8121 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8122 ;; include less whitespace
8123 (save-excursion
8124 (goto-char beg)
8125 (forward-line (- ne-beg ne-end))
8126 (setq beg (point))))
8127 ;; Find insertion point, with error handling
8128 (while (> cnt 0)
8129 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8130 (progn (goto-char beg0)
8131 (user-error "Cannot move past superior level or buffer limit")))
8132 (setq cnt (1- cnt)))
8133 (if (> arg 0)
8134 ;; Moving forward - still need to move over subtree
8135 (progn (org-end-of-subtree t t)
8136 (save-excursion
8137 (org-back-over-empty-lines)
8138 (or (bolp) (newline)))))
8139 (setq ne-ins (org-back-over-empty-lines))
8140 (move-marker ins-point (point))
8141 (setq txt (buffer-substring beg end))
8142 (org-save-markers-in-region beg end)
8143 (delete-region beg end)
8144 (org-remove-empty-overlays-at beg)
8145 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8146 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8147 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8148 (let ((bbb (point)))
8149 (insert-before-markers txt)
8150 (org-reinstall-markers-in-region bbb)
8151 (move-marker ins-point bbb))
8152 (or (bolp) (insert "\n"))
8153 (setq ins-end (point))
8154 (goto-char ins-point)
8155 (org-skip-whitespace)
8156 (when (and (< arg 0)
8157 (org-first-sibling-p)
8158 (> ne-ins ne-beg))
8159 ;; Move whitespace back to beginning
8160 (save-excursion
8161 (goto-char ins-end)
8162 (let ((kill-whole-line t))
8163 (kill-line (- ne-ins ne-beg)) (point)))
8164 (insert (make-string (- ne-ins ne-beg) ?\n)))
8165 (move-marker ins-point nil)
8166 (if folded
8167 (hide-subtree)
8168 (org-show-entry)
8169 (show-children)
8170 (org-cycle-hide-drawers 'children))
8171 (org-clean-visibility-after-subtree-move)
8172 ;; move back to the initial column we were at
8173 (move-to-column col)))
8175 (defvar org-subtree-clip ""
8176 "Clipboard for cut and paste of subtrees.
8177 This is actually only a copy of the kill, because we use the normal kill
8178 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8180 (defvar org-subtree-clip-folded nil
8181 "Was the last copied subtree folded?
8182 This is used to fold the tree back after pasting.")
8184 (defun org-cut-subtree (&optional n)
8185 "Cut the current subtree into the clipboard.
8186 With prefix arg N, cut this many sequential subtrees.
8187 This is a short-hand for marking the subtree and then cutting it."
8188 (interactive "p")
8189 (org-copy-subtree n 'cut))
8191 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8192 "Copy the current subtree it in the clipboard.
8193 With prefix arg N, copy this many sequential subtrees.
8194 This is a short-hand for marking the subtree and then copying it.
8195 If CUT is non-nil, actually cut the subtree.
8196 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8197 of some markers in the region, even if CUT is non-nil. This is
8198 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8199 (interactive "p")
8200 (let (beg end folded (beg0 (point)))
8201 (if (org-called-interactively-p 'any)
8202 (org-back-to-heading nil) ; take what looks like a subtree
8203 (org-back-to-heading t)) ; take what is really there
8204 (setq beg (point))
8205 (skip-chars-forward " \t\r\n")
8206 (save-match-data
8207 (if nosubtrees
8208 (outline-next-heading)
8209 (save-excursion (outline-end-of-heading)
8210 (setq folded (outline-invisible-p)))
8211 (condition-case nil
8212 (org-forward-heading-same-level (1- n) t)
8213 (error nil))
8214 (org-end-of-subtree t t)))
8215 (setq end (point))
8216 (goto-char beg0)
8217 (when (> end beg)
8218 (setq org-subtree-clip-folded folded)
8219 (when (or cut force-store-markers)
8220 (org-save-markers-in-region beg end))
8221 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8222 (setq org-subtree-clip (current-kill 0))
8223 (message "%s: Subtree(s) with %d characters"
8224 (if cut "Cut" "Copied")
8225 (length org-subtree-clip)))))
8227 (defun org-paste-subtree (&optional level tree for-yank)
8228 "Paste the clipboard as a subtree, with modification of headline level.
8229 The entire subtree is promoted or demoted in order to match a new headline
8230 level.
8232 If the cursor is at the beginning of a headline, the same level as
8233 that headline is used to paste the tree.
8235 If not, the new level is derived from the *visible* headings
8236 before and after the insertion point, and taken to be the inferior headline
8237 level of the two. So if the previous visible heading is level 3 and the
8238 next is level 4 (or vice versa), level 4 will be used for insertion.
8239 This makes sure that the subtree remains an independent subtree and does
8240 not swallow low level entries.
8242 You can also force a different level, either by using a numeric prefix
8243 argument, or by inserting the heading marker by hand. For example, if the
8244 cursor is after \"*****\", then the tree will be shifted to level 5.
8246 If optional TREE is given, use this text instead of the kill ring.
8248 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8249 move back over whitespace before inserting, and move point to the end of
8250 the inserted text when done."
8251 (interactive "P")
8252 (setq tree (or tree (and kill-ring (current-kill 0))))
8253 (unless (org-kill-is-subtree-p tree)
8254 (user-error "%s"
8255 (substitute-command-keys
8256 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8257 (org-with-limited-levels
8258 (let* ((visp (not (outline-invisible-p)))
8259 (txt tree)
8260 (^re_ "\\(\\*+\\)[ \t]*")
8261 (old-level (if (string-match org-outline-regexp-bol txt)
8262 (- (match-end 0) (match-beginning 0) 1)
8263 -1))
8264 (force-level (cond (level (prefix-numeric-value level))
8265 ((and (looking-at "[ \t]*$")
8266 (string-match
8267 "^\\*+$" (buffer-substring
8268 (point-at-bol) (point))))
8269 (- (match-end 1) (match-beginning 1)))
8270 ((and (bolp)
8271 (looking-at org-outline-regexp))
8272 (- (match-end 0) (point) 1))))
8273 (previous-level (save-excursion
8274 (condition-case nil
8275 (progn
8276 (outline-previous-visible-heading 1)
8277 (if (looking-at ^re_)
8278 (- (match-end 0) (match-beginning 0) 1)
8280 (error 1))))
8281 (next-level (save-excursion
8282 (condition-case nil
8283 (progn
8284 (or (looking-at org-outline-regexp)
8285 (outline-next-visible-heading 1))
8286 (if (looking-at ^re_)
8287 (- (match-end 0) (match-beginning 0) 1)
8289 (error 1))))
8290 (new-level (or force-level (max previous-level next-level)))
8291 (shift (if (or (= old-level -1)
8292 (= new-level -1)
8293 (= old-level new-level))
8295 (- new-level old-level)))
8296 (delta (if (> shift 0) -1 1))
8297 (func (if (> shift 0) 'org-demote 'org-promote))
8298 (org-odd-levels-only nil)
8299 beg end newend)
8300 ;; Remove the forced level indicator
8301 (if force-level
8302 (delete-region (point-at-bol) (point)))
8303 ;; Paste
8304 (beginning-of-line (if (bolp) 1 2))
8305 (setq beg (point))
8306 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8307 (insert-before-markers txt)
8308 (unless (string-match "\n\\'" txt) (insert "\n"))
8309 (setq newend (point))
8310 (org-reinstall-markers-in-region beg)
8311 (setq end (point))
8312 (goto-char beg)
8313 (skip-chars-forward " \t\n\r")
8314 (setq beg (point))
8315 (if (and (outline-invisible-p) visp)
8316 (save-excursion (outline-show-heading)))
8317 ;; Shift if necessary
8318 (unless (= shift 0)
8319 (save-restriction
8320 (narrow-to-region beg end)
8321 (while (not (= shift 0))
8322 (org-map-region func (point-min) (point-max))
8323 (setq shift (+ delta shift)))
8324 (goto-char (point-min))
8325 (setq newend (point-max))))
8326 (when (or (org-called-interactively-p 'interactive) for-yank)
8327 (message "Clipboard pasted as level %d subtree" new-level))
8328 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8329 kill-ring
8330 (eq org-subtree-clip (current-kill 0))
8331 org-subtree-clip-folded)
8332 ;; The tree was folded before it was killed/copied
8333 (hide-subtree))
8334 (and for-yank (goto-char newend)))))
8336 (defun org-kill-is-subtree-p (&optional txt)
8337 "Check if the current kill is an outline subtree, or a set of trees.
8338 Returns nil if kill does not start with a headline, or if the first
8339 headline level is not the largest headline level in the tree.
8340 So this will actually accept several entries of equal levels as well,
8341 which is OK for `org-paste-subtree'.
8342 If optional TXT is given, check this string instead of the current kill."
8343 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8344 (re (org-get-limited-outline-regexp))
8345 (^re (concat "^" re))
8346 (start-level (and kill
8347 (string-match
8348 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8349 kill)
8350 (- (match-end 2) (match-beginning 2) 1)))
8351 (start (1+ (or (match-beginning 2) -1))))
8352 (if (not start-level)
8353 (progn
8354 nil) ;; does not even start with a heading
8355 (catch 'exit
8356 (while (setq start (string-match ^re kill (1+ start)))
8357 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8358 (throw 'exit nil)))
8359 t))))
8361 (defvar org-markers-to-move nil
8362 "Markers that should be moved with a cut-and-paste operation.
8363 Those markers are stored together with their positions relative to
8364 the start of the region.")
8366 (defun org-save-markers-in-region (beg end)
8367 "Check markers in region.
8368 If these markers are between BEG and END, record their position relative
8369 to BEG, so that after moving the block of text, we can put the markers back
8370 into place.
8371 This function gets called just before an entry or tree gets cut from the
8372 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8373 called immediately, to move the markers with the entries."
8374 (setq org-markers-to-move nil)
8375 (when (featurep 'org-clock)
8376 (org-clock-save-markers-for-cut-and-paste beg end))
8377 (when (featurep 'org-agenda)
8378 (org-agenda-save-markers-for-cut-and-paste beg end)))
8380 (defun org-check-and-save-marker (marker beg end)
8381 "Check if MARKER is between BEG and END.
8382 If yes, remember the marker and the distance to BEG."
8383 (when (and (marker-buffer marker)
8384 (equal (marker-buffer marker) (current-buffer)))
8385 (if (and (>= marker beg) (< marker end))
8386 (push (cons marker (- marker beg)) org-markers-to-move))))
8388 (defun org-reinstall-markers-in-region (beg)
8389 "Move all remembered markers to their position relative to BEG."
8390 (mapc (lambda (x)
8391 (move-marker (car x) (+ beg (cdr x))))
8392 org-markers-to-move)
8393 (setq org-markers-to-move nil))
8395 (defun org-narrow-to-subtree ()
8396 "Narrow buffer to the current subtree."
8397 (interactive)
8398 (save-excursion
8399 (save-match-data
8400 (org-with-limited-levels
8401 (narrow-to-region
8402 (progn (org-back-to-heading t) (point))
8403 (progn (org-end-of-subtree t t)
8404 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8405 (point)))))))
8407 (defun org-narrow-to-block ()
8408 "Narrow buffer to the current block."
8409 (interactive)
8410 (let* ((case-fold-search t)
8411 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8412 "^[ \t]*#\\+end_.*")))
8413 (if blockp
8414 (narrow-to-region (car blockp) (cdr blockp))
8415 (user-error "Not in a block"))))
8417 (eval-when-compile
8418 (defvar org-property-drawer-re))
8420 (defvar org-property-start-re) ;; defined below
8421 (defun org-clone-subtree-with-time-shift (n &optional shift)
8422 "Clone the task (subtree) at point N times.
8423 The clones will be inserted as siblings.
8425 In interactive use, the user will be prompted for the number of
8426 clones to be produced. If the entry has a timestamp, the user
8427 will also be prompted for a time shift, which may be a repeater
8428 as used in time stamps, for example `+3d'. To disable this,
8429 you can call the function with a universal prefix argument.
8431 When a valid repeater is given and the entry contains any time
8432 stamps, the clones will become a sequence in time, with time
8433 stamps in the subtree shifted for each clone produced. If SHIFT
8434 is nil or the empty string, time stamps will be left alone. The
8435 ID property of the original subtree is removed.
8437 If the original subtree did contain time stamps with a repeater,
8438 the following will happen:
8439 - the repeater will be removed in each clone
8440 - an additional clone will be produced, with the current, unshifted
8441 date(s) in the entry.
8442 - the original entry will be placed *after* all the clones, with
8443 repeater intact.
8444 - the start days in the repeater in the original entry will be shifted
8445 to past the last clone.
8446 In this way you can spell out a number of instances of a repeating task,
8447 and still retain the repeater to cover future instances of the task."
8448 (interactive "nNumber of clones to produce: ")
8449 (let ((shift
8450 (or shift
8451 (if (and (not (equal current-prefix-arg '(4)))
8452 (save-excursion
8453 (re-search-forward org-ts-regexp-both
8454 (save-excursion
8455 (org-end-of-subtree t)
8456 (point)) t)))
8457 (read-from-minibuffer
8458 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8459 ""))) ;; No time shift
8460 (n-no-remove -1)
8461 (drawer-re org-drawer-regexp)
8462 beg end template task idprop
8463 shift-n shift-what doshift nmin nmax)
8464 (if (not (and (integerp n) (> n 0)))
8465 (error "Invalid number of replications %s" n))
8466 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8467 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8468 shift)))
8469 (error "Invalid shift specification %s" shift))
8470 (when doshift
8471 (setq shift-n (string-to-number (match-string 1 shift))
8472 shift-what (cdr (assoc (match-string 2 shift)
8473 '(("d" . day) ("w" . week)
8474 ("m" . month) ("y" . year))))))
8475 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8476 (setq nmin 1 nmax n)
8477 (org-back-to-heading t)
8478 (setq beg (point))
8479 (setq idprop (org-entry-get nil "ID"))
8480 (org-end-of-subtree t t)
8481 (or (bolp) (insert "\n"))
8482 (setq end (point))
8483 (setq template (buffer-substring beg end))
8484 (when (and doshift
8485 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8486 (delete-region beg end)
8487 (setq end beg)
8488 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8489 (goto-char end)
8490 (loop for n from nmin to nmax do
8491 ;; prepare clone
8492 (with-temp-buffer
8493 (insert template)
8494 (org-mode)
8495 (goto-char (point-min))
8496 (org-show-subtree)
8497 (and idprop (if org-clone-delete-id
8498 (org-entry-delete nil "ID")
8499 (org-id-get-create t)))
8500 (unless (= n 0)
8501 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8502 (kill-whole-line))
8503 (goto-char (point-min))
8504 (while (re-search-forward drawer-re nil t)
8505 (mapc (lambda (d)
8506 (org-remove-empty-drawer-at d (point))) org-drawers)))
8507 (goto-char (point-min))
8508 (when doshift
8509 (while (re-search-forward org-ts-regexp-both nil t)
8510 (org-timestamp-change (* n shift-n) shift-what))
8511 (unless (= n n-no-remove)
8512 (goto-char (point-min))
8513 (while (re-search-forward org-ts-regexp nil t)
8514 (save-excursion
8515 (goto-char (match-beginning 0))
8516 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8517 (delete-region (match-beginning 1) (match-end 1)))))))
8518 (setq task (buffer-string)))
8519 (insert task))
8520 (goto-char beg)))
8522 ;;; Outline Sorting
8524 (defun org-sort (with-case)
8525 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8526 Optional argument WITH-CASE means sort case-sensitively."
8527 (interactive "P")
8528 (cond
8529 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8530 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8532 (org-call-with-arg 'org-sort-entries with-case))))
8534 (defun org-sort-remove-invisible (s)
8535 "Remove invisible links from string S."
8536 (remove-text-properties 0 (length s) org-rm-props s)
8537 (while (string-match org-bracket-link-regexp s)
8538 (setq s (replace-match (if (match-end 2)
8539 (match-string 3 s)
8540 (match-string 1 s)) t t s)))
8541 (let ((st (format " %s " s)))
8542 (while (string-match org-emph-re st)
8543 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8544 (setq s (substring st 1 -1)))
8547 (defvar org-priority-regexp) ; defined later in the file
8549 (defvar org-after-sorting-entries-or-items-hook nil
8550 "Hook that is run after a bunch of entries or items have been sorted.
8551 When children are sorted, the cursor is in the parent line when this
8552 hook gets called. When a region or a plain list is sorted, the cursor
8553 will be in the first entry of the sorted region/list.")
8555 (defun org-sort-entries
8556 (&optional with-case sorting-type getkey-func compare-func property)
8557 "Sort entries on a certain level of an outline tree.
8558 If there is an active region, the entries in the region are sorted.
8559 Else, if the cursor is before the first entry, sort the top-level items.
8560 Else, the children of the entry at point are sorted.
8562 Sorting can be alphabetically, numerically, by date/time as given by
8563 a time stamp, by a property, by priority order, or by a custom function.
8565 The command prompts for the sorting type unless it has been given to the
8566 function through the SORTING-TYPE argument, which needs to be a character,
8567 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8568 precise meaning of each character:
8570 n Numerically, by converting the beginning of the entry/item to a number.
8571 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8572 o By order of TODO keywords.
8573 t By date/time, either the first active time stamp in the entry, or, if
8574 none exist, by the first inactive one.
8575 s By the scheduled date/time.
8576 d By deadline date/time.
8577 c By creation time, which is assumed to be the first inactive time stamp
8578 at the beginning of a line.
8579 p By priority according to the cookie.
8580 r By the value of a property.
8582 Capital letters will reverse the sort order.
8584 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8585 called with point at the beginning of the record. It must return either
8586 a string or a number that should serve as the sorting key for that record.
8588 Comparing entries ignores case by default. However, with an optional argument
8589 WITH-CASE, the sorting considers case as well.
8591 Sorting is done against the visible part of the headlines, it ignores hidden
8592 links."
8593 (interactive "P")
8594 (let ((case-func (if with-case 'identity 'downcase))
8595 (cmstr
8596 ;; The clock marker is lost when using `sort-subr', let's
8597 ;; store the clocking string.
8598 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8599 (save-excursion
8600 (goto-char org-clock-marker)
8601 (looking-back "^.*") (match-string-no-properties 0))))
8602 start beg end stars re re2
8603 txt what tmp)
8604 ;; Find beginning and end of region to sort
8605 (cond
8606 ((org-region-active-p)
8607 ;; we will sort the region
8608 (setq end (region-end)
8609 what "region")
8610 (goto-char (region-beginning))
8611 (if (not (org-at-heading-p)) (outline-next-heading))
8612 (setq start (point)))
8613 ((or (org-at-heading-p)
8614 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8615 ;; we will sort the children of the current headline
8616 (org-back-to-heading)
8617 (setq start (point)
8618 end (progn (org-end-of-subtree t t)
8619 (or (bolp) (insert "\n"))
8620 (org-back-over-empty-lines)
8621 (point))
8622 what "children")
8623 (goto-char start)
8624 (show-subtree)
8625 (outline-next-heading))
8627 ;; we will sort the top-level entries in this file
8628 (goto-char (point-min))
8629 (or (org-at-heading-p) (outline-next-heading))
8630 (setq start (point))
8631 (goto-char (point-max))
8632 (beginning-of-line 1)
8633 (when (looking-at ".*?\\S-")
8634 ;; File ends in a non-white line
8635 (end-of-line 1)
8636 (insert "\n"))
8637 (setq end (point-max))
8638 (setq what "top-level")
8639 (goto-char start)
8640 (show-all)))
8642 (setq beg (point))
8643 (if (>= beg end) (user-error "Nothing to sort"))
8645 (looking-at "\\(\\*+\\)")
8646 (setq stars (match-string 1)
8647 re (concat "^" (regexp-quote stars) " +")
8648 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8649 txt (buffer-substring beg end))
8650 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8651 (if (and (not (equal stars "*")) (string-match re2 txt))
8652 (user-error "Region to sort contains a level above the first entry"))
8654 (unless sorting-type
8655 (message
8656 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8657 [t]ime [s]cheduled [d]eadline [c]reated
8658 A/N/P/R/O/F/T/S/D/C means reversed:"
8659 what)
8660 (setq sorting-type (read-char-exclusive))
8662 (unless getkey-func
8663 (and (= (downcase sorting-type) ?f)
8664 (setq getkey-func
8665 (org-icompleting-read "Sort using function: "
8666 obarray 'fboundp t nil nil))
8667 (setq getkey-func (intern getkey-func))))
8669 (and (= (downcase sorting-type) ?r)
8670 (not property)
8671 (setq property
8672 (org-icompleting-read "Property: "
8673 (mapcar 'list (org-buffer-property-keys t))
8674 nil t))))
8676 (message "Sorting entries...")
8678 (save-restriction
8679 (narrow-to-region start end)
8680 (let ((dcst (downcase sorting-type))
8681 (case-fold-search nil)
8682 (now (current-time)))
8683 (sort-subr
8684 (/= dcst sorting-type)
8685 ;; This function moves to the beginning character of the "record" to
8686 ;; be sorted.
8687 (lambda nil
8688 (if (re-search-forward re nil t)
8689 (goto-char (match-beginning 0))
8690 (goto-char (point-max))))
8691 ;; This function moves to the last character of the "record" being
8692 ;; sorted.
8693 (lambda nil
8694 (save-match-data
8695 (condition-case nil
8696 (outline-forward-same-level 1)
8697 (error
8698 (goto-char (point-max))))))
8699 ;; This function returns the value that gets sorted against.
8700 (lambda nil
8701 (cond
8702 ((= dcst ?n)
8703 (if (looking-at org-complex-heading-regexp)
8704 (string-to-number (org-sort-remove-invisible (match-string 4)))
8705 nil))
8706 ((= dcst ?a)
8707 (if (looking-at org-complex-heading-regexp)
8708 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8709 nil))
8710 ((= dcst ?t)
8711 (let ((end (save-excursion (outline-next-heading) (point))))
8712 (if (or (re-search-forward org-ts-regexp end t)
8713 (re-search-forward org-ts-regexp-both end t))
8714 (org-time-string-to-seconds (match-string 0))
8715 (org-float-time now))))
8716 ((= dcst ?c)
8717 (let ((end (save-excursion (outline-next-heading) (point))))
8718 (if (re-search-forward
8719 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8720 end t)
8721 (org-time-string-to-seconds (match-string 0))
8722 (org-float-time now))))
8723 ((= dcst ?s)
8724 (let ((end (save-excursion (outline-next-heading) (point))))
8725 (if (re-search-forward org-scheduled-time-regexp end t)
8726 (org-time-string-to-seconds (match-string 1))
8727 (org-float-time now))))
8728 ((= dcst ?d)
8729 (let ((end (save-excursion (outline-next-heading) (point))))
8730 (if (re-search-forward org-deadline-time-regexp end t)
8731 (org-time-string-to-seconds (match-string 1))
8732 (org-float-time now))))
8733 ((= dcst ?p)
8734 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8735 (string-to-char (match-string 2))
8736 org-default-priority))
8737 ((= dcst ?r)
8738 (or (org-entry-get nil property) ""))
8739 ((= dcst ?o)
8740 (if (looking-at org-complex-heading-regexp)
8741 (- 9999 (length (member (match-string 2)
8742 org-todo-keywords-1)))))
8743 ((= dcst ?f)
8744 (if getkey-func
8745 (progn
8746 (setq tmp (funcall getkey-func))
8747 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8748 tmp)
8749 (error "Invalid key function `%s'" getkey-func)))
8750 (t (error "Invalid sorting type `%c'" sorting-type))))
8752 (cond
8753 ((= dcst ?a) 'string<)
8754 ((= dcst ?f) compare-func)
8755 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8756 (run-hooks 'org-after-sorting-entries-or-items-hook)
8757 ;; Reset the clock marker if needed
8758 (when cmstr
8759 (save-excursion
8760 (goto-char start)
8761 (search-forward cmstr nil t)
8762 (move-marker org-clock-marker (point))))
8763 (message "Sorting entries...done")))
8765 (defun org-do-sort (table what &optional with-case sorting-type)
8766 "Sort TABLE of WHAT according to SORTING-TYPE.
8767 The user will be prompted for the SORTING-TYPE if the call to this
8768 function does not specify it. WHAT is only for the prompt, to indicate
8769 what is being sorted. The sorting key will be extracted from
8770 the car of the elements of the table.
8771 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8772 (unless sorting-type
8773 (message
8774 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8775 what)
8776 (setq sorting-type (read-char-exclusive)))
8777 (let ((dcst (downcase sorting-type))
8778 extractfun comparefun)
8779 ;; Define the appropriate functions
8780 (cond
8781 ((= dcst ?n)
8782 (setq extractfun 'string-to-number
8783 comparefun (if (= dcst sorting-type) '< '>)))
8784 ((= dcst ?a)
8785 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8786 (lambda(x) (downcase (org-sort-remove-invisible x))))
8787 comparefun (if (= dcst sorting-type)
8788 'string<
8789 (lambda (a b) (and (not (string< a b))
8790 (not (string= a b)))))))
8791 ((= dcst ?t)
8792 (setq extractfun
8793 (lambda (x)
8794 (if (or (string-match org-ts-regexp x)
8795 (string-match org-ts-regexp-both x))
8796 (org-float-time
8797 (org-time-string-to-time (match-string 0 x)))
8799 comparefun (if (= dcst sorting-type) '< '>)))
8800 (t (error "Invalid sorting type `%c'" sorting-type)))
8802 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8803 table)
8804 (lambda (a b) (funcall comparefun (car a) (car b))))))
8807 ;;; The orgstruct minor mode
8809 ;; Define a minor mode which can be used in other modes in order to
8810 ;; integrate the org-mode structure editing commands.
8812 ;; This is really a hack, because the org-mode structure commands use
8813 ;; keys which normally belong to the major mode. Here is how it
8814 ;; works: The minor mode defines all the keys necessary to operate the
8815 ;; structure commands, but wraps the commands into a function which
8816 ;; tests if the cursor is currently at a headline or a plain list
8817 ;; item. If that is the case, the structure command is used,
8818 ;; temporarily setting many Org-mode variables like regular
8819 ;; expressions for filling etc. However, when any of those keys is
8820 ;; used at a different location, function uses `key-binding' to look
8821 ;; up if the key has an associated command in another currently active
8822 ;; keymap (minor modes, major mode, global), and executes that
8823 ;; command. There might be problems if any of the keys is otherwise
8824 ;; used as a prefix key.
8826 (defcustom orgstruct-heading-prefix-regexp ""
8827 "Regexp that matches the custom prefix of Org headlines in
8828 orgstruct(++)-mode."
8829 :group 'org
8830 :version "24.4"
8831 :package-version '(Org . "8.3")
8832 :type 'regexp)
8833 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8835 (defcustom orgstruct-setup-hook nil
8836 "Hook run after orgstruct-mode-map is filled."
8837 :group 'org
8838 :version "24.4"
8839 :package-version '(Org . "8.0")
8840 :type 'hook)
8842 (defvar orgstruct-initialized nil)
8844 (defvar org-local-vars nil
8845 "List of local variables, for use by `orgstruct-mode'.")
8847 ;;;###autoload
8848 (define-minor-mode orgstruct-mode
8849 "Toggle the minor mode `orgstruct-mode'.
8850 This mode is for using Org-mode structure commands in other
8851 modes. The following keys behave as if Org-mode were active, if
8852 the cursor is on a headline, or on a plain list item (both as
8853 defined by Org-mode)."
8854 nil " OrgStruct" (make-sparse-keymap)
8855 (funcall (if orgstruct-mode
8856 'add-to-invisibility-spec
8857 'remove-from-invisibility-spec)
8858 '(outline . t))
8859 (when orgstruct-mode
8860 (org-load-modules-maybe)
8861 (unless orgstruct-initialized
8862 (orgstruct-setup)
8863 (setq orgstruct-initialized t))))
8865 ;;;###autoload
8866 (defun turn-on-orgstruct ()
8867 "Unconditionally turn on `orgstruct-mode'."
8868 (orgstruct-mode 1))
8870 (defvar org-fb-vars nil)
8871 (make-variable-buffer-local 'org-fb-vars)
8872 (defun orgstruct++-mode (&optional arg)
8873 "Toggle `orgstruct-mode', the enhanced version of it.
8874 In addition to setting orgstruct-mode, this also exports all
8875 indentation and autofilling variables from org-mode into the
8876 buffer. It will also recognize item context in multiline items."
8877 (interactive "P")
8878 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8879 (if (< arg 1)
8880 (progn (orgstruct-mode -1)
8881 (mapc (lambda(v)
8882 (org-set-local (car v)
8883 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8884 org-fb-vars))
8885 (orgstruct-mode 1)
8886 (setq org-fb-vars nil)
8887 (unless org-local-vars
8888 (setq org-local-vars (org-get-local-variables)))
8889 (let (var val)
8890 (mapc
8891 (lambda (x)
8892 (when (string-match
8893 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8894 (symbol-name (car x)))
8895 (setq var (car x) val (nth 1 x))
8896 (push (list var `(quote ,(eval var))) org-fb-vars)
8897 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8898 org-local-vars)
8899 (org-set-local 'orgstruct-is-++ t))))
8901 (defvar orgstruct-is-++ nil
8902 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8903 (make-variable-buffer-local 'orgstruct-is-++)
8905 ;;;###autoload
8906 (defun turn-on-orgstruct++ ()
8907 "Unconditionally turn on `orgstruct++-mode'."
8908 (orgstruct++-mode 1))
8910 (defun orgstruct-error ()
8911 "Error when there is no default binding for a structure key."
8912 (interactive)
8913 (funcall (if (fboundp 'user-error)
8914 'user-error
8915 'error)
8916 "This key has no function outside structure elements"))
8918 (defun orgstruct-setup ()
8919 "Setup orgstruct keymap."
8920 (dolist (cell '((org-demote . t)
8921 (org-metaleft . t)
8922 (org-metaright . t)
8923 (org-promote . t)
8924 (org-shiftmetaleft . t)
8925 (org-shiftmetaright . t)
8926 org-backward-element
8927 org-backward-heading-same-level
8928 org-ctrl-c-ret
8929 org-ctrl-c-minus
8930 org-ctrl-c-star
8931 org-cycle
8932 org-forward-heading-same-level
8933 org-insert-heading
8934 org-insert-heading-respect-content
8935 org-kill-note-or-show-branches
8936 org-mark-subtree
8937 org-meta-return
8938 org-metadown
8939 org-metaup
8940 org-narrow-to-subtree
8941 org-promote-subtree
8942 org-reveal
8943 org-shiftdown
8944 org-shiftleft
8945 org-shiftmetadown
8946 org-shiftmetaup
8947 org-shiftright
8948 org-shifttab
8949 org-shifttab
8950 org-shiftup
8951 org-show-subtree
8952 org-sort
8953 org-up-element
8954 outline-demote
8955 outline-next-visible-heading
8956 outline-previous-visible-heading
8957 outline-promote
8958 outline-up-heading
8959 show-children))
8960 (let ((f (or (car-safe cell) cell))
8961 (disable-when-heading-prefix (cdr-safe cell)))
8962 (when (fboundp f)
8963 (let ((new-bindings))
8964 (dolist (binding (nconc (where-is-internal f org-mode-map)
8965 (where-is-internal f outline-mode-map)))
8966 (push binding new-bindings)
8967 ;; TODO use local-function-key-map
8968 (dolist (rep '(("<tab>" . "TAB")
8969 ("<return>" . "RET")
8970 ("<escape>" . "ESC")
8971 ("<delete>" . "DEL")))
8972 (setq binding (read-kbd-macro
8973 (let ((case-fold-search))
8974 (replace-regexp-in-string
8975 (regexp-quote (cdr rep))
8976 (car rep)
8977 (key-description binding)))))
8978 (pushnew binding new-bindings :test 'equal)))
8979 (dolist (binding new-bindings)
8980 (let ((key (lookup-key orgstruct-mode-map binding)))
8981 (when (or (not key) (numberp key))
8982 (condition-case nil
8983 (org-defkey orgstruct-mode-map
8984 binding
8985 (orgstruct-make-binding f binding disable-when-heading-prefix))
8986 (error nil)))))))))
8987 (run-hooks 'orgstruct-setup-hook))
8989 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8990 "Create a function for binding in the structure minor mode.
8991 FUN is the command to call inside a table. KEY is the key that
8992 should be checked in for a command to execute outside of tables.
8993 Non-nil `disable-when-heading-prefix' means to disable the command
8994 if `orgstruct-heading-prefix-regexp' is not empty."
8995 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8996 (let ((nname name)
8997 (i 0))
8998 (while (fboundp (intern nname))
8999 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9000 (setq name (intern nname)))
9001 (eval
9002 (let ((bindings '((org-heading-regexp
9003 (concat "^"
9004 orgstruct-heading-prefix-regexp
9005 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9006 (org-outline-regexp
9007 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9008 (org-outline-regexp-bol
9009 (concat "^" org-outline-regexp))
9010 (outline-regexp org-outline-regexp)
9011 (outline-heading-end-regexp "\n")
9012 (outline-level 'org-outline-level)
9013 (outline-heading-alist))))
9014 `(defun ,name (arg)
9015 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9016 "Outside of structure, run the binding of `"
9017 (key-description key) "'."
9018 (when disable-when-heading-prefix
9019 (concat
9020 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9021 "back to the default binding due to limitations of Org's implementation of\n"
9022 "`" (symbol-name fun) "'.")))
9023 (interactive "p")
9024 (let* ((disable
9025 ,(and disable-when-heading-prefix
9026 '(not (string= orgstruct-heading-prefix-regexp ""))))
9027 (fallback
9028 (or disable
9029 (not
9030 (let* ,bindings
9031 (org-context-p 'headline 'item
9032 ,(when (memq fun
9033 '(org-insert-heading
9034 org-insert-heading-respect-content
9035 org-meta-return))
9036 '(when orgstruct-is-++
9037 'item-body))))))))
9038 (if fallback
9039 (let* ((orgstruct-mode)
9040 (binding
9041 (loop with key = ,key
9042 for rep in
9043 '(nil
9044 ("<\\([^>]*\\)tab>" . "\\1TAB")
9045 ("<\\([^>]*\\)return>" . "\\1RET")
9046 ("<\\([^>]*\\)escape>" . "\\1ESC")
9047 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9049 (when rep
9050 (setq key (read-kbd-macro
9051 (let ((case-fold-search))
9052 (replace-regexp-in-string
9053 (car rep)
9054 (cdr rep)
9055 (key-description key))))))
9056 thereis (key-binding key))))
9057 (if (keymapp binding)
9058 (set-temporary-overlay-map binding)
9059 (let ((func (or binding
9060 (unless disable
9061 'orgstruct-error))))
9062 (when func
9063 (call-interactively func)))))
9064 (org-run-like-in-org-mode
9065 (lambda ()
9066 (interactive)
9067 (let* ,bindings
9068 (call-interactively ',fun)))))))))
9069 name))
9071 (defun org-contextualize-keys (alist contexts)
9072 "Return valid elements in ALIST depending on CONTEXTS.
9074 `org-agenda-custom-commands' or `org-capture-templates' are the
9075 values used for ALIST, and `org-agenda-custom-commands-contexts'
9076 or `org-capture-templates-contexts' are the associated contexts
9077 definitions."
9078 (let ((contexts
9079 ;; normalize contexts
9080 (mapcar
9081 (lambda(c) (cond ((listp (cadr c))
9082 (list (car c) (car c) (cadr c)))
9083 ((string= "" (cadr c))
9084 (list (car c) (car c) (caddr c)))
9085 (t c))) contexts))
9086 (a alist) c r s)
9087 ;; loop over all commands or templates
9088 (while (setq c (pop a))
9089 (let (vrules repl)
9090 (cond
9091 ((not (assoc (car c) contexts))
9092 (push c r))
9093 ((and (assoc (car c) contexts)
9094 (setq vrules (org-contextualize-validate-key
9095 (car c) contexts)))
9096 (mapc (lambda (vr)
9097 (when (not (equal (car vr) (cadr vr)))
9098 (setq repl vr))) vrules)
9099 (if (not repl) (push c r)
9100 (push (cadr repl) s)
9101 (push
9102 (cons (car c)
9103 (cdr (or (assoc (cadr repl) alist)
9104 (error "Undefined key `%s' as contextual replacement for `%s'"
9105 (cadr repl) (car c)))))
9106 r))))))
9107 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9108 (delq
9110 (delete-dups
9111 (mapcar (lambda (x)
9112 (let ((tpl (car x)))
9113 (when (not (delq
9115 (mapcar (lambda(y)
9116 (equal y tpl)) s))) x)))
9117 (reverse r))))))
9119 (defun org-contextualize-validate-key (key contexts)
9120 "Check CONTEXTS for agenda or capture KEY."
9121 (let (r rr res)
9122 (while (setq r (pop contexts))
9123 (mapc
9124 (lambda (rr)
9125 (when
9126 (and (equal key (car r))
9127 (if (functionp rr) (funcall rr)
9128 (or (and (eq (car rr) 'in-file)
9129 (buffer-file-name)
9130 (string-match (cdr rr) (buffer-file-name)))
9131 (and (eq (car rr) 'in-mode)
9132 (string-match (cdr rr) (symbol-name major-mode)))
9133 (and (eq (car rr) 'in-buffer)
9134 (string-match (cdr rr) (buffer-name)))
9135 (when (and (eq (car rr) 'not-in-file)
9136 (buffer-file-name))
9137 (not (string-match (cdr rr) (buffer-file-name))))
9138 (when (eq (car rr) 'not-in-mode)
9139 (not (string-match (cdr rr) (symbol-name major-mode))))
9140 (when (eq (car rr) 'not-in-buffer)
9141 (not (string-match (cdr rr) (buffer-name)))))))
9142 (push r res)))
9143 (car (last r))))
9144 (delete-dups (delq nil res))))
9146 (defun org-context-p (&rest contexts)
9147 "Check if local context is any of CONTEXTS.
9148 Possible values in the list of contexts are `table', `headline', and `item'."
9149 (let ((pos (point)))
9150 (goto-char (point-at-bol))
9151 (prog1 (or (and (memq 'table contexts)
9152 (looking-at "[ \t]*|"))
9153 (and (memq 'headline contexts)
9154 (looking-at org-outline-regexp))
9155 (and (memq 'item contexts)
9156 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9157 (and (memq 'item-body contexts)
9158 (org-in-item-p)))
9159 (goto-char pos))))
9161 (defun org-get-local-variables ()
9162 "Return a list of all local variables in an Org mode buffer."
9163 (let (varlist)
9164 (with-current-buffer (get-buffer-create "*Org tmp*")
9165 (erase-buffer)
9166 (org-mode)
9167 (setq varlist (buffer-local-variables)))
9168 (kill-buffer "*Org tmp*")
9169 (delq nil
9170 (mapcar
9171 (lambda (x)
9172 (setq x
9173 (if (symbolp x)
9174 (list x)
9175 (list (car x) (cdr x))))
9176 (if (and (not (get (car x) 'org-state))
9177 (string-match
9178 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9179 (symbol-name (car x))))
9180 x nil))
9181 varlist))))
9183 (defun org-clone-local-variables (from-buffer &optional regexp)
9184 "Clone local variables from FROM-BUFFER.
9185 Optional argument REGEXP selects variables to clone."
9186 (mapc
9187 (lambda (pair)
9188 (and (symbolp (car pair))
9189 (or (null regexp)
9190 (string-match regexp (symbol-name (car pair))))
9191 (set (make-local-variable (car pair))
9192 (cdr pair))))
9193 (buffer-local-variables from-buffer)))
9195 ;;;###autoload
9196 (defun org-run-like-in-org-mode (cmd)
9197 "Run a command, pretending that the current buffer is in Org-mode.
9198 This will temporarily bind local variables that are typically bound in
9199 Org-mode to the values they have in Org-mode, and then interactively
9200 call CMD."
9201 (org-load-modules-maybe)
9202 (unless org-local-vars
9203 (setq org-local-vars (org-get-local-variables)))
9204 (let (binds)
9205 (dolist (var org-local-vars)
9206 (when (or (not (boundp (car var)))
9207 (eq (symbol-value (car var))
9208 (default-value (car var))))
9209 (push (list (car var) `(quote ,(cadr var))) binds)))
9210 (eval `(let ,binds
9211 (call-interactively (quote ,cmd))))))
9213 ;;;; Archiving
9215 (defun org-get-category (&optional pos force-refresh)
9216 "Get the category applying to position POS."
9217 (save-match-data
9218 (if force-refresh (org-refresh-category-properties))
9219 (let ((pos (or pos (point))))
9220 (or (get-text-property pos 'org-category)
9221 (progn (org-refresh-category-properties)
9222 (get-text-property pos 'org-category))))))
9224 (defun org-refresh-category-properties ()
9225 "Refresh category text properties in the buffer."
9226 (let ((case-fold-search t)
9227 (inhibit-read-only t)
9228 (def-cat (cond
9229 ((null org-category)
9230 (if buffer-file-name
9231 (file-name-sans-extension
9232 (file-name-nondirectory buffer-file-name))
9233 "???"))
9234 ((symbolp org-category) (symbol-name org-category))
9235 (t org-category)))
9236 beg end cat pos optionp)
9237 (org-with-silent-modifications
9238 (save-excursion
9239 (save-restriction
9240 (widen)
9241 (goto-char (point-min))
9242 (put-text-property (point) (point-max) 'org-category def-cat)
9243 (while (re-search-forward
9244 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9245 (setq pos (match-end 0)
9246 optionp (equal (char-after (match-beginning 0)) ?#)
9247 cat (org-trim (match-string 2)))
9248 (if optionp
9249 (setq beg (point-at-bol) end (point-max))
9250 (org-back-to-heading t)
9251 (setq beg (point) end (org-end-of-subtree t t)))
9252 (put-text-property beg end 'org-category cat)
9253 (put-text-property beg end 'org-category-position beg)
9254 (goto-char pos)))))))
9256 (defun org-refresh-properties (dprop tprop)
9257 "Refresh buffer text properties.
9258 DPROP is the drawer property and TPROP is the corresponding text
9259 property to set."
9260 (let ((case-fold-search t)
9261 (inhibit-read-only t) p)
9262 (org-with-silent-modifications
9263 (save-excursion
9264 (save-restriction
9265 (widen)
9266 (goto-char (point-min))
9267 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9268 (setq p (org-match-string-no-properties 1))
9269 (save-excursion
9270 (org-back-to-heading t)
9271 (put-text-property
9272 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9275 ;;;; Link Stuff
9277 ;;; Link abbreviations
9279 (defun org-link-expand-abbrev (link)
9280 "Apply replacements as defined in `org-link-abbrev-alist'."
9281 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9282 (let* ((key (match-string 1 link))
9283 (as (or (assoc key org-link-abbrev-alist-local)
9284 (assoc key org-link-abbrev-alist)))
9285 (tag (and (match-end 2) (match-string 3 link)))
9286 rpl)
9287 (if (not as)
9288 link
9289 (setq rpl (cdr as))
9290 (cond
9291 ((symbolp rpl) (funcall rpl tag))
9292 ((string-match "%(\\([^)]+\\))" rpl)
9293 (replace-match
9294 (save-match-data
9295 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9296 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9297 ((string-match "%h" rpl)
9298 (replace-match (url-hexify-string (or tag "")) t t rpl))
9299 (t (concat rpl tag)))))
9300 link))
9302 ;;; Storing and inserting links
9304 (defvar org-insert-link-history nil
9305 "Minibuffer history for links inserted with `org-insert-link'.")
9307 (defvar org-stored-links nil
9308 "Contains the links stored with `org-store-link'.")
9310 (defvar org-store-link-plist nil
9311 "Plist with info about the most recently link created with `org-store-link'.")
9313 (defvar org-link-protocols nil
9314 "Link protocols added to Org-mode using `org-add-link-type'.")
9316 (defvar org-store-link-functions nil
9317 "List of functions that are called to create and store a link.
9318 Each function will be called in turn until one returns a non-nil
9319 value. Each function should check if it is responsible for creating
9320 this link (for example by looking at the major mode).
9321 If not, it must exit and return nil.
9322 If yes, it should return a non-nil value after a calling
9323 `org-store-link-props' with a list of properties and values.
9324 Special properties are:
9326 :type The link prefix, like \"http\". This must be given.
9327 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9328 This is obligatory as well.
9329 :description Optional default description for the second pair
9330 of brackets in an Org-mode link. The user can still change
9331 this when inserting this link into an Org-mode buffer.
9333 In addition to these, any additional properties can be specified
9334 and then used in capture templates.")
9336 (defun org-add-link-type (type &optional follow export)
9337 "Add TYPE to the list of `org-link-types'.
9338 Re-compute all regular expressions depending on `org-link-types'
9340 FOLLOW and EXPORT are two functions.
9342 FOLLOW should take the link path as the single argument and do whatever
9343 is necessary to follow the link, for example find a file or display
9344 a mail message.
9346 EXPORT should format the link path for export to one of the export formats.
9347 It should be a function accepting three arguments:
9349 path the path of the link, the text after the prefix (like \"http:\")
9350 desc the description of the link, if any, or a description added by
9351 org-export-normalize-links if there is none
9352 format the export format, a symbol like `html' or `latex' or `ascii'..
9354 The function may use the FORMAT information to return different values
9355 depending on the format. The return value will be put literally into
9356 the exported file. If the return value is nil, this means Org should
9357 do what it normally does with links which do not have EXPORT defined.
9359 Org-mode has a built-in default for exporting links. If you are happy with
9360 this default, there is no need to define an export function for the link
9361 type. For a simple example of an export function, see `org-bbdb.el'."
9362 (add-to-list 'org-link-types type t)
9363 (org-make-link-regexps)
9364 (if (assoc type org-link-protocols)
9365 (setcdr (assoc type org-link-protocols) (list follow export))
9366 (push (list type follow export) org-link-protocols)))
9368 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9369 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9371 ;;;###autoload
9372 (defun org-store-link (arg)
9373 "\\<org-mode-map>Store an org-link to the current location.
9374 This link is added to `org-stored-links' and can later be inserted
9375 into an org-buffer with \\[org-insert-link].
9377 For some link types, a prefix arg is interpreted.
9378 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9379 For file links, arg negates `org-context-in-file-links'.
9381 A double prefix arg force skipping storing functions that are not
9382 part of Org's core.
9384 A triple prefix arg force storing a link for each line in the
9385 active region."
9386 (interactive "P")
9387 (org-load-modules-maybe)
9388 (if (and (equal arg '(64)) (org-region-active-p))
9389 (save-excursion
9390 (let ((end (region-end)))
9391 (goto-char (region-beginning))
9392 (set-mark (point))
9393 (while (< (point-at-eol) end)
9394 (move-end-of-line 1) (activate-mark)
9395 (let (current-prefix-arg)
9396 (call-interactively 'org-store-link))
9397 (move-beginning-of-line 2)
9398 (set-mark (point)))))
9399 (org-with-limited-levels
9400 (setq org-store-link-plist nil)
9401 (let (link cpltxt desc description search
9402 txt custom-id agenda-link sfuns sfunsn)
9403 (cond
9405 ;; Store a link using an external link type
9406 ((and (not (equal arg '(16)))
9407 (setq sfuns
9408 (delq
9409 nil (mapcar (lambda (f)
9410 (let (fs) (if (funcall f) (push f fs))))
9411 org-store-link-functions))
9412 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9413 (or (and (cdr sfuns)
9414 (funcall (intern
9415 (completing-read
9416 "Which function for creating the link? "
9417 sfunsn t (car sfunsn)))))
9418 (funcall (caar sfuns)))
9419 (setq link (plist-get org-store-link-plist :link)
9420 desc (or (plist-get org-store-link-plist
9421 :description) link))))
9423 ;; Store a link from a source code buffer
9424 ((org-src-edit-buffer-p)
9425 (let (label gc)
9426 (while (or (not label)
9427 (save-excursion
9428 (save-restriction
9429 (widen)
9430 (goto-char (point-min))
9431 (re-search-forward
9432 (regexp-quote (format org-coderef-label-format label))
9433 nil t))))
9434 (when label (message "Label exists already") (sit-for 2))
9435 (setq label (read-string "Code line label: " label)))
9436 (end-of-line 1)
9437 (setq link (format org-coderef-label-format label))
9438 (setq gc (- 79 (length link)))
9439 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9440 (insert link)
9441 (setq link (concat "(" label ")") desc nil)))
9443 ;; We are in the agenda, link to referenced location
9444 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9445 (let ((m (or (get-text-property (point) 'org-hd-marker)
9446 (get-text-property (point) 'org-marker))))
9447 (when m
9448 (org-with-point-at m
9449 (setq agenda-link
9450 (if (org-called-interactively-p 'any)
9451 (call-interactively 'org-store-link)
9452 (org-store-link nil)))))))
9454 ((eq major-mode 'calendar-mode)
9455 (let ((cd (calendar-cursor-to-date)))
9456 (setq link
9457 (format-time-string
9458 (car org-time-stamp-formats)
9459 (apply 'encode-time
9460 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9461 nil nil nil))))
9462 (org-store-link-props :type "calendar" :date cd)))
9464 ((eq major-mode 'help-mode)
9465 (setq link (concat "help:" (save-excursion
9466 (goto-char (point-min))
9467 (looking-at "^[^ ]+")
9468 (match-string 0))))
9469 (org-store-link-props :type "help"))
9471 ((eq major-mode 'w3-mode)
9472 (setq cpltxt (if (and (buffer-name)
9473 (not (string-match "Untitled" (buffer-name))))
9474 (buffer-name)
9475 (url-view-url t))
9476 link (url-view-url t))
9477 (org-store-link-props :type "w3" :url (url-view-url t)))
9479 ((eq major-mode 'image-mode)
9480 (setq cpltxt (concat "file:"
9481 (abbreviate-file-name buffer-file-name))
9482 link cpltxt)
9483 (org-store-link-props :type "image" :file buffer-file-name))
9485 ;; In dired, store a link to the file of the current line
9486 ((eq major-mode 'dired-mode)
9487 (let ((file (dired-get-filename nil t)))
9488 (setq file (if file
9489 (abbreviate-file-name
9490 (expand-file-name (dired-get-filename nil t)))
9491 ;; otherwise, no file so use current directory.
9492 default-directory))
9493 (setq cpltxt (concat "file:" file)
9494 link cpltxt)))
9496 ((setq search (run-hook-with-args-until-success
9497 'org-create-file-search-functions))
9498 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9499 "::" search))
9500 (setq cpltxt (or description link)))
9502 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9503 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9504 (cond
9505 ;; Store a link using the target at point
9506 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9507 (setq cpltxt
9508 (concat "file:"
9509 (abbreviate-file-name
9510 (buffer-file-name (buffer-base-buffer)))
9511 "::" (match-string 1))
9512 link cpltxt))
9513 ((and (featurep 'org-id)
9514 (or (eq org-id-link-to-org-use-id t)
9515 (and (org-called-interactively-p 'any)
9516 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9517 (and (eq org-id-link-to-org-use-id
9518 'create-if-interactive-and-no-custom-id)
9519 (not custom-id))))
9520 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9521 ;; Store a link using the ID at point
9522 (setq link (condition-case nil
9523 (prog1 (org-id-store-link)
9524 (setq desc (plist-get org-store-link-plist
9525 :description)))
9526 (error
9527 ;; Probably before first headline, link only to file
9528 (concat "file:"
9529 (abbreviate-file-name
9530 (buffer-file-name (buffer-base-buffer))))))))
9532 ;; Just link to current headline
9533 (setq cpltxt (concat "file:"
9534 (abbreviate-file-name
9535 (buffer-file-name (buffer-base-buffer)))))
9536 ;; Add a context search string
9537 (when (org-xor org-context-in-file-links arg)
9538 (let* ((ee (org-element-at-point))
9539 (et (org-element-type ee))
9540 (ev (plist-get (cadr ee) :value))
9541 (ek (plist-get (cadr ee) :key))
9542 (eok (and (stringp ek) (string-match "name" ek))))
9543 (setq txt (cond
9544 ((org-at-heading-p) nil)
9545 ((and (eq et 'keyword) eok) ev)
9546 ((org-region-active-p)
9547 (buffer-substring (region-beginning) (region-end)))))
9548 (when (or (null txt) (string-match "\\S-" txt))
9549 (setq cpltxt
9550 (concat cpltxt "::"
9551 (condition-case nil
9552 (org-make-org-heading-search-string txt)
9553 (error "")))
9554 desc (or (and (eq et 'keyword) eok ev)
9555 (nth 4 (ignore-errors (org-heading-components)))
9556 "NONE")))))
9557 (if (string-match "::\\'" cpltxt)
9558 (setq cpltxt (substring cpltxt 0 -2)))
9559 (setq link cpltxt))))
9561 ((buffer-file-name (buffer-base-buffer))
9562 ;; Just link to this file here.
9563 (setq cpltxt (concat "file:"
9564 (abbreviate-file-name
9565 (buffer-file-name (buffer-base-buffer)))))
9566 ;; Add a context string.
9567 (when (org-xor org-context-in-file-links arg)
9568 (setq txt (if (org-region-active-p)
9569 (buffer-substring (region-beginning) (region-end))
9570 (buffer-substring (point-at-bol) (point-at-eol))))
9571 ;; Only use search option if there is some text.
9572 (when (string-match "\\S-" txt)
9573 (setq cpltxt
9574 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9575 desc "NONE")))
9576 (setq link cpltxt))
9578 ((org-called-interactively-p 'interactive)
9579 (user-error "No method for storing a link from this buffer"))
9581 (t (setq link nil)))
9583 ;; We're done setting link and desc, clean up
9584 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9585 (setq link (or link cpltxt)
9586 desc (or desc cpltxt))
9587 (cond ((equal desc "NONE") (setq desc nil))
9588 ((string-match org-bracket-link-analytic-regexp desc)
9589 (let ((d0 (match-string 3 desc))
9590 (p0 (match-string 5 desc)))
9591 (setq desc
9592 (replace-regexp-in-string
9593 org-bracket-link-regexp
9594 (concat (or p0 d0)
9595 (if (equal (length (match-string 0 desc))
9596 (length desc)) "*" "")) desc)))))
9598 ;; Return the link
9599 (if (not (and (or (org-called-interactively-p 'any)
9600 executing-kbd-macro) link))
9601 (or agenda-link (and link (org-make-link-string link desc)))
9602 (push (list link desc) org-stored-links)
9603 (message "Stored: %s" (or desc link))
9604 (when custom-id
9605 (setq link (concat "file:" (abbreviate-file-name
9606 (buffer-file-name)) "::#" custom-id))
9607 (push (list link desc) org-stored-links)))))))
9609 (defun org-store-link-props (&rest plist)
9610 "Store link properties, extract names and addresses."
9611 (let (x adr)
9612 (when (setq x (plist-get plist :from))
9613 (setq adr (mail-extract-address-components x))
9614 (setq plist (plist-put plist :fromname (car adr)))
9615 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9616 (when (setq x (plist-get plist :to))
9617 (setq adr (mail-extract-address-components x))
9618 (setq plist (plist-put plist :toname (car adr)))
9619 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9620 (let ((from (plist-get plist :from))
9621 (to (plist-get plist :to)))
9622 (when (and from to org-from-is-user-regexp)
9623 (setq plist
9624 (plist-put plist :fromto
9625 (if (string-match org-from-is-user-regexp from)
9626 (concat "to %t")
9627 (concat "from %f"))))))
9628 (setq org-store-link-plist plist))
9630 (defun org-add-link-props (&rest plist)
9631 "Add these properties to the link property list."
9632 (let (key value)
9633 (while plist
9634 (setq key (pop plist) value (pop plist))
9635 (setq org-store-link-plist
9636 (plist-put org-store-link-plist key value)))))
9638 (defun org-email-link-description (&optional fmt)
9639 "Return the description part of an email link.
9640 This takes information from `org-store-link-plist' and formats it
9641 according to FMT (default from `org-email-link-description-format')."
9642 (setq fmt (or fmt org-email-link-description-format))
9643 (let* ((p org-store-link-plist)
9644 (to (plist-get p :toaddress))
9645 (from (plist-get p :fromaddress))
9646 (table
9647 (list
9648 (cons "%c" (plist-get p :fromto))
9649 (cons "%F" (plist-get p :from))
9650 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9651 (cons "%T" (plist-get p :to))
9652 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9653 (cons "%s" (plist-get p :subject))
9654 (cons "%d" (plist-get p :date))
9655 (cons "%m" (plist-get p :message-id)))))
9656 (when (string-match "%c" fmt)
9657 ;; Check if the user wrote this message
9658 (if (and org-from-is-user-regexp from to
9659 (save-match-data (string-match org-from-is-user-regexp from)))
9660 (setq fmt (replace-match "to %t" t t fmt))
9661 (setq fmt (replace-match "from %f" t t fmt))))
9662 (org-replace-escapes fmt table)))
9664 (defun org-make-org-heading-search-string (&optional string)
9665 "Make search string for the current headline or STRING."
9666 (let ((s (or string
9667 (and (derived-mode-p 'org-mode)
9668 (save-excursion
9669 (org-back-to-heading t)
9670 (org-element-property :raw-value (org-element-at-point))))))
9671 (lines org-context-in-file-links))
9672 (or string (setq s (concat "*" s))) ; Add * for headlines
9673 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9674 (when (and string (integerp lines) (> lines 0))
9675 (let ((slines (org-split-string s "\n")))
9676 (when (< lines (length slines))
9677 (setq s (mapconcat
9678 'identity
9679 (reverse (nthcdr (- (length slines) lines)
9680 (reverse slines))) "\n")))))
9681 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9683 (defun org-make-link-string (link &optional description)
9684 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9685 (unless (string-match "\\S-" link)
9686 (error "Empty link"))
9687 (when (and description
9688 (stringp description)
9689 (not (string-match "\\S-" description)))
9690 (setq description nil))
9691 (when (stringp description)
9692 ;; Remove brackets from the description, they are fatal.
9693 (while (string-match "\\[" description)
9694 (setq description (replace-match "{" t t description)))
9695 (while (string-match "\\]" description)
9696 (setq description (replace-match "}" t t description))))
9697 (when (equal link description)
9698 ;; No description needed, it is identical
9699 (setq description nil))
9700 (when (and (not description)
9701 (not (string-match (org-image-file-name-regexp) link))
9702 (not (equal link (org-link-escape link))))
9703 (setq description (org-extract-attributes link)))
9704 (setq link
9705 (cond ((string-match (org-image-file-name-regexp) link) link)
9706 ((string-match org-link-types-re link)
9707 (concat (match-string 1 link)
9708 (org-link-escape (substring link (match-end 1)))))
9709 (t (org-link-escape link))))
9710 (concat "[[" link "]"
9711 (if description (concat "[" description "]") "")
9712 "]"))
9714 (defconst org-link-escape-chars
9715 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9716 "List of characters that should be escaped in link.
9717 This is the list that is used for internal purposes.")
9719 (defconst org-link-escape-chars-browser
9720 '(?\ ?\")
9721 "List of escapes for characters that are problematic in links.
9722 This is the list that is used before handing over to the browser.")
9724 (defun org-link-escape (text &optional table merge)
9725 "Return percent escaped representation of TEXT.
9726 TEXT is a string with the text to escape.
9727 Optional argument TABLE is a list with characters that should be
9728 escaped. When nil, `org-link-escape-chars' is used.
9729 If optional argument MERGE is set, merge TABLE into
9730 `org-link-escape-chars'."
9731 (cond
9732 ((and table merge)
9733 (mapc (lambda (defchr)
9734 (unless (member defchr table)
9735 (setq table (cons defchr table)))) org-link-escape-chars))
9736 ((null table)
9737 (setq table org-link-escape-chars)))
9738 (mapconcat
9739 (lambda (char)
9740 (if (or (member char table)
9741 (and (or (< char 32) (= char 37) (> char 126))
9742 org-url-hexify-p))
9743 (mapconcat (lambda (sequence-element)
9744 (format "%%%.2X" sequence-element))
9745 (or (encode-coding-char char 'utf-8)
9746 (error "Unable to percent escape character: %s"
9747 (char-to-string char))) "")
9748 (char-to-string char))) text ""))
9750 (defun org-link-unescape (str)
9751 "Unhex hexified Unicode strings as returned from the JavaScript function
9752 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9753 (unless (and (null str) (string= "" str))
9754 (let ((pos 0) (case-fold-search t) unhexed)
9755 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9756 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9757 (setq str (replace-match unhexed t t str))
9758 (setq pos (+ pos (length unhexed))))))
9759 str)
9761 (defun org-link-unescape-compound (hex)
9762 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9763 Note: this function also decodes single byte encodings like
9764 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9765 (save-match-data
9766 (let* ((bytes (cdr (split-string hex "%")))
9767 (ret "")
9768 (eat 0)
9769 (sum 0))
9770 (while bytes
9771 (let* ((val (string-to-number (pop bytes) 16))
9772 (shift-xor
9773 (if (= 0 eat)
9774 (cond
9775 ((>= val 252) (cons 6 252))
9776 ((>= val 248) (cons 5 248))
9777 ((>= val 240) (cons 4 240))
9778 ((>= val 224) (cons 3 224))
9779 ((>= val 192) (cons 2 192))
9780 (t (cons 0 0)))
9781 (cons 6 128))))
9782 (if (>= val 192) (setq eat (car shift-xor)))
9783 (setq val (logxor val (cdr shift-xor)))
9784 (setq sum (+ (lsh sum (car shift-xor)) val))
9785 (if (> eat 0) (setq eat (- eat 1)))
9786 (cond
9787 ((= 0 eat) ;multi byte
9788 (setq ret (concat ret (org-char-to-string sum)))
9789 (setq sum 0))
9790 ((not bytes) ; single byte(s)
9791 (setq ret (org-link-unescape-single-byte-sequence hex))))
9792 )) ;; end (while bytes
9793 ret )))
9795 (defun org-link-unescape-single-byte-sequence (hex)
9796 "Unhexify hex-encoded single byte character sequences."
9797 (mapconcat (lambda (byte)
9798 (char-to-string (string-to-number byte 16)))
9799 (cdr (split-string hex "%")) ""))
9801 (defun org-xor (a b)
9802 "Exclusive or."
9803 (if a (not b) b))
9805 (defun org-fixup-message-id-for-http (s)
9806 "Replace special characters in a message id, so it can be used in an http query."
9807 (when (string-match "%" s)
9808 (setq s (mapconcat (lambda (c)
9809 (if (eq c ?%)
9810 "%25"
9811 (char-to-string c)))
9812 s "")))
9813 (while (string-match "<" s)
9814 (setq s (replace-match "%3C" t t s)))
9815 (while (string-match ">" s)
9816 (setq s (replace-match "%3E" t t s)))
9817 (while (string-match "@" s)
9818 (setq s (replace-match "%40" t t s)))
9821 (defun org-link-prettify (link)
9822 "Return a human-readable representation of LINK.
9823 The car of LINK must be a raw link the cdr of LINK must be either
9824 a link description or nil."
9825 (let ((desc (or (cadr link) "<no description>")))
9826 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9827 "<" (car link) ">")))
9829 ;;;###autoload
9830 (defun org-insert-link-global ()
9831 "Insert a link like Org-mode does.
9832 This command can be called in any mode to insert a link in Org-mode syntax."
9833 (interactive)
9834 (org-load-modules-maybe)
9835 (org-run-like-in-org-mode 'org-insert-link))
9837 (defun org-insert-all-links (&optional keep)
9838 "Insert all links in `org-stored-links'."
9839 (interactive "P")
9840 (let ((links (copy-sequence org-stored-links)) l)
9841 (while (setq l (if keep (pop links) (pop org-stored-links)))
9842 (insert "- ")
9843 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9844 (insert "\n"))))
9846 (defun org-link-fontify-links-to-this-file ()
9847 "Fontify links to the current file in `org-stored-links'."
9848 (let ((f (buffer-file-name)) a b)
9849 (setq a (mapcar (lambda(l)
9850 (let ((ll (car l)))
9851 (when (and (string-match "^file:\\(.+\\)::" ll)
9852 (equal f (expand-file-name (match-string 1 ll))))
9853 ll)))
9854 org-stored-links))
9855 (when (featurep 'org-id)
9856 (setq b (mapcar (lambda(l)
9857 (let ((ll (car l)))
9858 (when (and (string-match "^id:\\(.+\\)$" ll)
9859 (equal f (expand-file-name
9860 (or (org-id-find-id-file
9861 (match-string 1 ll)) ""))))
9862 ll)))
9863 org-stored-links)))
9864 (mapcar (lambda(l)
9865 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9866 (delq nil (append a b)))))
9868 (defvar org-link-links-in-this-file nil)
9869 (defun org-insert-link (&optional complete-file link-location default-description)
9870 "Insert a link. At the prompt, enter the link.
9872 Completion can be used to insert any of the link protocol prefixes like
9873 http or ftp in use.
9875 The history can be used to select a link previously stored with
9876 `org-store-link'. When the empty string is entered (i.e. if you just
9877 press RET at the prompt), the link defaults to the most recently
9878 stored link. As SPC triggers completion in the minibuffer, you need to
9879 use M-SPC or C-q SPC to force the insertion of a space character.
9881 You will also be prompted for a description, and if one is given, it will
9882 be displayed in the buffer instead of the link.
9884 If there is already a link at point, this command will allow you to edit link
9885 and description parts.
9887 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9888 be selected using completion. The path to the file will be relative to the
9889 current directory if the file is in the current directory or a subdirectory.
9890 Otherwise, the link will be the absolute path as completed in the minibuffer
9891 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9892 option `org-link-file-path-type'.
9894 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9895 the current directory or below.
9897 With three \\[universal-argument] prefixes, negate the meaning of
9898 `org-keep-stored-link-after-insertion'.
9900 If `org-make-link-description-function' is non-nil, this function will be
9901 called with the link target, and the result will be the default
9902 link description.
9904 If the LINK-LOCATION parameter is non-nil, this value will be
9905 used as the link location instead of reading one interactively.
9907 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9908 be used as the default description."
9909 (interactive "P")
9910 (let* ((wcf (current-window-configuration))
9911 (origbuf (current-buffer))
9912 (region (if (org-region-active-p)
9913 (buffer-substring (region-beginning) (region-end))))
9914 (remove (and region (list (region-beginning) (region-end))))
9915 (desc region)
9916 tmphist ; byte-compile incorrectly complains about this
9917 (link link-location)
9918 (abbrevs org-link-abbrev-alist-local)
9919 entry file all-prefixes auto-desc)
9920 (cond
9921 (link-location) ; specified by arg, just use it.
9922 ((org-in-regexp org-bracket-link-regexp 1)
9923 ;; We do have a link at point, and we are going to edit it.
9924 (setq remove (list (match-beginning 0) (match-end 0)))
9925 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9926 (setq link (read-string "Link: "
9927 (org-link-unescape
9928 (org-match-string-no-properties 1)))))
9929 ((or (org-in-regexp org-angle-link-re)
9930 (org-in-regexp org-plain-link-re))
9931 ;; Convert to bracket link
9932 (setq remove (list (match-beginning 0) (match-end 0))
9933 link (read-string "Link: "
9934 (org-remove-angle-brackets (match-string 0)))))
9935 ((member complete-file '((4) (16)))
9936 ;; Completing read for file names.
9937 (setq link (org-file-complete-link complete-file)))
9939 ;; Read link, with completion for stored links.
9940 (org-link-fontify-links-to-this-file)
9941 (org-switch-to-buffer-other-window "*Org Links*")
9942 (with-current-buffer "*Org Links*"
9943 (erase-buffer)
9944 (insert "Insert a link.
9945 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9946 (when org-stored-links
9947 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9948 (insert (mapconcat 'org-link-prettify
9949 (reverse org-stored-links) "\n")))
9950 (goto-char (point-min)))
9951 (let ((cw (selected-window)))
9952 (select-window (get-buffer-window "*Org Links*" 'visible))
9953 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9954 (unless (pos-visible-in-window-p (point-max))
9955 (org-fit-window-to-buffer))
9956 (and (window-live-p cw) (select-window cw)))
9957 ;; Fake a link history, containing the stored links.
9958 (setq tmphist (append (mapcar 'car org-stored-links)
9959 org-insert-link-history))
9960 (setq all-prefixes (append (mapcar 'car abbrevs)
9961 (mapcar 'car org-link-abbrev-alist)
9962 org-link-types))
9963 (unwind-protect
9964 (progn
9965 (setq link
9966 (org-completing-read
9967 "Link: "
9968 (append
9969 (mapcar (lambda (x) (concat x ":"))
9970 all-prefixes)
9971 (mapcar 'car org-stored-links))
9972 nil nil nil
9973 'tmphist
9974 (caar org-stored-links)))
9975 (if (not (string-match "\\S-" link))
9976 (user-error "No link selected"))
9977 (mapc (lambda(l)
9978 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9979 org-stored-links)
9980 (if (or (member link all-prefixes)
9981 (and (equal ":" (substring link -1))
9982 (member (substring link 0 -1) all-prefixes)
9983 (setq link (substring link 0 -1))))
9984 (setq link (with-current-buffer origbuf
9985 (org-link-try-special-completion link)))))
9986 (set-window-configuration wcf)
9987 (kill-buffer "*Org Links*"))
9988 (setq entry (assoc link org-stored-links))
9989 (or entry (push link org-insert-link-history))
9990 (setq desc (or desc (nth 1 entry)))))
9992 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9993 (not org-keep-stored-link-after-insertion))
9994 (setq org-stored-links (delq (assoc link org-stored-links)
9995 org-stored-links)))
9997 (if (and (string-match org-plain-link-re link)
9998 (not (string-match org-ts-regexp link)))
9999 ;; URL-like link, normalize the use of angular brackets.
10000 (setq link (org-remove-angle-brackets link)))
10002 ;; Check if we are linking to the current file with a search
10003 ;; option If yes, simplify the link by using only the search
10004 ;; option.
10005 (when (and buffer-file-name
10006 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10007 (let* ((path (match-string 1 link))
10008 (case-fold-search nil)
10009 (search (match-string 2 link)))
10010 (save-match-data
10011 (if (equal (file-truename buffer-file-name) (file-truename path))
10012 ;; We are linking to this same file, with a search option
10013 (setq link search)))))
10015 ;; Check if we can/should use a relative path. If yes, simplify the link
10016 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10017 (let* ((type (match-string 1 link))
10018 (path (match-string 2 link))
10019 (origpath path)
10020 (case-fold-search nil))
10021 (cond
10022 ((or (eq org-link-file-path-type 'absolute)
10023 (equal complete-file '(16)))
10024 (setq path (abbreviate-file-name (expand-file-name path))))
10025 ((eq org-link-file-path-type 'noabbrev)
10026 (setq path (expand-file-name path)))
10027 ((eq org-link-file-path-type 'relative)
10028 (setq path (file-relative-name path)))
10030 (save-match-data
10031 (if (string-match (concat "^" (regexp-quote
10032 (expand-file-name
10033 (file-name-as-directory
10034 default-directory))))
10035 (expand-file-name path))
10036 ;; We are linking a file with relative path name.
10037 (setq path (substring (expand-file-name path)
10038 (match-end 0)))
10039 (setq path (abbreviate-file-name (expand-file-name path)))))))
10040 (setq link (concat type path))
10041 (if (equal desc origpath)
10042 (setq desc path))))
10044 (if org-make-link-description-function
10045 (setq desc
10046 (or (condition-case nil
10047 (funcall org-make-link-description-function link desc)
10048 (error (progn (message "Can't get link description from `%s'"
10049 (symbol-name org-make-link-description-function))
10050 (sit-for 2) nil)))
10051 (read-string "Description: " default-description)))
10052 (if default-description (setq desc default-description)
10053 (setq desc (or (and auto-desc desc)
10054 (read-string "Description: " desc)))))
10056 (unless (string-match "\\S-" desc) (setq desc nil))
10057 (if remove (apply 'delete-region remove))
10058 (insert (org-make-link-string link desc))))
10060 (defun org-link-try-special-completion (type)
10061 "If there is completion support for link type TYPE, offer it."
10062 (let ((fun (intern (concat "org-" type "-complete-link"))))
10063 (if (functionp fun)
10064 (funcall fun)
10065 (read-string "Link (no completion support): " (concat type ":")))))
10067 (defun org-file-complete-link (&optional arg)
10068 "Create a file link using completion."
10069 (let (file link)
10070 (setq file (org-iread-file-name "File: "))
10071 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10072 (pwd1 (file-name-as-directory (abbreviate-file-name
10073 (expand-file-name ".")))))
10074 (cond
10075 ((equal arg '(16))
10076 (setq link (concat
10077 "file:"
10078 (abbreviate-file-name (expand-file-name file)))))
10079 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10080 (setq link (concat "file:" (match-string 1 file))))
10081 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10082 (expand-file-name file))
10083 (setq link (concat
10084 "file:" (match-string 1 (expand-file-name file)))))
10085 (t (setq link (concat "file:" file)))))
10086 link))
10088 (defun org-iread-file-name (&rest args)
10089 "Read-file-name using `ido-mode' speedup if available.
10090 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10091 See `read-file-name' for a description of parameters."
10092 (org-without-partial-completion
10093 (if (and org-completion-use-ido
10094 (fboundp 'ido-read-file-name)
10095 (boundp 'ido-mode) ido-mode
10096 (listp (second args)))
10097 (let ((ido-enter-matching-directory nil))
10098 (apply 'ido-read-file-name args))
10099 (apply 'read-file-name args))))
10101 (defun org-completing-read (&rest args)
10102 "Completing-read with SPACE being a normal character."
10103 (let ((enable-recursive-minibuffers t)
10104 (minibuffer-local-completion-map
10105 (copy-keymap minibuffer-local-completion-map)))
10106 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10107 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10108 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10109 (apply 'org-icompleting-read args)))
10111 (defun org-completing-read-no-i (&rest args)
10112 (let (org-completion-use-ido org-completion-use-iswitchb)
10113 (apply 'org-completing-read args)))
10115 (defun org-iswitchb-completing-read (prompt choices &rest args)
10116 "Use iswitch as a completing-read replacement to choose from choices.
10117 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10118 from."
10119 (let* ((iswitchb-use-virtual-buffers nil)
10120 (iswitchb-make-buflist-hook
10121 (lambda ()
10122 (setq iswitchb-temp-buflist choices))))
10123 (iswitchb-read-buffer prompt)))
10125 (defun org-icompleting-read (&rest args)
10126 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10127 (org-without-partial-completion
10128 (if (and org-completion-use-ido
10129 (fboundp 'ido-completing-read)
10130 (boundp 'ido-mode) ido-mode
10131 (listp (second args)))
10132 (let ((ido-enter-matching-directory nil))
10133 (apply 'ido-completing-read (concat (car args))
10134 (if (consp (car (nth 1 args)))
10135 (mapcar 'car (nth 1 args))
10136 (nth 1 args))
10137 (cddr args)))
10138 (if (and org-completion-use-iswitchb
10139 (boundp 'iswitchb-mode) iswitchb-mode
10140 (listp (second args)))
10141 (apply 'org-iswitchb-completing-read (concat (car args))
10142 (if (consp (car (nth 1 args)))
10143 (mapcar 'car (nth 1 args))
10144 (nth 1 args))
10145 (cddr args))
10146 (apply 'completing-read args)))))
10148 (defun org-extract-attributes (s)
10149 "Extract the attributes cookie from a string and set as text property."
10150 (let (a attr (start 0) key value)
10151 (save-match-data
10152 (when (string-match "{{\\([^}]+\\)}}$" s)
10153 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10154 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10155 (setq key (match-string 1 a) value (match-string 2 a)
10156 start (match-end 0)
10157 attr (plist-put attr (intern key) value))))
10158 (org-add-props s nil 'org-attr attr))
10161 ;;; Opening/following a link
10163 (defvar org-link-search-failed nil)
10165 (defvar org-open-link-functions nil
10166 "Hook for functions finding a plain text link.
10167 These functions must take a single argument, the link content.
10168 They will be called for links that look like [[link text][description]]
10169 when LINK TEXT does not have a protocol like \"http:\" and does not look
10170 like a filename (e.g. \"./blue.png\").
10172 These functions will be called *before* Org attempts to resolve the
10173 link by doing text searches in the current buffer - so if you want a
10174 link \"[[target]]\" to still find \"<<target>>\", your function should
10175 handle this as a special case.
10177 When the function does handle the link, it must return a non-nil value.
10178 If it decides that it is not responsible for this link, it must return
10179 nil to indicate that that Org-mode can continue with other options
10180 like exact and fuzzy text search.")
10182 (defun org-next-link (&optional search-backward)
10183 "Move forward to the next link.
10184 If the link is in hidden text, expose it."
10185 (interactive "P")
10186 (when (and org-link-search-failed (eq this-command last-command))
10187 (goto-char (point-min))
10188 (message "Link search wrapped back to beginning of buffer"))
10189 (setq org-link-search-failed nil)
10190 (let* ((pos (point))
10191 (ct (org-context))
10192 (a (assoc :link ct))
10193 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10194 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10195 ((looking-at org-any-link-re)
10196 ;; Don't stay stuck at link without an org-link face
10197 (forward-char (if search-backward -1 1))))
10198 (if (funcall srch-fun org-any-link-re nil t)
10199 (progn
10200 (goto-char (match-beginning 0))
10201 (if (outline-invisible-p) (org-show-context)))
10202 (goto-char pos)
10203 (setq org-link-search-failed t)
10204 (message "No further link found"))))
10206 (defun org-previous-link ()
10207 "Move backward to the previous link.
10208 If the link is in hidden text, expose it."
10209 (interactive)
10210 (funcall 'org-next-link t))
10212 (defun org-translate-link (s)
10213 "Translate a link string if a translation function has been defined."
10214 (if (and org-link-translation-function
10215 (fboundp org-link-translation-function)
10216 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10217 (progn
10218 (setq s (funcall org-link-translation-function
10219 (match-string 1 s) (match-string 2 s)))
10220 (concat (car s) ":" (cdr s)))
10223 (defun org-translate-link-from-planner (type path)
10224 "Translate a link from Emacs Planner syntax so that Org can follow it.
10225 This is still an experimental function, your mileage may vary."
10226 (cond
10227 ((member type '("http" "https" "news" "ftp"))
10228 ;; standard Internet links are the same.
10229 nil)
10230 ((and (equal type "irc") (string-match "^//" path))
10231 ;; Planner has two / at the beginning of an irc link, we have 1.
10232 ;; We should have zero, actually....
10233 (setq path (substring path 1)))
10234 ((and (equal type "lisp") (string-match "^/" path))
10235 ;; Planner has a slash, we do not.
10236 (setq type "elisp" path (substring path 1)))
10237 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10238 ;; A typical message link. Planner has the id after the final slash,
10239 ;; we separate it with a hash mark
10240 (setq path (concat (match-string 1 path) "#"
10241 (org-remove-angle-brackets (match-string 2 path))))))
10242 (cons type path))
10244 (defun org-find-file-at-mouse (ev)
10245 "Open file link or URL at mouse."
10246 (interactive "e")
10247 (mouse-set-point ev)
10248 (org-open-at-point 'in-emacs))
10250 (defun org-open-at-mouse (ev)
10251 "Open file link or URL at mouse.
10252 See the docstring of `org-open-file' for details."
10253 (interactive "e")
10254 (mouse-set-point ev)
10255 (if (eq major-mode 'org-agenda-mode)
10256 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10257 (org-open-at-point))
10259 (defvar org-window-config-before-follow-link nil
10260 "The window configuration before following a link.
10261 This is saved in case the need arises to restore it.")
10263 (defvar org-open-link-marker (make-marker)
10264 "Marker pointing to the location where `org-open-at-point; was called.")
10266 ;;;###autoload
10267 (defun org-open-at-point-global ()
10268 "Follow a link like Org-mode does.
10269 This command can be called in any mode to follow a link that has
10270 Org-mode syntax."
10271 (interactive)
10272 (org-run-like-in-org-mode 'org-open-at-point))
10274 ;;;###autoload
10275 (defun org-open-link-from-string (s &optional arg reference-buffer)
10276 "Open a link in the string S, as if it was in Org-mode."
10277 (interactive "sLink: \nP")
10278 (let ((reference-buffer (or reference-buffer (current-buffer))))
10279 (with-temp-buffer
10280 (let ((org-inhibit-startup (not reference-buffer)))
10281 (org-mode)
10282 (insert s)
10283 (goto-char (point-min))
10284 (when reference-buffer
10285 (setq org-link-abbrev-alist-local
10286 (with-current-buffer reference-buffer
10287 org-link-abbrev-alist-local)))
10288 (org-open-at-point arg reference-buffer)))))
10290 (defvar org-open-at-point-functions nil
10291 "Hook that is run when following a link at point.
10293 Functions in this hook must return t if they identify and follow
10294 a link at point. If they don't find anything interesting at point,
10295 they must return nil.")
10297 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10298 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10299 (defun org-open-at-point (&optional arg reference-buffer)
10300 "Open link at or after point.
10301 If there is no link at point, this function will search forward up to
10302 the end of the current line.
10303 Normally, files will be opened by an appropriate application. If the
10304 optional prefix argument ARG is non-nil, Emacs will visit the file.
10305 With a double prefix argument, try to open outside of Emacs, in the
10306 application the system uses for this file type."
10307 (interactive "P")
10308 ;; if in a code block, then open the block's results
10309 (unless (call-interactively #'org-babel-open-src-block-result)
10310 (org-load-modules-maybe)
10311 (move-marker org-open-link-marker (point))
10312 (setq org-window-config-before-follow-link (current-window-configuration))
10313 (org-remove-occur-highlights nil nil t)
10314 (cond
10315 ((and (org-at-heading-p)
10316 (not (org-at-timestamp-p t))
10317 (not (org-in-regexp
10318 (concat org-plain-link-re "\\|"
10319 org-bracket-link-regexp "\\|"
10320 org-angle-link-re "\\|"
10321 "[ \t]:[^ \t\n]+:[ \t]*$")))
10322 (not (get-text-property (point) 'org-linked-text)))
10323 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10324 (lk0 (car lkall))
10325 (lk (if (stringp lk0) (list lk0) lk0))
10326 (lkend (cdr lkall)))
10327 (mapcar (lambda(l)
10328 (search-forward l nil lkend)
10329 (goto-char (match-beginning 0))
10330 (org-open-at-point))
10331 lk))
10332 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10333 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10334 ((and (org-at-timestamp-p t)
10335 (not (org-in-regexp org-bracket-link-regexp)))
10336 (org-follow-timestamp-link))
10337 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10338 (not (org-in-regexp org-any-link-re)))
10339 (org-footnote-action))
10341 (let (type path link line search (pos (point)))
10342 (catch 'match
10343 (save-excursion
10344 (skip-chars-forward "^]\n\r")
10345 (when (org-in-regexp org-bracket-link-regexp 1)
10346 (setq link (org-extract-attributes
10347 (org-link-unescape (org-match-string-no-properties 1))))
10348 (while (string-match " *\n *" link)
10349 (setq link (replace-match " " t t link)))
10350 (setq link (org-link-expand-abbrev link))
10351 (cond
10352 ((or (file-name-absolute-p link)
10353 (string-match "^\\.\\.?/" link))
10354 (setq type "file" path link))
10355 ((string-match org-link-re-with-space3 link)
10356 (setq type (match-string 1 link) path (match-string 2 link)))
10357 ((string-match "^help:+\\(.+\\)" link)
10358 (setq type "help" path (match-string 1 link)))
10359 (t (setq type "thisfile" path link)))
10360 (throw 'match t)))
10362 (when (get-text-property (point) 'org-linked-text)
10363 (setq type "thisfile"
10364 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10365 (1+ (point)) (point))
10366 path (buffer-substring
10367 (or (previous-single-property-change pos 'org-linked-text)
10368 (point-min))
10369 (or (next-single-property-change pos 'org-linked-text)
10370 (point-max)))
10371 ;; Ensure we will search for a <<<radio>>> link, not
10372 ;; a simple reference like <<ref>>
10373 path (concat "<" path))
10374 (throw 'match t))
10376 (save-excursion
10377 (when (or (org-in-regexp org-angle-link-re)
10378 (let ((match (org-in-regexp org-plain-link-re)))
10379 ;; Check a plain link is not within a bracket link
10380 (and match
10381 (save-excursion
10382 (progn
10383 (goto-char (car match))
10384 (not (org-in-regexp org-bracket-link-regexp))))))
10385 (let ((line_ending (save-excursion (end-of-line) (point))))
10386 ;; We are in a line before a plain or bracket link
10387 (or (re-search-forward org-plain-link-re line_ending t)
10388 (re-search-forward org-bracket-link-regexp line_ending t))))
10389 (setq type (match-string 1)
10390 path (org-link-unescape (match-string 2)))
10391 (throw 'match t)))
10392 (save-excursion
10393 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10394 (setq type "tags"
10395 path (match-string 1))
10396 (while (string-match ":" path)
10397 (setq path (replace-match "+" t t path)))
10398 (throw 'match t)))
10399 (when (org-in-regexp "<\\([^><\n]+\\)>")
10400 (setq type "tree-match"
10401 path (match-string 1))
10402 (throw 'match t)))
10403 (unless path
10404 (user-error "No link found"))
10406 ;; switch back to reference buffer
10407 ;; needed when if called in a temporary buffer through
10408 ;; org-open-link-from-string
10409 (with-current-buffer (or reference-buffer (current-buffer))
10411 ;; Remove any trailing spaces in path
10412 (if (string-match " +\\'" path)
10413 (setq path (replace-match "" t t path)))
10414 (if (and org-link-translation-function
10415 (fboundp org-link-translation-function))
10416 ;; Check if we need to translate the link
10417 (let ((tmp (funcall org-link-translation-function type path)))
10418 (setq type (car tmp) path (cdr tmp))))
10420 (cond
10422 ((assoc type org-link-protocols)
10423 (funcall (nth 1 (assoc type org-link-protocols)) path))
10425 ((equal type "help")
10426 (let ((f-or-v (intern path)))
10427 (cond ((fboundp f-or-v)
10428 (describe-function f-or-v))
10429 ((boundp f-or-v)
10430 (describe-variable f-or-v))
10431 (t (error "Not a known function or variable")))))
10433 ((equal type "mailto")
10434 (let ((cmd (car org-link-mailto-program))
10435 (args (cdr org-link-mailto-program)) args1
10436 (address path) (subject "") a)
10437 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10438 (setq address (match-string 1 path)
10439 subject (org-link-escape (match-string 2 path))))
10440 (while args
10441 (cond
10442 ((not (stringp (car args))) (push (pop args) args1))
10443 (t (setq a (pop args))
10444 (if (string-match "%a" a)
10445 (setq a (replace-match address t t a)))
10446 (if (string-match "%s" a)
10447 (setq a (replace-match subject t t a)))
10448 (push a args1))))
10449 (apply cmd (nreverse args1))))
10451 ((member type '("http" "https" "ftp" "news"))
10452 (browse-url
10453 (concat type ":"
10454 (if (org-string-match-p
10455 (concat "[[:nonascii:]"
10456 org-link-escape-chars-browser "]")
10457 path)
10458 (org-link-escape path org-link-escape-chars-browser)
10459 path))))
10461 ((string= type "doi")
10462 (browse-url
10463 (concat org-doi-server-url
10464 (if (org-string-match-p
10465 (concat "[[:nonascii:]"
10466 org-link-escape-chars-browser "]")
10467 path)
10468 (org-link-escape path org-link-escape-chars-browser)
10469 path))))
10471 ((member type '("message"))
10472 (browse-url (concat type ":" path)))
10474 ((string= type "tags")
10475 (org-tags-view arg path))
10477 ((string= type "tree-match")
10478 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10480 ((string= type "file")
10481 (if (string-match "::\\([0-9]+\\)\\'" path)
10482 (setq line (string-to-number (match-string 1 path))
10483 path (substring path 0 (match-beginning 0)))
10484 (if (string-match "::\\(.+\\)\\'" path)
10485 (setq search (match-string 1 path)
10486 path (substring path 0 (match-beginning 0)))))
10487 (if (string-match "[*?{]" (file-name-nondirectory path))
10488 (dired path)
10489 (org-open-file path arg line search)))
10491 ((string= type "shell")
10492 (let ((buf (generate-new-buffer "*Org Shell Output"))
10493 (cmd path))
10494 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10495 (string-match org-confirm-shell-link-not-regexp cmd))
10496 (not org-confirm-shell-link-function)
10497 (funcall org-confirm-shell-link-function
10498 (format "Execute \"%s\" in shell? "
10499 (org-add-props cmd nil
10500 'face 'org-warning))))
10501 (progn
10502 (message "Executing %s" cmd)
10503 (shell-command cmd buf)
10504 (if (featurep 'midnight)
10505 (setq clean-buffer-list-kill-buffer-names
10506 (cons buf clean-buffer-list-kill-buffer-names))))
10507 (error "Abort"))))
10509 ((string= type "elisp")
10510 (let ((cmd path))
10511 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10512 (string-match org-confirm-elisp-link-not-regexp cmd))
10513 (not org-confirm-elisp-link-function)
10514 (funcall org-confirm-elisp-link-function
10515 (format "Execute \"%s\" as elisp? "
10516 (org-add-props cmd nil
10517 'face 'org-warning))))
10518 (message "%s => %s" cmd
10519 (if (equal (string-to-char cmd) ?\()
10520 (eval (read cmd))
10521 (call-interactively (read cmd))))
10522 (error "Abort"))))
10524 ((and (string= type "thisfile")
10525 (or (run-hook-with-args-until-success
10526 'org-open-link-functions path)
10527 (and link
10528 (string-match "^id:" link)
10529 (or (featurep 'org-id) (require 'org-id))
10530 (progn
10531 (funcall (nth 1 (assoc "id" org-link-protocols))
10532 (substring path 3))
10533 t)))))
10535 ((string= type "thisfile")
10536 (if arg
10537 (switch-to-buffer-other-window
10538 (org-get-buffer-for-internal-link (current-buffer)))
10539 (org-mark-ring-push))
10540 (let ((cmd `(org-link-search
10541 ,path
10542 ,(cond ((equal arg '(4)) ''occur)
10543 ((equal arg '(16)) ''org-occur))
10544 ,pos)))
10545 (condition-case nil (let ((org-link-search-inhibit-query t))
10546 (eval cmd))
10547 (error (progn (widen) (eval cmd))))))
10549 (t (browse-url-at-point)))))))
10550 (move-marker org-open-link-marker nil)
10551 (run-hook-with-args 'org-follow-link-hook)))
10553 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10554 "Offer links in the current entry and return the selected link.
10555 If there is only one link, return it.
10556 If NTH is an integer, return the NTH link found.
10557 If ZERO is a string, check also this string for a link, and if
10558 there is one, return it."
10559 (with-current-buffer buffer
10560 (save-excursion
10561 (save-restriction
10562 (widen)
10563 (goto-char marker)
10564 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10565 "\\(" org-angle-link-re "\\)\\|"
10566 "\\(" org-plain-link-re "\\)"))
10567 (cnt ?0)
10568 (in-emacs (if (integerp nth) nil nth))
10569 have-zero end links link c)
10570 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10571 (push (match-string 0 zero) links)
10572 (setq cnt (1- cnt) have-zero t))
10573 (save-excursion
10574 (org-back-to-heading t)
10575 (setq end (save-excursion (outline-next-heading) (point)))
10576 (while (re-search-forward re end t)
10577 (push (match-string 0) links))
10578 (setq links (org-uniquify (reverse links))))
10579 (cond
10580 ((null links)
10581 (message "No links"))
10582 ((equal (length links) 1)
10583 (setq link (car links)))
10584 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10585 (setq link (nth (if have-zero nth (1- nth)) links)))
10586 (t ; we have to select a link
10587 (save-excursion
10588 (save-window-excursion
10589 (delete-other-windows)
10590 (with-output-to-temp-buffer "*Select Link*"
10591 (mapc (lambda (l)
10592 (if (not (string-match org-bracket-link-regexp l))
10593 (princ (format "[%c] %s\n" (incf cnt)
10594 (org-remove-angle-brackets l)))
10595 (if (match-end 3)
10596 (princ (format "[%c] %s (%s)\n" (incf cnt)
10597 (match-string 3 l) (match-string 1 l)))
10598 (princ (format "[%c] %s\n" (incf cnt)
10599 (match-string 1 l))))))
10600 links))
10601 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10602 (message "Select link to open, RET to open all:")
10603 (setq c (read-char-exclusive))
10604 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10605 (when (equal c ?q) (error "Abort"))
10606 (if (equal c ?\C-m)
10607 (setq link links)
10608 (setq nth (- c ?0))
10609 (if have-zero (setq nth (1+ nth)))
10610 (unless (and (integerp nth) (>= (length links) nth))
10611 (user-error "Invalid link selection"))
10612 (setq link (nth (1- nth) links)))))
10613 (cons link end))))))
10615 ;; Add special file links that specify the way of opening
10617 (org-add-link-type "file+sys" 'org-open-file-with-system)
10618 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10619 (defun org-open-file-with-system (path)
10620 "Open file at PATH using the system way of opening it."
10621 (org-open-file path 'system))
10622 (defun org-open-file-with-emacs (path)
10623 "Open file at PATH in Emacs."
10624 (org-open-file path 'emacs))
10627 ;;; File search
10629 (defvar org-create-file-search-functions nil
10630 "List of functions to construct the right search string for a file link.
10631 These functions are called in turn with point at the location to
10632 which the link should point.
10634 A function in the hook should first test if it would like to
10635 handle this file type, for example by checking the `major-mode'
10636 or the file extension. If it decides not to handle this file, it
10637 should just return nil to give other functions a chance. If it
10638 does handle the file, it must return the search string to be used
10639 when following the link. The search string will be part of the
10640 file link, given after a double colon, and `org-open-at-point'
10641 will automatically search for it. If special measures must be
10642 taken to make the search successful, another function should be
10643 added to the companion hook `org-execute-file-search-functions',
10644 which see.
10646 A function in this hook may also use `setq' to set the variable
10647 `description' to provide a suggestion for the descriptive text to
10648 be used for this link when it gets inserted into an Org-mode
10649 buffer with \\[org-insert-link].")
10651 (defvar org-execute-file-search-functions nil
10652 "List of functions to execute a file search triggered by a link.
10654 Functions added to this hook must accept a single argument, the
10655 search string that was part of the file link, the part after the
10656 double colon. The function must first check if it would like to
10657 handle this search, for example by checking the `major-mode' or
10658 the file extension. If it decides not to handle this search, it
10659 should just return nil to give other functions a chance. If it
10660 does handle the search, it must return a non-nil value to keep
10661 other functions from trying.
10663 Each function can access the current prefix argument through the
10664 variable `current-prefix-arg'. Note that a single prefix is used
10665 to force opening a link in Emacs, so it may be good to only use a
10666 numeric or double prefix to guide the search function.
10668 In case this is needed, a function in this hook can also restore
10669 the window configuration before `org-open-at-point' was called using:
10671 (set-window-configuration org-window-config-before-follow-link)")
10673 (defun org-link-search (s &optional type avoid-pos stealth)
10674 "Search for a link search option.
10675 If S is surrounded by forward slashes, it is interpreted as a
10676 regular expression. In org-mode files, this will create an `org-occur'
10677 sparse tree. In ordinary files, `occur' will be used to list matches.
10678 If the current buffer is in `dired-mode', grep will be used to search
10679 in all files. If AVOID-POS is given, ignore matches near that position.
10681 When optional argument STEALTH is non-nil, do not modify
10682 visibility around point, thus ignoring
10683 `org-show-hierarchy-above', `org-show-following-heading' and
10684 `org-show-siblings' variables."
10685 (let ((case-fold-search t)
10686 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10687 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10688 (append '(("") (" ") ("\t") ("\n"))
10689 org-emphasis-alist)
10690 "\\|") "\\)"))
10691 (pos (point))
10692 (pre nil) (post nil)
10693 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10694 (cond
10695 ;; First check if there are any special search functions
10696 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10697 ;; Now try the builtin stuff
10698 ((and (equal (string-to-char s0) ?#)
10699 (> (length s0) 1)
10700 (save-excursion
10701 (goto-char (point-min))
10702 (and
10703 (re-search-forward
10704 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10705 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10706 (setq type 'dedicated
10707 pos (match-beginning 0))))
10708 ;; There is an exact target for this
10709 (goto-char pos)
10710 (org-back-to-heading t)))
10711 ((save-excursion
10712 (goto-char (point-min))
10713 (and
10714 (re-search-forward
10715 (concat "<<" (regexp-quote s0) ">>") nil t)
10716 (setq type 'dedicated
10717 pos (match-beginning 0))))
10718 ;; There is an exact target for this
10719 (goto-char pos))
10720 ((save-excursion
10721 (goto-char (point-min))
10722 (and
10723 (re-search-forward
10724 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10725 (setq type 'dedicated pos (match-beginning 0))))
10726 ;; Found an element with a matching #+name affiliated keyword.
10727 (goto-char pos))
10728 ((and (string-match "^(\\(.*\\))$" s0)
10729 (save-excursion
10730 (goto-char (point-min))
10731 (and
10732 (re-search-forward
10733 (concat "[^[]" (regexp-quote
10734 (format org-coderef-label-format
10735 (match-string 1 s0))))
10736 nil t)
10737 (setq type 'dedicated
10738 pos (1+ (match-beginning 0))))))
10739 ;; There is a coderef target for this
10740 (goto-char pos))
10741 ((string-match "^/\\(.*\\)/$" s)
10742 ;; A regular expression
10743 (cond
10744 ((derived-mode-p 'org-mode)
10745 (org-occur (match-string 1 s)))
10746 (t (org-do-occur (match-string 1 s)))))
10747 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10748 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10749 (goto-char (point-min))
10750 (cond
10751 ((let (case-fold-search)
10752 (re-search-forward (format org-complex-heading-regexp-format
10753 (regexp-quote s))
10754 nil t))
10755 ;; OK, found a match
10756 (setq type 'dedicated)
10757 (goto-char (match-beginning 0)))
10758 ((and (not org-link-search-inhibit-query)
10759 (eq org-link-search-must-match-exact-headline 'query-to-create)
10760 (y-or-n-p "No match - create this as a new heading? "))
10761 (goto-char (point-max))
10762 (or (bolp) (newline))
10763 (insert "* " s "\n")
10764 (beginning-of-line 0))
10766 (goto-char pos)
10767 (error "No match"))))
10769 ;; A normal search string
10770 (when (equal (string-to-char s) ?*)
10771 ;; Anchor on headlines, post may include tags.
10772 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10773 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10774 s (substring s 1)))
10775 (remove-text-properties
10776 0 (length s)
10777 '(face nil mouse-face nil keymap nil fontified nil) s)
10778 ;; Make a series of regular expressions to find a match
10779 (setq words (org-split-string s "[ \n\r\t]+")
10781 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10782 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10783 "\\)" markers)
10784 re2a_ (concat "\\(" (mapconcat 'downcase words
10785 "[ \t\r\n]+") "\\)[ \t\r\n]")
10786 re2a (concat "[ \t\r\n]" re2a_)
10787 re4_ (concat "\\(" (mapconcat 'downcase words
10788 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10789 re4 (concat "[^a-zA-Z_]" re4_)
10791 re1 (concat pre re2 post)
10792 re3 (concat pre (if pre re4_ re4) post)
10793 re5 (concat pre ".*" re4)
10794 re2 (concat pre re2)
10795 re2a (concat pre (if pre re2a_ re2a))
10796 re4 (concat pre (if pre re4_ re4))
10797 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10798 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10799 re5 "\\)"))
10800 (cond
10801 ((eq type 'org-occur) (org-occur reall))
10802 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10803 (t (goto-char (point-min))
10804 (setq type 'fuzzy)
10805 (if (or (and (org-search-not-self 1 re0 nil t)
10806 (setq type 'dedicated))
10807 (org-search-not-self 1 re1 nil t)
10808 (org-search-not-self 1 re2 nil t)
10809 (org-search-not-self 1 re2a nil t)
10810 (org-search-not-self 1 re3 nil t)
10811 (org-search-not-self 1 re4 nil t)
10812 (org-search-not-self 1 re5 nil t))
10813 (goto-char (match-beginning 1))
10814 (goto-char pos)
10815 (error "No match"))))))
10816 (and (derived-mode-p 'org-mode)
10817 (not stealth)
10818 (org-show-context 'link-search))
10819 type))
10821 (defun org-search-not-self (group &rest args)
10822 "Execute `re-search-forward', but only accept matches that do not
10823 enclose the position of `org-open-link-marker'."
10824 (let ((m org-open-link-marker))
10825 (catch 'exit
10826 (while (apply 're-search-forward args)
10827 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10828 (goto-char (match-end group))
10829 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10830 (> (match-beginning 0) (marker-position m))
10831 (< (match-end 0) (marker-position m)))
10832 (save-match-data
10833 (or (not (org-in-regexp
10834 org-bracket-link-analytic-regexp 1))
10835 (not (match-end 4)) ; no description
10836 (and (<= (match-beginning 4) (point))
10837 (>= (match-end 4) (point))))))
10838 (throw 'exit (point))))))))
10840 (defun org-get-buffer-for-internal-link (buffer)
10841 "Return a buffer to be used for displaying the link target of internal links."
10842 (cond
10843 ((not org-display-internal-link-with-indirect-buffer)
10844 buffer)
10845 ((string-match "(Clone)$" (buffer-name buffer))
10846 (message "Buffer is already a clone, not making another one")
10847 ;; we also do not modify visibility in this case
10848 buffer)
10849 (t ; make a new indirect buffer for displaying the link
10850 (let* ((bn (buffer-name buffer))
10851 (ibn (concat bn "(Clone)"))
10852 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10853 (with-current-buffer ib (org-overview))
10854 ib))))
10856 (defun org-do-occur (regexp &optional cleanup)
10857 "Call the Emacs command `occur'.
10858 If CLEANUP is non-nil, remove the printout of the regular expression
10859 in the *Occur* buffer. This is useful if the regex is long and not useful
10860 to read."
10861 (occur regexp)
10862 (when cleanup
10863 (let ((cwin (selected-window)) win beg end)
10864 (when (setq win (get-buffer-window "*Occur*"))
10865 (select-window win))
10866 (goto-char (point-min))
10867 (when (re-search-forward "match[a-z]+" nil t)
10868 (setq beg (match-end 0))
10869 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10870 (setq end (1- (match-beginning 0)))))
10871 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10872 (goto-char (point-min))
10873 (select-window cwin))))
10875 ;;; The mark ring for links jumps
10877 (defvar org-mark-ring nil
10878 "Mark ring for positions before jumps in Org-mode.")
10879 (defvar org-mark-ring-last-goto nil
10880 "Last position in the mark ring used to go back.")
10881 ;; Fill and close the ring
10882 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10883 (loop for i from 1 to org-mark-ring-length do
10884 (push (make-marker) org-mark-ring))
10885 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10886 org-mark-ring)
10888 (defun org-mark-ring-push (&optional pos buffer)
10889 "Put the current position or POS into the mark ring and rotate it."
10890 (interactive)
10891 (setq pos (or pos (point)))
10892 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10893 (move-marker (car org-mark-ring)
10894 (or pos (point))
10895 (or buffer (current-buffer)))
10896 (message "%s"
10897 (substitute-command-keys
10898 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10900 (defun org-mark-ring-goto (&optional n)
10901 "Jump to the previous position in the mark ring.
10902 With prefix arg N, jump back that many stored positions. When
10903 called several times in succession, walk through the entire ring.
10904 Org-mode commands jumping to a different position in the current file,
10905 or to another Org-mode file, automatically push the old position
10906 onto the ring."
10907 (interactive "p")
10908 (let (p m)
10909 (if (eq last-command this-command)
10910 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10911 (setq p org-mark-ring))
10912 (setq org-mark-ring-last-goto p)
10913 (setq m (car p))
10914 (org-pop-to-buffer-same-window (marker-buffer m))
10915 (goto-char m)
10916 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10918 (defun org-remove-angle-brackets (s)
10919 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10920 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10922 (defun org-add-angle-brackets (s)
10923 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10924 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10926 (defun org-remove-double-quotes (s)
10927 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10928 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10931 ;;; Following specific links
10933 (defun org-follow-timestamp-link ()
10934 "Open an agenda view for the time-stamp date/range at point."
10935 (cond
10936 ((org-at-date-range-p t)
10937 (let ((org-agenda-start-on-weekday)
10938 (t1 (match-string 1))
10939 (t2 (match-string 2)) tt1 tt2)
10940 (setq tt1 (time-to-days (org-time-string-to-time t1))
10941 tt2 (time-to-days (org-time-string-to-time t2)))
10942 (let ((org-agenda-buffer-tmp-name
10943 (format "*Org Agenda(a:%s)"
10944 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10945 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10946 ((org-at-timestamp-p t)
10947 (let ((org-agenda-buffer-tmp-name
10948 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10949 (org-agenda-list nil (time-to-days (org-time-string-to-time
10950 (substring (match-string 1) 0 10)))
10951 1)))
10952 (t (error "This should not happen"))))
10955 ;;; Following file links
10956 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10957 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10958 (declare-function mailcap-mime-info
10959 "mailcap" (string &optional request no-decode))
10960 (defvar org-wait nil)
10961 (defun org-open-file (path &optional in-emacs line search)
10962 "Open the file at PATH.
10963 First, this expands any special file name abbreviations. Then the
10964 configuration variable `org-file-apps' is checked if it contains an
10965 entry for this file type, and if yes, the corresponding command is launched.
10967 If no application is found, Emacs simply visits the file.
10969 With optional prefix argument IN-EMACS, Emacs will visit the file.
10970 With a double \\[universal-argument] \\[universal-argument] \
10971 prefix arg, Org tries to avoid opening in Emacs
10972 and to use an external application to visit the file.
10974 Optional LINE specifies a line to go to, optional SEARCH a string
10975 to search for. If LINE or SEARCH is given, the file will be
10976 opened in Emacs, unless an entry from org-file-apps that makes
10977 use of groups in a regexp matches.
10979 If you want to change the way frames are used when following a
10980 link, please customize `org-link-frame-setup'.
10982 If the file does not exist, an error is thrown."
10983 (let* ((file (if (equal path "")
10984 buffer-file-name
10985 (substitute-in-file-name (expand-file-name path))))
10986 (file-apps (append org-file-apps (org-default-apps)))
10987 (apps (org-remove-if
10988 'org-file-apps-entry-match-against-dlink-p file-apps))
10989 (apps-dlink (org-remove-if-not
10990 'org-file-apps-entry-match-against-dlink-p file-apps))
10991 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10992 (dirp (if remp nil (file-directory-p file)))
10993 (file (if (and dirp org-open-directory-means-index-dot-org)
10994 (concat (file-name-as-directory file) "index.org")
10995 file))
10996 (a-m-a-p (assq 'auto-mode apps))
10997 (dfile (downcase file))
10998 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10999 (link (cond ((and (eq line nil)
11000 (eq search nil))
11001 file)
11002 (line
11003 (concat file "::" (number-to-string line)))
11004 (search
11005 (concat file "::" search))))
11006 (dlink (downcase link))
11007 (old-buffer (current-buffer))
11008 (old-pos (point))
11009 (old-mode major-mode)
11010 ext cmd link-match-data)
11011 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11012 (setq ext (match-string 1 dfile))
11013 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11014 (setq ext (match-string 1 dfile))))
11015 (cond
11016 ((member in-emacs '((16) system))
11017 (setq cmd (cdr (assoc 'system apps))))
11018 (in-emacs (setq cmd 'emacs))
11020 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11021 (and dirp (cdr (assoc 'directory apps)))
11022 ; first, try matching against apps-dlink
11023 ; if we get a match here, store the match data for later
11024 (let ((match (assoc-default dlink apps-dlink
11025 'string-match)))
11026 (if match
11027 (progn (setq link-match-data (match-data))
11028 match)
11029 (progn (setq in-emacs (or in-emacs line search))
11030 nil))) ; if we have no match in apps-dlink,
11031 ; always open the file in emacs if line or search
11032 ; is given (for backwards compatibility)
11033 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11034 'string-match)
11035 (cdr (assoc ext apps))
11036 (cdr (assoc t apps))))))
11037 (when (eq cmd 'system)
11038 (setq cmd (cdr (assoc 'system apps))))
11039 (when (eq cmd 'default)
11040 (setq cmd (cdr (assoc t apps))))
11041 (when (eq cmd 'mailcap)
11042 (require 'mailcap)
11043 (mailcap-parse-mailcaps)
11044 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11045 (command (mailcap-mime-info mime-type)))
11046 (if (stringp command)
11047 (setq cmd command)
11048 (setq cmd 'emacs))))
11049 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11050 (not (file-exists-p file))
11051 (not org-open-non-existing-files))
11052 (user-error "No such file: %s" file))
11053 (cond
11054 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11055 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11056 (while (string-match "['\"]%s['\"]" cmd)
11057 (setq cmd (replace-match "%s" t t cmd)))
11058 (while (string-match "%s" cmd)
11059 (setq cmd (replace-match
11060 (save-match-data
11061 (shell-quote-argument
11062 (convert-standard-filename file)))
11063 t t cmd)))
11065 ;; Replace "%1", "%2" etc. in command with group matches from regex
11066 (save-match-data
11067 (let ((match-index 1)
11068 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11069 (set-match-data link-match-data)
11070 (while (<= match-index number-of-groups)
11071 (let ((regex (concat "%" (number-to-string match-index)))
11072 (replace-with (match-string match-index dlink)))
11073 (while (string-match regex cmd)
11074 (setq cmd (replace-match replace-with t t cmd))))
11075 (setq match-index (+ match-index 1)))))
11077 (save-window-excursion
11078 (message "Running %s...done" cmd)
11079 (start-process-shell-command cmd nil cmd)
11080 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11081 ((or (stringp cmd)
11082 (eq cmd 'emacs))
11083 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11084 (widen)
11085 (if line (org-goto-line line)
11086 (if search (org-link-search search))))
11087 ((consp cmd)
11088 (let ((file (convert-standard-filename file)))
11089 (save-match-data
11090 (set-match-data link-match-data)
11091 (eval cmd))))
11092 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11093 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11094 (or (not (equal old-buffer (current-buffer)))
11095 (not (equal old-pos (point))))
11096 (org-mark-ring-push old-pos old-buffer))))
11098 (defun org-file-apps-entry-match-against-dlink-p (entry)
11099 "This function returns non-nil if `entry' uses a regular
11100 expression which should be matched against the whole link by
11101 org-open-file.
11103 It assumes that is the case when the entry uses a regular
11104 expression which has at least one grouping construct and the
11105 action is either a lisp form or a command string containing
11106 '%1', i.e. using at least one subexpression match as a
11107 parameter."
11108 (let ((selector (car entry))
11109 (action (cdr entry)))
11110 (if (stringp selector)
11111 (and (> (regexp-opt-depth selector) 0)
11112 (or (and (stringp action)
11113 (string-match "%[0-9]" action))
11114 (consp action)))
11115 nil)))
11117 (defun org-default-apps ()
11118 "Return the default applications for this operating system."
11119 (cond
11120 ((eq system-type 'darwin)
11121 org-file-apps-defaults-macosx)
11122 ((eq system-type 'windows-nt)
11123 org-file-apps-defaults-windowsnt)
11124 (t org-file-apps-defaults-gnu)))
11126 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11127 "Convert extensions to regular expressions in the cars of LIST.
11128 Also, weed out any non-string entries, because the return value is used
11129 only for regexp matching.
11130 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11131 point to the symbol `emacs', indicating that the file should
11132 be opened in Emacs."
11133 (append
11134 (delq nil
11135 (mapcar (lambda (x)
11136 (if (not (stringp (car x)))
11138 (if (string-match "\\W" (car x))
11140 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11141 list))
11142 (if add-auto-mode
11143 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11145 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11146 (defun org-file-remote-p (file)
11147 "Test whether FILE specifies a location on a remote system.
11148 Return non-nil if the location is indeed remote.
11150 For example, the filename \"/user@host:/foo\" specifies a location
11151 on the system \"/user@host:\"."
11152 (cond ((fboundp 'file-remote-p)
11153 (file-remote-p file))
11154 ((fboundp 'tramp-handle-file-remote-p)
11155 (tramp-handle-file-remote-p file))
11156 ((and (boundp 'ange-ftp-name-format)
11157 (string-match (car ange-ftp-name-format) file))
11158 t)))
11161 ;;;; Refiling
11163 (defun org-get-org-file ()
11164 "Read a filename, with default directory `org-directory'."
11165 (let ((default (or org-default-notes-file remember-data-file)))
11166 (read-file-name (format "File name [%s]: " default)
11167 (file-name-as-directory org-directory)
11168 default)))
11170 (defun org-notes-order-reversed-p ()
11171 "Check if the current file should receive notes in reversed order."
11172 (cond
11173 ((not org-reverse-note-order) nil)
11174 ((eq t org-reverse-note-order) t)
11175 ((not (listp org-reverse-note-order)) nil)
11176 (t (catch 'exit
11177 (let ((all org-reverse-note-order)
11178 entry)
11179 (while (setq entry (pop all))
11180 (if (string-match (car entry) buffer-file-name)
11181 (throw 'exit (cdr entry))))
11182 nil)))))
11184 (defvar org-refile-target-table nil
11185 "The list of refile targets, created by `org-refile'.")
11187 (defvar org-agenda-new-buffers nil
11188 "Buffers created to visit agenda files.")
11190 (defvar org-refile-cache nil
11191 "Cache for refile targets.")
11193 (defvar org-refile-markers nil
11194 "All the markers used for caching refile locations.")
11196 (defun org-refile-marker (pos)
11197 "Get a new refile marker, but only if caching is in use."
11198 (if (not org-refile-use-cache)
11200 (let ((m (make-marker)))
11201 (move-marker m pos)
11202 (push m org-refile-markers)
11203 m)))
11205 (defun org-refile-cache-clear ()
11206 "Clear the refile cache and disable all the markers."
11207 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11208 (setq org-refile-markers nil)
11209 (setq org-refile-cache nil)
11210 (message "Refile cache has been cleared"))
11212 (defun org-refile-cache-check-set (set)
11213 "Check if all the markers in the cache still have live buffers."
11214 (let (marker)
11215 (catch 'exit
11216 (while (and set (setq marker (nth 3 (pop set))))
11217 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11218 (when (and marker (null (marker-buffer marker)))
11219 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11220 (sit-for 3)
11221 (throw 'exit nil)))
11222 t)))
11224 (defun org-refile-cache-put (set &rest identifiers)
11225 "Push the refile targets SET into the cache, under IDENTIFIERS."
11226 (let* ((key (sha1 (prin1-to-string identifiers)))
11227 (entry (assoc key org-refile-cache)))
11228 (if entry
11229 (setcdr entry set)
11230 (push (cons key set) org-refile-cache))))
11232 (defun org-refile-cache-get (&rest identifiers)
11233 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11234 (cond
11235 ((not org-refile-cache) nil)
11236 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11238 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11239 org-refile-cache))))
11240 (and set (org-refile-cache-check-set set) set)))))
11242 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11243 "Produce a table with refile targets."
11244 (let ((case-fold-search nil)
11245 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11246 (entries (or org-refile-targets '((nil . (:level . 1)))))
11247 targets tgs txt re files f desc descre fast-path-p level pos0)
11248 (message "Getting targets...")
11249 (with-current-buffer (or default-buffer (current-buffer))
11250 (while (setq entry (pop entries))
11251 (setq files (car entry) desc (cdr entry))
11252 (setq fast-path-p nil)
11253 (cond
11254 ((null files) (setq files (list (current-buffer))))
11255 ((eq files 'org-agenda-files)
11256 (setq files (org-agenda-files 'unrestricted)))
11257 ((and (symbolp files) (fboundp files))
11258 (setq files (funcall files)))
11259 ((and (symbolp files) (boundp files))
11260 (setq files (symbol-value files))))
11261 (if (stringp files) (setq files (list files)))
11262 (cond
11263 ((eq (car desc) :tag)
11264 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11265 ((eq (car desc) :todo)
11266 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11267 ((eq (car desc) :regexp)
11268 (setq descre (cdr desc)))
11269 ((eq (car desc) :level)
11270 (setq descre (concat "^\\*\\{" (number-to-string
11271 (if org-odd-levels-only
11272 (1- (* 2 (cdr desc)))
11273 (cdr desc)))
11274 "\\}[ \t]")))
11275 ((eq (car desc) :maxlevel)
11276 (setq fast-path-p t)
11277 (setq descre (concat "^\\*\\{1," (number-to-string
11278 (if org-odd-levels-only
11279 (1- (* 2 (cdr desc)))
11280 (cdr desc)))
11281 "\\}[ \t]")))
11282 (t (error "Bad refiling target description %s" desc)))
11283 (while (setq f (pop files))
11284 (with-current-buffer
11285 (if (bufferp f) f (org-get-agenda-file-buffer f))
11287 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11288 (progn
11289 (if (bufferp f) (setq f (buffer-file-name
11290 (buffer-base-buffer f))))
11291 (setq f (and f (expand-file-name f)))
11292 (if (eq org-refile-use-outline-path 'file)
11293 (push (list (file-name-nondirectory f) f nil nil) tgs))
11294 (save-excursion
11295 (save-restriction
11296 (widen)
11297 (goto-char (point-min))
11298 (while (re-search-forward descre nil t)
11299 (goto-char (setq pos0 (point-at-bol)))
11300 (catch 'next
11301 (when org-refile-target-verify-function
11302 (save-match-data
11303 (or (funcall org-refile-target-verify-function)
11304 (throw 'next t))))
11305 (when (and (looking-at org-complex-heading-regexp)
11306 (not (member (match-string 4) excluded-entries))
11307 (match-string 4))
11308 (setq level (org-reduced-level
11309 (- (match-end 1) (match-beginning 1)))
11310 txt (org-link-display-format (match-string 4))
11311 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11312 re (format org-complex-heading-regexp-format
11313 (regexp-quote (match-string 4))))
11314 (when org-refile-use-outline-path
11315 (setq txt (mapconcat
11316 'org-protect-slash
11317 (append
11318 (if (eq org-refile-use-outline-path
11319 'file)
11320 (list (file-name-nondirectory
11321 (buffer-file-name
11322 (buffer-base-buffer))))
11323 (if (eq org-refile-use-outline-path
11324 'full-file-path)
11325 (list (buffer-file-name
11326 (buffer-base-buffer)))))
11327 (org-get-outline-path fast-path-p
11328 level txt)
11329 (list txt))
11330 "/")))
11331 (push (list txt f re (org-refile-marker (point)))
11332 tgs)))
11333 (when (= (point) pos0)
11334 ;; verification function has not moved point
11335 (goto-char (point-at-eol))))))))
11336 (when org-refile-use-cache
11337 (org-refile-cache-put tgs (buffer-file-name) descre))
11338 (setq targets (append tgs targets))))))
11339 (message "Getting targets...done")
11340 (nreverse targets)))
11342 (defun org-protect-slash (s)
11343 (while (string-match "/" s)
11344 (setq s (replace-match "\\" t t s)))
11347 (defvar org-olpa (make-vector 20 nil))
11349 (defun org-get-outline-path (&optional fastp level heading)
11350 "Return the outline path to the current entry, as a list.
11352 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11353 routine which makes outline path derivations for an entire file,
11354 avoiding backtracing. Refile target collection makes use of that."
11355 (if fastp
11356 (progn
11357 (if (> level 19)
11358 (error "Outline path failure, more than 19 levels"))
11359 (loop for i from level upto 19 do
11360 (aset org-olpa i nil))
11361 (prog1
11362 (delq nil (append org-olpa nil))
11363 (aset org-olpa level heading)))
11364 (let (rtn case-fold-search)
11365 (save-excursion
11366 (save-restriction
11367 (widen)
11368 (while (org-up-heading-safe)
11369 (when (looking-at org-complex-heading-regexp)
11370 (push (org-trim
11371 (replace-regexp-in-string
11372 ;; Remove statistical/checkboxes cookies
11373 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11374 (org-match-string-no-properties 4)))
11375 rtn)))
11376 rtn)))))
11378 (defun org-format-outline-path (path &optional width prefix separator)
11379 "Format the outline path PATH for display.
11380 WIDTH is the maximum number of characters that is available.
11381 PREFIX is a prefix to be included in the returned string,
11382 such as the file name.
11383 SEPARATOR is inserted between the different parts of the path,
11384 the default is \"/\"."
11385 (setq width (or width 79))
11386 (if prefix (setq width (- width (length prefix))))
11387 (if (not path)
11388 (or prefix "")
11389 (let* ((nsteps (length path))
11390 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11391 (maxwidth (if (<= total-width width)
11392 10000 ;; everything fits
11393 ;; we need to shorten the level headings
11394 (/ (- width nsteps) nsteps)))
11395 (org-odd-levels-only nil)
11396 (n 0)
11397 (total (1+ (length prefix))))
11398 (setq maxwidth (max maxwidth 10))
11399 (concat prefix
11400 (if prefix (or separator "/"))
11401 (mapconcat
11402 (lambda (h)
11403 (setq n (1+ n))
11404 (if (and (= n nsteps) (< maxwidth 10000))
11405 (setq maxwidth (- total-width total)))
11406 (if (< (length h) maxwidth)
11407 (progn (setq total (+ total (length h) 1)) h)
11408 (setq h (substring h 0 (- maxwidth 2))
11409 total (+ total maxwidth 1))
11410 (if (string-match "[ \t]+\\'" h)
11411 (setq h (substring h 0 (match-beginning 0))))
11412 (setq h (concat h "..")))
11413 (org-add-props h nil 'face
11414 (nth (% (1- n) org-n-level-faces)
11415 org-level-faces))
11417 path (or separator "/"))))))
11419 (defun org-display-outline-path (&optional file current separator just-return-string)
11420 "Display the current outline path in the echo area.
11422 If FILE is non-nil, prepend the output with the file name.
11423 If CURRENT is non-nil, append the current heading to the output.
11424 SEPARATOR is passed through to `org-format-outline-path'. It separates
11425 the different parts of the path and defaults to \"/\".
11426 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11427 (interactive "P")
11428 (let* (case-fold-search
11429 (bfn (buffer-file-name (buffer-base-buffer)))
11430 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11431 res)
11432 (if current (setq path (append path
11433 (save-excursion
11434 (org-back-to-heading t)
11435 (if (looking-at org-complex-heading-regexp)
11436 (list (match-string 4)))))))
11437 (setq res
11438 (org-format-outline-path
11439 path
11440 (1- (frame-width))
11441 (and file bfn (concat (file-name-nondirectory bfn) separator))
11442 separator))
11443 (if just-return-string
11444 (org-no-properties res)
11445 (org-unlogged-message "%s" res))))
11447 (defvar org-refile-history nil
11448 "History for refiling operations.")
11450 (defvar org-after-refile-insert-hook nil
11451 "Hook run after `org-refile' has inserted its stuff at the new location.
11452 Note that this is still *before* the stuff will be removed from
11453 the *old* location.")
11455 (defvar org-capture-last-stored-marker)
11456 (defvar org-refile-keep nil
11457 "Non-nil means `org-refile' will copy instead of refile.")
11459 (defun org-copy ()
11460 "Like `org-refile', but copy."
11461 (interactive)
11462 (let ((org-refile-keep t))
11463 (funcall 'org-refile nil nil nil "Copy")))
11465 (defun org-refile (&optional goto default-buffer rfloc msg)
11466 "Move the entry or entries at point to another heading.
11467 The list of target headings is compiled using the information in
11468 `org-refile-targets', which see.
11470 At the target location, the entry is filed as a subitem of the target
11471 heading. Depending on `org-reverse-note-order', the new subitem will
11472 either be the first or the last subitem.
11474 If there is an active region, all entries in that region will be moved.
11475 However, the region must fulfill the requirement that the first heading
11476 is the first one sets the top-level of the moved text - at most siblings
11477 below it are allowed.
11479 With prefix arg GOTO, the command will only visit the target location
11480 and not actually move anything.
11482 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11483 go to the location where the last refiling operation has put the subtree.
11485 With a numeric prefix argument of `2', refile to the running clock.
11487 With a numeric prefix argument of `3', emulate `org-refile-keep'
11488 being set to `t' and copy to the target location, don't move it.
11489 Beware that keeping refiled entries may result in duplicated ID
11490 properties.
11492 RFLOC can be a refile location obtained in a different way.
11494 MSG is a string to replace \"Refile\" in the default prompt with
11495 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11497 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11499 If you are using target caching (see `org-refile-use-cache'),
11500 you have to clear the target cache in order to find new targets.
11501 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11502 prefix argument (`C-u C-u C-u C-c C-w')."
11504 (interactive "P")
11505 (if (member goto '(0 (64)))
11506 (org-refile-cache-clear)
11507 (let* ((actionmsg (or msg "Refile"))
11508 (cbuf (current-buffer))
11509 (regionp (org-region-active-p))
11510 (region-start (and regionp (region-beginning)))
11511 (region-end (and regionp (region-end)))
11512 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11513 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11514 pos it nbuf file re level reversed)
11515 (setq last-command nil)
11516 (when regionp
11517 (goto-char region-start)
11518 (or (bolp) (goto-char (point-at-bol)))
11519 (setq region-start (point))
11520 (unless (or (org-kill-is-subtree-p
11521 (buffer-substring region-start region-end))
11522 (prog1 org-refile-active-region-within-subtree
11523 (let ((s (point-at-eol)))
11524 (org-toggle-heading)
11525 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11526 (user-error "The region is not a (sequence of) subtree(s)")))
11527 (if (equal goto '(16))
11528 (org-refile-goto-last-stored)
11529 (when (or
11530 (and (equal goto 2)
11531 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11532 (prog1
11533 (setq it (list (or org-clock-heading "running clock")
11534 (buffer-file-name
11535 (marker-buffer org-clock-hd-marker))
11537 (marker-position org-clock-hd-marker)))
11538 (setq goto nil)))
11539 (setq it (or rfloc
11540 (let (heading-text)
11541 (save-excursion
11542 (unless goto
11543 (org-back-to-heading t)
11544 (setq heading-text
11545 (nth 4 (org-heading-components))))
11547 (org-refile-get-location
11548 (cond (goto "Goto")
11549 (regionp (concat actionmsg " region to"))
11550 (t (concat actionmsg " subtree \""
11551 heading-text "\" to")))
11552 default-buffer
11553 (and (not (equal '(4) goto))
11554 org-refile-allow-creating-parent-nodes)
11555 goto))))))
11556 (setq file (nth 1 it)
11557 re (nth 2 it)
11558 pos (nth 3 it))
11559 (if (and (not goto)
11561 (equal (buffer-file-name) file)
11562 (if regionp
11563 (and (>= pos region-start)
11564 (<= pos region-end))
11565 (and (>= pos (point))
11566 (< pos (save-excursion
11567 (org-end-of-subtree t t))))))
11568 (error "Cannot refile to position inside the tree or region"))
11570 (setq nbuf (or (find-buffer-visiting file)
11571 (find-file-noselect file)))
11572 (if (and goto (not (equal goto 3)))
11573 (progn
11574 (org-pop-to-buffer-same-window nbuf)
11575 (goto-char pos)
11576 (org-show-context 'org-goto))
11577 (if regionp
11578 (progn
11579 (org-kill-new (buffer-substring region-start region-end))
11580 (org-save-markers-in-region region-start region-end))
11581 (org-copy-subtree 1 nil t))
11582 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11583 (find-file-noselect file)))
11584 (setq reversed (org-notes-order-reversed-p))
11585 (save-excursion
11586 (save-restriction
11587 (widen)
11588 (if pos
11589 (progn
11590 (goto-char pos)
11591 (looking-at org-outline-regexp)
11592 (setq level (org-get-valid-level (funcall outline-level) 1))
11593 (goto-char
11594 (if reversed
11595 (or (outline-next-heading) (point-max))
11596 (or (save-excursion (org-get-next-sibling))
11597 (org-end-of-subtree t t)
11598 (point-max)))))
11599 (setq level 1)
11600 (if (not reversed)
11601 (goto-char (point-max))
11602 (goto-char (point-min))
11603 (or (outline-next-heading) (goto-char (point-max)))))
11604 (if (not (bolp)) (newline))
11605 (org-paste-subtree level)
11606 (when org-log-refile
11607 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11608 (unless (eq org-log-refile 'note)
11609 (save-excursion (org-add-log-note))))
11610 (and org-auto-align-tags
11611 (let ((org-loop-over-headlines-in-active-region nil))
11612 (org-set-tags nil t)))
11613 (let ((bookmark-name (plist-get org-bookmark-names-plist
11614 :last-refile)))
11615 (when bookmark-name
11616 (with-demoted-errors
11617 (bookmark-set bookmark-name))))
11618 ;; If we are refiling for capture, make sure that the
11619 ;; last-capture pointers point here
11620 (when (org-bound-and-true-p org-refile-for-capture)
11621 (let ((bookmark-name (plist-get org-bookmark-names-plist
11622 :last-capture-marker)))
11623 (when bookmark-name
11624 (with-demoted-errors
11625 (bookmark-set bookmark-name))))
11626 (move-marker org-capture-last-stored-marker (point)))
11627 (if (fboundp 'deactivate-mark) (deactivate-mark))
11628 (run-hooks 'org-after-refile-insert-hook))))
11629 (unless org-refile-keep
11630 (if regionp
11631 (delete-region (point) (+ (point) (- region-end region-start)))
11632 (delete-region
11633 (and (org-back-to-heading t) (point))
11634 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11635 (when (featurep 'org-inlinetask)
11636 (org-inlinetask-remove-END-maybe))
11637 (setq org-markers-to-move nil)
11638 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11640 (defun org-refile-goto-last-stored ()
11641 "Go to the location where the last refile was stored."
11642 (interactive)
11643 (bookmark-jump "org-refile-last-stored")
11644 (message "This is the location of the last refile"))
11646 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11647 no-exclude)
11648 "Prompt the user for a refile location, using PROMPT.
11649 PROMPT should not be suffixed with a colon and a space, because
11650 this function appends the default value from
11651 `org-refile-history' automatically, if that is not empty.
11652 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11653 this is used for the GOTO interface."
11654 (let ((org-refile-targets org-refile-targets)
11655 (org-refile-use-outline-path org-refile-use-outline-path)
11656 excluded-entries)
11657 (when (and (derived-mode-p 'org-mode)
11658 (not org-refile-use-cache)
11659 (not no-exclude))
11660 (org-map-tree
11661 (lambda()
11662 (setq excluded-entries
11663 (append excluded-entries (list (org-get-heading t t)))))))
11664 (setq org-refile-target-table
11665 (org-refile-get-targets default-buffer excluded-entries)))
11666 (unless org-refile-target-table
11667 (user-error "No refile targets"))
11668 (let* ((cbuf (current-buffer))
11669 (partial-completion-mode nil)
11670 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11671 (cfunc (if (and org-refile-use-outline-path
11672 org-outline-path-complete-in-steps)
11673 'org-olpath-completing-read
11674 'org-icompleting-read))
11675 (extra (if org-refile-use-outline-path "/" ""))
11676 (cbnex (concat (buffer-name) extra))
11677 (filename (and cfn (expand-file-name cfn)))
11678 (tbl (mapcar
11679 (lambda (x)
11680 (if (and (not (member org-refile-use-outline-path
11681 '(file full-file-path)))
11682 (not (equal filename (nth 1 x))))
11683 (cons (concat (car x) extra " ("
11684 (file-name-nondirectory (nth 1 x)) ")")
11685 (cdr x))
11686 (cons (concat (car x) extra) (cdr x))))
11687 org-refile-target-table))
11688 (completion-ignore-case t)
11689 cdef
11690 (prompt (concat prompt
11691 (or (and (car org-refile-history)
11692 (concat " (default " (car org-refile-history) ")"))
11693 (and (assoc cbnex tbl) (setq cdef cbnex)
11694 (concat " (default " cbnex ")"))) ": "))
11695 pa answ parent-target child parent old-hist)
11696 (setq old-hist org-refile-history)
11697 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11698 nil 'org-refile-history (or cdef (car org-refile-history))))
11699 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11700 (org-refile-check-position pa)
11701 (if pa
11702 (progn
11703 (when (or (not org-refile-history)
11704 (not (eq old-hist org-refile-history))
11705 (not (equal (car pa) (car org-refile-history))))
11706 (setq org-refile-history
11707 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11708 org-refile-history
11709 (cdr org-refile-history))))
11710 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11711 (pop org-refile-history)))
11713 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11714 (progn
11715 (setq parent (match-string 1 answ)
11716 child (match-string 2 answ))
11717 (setq parent-target (or (assoc parent tbl)
11718 (assoc (concat parent "/") tbl)))
11719 (when (and parent-target
11720 (or (eq new-nodes t)
11721 (and (eq new-nodes 'confirm)
11722 (y-or-n-p (format "Create new node \"%s\"? "
11723 child)))))
11724 (org-refile-new-child parent-target child)))
11725 (user-error "Invalid target location")))))
11727 (declare-function org-string-nw-p "org-macs" (s))
11728 (defun org-refile-check-position (refile-pointer)
11729 "Check if the refile pointer matches the headline to which it points."
11730 (let* ((file (nth 1 refile-pointer))
11731 (re (nth 2 refile-pointer))
11732 (pos (nth 3 refile-pointer))
11733 buffer)
11734 (if (and (not (markerp pos)) (not file))
11735 (user-error "Please save the buffer to a file before refiling")
11736 (when (org-string-nw-p re)
11737 (setq buffer (if (markerp pos)
11738 (marker-buffer pos)
11739 (or (find-buffer-visiting file)
11740 (find-file-noselect file))))
11741 (with-current-buffer buffer
11742 (save-excursion
11743 (save-restriction
11744 (widen)
11745 (goto-char pos)
11746 (beginning-of-line 1)
11747 (unless (org-looking-at-p re)
11748 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11750 (defun org-refile-new-child (parent-target child)
11751 "Use refile target PARENT-TARGET to add new CHILD below it."
11752 (unless parent-target
11753 (error "Cannot find parent for new node"))
11754 (let ((file (nth 1 parent-target))
11755 (pos (nth 3 parent-target))
11756 level)
11757 (with-current-buffer (or (find-buffer-visiting file)
11758 (find-file-noselect file))
11759 (save-excursion
11760 (save-restriction
11761 (widen)
11762 (if pos
11763 (goto-char pos)
11764 (goto-char (point-max))
11765 (if (not (bolp)) (newline)))
11766 (when (looking-at org-outline-regexp)
11767 (setq level (funcall outline-level))
11768 (org-end-of-subtree t t))
11769 (org-back-over-empty-lines)
11770 (insert "\n" (make-string
11771 (if pos (org-get-valid-level level 1) 1) ?*)
11772 " " child "\n")
11773 (beginning-of-line 0)
11774 (list (concat (car parent-target) "/" child) file "" (point)))))))
11776 (defun org-olpath-completing-read (prompt collection &rest args)
11777 "Read an outline path like a file name."
11778 (let ((thetable collection)
11779 (org-completion-use-ido nil) ; does not work with ido.
11780 (org-completion-use-iswitchb nil)) ; or iswitchb
11781 (apply
11782 'org-icompleting-read prompt
11783 (lambda (string predicate &optional flag)
11784 (let (rtn r f (l (length string)))
11785 (cond
11786 ((eq flag nil)
11787 ;; try completion
11788 (try-completion string thetable))
11789 ((eq flag t)
11790 ;; all-completions
11791 (setq rtn (all-completions string thetable predicate))
11792 (mapcar
11793 (lambda (x)
11794 (setq r (substring x l))
11795 (if (string-match " ([^)]*)$" x)
11796 (setq f (match-string 0 x))
11797 (setq f ""))
11798 (if (string-match "/" r)
11799 (concat string (substring r 0 (match-end 0)) f)
11801 rtn))
11802 ((eq flag 'lambda)
11803 ;; exact match?
11804 (assoc string thetable)))))
11805 args)))
11807 ;;;; Dynamic blocks
11809 (defun org-find-dblock (name)
11810 "Find the first dynamic block with name NAME in the buffer.
11811 If not found, stay at current position and return nil."
11812 (let ((case-fold-search t) pos)
11813 (save-excursion
11814 (goto-char (point-min))
11815 (setq pos (and (re-search-forward
11816 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11817 (match-beginning 0))))
11818 (if pos (goto-char pos))
11819 pos))
11821 (defconst org-dblock-start-re
11822 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11823 "Matches the start line of a dynamic block, with parameters.")
11825 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11826 "Matches the end of a dynamic block.")
11828 (defun org-create-dblock (plist)
11829 "Create a dynamic block section, with parameters taken from PLIST.
11830 PLIST must contain a :name entry which is used as name of the block."
11831 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11832 (end-of-line 1)
11833 (newline))
11834 (let ((col (current-column))
11835 (name (plist-get plist :name)))
11836 (insert "#+BEGIN: " name)
11837 (while plist
11838 (if (eq (car plist) :name)
11839 (setq plist (cddr plist))
11840 (insert " " (prin1-to-string (pop plist)))))
11841 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11842 (beginning-of-line -2)))
11844 (defun org-prepare-dblock ()
11845 "Prepare dynamic block for refresh.
11846 This empties the block, puts the cursor at the insert position and returns
11847 the property list including an extra property :name with the block name."
11848 (unless (looking-at org-dblock-start-re)
11849 (user-error "Not at a dynamic block"))
11850 (let* ((begdel (1+ (match-end 0)))
11851 (name (org-no-properties (match-string 1)))
11852 (params (append (list :name name)
11853 (read (concat "(" (match-string 3) ")")))))
11854 (save-excursion
11855 (beginning-of-line 1)
11856 (skip-chars-forward " \t")
11857 (setq params (plist-put params :indentation-column (current-column))))
11858 (unless (re-search-forward org-dblock-end-re nil t)
11859 (error "Dynamic block not terminated"))
11860 (setq params
11861 (append params
11862 (list :content (buffer-substring
11863 begdel (match-beginning 0)))))
11864 (delete-region begdel (match-beginning 0))
11865 (goto-char begdel)
11866 (open-line 1)
11867 params))
11869 (defun org-map-dblocks (&optional command)
11870 "Apply COMMAND to all dynamic blocks in the current buffer.
11871 If COMMAND is not given, use `org-update-dblock'."
11872 (let ((cmd (or command 'org-update-dblock)))
11873 (save-excursion
11874 (goto-char (point-min))
11875 (while (re-search-forward org-dblock-start-re nil t)
11876 (goto-char (match-beginning 0))
11877 (save-excursion
11878 (condition-case nil
11879 (funcall cmd)
11880 (error (message "Error during update of dynamic block"))))
11881 (unless (re-search-forward org-dblock-end-re nil t)
11882 (error "Dynamic block not terminated"))))))
11884 (defun org-dblock-update (&optional arg)
11885 "User command for updating dynamic blocks.
11886 Update the dynamic block at point. With prefix ARG, update all dynamic
11887 blocks in the buffer."
11888 (interactive "P")
11889 (if arg
11890 (org-update-all-dblocks)
11891 (or (looking-at org-dblock-start-re)
11892 (org-beginning-of-dblock))
11893 (org-update-dblock)))
11895 (defun org-update-dblock ()
11896 "Update the dynamic block at point.
11897 This means to empty the block, parse for parameters and then call
11898 the correct writing function."
11899 (interactive)
11900 (save-window-excursion
11901 (let* ((pos (point))
11902 (line (org-current-line))
11903 (params (org-prepare-dblock))
11904 (name (plist-get params :name))
11905 (indent (plist-get params :indentation-column))
11906 (cmd (intern (concat "org-dblock-write:" name))))
11907 (message "Updating dynamic block `%s' at line %d..." name line)
11908 (funcall cmd params)
11909 (message "Updating dynamic block `%s' at line %d...done" name line)
11910 (goto-char pos)
11911 (when (and indent (> indent 0))
11912 (setq indent (make-string indent ?\ ))
11913 (save-excursion
11914 (org-beginning-of-dblock)
11915 (forward-line 1)
11916 (while (not (looking-at org-dblock-end-re))
11917 (insert indent)
11918 (beginning-of-line 2))
11919 (when (looking-at org-dblock-end-re)
11920 (and (looking-at "[ \t]+")
11921 (replace-match ""))
11922 (insert indent)))))))
11924 (defun org-beginning-of-dblock ()
11925 "Find the beginning of the dynamic block at point.
11926 Error if there is no such block at point."
11927 (let ((pos (point))
11928 beg)
11929 (end-of-line 1)
11930 (if (and (re-search-backward org-dblock-start-re nil t)
11931 (setq beg (match-beginning 0))
11932 (re-search-forward org-dblock-end-re nil t)
11933 (> (match-end 0) pos))
11934 (goto-char beg)
11935 (goto-char pos)
11936 (error "Not in a dynamic block"))))
11938 (defun org-update-all-dblocks ()
11939 "Update all dynamic blocks in the buffer.
11940 This function can be used in a hook."
11941 (interactive)
11942 (when (derived-mode-p 'org-mode)
11943 (org-map-dblocks 'org-update-dblock)))
11946 ;;;; Completion
11948 (declare-function org-export-backend-name "org-export" (cl-x))
11949 (declare-function org-export-backend-options "org-export" (cl-x))
11950 (defun org-get-export-keywords ()
11951 "Return a list of all currently understood export keywords.
11952 Export keywords include options, block names, attributes and
11953 keywords relative to each registered export back-end."
11954 (let (keywords)
11955 (dolist (backend
11956 (org-bound-and-true-p org-export--registered-backends)
11957 (delq nil keywords))
11958 ;; Back-end name (for keywords, like #+LATEX:)
11959 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11960 (dolist (option-entry (org-export-backend-options backend))
11961 ;; Back-end options.
11962 (push (nth 1 option-entry) keywords)))))
11964 (defconst org-options-keywords
11965 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11966 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11967 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11968 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11969 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11971 (defcustom org-structure-template-alist
11972 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11973 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11974 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11975 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11976 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11977 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11978 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11979 "<literal style=\"latex\">\n?\n</literal>")
11980 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11981 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11982 "<literal style=\"html\">\n?\n</literal>")
11983 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11984 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11985 ("A" "#+ASCII: " "")
11986 ("i" "#+INDEX: ?" "#+INDEX: ?")
11987 ("I" "#+INCLUDE: %file ?"
11988 "<include file=%file markup=\"?\">"))
11989 "Structure completion elements.
11990 This is a list of abbreviation keys and values. The value gets inserted
11991 if you type `<' followed by the key and then press the completion key,
11992 usually `M-TAB'. %file will be replaced by a file name after prompting
11993 for the file using completion. The cursor will be placed at the position
11994 of the `?` in the template.
11995 There are two templates for each key, the first uses the original Org syntax,
11996 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11997 the default when the /org-mtags.el/ module has been loaded. See also the
11998 variable `org-mtags-prefer-muse-templates'."
11999 :group 'org-completion
12000 :type '(repeat
12001 (list
12002 (string :tag "Key")
12003 (string :tag "Template")
12004 (string :tag "Muse Template"))))
12006 (defun org-try-structure-completion ()
12007 "Try to complete a structure template before point.
12008 This looks for strings like \"<e\" on an otherwise empty line and
12009 expands them."
12010 (let ((l (buffer-substring (point-at-bol) (point)))
12012 (when (and (looking-at "[ \t]*$")
12013 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12014 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12015 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12016 (match-beginning 1)) a)
12017 t)))
12019 (defun org-complete-expand-structure-template (start cell)
12020 "Expand a structure template."
12021 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12022 (rpl (nth (if musep 2 1) cell))
12023 (ind ""))
12024 (delete-region start (point))
12025 (when (string-match "\\`#\\+" rpl)
12026 (cond
12027 ((bolp))
12028 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12029 (setq ind (buffer-substring (point-at-bol) (point))))
12030 (t (newline))))
12031 (setq start (point))
12032 (if (string-match "%file" rpl)
12033 (setq rpl (replace-match
12034 (concat
12035 "\""
12036 (save-match-data
12037 (abbreviate-file-name (read-file-name "Include file: ")))
12038 "\"")
12039 t t rpl)))
12040 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12041 (concat "\n" ind)))
12042 (insert rpl)
12043 (if (re-search-backward "\\?" start t) (delete-char 1))))
12045 ;;;; TODO, DEADLINE, Comments
12047 (defun org-toggle-comment ()
12048 "Change the COMMENT state of an entry."
12049 (interactive)
12050 (save-excursion
12051 (org-back-to-heading)
12052 (let (case-fold-search)
12053 (cond
12054 ((looking-at (format org-heading-keyword-regexp-format
12055 org-comment-string))
12056 (goto-char (match-end 1))
12057 (looking-at (concat " +" org-comment-string))
12058 (replace-match "" t t)
12059 (when (eolp) (insert " ")))
12060 ((looking-at org-outline-regexp)
12061 (goto-char (match-end 0))
12062 (insert org-comment-string " "))))))
12064 (defvar org-last-todo-state-is-todo nil
12065 "This is non-nil when the last TODO state change led to a TODO state.
12066 If the last change removed the TODO tag or switched to DONE, then
12067 this is nil.")
12069 (defvar org-setting-tags nil) ; dynamically skipped
12071 (defvar org-todo-setup-filter-hook nil
12072 "Hook for functions that pre-filter todo specs.
12073 Each function takes a todo spec and returns either nil or the spec
12074 transformed into canonical form." )
12076 (defvar org-todo-get-default-hook nil
12077 "Hook for functions that get a default item for todo.
12078 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12079 nil or a string to be used for the todo mark." )
12081 (defvar org-agenda-headline-snapshot-before-repeat)
12083 (defun org-current-effective-time ()
12084 "Return current time adjusted for `org-extend-today-until' variable."
12085 (let* ((ct (org-current-time))
12086 (dct (decode-time ct))
12087 (ct1
12088 (cond
12089 (org-use-last-clock-out-time-as-effective-time
12090 (or (org-clock-get-last-clock-out-time) ct))
12091 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12092 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12093 (t ct))))
12094 ct1))
12096 (defun org-todo-yesterday (&optional arg)
12097 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12098 (interactive "P")
12099 (if (eq major-mode 'org-agenda-mode)
12100 (apply 'org-agenda-todo-yesterday arg)
12101 (let* ((hour (third (decode-time
12102 (org-current-time))))
12103 (org-extend-today-until (1+ hour)))
12104 (org-todo arg))))
12106 (defvar org-block-entry-blocking ""
12107 "First entry preventing the TODO state change.")
12109 (defun org-todo (&optional arg)
12110 "Change the TODO state of an item.
12111 The state of an item is given by a keyword at the start of the heading,
12112 like
12113 *** TODO Write paper
12114 *** DONE Call mom
12116 The different keywords are specified in the variable `org-todo-keywords'.
12117 By default the available states are \"TODO\" and \"DONE\".
12118 So for this example: when the item starts with TODO, it is changed to DONE.
12119 When it starts with DONE, the DONE is removed. And when neither TODO nor
12120 DONE are present, add TODO at the beginning of the heading.
12122 With \\[universal-argument] prefix arg, use completion to determine the new \
12123 state.
12124 With numeric prefix arg, switch to that state.
12125 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12126 keywords (nextset).
12127 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12128 With a numeric prefix arg of 0, inhibit note taking for the change.
12130 For calling through lisp, arg is also interpreted in the following way:
12131 'none -> empty state
12132 \"\"(empty string) -> switch to empty state
12133 'done -> switch to DONE
12134 'nextset -> switch to the next set of keywords
12135 'previousset -> switch to the previous set of keywords
12136 \"WAITING\" -> switch to the specified keyword, but only if it
12137 really is a member of `org-todo-keywords'."
12138 (interactive "P")
12139 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12140 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12141 'region-start-level 'region))
12142 org-loop-over-headlines-in-active-region)
12143 (org-map-entries
12144 `(org-todo ,arg)
12145 org-loop-over-headlines-in-active-region
12146 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12147 (if (equal arg '(16)) (setq arg 'nextset))
12148 (let ((org-blocker-hook org-blocker-hook)
12149 commentp
12150 case-fold-search)
12151 (when (equal arg '(64))
12152 (setq arg nil org-blocker-hook nil))
12153 (when (and org-blocker-hook
12154 (or org-inhibit-blocking
12155 (org-entry-get nil "NOBLOCKING")))
12156 (setq org-blocker-hook nil))
12157 (save-excursion
12158 (catch 'exit
12159 (org-back-to-heading t)
12160 (when (looking-at (concat "^\\*+ " org-comment-string))
12161 (org-toggle-comment)
12162 (setq commentp t))
12163 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12164 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12165 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12166 (let* ((match-data (match-data))
12167 (startpos (point-at-bol))
12168 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12169 (org-log-done org-log-done)
12170 (org-log-repeat org-log-repeat)
12171 (org-todo-log-states org-todo-log-states)
12172 (org-inhibit-logging
12173 (if (equal arg 0)
12174 (progn (setq arg nil) 'note) org-inhibit-logging))
12175 (this (match-string 1))
12176 (hl-pos (match-beginning 0))
12177 (head (org-get-todo-sequence-head this))
12178 (ass (assoc head org-todo-kwd-alist))
12179 (interpret (nth 1 ass))
12180 (done-word (nth 3 ass))
12181 (final-done-word (nth 4 ass))
12182 (org-last-state (or this ""))
12183 (completion-ignore-case t)
12184 (member (member this org-todo-keywords-1))
12185 (tail (cdr member))
12186 (org-state (cond
12187 ((and org-todo-key-trigger
12188 (or (and (equal arg '(4))
12189 (eq org-use-fast-todo-selection 'prefix))
12190 (and (not arg) org-use-fast-todo-selection
12191 (not (eq org-use-fast-todo-selection
12192 'prefix)))))
12193 ;; Use fast selection
12194 (org-fast-todo-selection))
12195 ((and (equal arg '(4))
12196 (or (not org-use-fast-todo-selection)
12197 (not org-todo-key-trigger)))
12198 ;; Read a state with completion
12199 (org-icompleting-read
12200 "State: " (mapcar 'list org-todo-keywords-1)
12201 nil t))
12202 ((eq arg 'right)
12203 (if this
12204 (if tail (car tail) nil)
12205 (car org-todo-keywords-1)))
12206 ((eq arg 'left)
12207 (if (equal member org-todo-keywords-1)
12209 (if this
12210 (nth (- (length org-todo-keywords-1)
12211 (length tail) 2)
12212 org-todo-keywords-1)
12213 (org-last org-todo-keywords-1))))
12214 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12215 (setq arg nil))) ; hack to fall back to cycling
12216 (arg
12217 ;; user or caller requests a specific state
12218 (cond
12219 ((equal arg "") nil)
12220 ((eq arg 'none) nil)
12221 ((eq arg 'done) (or done-word (car org-done-keywords)))
12222 ((eq arg 'nextset)
12223 (or (car (cdr (member head org-todo-heads)))
12224 (car org-todo-heads)))
12225 ((eq arg 'previousset)
12226 (let ((org-todo-heads (reverse org-todo-heads)))
12227 (or (car (cdr (member head org-todo-heads)))
12228 (car org-todo-heads))))
12229 ((car (member arg org-todo-keywords-1)))
12230 ((stringp arg)
12231 (user-error "State `%s' not valid in this file" arg))
12232 ((nth (1- (prefix-numeric-value arg))
12233 org-todo-keywords-1))))
12234 ((null member) (or head (car org-todo-keywords-1)))
12235 ((equal this final-done-word) nil) ;; -> make empty
12236 ((null tail) nil) ;; -> first entry
12237 ((memq interpret '(type priority))
12238 (if (eq this-command last-command)
12239 (car tail)
12240 (if (> (length tail) 0)
12241 (or done-word (car org-done-keywords))
12242 nil)))
12244 (car tail))))
12245 (org-state (or
12246 (run-hook-with-args-until-success
12247 'org-todo-get-default-hook org-state org-last-state)
12248 org-state))
12249 (next (if org-state (concat " " org-state " ") " "))
12250 (change-plist (list :type 'todo-state-change :from this :to org-state
12251 :position startpos))
12252 dolog now-done-p)
12253 (when org-blocker-hook
12254 (setq org-last-todo-state-is-todo
12255 (not (member this org-done-keywords)))
12256 (unless (save-excursion
12257 (save-match-data
12258 (org-with-wide-buffer
12259 (run-hook-with-args-until-failure
12260 'org-blocker-hook change-plist))))
12261 (if (org-called-interactively-p 'interactive)
12262 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12263 this org-state org-block-entry-blocking)
12264 ;; fail silently
12265 (message "TODO state change from %s to %s blocked (by \"%s\")"
12266 this org-state org-block-entry-blocking)
12267 (throw 'exit nil))))
12268 (store-match-data match-data)
12269 (replace-match next t t)
12270 (unless (pos-visible-in-window-p hl-pos)
12271 (message "TODO state changed to %s" (org-trim next)))
12272 (unless head
12273 (setq head (org-get-todo-sequence-head org-state)
12274 ass (assoc head org-todo-kwd-alist)
12275 interpret (nth 1 ass)
12276 done-word (nth 3 ass)
12277 final-done-word (nth 4 ass)))
12278 (when (memq arg '(nextset previousset))
12279 (message "Keyword-Set %d/%d: %s"
12280 (- (length org-todo-sets) -1
12281 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12282 (length org-todo-sets)
12283 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12284 (setq org-last-todo-state-is-todo
12285 (not (member org-state org-done-keywords)))
12286 (setq now-done-p (and (member org-state org-done-keywords)
12287 (not (member this org-done-keywords))))
12288 (and logging (org-local-logging logging))
12289 (when (and (or org-todo-log-states org-log-done)
12290 (not (eq org-inhibit-logging t))
12291 (not (memq arg '(nextset previousset))))
12292 ;; we need to look at recording a time and note
12293 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12294 (nth 2 (assoc this org-todo-log-states))))
12295 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12296 (setq dolog 'time))
12297 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12298 (and org-state
12299 (member org-state org-not-done-keywords)
12300 (not (member this org-not-done-keywords))))
12301 ;; This is now a todo state and was not one before
12302 ;; If there was a CLOSED time stamp, get rid of it.
12303 (org-add-planning-info nil nil 'closed))
12304 (when (and now-done-p org-log-done)
12305 ;; It is now done, and it was not done before
12306 (org-add-planning-info 'closed (org-current-effective-time))
12307 (if (and (not dolog) (eq 'note org-log-done))
12308 (org-add-log-setup 'done org-state this 'findpos 'note)))
12309 (when (and org-state dolog)
12310 ;; This is a non-nil state, and we need to log it
12311 (org-add-log-setup 'state org-state this 'findpos dolog)))
12312 ;; Fixup tag positioning
12313 (org-todo-trigger-tag-changes org-state)
12314 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12315 (when org-provide-todo-statistics
12316 (org-update-parent-todo-statistics))
12317 (run-hooks 'org-after-todo-state-change-hook)
12318 (if (and arg (not (member org-state org-done-keywords)))
12319 (setq head (org-get-todo-sequence-head org-state)))
12320 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12321 ;; Do we need to trigger a repeat?
12322 (when now-done-p
12323 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12324 ;; This is for the agenda, take a snapshot of the headline.
12325 (save-match-data
12326 (setq org-agenda-headline-snapshot-before-repeat
12327 (org-get-heading))))
12328 (org-auto-repeat-maybe org-state))
12329 ;; Fixup cursor location if close to the keyword
12330 (if (and (outline-on-heading-p)
12331 (not (bolp))
12332 (save-excursion (beginning-of-line 1)
12333 (looking-at org-todo-line-regexp))
12334 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12335 (progn
12336 (goto-char (or (match-end 2) (match-end 1)))
12337 (and (looking-at " ") (just-one-space))))
12338 (when org-trigger-hook
12339 (save-excursion
12340 (run-hook-with-args 'org-trigger-hook change-plist)))
12341 (when commentp (org-toggle-comment))))))))
12343 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12344 "Block turning an entry into a TODO, using the hierarchy.
12345 This checks whether the current task should be blocked from state
12346 changes. Such blocking occurs when:
12348 1. The task has children which are not all in a completed state.
12350 2. A task has a parent with the property :ORDERED:, and there
12351 are siblings prior to the current task with incomplete
12352 status.
12354 3. The parent of the task is blocked because it has siblings that should
12355 be done first, or is child of a block grandparent TODO entry."
12357 (if (not org-enforce-todo-dependencies)
12358 t ; if locally turned off don't block
12359 (catch 'dont-block
12360 ;; If this is not a todo state change, or if this entry is already DONE,
12361 ;; do not block
12362 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12363 (member (plist-get change-plist :from)
12364 (cons 'done org-done-keywords))
12365 (member (plist-get change-plist :to)
12366 (cons 'todo org-not-done-keywords))
12367 (not (plist-get change-plist :to)))
12368 (throw 'dont-block t))
12369 ;; If this task has children, and any are undone, it's blocked
12370 (save-excursion
12371 (org-back-to-heading t)
12372 (let ((this-level (funcall outline-level)))
12373 (outline-next-heading)
12374 (let ((child-level (funcall outline-level)))
12375 (while (and (not (eobp))
12376 (> child-level this-level))
12377 ;; this todo has children, check whether they are all
12378 ;; completed
12379 (if (and (not (org-entry-is-done-p))
12380 (org-entry-is-todo-p))
12381 (progn (setq org-block-entry-blocking (org-get-heading))
12382 (throw 'dont-block nil)))
12383 (outline-next-heading)
12384 (setq child-level (funcall outline-level))))))
12385 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12386 ;; any previous siblings are undone, it's blocked
12387 (save-excursion
12388 (org-back-to-heading t)
12389 (let* ((pos (point))
12390 (parent-pos (and (org-up-heading-safe) (point))))
12391 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12392 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12393 (forward-line 1)
12394 (re-search-forward org-not-done-heading-regexp pos t))
12395 (setq org-block-entry-blocking (match-string 0))
12396 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12397 ;; Search further up the hierarchy, to see if an ancestor is blocked
12398 (while t
12399 (goto-char parent-pos)
12400 (if (not (looking-at org-not-done-heading-regexp))
12401 (throw 'dont-block t)) ; do not block, parent is not a TODO
12402 (setq pos (point))
12403 (setq parent-pos (and (org-up-heading-safe) (point)))
12404 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12405 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12406 (forward-line 1)
12407 (re-search-forward org-not-done-heading-regexp pos t)
12408 (setq org-block-entry-blocking (org-get-heading)))
12409 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12411 (defcustom org-track-ordered-property-with-tag nil
12412 "Should the ORDERED property also be shown as a tag?
12413 The ORDERED property decides if an entry should require subtasks to be
12414 completed in sequence. Since a property is not very visible, setting
12415 this option means that toggling the ORDERED property with the command
12416 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12417 not relevant for the behavior, but it makes things more visible.
12419 Note that toggling the tag with tags commands will not change the property
12420 and therefore not influence behavior!
12422 This can be t, meaning the tag ORDERED should be used, It can also be a
12423 string to select a different tag for this task."
12424 :group 'org-todo
12425 :type '(choice
12426 (const :tag "No tracking" nil)
12427 (const :tag "Track with ORDERED tag" t)
12428 (string :tag "Use other tag")))
12430 (defun org-toggle-ordered-property ()
12431 "Toggle the ORDERED property of the current entry.
12432 For better visibility, you can track the value of this property with a tag.
12433 See variable `org-track-ordered-property-with-tag'."
12434 (interactive)
12435 (let* ((t1 org-track-ordered-property-with-tag)
12436 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12437 (save-excursion
12438 (org-back-to-heading)
12439 (if (org-entry-get nil "ORDERED")
12440 (progn
12441 (org-delete-property "ORDERED" "PROPERTIES")
12442 (and tag (org-toggle-tag tag 'off))
12443 (message "Subtasks can be completed in arbitrary order"))
12444 (org-entry-put nil "ORDERED" "t")
12445 (and tag (org-toggle-tag tag 'on))
12446 (message "Subtasks must be completed in sequence")))))
12448 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12449 (defun org-block-todo-from-checkboxes (change-plist)
12450 "Block turning an entry into a TODO, using checkboxes.
12451 This checks whether the current task should be blocked from state
12452 changes because there are unchecked boxes in this entry."
12453 (if (not org-enforce-todo-checkbox-dependencies)
12454 t ; if locally turned off don't block
12455 (catch 'dont-block
12456 ;; If this is not a todo state change, or if this entry is already DONE,
12457 ;; do not block
12458 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12459 (member (plist-get change-plist :from)
12460 (cons 'done org-done-keywords))
12461 (member (plist-get change-plist :to)
12462 (cons 'todo org-not-done-keywords))
12463 (not (plist-get change-plist :to)))
12464 (throw 'dont-block t))
12465 ;; If this task has checkboxes that are not checked, it's blocked
12466 (save-excursion
12467 (org-back-to-heading t)
12468 (let ((beg (point)) end)
12469 (outline-next-heading)
12470 (setq end (point))
12471 (goto-char beg)
12472 (if (org-list-search-forward
12473 (concat (org-item-beginning-re)
12474 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12475 "\\[[- ]\\]")
12476 end t)
12477 (progn
12478 (if (boundp 'org-blocked-by-checkboxes)
12479 (setq org-blocked-by-checkboxes t))
12480 (throw 'dont-block nil)))))
12481 t))) ; do not block
12483 (defun org-entry-blocked-p ()
12484 "Is the current entry blocked?"
12485 (org-with-silent-modifications
12486 (if (org-entry-get nil "NOBLOCKING")
12487 nil ;; Never block this entry
12488 (not (run-hook-with-args-until-failure
12489 'org-blocker-hook
12490 (list :type 'todo-state-change
12491 :position (point)
12492 :from 'todo
12493 :to 'done))))))
12495 (defun org-update-statistics-cookies (all)
12496 "Update the statistics cookie, either from TODO or from checkboxes.
12497 This should be called with the cursor in a line with a statistics cookie."
12498 (interactive "P")
12499 (if all
12500 (progn
12501 (org-update-checkbox-count 'all)
12502 (org-map-entries 'org-update-parent-todo-statistics))
12503 (if (not (org-at-heading-p))
12504 (org-update-checkbox-count)
12505 (let ((pos (point-marker))
12506 end l1 l2)
12507 (ignore-errors (org-back-to-heading t))
12508 (if (not (org-at-heading-p))
12509 (org-update-checkbox-count)
12510 (setq l1 (org-outline-level))
12511 (setq end (save-excursion
12512 (outline-next-heading)
12513 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12514 (point)))
12515 (if (and (save-excursion
12516 (re-search-forward
12517 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12518 (not (save-excursion (re-search-forward
12519 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12520 (org-update-checkbox-count)
12521 (if (and l2 (> l2 l1))
12522 (progn
12523 (goto-char end)
12524 (org-update-parent-todo-statistics))
12525 (goto-char pos)
12526 (beginning-of-line 1)
12527 (while (re-search-forward
12528 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12529 (point-at-eol) t)
12530 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12531 (goto-char pos)
12532 (move-marker pos nil)))))
12534 (defvar org-entry-property-inherited-from) ;; defined below
12535 (defun org-update-parent-todo-statistics ()
12536 "Update any statistics cookie in the parent of the current headline.
12537 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12538 the entire subtree and this will travel up the hierarchy and update
12539 statistics everywhere."
12540 (let* ((prop (save-excursion (org-up-heading-safe)
12541 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12542 (recursive (or (not org-hierarchical-todo-statistics)
12543 (and prop (string-match "\\<recursive\\>" prop))))
12544 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12546 (first t)
12547 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12548 level ltoggle l1 new ndel
12549 (cnt-all 0) (cnt-done 0) is-percent kwd
12550 checkbox-beg ov ovs ove cookie-present)
12551 (catch 'exit
12552 (save-excursion
12553 (beginning-of-line 1)
12554 (setq ltoggle (funcall outline-level))
12555 ;; Three situations are to consider:
12557 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12558 ;; to the top-level ancestor on the headline;
12560 ;; 2. If parent has "recursive" property, repeat up to the
12561 ;; headline setting that property, taking inheritance into
12562 ;; account;
12564 ;; 3. Else, move up to direct parent and proceed only once.
12565 (while (and (setq level (org-up-heading-safe))
12566 (or recursive first)
12567 (>= (point) lim))
12568 (setq first nil cookie-present nil)
12569 (unless (and level
12570 (not (string-match
12571 "\\<checkbox\\>"
12572 (downcase (or (org-entry-get nil "COOKIE_DATA")
12573 "")))))
12574 (throw 'exit nil))
12575 (while (re-search-forward box-re (point-at-eol) t)
12576 (setq cnt-all 0 cnt-done 0 cookie-present t)
12577 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12578 (save-match-data
12579 (unless (outline-next-heading) (throw 'exit nil))
12580 (while (and (looking-at org-complex-heading-regexp)
12581 (> (setq l1 (length (match-string 1))) level))
12582 (setq kwd (and (or recursive (= l1 ltoggle))
12583 (match-string 2)))
12584 (if (or (eq org-provide-todo-statistics 'all-headlines)
12585 (and (listp org-provide-todo-statistics)
12586 (or (member kwd org-provide-todo-statistics)
12587 (member kwd org-done-keywords))))
12588 (setq cnt-all (1+ cnt-all))
12589 (if (eq org-provide-todo-statistics t)
12590 (and kwd (setq cnt-all (1+ cnt-all)))))
12591 (and (member kwd org-done-keywords)
12592 (setq cnt-done (1+ cnt-done)))
12593 (outline-next-heading)))
12594 (setq new
12595 (if is-percent
12596 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12597 (format "[%d/%d]" cnt-done cnt-all))
12598 ndel (- (match-end 0) checkbox-beg))
12599 ;; handle overlays when updating cookie from column view
12600 (when (setq ov (car (overlays-at checkbox-beg)))
12601 (setq ovs (overlay-start ov) ove (overlay-end ov))
12602 (delete-overlay ov))
12603 (goto-char checkbox-beg)
12604 (insert new)
12605 (delete-region (point) (+ (point) ndel))
12606 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12607 (when ov (move-overlay ov ovs ove)))
12608 (when cookie-present
12609 (run-hook-with-args 'org-after-todo-statistics-hook
12610 cnt-done (- cnt-all cnt-done))))))
12611 (run-hooks 'org-todo-statistics-hook)))
12613 (defvar org-after-todo-statistics-hook nil
12614 "Hook that is called after a TODO statistics cookie has been updated.
12615 Each function is called with two arguments: the number of not-done entries
12616 and the number of done entries.
12618 For example, the following function, when added to this hook, will switch
12619 an entry to DONE when all children are done, and back to TODO when new
12620 entries are set to a TODO status. Note that this hook is only called
12621 when there is a statistics cookie in the headline!
12623 (defun org-summary-todo (n-done n-not-done)
12624 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12625 (let (org-log-done org-log-states) ; turn off logging
12626 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12629 (defvar org-todo-statistics-hook nil
12630 "Hook that is run whenever Org thinks TODO statistics should be updated.
12631 This hook runs even if there is no statistics cookie present, in which case
12632 `org-after-todo-statistics-hook' would not run.")
12634 (defun org-todo-trigger-tag-changes (state)
12635 "Apply the changes defined in `org-todo-state-tags-triggers'."
12636 (let ((l org-todo-state-tags-triggers)
12637 changes)
12638 (when (or (not state) (equal state ""))
12639 (setq changes (append changes (cdr (assoc "" l)))))
12640 (when (and (stringp state) (> (length state) 0))
12641 (setq changes (append changes (cdr (assoc state l)))))
12642 (when (member state org-not-done-keywords)
12643 (setq changes (append changes (cdr (assoc 'todo l)))))
12644 (when (member state org-done-keywords)
12645 (setq changes (append changes (cdr (assoc 'done l)))))
12646 (dolist (c changes)
12647 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12649 (defun org-local-logging (value)
12650 "Get logging settings from a property VALUE."
12651 (let* (words w a)
12652 ;; directly set the variables, they are already local.
12653 (setq org-log-done nil
12654 org-log-repeat nil
12655 org-todo-log-states nil)
12656 (setq words (org-split-string value))
12657 (while (setq w (pop words))
12658 (cond
12659 ((setq a (assoc w org-startup-options))
12660 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12661 (set (nth 1 a) (nth 2 a))))
12662 ((setq a (org-extract-log-state-settings w))
12663 (and (member (car a) org-todo-keywords-1)
12664 (push a org-todo-log-states)))))))
12666 (defun org-get-todo-sequence-head (kwd)
12667 "Return the head of the TODO sequence to which KWD belongs.
12668 If KWD is not set, check if there is a text property remembering the
12669 right sequence."
12670 (let (p)
12671 (cond
12672 ((not kwd)
12673 (or (get-text-property (point-at-bol) 'org-todo-head)
12674 (progn
12675 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12676 nil (point-at-eol)))
12677 (get-text-property p 'org-todo-head))))
12678 ((not (member kwd org-todo-keywords-1))
12679 (car org-todo-keywords-1))
12680 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12682 (defun org-fast-todo-selection ()
12683 "Fast TODO keyword selection with single keys.
12684 Returns the new TODO keyword, or nil if no state change should occur."
12685 (let* ((fulltable org-todo-key-alist)
12686 (done-keywords org-done-keywords) ;; needed for the faces.
12687 (maxlen (apply 'max (mapcar
12688 (lambda (x)
12689 (if (stringp (car x)) (string-width (car x)) 0))
12690 fulltable)))
12691 (expert nil)
12692 (fwidth (+ maxlen 3 1 3))
12693 (ncol (/ (- (window-width) 4) fwidth))
12694 tg cnt e c tbl
12695 groups ingroup)
12696 (save-excursion
12697 (save-window-excursion
12698 (if expert
12699 (set-buffer (get-buffer-create " *Org todo*"))
12700 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12701 (erase-buffer)
12702 (org-set-local 'org-done-keywords done-keywords)
12703 (setq tbl fulltable cnt 0)
12704 (while (setq e (pop tbl))
12705 (cond
12706 ((equal e '(:startgroup))
12707 (push '() groups) (setq ingroup t)
12708 (when (not (= cnt 0))
12709 (setq cnt 0)
12710 (insert "\n"))
12711 (insert "{ "))
12712 ((equal e '(:endgroup))
12713 (setq ingroup nil cnt 0)
12714 (insert "}\n"))
12715 ((equal e '(:newline))
12716 (when (not (= cnt 0))
12717 (setq cnt 0)
12718 (insert "\n")
12719 (setq e (car tbl))
12720 (while (equal (car tbl) '(:newline))
12721 (insert "\n")
12722 (setq tbl (cdr tbl)))))
12724 (setq tg (car e) c (cdr e))
12725 (if ingroup (push tg (car groups)))
12726 (setq tg (org-add-props tg nil 'face
12727 (org-get-todo-face tg)))
12728 (if (and (= cnt 0) (not ingroup)) (insert " "))
12729 (insert "[" c "] " tg (make-string
12730 (- fwidth 4 (length tg)) ?\ ))
12731 (when (= (setq cnt (1+ cnt)) ncol)
12732 (insert "\n")
12733 (if ingroup (insert " "))
12734 (setq cnt 0)))))
12735 (insert "\n")
12736 (goto-char (point-min))
12737 (if (not expert) (org-fit-window-to-buffer))
12738 (message "[a-z..]:Set [SPC]:clear")
12739 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12740 (cond
12741 ((or (= c ?\C-g)
12742 (and (= c ?q) (not (rassoc c fulltable))))
12743 (setq quit-flag t))
12744 ((= c ?\ ) nil)
12745 ((setq e (rassoc c fulltable) tg (car e))
12747 (t (setq quit-flag t)))))))
12749 (defun org-entry-is-todo-p ()
12750 (member (org-get-todo-state) org-not-done-keywords))
12752 (defun org-entry-is-done-p ()
12753 (member (org-get-todo-state) org-done-keywords))
12755 (defun org-get-todo-state ()
12756 "Return the TODO keyword of the current subtree."
12757 (save-excursion
12758 (org-back-to-heading t)
12759 (and (looking-at org-todo-line-regexp)
12760 (match-end 2)
12761 (match-string 2))))
12763 (defun org-at-date-range-p (&optional inactive-ok)
12764 "Is the cursor inside a date range?"
12765 (interactive)
12766 (save-excursion
12767 (catch 'exit
12768 (let ((pos (point)))
12769 (skip-chars-backward "^[<\r\n")
12770 (skip-chars-backward "<[")
12771 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12772 (>= (match-end 0) pos)
12773 (throw 'exit t))
12774 (skip-chars-backward "^<[\r\n")
12775 (skip-chars-backward "<[")
12776 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12777 (>= (match-end 0) pos)
12778 (throw 'exit t)))
12779 nil)))
12781 (defun org-get-repeat (&optional tagline)
12782 "Check if there is a deadline/schedule with repeater in this entry."
12783 (save-match-data
12784 (save-excursion
12785 (org-back-to-heading t)
12786 (and (re-search-forward (if tagline
12787 (concat tagline "\\s-*" org-repeat-re)
12788 org-repeat-re)
12789 (org-entry-end-position) t)
12790 (match-string-no-properties 1)))))
12792 (defvar org-last-changed-timestamp)
12793 (defvar org-last-inserted-timestamp)
12794 (defvar org-log-post-message)
12795 (defvar org-log-note-purpose)
12796 (defvar org-log-note-how)
12797 (defvar org-log-note-extra)
12798 (defun org-auto-repeat-maybe (done-word)
12799 "Check if the current headline contains a repeated deadline/schedule.
12800 If yes, set TODO state back to what it was and change the base date
12801 of repeating deadline/scheduled time stamps to new date.
12802 This function is run automatically after each state change to a DONE state."
12803 ;; last-state is dynamically scoped into this function
12804 (let* ((repeat (org-get-repeat))
12805 (aa (assoc org-last-state org-todo-kwd-alist))
12806 (interpret (nth 1 aa))
12807 (head (nth 2 aa))
12808 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12809 (msg "Entry repeats: ")
12810 (org-log-done nil)
12811 (org-todo-log-states nil)
12812 re type n what ts time to-state)
12813 (when repeat
12814 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12815 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12816 org-todo-repeat-to-state))
12817 (unless (and to-state (member to-state org-todo-keywords-1))
12818 (setq to-state (if (eq interpret 'type) org-last-state head)))
12819 (org-todo to-state)
12820 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12821 (org-entry-put nil "LAST_REPEAT" (format-time-string
12822 (org-time-stamp-format t t))))
12823 (when org-log-repeat
12824 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12825 (memq 'org-add-log-note post-command-hook))
12826 ;; OK, we are already setup for some record
12827 (if (eq org-log-repeat 'note)
12828 ;; make sure we take a note, not only a time stamp
12829 (setq org-log-note-how 'note))
12830 ;; Set up for taking a record
12831 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12832 org-last-state
12833 'findpos org-log-repeat)))
12834 (org-back-to-heading t)
12835 (org-add-planning-info nil nil 'closed)
12836 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12837 org-deadline-time-regexp "\\)\\|\\("
12838 org-ts-regexp "\\)"))
12839 (while (re-search-forward
12840 re (save-excursion (outline-next-heading) (point)) t)
12841 (setq type (if (match-end 1) org-scheduled-string
12842 (if (match-end 3) org-deadline-string "Plain:"))
12843 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12844 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12845 (setq n (string-to-number (match-string 2 ts))
12846 what (match-string 3 ts))
12847 (if (equal what "w") (setq n (* n 7) what "d"))
12848 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12849 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12850 ;; Preparation, see if we need to modify the start date for the change
12851 (when (match-end 1)
12852 (setq time (save-match-data (org-time-string-to-time ts)))
12853 (cond
12854 ((equal (match-string 1 ts) ".")
12855 ;; Shift starting date to today
12856 (org-timestamp-change
12857 (- (org-today) (time-to-days time))
12858 'day))
12859 ((equal (match-string 1 ts) "+")
12860 (let ((nshiftmax 10) (nshift 0))
12861 (while (or (= nshift 0)
12862 (<= (time-to-days time)
12863 (time-to-days (current-time))))
12864 (when (= (incf nshift) nshiftmax)
12865 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12866 (error "Abort")))
12867 (org-timestamp-change n (cdr (assoc what whata)))
12868 (org-at-timestamp-p t)
12869 (setq ts (match-string 1))
12870 (setq time (save-match-data (org-time-string-to-time ts)))))
12871 (org-timestamp-change (- n) (cdr (assoc what whata)))
12872 ;; rematch, so that we have everything in place for the real shift
12873 (org-at-timestamp-p t)
12874 (setq ts (match-string 1))
12875 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12876 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12877 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12878 (setq org-log-post-message msg)
12879 (message "%s" msg))))
12881 (defun org-show-todo-tree (arg)
12882 "Make a compact tree which shows all headlines marked with TODO.
12883 The tree will show the lines where the regexp matches, and all higher
12884 headlines above the match.
12885 With a \\[universal-argument] prefix, prompt for a regexp to match.
12886 With a numeric prefix N, construct a sparse tree for the Nth element
12887 of `org-todo-keywords-1'."
12888 (interactive "P")
12889 (let ((case-fold-search nil)
12890 (kwd-re
12891 (cond ((null arg) org-not-done-regexp)
12892 ((equal arg '(4))
12893 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12894 (mapcar 'list org-todo-keywords-1))))
12895 (concat "\\("
12896 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12897 "\\)\\>")))
12898 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12899 (regexp-quote (nth (1- (prefix-numeric-value arg))
12900 org-todo-keywords-1)))
12901 (t (user-error "Invalid prefix argument: %s" arg)))))
12902 (message "%d TODO entries found"
12903 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12905 (defun org-deadline (arg &optional time)
12906 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12907 With one universal prefix argument, remove any deadline from the item.
12908 With two universal prefix arguments, prompt for a warning delay.
12909 With argument TIME, set the deadline at the corresponding date. TIME
12910 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12911 (interactive "P")
12912 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12913 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12914 'region-start-level 'region))
12915 org-loop-over-headlines-in-active-region)
12916 (org-map-entries
12917 `(org-deadline ',arg ,time)
12918 org-loop-over-headlines-in-active-region
12919 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12920 (let* ((old-date (org-entry-get nil "DEADLINE"))
12921 (old-date-time (if old-date (org-time-string-to-time old-date)))
12922 (repeater (and old-date
12923 (string-match
12924 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12925 old-date)
12926 (match-string 1 old-date))))
12927 (cond
12928 ((equal arg '(4))
12929 (when (and old-date org-log-redeadline)
12930 (org-add-log-setup 'deldeadline nil old-date 'findpos
12931 org-log-redeadline))
12932 (org-remove-timestamp-with-keyword org-deadline-string)
12933 (message "Item no longer has a deadline."))
12934 ((equal arg '(16))
12935 (save-excursion
12936 (org-back-to-heading t)
12937 (if (re-search-forward
12938 org-deadline-time-regexp
12939 (save-excursion (outline-next-heading) (point)) t)
12940 (let* ((rpl0 (match-string 1))
12941 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12942 (replace-match
12943 (concat org-deadline-string
12944 " <" rpl
12945 (format " -%dd"
12946 (abs
12947 (- (time-to-days
12948 (save-match-data
12949 (org-read-date nil t nil "Warn starting from" old-date-time)))
12950 (time-to-days old-date-time))))
12951 ">") t t))
12952 (user-error "No deadline information to update"))))
12954 (org-add-planning-info 'deadline time 'closed)
12955 (when (and old-date org-log-redeadline
12956 (not (equal old-date
12957 (substring org-last-inserted-timestamp 1 -1))))
12958 (org-add-log-setup 'redeadline nil old-date 'findpos
12959 org-log-redeadline))
12960 (when repeater
12961 (save-excursion
12962 (org-back-to-heading t)
12963 (when (re-search-forward (concat org-deadline-string " "
12964 org-last-inserted-timestamp)
12965 (save-excursion
12966 (outline-next-heading) (point)) t)
12967 (goto-char (1- (match-end 0)))
12968 (insert " " repeater)
12969 (setq org-last-inserted-timestamp
12970 (concat (substring org-last-inserted-timestamp 0 -1)
12971 " " repeater
12972 (substring org-last-inserted-timestamp -1))))))
12973 (message "Deadline on %s" org-last-inserted-timestamp))))))
12975 (defun org-schedule (arg &optional time)
12976 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12977 With one universal prefix argument, remove any scheduling date from the item.
12978 With two universal prefix arguments, prompt for a delay cookie.
12979 With argument TIME, scheduled at the corresponding date. TIME can
12980 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12981 (interactive "P")
12982 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12983 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12984 'region-start-level 'region))
12985 org-loop-over-headlines-in-active-region)
12986 (org-map-entries
12987 `(org-schedule ',arg ,time)
12988 org-loop-over-headlines-in-active-region
12989 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12990 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12991 (old-date-time (if old-date (org-time-string-to-time old-date)))
12992 (repeater (and old-date
12993 (string-match
12994 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12995 old-date)
12996 (match-string 1 old-date))))
12997 (cond
12998 ((equal arg '(4))
12999 (progn
13000 (when (and old-date org-log-reschedule)
13001 (org-add-log-setup 'delschedule nil old-date 'findpos
13002 org-log-reschedule))
13003 (org-remove-timestamp-with-keyword org-scheduled-string)
13004 (message "Item is no longer scheduled.")))
13005 ((equal arg '(16))
13006 (save-excursion
13007 (org-back-to-heading t)
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 (defvar org-time-was-given) ; dynamically scoped parameter
13081 (defvar org-end-time-was-given) ; dynamically scoped parameter
13083 (defun org-add-planning-info (what &optional time &rest remove)
13084 "Insert new timestamp with keyword in the line directly after the headline.
13085 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13086 If non is given, the user is prompted for a date.
13087 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13088 be removed."
13089 (interactive)
13090 (let (org-time-was-given org-end-time-was-given ts
13091 end default-time default-input)
13093 (catch 'exit
13094 (when (and (memq what '(scheduled deadline))
13095 (or (not time)
13096 (and (stringp time)
13097 (string-match "^[-+]+[0-9]" time))))
13098 ;; Try to get a default date/time from existing timestamp
13099 (save-excursion
13100 (org-back-to-heading t)
13101 (setq end (save-excursion (outline-next-heading) (point)))
13102 (when (re-search-forward (if (eq what 'scheduled)
13103 org-scheduled-time-regexp
13104 org-deadline-time-regexp)
13105 end t)
13106 (setq ts (match-string 1)
13107 default-time
13108 (apply 'encode-time (org-parse-time-string ts))
13109 default-input (and ts (org-get-compact-tod ts))))))
13110 (when what
13111 (setq time
13112 (if (stringp time)
13113 ;; This is a string (relative or absolute), set proper date
13114 (apply 'encode-time
13115 (org-read-date-analyze
13116 time default-time (decode-time default-time)))
13117 ;; If necessary, get the time from the user
13118 (or time (org-read-date nil 'to-time nil nil
13119 default-time default-input)))))
13121 (when (and org-insert-labeled-timestamps-at-point
13122 (member what '(scheduled deadline)))
13123 (insert
13124 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13125 (org-insert-time-stamp time org-time-was-given
13126 nil nil nil (list org-end-time-was-given))
13127 (setq what nil))
13128 (save-excursion
13129 (save-restriction
13130 (let (col list elt ts buffer-invisibility-spec)
13131 (org-back-to-heading t)
13132 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13133 (goto-char (match-end 1))
13134 (setq col (current-column))
13135 (goto-char (match-end 0))
13136 (if (eobp) (insert "\n") (forward-char 1))
13137 (when (and (not what)
13138 (not (looking-at
13139 (concat "[ \t]*"
13140 org-keyword-time-not-clock-regexp))))
13141 ;; Nothing to add, nothing to remove...... :-)
13142 (throw 'exit nil))
13143 (if (and (not (looking-at org-outline-regexp))
13144 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13145 "[^\r\n]*"))
13146 (not (equal (match-string 1) org-clock-string)))
13147 (narrow-to-region (match-beginning 0) (match-end 0))
13148 (insert-before-markers "\n")
13149 (backward-char 1)
13150 (narrow-to-region (point) (point))
13151 (and org-adapt-indentation (org-indent-to-column col)))
13152 ;; Check if we have to remove something.
13153 (setq list (cons what remove))
13154 (while list
13155 (setq elt (pop list))
13156 (when (or (and (eq elt 'scheduled)
13157 (re-search-forward org-scheduled-time-regexp nil t))
13158 (and (eq elt 'deadline)
13159 (re-search-forward org-deadline-time-regexp nil t))
13160 (and (eq elt 'closed)
13161 (re-search-forward org-closed-time-regexp nil t)))
13162 (replace-match "")
13163 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13164 (and (looking-at "[ \t]+") (replace-match ""))
13165 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13166 (when what
13167 (insert
13168 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13169 (cond ((eq what 'scheduled) org-scheduled-string)
13170 ((eq what 'deadline) org-deadline-string)
13171 ((eq what 'closed) org-closed-string))
13172 " ")
13173 (setq ts (org-insert-time-stamp
13174 time
13175 (or org-time-was-given
13176 (and (eq what 'closed) org-log-done-with-time))
13177 (eq what 'closed)
13178 nil nil (list org-end-time-was-given)))
13179 (insert
13180 (if (not (or (bolp) (eq (char-before) ?\ )
13181 (memq (char-after) '(32 10))
13182 (eobp))) " " ""))
13183 (end-of-line 1))
13184 (goto-char (point-min))
13185 (widen)
13186 (if (and (looking-at "[ \t]*\n")
13187 (equal (char-before) ?\n))
13188 (delete-region (1- (point)) (point-at-eol)))
13189 ts))))))
13191 (defvar org-log-note-marker (make-marker))
13192 (defvar org-log-note-purpose nil)
13193 (defvar org-log-note-state nil)
13194 (defvar org-log-note-previous-state nil)
13195 (defvar org-log-note-how nil)
13196 (defvar org-log-note-extra nil)
13197 (defvar org-log-note-window-configuration nil)
13198 (defvar org-log-note-return-to (make-marker))
13199 (defvar org-log-note-effective-time nil
13200 "Remembered current time so that dynamically scoped
13201 `org-extend-today-until' affects tha timestamps in state change
13202 log")
13204 (defvar org-log-post-message nil
13205 "Message to be displayed after a log note has been stored.
13206 The auto-repeater uses this.")
13208 (defun org-add-note ()
13209 "Add a note to the current entry.
13210 This is done in the same way as adding a state change note."
13211 (interactive)
13212 (org-add-log-setup 'note nil nil 'findpos nil))
13214 (defvar org-property-end-re)
13215 (defun org-add-log-setup (&optional purpose state prev-state
13216 findpos how extra)
13217 "Set up the post command hook to take a note.
13218 If this is about to TODO state change, the new state is expected in STATE.
13219 When FINDPOS is non-nil, find the correct position for the note in
13220 the current entry. If not, assume that it can be inserted at point.
13221 HOW is an indicator what kind of note should be created.
13222 EXTRA is additional text that will be inserted into the notes buffer."
13223 (let* ((org-log-into-drawer (org-log-into-drawer))
13224 (drawer (cond ((stringp org-log-into-drawer)
13225 org-log-into-drawer)
13226 (org-log-into-drawer "LOGBOOK"))))
13227 (save-restriction
13228 (save-excursion
13229 (when findpos
13230 (org-back-to-heading t)
13231 (narrow-to-region (point) (save-excursion
13232 (outline-next-heading) (point)))
13233 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13234 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13235 "[^\r\n]*\\)?"))
13236 (goto-char (match-end 0))
13237 (cond
13238 (drawer
13239 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13240 nil t)
13241 (progn
13242 (goto-char (match-end 0))
13243 (or org-log-states-order-reversed
13244 (and (re-search-forward org-property-end-re nil t)
13245 (goto-char (1- (match-beginning 0))))))
13246 (insert "\n:" drawer ":\n:END:")
13247 (beginning-of-line 0)
13248 (org-indent-line)
13249 (beginning-of-line 2)
13250 (org-indent-line)
13251 (end-of-line 0)))
13252 ((and org-log-state-notes-insert-after-drawers
13253 (save-excursion
13254 (forward-line) (looking-at org-drawer-regexp)))
13255 (forward-line)
13256 (while (looking-at org-drawer-regexp)
13257 (goto-char (match-end 0))
13258 (re-search-forward org-property-end-re (point-max) t)
13259 (forward-line))
13260 (forward-line -1)))
13261 (unless org-log-states-order-reversed
13262 (and (= (char-after) ?\n) (forward-char 1))
13263 (org-skip-over-state-notes)
13264 (skip-chars-backward " \t\n\r")))
13265 (move-marker org-log-note-marker (point))
13266 (setq org-log-note-purpose purpose
13267 org-log-note-state state
13268 org-log-note-previous-state prev-state
13269 org-log-note-how how
13270 org-log-note-extra extra
13271 org-log-note-effective-time (org-current-effective-time))
13272 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13274 (defun org-skip-over-state-notes ()
13275 "Skip past the list of State notes in an entry."
13276 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13277 (when (ignore-errors (goto-char (org-in-item-p)))
13278 (let* ((struct (org-list-struct))
13279 (prevs (org-list-prevs-alist struct)))
13280 (while (looking-at "[ \t]*- State")
13281 (goto-char (or (org-list-get-next-item (point) struct prevs)
13282 (org-list-get-item-end (point) struct)))))))
13284 (defun org-add-log-note (&optional purpose)
13285 "Pop up a window for taking a note, and add this note later at point."
13286 (remove-hook 'post-command-hook 'org-add-log-note)
13287 (setq org-log-note-window-configuration (current-window-configuration))
13288 (delete-other-windows)
13289 (move-marker org-log-note-return-to (point))
13290 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13291 (goto-char org-log-note-marker)
13292 (org-switch-to-buffer-other-window "*Org Note*")
13293 (erase-buffer)
13294 (if (memq org-log-note-how '(time state))
13295 (let (current-prefix-arg) (org-store-log-note))
13296 (let ((org-inhibit-startup t)) (org-mode))
13297 (insert (format "# Insert note for %s.
13298 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13299 (cond
13300 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13301 ((eq org-log-note-purpose 'done) "closed todo item")
13302 ((eq org-log-note-purpose 'state)
13303 (format "state change from \"%s\" to \"%s\""
13304 (or org-log-note-previous-state "")
13305 (or org-log-note-state "")))
13306 ((eq org-log-note-purpose 'reschedule)
13307 "rescheduling")
13308 ((eq org-log-note-purpose 'delschedule)
13309 "no longer scheduled")
13310 ((eq org-log-note-purpose 'redeadline)
13311 "changing deadline")
13312 ((eq org-log-note-purpose 'deldeadline)
13313 "removing deadline")
13314 ((eq org-log-note-purpose 'refile)
13315 "refiling")
13316 ((eq org-log-note-purpose 'note)
13317 "this entry")
13318 (t (error "This should not happen")))))
13319 (if org-log-note-extra (insert org-log-note-extra))
13320 (org-set-local 'org-finish-function 'org-store-log-note)
13321 (run-hooks 'org-log-buffer-setup-hook)))
13323 (defvar org-note-abort nil) ; dynamically scoped
13324 (defun org-store-log-note ()
13325 "Finish taking a log note, and insert it to where it belongs."
13326 (let ((txt (buffer-string)))
13327 (kill-buffer (current-buffer))
13328 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13329 lines ind bul)
13330 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13331 (setq txt (replace-match "" t t txt)))
13332 (if (string-match "\\s-+\\'" txt)
13333 (setq txt (replace-match "" t t txt)))
13334 (setq lines (org-split-string txt "\n"))
13335 (when (and note (string-match "\\S-" note))
13336 (setq note
13337 (org-replace-escapes
13338 note
13339 (list (cons "%u" (user-login-name))
13340 (cons "%U" user-full-name)
13341 (cons "%t" (format-time-string
13342 (org-time-stamp-format 'long 'inactive)
13343 org-log-note-effective-time))
13344 (cons "%T" (format-time-string
13345 (org-time-stamp-format 'long nil)
13346 org-log-note-effective-time))
13347 (cons "%d" (format-time-string
13348 (org-time-stamp-format nil 'inactive)
13349 org-log-note-effective-time))
13350 (cons "%D" (format-time-string
13351 (org-time-stamp-format nil nil)
13352 org-log-note-effective-time))
13353 (cons "%s" (if org-log-note-state
13354 (concat "\"" org-log-note-state "\"")
13355 ""))
13356 (cons "%S" (if org-log-note-previous-state
13357 (concat "\"" org-log-note-previous-state "\"")
13358 "\"\"")))))
13359 (if lines (setq note (concat note " \\\\")))
13360 (push note lines))
13361 (when (or current-prefix-arg org-note-abort)
13362 (when org-log-into-drawer
13363 (org-remove-empty-drawer-at
13364 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13365 org-log-note-marker))
13366 (setq lines nil))
13367 (when lines
13368 (with-current-buffer (marker-buffer org-log-note-marker)
13369 (save-excursion
13370 (goto-char org-log-note-marker)
13371 (move-marker org-log-note-marker nil)
13372 (end-of-line 1)
13373 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13374 (setq ind (save-excursion
13375 (if (ignore-errors (goto-char (org-in-item-p)))
13376 (let ((struct (org-list-struct)))
13377 (org-list-get-ind
13378 (org-list-get-top-point struct) struct))
13379 (skip-chars-backward " \r\t\n")
13380 (cond
13381 ((and (org-at-heading-p)
13382 org-adapt-indentation)
13383 (1+ (org-current-level)))
13384 ((org-at-heading-p) 0)
13385 (t (org-get-indentation))))))
13386 (setq bul (org-list-bullet-string "-"))
13387 (org-indent-line-to ind)
13388 (insert bul (pop lines))
13389 (let ((ind-body (+ (length bul) ind)))
13390 (while lines
13391 (insert "\n")
13392 (org-indent-line-to ind-body)
13393 (insert (pop lines))))
13394 (message "Note stored")
13395 (org-back-to-heading t)
13396 (org-cycle-hide-drawers 'children))
13397 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13398 ;; from within `org-add-log-note' because `buffer-undo-list'
13399 ;; is then modified outside of `org-with-remote-undo'.
13400 (when (eq this-command 'org-agenda-todo)
13401 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13402 ;; Don't add undo information when called from `org-agenda-todo'
13403 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13404 (set-window-configuration org-log-note-window-configuration)
13405 (with-current-buffer (marker-buffer org-log-note-return-to)
13406 (goto-char org-log-note-return-to))
13407 (move-marker org-log-note-return-to nil)
13408 (and org-log-post-message (message "%s" org-log-post-message))))
13410 (defun org-remove-empty-drawer-at (drawer pos)
13411 "Remove an empty drawer DRAWER at position POS.
13412 POS may also be a marker."
13413 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13414 (save-excursion
13415 (save-restriction
13416 (widen)
13417 (goto-char pos)
13418 (if (org-in-regexp
13419 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13420 (replace-match ""))))))
13422 (defvar org-ts-type nil)
13423 (defun org-sparse-tree (&optional arg type)
13424 "Create a sparse tree, prompt for the details.
13425 This command can create sparse trees. You first need to select the type
13426 of match used to create the tree:
13428 t Show all TODO entries.
13429 T Show entries with a specific TODO keyword.
13430 m Show entries selected by a tags/property match.
13431 p Enter a property name and its value (both with completion on existing
13432 names/values) and show entries with that property.
13433 r Show entries matching a regular expression (`/' can be used as well).
13434 b Show deadlines and scheduled items before a date.
13435 a Show deadlines and scheduled items after a date.
13436 d Show deadlines due within `org-deadline-warning-days'.
13437 D Show deadlines and scheduled items between a date range."
13438 (interactive "P")
13439 (let (ans kwd value ts-type)
13440 (setq type (or type org-sparse-tree-default-date-type))
13441 (setq org-ts-type type)
13442 (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"
13443 (cond ((eq type 'all) "all timestamps")
13444 ((eq type 'scheduled) "only scheduled")
13445 ((eq type 'deadline) "only deadline")
13446 ((eq type 'active) "only active timestamps")
13447 ((eq type 'inactive) "only inactive timestamps")
13448 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13449 ((eq type 'closed) "with a closed time-stamp")
13450 (t "scheduled/deadline")))
13451 (setq ans (read-char-exclusive))
13452 (cond
13453 ((equal ans ?c)
13454 (org-sparse-tree
13455 arg (cadr (member type '(scheduled-or-deadline
13456 all scheduled deadline active inactive closed)))))
13457 ((equal ans ?d)
13458 (call-interactively 'org-check-deadlines))
13459 ((equal ans ?b)
13460 (call-interactively 'org-check-before-date))
13461 ((equal ans ?a)
13462 (call-interactively 'org-check-after-date))
13463 ((equal ans ?D)
13464 (call-interactively 'org-check-dates-range))
13465 ((equal ans ?t)
13466 (call-interactively 'org-show-todo-tree))
13467 ((equal ans ?T)
13468 (org-show-todo-tree '(4)))
13469 ((member ans '(?T ?m))
13470 (call-interactively 'org-match-sparse-tree))
13471 ((member ans '(?p ?P))
13472 (setq kwd (org-icompleting-read "Property: "
13473 (mapcar 'list (org-buffer-property-keys))))
13474 (setq value (org-icompleting-read "Value: "
13475 (mapcar 'list (org-property-values kwd))))
13476 (unless (string-match "\\`{.*}\\'" value)
13477 (setq value (concat "\"" value "\"")))
13478 (org-match-sparse-tree arg (concat kwd "=" value)))
13479 ((member ans '(?r ?R ?/))
13480 (call-interactively 'org-occur))
13481 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13483 (defvar org-occur-highlights nil
13484 "List of overlays used for occur matches.")
13485 (make-variable-buffer-local 'org-occur-highlights)
13486 (defvar org-occur-parameters nil
13487 "Parameters of the active org-occur calls.
13488 This is a list, each call to org-occur pushes as cons cell,
13489 containing the regular expression and the callback, onto the list.
13490 The list can contain several entries if `org-occur' has been called
13491 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13492 will only contain one set of parameters. When the highlights are
13493 removed (for example with `C-c C-c', or with the next edit (depending
13494 on `org-remove-highlights-with-change'), this variable is emptied
13495 as well.")
13496 (make-variable-buffer-local 'org-occur-parameters)
13498 (defun org-occur (regexp &optional keep-previous callback)
13499 "Make a compact tree which shows all matches of REGEXP.
13500 The tree will show the lines where the regexp matches, and all higher
13501 headlines above the match. It will also show the heading after the match,
13502 to make sure editing the matching entry is easy.
13503 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13504 call to `org-occur' will be kept, to allow stacking of calls to this
13505 command.
13506 If CALLBACK is non-nil, it is a function which is called to confirm
13507 that the match should indeed be shown."
13508 (interactive "sRegexp: \nP")
13509 (when (equal regexp "")
13510 (user-error "Regexp cannot be empty"))
13511 (unless keep-previous
13512 (org-remove-occur-highlights nil nil t))
13513 (push (cons regexp callback) org-occur-parameters)
13514 (let ((cnt 0))
13515 (save-excursion
13516 (goto-char (point-min))
13517 (if (or (not keep-previous) ; do not want to keep
13518 (not org-occur-highlights)) ; no previous matches
13519 ;; hide everything
13520 (org-overview))
13521 (while (re-search-forward regexp nil t)
13522 (when (or (not callback)
13523 (save-match-data (funcall callback)))
13524 (setq cnt (1+ cnt))
13525 (when org-highlight-sparse-tree-matches
13526 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13527 (org-show-context 'occur-tree))))
13528 (when org-remove-highlights-with-change
13529 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13530 nil 'local))
13531 (unless org-sparse-tree-open-archived-trees
13532 (org-hide-archived-subtrees (point-min) (point-max)))
13533 (run-hooks 'org-occur-hook)
13534 (if (org-called-interactively-p 'interactive)
13535 (message "%d match(es) for regexp %s" cnt regexp))
13536 cnt))
13538 (defun org-occur-next-match (&optional n reset)
13539 "Function for `next-error-function' to find sparse tree matches.
13540 N is the number of matches to move, when negative move backwards.
13541 RESET is entirely ignored - this function always goes back to the
13542 starting point when no match is found."
13543 (let* ((limit (if (< n 0) (point-min) (point-max)))
13544 (search-func (if (< n 0)
13545 'previous-single-char-property-change
13546 'next-single-char-property-change))
13547 (n (abs n))
13548 (pos (point))
13550 (catch 'exit
13551 (while (setq p1 (funcall search-func (point) 'org-type))
13552 (when (equal p1 limit)
13553 (goto-char pos)
13554 (error "No more matches"))
13555 (when (equal (get-char-property p1 'org-type) 'org-occur)
13556 (setq n (1- n))
13557 (when (= n 0)
13558 (goto-char p1)
13559 (throw 'exit (point))))
13560 (goto-char p1))
13561 (goto-char p1)
13562 (error "No more matches"))))
13564 (defun org-show-context (&optional key)
13565 "Make sure point and context are visible.
13566 How much context is shown depends upon the variables
13567 `org-show-hierarchy-above', `org-show-following-heading',
13568 `org-show-entry-below' and `org-show-siblings'."
13569 (let ((heading-p (org-at-heading-p t))
13570 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13571 (following-p (org-get-alist-option org-show-following-heading key))
13572 (entry-p (org-get-alist-option org-show-entry-below key))
13573 (siblings-p (org-get-alist-option org-show-siblings key)))
13574 ;; Show heading or entry text
13575 (if (and heading-p (not entry-p))
13576 (org-flag-heading nil) ; only show the heading
13577 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13578 (org-show-hidden-entry))) ; show entire entry
13579 (when following-p
13580 ;; Show next sibling, or heading below text
13581 (save-excursion
13582 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13583 (org-flag-heading nil))))
13584 (when siblings-p (org-show-siblings))
13585 (when hierarchy-p
13586 ;; show all higher headings, possibly with siblings
13587 (save-excursion
13588 (while (and (condition-case nil
13589 (progn (org-up-heading-all 1) t)
13590 (error nil))
13591 (not (bobp)))
13592 (org-flag-heading nil)
13593 (when siblings-p (org-show-siblings)))))
13594 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13596 (defvar org-reveal-start-hook nil
13597 "Hook run before revealing a location.")
13599 (defun org-reveal (&optional siblings)
13600 "Show current entry, hierarchy above it, and the following headline.
13601 This can be used to show a consistent set of context around locations
13602 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13603 not t for the search context.
13605 With optional argument SIBLINGS, on each level of the hierarchy all
13606 siblings are shown. This repairs the tree structure to what it would
13607 look like when opened with hierarchical calls to `org-cycle'.
13608 With double optional argument \\[universal-argument] \\[universal-argument], \
13609 go to the parent and show the
13610 entire tree."
13611 (interactive "P")
13612 (run-hooks 'org-reveal-start-hook)
13613 (let ((org-show-hierarchy-above t)
13614 (org-show-following-heading t)
13615 (org-show-siblings (if siblings t org-show-siblings)))
13616 (org-show-context nil))
13617 (when (equal siblings '(16))
13618 (save-excursion
13619 (when (org-up-heading-safe)
13620 (org-show-subtree)
13621 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13623 (defun org-highlight-new-match (beg end)
13624 "Highlight from BEG to END and mark the highlight is an occur headline."
13625 (let ((ov (make-overlay beg end)))
13626 (overlay-put ov 'face 'secondary-selection)
13627 (overlay-put ov 'org-type 'org-occur)
13628 (push ov org-occur-highlights)))
13630 (defun org-remove-occur-highlights (&optional beg end noremove)
13631 "Remove the occur highlights from the buffer.
13632 BEG and END are ignored. If NOREMOVE is nil, remove this function
13633 from the `before-change-functions' in the current buffer."
13634 (interactive)
13635 (unless org-inhibit-highlight-removal
13636 (mapc 'delete-overlay org-occur-highlights)
13637 (setq org-occur-highlights nil)
13638 (setq org-occur-parameters nil)
13639 (unless noremove
13640 (remove-hook 'before-change-functions
13641 'org-remove-occur-highlights 'local))))
13643 ;;;; Priorities
13645 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13646 "Regular expression matching the priority indicator.")
13648 (defvar org-remove-priority-next-time nil)
13650 (defun org-priority-up ()
13651 "Increase the priority of the current item."
13652 (interactive)
13653 (org-priority 'up))
13655 (defun org-priority-down ()
13656 "Decrease the priority of the current item."
13657 (interactive)
13658 (org-priority 'down))
13660 (defun org-priority (&optional action show)
13661 "Change the priority of an item.
13662 ACTION can be `set', `up', `down', or a character."
13663 (interactive "P")
13664 (if (equal action '(4))
13665 (org-show-priority)
13666 (unless org-enable-priority-commands
13667 (user-error "Priority commands are disabled"))
13668 (setq action (or action 'set))
13669 (let (current new news have remove)
13670 (save-excursion
13671 (org-back-to-heading t)
13672 (if (looking-at org-priority-regexp)
13673 (setq current (string-to-char (match-string 2))
13674 have t))
13675 (cond
13676 ((eq action 'remove)
13677 (setq remove t new ?\ ))
13678 ((or (eq action 'set)
13679 (if (featurep 'xemacs) (characterp action) (integerp action)))
13680 (if (not (eq action 'set))
13681 (setq new action)
13682 (message "Priority %c-%c, SPC to remove: "
13683 org-highest-priority org-lowest-priority)
13684 (save-match-data
13685 (setq new (read-char-exclusive))))
13686 (if (and (= (upcase org-highest-priority) org-highest-priority)
13687 (= (upcase org-lowest-priority) org-lowest-priority))
13688 (setq new (upcase new)))
13689 (cond ((equal new ?\ ) (setq remove t))
13690 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13691 (user-error "Priority must be between `%c' and `%c'"
13692 org-highest-priority org-lowest-priority))))
13693 ((eq action 'up)
13694 (setq new (if have
13695 (1- current) ; normal cycling
13696 ;; last priority was empty
13697 (if (eq last-command this-command)
13698 org-lowest-priority ; wrap around empty to lowest
13699 ;; default
13700 (if org-priority-start-cycle-with-default
13701 org-default-priority
13702 (1- org-default-priority))))))
13703 ((eq action 'down)
13704 (setq new (if have
13705 (1+ current) ; normal cycling
13706 ;; last priority was empty
13707 (if (eq last-command this-command)
13708 org-highest-priority ; wrap around empty to highest
13709 ;; default
13710 (if org-priority-start-cycle-with-default
13711 org-default-priority
13712 (1+ org-default-priority))))))
13713 (t (user-error "Invalid action")))
13714 (if (or (< (upcase new) org-highest-priority)
13715 (> (upcase new) org-lowest-priority))
13716 (if (and (memq action '(up down))
13717 (not have) (not (eq last-command this-command)))
13718 ;; `new' is from default priority
13719 (error
13720 "The default can not be set, see `org-default-priority' why")
13721 ;; normal cycling: `new' is beyond highest/lowest priority
13722 ;; and is wrapped around to the empty priority
13723 (setq remove t)))
13724 (setq news (format "%c" new))
13725 (if have
13726 (if remove
13727 (replace-match "" t t nil 1)
13728 (replace-match news t t nil 2))
13729 (if remove
13730 (user-error "No priority cookie found in line")
13731 (let ((case-fold-search nil))
13732 (looking-at org-todo-line-regexp))
13733 (if (match-end 2)
13734 (progn
13735 (goto-char (match-end 2))
13736 (insert " [#" news "]"))
13737 (goto-char (match-beginning 3))
13738 (insert "[#" news "] "))))
13739 (org-preserve-lc (org-set-tags nil 'align)))
13740 (if remove
13741 (message "Priority removed")
13742 (message "Priority of current item set to %s" news)))))
13744 (defun org-show-priority ()
13745 "Show the priority of the current item.
13746 This priority is composed of the main priority given with the [#A] cookies,
13747 and by additional input from the age of a schedules or deadline entry."
13748 (interactive)
13749 (let ((pri (if (eq major-mode 'org-agenda-mode)
13750 (org-get-at-bol 'priority)
13751 (save-excursion
13752 (save-match-data
13753 (beginning-of-line)
13754 (and (looking-at org-heading-regexp)
13755 (org-get-priority (match-string 0))))))))
13756 (message "Priority is %d" (if pri pri -1000))))
13758 (defun org-get-priority (s)
13759 "Find priority cookie and return priority."
13760 (save-match-data
13761 (if (functionp org-get-priority-function)
13762 (funcall org-get-priority-function)
13763 (if (not (string-match org-priority-regexp s))
13764 (* 1000 (- org-lowest-priority org-default-priority))
13765 (* 1000 (- org-lowest-priority
13766 (string-to-char (match-string 2 s))))))))
13768 ;;;; Tags
13770 (defvar org-agenda-archives-mode)
13771 (defvar org-map-continue-from nil
13772 "Position from where mapping should continue.
13773 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13775 (defvar org-scanner-tags nil
13776 "The current tag list while the tags scanner is running.")
13777 (defvar org-trust-scanner-tags nil
13778 "Should `org-get-tags-at' use the tags for the scanner.
13779 This is for internal dynamical scoping only.
13780 When this is non-nil, the function `org-get-tags-at' will return the value
13781 of `org-scanner-tags' instead of building the list by itself. This
13782 can lead to large speed-ups when the tags scanner is used in a file with
13783 many entries, and when the list of tags is retrieved, for example to
13784 obtain a list of properties. Building the tags list for each entry in such
13785 a file becomes an N^2 operation - but with this variable set, it scales
13786 as N.")
13788 (defun org-scan-tags (action matcher todo-only &optional start-level)
13789 "Sca headline tags with inheritance and produce output ACTION.
13791 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13792 or `agenda' to produce an entry list for an agenda view. It can also be
13793 a Lisp form or a function that should be called at each matched headline, in
13794 this case the return value is a list of all return values from these calls.
13796 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13797 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13798 only lines with a not-done TODO keyword are included in the output.
13799 This should be the same variable that was scoped into
13800 and set by `org-make-tags-matcher' when it constructed MATCHER.
13802 START-LEVEL can be a string with asterisks, reducing the scope to
13803 headlines matching this string."
13804 (require 'org-agenda)
13805 (let* ((re (concat "^"
13806 (if start-level
13807 ;; Get the correct level to match
13808 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13809 org-outline-regexp)
13810 " *\\(\\<\\("
13811 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13812 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13813 (props (list 'face 'default
13814 'done-face 'org-agenda-done
13815 'undone-face 'default
13816 'mouse-face 'highlight
13817 'org-not-done-regexp org-not-done-regexp
13818 'org-todo-regexp org-todo-regexp
13819 'org-complex-heading-regexp org-complex-heading-regexp
13820 'help-echo
13821 (format "mouse-2 or RET jump to org file %s"
13822 (abbreviate-file-name
13823 (or (buffer-file-name (buffer-base-buffer))
13824 (buffer-name (buffer-base-buffer)))))))
13825 (org-map-continue-from nil)
13826 lspos tags tags-list
13827 (tags-alist (list (cons 0 org-file-tags)))
13828 (llast 0) rtn rtn1 level category i txt
13829 todo marker entry priority)
13830 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13831 (setq action (list 'lambda nil action)))
13832 (save-excursion
13833 (goto-char (point-min))
13834 (when (eq action 'sparse-tree)
13835 (org-overview)
13836 (org-remove-occur-highlights))
13837 (while (let (case-fold-search)
13838 (re-search-forward re nil t))
13839 (setq org-map-continue-from nil)
13840 (catch :skip
13841 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13842 tags (if (match-end 4) (org-match-string-no-properties 4)))
13843 (goto-char (setq lspos (match-beginning 0)))
13844 (setq level (org-reduced-level (org-outline-level))
13845 category (org-get-category))
13846 (setq i llast llast level)
13847 ;; remove tag lists from same and sublevels
13848 (while (>= i level)
13849 (when (setq entry (assoc i tags-alist))
13850 (setq tags-alist (delete entry tags-alist)))
13851 (setq i (1- i)))
13852 ;; add the next tags
13853 (when tags
13854 (setq tags (org-split-string tags ":")
13855 tags-alist
13856 (cons (cons level tags) tags-alist)))
13857 ;; compile tags for current headline
13858 (setq tags-list
13859 (if org-use-tag-inheritance
13860 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13861 tags)
13862 org-scanner-tags tags-list)
13863 (when org-use-tag-inheritance
13864 (setcdr (car tags-alist)
13865 (mapcar (lambda (x)
13866 (setq x (copy-sequence x))
13867 (org-add-prop-inherited x))
13868 (cdar tags-alist))))
13869 (when (and tags org-use-tag-inheritance
13870 (or (not (eq t org-use-tag-inheritance))
13871 org-tags-exclude-from-inheritance))
13872 ;; selective inheritance, remove uninherited ones
13873 (setcdr (car tags-alist)
13874 (org-remove-uninherited-tags (cdar tags-alist))))
13875 (when (and
13877 ;; eval matcher only when the todo condition is OK
13878 (and (or (not todo-only) (member todo org-not-done-keywords))
13879 (let ((case-fold-search t) (org-trust-scanner-tags t))
13880 (eval matcher)))
13882 ;; Call the skipper, but return t if it does not skip,
13883 ;; so that the `and' form continues evaluating
13884 (progn
13885 (unless (eq action 'sparse-tree) (org-agenda-skip))
13888 ;; Check if timestamps are deselecting this entry
13889 (or (not todo-only)
13890 (and (member todo org-not-done-keywords)
13891 (or (not org-agenda-tags-todo-honor-ignore-options)
13892 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13894 ;; select this headline
13895 (cond
13896 ((eq action 'sparse-tree)
13897 (and org-highlight-sparse-tree-matches
13898 (org-get-heading) (match-end 0)
13899 (org-highlight-new-match
13900 (match-beginning 1) (match-end 1)))
13901 (org-show-context 'tags-tree))
13902 ((eq action 'agenda)
13903 (setq txt (org-agenda-format-item
13905 (concat
13906 (if (eq org-tags-match-list-sublevels 'indented)
13907 (make-string (1- level) ?.) "")
13908 (org-get-heading))
13909 level category
13910 tags-list)
13911 priority (org-get-priority txt))
13912 (goto-char lspos)
13913 (setq marker (org-agenda-new-marker))
13914 (org-add-props txt props
13915 'org-marker marker 'org-hd-marker marker 'org-category category
13916 'todo-state todo
13917 'priority priority 'type "tagsmatch")
13918 (push txt rtn))
13919 ((functionp action)
13920 (setq org-map-continue-from nil)
13921 (save-excursion
13922 (setq rtn1 (funcall action))
13923 (push rtn1 rtn)))
13924 (t (user-error "Invalid action")))
13926 ;; if we are to skip sublevels, jump to end of subtree
13927 (unless org-tags-match-list-sublevels
13928 (org-end-of-subtree t)
13929 (backward-char 1))))
13930 ;; Get the correct position from where to continue
13931 (if org-map-continue-from
13932 (goto-char org-map-continue-from)
13933 (and (= (point) lspos) (end-of-line 1)))))
13934 (when (and (eq action 'sparse-tree)
13935 (not org-sparse-tree-open-archived-trees))
13936 (org-hide-archived-subtrees (point-min) (point-max)))
13937 (nreverse rtn)))
13939 (defun org-remove-uninherited-tags (tags)
13940 "Remove all tags that are not inherited from the list TAGS."
13941 (cond
13942 ((eq org-use-tag-inheritance t)
13943 (if org-tags-exclude-from-inheritance
13944 (org-delete-all org-tags-exclude-from-inheritance tags)
13945 tags))
13946 ((not org-use-tag-inheritance) nil)
13947 ((stringp org-use-tag-inheritance)
13948 (delq nil (mapcar
13949 (lambda (x)
13950 (if (and (string-match org-use-tag-inheritance x)
13951 (not (member x org-tags-exclude-from-inheritance)))
13952 x nil))
13953 tags)))
13954 ((listp org-use-tag-inheritance)
13955 (delq nil (mapcar
13956 (lambda (x)
13957 (if (member x org-use-tag-inheritance) x nil))
13958 tags)))))
13960 (defun org-match-sparse-tree (&optional todo-only match)
13961 "Create a sparse tree according to tags string MATCH.
13962 MATCH can contain positive and negative selection of tags, like
13963 \"+WORK+URGENT-WITHBOSS\".
13964 If optional argument TODO-ONLY is non-nil, only select lines that are
13965 also TODO lines."
13966 (interactive "P")
13967 (org-agenda-prepare-buffers (list (current-buffer)))
13968 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13970 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13972 (defvar org-cached-props nil)
13973 (defun org-cached-entry-get (pom property)
13974 (if (or (eq t org-use-property-inheritance)
13975 (and (stringp org-use-property-inheritance)
13976 (string-match org-use-property-inheritance property))
13977 (and (listp org-use-property-inheritance)
13978 (member property org-use-property-inheritance)))
13979 ;; Caching is not possible, check it directly
13980 (org-entry-get pom property 'inherit)
13981 ;; Get all properties, so that we can do complicated checks easily
13982 (cdr (assoc property (or org-cached-props
13983 (setq org-cached-props
13984 (org-entry-properties pom)))))))
13986 (defun org-global-tags-completion-table (&optional files)
13987 "Return the list of all tags in all agenda buffer/files.
13988 Optional FILES argument is a list of files which can be used
13989 instead of the agenda files."
13990 (save-excursion
13991 (org-uniquify
13992 (delq nil
13993 (apply 'append
13994 (mapcar
13995 (lambda (file)
13996 (set-buffer (find-file-noselect file))
13997 (append (org-get-buffer-tags)
13998 (mapcar (lambda (x) (if (stringp (car-safe x))
13999 (list (car-safe x)) nil))
14000 org-tag-alist)))
14001 (if (and files (car files))
14002 files
14003 (org-agenda-files))))))))
14005 (defun org-make-tags-matcher (match)
14006 "Create the TAGS/TODO matcher form for the selection string MATCH.
14008 The variable `todo-only' is scoped dynamically into this function.
14009 It will be set to t if the matcher restricts matching to TODO entries,
14010 otherwise will not be touched.
14012 Returns a cons of the selection string MATCH and the constructed
14013 lisp form implementing the matcher. The matcher is to be evaluated
14014 at an Org entry, with point on the headline, and returns t if the
14015 entry matches the selection string MATCH. The returned lisp form
14016 references two variables with information about the entry, which
14017 must be bound around the form's evaluation: todo, the TODO keyword
14018 at the entry (or nil of none); and tags-list, the list of all tags
14019 at the entry including inherited ones. Additionally, the category
14020 of the entry (if any) must be specified as the text property
14021 'org-category on the headline.
14023 See also `org-scan-tags'.
14025 (declare (special todo-only))
14026 (unless (boundp 'todo-only)
14027 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14028 (unless match
14029 ;; Get a new match request, with completion against the global
14030 ;; tags table and the local tags in current buffer
14031 (let ((org-last-tags-completion-table
14032 (org-uniquify
14033 (delq nil (append (org-get-buffer-tags)
14034 (org-global-tags-completion-table))))))
14035 (setq match (org-completing-read-no-i
14036 "Match: " 'org-tags-completion-function nil nil nil
14037 'org-tags-history))))
14039 ;; Parse the string and create a lisp form
14040 (let ((match0 match)
14041 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14042 minus tag mm
14043 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14044 orterms term orlist re-p str-p level-p level-op time-p
14045 prop-p pn pv po gv rest (start 0) (ss 0))
14046 ;; Expand group tags
14047 (setq match (org-tags-expand match))
14049 ;; Check if there is a TODO part of this match, which would be the
14050 ;; part after a "/". TO make sure that this slash is not part of
14051 ;; a property value to be matched against, we also check that there
14052 ;; is no " after that slash.
14053 ;; First, find the last slash
14054 (while (string-match "/+" match ss)
14055 (setq start (match-beginning 0) ss (match-end 0)))
14056 (if (and (string-match "/+" match start)
14057 (not (save-match-data (string-match "\"" match start))))
14058 ;; match contains also a todo-matching request
14059 (progn
14060 (setq tagsmatch (substring match 0 (match-beginning 0))
14061 todomatch (substring match (match-end 0)))
14062 (if (string-match "^!" todomatch)
14063 (setq todo-only t todomatch (substring todomatch 1)))
14064 (if (string-match "^\\s-*$" todomatch)
14065 (setq todomatch nil)))
14066 ;; only matching tags
14067 (setq tagsmatch match todomatch nil))
14069 ;; Make the tags matcher
14070 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14071 (setq tagsmatcher t)
14072 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14073 (while (setq term (pop orterms))
14074 (while (and (equal (substring term -1) "\\") orterms)
14075 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14076 (while (string-match re term)
14077 (setq rest (substring term (match-end 0))
14078 minus (and (match-end 1)
14079 (equal (match-string 1 term) "-"))
14080 tag (save-match-data (replace-regexp-in-string
14081 "\\\\-" "-"
14082 (match-string 2 term)))
14083 re-p (equal (string-to-char tag) ?{)
14084 level-p (match-end 4)
14085 prop-p (match-end 5)
14086 mm (cond
14087 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14088 (level-p
14089 (setq level-op (org-op-to-function (match-string 3 term)))
14090 `(,level-op level ,(string-to-number
14091 (match-string 4 term))))
14092 (prop-p
14093 (setq pn (match-string 5 term)
14094 po (match-string 6 term)
14095 pv (match-string 7 term)
14096 re-p (equal (string-to-char pv) ?{)
14097 str-p (equal (string-to-char pv) ?\")
14098 time-p (save-match-data
14099 (string-match "^\"[[<].*[]>]\"$" pv))
14100 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14101 (if time-p (setq pv (org-matcher-time pv)))
14102 (setq po (org-op-to-function po (if time-p 'time str-p)))
14103 (cond
14104 ((equal pn "CATEGORY")
14105 (setq gv '(get-text-property (point) 'org-category)))
14106 ((equal pn "TODO")
14107 (setq gv 'todo))
14109 (setq gv `(org-cached-entry-get nil ,pn))))
14110 (if re-p
14111 (if (eq po 'org<>)
14112 `(not (string-match ,pv (or ,gv "")))
14113 `(string-match ,pv (or ,gv "")))
14114 (if str-p
14115 `(,po (or ,gv "") ,pv)
14116 `(,po (string-to-number (or ,gv ""))
14117 ,(string-to-number pv) ))))
14118 (t `(member ,tag tags-list)))
14119 mm (if minus (list 'not mm) mm)
14120 term rest)
14121 (push mm tagsmatcher))
14122 (push (if (> (length tagsmatcher) 1)
14123 (cons 'and tagsmatcher)
14124 (car tagsmatcher))
14125 orlist)
14126 (setq tagsmatcher nil))
14127 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14128 (setq tagsmatcher
14129 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14130 ;; Make the todo matcher
14131 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14132 (setq todomatcher t)
14133 (setq orterms (org-split-string todomatch "|") orlist nil)
14134 (while (setq term (pop orterms))
14135 (while (string-match re term)
14136 (setq minus (and (match-end 1)
14137 (equal (match-string 1 term) "-"))
14138 kwd (match-string 2 term)
14139 re-p (equal (string-to-char kwd) ?{)
14140 term (substring term (match-end 0))
14141 mm (if re-p
14142 `(string-match ,(substring kwd 1 -1) todo)
14143 (list 'equal 'todo kwd))
14144 mm (if minus (list 'not mm) mm))
14145 (push mm todomatcher))
14146 (push (if (> (length todomatcher) 1)
14147 (cons 'and todomatcher)
14148 (car todomatcher))
14149 orlist)
14150 (setq todomatcher nil))
14151 (setq todomatcher (if (> (length orlist) 1)
14152 (cons 'or orlist) (car orlist))))
14154 ;; Return the string and lisp forms of the matcher
14155 (setq matcher (if todomatcher
14156 (list 'and tagsmatcher todomatcher)
14157 tagsmatcher))
14158 (when todo-only
14159 (setq matcher (list 'and '(member todo org-not-done-keywords)
14160 matcher)))
14161 (cons match0 matcher)))
14163 (defun org-tags-expand (match &optional single-as-list downcased)
14164 "Expand group tags in MATCH.
14166 This replaces every group tag in MATCH with a regexp tag search.
14167 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14168 will be replaced like this:
14170 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14171 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14172 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14174 Replacing by a regexp preserves the structure of the match.
14175 E.g., this expansion
14177 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14179 will match anything tagged with \"Lab\" and \"Home\", or tagged
14180 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14182 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14183 assumed to be a single group tag, and the function will return
14184 the list of tags in this group.
14186 When DOWNCASE is non-nil, expand downcased TAGS."
14187 (if org-group-tags
14188 (let* ((case-fold-search t)
14189 (stable org-mode-syntax-table)
14190 (tal (or org-tag-groups-alist-for-agenda
14191 org-tag-groups-alist))
14192 (tal (if downcased
14193 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14194 (tml (mapcar 'car tal))
14195 (rtnmatch match) rpl)
14196 ;; @ and _ are allowed as word-components in tags
14197 (modify-syntax-entry ?@ "w" stable)
14198 (modify-syntax-entry ?_ "w" stable)
14199 (while (and tml
14200 (with-syntax-table stable
14201 (string-match
14202 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14203 (regexp-opt tml) "\\>\\)") rtnmatch)))
14204 (let* ((dir (match-string 1 rtnmatch))
14205 (tag (match-string 2 rtnmatch))
14206 (tag (if downcased (downcase tag) tag)))
14207 (setq tml (delete tag tml))
14208 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14209 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14210 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14211 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14212 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14213 (if single-as-list
14214 (or (reverse rpl) (list rtnmatch))
14215 rtnmatch))
14216 (if single-as-list (list (if downcased (downcase match) match))
14217 match)))
14219 (defun org-op-to-function (op &optional stringp)
14220 "Turn an operator into the appropriate function."
14221 (setq op
14222 (cond
14223 ((equal op "<" ) '(< string< org-time<))
14224 ((equal op ">" ) '(> org-string> org-time>))
14225 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14226 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14227 ((member op '("=" "==")) '(= string= org-time=))
14228 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14229 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14231 (defun org<> (a b) (not (= a b)))
14232 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14233 (defun org-string>= (a b) (not (string< a b)))
14234 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14235 (defun org-string<> (a b) (not (string= 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) (> a b)))
14240 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14241 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14242 (defun org-2ft (s)
14243 "Convert S to a floating point time.
14244 If S is already a number, just return it. If it is a string, parse
14245 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14246 (cond
14247 ((numberp s) s)
14248 ((stringp s)
14249 (condition-case nil
14250 (float-time (apply 'encode-time (org-parse-time-string s)))
14251 (error 0.)))
14252 (t 0.)))
14254 (defun org-time-today ()
14255 "Time in seconds today at 0:00.
14256 Returns the float number of seconds since the beginning of the
14257 epoch to the beginning of today (00:00)."
14258 (float-time (apply 'encode-time
14259 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14261 (defun org-matcher-time (s)
14262 "Interpret a time comparison value."
14263 (save-match-data
14264 (cond
14265 ((string= s "<now>") (float-time))
14266 ((string= s "<today>") (org-time-today))
14267 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14268 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14269 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14270 (+ (org-time-today)
14271 (* (string-to-number (match-string 1 s))
14272 (cdr (assoc (match-string 2 s)
14273 '(("d" . 86400.0) ("w" . 604800.0)
14274 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14275 (t (org-2ft s)))))
14277 (defun org-match-any-p (re list)
14278 "Does re match any element of list?"
14279 (setq list (mapcar (lambda (x) (string-match re x)) list))
14280 (delq nil list))
14282 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14283 (defvar org-tags-overlay (make-overlay 1 1))
14284 (org-detach-overlay org-tags-overlay)
14286 (defun org-get-local-tags-at (&optional pos)
14287 "Get a list of tags defined in the current headline."
14288 (org-get-tags-at pos 'local))
14290 (defun org-get-local-tags ()
14291 "Get a list of tags defined in the current headline."
14292 (org-get-tags-at nil 'local))
14294 (defun org-get-tags-at (&optional pos local)
14295 "Get a list of all headline tags applicable at POS.
14296 POS defaults to point. If tags are inherited, the list contains
14297 the targets in the same sequence as the headlines appear, i.e.
14298 the tags of the current headline come last.
14299 When LOCAL is non-nil, only return tags from the current headline,
14300 ignore inherited ones."
14301 (interactive)
14302 (if (and org-trust-scanner-tags
14303 (or (not pos) (equal pos (point)))
14304 (not local))
14305 org-scanner-tags
14306 (let (tags ltags lastpos parent)
14307 (save-excursion
14308 (save-restriction
14309 (widen)
14310 (goto-char (or pos (point)))
14311 (save-match-data
14312 (catch 'done
14313 (condition-case nil
14314 (progn
14315 (org-back-to-heading t)
14316 (while (not (equal lastpos (point)))
14317 (setq lastpos (point))
14318 (when (looking-at
14319 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14320 (setq ltags (org-split-string
14321 (org-match-string-no-properties 1) ":"))
14322 (when parent
14323 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14324 (setq tags (append
14325 (if parent
14326 (org-remove-uninherited-tags ltags)
14327 ltags)
14328 tags)))
14329 (or org-use-tag-inheritance (throw 'done t))
14330 (if local (throw 'done t))
14331 (or (org-up-heading-safe) (error nil))
14332 (setq parent t)))
14333 (error nil)))))
14334 (if local
14335 tags
14336 (reverse (delete-dups
14337 (reverse (append
14338 (org-remove-uninherited-tags
14339 org-file-tags) tags)))))))))
14341 (defun org-add-prop-inherited (s)
14342 (add-text-properties 0 (length s) '(inherited t) s)
14345 (defun org-toggle-tag (tag &optional onoff)
14346 "Toggle the tag TAG for the current line.
14347 If ONOFF is `on' or `off', don't toggle but set to this state."
14348 (let (res current)
14349 (save-excursion
14350 (org-back-to-heading t)
14351 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14352 (point-at-eol) t)
14353 (progn
14354 (setq current (match-string 1))
14355 (replace-match ""))
14356 (setq current ""))
14357 (setq current (nreverse (org-split-string current ":")))
14358 (cond
14359 ((eq onoff 'on)
14360 (setq res t)
14361 (or (member tag current) (push tag current)))
14362 ((eq onoff 'off)
14363 (or (not (member tag current)) (setq current (delete tag current))))
14364 (t (if (member tag current)
14365 (setq current (delete tag current))
14366 (setq res t)
14367 (push tag current))))
14368 (end-of-line 1)
14369 (if current
14370 (progn
14371 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14372 (org-set-tags nil t))
14373 (delete-horizontal-space))
14374 (run-hooks 'org-after-tags-change-hook))
14375 res))
14377 (defun org-align-tags-here (to-col)
14378 ;; Assumes that this is a headline
14379 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14380 (beginning-of-line 1)
14381 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14382 (< pos (match-beginning 2)))
14383 (progn
14384 (setq tags-l (- (match-end 2) (match-beginning 2)))
14385 (goto-char (match-beginning 1))
14386 (insert " ")
14387 (delete-region (point) (1+ (match-beginning 2)))
14388 (setq ncol (max (current-column)
14389 (1+ col)
14390 (if (> to-col 0)
14391 to-col
14392 (- (abs to-col) tags-l))))
14393 (setq p (point))
14394 (insert (make-string (- ncol (current-column)) ?\ ))
14395 (setq ncol (current-column))
14396 (when indent-tabs-mode (tabify p (point-at-eol)))
14397 (org-move-to-column (min ncol col) t nil t))
14398 (goto-char pos))))
14400 (defun org-set-tags-command (&optional arg just-align)
14401 "Call the set-tags command for the current entry."
14402 (interactive "P")
14403 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14404 (org-set-tags arg just-align)
14405 (save-excursion
14406 (unless (and (org-region-active-p)
14407 org-loop-over-headlines-in-active-region)
14408 (org-back-to-heading t))
14409 (org-set-tags arg just-align))))
14411 (defun org-set-tags-to (data)
14412 "Set the tags of the current entry to DATA, replacing the current tags.
14413 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14414 If DATA is nil or the empty string, any tags will be removed."
14415 (interactive "sTags: ")
14416 (setq data
14417 (cond
14418 ((eq data nil) "")
14419 ((equal data "") "")
14420 ((stringp data)
14421 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14422 ":"))
14423 ((listp data)
14424 (concat ":" (mapconcat 'identity data ":") ":"))))
14425 (when data
14426 (save-excursion
14427 (org-back-to-heading t)
14428 (when (looking-at org-complex-heading-regexp)
14429 (if (match-end 5)
14430 (progn
14431 (goto-char (match-beginning 5))
14432 (insert data)
14433 (delete-region (point) (point-at-eol))
14434 (org-set-tags nil 'align))
14435 (goto-char (point-at-eol))
14436 (insert " " data)
14437 (org-set-tags nil 'align)))
14438 (beginning-of-line 1)
14439 (if (looking-at ".*?\\([ \t]+\\)$")
14440 (delete-region (match-beginning 1) (match-end 1))))))
14442 (defun org-align-all-tags ()
14443 "Align the tags i all headings."
14444 (interactive)
14445 (save-excursion
14446 (or (ignore-errors (org-back-to-heading t))
14447 (outline-next-heading))
14448 (if (org-at-heading-p)
14449 (org-set-tags t)
14450 (message "No headings"))))
14452 (defvar org-indent-indentation-per-level)
14453 (defun org-set-tags (&optional arg just-align)
14454 "Set the tags for the current headline.
14455 With prefix ARG, realign all tags in headings in the current buffer."
14456 (interactive "P")
14457 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14458 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14459 'region-start-level 'region))
14460 org-loop-over-headlines-in-active-region)
14461 (org-map-entries
14462 ;; We don't use ARG and JUST-ALIGN here these args are not
14463 ;; useful when looping over headlines
14464 `(org-set-tags)
14465 org-loop-over-headlines-in-active-region
14466 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14467 (let* ((re org-outline-regexp-bol)
14468 (current (unless arg (org-get-tags-string)))
14469 (col (current-column))
14470 (org-setting-tags t)
14471 table current-tags inherited-tags ; computed below when needed
14472 tags p0 c0 c1 rpl di tc level)
14473 (if arg
14474 (save-excursion
14475 (goto-char (point-min))
14476 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14477 (while (re-search-forward re nil t)
14478 (org-set-tags nil t)
14479 (end-of-line 1)))
14480 (message "All tags realigned to column %d" org-tags-column))
14481 (if just-align
14482 (setq tags current)
14483 ;; Get a new set of tags from the user
14484 (save-excursion
14485 (setq table (append org-tag-persistent-alist
14486 (or org-tag-alist (org-get-buffer-tags))
14487 (and
14488 org-complete-tags-always-offer-all-agenda-tags
14489 (org-global-tags-completion-table
14490 (org-agenda-files))))
14491 org-last-tags-completion-table table
14492 current-tags (org-split-string current ":")
14493 inherited-tags (nreverse
14494 (nthcdr (length current-tags)
14495 (nreverse (org-get-tags-at))))
14496 tags
14497 (if (or (eq t org-use-fast-tag-selection)
14498 (and org-use-fast-tag-selection
14499 (delq nil (mapcar 'cdr table))))
14500 (org-fast-tag-selection
14501 current-tags inherited-tags table
14502 (if org-fast-tag-selection-include-todo
14503 org-todo-key-alist))
14504 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14505 (org-trim
14506 (org-icompleting-read "Tags: "
14507 'org-tags-completion-function
14508 nil nil current 'org-tags-history))))))
14509 (while (string-match "[-+&]+" tags)
14510 ;; No boolean logic, just a list
14511 (setq tags (replace-match ":" t t tags))))
14513 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14515 (if org-tags-sort-function
14516 (setq tags (mapconcat 'identity
14517 (sort (org-split-string
14518 tags (org-re "[^[:alnum:]_@#%]+"))
14519 org-tags-sort-function) ":")))
14521 (if (string-match "\\`[\t ]*\\'" tags)
14522 (setq tags "")
14523 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14524 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14526 ;; Insert new tags at the correct column
14527 (beginning-of-line 1)
14528 (setq level (or (and (looking-at org-outline-regexp)
14529 (- (match-end 0) (point) 1))
14531 (cond
14532 ((and (equal current "") (equal tags "")))
14533 ((re-search-forward
14534 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14535 (point-at-eol) t)
14536 (if (equal tags "")
14537 (setq rpl "")
14538 (goto-char (match-beginning 0))
14539 (setq c0 (current-column)
14540 ;; compute offset for the case of org-indent-mode active
14541 di (if org-indent-mode
14542 (* (1- org-indent-indentation-per-level) (1- level))
14544 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14545 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14546 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14547 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14548 (replace-match rpl t t)
14549 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14550 tags)
14551 (t (error "Tags alignment failed")))
14552 (org-move-to-column col)
14553 (unless just-align
14554 (run-hooks 'org-after-tags-change-hook))))))
14556 (defun org-change-tag-in-region (beg end tag off)
14557 "Add or remove TAG for each entry in the region.
14558 This works in the agenda, and also in an org-mode buffer."
14559 (interactive
14560 (list (region-beginning) (region-end)
14561 (let ((org-last-tags-completion-table
14562 (if (derived-mode-p 'org-mode)
14563 (org-uniquify
14564 (delq nil (append (org-get-buffer-tags)
14565 (org-global-tags-completion-table))))
14566 (org-global-tags-completion-table))))
14567 (org-icompleting-read
14568 "Tag: " 'org-tags-completion-function nil nil nil
14569 'org-tags-history))
14570 (progn
14571 (message "[s]et or [r]emove? ")
14572 (equal (read-char-exclusive) ?r))))
14573 (if (fboundp 'deactivate-mark) (deactivate-mark))
14574 (let ((agendap (equal major-mode 'org-agenda-mode))
14575 l1 l2 m buf pos newhead (cnt 0))
14576 (goto-char end)
14577 (setq l2 (1- (org-current-line)))
14578 (goto-char beg)
14579 (setq l1 (org-current-line))
14580 (loop for l from l1 to l2 do
14581 (org-goto-line l)
14582 (setq m (get-text-property (point) 'org-hd-marker))
14583 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14584 (and agendap m))
14585 (setq buf (if agendap (marker-buffer m) (current-buffer))
14586 pos (if agendap m (point)))
14587 (with-current-buffer buf
14588 (save-excursion
14589 (save-restriction
14590 (goto-char pos)
14591 (setq cnt (1+ cnt))
14592 (org-toggle-tag tag (if off 'off 'on))
14593 (setq newhead (org-get-heading)))))
14594 (and agendap (org-agenda-change-all-lines newhead m))))
14595 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14597 (defun org-tags-completion-function (string predicate &optional flag)
14598 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14599 (confirm (lambda (x) (stringp (car x)))))
14600 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14601 (setq s1 (match-string 1 string)
14602 s2 (match-string 2 string))
14603 (setq s1 "" s2 string))
14604 (cond
14605 ((eq flag nil)
14606 ;; try completion
14607 (setq rtn (try-completion s2 ctable confirm))
14608 (if (stringp rtn)
14609 (setq rtn
14610 (concat s1 s2 (substring rtn (length s2))
14611 (if (and org-add-colon-after-tag-completion
14612 (assoc rtn ctable))
14613 ":" ""))))
14614 rtn)
14615 ((eq flag t)
14616 ;; all-completions
14617 (all-completions s2 ctable confirm))
14618 ((eq flag 'lambda)
14619 ;; exact match?
14620 (assoc s2 ctable)))))
14622 (defun org-fast-tag-insert (kwd tags face &optional end)
14623 "Insert KDW, and the TAGS, the latter with face FACE.
14624 Also insert END."
14625 (insert (format "%-12s" (concat kwd ":"))
14626 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14627 (or end "")))
14629 (defun org-fast-tag-show-exit (flag)
14630 (save-excursion
14631 (org-goto-line 3)
14632 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14633 (replace-match ""))
14634 (when flag
14635 (end-of-line 1)
14636 (org-move-to-column (- (window-width) 19) t)
14637 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14639 (defun org-set-current-tags-overlay (current prefix)
14640 "Add an overlay to CURRENT tag with PREFIX."
14641 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14642 (if (featurep 'xemacs)
14643 (org-overlay-display org-tags-overlay (concat prefix s)
14644 'secondary-selection)
14645 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14646 (org-overlay-display org-tags-overlay (concat prefix s)))))
14648 (defvar org-last-tag-selection-key nil)
14649 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14650 "Fast tag selection with single keys.
14651 CURRENT is the current list of tags in the headline, INHERITED is the
14652 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14653 possibly with grouping information. TODO-TABLE is a similar table with
14654 TODO keywords, should these have keys assigned to them.
14655 If the keys are nil, a-z are automatically assigned.
14656 Returns the new tags string, or nil to not change the current settings."
14657 (let* ((fulltable (append table todo-table))
14658 (maxlen (apply 'max (mapcar
14659 (lambda (x)
14660 (if (stringp (car x)) (string-width (car x)) 0))
14661 fulltable)))
14662 (buf (current-buffer))
14663 (expert (eq org-fast-tag-selection-single-key 'expert))
14664 (buffer-tags nil)
14665 (fwidth (+ maxlen 3 1 3))
14666 (ncol (/ (- (window-width) 4) fwidth))
14667 (i-face 'org-done)
14668 (c-face 'org-todo)
14669 tg cnt e c char c1 c2 ntable tbl rtn
14670 ov-start ov-end ov-prefix
14671 (exit-after-next org-fast-tag-selection-single-key)
14672 (done-keywords org-done-keywords)
14673 groups ingroup)
14674 (save-excursion
14675 (beginning-of-line 1)
14676 (if (looking-at
14677 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14678 (setq ov-start (match-beginning 1)
14679 ov-end (match-end 1)
14680 ov-prefix "")
14681 (setq ov-start (1- (point-at-eol))
14682 ov-end (1+ ov-start))
14683 (skip-chars-forward "^\n\r")
14684 (setq ov-prefix
14685 (concat
14686 (buffer-substring (1- (point)) (point))
14687 (if (> (current-column) org-tags-column)
14689 (make-string (- org-tags-column (current-column)) ?\ ))))))
14690 (move-overlay org-tags-overlay ov-start ov-end)
14691 (save-window-excursion
14692 (if expert
14693 (set-buffer (get-buffer-create " *Org tags*"))
14694 (delete-other-windows)
14695 (split-window-vertically)
14696 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14697 (erase-buffer)
14698 (org-set-local 'org-done-keywords done-keywords)
14699 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14700 (org-fast-tag-insert "Current" current c-face "\n\n")
14701 (org-fast-tag-show-exit exit-after-next)
14702 (org-set-current-tags-overlay current ov-prefix)
14703 (setq tbl fulltable char ?a cnt 0)
14704 (while (setq e (pop tbl))
14705 (cond
14706 ((equal (car e) :startgroup)
14707 (push '() groups) (setq ingroup t)
14708 (when (not (= cnt 0))
14709 (setq cnt 0)
14710 (insert "\n"))
14711 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14712 ((equal (car e) :endgroup)
14713 (setq ingroup nil cnt 0)
14714 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14715 ((equal e '(:newline))
14716 (when (not (= cnt 0))
14717 (setq cnt 0)
14718 (insert "\n")
14719 (setq e (car tbl))
14720 (while (equal (car tbl) '(:newline))
14721 (insert "\n")
14722 (setq tbl (cdr tbl)))))
14723 ((equal e '(:grouptags)) nil)
14725 (setq tg (copy-sequence (car e)) c2 nil)
14726 (if (cdr e)
14727 (setq c (cdr e))
14728 ;; automatically assign a character.
14729 (setq c1 (string-to-char
14730 (downcase (substring
14731 tg (if (= (string-to-char tg) ?@) 1 0)))))
14732 (if (or (rassoc c1 ntable) (rassoc c1 table))
14733 (while (or (rassoc char ntable) (rassoc char table))
14734 (setq char (1+ char)))
14735 (setq c2 c1))
14736 (setq c (or c2 char)))
14737 (if ingroup (push tg (car groups)))
14738 (setq tg (org-add-props tg nil 'face
14739 (cond
14740 ((not (assoc tg table))
14741 (org-get-todo-face tg))
14742 ((member tg current) c-face)
14743 ((member tg inherited) i-face))))
14744 (if (equal (caar tbl) :grouptags)
14745 (org-add-props tg nil 'face 'org-tag-group))
14746 (if (and (= cnt 0) (not ingroup)) (insert " "))
14747 (insert "[" c "] " tg (make-string
14748 (- fwidth 4 (length tg)) ?\ ))
14749 (push (cons tg c) ntable)
14750 (when (= (setq cnt (1+ cnt)) ncol)
14751 (insert "\n")
14752 (if ingroup (insert " "))
14753 (setq cnt 0)))))
14754 (setq ntable (nreverse ntable))
14755 (insert "\n")
14756 (goto-char (point-min))
14757 (if (not expert) (org-fit-window-to-buffer))
14758 (setq rtn
14759 (catch 'exit
14760 (while t
14761 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14762 (if (not groups) "no " "")
14763 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14764 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14765 (setq org-last-tag-selection-key c)
14766 (cond
14767 ((= c ?\r) (throw 'exit t))
14768 ((= c ?!)
14769 (setq groups (not groups))
14770 (goto-char (point-min))
14771 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14772 ((= c ?\C-c)
14773 (if (not expert)
14774 (org-fast-tag-show-exit
14775 (setq exit-after-next (not exit-after-next)))
14776 (setq expert nil)
14777 (delete-other-windows)
14778 (set-window-buffer (split-window-vertically) " *Org tags*")
14779 (org-switch-to-buffer-other-window " *Org tags*")
14780 (org-fit-window-to-buffer)))
14781 ((or (= c ?\C-g)
14782 (and (= c ?q) (not (rassoc c ntable))))
14783 (org-detach-overlay org-tags-overlay)
14784 (setq quit-flag t))
14785 ((= c ?\ )
14786 (setq current nil)
14787 (if exit-after-next (setq exit-after-next 'now)))
14788 ((= c ?\t)
14789 (condition-case nil
14790 (setq tg (org-icompleting-read
14791 "Tag: "
14792 (or buffer-tags
14793 (with-current-buffer buf
14794 (org-get-buffer-tags)))))
14795 (quit (setq tg "")))
14796 (when (string-match "\\S-" tg)
14797 (add-to-list 'buffer-tags (list tg))
14798 (if (member tg current)
14799 (setq current (delete tg current))
14800 (push tg current)))
14801 (if exit-after-next (setq exit-after-next 'now)))
14802 ((setq e (rassoc c todo-table) tg (car e))
14803 (with-current-buffer buf
14804 (save-excursion (org-todo tg)))
14805 (if exit-after-next (setq exit-after-next 'now)))
14806 ((setq e (rassoc c ntable) tg (car e))
14807 (if (member tg current)
14808 (setq current (delete tg current))
14809 (loop for g in groups do
14810 (if (member tg g)
14811 (mapc (lambda (x)
14812 (setq current (delete x current)))
14813 g)))
14814 (push tg current))
14815 (if exit-after-next (setq exit-after-next 'now))))
14817 ;; Create a sorted list
14818 (setq current
14819 (sort current
14820 (lambda (a b)
14821 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14822 (if (eq exit-after-next 'now) (throw 'exit t))
14823 (goto-char (point-min))
14824 (beginning-of-line 2)
14825 (delete-region (point) (point-at-eol))
14826 (org-fast-tag-insert "Current" current c-face)
14827 (org-set-current-tags-overlay current ov-prefix)
14828 (while (re-search-forward
14829 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14830 (setq tg (match-string 1))
14831 (add-text-properties
14832 (match-beginning 1) (match-end 1)
14833 (list 'face
14834 (cond
14835 ((member tg current) c-face)
14836 ((member tg inherited) i-face)
14837 (t (get-text-property (match-beginning 1) 'face))))))
14838 (goto-char (point-min)))))
14839 (org-detach-overlay org-tags-overlay)
14840 (if rtn
14841 (mapconcat 'identity current ":")
14842 nil))))
14844 (defun org-get-tags-string ()
14845 "Get the TAGS string in the current headline."
14846 (unless (org-at-heading-p t)
14847 (user-error "Not on a heading"))
14848 (save-excursion
14849 (beginning-of-line 1)
14850 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14851 (org-match-string-no-properties 1)
14852 "")))
14854 (defun org-get-tags ()
14855 "Get the list of tags specified in the current headline."
14856 (org-split-string (org-get-tags-string) ":"))
14858 (defun org-get-buffer-tags ()
14859 "Get a table of all tags used in the buffer, for completion."
14860 (let (tags)
14861 (save-excursion
14862 (goto-char (point-min))
14863 (while (re-search-forward
14864 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14865 (when (equal (char-after (point-at-bol 0)) ?*)
14866 (mapc (lambda (x) (add-to-list 'tags x))
14867 (org-split-string (org-match-string-no-properties 1) ":")))))
14868 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14869 (mapcar 'list tags)))
14871 ;;;; The mapping API
14873 (defun org-map-entries (func &optional match scope &rest skip)
14874 "Call FUNC at each headline selected by MATCH in SCOPE.
14876 FUNC is a function or a lisp form. The function will be called without
14877 arguments, with the cursor positioned at the beginning of the headline.
14878 The return values of all calls to the function will be collected and
14879 returned as a list.
14881 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14882 does not need to preserve point. After evaluation, the cursor will be
14883 moved to the end of the line (presumably of the headline of the
14884 processed entry) and search continues from there. Under some
14885 circumstances, this may not produce the wanted results. For example,
14886 if you have removed (e.g. archived) the current (sub)tree it could
14887 mean that the next entry will be skipped entirely. In such cases, you
14888 can specify the position from where search should continue by making
14889 FUNC set the variable `org-map-continue-from' to the desired buffer
14890 position.
14892 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14893 Only headlines that are matched by this query will be considered during
14894 the iteration. When MATCH is nil or t, all headlines will be
14895 visited by the iteration.
14897 SCOPE determines the scope of this command. It can be any of:
14899 nil The current buffer, respecting the restriction if any
14900 tree The subtree started with the entry at point
14901 region The entries within the active region, if any
14902 region-start-level
14903 The entries within the active region, but only those at
14904 the same level than the first one.
14905 file The current buffer, without restriction
14906 file-with-archives
14907 The current buffer, and any archives associated with it
14908 agenda All agenda files
14909 agenda-with-archives
14910 All agenda files with any archive files associated with them
14911 \(file1 file2 ...)
14912 If this is a list, all files in the list will be scanned
14914 The remaining args are treated as settings for the skipping facilities of
14915 the scanner. The following items can be given here:
14917 archive skip trees with the archive tag
14918 comment skip trees with the COMMENT keyword
14919 function or Emacs Lisp form:
14920 will be used as value for `org-agenda-skip-function', so
14921 whenever the function returns a position, FUNC will not be
14922 called for that entry and search will continue from the
14923 position returned
14925 If your function needs to retrieve the tags including inherited tags
14926 at the *current* entry, you can use the value of the variable
14927 `org-scanner-tags' which will be much faster than getting the value
14928 with `org-get-tags-at'. If your function gets properties with
14929 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14930 to t around the call to `org-entry-properties' to get the same speedup.
14931 Note that if your function moves around to retrieve tags and properties at
14932 a *different* entry, you cannot use these techniques."
14933 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14934 (not (org-region-active-p)))
14935 (let* ((org-agenda-archives-mode nil) ; just to make sure
14936 (org-agenda-skip-archived-trees (memq 'archive skip))
14937 (org-agenda-skip-comment-trees (memq 'comment skip))
14938 (org-agenda-skip-function
14939 (car (org-delete-all '(comment archive) skip)))
14940 (org-tags-match-list-sublevels t)
14941 (start-level (eq scope 'region-start-level))
14942 matcher file res
14943 org-todo-keywords-for-agenda
14944 org-done-keywords-for-agenda
14945 org-todo-keyword-alist-for-agenda
14946 org-drawers-for-agenda
14947 org-tag-alist-for-agenda
14948 todo-only)
14950 (cond
14951 ((eq match t) (setq matcher t))
14952 ((eq match nil) (setq matcher t))
14953 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14955 (save-window-excursion
14956 (save-restriction
14957 (cond ((eq scope 'tree)
14958 (org-back-to-heading t)
14959 (org-narrow-to-subtree)
14960 (setq scope nil))
14961 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14962 (org-region-active-p))
14963 ;; If needed, set start-level to a string like "2"
14964 (when start-level
14965 (save-excursion
14966 (goto-char (region-beginning))
14967 (unless (org-at-heading-p) (outline-next-heading))
14968 (setq start-level (org-current-level))))
14969 (narrow-to-region (region-beginning)
14970 (save-excursion
14971 (goto-char (region-end))
14972 (unless (and (bolp) (org-at-heading-p))
14973 (outline-next-heading))
14974 (point)))
14975 (setq scope nil)))
14977 (if (not scope)
14978 (progn
14979 (org-agenda-prepare-buffers
14980 (list (buffer-file-name (current-buffer))))
14981 (setq res (org-scan-tags func matcher todo-only start-level)))
14982 ;; Get the right scope
14983 (cond
14984 ((and scope (listp scope) (symbolp (car scope)))
14985 (setq scope (eval scope)))
14986 ((eq scope 'agenda)
14987 (setq scope (org-agenda-files t)))
14988 ((eq scope 'agenda-with-archives)
14989 (setq scope (org-agenda-files t))
14990 (setq scope (org-add-archive-files scope)))
14991 ((eq scope 'file)
14992 (setq scope (list (buffer-file-name))))
14993 ((eq scope 'file-with-archives)
14994 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14995 (org-agenda-prepare-buffers scope)
14996 (while (setq file (pop scope))
14997 (with-current-buffer (org-find-base-buffer-visiting file)
14998 (save-excursion
14999 (save-restriction
15000 (widen)
15001 (goto-char (point-min))
15002 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15003 res)))
15005 ;;;; Properties
15007 ;;; Setting and retrieving properties
15009 (defconst org-special-properties
15010 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15011 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15012 "The special properties valid in Org-mode.
15014 These are properties that are not defined in the property drawer,
15015 but in some other way.")
15017 (defconst org-default-properties
15018 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15019 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15020 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15021 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15022 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15023 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15024 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15025 "Some properties that are used by Org-mode for various purposes.
15026 Being in this list makes sure that they are offered for completion.")
15028 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15029 "Regular expression matching the first line of a property drawer.")
15031 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15032 "Regular expression matching the last line of a property drawer.")
15034 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15035 "Regular expression matching the first line of a property drawer.")
15037 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15038 "Regular expression matching the first line of a property drawer.")
15040 (defconst org-property-drawer-re
15041 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15042 org-property-end-re "\\)\n?")
15043 "Matches an entire property drawer.")
15045 (defconst org-clock-drawer-re
15046 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15047 org-property-end-re "\\)\n?")
15048 "Matches an entire clock drawer.")
15050 (defun org-property-action ()
15051 "Do an action on properties."
15052 (interactive)
15053 (let (c)
15054 (org-at-property-p)
15055 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15056 (setq c (read-char-exclusive))
15057 (cond
15058 ((equal c ?s)
15059 (call-interactively 'org-set-property))
15060 ((equal c ?d)
15061 (call-interactively 'org-delete-property))
15062 ((equal c ?D)
15063 (call-interactively 'org-delete-property-globally))
15064 ((equal c ?c)
15065 (call-interactively 'org-compute-property-at-point))
15066 (t (user-error "No such property action %c" c)))))
15068 (defun org-inc-effort ()
15069 "Increment the value of the effort property in the current entry."
15070 (interactive)
15071 (org-set-effort nil t))
15073 (defvar org-clock-effort) ;; Defined in org-clock.el
15074 (defvar org-clock-current-task) ;; Defined in org-clock.el
15075 (defun org-set-effort (&optional value increment)
15076 "Set the effort property of the current entry.
15077 With numerical prefix arg, use the nth allowed value, 0 stands for the
15078 10th allowed value.
15080 When INCREMENT is non-nil, set the property to the next allowed value."
15081 (interactive "P")
15082 (if (equal value 0) (setq value 10))
15083 (let* ((completion-ignore-case t)
15084 (prop org-effort-property)
15085 (cur (org-entry-get nil prop))
15086 (allowed (org-property-get-allowed-values nil prop 'table))
15087 (existing (mapcar 'list (org-property-values prop)))
15088 (heading (nth 4 (org-heading-components)))
15090 (val (cond
15091 ((stringp value) value)
15092 ((and allowed (integerp value))
15093 (or (car (nth (1- value) allowed))
15094 (car (org-last allowed))))
15095 ((and allowed increment)
15096 (or (caadr (member (list cur) allowed))
15097 (user-error "Allowed effort values are not set")))
15098 (allowed
15099 (message "Select 1-9,0, [RET%s]: %s"
15100 (if cur (concat "=" cur) "")
15101 (mapconcat 'car allowed " "))
15102 (setq rpl (read-char-exclusive))
15103 (if (equal rpl ?\r)
15105 (setq rpl (- rpl ?0))
15106 (if (equal rpl 0) (setq rpl 10))
15107 (if (and (> rpl 0) (<= rpl (length allowed)))
15108 (car (nth (1- rpl) allowed))
15109 (org-completing-read "Effort: " allowed nil))))
15111 (let (org-completion-use-ido org-completion-use-iswitchb)
15112 (org-completing-read
15113 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15114 (concat "[" cur "]") "")
15115 ": ")
15116 existing nil nil "" nil cur))))))
15117 (unless (equal (org-entry-get nil prop) val)
15118 (org-entry-put nil prop val))
15119 (save-excursion
15120 (org-back-to-heading t)
15121 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15122 (when (string= heading org-clock-current-task)
15123 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15124 (org-clock-update-mode-line))
15125 (message "%s is now %s" prop val)))
15127 (defun org-at-property-p ()
15128 "Is cursor inside a property drawer?"
15129 (save-excursion
15130 (when (equal 'node-property (car (org-element-at-point)))
15131 (beginning-of-line 1)
15132 (looking-at org-property-re))))
15134 (defun org-get-property-block (&optional beg end force)
15135 "Return the (beg . end) range of the body of the property drawer.
15136 BEG and END are the beginning and end of the current subtree, or of
15137 the part before the first headline. If they are not given, they will
15138 be found. If the drawer does not exist and FORCE is non-nil, create
15139 the drawer."
15140 (catch 'exit
15141 (save-excursion
15142 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15143 (progn (org-back-to-heading t) (point))))
15144 (end (or end (and (not (outline-next-heading)) (point-max))
15145 (point))))
15146 (goto-char beg)
15147 (if (re-search-forward org-property-start-re end t)
15148 (setq beg (1+ (match-end 0)))
15149 (if force
15150 (save-excursion
15151 (org-insert-property-drawer)
15152 (setq end (progn (outline-next-heading) (point))))
15153 (throw 'exit nil))
15154 (goto-char beg)
15155 (if (re-search-forward org-property-start-re end t)
15156 (setq beg (1+ (match-end 0)))))
15157 (if (re-search-forward org-property-end-re end t)
15158 (setq end (match-beginning 0))
15159 (or force (throw 'exit nil))
15160 (goto-char beg)
15161 (setq end beg)
15162 (org-indent-line)
15163 (insert ":END:\n"))
15164 (cons beg end)))))
15166 (defun org-entry-properties (&optional pom which specific)
15167 "Get all properties of the entry at point-or-marker POM.
15168 This includes the TODO keyword, the tags, time strings for deadline,
15169 scheduled, and clocking, and any additional properties defined in the
15170 entry. The return value is an alist, keys may occur multiple times
15171 if the property key was used several times.
15172 POM may also be nil, in which case the current entry is used.
15173 If WHICH is nil or `all', get all properties. If WHICH is
15174 `special' or `standard', only get that subclass. If WHICH
15175 is a string only get exactly this property. SPECIFIC can be a string, the
15176 specific property we are interested in. Specifying it can speed
15177 things up because then unnecessary parsing is avoided."
15178 (setq which (or which 'all))
15179 (org-with-point-at pom
15180 (let ((clockstr (substring org-clock-string 0 -1))
15181 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15182 (case-fold-search nil)
15183 beg end range props sum-props key key1 value string clocksum clocksumt)
15184 (save-excursion
15185 (when (condition-case nil
15186 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15187 (error nil))
15188 (setq beg (point))
15189 (setq sum-props (get-text-property (point) 'org-summaries))
15190 (setq clocksum (get-text-property (point) :org-clock-minutes)
15191 clocksumt (get-text-property (point) :org-clock-minutes-today))
15192 (outline-next-heading)
15193 (setq end (point))
15194 (when (memq which '(all special))
15195 ;; Get the special properties, like TODO and tags
15196 (goto-char beg)
15197 (when (and (or (not specific) (string= specific "TODO"))
15198 (looking-at org-todo-line-regexp) (match-end 2))
15199 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15200 (when (and (or (not specific) (string= specific "PRIORITY"))
15201 (looking-at org-priority-regexp))
15202 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15203 (when (or (not specific) (string= specific "FILE"))
15204 (push (cons "FILE" buffer-file-name) props))
15205 (when (and (or (not specific) (string= specific "TAGS"))
15206 (setq value (org-get-tags-string))
15207 (string-match "\\S-" value))
15208 (push (cons "TAGS" value) props))
15209 (when (and (or (not specific) (string= specific "ALLTAGS"))
15210 (setq value (org-get-tags-at)))
15211 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15212 ":"))
15213 props))
15214 (when (or (not specific) (string= specific "BLOCKED"))
15215 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15216 (when (or (not specific)
15217 (member specific
15218 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15219 "TIMESTAMP" "TIMESTAMP_IA")))
15220 (catch 'match
15221 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15222 (setq key (if (match-end 1)
15223 (substring (org-match-string-no-properties 1)
15224 0 -1))
15225 string (if (equal key clockstr)
15226 (org-trim
15227 (buffer-substring-no-properties
15228 (match-beginning 3) (goto-char
15229 (point-at-eol))))
15230 (substring (org-match-string-no-properties 3)
15231 1 -1)))
15232 ;; Get the correct property name from the key. This is
15233 ;; necessary if the user has configured time keywords.
15234 (setq key1 (concat key ":"))
15235 (cond
15236 ((not key)
15237 (setq key
15238 (if (= (char-after (match-beginning 3)) ?\[)
15239 "TIMESTAMP_IA" "TIMESTAMP")))
15240 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15241 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15242 ((equal key1 org-closed-string) (setq key "CLOSED"))
15243 ((equal key1 org-clock-string) (setq key "CLOCK")))
15244 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15245 (progn
15246 (push (cons key string) props)
15247 ;; no need to search further if match is found
15248 (throw 'match t))
15249 (when (or (equal key "CLOCK") (not (assoc key props)))
15250 (push (cons key string) props)))))))
15252 (when (memq which '(all standard))
15253 ;; Get the standard properties, like :PROP: ...
15254 (setq range (org-get-property-block beg end))
15255 (when range
15256 (goto-char (car range))
15257 (while (re-search-forward org-property-re
15258 (cdr range) t)
15259 (setq key (org-match-string-no-properties 2)
15260 value (org-trim (or (org-match-string-no-properties 3) "")))
15261 (unless (member key excluded)
15262 (push (cons key (or value "")) props)))))
15263 (if clocksum
15264 (push (cons "CLOCKSUM"
15265 (org-columns-number-to-string (/ (float clocksum) 60.)
15266 'add_times))
15267 props))
15268 (if clocksumt
15269 (push (cons "CLOCKSUM_T"
15270 (org-columns-number-to-string (/ (float clocksumt) 60.)
15271 'add_times))
15272 props))
15273 (unless (assoc "CATEGORY" props)
15274 (push (cons "CATEGORY" (org-get-category)) props))
15275 (append sum-props (nreverse props)))))))
15277 (defun org-entry-get (pom property &optional inherit literal-nil)
15278 "Get value of PROPERTY for entry or content at point-or-marker POM.
15279 If INHERIT is non-nil and the entry does not have the property,
15280 then also check higher levels of the hierarchy.
15281 If INHERIT is the symbol `selective', use inheritance only if the setting
15282 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15283 If the property is present but empty, the return value is the empty string.
15284 If the property is not present at all, nil is returned.
15286 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15287 do not interpret it as the list atom nil. This is used for inheritance
15288 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15289 (org-with-point-at pom
15290 (if (and inherit (if (eq inherit 'selective)
15291 (org-property-inherit-p property)
15293 (org-entry-get-with-inheritance property literal-nil)
15294 (if (member property org-special-properties)
15295 ;; We need a special property. Use `org-entry-properties' to
15296 ;; retrieve it, but specify the wanted property
15297 (cdr (assoc property (org-entry-properties nil 'special property)))
15298 (let ((range (org-get-property-block)))
15299 (when (and range (not (eq (car range) (cdr range))))
15300 (let* ((props (list (or (assoc property org-file-properties)
15301 (assoc property org-global-properties)
15302 (assoc property org-global-properties-fixed))))
15303 (ap (lambda (key)
15304 (when (re-search-forward
15305 (org-re-property key) (cdr range) t)
15306 (setq props
15307 (org-update-property-plist
15309 (if (match-end 3)
15310 (org-match-string-no-properties 3) "")
15311 props)))))
15312 val)
15313 (goto-char (car range))
15314 (funcall ap property)
15315 (goto-char (car range))
15316 (while (funcall ap (concat property "+")))
15317 (setq val (cdr (assoc property props)))
15318 (when val (if literal-nil val (org-not-nil val))))))))))
15320 (defun org-property-or-variable-value (var &optional inherit)
15321 "Check if there is a property fixing the value of VAR.
15322 If yes, return this value. If not, return the current value of the variable."
15323 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15324 (if (and prop (stringp prop) (string-match "\\S-" prop))
15325 (read prop)
15326 (symbol-value var))))
15328 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15329 "Delete the property PROPERTY from entry at point-or-marker POM.
15330 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15331 an empty drawer to delete."
15332 (org-with-point-at pom
15333 (if (member property org-special-properties)
15334 nil ; cannot delete these properties.
15335 (let ((range (org-get-property-block)))
15336 (if (and range
15337 (goto-char (car range))
15338 (re-search-forward
15339 (org-re-property property)
15340 (cdr range) t))
15341 (progn
15342 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15343 (and delete-empty-drawer
15344 (org-remove-empty-drawer-at
15345 delete-empty-drawer (car range)))
15347 nil)))))
15349 ;; Multi-values properties are properties that contain multiple values
15350 ;; These values are assumed to be single words, separated by whitespace.
15351 (defun org-entry-add-to-multivalued-property (pom property value)
15352 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15353 (let* ((old (org-entry-get pom property))
15354 (values (and old (org-split-string old "[ \t]"))))
15355 (setq value (org-entry-protect-space value))
15356 (unless (member value values)
15357 (setq values (append values (list value)))
15358 (org-entry-put pom property
15359 (mapconcat 'identity values " ")))))
15361 (defun org-entry-remove-from-multivalued-property (pom property value)
15362 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15363 (let* ((old (org-entry-get pom property))
15364 (values (and old (org-split-string old "[ \t]"))))
15365 (setq value (org-entry-protect-space value))
15366 (when (member value values)
15367 (setq values (delete value values))
15368 (org-entry-put pom property
15369 (mapconcat 'identity values " ")))))
15371 (defun org-entry-member-in-multivalued-property (pom property value)
15372 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15373 (let* ((old (org-entry-get pom property))
15374 (values (and old (org-split-string old "[ \t]"))))
15375 (setq value (org-entry-protect-space value))
15376 (member value values)))
15378 (defun org-entry-get-multivalued-property (pom property)
15379 "Return a list of values in a multivalued property."
15380 (let* ((value (org-entry-get pom property))
15381 (values (and value (org-split-string value "[ \t]"))))
15382 (mapcar 'org-entry-restore-space values)))
15384 (defun org-entry-put-multivalued-property (pom property &rest values)
15385 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15386 VALUES should be a list of strings. Spaces will be protected."
15387 (org-entry-put pom property
15388 (mapconcat 'org-entry-protect-space values " "))
15389 (let* ((value (org-entry-get pom property))
15390 (values (and value (org-split-string value "[ \t]"))))
15391 (mapcar 'org-entry-restore-space values)))
15393 (defun org-entry-protect-space (s)
15394 "Protect spaces and newline in string S."
15395 (while (string-match " " s)
15396 (setq s (replace-match "%20" t t s)))
15397 (while (string-match "\n" s)
15398 (setq s (replace-match "%0A" t t s)))
15401 (defun org-entry-restore-space (s)
15402 "Restore spaces and newline in string S."
15403 (while (string-match "%20" s)
15404 (setq s (replace-match " " t t s)))
15405 (while (string-match "%0A" s)
15406 (setq s (replace-match "\n" t t s)))
15409 (defvar org-entry-property-inherited-from (make-marker)
15410 "Marker pointing to the entry from where a property was inherited.
15411 Each call to `org-entry-get-with-inheritance' will set this marker to the
15412 location of the entry where the inheritance search matched. If there was
15413 no match, the marker will point nowhere.
15414 Note that also `org-entry-get' calls this function, if the INHERIT flag
15415 is set.")
15417 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15418 "Get PROPERTY of entry or content at point, search higher levels if needed.
15419 The search will stop at the first ancestor which has the property defined.
15420 If the value found is \"nil\", return nil to show that the property
15421 should be considered as undefined (this is the meaning of nil here).
15422 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15423 (move-marker org-entry-property-inherited-from nil)
15424 (let (tmp)
15425 (save-excursion
15426 (save-restriction
15427 (widen)
15428 (catch 'ex
15429 (while t
15430 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15431 (or (ignore-errors (org-back-to-heading t))
15432 (goto-char (point-min)))
15433 (move-marker org-entry-property-inherited-from (point))
15434 (throw 'ex tmp))
15435 (or (ignore-errors (org-up-heading-safe))
15436 (throw 'ex nil))))))
15437 (setq tmp (or tmp
15438 (cdr (assoc property org-file-properties))
15439 (cdr (assoc property org-global-properties))
15440 (cdr (assoc property org-global-properties-fixed))))
15441 (if literal-nil tmp (org-not-nil tmp))))
15443 (defvar org-property-changed-functions nil
15444 "Hook called when the value of a property has changed.
15445 Each hook function should accept two arguments, the name of the property
15446 and the new value.")
15448 (defun org-entry-put (pom property value)
15449 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15450 (org-with-point-at pom
15451 (org-back-to-heading t)
15452 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15453 range)
15454 (cond
15455 ((equal property "TODO")
15456 (when (and (stringp value) (string-match "\\S-" value)
15457 (not (member value org-todo-keywords-1)))
15458 (user-error "\"%s\" is not a valid TODO state" value))
15459 (if (or (not value)
15460 (not (string-match "\\S-" value)))
15461 (setq value 'none))
15462 (org-todo value)
15463 (org-set-tags nil 'align))
15464 ((equal property "PRIORITY")
15465 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15466 (string-to-char value) ?\ ))
15467 (org-set-tags nil 'align))
15468 ((equal property "CLOCKSUM")
15469 (if (not (re-search-forward
15470 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15471 (error "Cannot find a clock log")
15472 (goto-char (- (match-end 1) 2))
15473 (cond
15474 ((eq value 'earlier) (org-timestamp-down))
15475 ((eq value 'later) (org-timestamp-up)))
15476 (org-clock-sum-current-item)))
15477 ((equal property "SCHEDULED")
15478 (if (re-search-forward org-scheduled-time-regexp end t)
15479 (cond
15480 ((eq value 'earlier) (org-timestamp-change -1 'day))
15481 ((eq value 'later) (org-timestamp-change 1 'day))
15482 (t (call-interactively 'org-schedule)))
15483 (call-interactively 'org-schedule)))
15484 ((equal property "DEADLINE")
15485 (if (re-search-forward org-deadline-time-regexp end t)
15486 (cond
15487 ((eq value 'earlier) (org-timestamp-change -1 'day))
15488 ((eq value 'later) (org-timestamp-change 1 'day))
15489 (t (call-interactively 'org-deadline)))
15490 (call-interactively 'org-deadline)))
15491 ((member property org-special-properties)
15492 (error "The %s property can not yet be set with `org-entry-put'"
15493 property))
15494 (t ; a non-special property
15495 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15496 (setq range (org-get-property-block beg end 'force))
15497 (goto-char (car range))
15498 (if (re-search-forward
15499 (org-re-property property) (cdr range) t)
15500 (progn
15501 (delete-region (match-beginning 0) (match-end 0))
15502 (goto-char (match-beginning 0)))
15503 (goto-char (cdr range))
15504 (insert "\n")
15505 (backward-char 1)
15506 (org-indent-line))
15507 (insert ":" property ":")
15508 (and value (insert " " value))
15509 (org-indent-line)))))
15510 (run-hook-with-args 'org-property-changed-functions property value)))
15512 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15513 "Get all property keys in the current buffer.
15514 With INCLUDE-SPECIALS, also list the special properties that reflect things
15515 like tags and TODO state.
15516 With INCLUDE-DEFAULTS, also include properties that has special meaning
15517 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15518 and others.
15519 With INCLUDE-COLUMNS, also include property names given in COLUMN
15520 formats in the current buffer."
15521 (let (rtn range cfmt s p)
15522 (save-excursion
15523 (save-restriction
15524 (widen)
15525 (goto-char (point-min))
15526 (while (re-search-forward org-property-start-re nil t)
15527 (setq range (org-get-property-block))
15528 (goto-char (car range))
15529 (while (re-search-forward org-property-re
15530 (cdr range) t)
15531 (add-to-list 'rtn (org-match-string-no-properties 2)))
15532 (outline-next-heading))))
15534 (when include-specials
15535 (setq rtn (append org-special-properties rtn)))
15537 (when include-defaults
15538 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15539 (add-to-list 'rtn org-effort-property))
15541 (when include-columns
15542 (save-excursion
15543 (save-restriction
15544 (widen)
15545 (goto-char (point-min))
15546 (while (re-search-forward
15547 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15548 nil t)
15549 (setq cfmt (match-string 2) s 0)
15550 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15551 cfmt s)
15552 (setq s (match-end 0)
15553 p (match-string 1 cfmt))
15554 (unless (or (equal p "ITEM")
15555 (member p org-special-properties))
15556 (add-to-list 'rtn (match-string 1 cfmt))))))))
15558 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15560 (defun org-property-values (key)
15561 "Return a list of all values of property KEY in the current buffer."
15562 (save-excursion
15563 (save-restriction
15564 (widen)
15565 (goto-char (point-min))
15566 (let ((re (org-re-property key))
15567 values)
15568 (while (re-search-forward re nil t)
15569 (add-to-list 'values (org-trim (match-string 3))))
15570 (delete "" values)))))
15572 (defun org-insert-property-drawer ()
15573 "Insert a property drawer into the current entry."
15574 (org-back-to-heading t)
15575 (looking-at org-outline-regexp)
15576 (let ((indent (if org-adapt-indentation
15577 (- (match-end 0) (match-beginning 0))
15579 (beg (point))
15580 (re (concat "^[ \t]*" org-keyword-time-regexp))
15581 end hiddenp)
15582 (outline-next-heading)
15583 (setq end (point))
15584 (goto-char beg)
15585 (while (re-search-forward re end t))
15586 (setq hiddenp (outline-invisible-p))
15587 (end-of-line 1)
15588 (and (equal (char-after) ?\n) (forward-char 1))
15589 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15590 (if (member (match-string 1) '("CLOCK:" ":END:"))
15591 ;; just skip this line
15592 (beginning-of-line 2)
15593 ;; Drawer start, find the end
15594 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15595 (beginning-of-line 1)))
15596 (org-skip-over-state-notes)
15597 (skip-chars-backward " \t\n\r")
15598 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15599 (forward-char 1))
15600 (goto-char (point-at-eol))
15601 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15602 (beginning-of-line 0)
15603 (org-indent-to-column indent)
15604 (beginning-of-line 2)
15605 (org-indent-to-column indent)
15606 (beginning-of-line 0)
15607 (if hiddenp
15608 (save-excursion
15609 (org-back-to-heading t)
15610 (hide-entry))
15611 (org-flag-drawer t))))
15613 (defun org-insert-drawer (&optional arg drawer)
15614 "Insert a drawer at point.
15616 Optional argument DRAWER, when non-nil, is a string representing
15617 drawer's name. Otherwise, the user is prompted for a name.
15619 If a region is active, insert the drawer around that region
15620 instead.
15622 Point is left between drawer's boundaries."
15623 (interactive "P")
15624 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15625 "LOGBOOK"))
15626 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15627 ;; internally by Org. They are meant to be inserted
15628 ;; automatically.
15629 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15630 ;; Remove system drawers from list. Note: For some reason,
15631 ;; `org-completing-read' ignores the predicate while
15632 ;; `completing-read' handles it fine.
15633 (drawer (if arg "PROPERTIES"
15634 (or drawer
15635 (completing-read
15636 "Drawer: " org-drawers
15637 (lambda (d) (not (member d system-drawers))))))))
15638 (cond
15639 ;; With C-u, fall back on `org-insert-property-drawer'
15640 (arg (org-insert-property-drawer))
15641 ;; With an active region, insert a drawer at point.
15642 ((not (org-region-active-p))
15643 (progn
15644 (unless (bolp) (insert "\n"))
15645 (insert (format ":%s:\n\n:END:\n" drawer))
15646 (forward-line -2)))
15647 ;; Otherwise, insert the drawer at point
15649 (let ((rbeg (region-beginning))
15650 (rend (copy-marker (region-end))))
15651 (unwind-protect
15652 (progn
15653 (goto-char rbeg)
15654 (beginning-of-line)
15655 (when (save-excursion
15656 (re-search-forward org-outline-regexp-bol rend t))
15657 (user-error "Drawers cannot contain headlines"))
15658 ;; Position point at the beginning of the first
15659 ;; non-blank line in region. Insert drawer's opening
15660 ;; there, then indent it.
15661 (org-skip-whitespace)
15662 (beginning-of-line)
15663 (insert ":" drawer ":\n")
15664 (forward-line -1)
15665 (indent-for-tab-command)
15666 ;; Move point to the beginning of the first blank line
15667 ;; after the last non-blank line in region. Insert
15668 ;; drawer's closing, then indent it.
15669 (goto-char rend)
15670 (skip-chars-backward " \r\t\n")
15671 (insert "\n:END:")
15672 (deactivate-mark t)
15673 (indent-for-tab-command)
15674 (unless (eolp) (insert "\n")))
15675 ;; Clear marker, whatever the outcome of insertion is.
15676 (set-marker rend nil)))))))
15678 (defvar org-property-set-functions-alist nil
15679 "Property set function alist.
15680 Each entry should have the following format:
15682 (PROPERTY . READ-FUNCTION)
15684 The read function will be called with the same argument as
15685 `org-completing-read'.")
15687 (defun org-set-property-function (property)
15688 "Get the function that should be used to set PROPERTY.
15689 This is computed according to `org-property-set-functions-alist'."
15690 (or (cdr (assoc property org-property-set-functions-alist))
15691 'org-completing-read))
15693 (defun org-read-property-value (property)
15694 "Read PROPERTY value from user."
15695 (let* ((completion-ignore-case t)
15696 (allowed (org-property-get-allowed-values nil property 'table))
15697 (cur (org-entry-get nil property))
15698 (prompt (concat property " value"
15699 (if (and cur (string-match "\\S-" cur))
15700 (concat " [" cur "]") "") ": "))
15701 (set-function (org-set-property-function property))
15702 (val (if allowed
15703 (funcall set-function prompt allowed nil
15704 (not (get-text-property 0 'org-unrestricted
15705 (caar allowed))))
15706 (let (org-completion-use-ido org-completion-use-iswitchb)
15707 (funcall set-function prompt
15708 (mapcar 'list (org-property-values property))
15709 nil nil "" nil cur)))))
15710 (if (equal val "")
15712 val)))
15714 (defvar org-last-set-property nil)
15715 (defvar org-last-set-property-value nil)
15716 (defun org-read-property-name ()
15717 "Read a property name."
15718 (let* ((completion-ignore-case t)
15719 (keys (org-buffer-property-keys nil t t))
15720 (default-prop (or (save-excursion
15721 (save-match-data
15722 (beginning-of-line)
15723 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15724 (null (string= (match-string 1) "END"))
15725 (match-string 1))))
15726 org-last-set-property))
15727 (property (org-icompleting-read
15728 (concat "Property"
15729 (if default-prop (concat " [" default-prop "]") "")
15730 ": ")
15731 (mapcar 'list keys)
15732 nil nil nil nil
15733 default-prop)))
15734 (if (member property keys)
15735 property
15736 (or (cdr (assoc (downcase property)
15737 (mapcar (lambda (x) (cons (downcase x) x))
15738 keys)))
15739 property))))
15741 (defun org-set-property-and-value (use-last)
15742 "Allow to set [PROPERTY]: [value] direction from prompt.
15743 When use-default, don't even ask, just use the last
15744 \"[PROPERTY]: [value]\" string from the history."
15745 (interactive "P")
15746 (let* ((completion-ignore-case t)
15747 (pv (or (and use-last org-last-set-property-value)
15748 (org-completing-read
15749 "Enter a \"[Property]: [value]\" pair: "
15750 nil nil nil nil nil
15751 org-last-set-property-value)))
15752 prop val)
15753 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15754 (setq prop (match-string 1 pv)
15755 val (match-string 2 pv))
15756 (org-set-property prop val))))
15758 (defun org-set-property (property value)
15759 "In the current entry, set PROPERTY to VALUE.
15760 When called interactively, this will prompt for a property name, offering
15761 completion on existing and default properties. And then it will prompt
15762 for a value, offering completion either on allowed values (via an inherited
15763 xxx_ALL property) or on existing values in other instances of this property
15764 in the current file."
15765 (interactive (list nil nil))
15766 (let* ((property (or property (org-read-property-name)))
15767 (value (or value (org-read-property-value property)))
15768 (fn (cdr (assoc property org-properties-postprocess-alist))))
15769 (setq org-last-set-property property)
15770 (setq org-last-set-property-value (concat property ": " value))
15771 ;; Possibly postprocess the inserted value:
15772 (when fn (setq value (funcall fn value)))
15773 (unless (equal (org-entry-get nil property) value)
15774 (org-entry-put nil property value))))
15776 (defun org-delete-property (property &optional delete-empty-drawer)
15777 "In the current entry, delete PROPERTY.
15778 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15779 an empty drawer to delete."
15780 (interactive
15781 (let* ((completion-ignore-case t)
15782 (prop (org-icompleting-read "Property: "
15783 (org-entry-properties nil 'standard))))
15784 (list prop)))
15785 (message "Property %s %s" property
15786 (if (org-entry-delete nil property delete-empty-drawer)
15787 "deleted"
15788 "was not present in the entry")))
15790 (defun org-delete-property-globally (property)
15791 "Remove PROPERTY globally, from all entries."
15792 (interactive
15793 (let* ((completion-ignore-case t)
15794 (prop (org-icompleting-read
15795 "Globally remove property: "
15796 (mapcar 'list (org-buffer-property-keys)))))
15797 (list prop)))
15798 (save-excursion
15799 (save-restriction
15800 (widen)
15801 (goto-char (point-min))
15802 (let ((cnt 0))
15803 (while (re-search-forward
15804 (org-re-property property)
15805 nil t)
15806 (setq cnt (1+ cnt))
15807 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15808 (message "Property \"%s\" removed from %d entries" property cnt)))))
15810 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15812 (defun org-compute-property-at-point ()
15813 "Compute the property at point.
15814 This looks for an enclosing column format, extracts the operator and
15815 then applies it to the property in the column format's scope."
15816 (interactive)
15817 (unless (org-at-property-p)
15818 (user-error "Not at a property"))
15819 (let ((prop (org-match-string-no-properties 2)))
15820 (org-columns-get-format-and-top-level)
15821 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15822 (user-error "No operator defined for property %s" prop))
15823 (org-columns-compute prop)))
15825 (defvar org-property-allowed-value-functions nil
15826 "Hook for functions supplying allowed values for a specific property.
15827 The functions must take a single argument, the name of the property, and
15828 return a flat list of allowed values. If \":ETC\" is one of
15829 the values, this means that these values are intended as defaults for
15830 completion, but that other values should be allowed too.
15831 The functions must return nil if they are not responsible for this
15832 property.")
15834 (defun org-property-get-allowed-values (pom property &optional table)
15835 "Get allowed values for the property PROPERTY.
15836 When TABLE is non-nil, return an alist that can directly be used for
15837 completion."
15838 (let (vals)
15839 (cond
15840 ((equal property "TODO")
15841 (setq vals (org-with-point-at pom
15842 (append org-todo-keywords-1 '("")))))
15843 ((equal property "PRIORITY")
15844 (let ((n org-lowest-priority))
15845 (while (>= n org-highest-priority)
15846 (push (char-to-string n) vals)
15847 (setq n (1- n)))))
15848 ((member property org-special-properties))
15849 ((setq vals (run-hook-with-args-until-success
15850 'org-property-allowed-value-functions property)))
15852 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15853 (when (and vals (string-match "\\S-" vals))
15854 (setq vals (car (read-from-string (concat "(" vals ")"))))
15855 (setq vals (mapcar (lambda (x)
15856 (cond ((stringp x) x)
15857 ((numberp x) (number-to-string x))
15858 ((symbolp x) (symbol-name x))
15859 (t "???")))
15860 vals)))))
15861 (when (member ":ETC" vals)
15862 (setq vals (remove ":ETC" vals))
15863 (org-add-props (car vals) '(org-unrestricted t)))
15864 (if table (mapcar 'list vals) vals)))
15866 (defun org-property-previous-allowed-value (&optional previous)
15867 "Switch to the next allowed value for this property."
15868 (interactive)
15869 (org-property-next-allowed-value t))
15871 (defun org-property-next-allowed-value (&optional previous)
15872 "Switch to the next allowed value for this property."
15873 (interactive)
15874 (unless (org-at-property-p)
15875 (user-error "Not at a property"))
15876 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15877 (key (match-string 2))
15878 (value (match-string 3))
15879 (allowed (or (org-property-get-allowed-values (point) key)
15880 (and (member value '("[ ]" "[-]" "[X]"))
15881 '("[ ]" "[X]"))))
15882 (heading (save-match-data (nth 4 (org-heading-components))))
15883 nval)
15884 (unless allowed
15885 (user-error "Allowed values for this property have not been defined"))
15886 (if previous (setq allowed (reverse allowed)))
15887 (if (member value allowed)
15888 (setq nval (car (cdr (member value allowed)))))
15889 (setq nval (or nval (car allowed)))
15890 (if (equal nval value)
15891 (user-error "Only one allowed value for this property"))
15892 (org-at-property-p)
15893 (replace-match (concat " :" key ": " nval) t t)
15894 (org-indent-line)
15895 (beginning-of-line 1)
15896 (skip-chars-forward " \t")
15897 (when (equal prop org-effort-property)
15898 (save-excursion
15899 (org-back-to-heading t)
15900 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15901 (when (string= org-clock-current-task heading)
15902 (setq org-clock-effort nval)
15903 (org-clock-update-mode-line)))
15904 (run-hook-with-args 'org-property-changed-functions key nval)))
15906 (defun org-find-olp (path &optional this-buffer)
15907 "Return a marker pointing to the entry at outline path OLP.
15908 If anything goes wrong, throw an error.
15909 You can wrap this call to catch the error like this:
15911 (condition-case msg
15912 (org-mobile-locate-entry (match-string 4))
15913 (error (nth 1 msg)))
15915 The return value will then be either a string with the error message,
15916 or a marker if everything is OK.
15918 If THIS-BUFFER is set, the outline path does not contain a file,
15919 only headings."
15920 (let* ((file (if this-buffer buffer-file-name (pop path)))
15921 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15922 (level 1)
15923 (lmin 1)
15924 (lmax 1)
15925 limit re end found pos heading cnt flevel)
15926 (unless buffer (error "File not found :%s" file))
15927 (with-current-buffer buffer
15928 (save-excursion
15929 (save-restriction
15930 (widen)
15931 (setq limit (point-max))
15932 (goto-char (point-min))
15933 (while (setq heading (pop path))
15934 (setq re (format org-complex-heading-regexp-format
15935 (regexp-quote heading)))
15936 (setq cnt 0 pos (point))
15937 (while (re-search-forward re end t)
15938 (setq level (- (match-end 1) (match-beginning 1)))
15939 (if (and (>= level lmin) (<= level lmax))
15940 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15941 (when (= cnt 0) (error "Heading not found on level %d: %s"
15942 lmax heading))
15943 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15944 lmax heading))
15945 (goto-char found)
15946 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15947 (setq end (save-excursion (org-end-of-subtree t t))))
15948 (when (org-at-heading-p)
15949 (point-marker)))))))
15951 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15952 "Find node HEADING in BUFFER.
15953 Return a marker to the heading if it was found, or nil if not.
15954 If POS-ONLY is set, return just the position instead of a marker.
15956 The heading text must match exact, but it may have a TODO keyword,
15957 a priority cookie and tags in the standard locations."
15958 (with-current-buffer (or buffer (current-buffer))
15959 (save-excursion
15960 (save-restriction
15961 (widen)
15962 (goto-char (point-min))
15963 (let (case-fold-search)
15964 (if (re-search-forward
15965 (format org-complex-heading-regexp-format
15966 (regexp-quote heading)) nil t)
15967 (if pos-only
15968 (match-beginning 0)
15969 (move-marker (make-marker) (match-beginning 0)))))))))
15971 (defun org-find-exact-heading-in-directory (heading &optional dir)
15972 "Find Org node headline HEADING in all .org files in directory DIR.
15973 When the target headline is found, return a marker to this location."
15974 (let ((files (directory-files (or dir default-directory)
15975 nil "\\`[^.#].*\\.org\\'"))
15976 file visiting m buffer)
15977 (catch 'found
15978 (while (setq file (pop files))
15979 (message "trying %s" file)
15980 (setq visiting (org-find-base-buffer-visiting file))
15981 (setq buffer (or visiting (find-file-noselect file)))
15982 (setq m (org-find-exact-headline-in-buffer
15983 heading buffer))
15984 (when (and (not m) (not visiting)) (kill-buffer buffer))
15985 (and m (throw 'found m))))))
15987 (defun org-find-entry-with-id (ident)
15988 "Locate the entry that contains the ID property with exact value IDENT.
15989 IDENT can be a string, a symbol or a number, this function will search for
15990 the string representation of it.
15991 Return the position where this entry starts, or nil if there is no such entry."
15992 (interactive "sID: ")
15993 (let ((id (cond
15994 ((stringp ident) ident)
15995 ((symbol-name ident) (symbol-name ident))
15996 ((numberp ident) (number-to-string ident))
15997 (t (error "IDENT %s must be a string, symbol or number" ident))))
15998 (case-fold-search nil))
15999 (save-excursion
16000 (save-restriction
16001 (widen)
16002 (goto-char (point-min))
16003 (when (re-search-forward
16004 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16005 nil t)
16006 (org-back-to-heading t)
16007 (point))))))
16009 ;;;; Timestamps
16011 (defvar org-last-changed-timestamp nil)
16012 (defvar org-last-inserted-timestamp nil
16013 "The last time stamp inserted with `org-insert-time-stamp'.")
16014 (defvar org-ts-what) ; dynamically scoped parameter
16016 (defun org-time-stamp (arg &optional inactive)
16017 "Prompt for a date/time and insert a time stamp.
16018 If the user specifies a time like HH:MM or if this command is
16019 called with at least one prefix argument, the time stamp contains
16020 the date and the time. Otherwise, only the date is be included.
16022 All parts of a date not specified by the user is filled in from
16023 the current date/time. So if you just press return without
16024 typing anything, the time stamp will represent the current
16025 date/time.
16027 If there is already a timestamp at the cursor, it will be
16028 modified.
16030 With two universal prefix arguments, insert an active timestamp
16031 with the current time without prompting the user.
16033 When called from lisp, the timestamp is inactive if INACTIVE is
16034 non-nil."
16035 (interactive "P")
16036 (let* ((ts nil)
16037 (default-time
16038 ;; Default time is either today, or, when entering a range,
16039 ;; the range start.
16040 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16041 (save-excursion
16042 (re-search-backward
16043 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16044 (- (point) 20) t)))
16045 (apply 'encode-time (org-parse-time-string (match-string 1)))
16046 (current-time)))
16047 (default-input (and ts (org-get-compact-tod ts)))
16048 (repeater (save-excursion
16049 (save-match-data
16050 (beginning-of-line)
16051 (when (re-search-forward
16052 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16053 (save-excursion (progn (end-of-line) (point))) t)
16054 (match-string 0)))))
16055 org-time-was-given org-end-time-was-given time)
16056 (cond
16057 ((and (org-at-timestamp-p t)
16058 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16059 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16060 (insert "--")
16061 (setq time (let ((this-command this-command))
16062 (org-read-date arg 'totime nil nil
16063 default-time default-input inactive)))
16064 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16065 ((org-at-timestamp-p t)
16066 (setq time (let ((this-command this-command))
16067 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16068 (when (org-at-timestamp-p t) ; just to get the match data
16069 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16070 (replace-match "")
16071 (setq org-last-changed-timestamp
16072 (org-insert-time-stamp
16073 time (or org-time-was-given arg)
16074 inactive nil nil (list org-end-time-was-given)))
16075 (when repeater (goto-char (1- (point))) (insert " " repeater)
16076 (setq org-last-changed-timestamp
16077 (concat (substring org-last-inserted-timestamp 0 -1)
16078 " " repeater ">"))))
16079 (message "Timestamp updated"))
16080 ((equal arg '(16))
16081 (org-insert-time-stamp (current-time) t inactive))
16083 (setq time (let ((this-command this-command))
16084 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16085 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16086 nil nil (list org-end-time-was-given))))))
16088 ;; FIXME: can we use this for something else, like computing time differences?
16089 (defun org-get-compact-tod (s)
16090 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16091 (let* ((t1 (match-string 1 s))
16092 (h1 (string-to-number (match-string 2 s)))
16093 (m1 (string-to-number (match-string 3 s)))
16094 (t2 (and (match-end 4) (match-string 5 s)))
16095 (h2 (and t2 (string-to-number (match-string 6 s))))
16096 (m2 (and t2 (string-to-number (match-string 7 s))))
16097 dh dm)
16098 (if (not t2)
16100 (setq dh (- h2 h1) dm (- m2 m1))
16101 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16102 (concat t1 "+" (number-to-string dh)
16103 (and (/= 0 dm) (format ":%02d" dm)))))))
16105 (defun org-time-stamp-inactive (&optional arg)
16106 "Insert an inactive time stamp.
16107 An inactive time stamp is enclosed in square brackets instead of angle
16108 brackets. It is inactive in the sense that it does not trigger agenda entries,
16109 does not link to the calendar and cannot be changed with the S-cursor keys.
16110 So these are more for recording a certain time/date."
16111 (interactive "P")
16112 (org-time-stamp arg 'inactive))
16114 (defvar org-date-ovl (make-overlay 1 1))
16115 (overlay-put org-date-ovl 'face 'org-date-selected)
16116 (org-detach-overlay org-date-ovl)
16118 (defvar org-ans1) ; dynamically scoped parameter
16119 (defvar org-ans2) ; dynamically scoped parameter
16121 (defvar org-plain-time-of-day-regexp) ; defined below
16123 (defvar org-overriding-default-time nil) ; dynamically scoped
16124 (defvar org-read-date-overlay nil)
16125 (defvar org-dcst nil) ; dynamically scoped
16126 (defvar org-read-date-history nil)
16127 (defvar org-read-date-final-answer nil)
16128 (defvar org-read-date-analyze-futurep nil)
16129 (defvar org-read-date-analyze-forced-year nil)
16130 (defvar org-read-date-inactive)
16132 (defvar org-read-date-minibuffer-local-map
16133 (let* ((org-replace-disputed-keys nil)
16134 (map (make-sparse-keymap)))
16135 (set-keymap-parent map minibuffer-local-map)
16136 (org-defkey map (kbd ".")
16137 (lambda () (interactive)
16138 ;; Are we at the beginning of the prompt?
16139 (if (looking-back "^[^:]+: ")
16140 (org-eval-in-calendar '(calendar-goto-today))
16141 (insert "."))))
16142 (org-defkey map (kbd "C-.")
16143 (lambda () (interactive)
16144 (org-eval-in-calendar '(calendar-goto-today))))
16145 (org-defkey map [(meta shift left)]
16146 (lambda () (interactive)
16147 (org-eval-in-calendar '(calendar-backward-month 1))))
16148 (org-defkey map [(meta shift right)]
16149 (lambda () (interactive)
16150 (org-eval-in-calendar '(calendar-forward-month 1))))
16151 (org-defkey map [(meta shift up)]
16152 (lambda () (interactive)
16153 (org-eval-in-calendar '(calendar-backward-year 1))))
16154 (org-defkey map [(meta shift down)]
16155 (lambda () (interactive)
16156 (org-eval-in-calendar '(calendar-forward-year 1))))
16157 (org-defkey map [?\e (shift left)]
16158 (lambda () (interactive)
16159 (org-eval-in-calendar '(calendar-backward-month 1))))
16160 (org-defkey map [?\e (shift right)]
16161 (lambda () (interactive)
16162 (org-eval-in-calendar '(calendar-forward-month 1))))
16163 (org-defkey map [?\e (shift up)]
16164 (lambda () (interactive)
16165 (org-eval-in-calendar '(calendar-backward-year 1))))
16166 (org-defkey map [?\e (shift down)]
16167 (lambda () (interactive)
16168 (org-eval-in-calendar '(calendar-forward-year 1))))
16169 (org-defkey map [(shift up)]
16170 (lambda () (interactive)
16171 (org-eval-in-calendar '(calendar-backward-week 1))))
16172 (org-defkey map [(shift down)]
16173 (lambda () (interactive)
16174 (org-eval-in-calendar '(calendar-forward-week 1))))
16175 (org-defkey map [(shift left)]
16176 (lambda () (interactive)
16177 (org-eval-in-calendar '(calendar-backward-day 1))))
16178 (org-defkey map [(shift right)]
16179 (lambda () (interactive)
16180 (org-eval-in-calendar '(calendar-forward-day 1))))
16181 (org-defkey map "!"
16182 (lambda () (interactive)
16183 (org-eval-in-calendar '(diary-view-entries))
16184 (message "")))
16185 (org-defkey map ">"
16186 (lambda () (interactive)
16187 (org-eval-in-calendar '(scroll-calendar-left 1))))
16188 (org-defkey map "<"
16189 (lambda () (interactive)
16190 (org-eval-in-calendar '(scroll-calendar-right 1))))
16191 (org-defkey map "\C-v"
16192 (lambda () (interactive)
16193 (org-eval-in-calendar
16194 '(calendar-scroll-left-three-months 1))))
16195 (org-defkey map "\M-v"
16196 (lambda () (interactive)
16197 (org-eval-in-calendar
16198 '(calendar-scroll-right-three-months 1))))
16199 map)
16200 "Keymap for minibuffer commands when using `org-read-date'.")
16202 (defvar org-def)
16203 (defvar org-defdecode)
16204 (defvar org-with-time)
16206 (defun org-read-date (&optional org-with-time to-time from-string prompt
16207 default-time default-input inactive)
16208 "Read a date, possibly a time, and make things smooth for the user.
16209 The prompt will suggest to enter an ISO date, but you can also enter anything
16210 which will at least partially be understood by `parse-time-string'.
16211 Unrecognized parts of the date will default to the current day, month, year,
16212 hour and minute. If this command is called to replace a timestamp at point,
16213 or to enter the second timestamp of a range, the default time is taken
16214 from the existing stamp. Furthermore, the command prefers the future,
16215 so if you are giving a date where the year is not given, and the day-month
16216 combination is already past in the current year, it will assume you
16217 mean next year. For details, see the manual. A few examples:
16219 3-2-5 --> 2003-02-05
16220 feb 15 --> currentyear-02-15
16221 2/15 --> currentyear-02-15
16222 sep 12 9 --> 2009-09-12
16223 12:45 --> today 12:45
16224 22 sept 0:34 --> currentyear-09-22 0:34
16225 12 --> currentyear-currentmonth-12
16226 Fri --> nearest Friday after today
16227 -Tue --> last Tuesday
16228 etc.
16230 Furthermore you can specify a relative date by giving, as the *first* thing
16231 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16232 change in days weeks, months, years.
16233 With a single plus or minus, the date is relative to today. With a double
16234 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16235 +4d --> four days from today
16236 +4 --> same as above
16237 +2w --> two weeks from today
16238 ++5 --> five days from default date
16240 The function understands only English month and weekday abbreviations.
16242 While prompting, a calendar is popped up - you can also select the
16243 date with the mouse (button 1). The calendar shows a period of three
16244 months. To scroll it to other months, use the keys `>' and `<'.
16245 If you don't like the calendar, turn it off with
16246 \(setq org-read-date-popup-calendar nil)
16248 With optional argument TO-TIME, the date will immediately be converted
16249 to an internal time.
16250 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16251 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16252 still enter a time, and this function will inform the calling routine
16253 about this change. The calling routine may then choose to change the
16254 format used to insert the time stamp into the buffer to include the time.
16255 With optional argument FROM-STRING, read from this string instead from
16256 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16257 the time/date that is used for everything that is not specified by the
16258 user."
16259 (require 'parse-time)
16260 (let* ((org-time-stamp-rounding-minutes
16261 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16262 (org-dcst org-display-custom-times)
16263 (ct (org-current-time))
16264 (org-def (or org-overriding-default-time default-time ct))
16265 (org-defdecode (decode-time org-def))
16266 (dummy (progn
16267 (when (< (nth 2 org-defdecode) org-extend-today-until)
16268 (setcar (nthcdr 2 org-defdecode) -1)
16269 (setcar (nthcdr 1 org-defdecode) 59)
16270 (setq org-def (apply 'encode-time org-defdecode)
16271 org-defdecode (decode-time org-def)))))
16272 (mouse-autoselect-window nil) ; Don't let the mouse jump
16273 (calendar-frame-setup nil)
16274 (calendar-setup nil)
16275 (calendar-move-hook nil)
16276 (calendar-view-diary-initially-flag nil)
16277 (calendar-view-holidays-initially-flag nil)
16278 (timestr (format-time-string
16279 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16280 (prompt (concat (if prompt (concat prompt " ") "")
16281 (format "Date+time [%s]: " timestr)))
16282 ans (org-ans0 "") org-ans1 org-ans2 final)
16284 (cond
16285 (from-string (setq ans from-string))
16286 (org-read-date-popup-calendar
16287 (save-excursion
16288 (save-window-excursion
16289 (calendar)
16290 (org-eval-in-calendar '(setq cursor-type nil) t)
16291 (unwind-protect
16292 (progn
16293 (calendar-forward-day (- (time-to-days org-def)
16294 (calendar-absolute-from-gregorian
16295 (calendar-current-date))))
16296 (org-eval-in-calendar nil t)
16297 (let* ((old-map (current-local-map))
16298 (map (copy-keymap calendar-mode-map))
16299 (minibuffer-local-map
16300 (copy-keymap org-read-date-minibuffer-local-map)))
16301 (org-defkey map (kbd "RET") 'org-calendar-select)
16302 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16303 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16304 (unwind-protect
16305 (progn
16306 (use-local-map map)
16307 (setq org-read-date-inactive inactive)
16308 (add-hook 'post-command-hook 'org-read-date-display)
16309 (setq org-ans0 (read-string prompt default-input
16310 'org-read-date-history nil))
16311 ;; org-ans0: from prompt
16312 ;; org-ans1: from mouse click
16313 ;; org-ans2: from calendar motion
16314 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16315 (remove-hook 'post-command-hook 'org-read-date-display)
16316 (use-local-map old-map)
16317 (when org-read-date-overlay
16318 (delete-overlay org-read-date-overlay)
16319 (setq org-read-date-overlay nil)))))
16320 (bury-buffer "*Calendar*")))))
16322 (t ; Naked prompt only
16323 (unwind-protect
16324 (setq ans (read-string prompt default-input
16325 'org-read-date-history timestr))
16326 (when org-read-date-overlay
16327 (delete-overlay org-read-date-overlay)
16328 (setq org-read-date-overlay nil)))))
16330 (setq final (org-read-date-analyze ans org-def org-defdecode))
16332 (when org-read-date-analyze-forced-year
16333 (message "Year was forced into %s"
16334 (if org-read-date-force-compatible-dates
16335 "compatible range (1970-2037)"
16336 "range representable on this machine"))
16337 (ding))
16339 ;; One round trip to get rid of 34th of August and stuff like that....
16340 (setq final (decode-time (apply 'encode-time final)))
16342 (setq org-read-date-final-answer ans)
16344 (if to-time
16345 (apply 'encode-time final)
16346 (if (and (boundp 'org-time-was-given) org-time-was-given)
16347 (format "%04d-%02d-%02d %02d:%02d"
16348 (nth 5 final) (nth 4 final) (nth 3 final)
16349 (nth 2 final) (nth 1 final))
16350 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16352 (defun org-read-date-display ()
16353 "Display the current date prompt interpretation in the minibuffer."
16354 (when org-read-date-display-live
16355 (when org-read-date-overlay
16356 (delete-overlay org-read-date-overlay))
16357 (when (minibufferp (current-buffer))
16358 (save-excursion
16359 (end-of-line 1)
16360 (while (not (equal (buffer-substring
16361 (max (point-min) (- (point) 4)) (point))
16362 " "))
16363 (insert " ")))
16364 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16365 " " (or org-ans1 org-ans2)))
16366 (org-end-time-was-given nil)
16367 (f (org-read-date-analyze ans org-def org-defdecode))
16368 (fmts (if org-dcst
16369 org-time-stamp-custom-formats
16370 org-time-stamp-formats))
16371 (fmt (if (or org-with-time
16372 (and (boundp 'org-time-was-given) org-time-was-given))
16373 (cdr fmts)
16374 (car fmts)))
16375 (txt (format-time-string fmt (apply 'encode-time f)))
16376 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16377 (txt (concat "=> " txt)))
16378 (when (and org-end-time-was-given
16379 (string-match org-plain-time-of-day-regexp txt))
16380 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16381 org-end-time-was-given
16382 (substring txt (match-end 0)))))
16383 (when org-read-date-analyze-futurep
16384 (setq txt (concat txt " (=>F)")))
16385 (setq org-read-date-overlay
16386 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16387 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16389 (defun org-read-date-analyze (ans org-def org-defdecode)
16390 "Analyze the combined answer of the date prompt."
16391 ;; FIXME: cleanup and comment
16392 (let ((nowdecode (decode-time (current-time)))
16393 delta deltan deltaw deltadef year month day
16394 hour minute second wday pm h2 m2 tl wday1
16395 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16396 (setq org-read-date-analyze-futurep nil
16397 org-read-date-analyze-forced-year nil)
16398 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16399 (setq ans "+0"))
16401 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16402 (setq ans (replace-match "" t t ans)
16403 deltan (car delta)
16404 deltaw (nth 1 delta)
16405 deltadef (nth 2 delta)))
16407 ;; Check if there is an iso week date in there. If yes, store the
16408 ;; info and postpone interpreting it until the rest of the parsing
16409 ;; is done.
16410 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16411 (setq iso-year (if (match-end 1)
16412 (org-small-year-to-year
16413 (string-to-number (match-string 1 ans))))
16414 iso-weekday (if (match-end 3)
16415 (string-to-number (match-string 3 ans)))
16416 iso-week (string-to-number (match-string 2 ans)))
16417 (setq ans (replace-match "" t t ans)))
16419 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16420 (when (string-match
16421 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16422 (setq year (if (match-end 2)
16423 (string-to-number (match-string 2 ans))
16424 (progn (setq kill-year t)
16425 (string-to-number (format-time-string "%Y"))))
16426 month (string-to-number (match-string 3 ans))
16427 day (string-to-number (match-string 4 ans)))
16428 (if (< year 100) (setq year (+ 2000 year)))
16429 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16430 t nil ans)))
16432 ;; Help matching dotted european dates
16433 (when (string-match
16434 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16435 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16436 (setq kill-year t)
16437 (string-to-number (format-time-string "%Y")))
16438 day (string-to-number (match-string 1 ans))
16439 month (string-to-number (match-string 2 ans))
16440 ans (replace-match (format "%04d-%02d-%02d" year month day)
16441 t nil ans)))
16443 ;; Help matching american dates, like 5/30 or 5/30/7
16444 (when (string-match
16445 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16446 (setq year (if (match-end 4)
16447 (string-to-number (match-string 4 ans))
16448 (progn (setq kill-year t)
16449 (string-to-number (format-time-string "%Y"))))
16450 month (string-to-number (match-string 1 ans))
16451 day (string-to-number (match-string 2 ans)))
16452 (if (< year 100) (setq year (+ 2000 year)))
16453 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16454 t nil ans)))
16455 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16456 ;; If there is a time with am/pm, and *no* time without it, we convert
16457 ;; so that matching will be successful.
16458 (loop for i from 1 to 2 do ; twice, for end time as well
16459 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16460 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16461 (setq hour (string-to-number (match-string 1 ans))
16462 minute (if (match-end 3)
16463 (string-to-number (match-string 3 ans))
16465 pm (equal ?p
16466 (string-to-char (downcase (match-string 4 ans)))))
16467 (if (and (= hour 12) (not pm))
16468 (setq hour 0)
16469 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16470 (setq ans (replace-match (format "%02d:%02d" hour minute)
16471 t t ans))))
16473 ;; Check if a time range is given as a duration
16474 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16475 (setq hour (string-to-number (match-string 1 ans))
16476 h2 (+ hour (string-to-number (match-string 3 ans)))
16477 minute (string-to-number (match-string 2 ans))
16478 m2 (+ minute (if (match-end 5) (string-to-number
16479 (match-string 5 ans))0)))
16480 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16481 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16482 t t ans)))
16484 ;; Check if there is a time range
16485 (when (boundp 'org-end-time-was-given)
16486 (setq org-time-was-given nil)
16487 (when (and (string-match org-plain-time-of-day-regexp ans)
16488 (match-end 8))
16489 (setq org-end-time-was-given (match-string 8 ans))
16490 (setq ans (concat (substring ans 0 (match-beginning 7))
16491 (substring ans (match-end 7))))))
16493 (setq tl (parse-time-string ans)
16494 day (or (nth 3 tl) (nth 3 org-defdecode))
16495 month (or (nth 4 tl)
16496 (if (and org-read-date-prefer-future
16497 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16498 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16499 (nth 4 org-defdecode)))
16500 year (or (and (not kill-year) (nth 5 tl))
16501 (if (and org-read-date-prefer-future
16502 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16503 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16504 (nth 5 org-defdecode)))
16505 hour (or (nth 2 tl) (nth 2 org-defdecode))
16506 minute (or (nth 1 tl) (nth 1 org-defdecode))
16507 second (or (nth 0 tl) 0)
16508 wday (nth 6 tl))
16510 (when (and (eq org-read-date-prefer-future 'time)
16511 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16512 (equal day (nth 3 nowdecode))
16513 (equal month (nth 4 nowdecode))
16514 (equal year (nth 5 nowdecode))
16515 (nth 2 tl)
16516 (or (< (nth 2 tl) (nth 2 nowdecode))
16517 (and (= (nth 2 tl) (nth 2 nowdecode))
16518 (nth 1 tl)
16519 (< (nth 1 tl) (nth 1 nowdecode)))))
16520 (setq day (1+ day)
16521 futurep t))
16523 ;; Special date definitions below
16524 (cond
16525 (iso-week
16526 ;; There was an iso week
16527 (require 'cal-iso)
16528 (setq futurep nil)
16529 (setq year (or iso-year year)
16530 day (or iso-weekday wday 1)
16531 wday nil ; to make sure that the trigger below does not match
16532 iso-date (calendar-gregorian-from-absolute
16533 (calendar-absolute-from-iso
16534 (list iso-week day year))))
16535 ; FIXME: Should we also push ISO weeks into the future?
16536 ; (when (and org-read-date-prefer-future
16537 ; (not iso-year)
16538 ; (< (calendar-absolute-from-gregorian iso-date)
16539 ; (time-to-days (current-time))))
16540 ; (setq year (1+ year)
16541 ; iso-date (calendar-gregorian-from-absolute
16542 ; (calendar-absolute-from-iso
16543 ; (list iso-week day year)))))
16544 (setq month (car iso-date)
16545 year (nth 2 iso-date)
16546 day (nth 1 iso-date)))
16547 (deltan
16548 (setq futurep nil)
16549 (unless deltadef
16550 (let ((now (decode-time (current-time))))
16551 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16552 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16553 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16554 ((equal deltaw "m") (setq month (+ month deltan)))
16555 ((equal deltaw "y") (setq year (+ year deltan)))))
16556 ((and wday (not (nth 3 tl)))
16557 ;; Weekday was given, but no day, so pick that day in the week
16558 ;; on or after the derived date.
16559 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16560 (unless (equal wday wday1)
16561 (setq day (+ day (% (- wday wday1 -7) 7))))))
16562 (if (and (boundp 'org-time-was-given)
16563 (nth 2 tl))
16564 (setq org-time-was-given t))
16565 (if (< year 100) (setq year (+ 2000 year)))
16566 ;; Check of the date is representable
16567 (if org-read-date-force-compatible-dates
16568 (progn
16569 (if (< year 1970)
16570 (setq year 1970 org-read-date-analyze-forced-year t))
16571 (if (> year 2037)
16572 (setq year 2037 org-read-date-analyze-forced-year t)))
16573 (condition-case nil
16574 (ignore (encode-time second minute hour day month year))
16575 (error
16576 (setq year (nth 5 org-defdecode))
16577 (setq org-read-date-analyze-forced-year t))))
16578 (setq org-read-date-analyze-futurep futurep)
16579 (list second minute hour day month year)))
16581 (defvar parse-time-weekdays)
16582 (defun org-read-date-get-relative (s today default)
16583 "Check string S for special relative date string.
16584 TODAY and DEFAULT are internal times, for today and for a default.
16585 Return shift list (N what def-flag)
16586 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16587 N is the number of WHATs to shift.
16588 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16589 the DEFAULT date rather than TODAY."
16590 (require 'parse-time)
16591 (when (and
16592 (string-match
16593 (concat
16594 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16595 "\\([0-9]+\\)?"
16596 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16597 "\\([ \t]\\|$\\)") s)
16598 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16599 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16600 (string-to-char (substring (match-string 1 s) -1))
16601 ?+))
16602 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16603 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16604 (what (if (match-end 3) (match-string 3 s) "d"))
16605 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16606 (date (if rel default today))
16607 (wday (nth 6 (decode-time date)))
16608 delta)
16609 (if wday1
16610 (progn
16611 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16612 (if (= delta 0) (setq delta 7))
16613 (if (= dir ?-)
16614 (progn
16615 (setq delta (- delta 7))
16616 (if (= delta 0) (setq delta -7))))
16617 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16618 (list delta "d" rel))
16619 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16621 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16622 "Turn a user-specified date into the internal representation.
16623 The internal representation needed by the calendar is (month day year).
16624 This is a wrapper to handle the brain-dead convention in calendar that
16625 user function argument order change dependent on argument order."
16626 (if (boundp 'calendar-date-style)
16627 (cond
16628 ((eq calendar-date-style 'american)
16629 (list arg1 arg2 arg3))
16630 ((eq calendar-date-style 'european)
16631 (list arg2 arg1 arg3))
16632 ((eq calendar-date-style 'iso)
16633 (list arg2 arg3 arg1)))
16634 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16635 (if (org-bound-and-true-p european-calendar-style)
16636 (list arg2 arg1 arg3)
16637 (list arg1 arg2 arg3)))))
16639 (defun org-eval-in-calendar (form &optional keepdate)
16640 "Eval FORM in the calendar window and return to current window.
16641 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16642 otherwise stick to the current value of `org-ans2'."
16643 (let ((sf (selected-frame))
16644 (sw (selected-window)))
16645 (select-window (get-buffer-window "*Calendar*" t))
16646 (eval form)
16647 (when (and (not keepdate) (calendar-cursor-to-date))
16648 (let* ((date (calendar-cursor-to-date))
16649 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16650 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16651 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16652 (select-window sw)
16653 (org-select-frame-set-input-focus sf)))
16655 (defun org-calendar-select ()
16656 "Return to `org-read-date' with the date currently selected.
16657 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16658 (interactive)
16659 (when (calendar-cursor-to-date)
16660 (let* ((date (calendar-cursor-to-date))
16661 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16662 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16663 (if (active-minibuffer-window) (exit-minibuffer))))
16665 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16666 "Insert a date stamp for the date given by the internal TIME.
16667 WITH-HM means use the stamp format that includes the time of the day.
16668 INACTIVE means use square brackets instead of angular ones, so that the
16669 stamp will not contribute to the agenda.
16670 PRE and POST are optional strings to be inserted before and after the
16671 stamp.
16672 The command returns the inserted time stamp."
16673 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16674 stamp)
16675 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16676 (insert-before-markers (or pre ""))
16677 (when (listp extra)
16678 (setq extra (car extra))
16679 (if (and (stringp extra)
16680 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16681 (setq extra (format "-%02d:%02d"
16682 (string-to-number (match-string 1 extra))
16683 (string-to-number (match-string 2 extra))))
16684 (setq extra nil)))
16685 (when extra
16686 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16687 (insert-before-markers (setq stamp (format-time-string fmt time)))
16688 (insert-before-markers (or post ""))
16689 (setq org-last-inserted-timestamp stamp)))
16691 (defun org-toggle-time-stamp-overlays ()
16692 "Toggle the use of custom time stamp formats."
16693 (interactive)
16694 (setq org-display-custom-times (not org-display-custom-times))
16695 (unless org-display-custom-times
16696 (let ((p (point-min)) (bmp (buffer-modified-p)))
16697 (while (setq p (next-single-property-change p 'display))
16698 (if (and (get-text-property p 'display)
16699 (eq (get-text-property p 'face) 'org-date))
16700 (remove-text-properties
16701 p (setq p (next-single-property-change p 'display))
16702 '(display t))))
16703 (set-buffer-modified-p bmp)))
16704 (if (featurep 'xemacs)
16705 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16706 (org-restart-font-lock)
16707 (setq org-table-may-need-update t)
16708 (if org-display-custom-times
16709 (message "Time stamps are overlaid with custom format")
16710 (message "Time stamp overlays removed")))
16712 (defun org-display-custom-time (beg end)
16713 "Overlay modified time stamp format over timestamp between BEG and END."
16714 (let* ((ts (buffer-substring beg end))
16715 t1 w1 with-hm tf time str w2 (off 0))
16716 (save-match-data
16717 (setq t1 (org-parse-time-string ts t))
16718 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16719 (setq off (- (match-end 0) (match-beginning 0)))))
16720 (setq end (- end off))
16721 (setq w1 (- end beg)
16722 with-hm (and (nth 1 t1) (nth 2 t1))
16723 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16724 time (org-fix-decoded-time t1)
16725 str (org-add-props
16726 (format-time-string
16727 (substring tf 1 -1) (apply 'encode-time time))
16728 nil 'mouse-face 'highlight)
16729 w2 (length str))
16730 (if (not (= w2 w1))
16731 (add-text-properties (1+ beg) (+ 2 beg)
16732 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16733 (if (featurep 'xemacs)
16734 (progn
16735 (put-text-property beg end 'invisible t)
16736 (put-text-property beg end 'end-glyph (make-glyph str)))
16737 (put-text-property beg end 'display str))))
16739 (defun org-translate-time (string)
16740 "Translate all timestamps in STRING to custom format.
16741 But do this only if the variable `org-display-custom-times' is set."
16742 (when org-display-custom-times
16743 (save-match-data
16744 (let* ((start 0)
16745 (re org-ts-regexp-both)
16746 t1 with-hm inactive tf time str beg end)
16747 (while (setq start (string-match re string start))
16748 (setq beg (match-beginning 0)
16749 end (match-end 0)
16750 t1 (save-match-data
16751 (org-parse-time-string (substring string beg end) t))
16752 with-hm (and (nth 1 t1) (nth 2 t1))
16753 inactive (equal (substring string beg (1+ beg)) "[")
16754 tf (funcall (if with-hm 'cdr 'car)
16755 org-time-stamp-custom-formats)
16756 time (org-fix-decoded-time t1)
16757 str (format-time-string
16758 (concat
16759 (if inactive "[" "<") (substring tf 1 -1)
16760 (if inactive "]" ">"))
16761 (apply 'encode-time time))
16762 string (replace-match str t t string)
16763 start (+ start (length str)))))))
16764 string)
16766 (defun org-fix-decoded-time (time)
16767 "Set 0 instead of nil for the first 6 elements of time.
16768 Don't touch the rest."
16769 (let ((n 0))
16770 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16772 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16774 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16775 "Difference between TIMESTAMP-STRING and now in days.
16776 If SECONDS is non-nil, return the difference in seconds."
16777 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16778 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16779 (funcall fdiff (current-time)))))
16781 (defun org-deadline-close (timestamp-string &optional ndays)
16782 "Is the time in TIMESTAMP-STRING close to the current date?"
16783 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16784 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16785 (not (org-entry-is-done-p))))
16787 (defun org-get-wdays (ts &optional delay zero-delay)
16788 "Get the deadline lead time appropriate for timestring TS.
16789 When DELAY is non-nil, get the delay time for scheduled items
16790 instead of the deadline lead time. When ZERO-DELAY is non-nil
16791 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16792 don't try to find the delay cookie in the scheduled timestamp."
16793 (let ((tv (if delay org-scheduled-delay-days
16794 org-deadline-warning-days)))
16795 (cond
16796 ((or (and delay (< tv 0))
16797 (and delay zero-delay (<= tv 0))
16798 (and (not delay) (<= tv 0)))
16799 ;; Enforce this value no matter what
16800 (- tv))
16801 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16802 ;; lead time is specified.
16803 (floor (* (string-to-number (match-string 1 ts))
16804 (cdr (assoc (match-string 2 ts)
16805 '(("d" . 1) ("w" . 7)
16806 ("m" . 30.4) ("y" . 365.25)
16807 ("h" . 0.041667)))))))
16808 ;; go for the default.
16809 (t tv))))
16811 (defun org-calendar-select-mouse (ev)
16812 "Return to `org-read-date' with the date currently selected.
16813 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16814 (interactive "e")
16815 (mouse-set-point ev)
16816 (when (calendar-cursor-to-date)
16817 (let* ((date (calendar-cursor-to-date))
16818 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16819 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16820 (if (active-minibuffer-window) (exit-minibuffer))))
16822 (defun org-check-deadlines (ndays)
16823 "Check if there are any deadlines due or past due.
16824 A deadline is considered due if it happens within `org-deadline-warning-days'
16825 days from today's date. If the deadline appears in an entry marked DONE,
16826 it is not shown. The prefix arg NDAYS can be used to test that many
16827 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16828 (interactive "P")
16829 (let* ((org-warn-days
16830 (cond
16831 ((equal ndays '(4)) 100000)
16832 (ndays (prefix-numeric-value ndays))
16833 (t (abs org-deadline-warning-days))))
16834 (case-fold-search nil)
16835 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16836 (callback
16837 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16839 (message "%d deadlines past-due or due within %d days"
16840 (org-occur regexp nil callback)
16841 org-warn-days)))
16843 (defsubst org-re-timestamp (type)
16844 "Return a regexp for timestamp TYPE.
16845 Allowed values for TYPE are:
16847 all: all timestamps
16848 active: only active timestamps (<...>)
16849 inactive: only inactive timestamps ([...])
16850 scheduled: only scheduled timestamps
16851 deadline: only deadline timestamps
16852 closed: only closed time-stamps
16854 When TYPE is nil, fall back on returning a regexp that matches
16855 both scheduled and deadline timestamps."
16856 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16857 ((eq type 'active) org-ts-regexp)
16858 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16859 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16860 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16861 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16862 ((eq type 'scheduled-or-deadline)
16863 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16865 (defun org-check-before-date (date)
16866 "Check if there are deadlines or scheduled entries before DATE."
16867 (interactive (list (org-read-date)))
16868 (let ((case-fold-search nil)
16869 (regexp (org-re-timestamp org-ts-type))
16870 (callback
16871 (lambda () (time-less-p
16872 (org-time-string-to-time (match-string 1))
16873 (org-time-string-to-time date)))))
16874 (message "%d entries before %s"
16875 (org-occur regexp nil callback) date)))
16877 (defun org-check-after-date (date)
16878 "Check if there are deadlines or scheduled entries after DATE."
16879 (interactive (list (org-read-date)))
16880 (let ((case-fold-search nil)
16881 (regexp (org-re-timestamp org-ts-type))
16882 (callback
16883 (lambda () (not
16884 (time-less-p
16885 (org-time-string-to-time (match-string 1))
16886 (org-time-string-to-time date))))))
16887 (message "%d entries after %s"
16888 (org-occur regexp nil callback) date)))
16890 (defun org-check-dates-range (start-date end-date)
16891 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16892 (interactive (list (org-read-date nil nil nil "Range starts")
16893 (org-read-date nil nil nil "Range end")))
16894 (let ((case-fold-search nil)
16895 (regexp (org-re-timestamp org-ts-type))
16896 (callback
16897 (lambda ()
16898 (let ((match (match-string 1)))
16899 (and
16900 (not (time-less-p
16901 (org-time-string-to-time match)
16902 (org-time-string-to-time start-date)))
16903 (time-less-p
16904 (org-time-string-to-time match)
16905 (org-time-string-to-time end-date)))))))
16906 (message "%d entries between %s and %s"
16907 (org-occur regexp nil callback) start-date end-date)))
16909 (defun org-evaluate-time-range (&optional to-buffer)
16910 "Evaluate a time range by computing the difference between start and end.
16911 Normally the result is just printed in the echo area, but with prefix arg
16912 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16913 If the time range is actually in a table, the result is inserted into the
16914 next column.
16915 For time difference computation, a year is assumed to be exactly 365
16916 days in order to avoid rounding problems."
16917 (interactive "P")
16919 (org-clock-update-time-maybe)
16920 (save-excursion
16921 (unless (org-at-date-range-p t)
16922 (goto-char (point-at-bol))
16923 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16924 (if (not (org-at-date-range-p t))
16925 (user-error "Not at a time-stamp range, and none found in current line")))
16926 (let* ((ts1 (match-string 1))
16927 (ts2 (match-string 2))
16928 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16929 (match-end (match-end 0))
16930 (time1 (org-time-string-to-time ts1))
16931 (time2 (org-time-string-to-time ts2))
16932 (t1 (org-float-time time1))
16933 (t2 (org-float-time time2))
16934 (diff (abs (- t2 t1)))
16935 (negative (< (- t2 t1) 0))
16936 ;; (ys (floor (* 365 24 60 60)))
16937 (ds (* 24 60 60))
16938 (hs (* 60 60))
16939 (fy "%dy %dd %02d:%02d")
16940 (fy1 "%dy %dd")
16941 (fd "%dd %02d:%02d")
16942 (fd1 "%dd")
16943 (fh "%02d:%02d")
16944 y d h m align)
16945 (if havetime
16946 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16948 d (floor (/ diff ds)) diff (mod diff ds)
16949 h (floor (/ diff hs)) diff (mod diff hs)
16950 m (floor (/ diff 60)))
16951 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16953 d (floor (+ (/ diff ds) 0.5))
16954 h 0 m 0))
16955 (if (not to-buffer)
16956 (message "%s" (org-make-tdiff-string y d h m))
16957 (if (org-at-table-p)
16958 (progn
16959 (goto-char match-end)
16960 (setq align t)
16961 (and (looking-at " *|") (goto-char (match-end 0))))
16962 (goto-char match-end))
16963 (if (looking-at
16964 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16965 (replace-match ""))
16966 (if negative (insert " -"))
16967 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16968 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16969 (insert " " (format fh h m))))
16970 (if align (org-table-align))
16971 (message "Time difference inserted")))))
16973 (defun org-make-tdiff-string (y d h m)
16974 (let ((fmt "")
16975 (l nil))
16976 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16977 l (push y l)))
16978 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16979 l (push d l)))
16980 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16981 l (push h l)))
16982 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16983 l (push m l)))
16984 (apply 'format fmt (nreverse l))))
16986 (defun org-time-string-to-time (s &optional buffer pos)
16987 "Convert a timestamp string into internal time."
16988 (condition-case errdata
16989 (apply 'encode-time (org-parse-time-string s))
16990 (error (error "Bad timestamp `%s'%s\nError was: %s"
16991 s (if (not (and buffer pos))
16993 (format " at %d in buffer `%s'" pos buffer))
16994 (cdr errdata)))))
16996 (defun org-time-string-to-seconds (s)
16997 "Convert a timestamp string to a number of seconds."
16998 (org-float-time (org-time-string-to-time s)))
17000 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17001 "Convert a time stamp to an absolute day number.
17002 If there is a specifier for a cyclic time stamp, get the closest
17003 date to DAYNR.
17004 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17005 The variable `date' is bound by the calendar when this is called."
17006 (cond
17007 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17008 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17009 daynr
17010 (+ daynr 1000)))
17011 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17012 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17013 (time-to-days (current-time))) (match-string 0 s)
17014 prefer show-all))
17015 (t (time-to-days
17016 (condition-case errdata
17017 (apply 'encode-time (org-parse-time-string s))
17018 (error (error "Bad timestamp `%s'%s\nError was: %s"
17019 s (if (not (and buffer pos))
17021 (format " at %d in buffer `%s'" pos buffer))
17022 (cdr errdata))))))))
17024 (defun org-days-to-iso-week (days)
17025 "Return the iso week number."
17026 (require 'cal-iso)
17027 (car (calendar-iso-from-absolute days)))
17029 (defun org-small-year-to-year (year)
17030 "Convert 2-digit years into 4-digit years.
17031 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17032 The year 2000 cannot be abbreviated. Any year larger than 99
17033 is returned unchanged."
17034 (if (< year 38)
17035 (setq year (+ 2000 year))
17036 (if (< year 100)
17037 (setq year (+ 1900 year))))
17038 year)
17040 (defun org-time-from-absolute (d)
17041 "Return the time corresponding to date D.
17042 D may be an absolute day number, or a calendar-type list (month day year)."
17043 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17044 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17046 (defun org-calendar-holiday ()
17047 "List of holidays, for Diary display in Org-mode."
17048 (require 'holidays)
17049 (let ((hl (funcall
17050 (if (fboundp 'calendar-check-holidays)
17051 'calendar-check-holidays 'check-calendar-holidays) date)))
17052 (if hl (mapconcat 'identity hl "; "))))
17054 (defun org-diary-sexp-entry (sexp entry date)
17055 "Process a SEXP diary ENTRY for DATE."
17056 (require 'diary-lib)
17057 (let ((result (if calendar-debug-sexp
17058 (let ((stack-trace-on-error t))
17059 (eval (car (read-from-string sexp))))
17060 (condition-case nil
17061 (eval (car (read-from-string sexp)))
17062 (error
17063 (beep)
17064 (message "Bad sexp at line %d in %s: %s"
17065 (org-current-line)
17066 (buffer-file-name) sexp)
17067 (sleep-for 2))))))
17068 (cond ((stringp result) (split-string result "; "))
17069 ((and (consp result)
17070 (not (consp (cdr result)))
17071 (stringp (cdr result))) (cdr result))
17072 ((and (consp result)
17073 (stringp (car result))) result)
17074 (result entry))))
17076 (defun org-diary-to-ical-string (frombuf)
17077 "Get iCalendar entries from diary entries in buffer FROMBUF.
17078 This uses the icalendar.el library."
17079 (let* ((tmpdir (if (featurep 'xemacs)
17080 (temp-directory)
17081 temporary-file-directory))
17082 (tmpfile (make-temp-name
17083 (expand-file-name "orgics" tmpdir)))
17084 buf rtn b e)
17085 (with-current-buffer frombuf
17086 (icalendar-export-region (point-min) (point-max) tmpfile)
17087 (setq buf (find-buffer-visiting tmpfile))
17088 (set-buffer buf)
17089 (goto-char (point-min))
17090 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17091 (setq b (match-beginning 0)))
17092 (goto-char (point-max))
17093 (if (re-search-backward "^END:VEVENT" nil t)
17094 (setq e (match-end 0)))
17095 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17096 (kill-buffer buf)
17097 (delete-file tmpfile)
17098 rtn))
17100 (defun org-closest-date (start current change prefer show-all)
17101 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17102 When PREFER is `past', return a date that is either CURRENT or past.
17103 When PREFER is `future', return a date that is either CURRENT or future.
17104 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17105 ;; Make the proper lists from the dates
17106 (catch 'exit
17107 (let ((a1 '(("h" . hour)
17108 ("d" . day)
17109 ("w" . week)
17110 ("m" . month)
17111 ("y" . year)))
17112 (shour (nth 2 (org-parse-time-string start)))
17113 dn dw sday cday n1 n2 n0
17114 d m y y1 y2 date1 date2 nmonths nm ny m2)
17116 (setq start (org-date-to-gregorian start)
17117 current (org-date-to-gregorian
17118 (if show-all
17119 current
17120 (time-to-days (current-time))))
17121 sday (calendar-absolute-from-gregorian start)
17122 cday (calendar-absolute-from-gregorian current))
17124 (if (<= cday sday) (throw 'exit sday))
17126 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17127 (setq dn (string-to-number (match-string 1 change))
17128 dw (cdr (assoc (match-string 2 change) a1)))
17129 (user-error "Invalid change specifier: %s" change))
17130 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17131 (cond
17132 ((eq dw 'hour)
17133 (let ((missing-hours
17134 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17135 dn)))
17136 (setq n1 (if (zerop missing-hours) cday
17137 (- cday (1+ (floor (/ missing-hours 24)))))
17138 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17139 ((eq dw 'day)
17140 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17141 n2 (+ n1 dn)))
17142 ((eq dw 'year)
17143 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17144 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17145 (setq date1 (list m d y1)
17146 n1 (calendar-absolute-from-gregorian date1)
17147 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17148 n2 (calendar-absolute-from-gregorian date2)))
17149 ((eq dw 'month)
17150 ;; approx number of month between the two dates
17151 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17152 ;; How often does dn fit in there?
17153 (setq d (nth 1 start) m (car start) y (nth 2 start)
17154 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17155 m (+ m nm)
17156 ny (floor (/ m 12))
17157 y (+ y ny)
17158 m (- m (* ny 12)))
17159 (while (> m 12) (setq m (- m 12) y (1+ y)))
17160 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17161 (setq m2 (+ m dn) y2 y)
17162 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17163 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17164 (while (<= n2 cday)
17165 (setq n1 n2 m m2 y y2)
17166 (setq m2 (+ m dn) y2 y)
17167 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17168 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17169 ;; Make sure n1 is the earlier date
17170 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17171 (if show-all
17172 (cond
17173 ((eq prefer 'past) (if (= cday n2) n2 n1))
17174 ((eq prefer 'future) (if (= cday n1) n1 n2))
17175 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17176 (cond
17177 ((eq prefer 'past) (if (= cday n2) n2 n1))
17178 ((eq prefer 'future) (if (= cday n1) n1 n2))
17179 (t (if (= cday n1) n1 n2)))))))
17181 (defun org-date-to-gregorian (date)
17182 "Turn any specification of DATE into a Gregorian date for the calendar."
17183 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17184 ((and (listp date) (= (length date) 3)) date)
17185 ((stringp date)
17186 (setq date (org-parse-time-string date))
17187 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17188 ((listp date)
17189 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17191 (defun org-parse-time-string (s &optional nodefault)
17192 "Parse the standard Org-mode time string.
17193 This should be a lot faster than the normal `parse-time-string'.
17194 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17195 hour and minute fields will be nil if not given."
17196 (cond ((string-match org-ts-regexp0 s)
17197 (list 0
17198 (if (or (match-beginning 8) (not nodefault))
17199 (string-to-number (or (match-string 8 s) "0")))
17200 (if (or (match-beginning 7) (not nodefault))
17201 (string-to-number (or (match-string 7 s) "0")))
17202 (string-to-number (match-string 4 s))
17203 (string-to-number (match-string 3 s))
17204 (string-to-number (match-string 2 s))
17205 nil nil nil))
17206 ((string-match "^<[^>]+>$" s)
17207 (decode-time (seconds-to-time (org-matcher-time s))))
17208 (t (error "Not a standard Org-mode time string: %s" s))))
17210 (defun org-timestamp-up (&optional arg)
17211 "Increase the date item at the cursor by one.
17212 If the cursor is on the year, change the year. If it is on the month,
17213 the day or the time, change that.
17214 With prefix ARG, change by that many units."
17215 (interactive "p")
17216 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17218 (defun org-timestamp-down (&optional arg)
17219 "Decrease the date item at the cursor by one.
17220 If the cursor is on the year, change the year. If it is on the month,
17221 the day or the time, change that.
17222 With prefix ARG, change by that many units."
17223 (interactive "p")
17224 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17226 (defun org-timestamp-up-day (&optional arg)
17227 "Increase the date in the time stamp by one day.
17228 With prefix ARG, change that many days."
17229 (interactive "p")
17230 (if (and (not (org-at-timestamp-p t))
17231 (org-at-heading-p))
17232 (org-todo 'up)
17233 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17235 (defun org-timestamp-down-day (&optional arg)
17236 "Decrease the date in the time stamp by one day.
17237 With prefix ARG, change that many days."
17238 (interactive "p")
17239 (if (and (not (org-at-timestamp-p t))
17240 (org-at-heading-p))
17241 (org-todo 'down)
17242 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17244 (defun org-at-timestamp-p (&optional inactive-ok)
17245 "Determine if the cursor is in or at a timestamp."
17246 (interactive)
17247 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17248 (pos (point))
17249 (ans (or (looking-at tsr)
17250 (save-excursion
17251 (skip-chars-backward "^[<\n\r\t")
17252 (if (> (point) (point-min)) (backward-char 1))
17253 (and (looking-at tsr)
17254 (> (- (match-end 0) pos) -1))))))
17255 (and ans
17256 (boundp 'org-ts-what)
17257 (setq org-ts-what
17258 (cond
17259 ((= pos (match-beginning 0)) 'bracket)
17260 ;; Point is considered to be "on the bracket" whether
17261 ;; it's really on it or right after it.
17262 ((= pos (1- (match-end 0))) 'bracket)
17263 ((= pos (match-end 0)) 'after)
17264 ((org-pos-in-match-range pos 2) 'year)
17265 ((org-pos-in-match-range pos 3) 'month)
17266 ((org-pos-in-match-range pos 7) 'hour)
17267 ((org-pos-in-match-range pos 8) 'minute)
17268 ((or (org-pos-in-match-range pos 4)
17269 (org-pos-in-match-range pos 5)) 'day)
17270 ((and (> pos (or (match-end 8) (match-end 5)))
17271 (< pos (match-end 0)))
17272 (- pos (or (match-end 8) (match-end 5))))
17273 (t 'day))))
17274 ans))
17276 (defun org-toggle-timestamp-type ()
17277 "Toggle the type (<active> or [inactive]) of a time stamp."
17278 (interactive)
17279 (when (org-at-timestamp-p t)
17280 (let ((beg (match-beginning 0)) (end (match-end 0))
17281 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17282 (save-excursion
17283 (goto-char beg)
17284 (while (re-search-forward "[][<>]" end t)
17285 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17286 t t)))
17287 (message "Timestamp is now %sactive"
17288 (if (equal (char-after beg) ?<) "" "in")))))
17290 (defun org-at-clock-log-p nil
17291 "Is the cursor on the clock log line?"
17292 (save-excursion
17293 (move-beginning-of-line 1)
17294 (looking-at "^[ \t]*CLOCK:")))
17296 (defvar org-clock-history) ; defined in org-clock.el
17297 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17298 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17299 "Change the date in the time stamp at point.
17300 The date will be changed by N times WHAT. WHAT can be `day', `month',
17301 `year', `minute', `second'. If WHAT is not given, the cursor position
17302 in the timestamp determines what will be changed.
17303 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17304 (let ((origin (point)) origin-cat
17305 with-hm inactive
17306 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17307 org-ts-what
17308 extra rem
17309 ts time time0 fixnext clrgx)
17310 (if (not (org-at-timestamp-p t))
17311 (user-error "Not at a timestamp"))
17312 (if (and (not what) (eq org-ts-what 'bracket))
17313 (org-toggle-timestamp-type)
17314 ;; Point isn't on brackets. Remember the part of the time-stamp
17315 ;; the point was in. Indeed, size of time-stamps may change,
17316 ;; but point must be kept in the same category nonetheless.
17317 (setq origin-cat org-ts-what)
17318 (if (and (not what) (not (eq org-ts-what 'day))
17319 org-display-custom-times
17320 (get-text-property (point) 'display)
17321 (not (get-text-property (1- (point)) 'display)))
17322 (setq org-ts-what 'day))
17323 (setq org-ts-what (or what org-ts-what)
17324 inactive (= (char-after (match-beginning 0)) ?\[)
17325 ts (match-string 0))
17326 (replace-match "")
17327 (when (string-match
17328 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17330 (setq extra (match-string 1 ts))
17331 (if suppress-tmp-delay
17332 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17333 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17334 (setq with-hm t))
17335 (setq time0 (org-parse-time-string ts))
17336 (when (and updown
17337 (eq org-ts-what 'minute)
17338 (not current-prefix-arg))
17339 ;; This looks like s-up and s-down. Change by one rounding step.
17340 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17341 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17342 (setcar (cdr time0) (+ (nth 1 time0)
17343 (if (> n 0) (- rem) (- dm rem))))))
17344 (setq time
17345 (encode-time (or (car time0) 0)
17346 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17347 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17348 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17349 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17350 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17351 (nthcdr 6 time0)))
17352 (when (and (member org-ts-what '(hour minute))
17353 extra
17354 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17355 (setq extra (org-modify-ts-extra
17356 extra
17357 (if (eq org-ts-what 'hour) 2 5)
17358 n dm)))
17359 (when (integerp org-ts-what)
17360 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17361 (if (eq what 'calendar)
17362 (let ((cal-date (org-get-date-from-calendar)))
17363 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17364 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17365 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17366 (setcar time0 (or (car time0) 0))
17367 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17368 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17369 (setq time (apply 'encode-time time0))))
17370 ;; Insert the new time-stamp, and ensure point stays in the same
17371 ;; category as before (i.e. not after the last position in that
17372 ;; category).
17373 (let ((pos (point)))
17374 ;; Stay before inserted string. `save-excursion' is of no use.
17375 (setq org-last-changed-timestamp
17376 (org-insert-time-stamp time with-hm inactive nil nil extra))
17377 (goto-char pos))
17378 (save-match-data
17379 (looking-at org-ts-regexp3)
17380 (goto-char (cond
17381 ;; `day' category ends before `hour' if any, or at
17382 ;; the end of the day name.
17383 ((eq origin-cat 'day)
17384 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17385 ((eq origin-cat 'hour) (min (match-end 7) origin))
17386 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17387 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17388 ;; `year' and `month' have both fixed size: point
17389 ;; couldn't have moved into another part.
17390 (t origin))))
17391 ;; Update clock if on a CLOCK line.
17392 (org-clock-update-time-maybe)
17393 ;; Maybe adjust the closest clock in `org-clock-history'
17394 (when org-clock-adjust-closest
17395 (if (not (and (org-at-clock-log-p)
17396 (< 1 (length (delq nil (mapcar 'marker-position
17397 org-clock-history))))))
17398 (message "No clock to adjust")
17399 (cond ((save-excursion ; fix previous clock?
17400 (re-search-backward org-ts-regexp0 nil t)
17401 (org-looking-back (concat org-clock-string " \\[")))
17402 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17403 ((save-excursion ; fix next clock?
17404 (re-search-backward org-ts-regexp0 nil t)
17405 (looking-at (concat org-ts-regexp0 "\\] =>")))
17406 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17407 (save-window-excursion
17408 ;; Find closest clock to point, adjust the previous/next one in history
17409 (let* ((p (save-excursion (org-back-to-heading t)))
17410 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17411 (clfixnth
17412 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17413 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17414 (if (not clfixpos)
17415 (message "No clock to adjust")
17416 (save-excursion
17417 (org-goto-marker-or-bmk clfixpos)
17418 (org-show-subtree)
17419 (when (re-search-forward clrgx nil t)
17420 (goto-char (match-beginning 1))
17421 (let (org-clock-adjust-closest)
17422 (org-timestamp-change n org-ts-what updown))
17423 (message "Clock adjusted in %s for heading: %s"
17424 (file-name-nondirectory (buffer-file-name))
17425 (org-get-heading t t)))))))))
17426 ;; Try to recenter the calendar window, if any.
17427 (if (and org-calendar-follow-timestamp-change
17428 (get-buffer-window "*Calendar*" t)
17429 (memq org-ts-what '(day month year)))
17430 (org-recenter-calendar (time-to-days time))))))
17432 (defun org-modify-ts-extra (s pos n dm)
17433 "Change the different parts of the lead-time and repeat fields in timestamp."
17434 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17435 ng h m new rem)
17436 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17437 (cond
17438 ((or (org-pos-in-match-range pos 2)
17439 (org-pos-in-match-range pos 3))
17440 (setq m (string-to-number (match-string 3 s))
17441 h (string-to-number (match-string 2 s)))
17442 (if (org-pos-in-match-range pos 2)
17443 (setq h (+ h n))
17444 (setq n (* dm (org-no-warnings (signum n))))
17445 (when (not (= 0 (setq rem (% m dm))))
17446 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17447 (setq m (+ m n)))
17448 (if (< m 0) (setq m (+ m 60) h (1- h)))
17449 (if (> m 59) (setq m (- m 60) h (1+ h)))
17450 (setq h (min 24 (max 0 h)))
17451 (setq ng 1 new (format "-%02d:%02d" h m)))
17452 ((org-pos-in-match-range pos 6)
17453 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17454 ((org-pos-in-match-range pos 5)
17455 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17457 ((org-pos-in-match-range pos 9)
17458 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17459 ((org-pos-in-match-range pos 8)
17460 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17462 (when ng
17463 (setq s (concat
17464 (substring s 0 (match-beginning ng))
17466 (substring s (match-end ng))))))
17469 (defun org-recenter-calendar (date)
17470 "If the calendar is visible, recenter it to DATE."
17471 (let ((cwin (get-buffer-window "*Calendar*" t)))
17472 (when cwin
17473 (let ((calendar-move-hook nil))
17474 (with-selected-window cwin
17475 (calendar-goto-date (if (listp date) date
17476 (calendar-gregorian-from-absolute date))))))))
17478 (defun org-goto-calendar (&optional arg)
17479 "Go to the Emacs calendar at the current date.
17480 If there is a time stamp in the current line, go to that date.
17481 A prefix ARG can be used to force the current date."
17482 (interactive "P")
17483 (let ((tsr org-ts-regexp) diff
17484 (calendar-move-hook nil)
17485 (calendar-view-holidays-initially-flag nil)
17486 (calendar-view-diary-initially-flag nil))
17487 (if (or (org-at-timestamp-p)
17488 (save-excursion
17489 (beginning-of-line 1)
17490 (looking-at (concat ".*" tsr))))
17491 (let ((d1 (time-to-days (current-time)))
17492 (d2 (time-to-days
17493 (org-time-string-to-time (match-string 1)))))
17494 (setq diff (- d2 d1))))
17495 (calendar)
17496 (calendar-goto-today)
17497 (if (and diff (not arg)) (calendar-forward-day diff))))
17499 (defun org-get-date-from-calendar ()
17500 "Return a list (month day year) of date at point in calendar."
17501 (with-current-buffer "*Calendar*"
17502 (save-match-data
17503 (calendar-cursor-to-date))))
17505 (defun org-date-from-calendar ()
17506 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17507 If there is already a time stamp at the cursor position, update it."
17508 (interactive)
17509 (if (org-at-timestamp-p t)
17510 (org-timestamp-change 0 'calendar)
17511 (let ((cal-date (org-get-date-from-calendar)))
17512 (org-insert-time-stamp
17513 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17515 (defcustom org-effort-durations
17516 `(("h" . 60)
17517 ("d" . ,(* 60 8))
17518 ("w" . ,(* 60 8 5))
17519 ("m" . ,(* 60 8 5 4))
17520 ("y" . ,(* 60 8 5 40)))
17521 "Conversion factor to minutes for an effort modifier.
17523 Each entry has the form (MODIFIER . MINUTES).
17525 In an effort string, a number followed by MODIFIER is multiplied
17526 by the specified number of MINUTES to obtain an effort in
17527 minutes.
17529 For example, if the value of this variable is ((\"hours\" . 60)), then an
17530 effort string \"2hours\" is equivalent to 120 minutes."
17531 :group 'org-agenda
17532 :version "24.1"
17533 :type '(alist :key-type (string :tag "Modifier")
17534 :value-type (number :tag "Minutes")))
17536 (defun org-minutes-to-clocksum-string (m)
17537 "Format number of minutes as a clocksum string.
17538 The format is determined by `org-time-clocksum-format',
17539 `org-time-clocksum-use-fractional' and
17540 `org-time-clocksum-fractional-format' and
17541 `org-time-clocksum-use-effort-durations'."
17542 (let ((clocksum "")
17543 (m (round m)) ; Don't allow fractions of minutes
17544 h d w mo y fmt n)
17545 (setq h (if org-time-clocksum-use-effort-durations
17546 (cdr (assoc "h" org-effort-durations)) 60)
17547 d (if org-time-clocksum-use-effort-durations
17548 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17549 w (if org-time-clocksum-use-effort-durations
17550 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17551 mo (if org-time-clocksum-use-effort-durations
17552 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17553 y (if org-time-clocksum-use-effort-durations
17554 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17555 ;; fractional format
17556 (if org-time-clocksum-use-fractional
17557 (cond
17558 ;; single format string
17559 ((stringp org-time-clocksum-fractional-format)
17560 (format org-time-clocksum-fractional-format (/ m (float h))))
17561 ;; choice of fractional formats for different time units
17562 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17563 (> (/ (truncate m) (* y d h)) 0))
17564 (format fmt (/ m (* y d (float h)))))
17565 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17566 (> (/ (truncate m) (* mo d h)) 0))
17567 (format fmt (/ m (* mo d (float h)))))
17568 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17569 (> (/ (truncate m) (* w d h)) 0))
17570 (format fmt (/ m (* w d (float h)))))
17571 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17572 (> (/ (truncate m) (* d h)) 0))
17573 (format fmt (/ m (* d (float h)))))
17574 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17575 (> (/ (truncate m) h) 0))
17576 (format fmt (/ m (float h))))
17577 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17578 (format fmt m))
17579 ;; fall back to smallest time unit with a format
17580 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17581 (format fmt (/ m (float h))))
17582 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17583 (format fmt (/ m (* d (float h)))))
17584 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17585 (format fmt (/ m (* w d (float h)))))
17586 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17587 (format fmt (/ m (* mo d (float h)))))
17588 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17589 (format fmt (/ m (* y d (float h))))))
17590 ;; standard (non-fractional) format, with single format string
17591 (if (stringp org-time-clocksum-format)
17592 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17593 ;; separate formats components
17594 (and (setq fmt (plist-get org-time-clocksum-format :years))
17595 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17596 (plist-get org-time-clocksum-format :require-years))
17597 (setq clocksum (concat clocksum (format fmt n))
17598 m (- m (* n y d h))))
17599 (and (setq fmt (plist-get org-time-clocksum-format :months))
17600 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17601 (plist-get org-time-clocksum-format :require-months))
17602 (setq clocksum (concat clocksum (format fmt n))
17603 m (- m (* n mo d h))))
17604 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17605 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17606 (plist-get org-time-clocksum-format :require-weeks))
17607 (setq clocksum (concat clocksum (format fmt n))
17608 m (- m (* n w d h))))
17609 (and (setq fmt (plist-get org-time-clocksum-format :days))
17610 (or (> (setq n (/ (truncate m) (* d h))) 0)
17611 (plist-get org-time-clocksum-format :require-days))
17612 (setq clocksum (concat clocksum (format fmt n))
17613 m (- m (* n d h))))
17614 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17615 (or (> (setq n (/ (truncate m) h)) 0)
17616 (plist-get org-time-clocksum-format :require-hours))
17617 (setq clocksum (concat clocksum (format fmt n))
17618 m (- m (* n h))))
17619 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17620 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17621 (setq clocksum (concat clocksum (format fmt m))))
17622 ;; return formatted time duration
17623 clocksum))))
17625 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17626 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17627 "Org mode version 8.0")
17629 (defun org-hours-to-clocksum-string (n)
17630 (org-minutes-to-clocksum-string (* n 60)))
17632 (defun org-hh:mm-string-to-minutes (s)
17633 "Convert a string H:MM to a number of minutes.
17634 If the string is just a number, interpret it as minutes.
17635 In fact, the first hh:mm or number in the string will be taken,
17636 there can be extra stuff in the string.
17637 If no number is found, the return value is 0."
17638 (cond
17639 ((integerp s) s)
17640 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17641 (+ (* (string-to-number (match-string 1 s)) 60)
17642 (string-to-number (match-string 2 s))))
17643 ((string-match "\\([0-9]+\\)" s)
17644 (string-to-number (match-string 1 s)))
17645 (t 0)))
17647 (defcustom org-image-actual-width t
17648 "Should we use the actual width of images when inlining them?
17650 When set to `t', always use the image width.
17652 When set to a number, use imagemagick (when available) to set
17653 the image's width to this value.
17655 When set to a number in a list, try to get the width from any
17656 #+ATTR.* keyword if it matches a width specification like
17658 #+ATTR_HTML: :width 300px
17660 and fall back on that number if none is found.
17662 When set to nil, try to get the width from an #+ATTR.* keyword
17663 and fall back on the original width if none is found.
17665 This requires Emacs >= 24.1, build with imagemagick support."
17666 :group 'org-appearance
17667 :version "24.4"
17668 :package-version '(Org . "8.0")
17669 :type '(choice
17670 (const :tag "Use the image width" t)
17671 (integer :tag "Use a number of pixels")
17672 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17673 (const :tag "Use #+ATTR* or don't resize" nil)))
17675 (defcustom org-agenda-inhibit-startup nil
17676 "Inhibit startup when preparing agenda buffers.
17677 When this variable is `t' (the default), the initialization of
17678 the Org agenda buffers is inhibited: e.g. the visibility state
17679 is not set, the tables are not re-aligned, etc."
17680 :type 'boolean
17681 :version "24.3"
17682 :group 'org-agenda)
17684 (defcustom org-agenda-ignore-drawer-properties nil
17685 "Avoid updating text properties when building the agenda.
17686 Properties are used to prepare buffers for effort estimates, appointments,
17687 and subtree-local categories.
17688 If you don't use these in the agenda, you can add them to this list and
17689 agenda building will be a bit faster.
17690 The value is a list, with zero or more of the symbols `effort', `appt',
17691 or `category'."
17692 :type '(set :greedy t
17693 (const effort)
17694 (const appt)
17695 (const category))
17696 :version "24.3"
17697 :group 'org-agenda)
17699 (defun org-duration-string-to-minutes (s &optional output-to-string)
17700 "Convert a duration string S to minutes.
17702 A bare number is interpreted as minutes, modifiers can be set by
17703 customizing `org-effort-durations' (which see).
17705 Entries containing a colon are interpreted as H:MM by
17706 `org-hh:mm-string-to-minutes'."
17707 (let ((result 0)
17708 (re (concat "\\([0-9.]+\\) *\\("
17709 (regexp-opt (mapcar 'car org-effort-durations))
17710 "\\)")))
17711 (while (string-match re s)
17712 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17713 (string-to-number (match-string 1 s))))
17714 (setq s (replace-match "" nil t s)))
17715 (setq result (floor result))
17716 (incf result (org-hh:mm-string-to-minutes s))
17717 (if output-to-string (number-to-string result) result)))
17719 ;;;; Files
17721 (defun org-save-all-org-buffers ()
17722 "Save all Org-mode buffers without user confirmation."
17723 (interactive)
17724 (message "Saving all Org-mode buffers...")
17725 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17726 (when (featurep 'org-id) (org-id-locations-save))
17727 (message "Saving all Org-mode buffers... done"))
17729 (defun org-revert-all-org-buffers ()
17730 "Revert all Org-mode buffers.
17731 Prompt for confirmation when there are unsaved changes.
17732 Be sure you know what you are doing before letting this function
17733 overwrite your changes.
17735 This function is useful in a setup where one tracks org files
17736 with a version control system, to revert on one machine after pulling
17737 changes from another. I believe the procedure must be like this:
17739 1. M-x org-save-all-org-buffers
17740 2. Pull changes from the other machine, resolve conflicts
17741 3. M-x org-revert-all-org-buffers"
17742 (interactive)
17743 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17744 (user-error "Abort"))
17745 (save-excursion
17746 (save-window-excursion
17747 (mapc
17748 (lambda (b)
17749 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17750 (with-current-buffer b buffer-file-name))
17751 (org-pop-to-buffer-same-window b)
17752 (revert-buffer t 'no-confirm)))
17753 (buffer-list))
17754 (when (and (featurep 'org-id) org-id-track-globally)
17755 (org-id-locations-load)))))
17757 ;;;; Agenda files
17759 ;;;###autoload
17760 (defun org-switchb (&optional arg)
17761 "Switch between Org buffers.
17762 With one prefix argument, restrict available buffers to files.
17763 With two prefix arguments, restrict available buffers to agenda files.
17765 Defaults to `iswitchb' for buffer name completion.
17766 Set `org-completion-use-ido' to make it use ido instead."
17767 (interactive "P")
17768 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17769 ((equal arg '(16)) (org-buffer-list 'agenda))
17770 (t (org-buffer-list))))
17771 (org-completion-use-iswitchb org-completion-use-iswitchb)
17772 (org-completion-use-ido org-completion-use-ido))
17773 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17774 (setq org-completion-use-iswitchb t))
17775 (org-pop-to-buffer-same-window
17776 (org-icompleting-read "Org buffer: "
17777 (mapcar 'list (mapcar 'buffer-name blist))
17778 nil t))))
17780 ;;; Define some older names previously used for this functionality
17781 ;;;###autoload
17782 (defalias 'org-ido-switchb 'org-switchb)
17783 ;;;###autoload
17784 (defalias 'org-iswitchb 'org-switchb)
17786 (defun org-buffer-list (&optional predicate exclude-tmp)
17787 "Return a list of Org buffers.
17788 PREDICATE can be `export', `files' or `agenda'.
17790 export restrict the list to Export buffers.
17791 files restrict the list to buffers visiting Org files.
17792 agenda restrict the list to buffers visiting agenda files.
17794 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17795 (let* ((bfn nil)
17796 (agenda-files (and (eq predicate 'agenda)
17797 (mapcar 'file-truename (org-agenda-files t))))
17798 (filter
17799 (cond
17800 ((eq predicate 'files)
17801 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17802 ((eq predicate 'export)
17803 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17804 ((eq predicate 'agenda)
17805 (lambda (b)
17806 (with-current-buffer b
17807 (and (derived-mode-p 'org-mode)
17808 (setq bfn (buffer-file-name b))
17809 (member (file-truename bfn) agenda-files)))))
17810 (t (lambda (b) (with-current-buffer b
17811 (or (derived-mode-p 'org-mode)
17812 (string-match "\*Org .*Export"
17813 (buffer-name b)))))))))
17814 (delq nil
17815 (mapcar
17816 (lambda(b)
17817 (if (and (funcall filter b)
17818 (or (not exclude-tmp)
17819 (not (string-match "tmp" (buffer-name b)))))
17821 nil))
17822 (buffer-list)))))
17824 (defun org-agenda-files (&optional unrestricted archives)
17825 "Get the list of agenda files.
17826 Optional UNRESTRICTED means return the full list even if a restriction
17827 is currently in place.
17828 When ARCHIVES is t, include all archive files that are really being
17829 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17830 `org-agenda-archives-mode' is t."
17831 (let ((files
17832 (cond
17833 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17834 ((stringp org-agenda-files) (org-read-agenda-file-list))
17835 ((listp org-agenda-files) org-agenda-files)
17836 (t (error "Invalid value of `org-agenda-files'")))))
17837 (setq files (apply 'append
17838 (mapcar (lambda (f)
17839 (if (file-directory-p f)
17840 (directory-files
17841 f t org-agenda-file-regexp)
17842 (list f)))
17843 files)))
17844 (when org-agenda-skip-unavailable-files
17845 (setq files (delq nil
17846 (mapcar (function
17847 (lambda (file)
17848 (and (file-readable-p file) file)))
17849 files))))
17850 (when (or (eq archives t)
17851 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17852 (setq files (org-add-archive-files files)))
17853 files))
17855 (defun org-agenda-file-p (&optional file)
17856 "Return non-nil, if FILE is an agenda file.
17857 If FILE is omitted, use the file associated with the current
17858 buffer."
17859 (member (or file (buffer-file-name))
17860 (org-agenda-files t)))
17862 (defun org-edit-agenda-file-list ()
17863 "Edit the list of agenda files.
17864 Depending on setup, this either uses customize to edit the variable
17865 `org-agenda-files', or it visits the file that is holding the list. In the
17866 latter case, the buffer is set up in a way that saving it automatically kills
17867 the buffer and restores the previous window configuration."
17868 (interactive)
17869 (if (stringp org-agenda-files)
17870 (let ((cw (current-window-configuration)))
17871 (find-file org-agenda-files)
17872 (org-set-local 'org-window-configuration cw)
17873 (org-add-hook 'after-save-hook
17874 (lambda ()
17875 (set-window-configuration
17876 (prog1 org-window-configuration
17877 (kill-buffer (current-buffer))))
17878 (org-install-agenda-files-menu)
17879 (message "New agenda file list installed"))
17880 nil 'local)
17881 (message "%s" (substitute-command-keys
17882 "Edit list and finish with \\[save-buffer]")))
17883 (customize-variable 'org-agenda-files)))
17885 (defun org-store-new-agenda-file-list (list)
17886 "Set new value for the agenda file list and save it correctly."
17887 (if (stringp org-agenda-files)
17888 (let ((fe (org-read-agenda-file-list t)) b u)
17889 (while (setq b (find-buffer-visiting org-agenda-files))
17890 (kill-buffer b))
17891 (with-temp-file org-agenda-files
17892 (insert
17893 (mapconcat
17894 (lambda (f) ;; Keep un-expanded entries.
17895 (if (setq u (assoc f fe))
17896 (cdr u)
17898 list "\n")
17899 "\n")))
17900 (let ((org-mode-hook nil) (org-inhibit-startup t)
17901 (org-insert-mode-line-in-empty-file nil))
17902 (setq org-agenda-files list)
17903 (customize-save-variable 'org-agenda-files org-agenda-files))))
17905 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17906 "Read the list of agenda files from a file.
17907 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17908 filenames, used by `org-store-new-agenda-file-list' to write back
17909 un-expanded file names."
17910 (when (file-directory-p org-agenda-files)
17911 (error "`org-agenda-files' cannot be a single directory"))
17912 (when (stringp org-agenda-files)
17913 (with-temp-buffer
17914 (insert-file-contents org-agenda-files)
17915 (mapcar
17916 (lambda (f)
17917 (let ((e (expand-file-name (substitute-in-file-name f)
17918 org-directory)))
17919 (if pair-with-expansion
17920 (cons e f)
17921 e)))
17922 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17924 ;;;###autoload
17925 (defun org-cycle-agenda-files ()
17926 "Cycle through the files in `org-agenda-files'.
17927 If the current buffer visits an agenda file, find the next one in the list.
17928 If the current buffer does not, find the first agenda file."
17929 (interactive)
17930 (let* ((fs (org-agenda-files t))
17931 (files (append fs (list (car fs))))
17932 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17933 file)
17934 (unless files (user-error "No agenda files"))
17935 (catch 'exit
17936 (while (setq file (pop files))
17937 (if (equal (file-truename file) tcf)
17938 (when (car files)
17939 (find-file (car files))
17940 (throw 'exit t))))
17941 (find-file (car fs)))
17942 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17944 (defun org-agenda-file-to-front (&optional to-end)
17945 "Move/add the current file to the top of the agenda file list.
17946 If the file is not present in the list, it is added to the front. If it is
17947 present, it is moved there. With optional argument TO-END, add/move to the
17948 end of the list."
17949 (interactive "P")
17950 (let ((org-agenda-skip-unavailable-files nil)
17951 (file-alist (mapcar (lambda (x)
17952 (cons (file-truename x) x))
17953 (org-agenda-files t)))
17954 (ctf (file-truename
17955 (or buffer-file-name
17956 (user-error "Please save the current buffer to a file"))))
17957 x had)
17958 (setq x (assoc ctf file-alist) had x)
17960 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17961 (if to-end
17962 (setq file-alist (append (delq x file-alist) (list x)))
17963 (setq file-alist (cons x (delq x file-alist))))
17964 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17965 (org-install-agenda-files-menu)
17966 (message "File %s to %s of agenda file list"
17967 (if had "moved" "added") (if to-end "end" "front"))))
17969 (defun org-remove-file (&optional file)
17970 "Remove current file from the list of files in variable `org-agenda-files'.
17971 These are the files which are being checked for agenda entries.
17972 Optional argument FILE means use this file instead of the current."
17973 (interactive)
17974 (let* ((org-agenda-skip-unavailable-files nil)
17975 (file (or file buffer-file-name
17976 (user-error "Current buffer does not visit a file")))
17977 (true-file (file-truename file))
17978 (afile (abbreviate-file-name file))
17979 (files (delq nil (mapcar
17980 (lambda (x)
17981 (if (equal true-file
17982 (file-truename x))
17983 nil x))
17984 (org-agenda-files t)))))
17985 (if (not (= (length files) (length (org-agenda-files t))))
17986 (progn
17987 (org-store-new-agenda-file-list files)
17988 (org-install-agenda-files-menu)
17989 (message "Removed file: %s" afile))
17990 (message "File was not in list: %s (not removed)" afile))))
17992 (defun org-file-menu-entry (file)
17993 (vector file (list 'find-file file) t))
17995 (defun org-check-agenda-file (file)
17996 "Make sure FILE exists. If not, ask user what to do."
17997 (when (not (file-exists-p file))
17998 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17999 (abbreviate-file-name file))
18000 (let ((r (downcase (read-char-exclusive))))
18001 (cond
18002 ((equal r ?r)
18003 (org-remove-file file)
18004 (throw 'nextfile t))
18005 (t (error "Abort"))))))
18007 (defun org-get-agenda-file-buffer (file)
18008 "Get a buffer visiting FILE. If the buffer needs to be created, add
18009 it to the list of buffers which might be released later."
18010 (let ((buf (org-find-base-buffer-visiting file)))
18011 (if buf
18012 buf ; just return it
18013 ;; Make a new buffer and remember it
18014 (setq buf (find-file-noselect file))
18015 (if buf (push buf org-agenda-new-buffers))
18016 buf)))
18018 (defun org-release-buffers (blist)
18019 "Release all buffers in list, asking the user for confirmation when needed.
18020 When a buffer is unmodified, it is just killed. When modified, it is saved
18021 \(if the user agrees) and then killed."
18022 (let (buf file)
18023 (while (setq buf (pop blist))
18024 (setq file (buffer-file-name buf))
18025 (when (and (buffer-modified-p buf)
18026 file
18027 (y-or-n-p (format "Save file %s? " file)))
18028 (with-current-buffer buf (save-buffer)))
18029 (kill-buffer buf))))
18031 (defun org-agenda-prepare-buffers (files)
18032 "Create buffers for all agenda files, protect archived trees and comments."
18033 (interactive)
18034 (let ((pa '(:org-archived t))
18035 (pc '(:org-comment t))
18036 (pall '(:org-archived t :org-comment t))
18037 (inhibit-read-only t)
18038 (org-inhibit-startup org-agenda-inhibit-startup)
18039 (rea (concat ":" org-archive-tag ":"))
18040 file re pos)
18041 (setq org-tag-alist-for-agenda nil
18042 org-tag-groups-alist-for-agenda nil)
18043 (save-window-excursion
18044 (save-restriction
18045 (while (setq file (pop files))
18046 (catch 'nextfile
18047 (if (bufferp file)
18048 (set-buffer file)
18049 (org-check-agenda-file file)
18050 (set-buffer (org-get-agenda-file-buffer file)))
18051 (widen)
18052 (org-set-regexps-and-options-for-tags)
18053 (setq pos (point))
18054 (goto-char (point-min))
18055 (let ((case-fold-search t))
18056 (when (search-forward "#+setupfile" nil t)
18057 ;; Don't set all regexps and options systematically as
18058 ;; this is only run for setting agenda tags from setup
18059 ;; file
18060 (org-set-regexps-and-options)))
18061 (or (memq 'category org-agenda-ignore-drawer-properties)
18062 (org-refresh-category-properties))
18063 (or (memq 'effort org-agenda-ignore-drawer-properties)
18064 (org-refresh-properties org-effort-property 'org-effort))
18065 (or (memq 'appt org-agenda-ignore-drawer-properties)
18066 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18067 (setq org-todo-keywords-for-agenda
18068 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18069 (setq org-done-keywords-for-agenda
18070 (append org-done-keywords-for-agenda org-done-keywords))
18071 (setq org-todo-keyword-alist-for-agenda
18072 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18073 (setq org-drawers-for-agenda
18074 (append org-drawers-for-agenda org-drawers))
18075 (setq org-tag-alist-for-agenda
18076 (org-uniquify
18077 (append org-tag-alist-for-agenda
18078 org-tag-alist
18079 org-tag-persistent-alist)))
18080 (if org-group-tags
18081 (setq org-tag-groups-alist-for-agenda
18082 (org-uniquify-alist
18083 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18084 (org-with-silent-modifications
18085 (save-excursion
18086 (remove-text-properties (point-min) (point-max) pall)
18087 (when org-agenda-skip-archived-trees
18088 (goto-char (point-min))
18089 (while (re-search-forward rea nil t)
18090 (if (org-at-heading-p t)
18091 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18092 (goto-char (point-min))
18093 (setq re (format org-heading-keyword-regexp-format
18094 org-comment-string))
18095 (while (re-search-forward re nil t)
18096 (add-text-properties
18097 (match-beginning 0) (org-end-of-subtree t) pc))))
18098 (goto-char pos)))))
18099 (setq org-todo-keywords-for-agenda
18100 (org-uniquify org-todo-keywords-for-agenda))
18101 (setq org-todo-keyword-alist-for-agenda
18102 (org-uniquify org-todo-keyword-alist-for-agenda))))
18105 ;;;; CDLaTeX minor mode
18107 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18108 "Keymap for the minor `org-cdlatex-mode'.")
18110 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18111 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18112 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18113 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18114 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18116 (defvar org-cdlatex-texmathp-advice-is-done nil
18117 "Flag remembering if we have applied the advice to texmathp already.")
18119 (define-minor-mode org-cdlatex-mode
18120 "Toggle the minor `org-cdlatex-mode'.
18121 This mode supports entering LaTeX environment and math in LaTeX fragments
18122 in Org-mode.
18123 \\{org-cdlatex-mode-map}"
18124 nil " OCDL" nil
18125 (when org-cdlatex-mode
18126 (require 'cdlatex)
18127 (run-hooks 'cdlatex-mode-hook)
18128 (cdlatex-compute-tables))
18129 (unless org-cdlatex-texmathp-advice-is-done
18130 (setq org-cdlatex-texmathp-advice-is-done t)
18131 (defadvice texmathp (around org-math-always-on activate)
18132 "Always return t in org-mode buffers.
18133 This is because we want to insert math symbols without dollars even outside
18134 the LaTeX math segments. If Orgmode thinks that point is actually inside
18135 an embedded LaTeX fragment, let texmathp do its job.
18136 \\[org-cdlatex-mode-map]"
18137 (interactive)
18138 (let (p)
18139 (cond
18140 ((not (derived-mode-p 'org-mode)) ad-do-it)
18141 ((eq this-command 'cdlatex-math-symbol)
18142 (setq ad-return-value t
18143 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18145 (let ((p (org-inside-LaTeX-fragment-p)))
18146 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18147 (setq ad-return-value t
18148 texmathp-why '("Org-mode embedded math" . 0))
18149 (if p ad-do-it)))))))))
18151 (defun turn-on-org-cdlatex ()
18152 "Unconditionally turn on `org-cdlatex-mode'."
18153 (org-cdlatex-mode 1))
18155 (defun org-try-cdlatex-tab ()
18156 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18157 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18158 - inside a LaTeX fragment, or
18159 - after the first word in a line, where an abbreviation expansion could
18160 insert a LaTeX environment."
18161 (when org-cdlatex-mode
18162 (cond
18163 ;; Before any word on the line: No expansion possible.
18164 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18165 ;; Just after first word on the line: Expand it. Make sure it
18166 ;; cannot happen on headlines, though.
18167 ((save-excursion
18168 (skip-chars-backward "a-zA-Z0-9*")
18169 (skip-chars-backward " \t")
18170 (and (bolp) (not (org-at-heading-p))))
18171 (cdlatex-tab) t)
18172 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18174 (defun org-cdlatex-underscore-caret (&optional arg)
18175 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18176 Revert to the normal definition outside of these fragments."
18177 (interactive "P")
18178 (if (org-inside-LaTeX-fragment-p)
18179 (call-interactively 'cdlatex-sub-superscript)
18180 (let (org-cdlatex-mode)
18181 (call-interactively (key-binding (vector last-input-event))))))
18183 (defun org-cdlatex-math-modify (&optional arg)
18184 "Execute `cdlatex-math-modify' in LaTeX fragments.
18185 Revert to the normal definition outside of these fragments."
18186 (interactive "P")
18187 (if (org-inside-LaTeX-fragment-p)
18188 (call-interactively 'cdlatex-math-modify)
18189 (let (org-cdlatex-mode)
18190 (call-interactively (key-binding (vector last-input-event))))))
18194 ;;;; LaTeX fragments
18196 (defvar org-latex-regexps
18197 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18198 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18199 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18200 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18201 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18202 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18203 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18204 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18205 "Regular expressions for matching embedded LaTeX.")
18207 (defun org-inside-LaTeX-fragment-p ()
18208 "Test if point is inside a LaTeX fragment.
18209 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18210 sequence appearing also before point.
18211 Even though the matchers for math are configurable, this function assumes
18212 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18213 delimiters are skipped when they have been removed by customization.
18214 The return value is nil, or a cons cell with the delimiter and the
18215 position of this delimiter.
18217 This function does a reasonably good job, but can locally be fooled by
18218 for example currency specifications. For example it will assume being in
18219 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18220 fragments that are properly closed, but during editing, we have to live
18221 with the uncertainty caused by missing closing delimiters. This function
18222 looks only before point, not after."
18223 (catch 'exit
18224 (let ((pos (point))
18225 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18226 (lim (progn
18227 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18228 (point)))
18229 dd-on str (start 0) m re)
18230 (goto-char pos)
18231 (when dodollar
18232 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18233 re (nth 1 (assoc "$" org-latex-regexps)))
18234 (while (string-match re str start)
18235 (cond
18236 ((= (match-end 0) (length str))
18237 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18238 ((= (match-end 0) (- (length str) 5))
18239 (throw 'exit nil))
18240 (t (setq start (match-end 0))))))
18241 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18242 (goto-char pos)
18243 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18244 (and (match-beginning 2) (throw 'exit nil))
18245 ;; count $$
18246 (while (re-search-backward "\\$\\$" lim t)
18247 (setq dd-on (not dd-on)))
18248 (goto-char pos)
18249 (if dd-on (cons "$$" m))))))
18251 (defun org-inside-latex-macro-p ()
18252 "Is point inside a LaTeX macro or its arguments?"
18253 (save-match-data
18254 (org-in-regexp
18255 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18257 (defvar org-latex-fragment-image-overlays nil
18258 "List of overlays carrying the images of latex fragments.")
18259 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18261 (defun org-remove-latex-fragment-image-overlays ()
18262 "Remove all overlays with LaTeX fragment images in current buffer."
18263 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18264 (setq org-latex-fragment-image-overlays nil))
18266 (defun org-preview-latex-fragment (&optional subtree)
18267 "Preview the LaTeX fragment at point, or all locally or globally.
18268 If the cursor is in a LaTeX fragment, create the image and overlay
18269 it over the source code. If there is no fragment at point, display
18270 all fragments in the current text, from one headline to the next. With
18271 prefix SUBTREE, display all fragments in the current subtree. With a
18272 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18273 the cursor is before the first headline,
18274 display all fragments in the buffer.
18275 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18276 (interactive "P")
18277 (unless buffer-file-name
18278 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18279 (when (display-graphic-p)
18280 (org-remove-latex-fragment-image-overlays)
18281 (save-excursion
18282 (save-restriction
18283 (let (beg end at msg)
18284 (cond
18285 ((or (equal subtree '(16))
18286 (not (save-excursion
18287 (re-search-backward org-outline-regexp-bol nil t))))
18288 (setq beg (point-min) end (point-max)
18289 msg "Creating images for buffer...%s"))
18290 ((equal subtree '(4))
18291 (org-back-to-heading)
18292 (setq beg (point) end (org-end-of-subtree t)
18293 msg "Creating images for subtree...%s"))
18295 (if (setq at (org-inside-LaTeX-fragment-p))
18296 (goto-char (max (point-min) (- (cdr at) 2)))
18297 (org-back-to-heading))
18298 (setq beg (point) end (progn (outline-next-heading) (point))
18299 msg (if at "Creating image...%s"
18300 "Creating images for entry...%s"))))
18301 (message msg "")
18302 (narrow-to-region beg end)
18303 (goto-char beg)
18304 (org-format-latex
18305 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18306 (file-name-nondirectory
18307 buffer-file-name)))
18308 default-directory 'overlays msg at 'forbuffer
18309 org-latex-create-formula-image-program)
18310 (message msg "done. Use `C-c C-c' to remove images."))))))
18312 (defun org-format-latex (prefix &optional dir overlays msg at
18313 forbuffer processing-type)
18314 "Replace LaTeX fragments with links to an image, and produce images.
18315 Some of the options can be changed using the variable
18316 `org-format-latex-options'."
18317 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18318 (let* ((prefixnodir (file-name-nondirectory prefix))
18319 (absprefix (expand-file-name prefix dir))
18320 (todir (file-name-directory absprefix))
18321 (opt org-format-latex-options)
18322 (optnew org-format-latex-options)
18323 (matchers (plist-get opt :matchers))
18324 (re-list org-latex-regexps)
18325 (cnt 0) txt hash link beg end re e checkdir
18326 string
18327 m n block-type block linkfile movefile ov)
18328 ;; Check the different regular expressions
18329 (while (setq e (pop re-list))
18330 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18331 block (if block-type "\n\n" ""))
18332 (when (member m matchers)
18333 (goto-char (point-min))
18334 (while (re-search-forward re nil t)
18335 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18336 (or (not overlays)
18337 (not (eq (get-char-property (match-beginning n)
18338 'org-overlay-type)
18339 'org-latex-overlay))))
18340 (cond
18341 ((eq processing-type 'verbatim))
18342 ((eq processing-type 'mathjax)
18343 ;; Prepare for MathJax processing.
18344 (setq string (match-string n))
18345 (when (member m '("$" "$1"))
18346 (save-excursion
18347 (delete-region (match-beginning n) (match-end n))
18348 (goto-char (match-beginning n))
18349 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18350 ((or (eq processing-type 'dvipng)
18351 (eq processing-type 'imagemagick))
18352 ;; Process to an image.
18353 (setq txt (match-string n)
18354 beg (match-beginning n) end (match-end n)
18355 cnt (1+ cnt))
18356 (let ((face (face-at-point))
18357 (fg (plist-get opt :foreground))
18358 (bg (plist-get opt :background))
18359 ;; Ensure full list is printed.
18360 print-length print-level)
18361 (when forbuffer
18362 ;; Get the colors from the face at point.
18363 (goto-char beg)
18364 (when (eq fg 'auto)
18365 (setq fg (face-attribute face :foreground nil 'default)))
18366 (when (eq bg 'auto)
18367 (setq bg (face-attribute face :background nil 'default)))
18368 (setq optnew (copy-sequence opt))
18369 (plist-put optnew :foreground fg)
18370 (plist-put optnew :background bg))
18371 (setq hash (sha1 (prin1-to-string
18372 (list org-format-latex-header
18373 org-latex-default-packages-alist
18374 org-latex-packages-alist
18375 org-format-latex-options
18376 forbuffer txt fg bg)))
18377 linkfile (format "%s_%s.png" prefix hash)
18378 movefile (format "%s_%s.png" absprefix hash)))
18379 (setq link (concat block "[[file:" linkfile "]]" block))
18380 (if msg (message msg cnt))
18381 (goto-char beg)
18382 (unless checkdir ; Ensure the directory exists.
18383 (setq checkdir t)
18384 (or (file-directory-p todir) (make-directory todir t)))
18385 (unless (file-exists-p movefile)
18386 (org-create-formula-image
18387 txt movefile optnew forbuffer processing-type))
18388 (if overlays
18389 (progn
18390 (mapc (lambda (o)
18391 (if (eq (overlay-get o 'org-overlay-type)
18392 'org-latex-overlay)
18393 (delete-overlay o)))
18394 (overlays-in beg end))
18395 (setq ov (make-overlay beg end))
18396 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18397 (if (featurep 'xemacs)
18398 (progn
18399 (overlay-put ov 'invisible t)
18400 (overlay-put
18401 ov 'end-glyph
18402 (make-glyph (vector 'png :file movefile))))
18403 (overlay-put
18404 ov 'display
18405 (list 'image :type 'png :file movefile :ascent 'center)))
18406 (push ov org-latex-fragment-image-overlays)
18407 (goto-char end))
18408 (delete-region beg end)
18409 (insert (org-add-props link
18410 (list 'org-latex-src
18411 (replace-regexp-in-string
18412 "\"" "" txt)
18413 'org-latex-src-embed-type
18414 (if block-type 'paragraph 'character))))))
18415 ((eq processing-type 'mathml)
18416 ;; Process to MathML
18417 (unless (save-match-data (org-format-latex-mathml-available-p))
18418 (user-error "LaTeX to MathML converter not configured"))
18419 (setq txt (match-string n)
18420 beg (match-beginning n) end (match-end n)
18421 cnt (1+ cnt))
18422 (if msg (message msg cnt))
18423 (goto-char beg)
18424 (delete-region beg end)
18425 (insert (org-format-latex-as-mathml
18426 txt block-type prefix dir)))
18428 (error "Unknown conversion type %s for LaTeX fragments"
18429 processing-type)))))))))
18431 (defun org-create-math-formula (latex-frag &optional mathml-file)
18432 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18433 Use `org-latex-to-mathml-convert-command'. If the conversion is
18434 sucessful, return the portion between \"<math...> </math>\"
18435 elements otherwise return nil. When MATHML-FILE is specified,
18436 write the results in to that file. When invoked as an
18437 interactive command, prompt for LATEX-FRAG, with initial value
18438 set to the current active region and echo the results for user
18439 inspection."
18440 (interactive (list (let ((frag (when (org-region-active-p)
18441 (buffer-substring-no-properties
18442 (region-beginning) (region-end)))))
18443 (read-string "LaTeX Fragment: " frag nil frag))))
18444 (unless latex-frag (error "Invalid LaTeX fragment"))
18445 (let* ((tmp-in-file (file-relative-name
18446 (make-temp-name (expand-file-name "ltxmathml-in"))))
18447 (ignore (write-region latex-frag nil tmp-in-file))
18448 (tmp-out-file (file-relative-name
18449 (make-temp-name (expand-file-name "ltxmathml-out"))))
18450 (cmd (format-spec
18451 org-latex-to-mathml-convert-command
18452 `((?j . ,(shell-quote-argument
18453 (expand-file-name org-latex-to-mathml-jar-file)))
18454 (?I . ,(shell-quote-argument tmp-in-file))
18455 (?o . ,(shell-quote-argument tmp-out-file)))))
18456 mathml shell-command-output)
18457 (when (org-called-interactively-p 'any)
18458 (unless (org-format-latex-mathml-available-p)
18459 (user-error "LaTeX to MathML converter not configured")))
18460 (message "Running %s" cmd)
18461 (setq shell-command-output (shell-command-to-string cmd))
18462 (setq mathml
18463 (when (file-readable-p tmp-out-file)
18464 (with-current-buffer (find-file-noselect tmp-out-file t)
18465 (goto-char (point-min))
18466 (when (re-search-forward
18467 (concat
18468 (regexp-quote
18469 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18470 "\\(.\\|\n\\)*"
18471 (regexp-quote "</math>")) nil t)
18472 (prog1 (match-string 0) (kill-buffer))))))
18473 (cond
18474 (mathml
18475 (setq mathml
18476 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18477 (when mathml-file
18478 (write-region mathml nil mathml-file))
18479 (when (org-called-interactively-p 'any)
18480 (message mathml)))
18481 ((message "LaTeX to MathML conversion failed")
18482 (message shell-command-output)))
18483 (delete-file tmp-in-file)
18484 (when (file-exists-p tmp-out-file)
18485 (delete-file tmp-out-file))
18486 mathml))
18488 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18489 prefix &optional dir)
18490 "Use `org-create-math-formula' but check local cache first."
18491 (let* ((absprefix (expand-file-name prefix dir))
18492 (print-length nil) (print-level nil)
18493 (formula-id (concat
18494 "formula-"
18495 (sha1
18496 (prin1-to-string
18497 (list latex-frag
18498 org-latex-to-mathml-convert-command)))))
18499 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18500 (formula-cache-dir (file-name-directory formula-cache)))
18502 (unless (file-directory-p formula-cache-dir)
18503 (make-directory formula-cache-dir t))
18505 (unless (file-exists-p formula-cache)
18506 (org-create-math-formula latex-frag formula-cache))
18508 (if (file-exists-p formula-cache)
18509 ;; Successful conversion. Return the link to MathML file.
18510 (org-add-props
18511 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18512 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18513 'org-latex-src-embed-type (if latex-frag-type
18514 'paragraph 'character)))
18515 ;; Failed conversion. Return the LaTeX fragment verbatim
18516 latex-frag)))
18518 (defun org-create-formula-image (string tofile options buffer &optional type)
18519 "Create an image from LaTeX source using dvipng or convert.
18520 This function calls either `org-create-formula-image-with-dvipng'
18521 or `org-create-formula-image-with-imagemagick' depending on the
18522 value of `org-latex-create-formula-image-program' or on the value
18523 of the optional TYPE variable.
18525 Note: ultimately these two function should be combined as they
18526 share a good deal of logic."
18527 (org-check-external-command
18528 "latex" "needed to convert LaTeX fragments to images")
18529 (funcall
18530 (case (or type org-latex-create-formula-image-program)
18531 ('dvipng
18532 (org-check-external-command
18533 "dvipng" "needed to convert LaTeX fragments to images")
18534 #'org-create-formula-image-with-dvipng)
18535 ('imagemagick
18536 (org-check-external-command
18537 "convert" "you need to install imagemagick")
18538 #'org-create-formula-image-with-imagemagick)
18539 (t (error
18540 "Invalid value of `org-latex-create-formula-image-program'")))
18541 string tofile options buffer))
18543 (declare-function org-export-get-backend "ox" (name))
18544 (declare-function org-export--get-global-options "ox" (&optional backend))
18545 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18546 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18547 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18548 (defun org-create-formula--latex-header ()
18549 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18550 (let ((info (org-combine-plists (org-export--get-global-options
18551 (org-export-get-backend 'latex))
18552 (org-export--get-inbuffer-options
18553 (org-export-get-backend 'latex)))))
18554 (org-latex-guess-babel-language
18555 (org-latex-guess-inputenc
18556 (org-splice-latex-header
18557 org-format-latex-header
18558 org-latex-default-packages-alist
18559 org-latex-packages-alist t
18560 (plist-get info :latex-header)))
18561 info)))
18563 ;; This function borrows from Ganesh Swami's latex2png.el
18564 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18565 "This calls dvipng."
18566 (require 'ox-latex)
18567 (let* ((tmpdir (if (featurep 'xemacs)
18568 (temp-directory)
18569 temporary-file-directory))
18570 (texfilebase (make-temp-name
18571 (expand-file-name "orgtex" tmpdir)))
18572 (texfile (concat texfilebase ".tex"))
18573 (dvifile (concat texfilebase ".dvi"))
18574 (pngfile (concat texfilebase ".png"))
18575 (fnh (if (featurep 'xemacs)
18576 (font-height (face-font 'default))
18577 (face-attribute 'default :height nil)))
18578 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18579 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18580 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18581 "Black"))
18582 (bg (or (plist-get options (if buffer :background :html-background))
18583 "Transparent")))
18584 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18585 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18586 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18587 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18588 (let ((latex-header (org-create-formula--latex-header)))
18589 (with-temp-file texfile
18590 (insert latex-header)
18591 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18592 (let ((dir default-directory))
18593 (condition-case nil
18594 (progn
18595 (cd tmpdir)
18596 (call-process "latex" nil nil nil texfile))
18597 (error nil))
18598 (cd dir))
18599 (if (not (file-exists-p dvifile))
18600 (progn (message "Failed to create dvi file from %s" texfile) nil)
18601 (condition-case nil
18602 (if (featurep 'xemacs)
18603 (call-process "dvipng" nil nil nil
18604 "-fg" fg "-bg" bg
18605 "-T" "tight"
18606 "-o" pngfile
18607 dvifile)
18608 (call-process "dvipng" nil nil nil
18609 "-fg" fg "-bg" bg
18610 "-D" dpi
18611 ;;"-x" scale "-y" scale
18612 "-T" "tight"
18613 "-o" pngfile
18614 dvifile))
18615 (error nil))
18616 (if (not (file-exists-p pngfile))
18617 (if org-format-latex-signal-error
18618 (error "Failed to create png file from %s" texfile)
18619 (message "Failed to create png file from %s" texfile)
18620 nil)
18621 ;; Use the requested file name and clean up
18622 (copy-file pngfile tofile 'replace)
18623 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18624 (if (file-exists-p (concat texfilebase e))
18625 (delete-file (concat texfilebase e))))
18626 pngfile))))
18628 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18629 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18630 "This calls convert, which is included into imagemagick."
18631 (require 'ox-latex)
18632 (let* ((tmpdir (if (featurep 'xemacs)
18633 (temp-directory)
18634 temporary-file-directory))
18635 (texfilebase (make-temp-name
18636 (expand-file-name "orgtex" tmpdir)))
18637 (texfile (concat texfilebase ".tex"))
18638 (pdffile (concat texfilebase ".pdf"))
18639 (pngfile (concat texfilebase ".png"))
18640 (fnh (if (featurep 'xemacs)
18641 (font-height (face-font 'default))
18642 (face-attribute 'default :height nil)))
18643 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18644 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18645 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18646 "black"))
18647 (bg (or (plist-get options (if buffer :background :html-background))
18648 "white")))
18649 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18650 (setq fg (org-latex-color-format fg)))
18651 (if (eq bg 'default) (setq bg (org-latex-color :background))
18652 (setq bg (org-latex-color-format
18653 (if (string= bg "Transparent") "white" bg))))
18654 (let ((latex-header (org-create-formula--latex-header)))
18655 (with-temp-file texfile
18656 (insert latex-header)
18657 (insert "\n\\begin{document}\n"
18658 "\\definecolor{fg}{rgb}{" fg "}\n"
18659 "\\definecolor{bg}{rgb}{" bg "}\n"
18660 "\n\\pagecolor{bg}\n"
18661 "\n{\\color{fg}\n"
18662 string
18663 "\n}\n"
18664 "\n\\end{document}\n")))
18665 (org-latex-compile texfile t)
18666 (if (not (file-exists-p pdffile))
18667 (progn (message "Failed to create pdf file from %s" texfile) nil)
18668 (condition-case nil
18669 (if (featurep 'xemacs)
18670 (call-process "convert" nil nil nil
18671 "-density" "96"
18672 "-trim"
18673 "-antialias"
18674 pdffile
18675 "-quality" "100"
18676 ;; "-sharpen" "0x1.0"
18677 pngfile)
18678 (call-process "convert" nil nil nil
18679 "-density" dpi
18680 "-trim"
18681 "-antialias"
18682 pdffile
18683 "-quality" "100"
18684 ;; "-sharpen" "0x1.0"
18685 pngfile))
18686 (error nil))
18687 (if (not (file-exists-p pngfile))
18688 (if org-format-latex-signal-error
18689 (error "Failed to create png file from %s" texfile)
18690 (message "Failed to create png file from %s" texfile)
18691 nil)
18692 ;; Use the requested file name and clean up
18693 (copy-file pngfile tofile 'replace)
18694 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18695 (if (file-exists-p (concat texfilebase e))
18696 (delete-file (concat texfilebase e))))
18697 pngfile))))
18699 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18700 "Fill a LaTeX header template TPL.
18701 In the template, the following place holders will be recognized:
18703 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18704 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18705 [PACKAGES] \\usepackage statements for PKG
18706 [NO-PACKAGES] do not include PKG
18707 [EXTRA] the string EXTRA
18708 [NO-EXTRA] do not include EXTRA
18710 For backward compatibility, if both the positive and the negative place
18711 holder is missing, the positive one (without the \"NO-\") will be
18712 assumed to be present at the end of the template.
18713 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18714 EXTRA is a string.
18715 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18716 (let (rpl (end ""))
18717 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18718 (setq rpl (if (or (match-end 1) (not def-pkg))
18719 "" (org-latex-packages-to-string def-pkg snippets-p t))
18720 tpl (replace-match rpl t t tpl))
18721 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18723 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18724 (setq rpl (if (or (match-end 1) (not pkg))
18725 "" (org-latex-packages-to-string pkg snippets-p t))
18726 tpl (replace-match rpl t t tpl))
18727 (if pkg (setq end
18728 (concat end "\n"
18729 (org-latex-packages-to-string pkg snippets-p)))))
18731 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18732 (setq rpl (if (or (match-end 1) (not extra))
18733 "" (concat extra "\n"))
18734 tpl (replace-match rpl t t tpl))
18735 (if (and extra (string-match "\\S-" extra))
18736 (setq end (concat end "\n" extra))))
18738 (if (string-match "\\S-" end)
18739 (concat tpl "\n" end)
18740 tpl)))
18742 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18743 "Turn an alist of packages into a string with the \\usepackage macros."
18744 (setq pkg (mapconcat (lambda(p)
18745 (cond
18746 ((stringp p) p)
18747 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18748 (format "%% Package %s omitted" (cadr p)))
18749 ((equal "" (car p))
18750 (format "\\usepackage{%s}" (cadr p)))
18752 (format "\\usepackage[%s]{%s}"
18753 (car p) (cadr p)))))
18755 "\n"))
18756 (if newline (concat pkg "\n") pkg))
18758 (defun org-dvipng-color (attr)
18759 "Return a RGB color specification for dvipng."
18760 (apply 'format "rgb %s %s %s"
18761 (mapcar 'org-normalize-color
18762 (if (featurep 'xemacs)
18763 (color-rgb-components
18764 (face-property 'default
18765 (cond ((eq attr :foreground) 'foreground)
18766 ((eq attr :background) 'background))))
18767 (color-values (face-attribute 'default attr nil))))))
18769 (defun org-dvipng-color-format (color-name)
18770 "Convert COLOR-NAME to a RGB color value for dvipng."
18771 (apply 'format "rgb %s %s %s"
18772 (mapcar 'org-normalize-color
18773 (color-values color-name))))
18775 (defun org-latex-color (attr)
18776 "Return a RGB color for the LaTeX color package."
18777 (apply 'format "%s,%s,%s"
18778 (mapcar 'org-normalize-color
18779 (if (featurep 'xemacs)
18780 (color-rgb-components
18781 (face-property 'default
18782 (cond ((eq attr :foreground) 'foreground)
18783 ((eq attr :background) 'background))))
18784 (color-values (face-attribute 'default attr nil))))))
18786 (defun org-latex-color-format (color-name)
18787 "Convert COLOR-NAME to a RGB color value."
18788 (apply 'format "%s,%s,%s"
18789 (mapcar 'org-normalize-color
18790 (color-values color-name))))
18792 (defun org-normalize-color (value)
18793 "Return string to be used as color value for an RGB component."
18794 (format "%g" (/ value 65535.0)))
18798 ;; Image display
18800 (defvar org-inline-image-overlays nil)
18801 (make-variable-buffer-local 'org-inline-image-overlays)
18803 (defun org-toggle-inline-images (&optional include-linked)
18804 "Toggle the display of inline images.
18805 INCLUDE-LINKED is passed to `org-display-inline-images'."
18806 (interactive "P")
18807 (if org-inline-image-overlays
18808 (progn
18809 (org-remove-inline-images)
18810 (message "Inline image display turned off"))
18811 (org-display-inline-images include-linked)
18812 (if (and (org-called-interactively-p)
18813 org-inline-image-overlays)
18814 (message "%d images displayed inline"
18815 (length org-inline-image-overlays))
18816 (message "No images to display inline"))))
18818 (defun org-redisplay-inline-images ()
18819 "Refresh the display of inline images."
18820 (interactive)
18821 (if (not org-inline-image-overlays)
18822 (org-toggle-inline-images)
18823 (org-toggle-inline-images)
18824 (org-toggle-inline-images)))
18826 (defun org-display-inline-images (&optional include-linked refresh beg end)
18827 "Display inline images.
18828 Normally only links without a description part are inlined, because this
18829 is how it will work for export. When INCLUDE-LINKED is set, also links
18830 with a description part will be inlined. This can be nice for a quick
18831 look at those images, but it does not reflect what exported files will look
18832 like.
18833 When REFRESH is set, refresh existing images between BEG and END.
18834 This will create new image displays only if necessary.
18835 BEG and END default to the buffer boundaries."
18836 (interactive "P")
18837 (when (display-graphic-p)
18838 (unless refresh
18839 (org-remove-inline-images)
18840 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18841 (save-excursion
18842 (save-restriction
18843 (widen)
18844 (setq beg (or beg (point-min)) end (or end (point-max)))
18845 (goto-char beg)
18846 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18847 (substring (org-image-file-name-regexp) 0 -2)
18848 "\\)\\]" (if include-linked "" "\\]")))
18849 (case-fold-search t)
18850 old file ov img type attrwidth width)
18851 (while (re-search-forward re end t)
18852 (setq old (get-char-property-and-overlay (match-beginning 1)
18853 'org-image-overlay)
18854 file (expand-file-name
18855 (concat (or (match-string 3) "") (match-string 4))))
18856 (when (image-type-available-p 'imagemagick)
18857 (setq attrwidth (if (or (listp org-image-actual-width)
18858 (null org-image-actual-width))
18859 (save-excursion
18860 (save-match-data
18861 (when (re-search-backward
18862 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18863 (save-excursion
18864 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18865 (string-to-number (match-string 1))))))
18866 width (cond ((eq org-image-actual-width t) nil)
18867 ((null org-image-actual-width) attrwidth)
18868 ((numberp org-image-actual-width)
18869 org-image-actual-width)
18870 ((listp org-image-actual-width)
18871 (or attrwidth (car org-image-actual-width))))
18872 type (if width 'imagemagick)))
18873 (when (file-exists-p file)
18874 (if (and (car-safe old) refresh)
18875 (image-refresh (overlay-get (cdr old) 'display))
18876 (setq img (save-match-data (create-image file type nil :width width)))
18877 (when img
18878 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18879 (overlay-put ov 'display img)
18880 (overlay-put ov 'face 'default)
18881 (overlay-put ov 'org-image-overlay t)
18882 (overlay-put ov 'modification-hooks
18883 (list 'org-display-inline-remove-overlay))
18884 (push ov org-inline-image-overlays))))))))))
18886 (define-obsolete-function-alias
18887 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18889 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18890 "Remove inline-display overlay if a corresponding region is modified."
18891 (let ((inhibit-modification-hooks t))
18892 (when (and ov after)
18893 (delete ov org-inline-image-overlays)
18894 (delete-overlay ov))))
18896 (defun org-remove-inline-images ()
18897 "Remove inline display of images."
18898 (interactive)
18899 (mapc 'delete-overlay org-inline-image-overlays)
18900 (setq org-inline-image-overlays nil))
18902 ;;;; Key bindings
18904 ;; Outline functions from `outline-mode-prefix-map'
18905 ;; that can be remapped in Org:
18906 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18907 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18908 (define-key org-mode-map [remap outline-forward-same-level]
18909 'org-forward-heading-same-level)
18910 (define-key org-mode-map [remap outline-backward-same-level]
18911 'org-backward-heading-same-level)
18912 (define-key org-mode-map [remap show-branches]
18913 'org-kill-note-or-show-branches)
18914 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18915 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18916 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18918 ;; Outline functions from `outline-mode-prefix-map' that can not
18919 ;; be remapped in Org:
18921 ;; - the column "key binding" shows whether the Outline function is still
18922 ;; available in Org mode on the same key that it has been bound to in
18923 ;; Outline mode:
18924 ;; - "overridden": key used for a different functionality in Org mode
18925 ;; - else: key still bound to the same Outline function in Org mode
18927 ;; | Outline function | key binding | Org replacement |
18928 ;; |------------------------------------+-------------+-----------------------|
18929 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18930 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18931 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18932 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18933 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18934 ;; | `show-entry' | overridden | no replacement |
18935 ;; | `show-children' | `C-c C-i' | visibility cycling |
18936 ;; | `show-branches' | `C-c C-k' | still same function |
18937 ;; | `show-subtree' | overridden | visibility cycling |
18938 ;; | `show-all' | overridden | no replacement |
18939 ;; | `hide-subtree' | overridden | visibility cycling |
18940 ;; | `hide-body' | overridden | no replacement |
18941 ;; | `hide-entry' | overridden | visibility cycling |
18942 ;; | `hide-leaves' | overridden | no replacement |
18943 ;; | `hide-sublevels' | overridden | no replacement |
18944 ;; | `hide-other' | overridden | no replacement |
18946 ;; Make `C-c C-x' a prefix key
18947 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18949 ;; TAB key with modifiers
18950 (org-defkey org-mode-map "\C-i" 'org-cycle)
18951 (org-defkey org-mode-map [(tab)] 'org-cycle)
18952 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18953 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18954 ;; The following line is necessary under Suse GNU/Linux
18955 (unless (featurep 'xemacs)
18956 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18957 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18958 (define-key org-mode-map [backtab] 'org-shifttab)
18960 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18961 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18962 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18964 ;; Cursor keys with modifiers
18965 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18966 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18967 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18968 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18970 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18971 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18972 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18973 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18975 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18976 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18977 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18978 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18980 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18981 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18982 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18983 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18985 ;; Babel keys
18986 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18987 (mapc (lambda (pair)
18988 (define-key org-babel-map (car pair) (cdr pair)))
18989 org-babel-key-bindings)
18991 ;;; Extra keys for tty access.
18992 ;; We only set them when really needed because otherwise the
18993 ;; menus don't show the simple keys
18995 (when (or org-use-extra-keys
18996 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18997 (not window-system))
18998 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18999 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19000 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19001 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19002 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19003 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19004 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19005 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19006 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19007 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19008 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19009 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19010 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19011 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19012 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19013 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19014 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19015 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19016 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19017 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19018 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19019 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19020 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19021 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19022 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19023 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19024 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19025 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19027 ;; All the other keys
19029 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19030 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19031 (if (boundp 'narrow-map)
19032 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19033 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19034 (if (boundp 'narrow-map)
19035 (org-defkey narrow-map "b" 'org-narrow-to-block)
19036 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19037 (if (boundp 'narrow-map)
19038 (org-defkey narrow-map "e" 'org-narrow-to-element)
19039 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19040 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19041 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19042 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19043 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19044 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19045 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19046 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19047 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19048 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19049 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19050 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19051 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19052 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19053 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19054 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19055 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19056 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19057 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19058 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19059 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19060 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19061 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19062 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19063 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19064 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19065 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19066 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19067 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19068 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19069 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19070 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19071 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19072 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19073 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19074 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19075 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19076 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19077 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19078 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19079 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19080 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19081 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19082 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19083 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19084 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19085 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19086 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19087 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19088 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19089 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19090 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19091 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19092 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19093 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19094 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19095 (org-defkey org-mode-map "\C-c^" 'org-sort)
19096 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19097 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19098 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19099 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19100 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19101 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19102 (org-defkey org-mode-map "\C-m" 'org-return)
19103 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19104 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19105 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19106 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19107 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19108 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19109 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19110 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19111 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19112 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19113 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19114 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19115 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19116 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19117 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19118 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19119 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19120 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19121 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19122 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19123 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19124 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19125 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19127 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19128 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19129 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19131 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19132 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19133 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19134 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19135 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19136 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19137 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19138 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19139 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19140 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19141 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19142 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19143 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19144 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19145 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19146 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19147 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19148 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19149 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19150 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19151 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19152 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19153 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19155 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19156 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19157 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19158 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19159 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19161 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19163 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19165 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19166 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19168 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19171 (when (featurep 'xemacs)
19172 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19175 (defconst org-speed-commands-default
19177 ("Outline Navigation")
19178 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19179 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19180 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19181 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19182 ("F" . org-next-block)
19183 ("B" . org-previous-block)
19184 ("u" . (org-speed-move-safe 'outline-up-heading))
19185 ("j" . org-goto)
19186 ("g" . (org-refile t))
19187 ("Outline Visibility")
19188 ("c" . org-cycle)
19189 ("C" . org-shifttab)
19190 (" " . org-display-outline-path)
19191 ("s" . org-narrow-to-subtree)
19192 ("=" . org-columns)
19193 ("Outline Structure Editing")
19194 ("U" . org-shiftmetaup)
19195 ("D" . org-shiftmetadown)
19196 ("r" . org-metaright)
19197 ("l" . org-metaleft)
19198 ("R" . org-shiftmetaright)
19199 ("L" . org-shiftmetaleft)
19200 ("i" . (progn (forward-char 1) (call-interactively
19201 'org-insert-heading-respect-content)))
19202 ("^" . org-sort)
19203 ("w" . org-refile)
19204 ("a" . org-archive-subtree-default-with-confirmation)
19205 ("@" . org-mark-subtree)
19206 ("#" . org-toggle-comment)
19207 ("Clock Commands")
19208 ("I" . org-clock-in)
19209 ("O" . org-clock-out)
19210 ("Meta Data Editing")
19211 ("t" . org-todo)
19212 ("," . (org-priority))
19213 ("0" . (org-priority ?\ ))
19214 ("1" . (org-priority ?A))
19215 ("2" . (org-priority ?B))
19216 ("3" . (org-priority ?C))
19217 (":" . org-set-tags-command)
19218 ("e" . org-set-effort)
19219 ("E" . org-inc-effort)
19220 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19221 (org-entry-put (point) "APPT_WARNTIME" m)))
19222 ("Agenda Views etc")
19223 ("v" . org-agenda)
19224 ("/" . org-sparse-tree)
19225 ("Misc")
19226 ("o" . org-open-at-point)
19227 ("?" . org-speed-command-help)
19228 ("<" . (org-agenda-set-restriction-lock 'subtree))
19229 (">" . (org-agenda-remove-restriction-lock))
19231 "The default speed commands.")
19233 (defun org-print-speed-command (e)
19234 (if (> (length (car e)) 1)
19235 (progn
19236 (princ "\n")
19237 (princ (car e))
19238 (princ "\n")
19239 (princ (make-string (length (car e)) ?-))
19240 (princ "\n"))
19241 (princ (car e))
19242 (princ " ")
19243 (if (symbolp (cdr e))
19244 (princ (symbol-name (cdr e)))
19245 (prin1 (cdr e)))
19246 (princ "\n")))
19248 (defun org-speed-command-help ()
19249 "Show the available speed commands."
19250 (interactive)
19251 (if (not org-use-speed-commands)
19252 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19253 (with-output-to-temp-buffer "*Help*"
19254 (princ "User-defined Speed commands\n===========================\n")
19255 (mapc 'org-print-speed-command org-speed-commands-user)
19256 (princ "\n")
19257 (princ "Built-in Speed commands\n=======================\n")
19258 (mapc 'org-print-speed-command org-speed-commands-default))
19259 (with-current-buffer "*Help*"
19260 (setq truncate-lines t))))
19262 (defun org-speed-move-safe (cmd)
19263 "Execute CMD, but make sure that the cursor always ends up in a headline.
19264 If not, return to the original position and throw an error."
19265 (interactive)
19266 (let ((pos (point)))
19267 (call-interactively cmd)
19268 (unless (and (bolp) (org-at-heading-p))
19269 (goto-char pos)
19270 (error "Boundary reached while executing %s" cmd))))
19272 (defvar org-self-insert-command-undo-counter 0)
19274 (defvar org-table-auto-blank-field) ; defined in org-table.el
19275 (defvar org-speed-command nil)
19277 (define-obsolete-function-alias
19278 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19280 (defun org-speed-command-activate (keys)
19281 "Hook for activating single-letter speed commands.
19282 `org-speed-commands-default' specifies a minimal command set.
19283 Use `org-speed-commands-user' for further customization."
19284 (when (or (and (bolp) (looking-at org-outline-regexp))
19285 (and (functionp org-use-speed-commands)
19286 (funcall org-use-speed-commands)))
19287 (cdr (assoc keys (append org-speed-commands-user
19288 org-speed-commands-default)))))
19290 (define-obsolete-function-alias
19291 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19293 (defun org-babel-speed-command-activate (keys)
19294 "Hook for activating single-letter code block commands."
19295 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19296 (cdr (assoc keys org-babel-key-bindings))))
19298 (defcustom org-speed-command-hook
19299 '(org-speed-command-default-hook org-babel-speed-command-hook)
19300 "Hook for activating speed commands at strategic locations.
19301 Hook functions are called in sequence until a valid handler is
19302 found.
19304 Each hook takes a single argument, a user-pressed command key
19305 which is also a `self-insert-command' from the global map.
19307 Within the hook, examine the cursor position and the command key
19308 and return nil or a valid handler as appropriate. Handler could
19309 be one of an interactive command, a function, or a form.
19311 Set `org-use-speed-commands' to non-nil value to enable this
19312 hook. The default setting is `org-speed-command-activate'."
19313 :group 'org-structure
19314 :version "24.1"
19315 :type 'hook)
19317 (defun org-self-insert-command (N)
19318 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19319 If the cursor is in a table looking at whitespace, the whitespace is
19320 overwritten, and the table is not marked as requiring realignment."
19321 (interactive "p")
19322 (org-check-before-invisible-edit 'insert)
19323 (cond
19324 ((and org-use-speed-commands
19325 (setq org-speed-command
19326 (run-hook-with-args-until-success
19327 'org-speed-command-hook (this-command-keys))))
19328 (cond
19329 ((commandp org-speed-command)
19330 (setq this-command org-speed-command)
19331 (call-interactively org-speed-command))
19332 ((functionp org-speed-command)
19333 (funcall org-speed-command))
19334 ((and org-speed-command (listp org-speed-command))
19335 (eval org-speed-command))
19336 (t (let (org-use-speed-commands)
19337 (call-interactively 'org-self-insert-command)))))
19338 ((and
19339 (org-table-p)
19340 (progn
19341 ;; check if we blank the field, and if that triggers align
19342 (and (featurep 'org-table) org-table-auto-blank-field
19343 (member last-command
19344 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19345 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19346 ;; got extra space, this field does not determine column width
19347 (let (org-table-may-need-update) (org-table-blank-field))
19348 ;; no extra space, this field may determine column width
19349 (org-table-blank-field)))
19351 (eq N 1)
19352 (looking-at "[^|\n]* |"))
19353 (let (org-table-may-need-update)
19354 (goto-char (1- (match-end 0)))
19355 (backward-delete-char 1)
19356 (goto-char (match-beginning 0))
19357 (self-insert-command N)))
19359 (setq org-table-may-need-update t)
19360 (self-insert-command N)
19361 (org-fix-tags-on-the-fly)
19362 (if org-self-insert-cluster-for-undo
19363 (if (not (eq last-command 'org-self-insert-command))
19364 (setq org-self-insert-command-undo-counter 1)
19365 (if (>= org-self-insert-command-undo-counter 20)
19366 (setq org-self-insert-command-undo-counter 1)
19367 (and (> org-self-insert-command-undo-counter 0)
19368 buffer-undo-list (listp buffer-undo-list)
19369 (not (cadr buffer-undo-list)) ; remove nil entry
19370 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19371 (setq org-self-insert-command-undo-counter
19372 (1+ org-self-insert-command-undo-counter))))))))
19374 (defun org-check-before-invisible-edit (kind)
19375 "Check is editing if kind KIND would be dangerous with invisible text around.
19376 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19377 ;; First, try to get out of here as quickly as possible, to reduce overhead
19378 (if (and org-catch-invisible-edits
19379 (or (not (boundp 'visible-mode)) (not visible-mode))
19380 (or (get-char-property (point) 'invisible)
19381 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19382 ;; OK, we need to take a closer look
19383 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19384 (invisible-before-point (if (bobp) nil (get-char-property
19385 (1- (point)) 'invisible)))
19386 (border-and-ok-direction
19388 ;; Check if we are acting predictably before invisible text
19389 (and invisible-at-point (not invisible-before-point)
19390 (memq kind '(insert delete-backward)))
19391 ;; Check if we are acting predictably after invisible text
19392 ;; This works not well, and I have turned it off. It seems
19393 ;; better to always show and stop after invisible text.
19394 ;; (and (not invisible-at-point) invisible-before-point
19395 ;; (memq kind '(insert delete)))
19397 (when (or (memq invisible-at-point '(outline org-hide-block t))
19398 (memq invisible-before-point '(outline org-hide-block t)))
19399 (if (eq org-catch-invisible-edits 'error)
19400 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19401 (if (and org-custom-properties-overlays
19402 (y-or-n-p "Display invisible properties in this buffer? "))
19403 (org-toggle-custom-properties-visibility)
19404 ;; Make the area visible
19405 (save-excursion
19406 (if invisible-before-point
19407 (goto-char (previous-single-char-property-change
19408 (point) 'invisible)))
19409 (org-cycle))
19410 (cond
19411 ((eq org-catch-invisible-edits 'show)
19412 ;; That's it, we do the edit after showing
19413 (message
19414 "Unfolding invisible region around point before editing")
19415 (sit-for 1))
19416 ((and (eq org-catch-invisible-edits 'smart)
19417 border-and-ok-direction)
19418 (message "Unfolding invisible region around point before editing"))
19420 ;; Don't do the edit, make the user repeat it in full visibility
19421 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19423 (defun org-fix-tags-on-the-fly ()
19424 (when (and (equal (char-after (point-at-bol)) ?*)
19425 (org-at-heading-p))
19426 (org-align-tags-here org-tags-column)))
19428 (defun org-delete-backward-char (N)
19429 "Like `delete-backward-char', insert whitespace at field end in tables.
19430 When deleting backwards, in tables this function will insert whitespace in
19431 front of the next \"|\" separator, to keep the table aligned. The table will
19432 still be marked for re-alignment if the field did fill the entire column,
19433 because, in this case the deletion might narrow the column."
19434 (interactive "p")
19435 (save-match-data
19436 (org-check-before-invisible-edit 'delete-backward)
19437 (if (and (org-table-p)
19438 (eq N 1)
19439 (string-match "|" (buffer-substring (point-at-bol) (point)))
19440 (looking-at ".*?|"))
19441 (let ((pos (point))
19442 (noalign (looking-at "[^|\n\r]* |"))
19443 (c org-table-may-need-update))
19444 (backward-delete-char N)
19445 (if (not overwrite-mode)
19446 (progn
19447 (skip-chars-forward "^|")
19448 (insert " ")
19449 (goto-char (1- pos))))
19450 ;; noalign: if there were two spaces at the end, this field
19451 ;; does not determine the width of the column.
19452 (if noalign (setq org-table-may-need-update c)))
19453 (backward-delete-char N)
19454 (org-fix-tags-on-the-fly))))
19456 (defun org-delete-char (N)
19457 "Like `delete-char', but insert whitespace at field end in tables.
19458 When deleting characters, 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)
19465 (if (and (org-table-p)
19466 (not (bolp))
19467 (not (= (char-after) ?|))
19468 (eq N 1))
19469 (if (looking-at ".*?|")
19470 (let ((pos (point))
19471 (noalign (looking-at "[^|\n\r]* |"))
19472 (c org-table-may-need-update))
19473 (replace-match
19474 (concat (substring (match-string 0) 1 -1) " |") nil t)
19475 (goto-char pos)
19476 ;; noalign: if there were two spaces at the end, this field
19477 ;; does not determine the width of the column.
19478 (if noalign (setq org-table-may-need-update c)))
19479 (delete-char N))
19480 (delete-char N)
19481 (org-fix-tags-on-the-fly))))
19483 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19484 (put 'org-self-insert-command 'delete-selection t)
19485 (put 'orgtbl-self-insert-command 'delete-selection t)
19486 (put 'org-delete-char 'delete-selection 'supersede)
19487 (put 'org-delete-backward-char 'delete-selection 'supersede)
19488 (put 'org-yank 'delete-selection 'yank)
19490 ;; Make `flyspell-mode' delay after some commands
19491 (put 'org-self-insert-command 'flyspell-delayed t)
19492 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19493 (put 'org-delete-char 'flyspell-delayed t)
19494 (put 'org-delete-backward-char 'flyspell-delayed t)
19496 ;; Make pabbrev-mode expand after org-mode commands
19497 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19498 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19500 ;; How to do this: Measure non-white length of current string
19501 ;; If equal to column width, we should realign.
19503 (defun org-remap (map &rest commands)
19504 "In MAP, remap the functions given in COMMANDS.
19505 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19506 (let (new old)
19507 (while commands
19508 (setq old (pop commands) new (pop commands))
19509 (if (fboundp 'command-remapping)
19510 (org-defkey map (vector 'remap old) new)
19511 (substitute-key-definition old new map global-map)))))
19513 (defun org-transpose-words ()
19514 "Transpose words for Org.
19515 This uses the `org-mode-transpose-word-syntax-table' syntax
19516 table, which interprets characters in `org-emphasis-alist' as
19517 word constituants."
19518 (interactive)
19519 (with-syntax-table org-mode-transpose-word-syntax-table
19520 (call-interactively 'transpose-words)))
19521 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19523 (when (eq org-enable-table-editor 'optimized)
19524 ;; If the user wants maximum table support, we need to hijack
19525 ;; some standard editing functions
19526 (org-remap org-mode-map
19527 'self-insert-command 'org-self-insert-command
19528 'delete-char 'org-delete-char
19529 'delete-backward-char 'org-delete-backward-char)
19530 (org-defkey org-mode-map "|" 'org-force-self-insert))
19532 (defvar org-ctrl-c-ctrl-c-hook nil
19533 "Hook for functions attaching themselves to `C-c C-c'.
19535 This can be used to add additional functionality to the C-c C-c
19536 key which executes context-dependent commands. This hook is run
19537 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19538 run after the last test.
19540 Each function will be called with no arguments. The function
19541 must check if the context is appropriate for it to act. If yes,
19542 it should do its thing and then return a non-nil value. If the
19543 context is wrong, just do nothing and return nil.")
19545 (defvar org-ctrl-c-ctrl-c-final-hook nil
19546 "Hook for functions attaching themselves to `C-c C-c'.
19548 This can be used to add additional functionality to the C-c C-c
19549 key which executes context-dependent commands. This hook is run
19550 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19551 before the first test.
19553 Each function will be called with no arguments. The function
19554 must check if the context is appropriate for it to act. If yes,
19555 it should do its thing and then return a non-nil value. If the
19556 context is wrong, just do nothing and return nil.")
19558 (defvar org-tab-first-hook nil
19559 "Hook for functions to attach themselves to TAB.
19560 See `org-ctrl-c-ctrl-c-hook' for more information.
19561 This hook runs as the first action when TAB is pressed, even before
19562 `org-cycle' messes around with the `outline-regexp' to cater for
19563 inline tasks and plain list item folding.
19564 If any function in this hook returns t, any other actions that
19565 would have been caused by TAB (such as table field motion or visibility
19566 cycling) will not occur.")
19568 (defvar org-tab-after-check-for-table-hook nil
19569 "Hook for functions to attach themselves to TAB.
19570 See `org-ctrl-c-ctrl-c-hook' for more information.
19571 This hook runs after it has been established that the cursor is not in a
19572 table, but before checking if the cursor is in a headline or if global cycling
19573 should be done.
19574 If any function in this hook returns t, not other actions like visibility
19575 cycling will be done.")
19577 (defvar org-tab-after-check-for-cycling-hook nil
19578 "Hook for functions to attach themselves to TAB.
19579 See `org-ctrl-c-ctrl-c-hook' for more information.
19580 This hook runs after it has been established that not table field motion and
19581 not visibility should be done because of current context. This is probably
19582 the place where a package like yasnippets can hook in.")
19584 (defvar org-tab-before-tab-emulation-hook nil
19585 "Hook for functions to attach themselves to TAB.
19586 See `org-ctrl-c-ctrl-c-hook' for more information.
19587 This hook runs after every other options for TAB have been exhausted, but
19588 before indentation and \t insertion takes place.")
19590 (defvar org-metaleft-hook nil
19591 "Hook for functions attaching themselves to `M-left'.
19592 See `org-ctrl-c-ctrl-c-hook' for more information.")
19593 (defvar org-metaright-hook nil
19594 "Hook for functions attaching themselves to `M-right'.
19595 See `org-ctrl-c-ctrl-c-hook' for more information.")
19596 (defvar org-metaup-hook nil
19597 "Hook for functions attaching themselves to `M-up'.
19598 See `org-ctrl-c-ctrl-c-hook' for more information.")
19599 (defvar org-metadown-hook nil
19600 "Hook for functions attaching themselves to `M-down'.
19601 See `org-ctrl-c-ctrl-c-hook' for more information.")
19602 (defvar org-shiftmetaleft-hook nil
19603 "Hook for functions attaching themselves to `M-S-left'.
19604 See `org-ctrl-c-ctrl-c-hook' for more information.")
19605 (defvar org-shiftmetaright-hook nil
19606 "Hook for functions attaching themselves to `M-S-right'.
19607 See `org-ctrl-c-ctrl-c-hook' for more information.")
19608 (defvar org-shiftmetaup-hook nil
19609 "Hook for functions attaching themselves to `M-S-up'.
19610 See `org-ctrl-c-ctrl-c-hook' for more information.")
19611 (defvar org-shiftmetadown-hook nil
19612 "Hook for functions attaching themselves to `M-S-down'.
19613 See `org-ctrl-c-ctrl-c-hook' for more information.")
19614 (defvar org-metareturn-hook nil
19615 "Hook for functions attaching themselves to `M-RET'.
19616 See `org-ctrl-c-ctrl-c-hook' for more information.")
19617 (defvar org-shiftup-hook nil
19618 "Hook for functions attaching themselves to `S-up'.
19619 See `org-ctrl-c-ctrl-c-hook' for more information.")
19620 (defvar org-shiftup-final-hook nil
19621 "Hook for functions attaching themselves to `S-up'.
19622 This one runs after all other options except shift-select have been excluded.
19623 See `org-ctrl-c-ctrl-c-hook' for more information.")
19624 (defvar org-shiftdown-hook nil
19625 "Hook for functions attaching themselves to `S-down'.
19626 See `org-ctrl-c-ctrl-c-hook' for more information.")
19627 (defvar org-shiftdown-final-hook nil
19628 "Hook for functions attaching themselves to `S-down'.
19629 This one runs after all other options except shift-select have been excluded.
19630 See `org-ctrl-c-ctrl-c-hook' for more information.")
19631 (defvar org-shiftleft-hook nil
19632 "Hook for functions attaching themselves to `S-left'.
19633 See `org-ctrl-c-ctrl-c-hook' for more information.")
19634 (defvar org-shiftleft-final-hook nil
19635 "Hook for functions attaching themselves to `S-left'.
19636 This one runs after all other options except shift-select have been excluded.
19637 See `org-ctrl-c-ctrl-c-hook' for more information.")
19638 (defvar org-shiftright-hook nil
19639 "Hook for functions attaching themselves to `S-right'.
19640 See `org-ctrl-c-ctrl-c-hook' for more information.")
19641 (defvar org-shiftright-final-hook nil
19642 "Hook for functions attaching themselves to `S-right'.
19643 This one runs after all other options except shift-select have been excluded.
19644 See `org-ctrl-c-ctrl-c-hook' for more information.")
19646 (defun org-modifier-cursor-error ()
19647 "Throw an error, a modified cursor command was applied in wrong context."
19648 (user-error "This command is active in special context like tables, headlines or items"))
19650 (defun org-shiftselect-error ()
19651 "Throw an error because Shift-Cursor command was applied in wrong context."
19652 (if (and (boundp 'shift-select-mode) shift-select-mode)
19653 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19654 (user-error "This command works only in special context like headlines or timestamps")))
19656 (defun org-call-for-shift-select (cmd)
19657 (let ((this-command-keys-shift-translated t))
19658 (call-interactively cmd)))
19660 (defun org-shifttab (&optional arg)
19661 "Global visibility cycling or move to previous table field.
19662 Call `org-table-previous-field' within a table.
19663 When ARG is nil, cycle globally through visibility states.
19664 When ARG is a numeric prefix, show contents of this level."
19665 (interactive "P")
19666 (cond
19667 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19668 ((integerp arg)
19669 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19670 (message "Content view to level: %d" arg)
19671 (org-content (prefix-numeric-value arg2))
19672 (org-cycle-show-empty-lines t)
19673 (setq org-cycle-global-status 'overview)))
19674 (t (call-interactively 'org-global-cycle))))
19676 (defun org-shiftmetaleft ()
19677 "Promote subtree or delete table column.
19678 Calls `org-promote-subtree', `org-outdent-item-tree', or
19679 `org-table-delete-column', depending on context. See the
19680 individual commands for more information."
19681 (interactive)
19682 (cond
19683 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19684 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19685 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19686 ((if (not (org-region-active-p)) (org-at-item-p)
19687 (save-excursion (goto-char (region-beginning))
19688 (org-at-item-p)))
19689 (call-interactively 'org-outdent-item-tree))
19690 (t (org-modifier-cursor-error))))
19692 (defun org-shiftmetaright ()
19693 "Demote subtree or insert table column.
19694 Calls `org-demote-subtree', `org-indent-item-tree', or
19695 `org-table-insert-column', depending on context. See the
19696 individual commands for more information."
19697 (interactive)
19698 (cond
19699 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19700 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19701 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19702 ((if (not (org-region-active-p)) (org-at-item-p)
19703 (save-excursion (goto-char (region-beginning))
19704 (org-at-item-p)))
19705 (call-interactively 'org-indent-item-tree))
19706 (t (org-modifier-cursor-error))))
19708 (defun org-shiftmetaup (&optional arg)
19709 "Move subtree up or kill table row.
19710 Calls `org-move-subtree-up' or `org-table-kill-row' or
19711 `org-move-item-up' or `org-timestamp-up', depending on context.
19712 See the individual commands for more information."
19713 (interactive "P")
19714 (cond
19715 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19716 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19717 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19718 ((org-at-item-p) (call-interactively 'org-move-item-up))
19719 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19720 (call-interactively 'org-timestamp-up)))
19721 (t (call-interactively 'org-drag-line-backward))))
19723 (defun org-shiftmetadown (&optional arg)
19724 "Move subtree down or insert table row.
19725 Calls `org-move-subtree-down' or `org-table-insert-row' or
19726 `org-move-item-down' or `org-timestamp-up', depending on context.
19727 See the individual commands for more information."
19728 (interactive "P")
19729 (cond
19730 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19731 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19732 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19733 ((org-at-item-p) (call-interactively 'org-move-item-down))
19734 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19735 (call-interactively 'org-timestamp-down)))
19736 (t (call-interactively 'org-drag-line-forward))))
19738 (defsubst org-hidden-tree-error ()
19739 (user-error
19740 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19742 (defun org-metaleft (&optional arg)
19743 "Promote heading or move table column to left.
19744 Calls `org-do-promote' or `org-table-move-column', depending on context.
19745 With no specific context, calls the Emacs default `backward-word'.
19746 See the individual commands for more information."
19747 (interactive "P")
19748 (cond
19749 ((run-hook-with-args-until-success 'org-metaleft-hook))
19750 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19751 ((org-with-limited-levels
19752 (or (org-at-heading-p)
19753 (and (org-region-active-p)
19754 (save-excursion
19755 (goto-char (region-beginning))
19756 (org-at-heading-p)))))
19757 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19758 (call-interactively 'org-do-promote))
19759 ;; At an inline task.
19760 ((org-at-heading-p)
19761 (call-interactively 'org-inlinetask-promote))
19762 ((or (org-at-item-p)
19763 (and (org-region-active-p)
19764 (save-excursion
19765 (goto-char (region-beginning))
19766 (org-at-item-p))))
19767 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19768 (call-interactively 'org-outdent-item))
19769 (t (call-interactively 'backward-word))))
19771 (defun org-metaright (&optional arg)
19772 "Demote a subtree, a list item or move table column to right.
19773 In front of a drawer or a block keyword, indent it correctly.
19774 With no specific context, calls the Emacs default `forward-word'.
19775 See the individual commands for more information."
19776 (interactive "P")
19777 (cond
19778 ((run-hook-with-args-until-success 'org-metaright-hook))
19779 ((org-at-table-p) (call-interactively 'org-table-move-column))
19780 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19781 ((org-at-block-p) (call-interactively 'org-indent-block))
19782 ((org-with-limited-levels
19783 (or (org-at-heading-p)
19784 (and (org-region-active-p)
19785 (save-excursion
19786 (goto-char (region-beginning))
19787 (org-at-heading-p)))))
19788 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19789 (call-interactively 'org-do-demote))
19790 ;; At an inline task.
19791 ((org-at-heading-p)
19792 (call-interactively 'org-inlinetask-demote))
19793 ((or (org-at-item-p)
19794 (and (org-region-active-p)
19795 (save-excursion
19796 (goto-char (region-beginning))
19797 (org-at-item-p))))
19798 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19799 (call-interactively 'org-indent-item))
19800 (t (call-interactively 'forward-word))))
19802 (defun org-check-for-hidden (what)
19803 "Check if there are hidden headlines/items in the current visual line.
19804 WHAT can be either `headlines' or `items'. If the current line is
19805 an outline or item heading and it has a folded subtree below it,
19806 this function returns t, nil otherwise."
19807 (let ((re (cond
19808 ((eq what 'headlines) org-outline-regexp-bol)
19809 ((eq what 'items) (org-item-beginning-re))
19810 (t (error "This should not happen"))))
19811 beg end)
19812 (save-excursion
19813 (catch 'exit
19814 (unless (org-region-active-p)
19815 (setq beg (point-at-bol))
19816 (beginning-of-line 2)
19817 (while (and (not (eobp)) ;; this is like `next-line'
19818 (get-char-property (1- (point)) 'invisible))
19819 (beginning-of-line 2))
19820 (setq end (point))
19821 (goto-char beg)
19822 (goto-char (point-at-eol))
19823 (setq end (max end (point)))
19824 (while (re-search-forward re end t)
19825 (if (get-char-property (match-beginning 0) 'invisible)
19826 (throw 'exit t))))
19827 nil))))
19829 (defun org-metaup (&optional arg)
19830 "Move subtree up or move table row up.
19831 Calls `org-move-subtree-up' or `org-table-move-row' or
19832 `org-move-item-up', depending on context. See the individual commands
19833 for more information."
19834 (interactive "P")
19835 (cond
19836 ((run-hook-with-args-until-success 'org-metaup-hook))
19837 ((org-region-active-p)
19838 (let* ((a (min (region-beginning) (region-end)))
19839 (b (1- (max (region-beginning) (region-end))))
19840 (c (save-excursion (goto-char a)
19841 (move-beginning-of-line 0)))
19842 (d (save-excursion (goto-char a)
19843 (move-end-of-line 0) (point))))
19844 (transpose-regions a b c d)
19845 (goto-char c)))
19846 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19847 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19848 ((org-at-item-p) (call-interactively 'org-move-item-up))
19849 (t (org-drag-element-backward))))
19851 (defun org-metadown (&optional arg)
19852 "Move subtree down or move table row down.
19853 Calls `org-move-subtree-down' or `org-table-move-row' or
19854 `org-move-item-down', depending on context. See the individual
19855 commands for more information."
19856 (interactive "P")
19857 (cond
19858 ((run-hook-with-args-until-success 'org-metadown-hook))
19859 ((org-region-active-p)
19860 (let* ((a (min (region-beginning) (region-end)))
19861 (b (max (region-beginning) (region-end)))
19862 (c (save-excursion (goto-char b)
19863 (move-beginning-of-line 1)))
19864 (d (save-excursion (goto-char b)
19865 (move-end-of-line 1) (1+ (point)))))
19866 (transpose-regions a b c d)
19867 (goto-char d)))
19868 ((org-at-table-p) (call-interactively 'org-table-move-row))
19869 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19870 ((org-at-item-p) (call-interactively 'org-move-item-down))
19871 (t (org-drag-element-forward))))
19873 (defun org-shiftup (&optional arg)
19874 "Increase item in timestamp or increase priority of current headline.
19875 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19876 depending on context. See the individual commands for more information."
19877 (interactive "P")
19878 (cond
19879 ((run-hook-with-args-until-success 'org-shiftup-hook))
19880 ((and org-support-shift-select (org-region-active-p))
19881 (org-call-for-shift-select 'previous-line))
19882 ((org-at-timestamp-p t)
19883 (call-interactively (if org-edit-timestamp-down-means-later
19884 'org-timestamp-down 'org-timestamp-up)))
19885 ((and (not (eq org-support-shift-select 'always))
19886 org-enable-priority-commands
19887 (org-at-heading-p))
19888 (call-interactively 'org-priority-up))
19889 ((and (not org-support-shift-select) (org-at-item-p))
19890 (call-interactively 'org-previous-item))
19891 ((org-clocktable-try-shift 'up arg))
19892 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19893 (org-support-shift-select
19894 (org-call-for-shift-select 'previous-line))
19895 (t (org-shiftselect-error))))
19897 (defun org-shiftdown (&optional arg)
19898 "Decrease item in timestamp or decrease priority of current headline.
19899 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19900 depending on context. See the individual commands for more information."
19901 (interactive "P")
19902 (cond
19903 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19904 ((and org-support-shift-select (org-region-active-p))
19905 (org-call-for-shift-select 'next-line))
19906 ((org-at-timestamp-p t)
19907 (call-interactively (if org-edit-timestamp-down-means-later
19908 'org-timestamp-up 'org-timestamp-down)))
19909 ((and (not (eq org-support-shift-select 'always))
19910 org-enable-priority-commands
19911 (org-at-heading-p))
19912 (call-interactively 'org-priority-down))
19913 ((and (not org-support-shift-select) (org-at-item-p))
19914 (call-interactively 'org-next-item))
19915 ((org-clocktable-try-shift 'down arg))
19916 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19917 (org-support-shift-select
19918 (org-call-for-shift-select 'next-line))
19919 (t (org-shiftselect-error))))
19921 (defun org-shiftright (&optional arg)
19922 "Cycle the thing at point or in the current line, depending on context.
19923 Depending on context, this does one of the following:
19925 - switch a timestamp at point one day into the future
19926 - on a headline, switch to the next TODO keyword.
19927 - on an item, switch entire list to the next bullet type
19928 - on a property line, switch to the next allowed value
19929 - on a clocktable definition line, move time block into the future"
19930 (interactive "P")
19931 (cond
19932 ((run-hook-with-args-until-success 'org-shiftright-hook))
19933 ((and org-support-shift-select (org-region-active-p))
19934 (org-call-for-shift-select 'forward-char))
19935 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19936 ((and (not (eq org-support-shift-select 'always))
19937 (org-at-heading-p))
19938 (let ((org-inhibit-logging
19939 (not org-treat-S-cursor-todo-selection-as-state-change))
19940 (org-inhibit-blocking
19941 (not org-treat-S-cursor-todo-selection-as-state-change)))
19942 (org-call-with-arg 'org-todo 'right)))
19943 ((or (and org-support-shift-select
19944 (not (eq org-support-shift-select 'always))
19945 (org-at-item-bullet-p))
19946 (and (not org-support-shift-select) (org-at-item-p)))
19947 (org-call-with-arg 'org-cycle-list-bullet nil))
19948 ((and (not (eq org-support-shift-select 'always))
19949 (org-at-property-p))
19950 (call-interactively 'org-property-next-allowed-value))
19951 ((org-clocktable-try-shift 'right arg))
19952 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19953 (org-support-shift-select
19954 (org-call-for-shift-select 'forward-char))
19955 (t (org-shiftselect-error))))
19957 (defun org-shiftleft (&optional arg)
19958 "Cycle the thing at point or in the current line, depending on context.
19959 Depending on context, this does one of the following:
19961 - switch a timestamp at point one day into the past
19962 - on a headline, switch to the previous TODO keyword.
19963 - on an item, switch entire list to the previous bullet type
19964 - on a property line, switch to the previous allowed value
19965 - on a clocktable definition line, move time block into the past"
19966 (interactive "P")
19967 (cond
19968 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19969 ((and org-support-shift-select (org-region-active-p))
19970 (org-call-for-shift-select 'backward-char))
19971 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19972 ((and (not (eq org-support-shift-select 'always))
19973 (org-at-heading-p))
19974 (let ((org-inhibit-logging
19975 (not org-treat-S-cursor-todo-selection-as-state-change))
19976 (org-inhibit-blocking
19977 (not org-treat-S-cursor-todo-selection-as-state-change)))
19978 (org-call-with-arg 'org-todo 'left)))
19979 ((or (and org-support-shift-select
19980 (not (eq org-support-shift-select 'always))
19981 (org-at-item-bullet-p))
19982 (and (not org-support-shift-select) (org-at-item-p)))
19983 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19984 ((and (not (eq org-support-shift-select 'always))
19985 (org-at-property-p))
19986 (call-interactively 'org-property-previous-allowed-value))
19987 ((org-clocktable-try-shift 'left arg))
19988 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19989 (org-support-shift-select
19990 (org-call-for-shift-select 'backward-char))
19991 (t (org-shiftselect-error))))
19993 (defun org-shiftcontrolright ()
19994 "Switch to next TODO set."
19995 (interactive)
19996 (cond
19997 ((and org-support-shift-select (org-region-active-p))
19998 (org-call-for-shift-select 'forward-word))
19999 ((and (not (eq org-support-shift-select 'always))
20000 (org-at-heading-p))
20001 (org-call-with-arg 'org-todo 'nextset))
20002 (org-support-shift-select
20003 (org-call-for-shift-select 'forward-word))
20004 (t (org-shiftselect-error))))
20006 (defun org-shiftcontrolleft ()
20007 "Switch to previous TODO set."
20008 (interactive)
20009 (cond
20010 ((and org-support-shift-select (org-region-active-p))
20011 (org-call-for-shift-select 'backward-word))
20012 ((and (not (eq org-support-shift-select 'always))
20013 (org-at-heading-p))
20014 (org-call-with-arg 'org-todo 'previousset))
20015 (org-support-shift-select
20016 (org-call-for-shift-select 'backward-word))
20017 (t (org-shiftselect-error))))
20019 (defun org-shiftcontrolup (&optional n)
20020 "Change timestamps synchronously up in CLOCK log lines.
20021 Optional argument N tells to change by that many units."
20022 (interactive "P")
20023 (cond ((and (not org-support-shift-select)
20024 (org-at-clock-log-p)
20025 (org-at-timestamp-p t))
20026 (org-clock-timestamps-up n))
20027 (t (org-shiftselect-error))))
20029 (defun org-shiftcontroldown (&optional n)
20030 "Change timestamps synchronously down in CLOCK log lines.
20031 Optional argument N tells to change by that many units."
20032 (interactive "P")
20033 (cond ((and (not org-support-shift-select)
20034 (org-at-clock-log-p)
20035 (org-at-timestamp-p t))
20036 (org-clock-timestamps-down n))
20037 (t (org-shiftselect-error))))
20039 (defun org-ctrl-c-ret ()
20040 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20041 (interactive)
20042 (cond
20043 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20044 (t (call-interactively 'org-insert-heading))))
20046 (defun org-find-visible ()
20047 (let ((s (point)))
20048 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20049 (get-char-property s 'invisible)))
20051 (defun org-find-invisible ()
20052 (let ((s (point)))
20053 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20054 (not (get-char-property s 'invisible))))
20057 (defun org-copy-visible (beg end)
20058 "Copy the visible parts of the region."
20059 (interactive "r")
20060 (let (snippets s)
20061 (save-excursion
20062 (save-restriction
20063 (narrow-to-region beg end)
20064 (setq s (goto-char (point-min)))
20065 (while (not (= (point) (point-max)))
20066 (goto-char (org-find-invisible))
20067 (push (buffer-substring s (point)) snippets)
20068 (setq s (goto-char (org-find-visible))))))
20069 (kill-new (apply 'concat (nreverse snippets)))))
20071 (defun org-copy-special ()
20072 "Copy region in table or copy current subtree.
20073 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20074 See the individual commands for more information."
20075 (interactive)
20076 (call-interactively
20077 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20079 (defun org-cut-special ()
20080 "Cut region in table or cut current subtree.
20081 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20082 See the individual commands for more information."
20083 (interactive)
20084 (call-interactively
20085 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20087 (defun org-paste-special (arg)
20088 "Paste rectangular region into table, or past subtree relative to level.
20089 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20090 See the individual commands for more information."
20091 (interactive "P")
20092 (if (org-at-table-p)
20093 (org-table-paste-rectangle)
20094 (org-paste-subtree arg)))
20096 (defsubst org-in-fixed-width-region-p ()
20097 "Is point in a fixed-width region?"
20098 (save-match-data
20099 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20101 (defun org-edit-special (&optional arg)
20102 "Call a special editor for the element at point.
20103 When at a table, call the formula editor with `org-table-edit-formulas'.
20104 When in a source code block, call `org-edit-src-code'.
20105 When in a fixed-width region, call `org-edit-fixed-width-region'.
20106 When at an #+INCLUDE keyword, visit the included file.
20107 On a link, call `ffap' to visit the link at point.
20108 Otherwise, return a user error."
20109 (interactive "P")
20110 (let ((element (org-element-at-point)))
20111 (assert (not buffer-read-only) nil
20112 "Buffer is read-only: %s" (buffer-name))
20113 (case (org-element-type element)
20114 (src-block
20115 (if (not arg) (org-edit-src-code)
20116 (let* ((info (org-babel-get-src-block-info))
20117 (lang (nth 0 info))
20118 (params (nth 2 info))
20119 (session (cdr (assq :session params))))
20120 (if (not session) (org-edit-src-code)
20121 ;; At a src-block with a session and function called with
20122 ;; an ARG: switch to the buffer related to the inferior
20123 ;; process.
20124 (switch-to-buffer
20125 (funcall (intern (concat "org-babel-prep-session:" lang))
20126 session params))))))
20127 (keyword
20128 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20129 (find-file
20130 (org-remove-double-quotes
20131 (car (org-split-string (org-element-property :value element)))))
20132 (user-error "No special environment to edit here")))
20133 (table
20134 (if (eq (org-element-property :type element) 'table.el)
20135 (org-edit-src-code)
20136 (call-interactively 'org-table-edit-formulas)))
20137 ;; Only Org tables contain `table-row' type elements.
20138 (table-row (call-interactively 'org-table-edit-formulas))
20139 ((example-block export-block) (org-edit-src-code))
20140 (fixed-width (org-edit-fixed-width-region))
20141 (otherwise
20142 ;; No notable element at point. Though, we may be at a link,
20143 ;; which is an object. Thus, scan deeper.
20144 (if (eq (org-element-type (org-element-context element)) 'link)
20145 (call-interactively 'ffap)
20146 (user-error "No special environment to edit here"))))))
20148 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20149 (defun org-ctrl-c-ctrl-c (&optional arg)
20150 "Set tags in headline, or update according to changed information at point.
20152 This command does many different things, depending on context:
20154 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20155 this is what we do.
20157 - If the cursor is on a statistics cookie, update it.
20159 - If the cursor is in a headline, prompt for tags and insert them
20160 into the current line, aligned to `org-tags-column'. When called
20161 with prefix arg, realign all tags in the current buffer.
20163 - If the cursor is in one of the special #+KEYWORD lines, this
20164 triggers scanning the buffer for these lines and updating the
20165 information.
20167 - If the cursor is inside a table, realign the table. This command
20168 works even if the automatic table editor has been turned off.
20170 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20171 the entire table.
20173 - If the cursor is at a footnote reference or definition, jump to
20174 the corresponding definition or references, respectively.
20176 - If the cursor is a the beginning of a dynamic block, update it.
20178 - If the current buffer is a capture buffer, close note and file it.
20180 - If the cursor is on a <<<target>>>, update radio targets and
20181 corresponding links in this buffer.
20183 - If the cursor is on a numbered item in a plain list, renumber the
20184 ordered list.
20186 - If the cursor is on a checkbox, toggle it.
20188 - If the cursor is on a code block, evaluate it. The variable
20189 `org-confirm-babel-evaluate' can be used to control prompting
20190 before code block evaluation, by default every code block
20191 evaluation requires confirmation. Code block evaluation can be
20192 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20193 (interactive "P")
20194 (cond
20195 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20196 org-occur-highlights
20197 org-latex-fragment-image-overlays)
20198 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20199 (org-remove-occur-highlights)
20200 (org-remove-latex-fragment-image-overlays)
20201 (message "Temporary highlights/overlays removed from current buffer"))
20202 ((and (local-variable-p 'org-finish-function (current-buffer))
20203 (fboundp org-finish-function))
20204 (funcall org-finish-function))
20205 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20207 (let* ((context (org-element-context)) (type (org-element-type context)))
20208 ;; Test if point is within a blank line.
20209 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20210 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20211 (user-error "C-c C-c can do nothing useful at this location"))
20212 ;; When at a link, act according to the parent instead.
20213 (when (eq type 'link)
20214 (setq context (org-element-property :parent context))
20215 (setq type (org-element-type context)))
20216 ;; For convenience: at the first line of a paragraph on the
20217 ;; same line as an item, apply function on that item instead.
20218 (when (eq type 'paragraph)
20219 (let ((parent (org-element-property :parent context)))
20220 (when (and (eq (org-element-type parent) 'item)
20221 (= (point-at-bol) (org-element-property :begin parent)))
20222 (setq context parent type 'item))))
20223 ;; Act according to type of element or object at point.
20224 (case type
20225 (clock (org-clock-update-time-maybe))
20226 (dynamic-block
20227 (save-excursion
20228 (goto-char (org-element-property :post-affiliated context))
20229 (org-update-dblock)))
20230 (footnote-definition
20231 (goto-char (org-element-property :post-affiliated context))
20232 (call-interactively 'org-footnote-action))
20233 (footnote-reference (call-interactively 'org-footnote-action))
20234 ((headline inlinetask)
20235 (save-excursion (goto-char (org-element-property :begin context))
20236 (call-interactively 'org-set-tags)))
20237 (item
20238 ;; At an item: a double C-u set checkbox to "[-]"
20239 ;; unconditionally, whereas a single one will toggle its
20240 ;; presence. Without an universal argument, if the item
20241 ;; has a checkbox, toggle it. Otherwise repair the list.
20242 (let* ((box (org-element-property :checkbox context))
20243 (struct (org-element-property :structure context))
20244 (old-struct (copy-tree struct))
20245 (parents (org-list-parents-alist struct))
20246 (prevs (org-list-prevs-alist struct))
20247 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20248 (org-list-set-checkbox
20249 (org-element-property :begin context) struct
20250 (cond ((equal arg '(16)) "[-]")
20251 ((and (not box) (equal arg '(4))) "[ ]")
20252 ((or (not box) (equal arg '(4))) nil)
20253 ((eq box 'on) "[ ]")
20254 (t "[X]")))
20255 ;; Mimic `org-list-write-struct' but with grabbing
20256 ;; a return value from `org-list-struct-fix-box'.
20257 (org-list-struct-fix-ind struct parents 2)
20258 (org-list-struct-fix-item-end struct)
20259 (org-list-struct-fix-bul struct prevs)
20260 (org-list-struct-fix-ind struct parents)
20261 (let ((block-item
20262 (org-list-struct-fix-box struct parents prevs orderedp)))
20263 (if (and box (equal struct old-struct))
20264 (if (equal arg '(16))
20265 (message "Checkboxes already reset")
20266 (user-error "Cannot toggle this checkbox: %s"
20267 (if (eq box 'on)
20268 "all subitems checked"
20269 "unchecked subitems")))
20270 (org-list-struct-apply-struct struct old-struct)
20271 (org-update-checkbox-count-maybe))
20272 (when block-item
20273 (message "Checkboxes were removed due to empty box at line %d"
20274 (org-current-line block-item))))))
20275 (keyword
20276 (let ((org-inhibit-startup-visibility-stuff t)
20277 (org-startup-align-all-tables nil))
20278 (when (boundp 'org-table-coordinate-overlays)
20279 (mapc 'delete-overlay org-table-coordinate-overlays)
20280 (setq org-table-coordinate-overlays nil))
20281 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20282 (message "Local setup has been refreshed"))
20283 (plain-list
20284 ;; At a plain list, with a double C-u argument, set
20285 ;; checkboxes of each item to "[-]", whereas a single one
20286 ;; will toggle their presence according to the state of the
20287 ;; first item in the list. Without an argument, repair the
20288 ;; list.
20289 (let* ((begin (org-element-property :contents-begin context))
20290 (beginm (move-marker (make-marker) begin))
20291 (struct (org-element-property :structure context))
20292 (old-struct (copy-tree struct))
20293 (first-box (save-excursion
20294 (goto-char begin)
20295 (looking-at org-list-full-item-re)
20296 (match-string-no-properties 3)))
20297 (new-box (cond ((equal arg '(16)) "[-]")
20298 ((equal arg '(4)) (unless first-box "[ ]"))
20299 ((equal first-box "[X]") "[ ]")
20300 (t "[X]"))))
20301 (cond
20302 (arg
20303 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20304 (org-list-get-all-items
20305 begin struct (org-list-prevs-alist struct))))
20306 ((and first-box (eq (point) begin))
20307 ;; For convenience, when point is at bol on the first
20308 ;; item of the list and no argument is provided, simply
20309 ;; toggle checkbox of that item, if any.
20310 (org-list-set-checkbox begin struct new-box)))
20311 (org-list-write-struct
20312 struct (org-list-parents-alist struct) old-struct)
20313 (org-update-checkbox-count-maybe)
20314 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20315 ((property-drawer node-property)
20316 (call-interactively 'org-property-action))
20317 ((radio-target target)
20318 (call-interactively 'org-update-radio-target-regexp))
20319 (statistics-cookie
20320 (call-interactively 'org-update-statistics-cookies))
20321 ((table table-cell table-row)
20322 ;; At a table, recalculate every field and align it. Also
20323 ;; send the table if necessary. If the table has
20324 ;; a `table.el' type, just give up. At a table row or
20325 ;; cell, maybe recalculate line but always align table.
20326 (if (eq (org-element-property :type context) 'table.el)
20327 (message "Use C-c ' to edit table.el tables")
20328 (let ((org-enable-table-editor t))
20329 (if (or (eq type 'table)
20330 ;; Check if point is at a TBLFM line.
20331 (and (eq type 'table-row)
20332 (= (point) (org-element-property :end context))))
20333 (save-excursion
20334 (if (org-at-TBLFM-p)
20335 (progn (require 'org-table)
20336 (org-table-calc-current-TBLFM))
20337 (goto-char (org-element-property :contents-begin context))
20338 (org-call-with-arg 'org-table-recalculate (or arg t))
20339 (orgtbl-send-table 'maybe)))
20340 (org-table-maybe-eval-formula)
20341 (cond (arg (call-interactively 'org-table-recalculate))
20342 ((org-table-maybe-recalculate-line))
20343 (t (org-table-align)))))))
20344 (timestamp (org-timestamp-change 0 'day))
20345 (otherwise
20346 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20347 (user-error
20348 "C-c C-c can do nothing useful at this location")))))))))
20350 (defun org-mode-restart ()
20351 "Restart Org-mode, to scan again for special lines.
20352 Also updates the keyword regular expressions."
20353 (interactive)
20354 (org-mode)
20355 (message "Org-mode restarted"))
20357 (defun org-kill-note-or-show-branches ()
20358 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20359 (interactive)
20360 (if (not org-finish-function)
20361 (progn
20362 (hide-subtree)
20363 (call-interactively 'show-branches))
20364 (let ((org-note-abort t))
20365 (funcall org-finish-function))))
20367 (defun org-open-line (n)
20368 "Insert a new row in tables, call `open-line' elsewhere.
20369 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20370 (interactive "*p")
20371 (cond
20372 ((not org-special-ctrl-o)
20373 (open-line n))
20374 ((org-at-table-p)
20375 (org-table-insert-row))
20377 (open-line n))))
20379 (defun org-return (&optional indent)
20380 "Goto next table row or insert a newline.
20381 Calls `org-table-next-row' or `newline', depending on context.
20382 See the individual commands for more information."
20383 (interactive)
20384 (let (org-ts-what)
20385 (cond
20386 ((or (bobp) (org-in-src-block-p))
20387 (if indent (newline-and-indent) (newline)))
20388 ((org-at-table-p)
20389 (org-table-justify-field-maybe)
20390 (call-interactively 'org-table-next-row))
20391 ;; when `newline-and-indent' is called within a list, make sure
20392 ;; text moved stays inside the item.
20393 ((and (org-in-item-p) indent)
20394 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20395 (progn
20396 (save-match-data (newline))
20397 (org-indent-line-to (length (match-string 0))))
20398 (let ((ind (org-get-indentation)))
20399 (newline)
20400 (if (org-looking-back org-list-end-re)
20401 (org-indent-line)
20402 (org-indent-line-to ind)))))
20403 ((and org-return-follows-link
20404 (org-at-timestamp-p t)
20405 (not (eq org-ts-what 'after)))
20406 (org-follow-timestamp-link))
20407 ((and org-return-follows-link
20408 (let ((tprop (get-text-property (point) 'face)))
20409 (or (eq tprop 'org-link)
20410 (and (listp tprop) (memq 'org-link tprop)))))
20411 (call-interactively 'org-open-at-point))
20412 ((and (org-at-heading-p)
20413 (looking-at
20414 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20415 (org-show-entry)
20416 (end-of-line 1)
20417 (newline))
20418 (t (if indent (newline-and-indent) (newline))))))
20420 (defun org-return-indent ()
20421 "Goto next table row or insert a newline and indent.
20422 Calls `org-table-next-row' or `newline-and-indent', depending on
20423 context. See the individual commands for more information."
20424 (interactive)
20425 (org-return t))
20427 (defun org-ctrl-c-star ()
20428 "Compute table, or change heading status of lines.
20429 Calls `org-table-recalculate' or `org-toggle-heading',
20430 depending on context."
20431 (interactive)
20432 (cond
20433 ((org-at-table-p)
20434 (call-interactively 'org-table-recalculate))
20436 ;; Convert all lines in region to list items
20437 (call-interactively 'org-toggle-heading))))
20439 (defun org-ctrl-c-minus ()
20440 "Insert separator line in table or modify bullet status of line.
20441 Also turns a plain line or a region of lines into list items.
20442 Calls `org-table-insert-hline', `org-toggle-item', or
20443 `org-cycle-list-bullet', depending on context."
20444 (interactive)
20445 (cond
20446 ((org-at-table-p)
20447 (call-interactively 'org-table-insert-hline))
20448 ((org-region-active-p)
20449 (call-interactively 'org-toggle-item))
20450 ((org-in-item-p)
20451 (call-interactively 'org-cycle-list-bullet))
20453 (call-interactively 'org-toggle-item))))
20455 (defun org-toggle-item (arg)
20456 "Convert headings or normal lines to items, items to normal lines.
20457 If there is no active region, only the current line is considered.
20459 If the first non blank line in the region is a headline, convert
20460 all headlines to items, shifting text accordingly.
20462 If it is an item, convert all items to normal lines.
20464 If it is normal text, change region into a list of items.
20465 With a prefix argument ARG, change the region in a single item."
20466 (interactive "P")
20467 (let ((shift-text
20468 (function
20469 ;; Shift text in current section to IND, from point to END.
20470 ;; The function leaves point to END line.
20471 (lambda (ind end)
20472 (let ((min-i 1000) (end (copy-marker end)))
20473 ;; First determine the minimum indentation (MIN-I) of
20474 ;; the text.
20475 (save-excursion
20476 (catch 'exit
20477 (while (< (point) end)
20478 (let ((i (org-get-indentation)))
20479 (cond
20480 ;; Skip blank lines and inline tasks.
20481 ((looking-at "^[ \t]*$"))
20482 ((looking-at org-outline-regexp-bol))
20483 ;; We can't find less than 0 indentation.
20484 ((zerop i) (throw 'exit (setq min-i 0)))
20485 ((< i min-i) (setq min-i i))))
20486 (forward-line))))
20487 ;; Then indent each line so that a line indented to
20488 ;; MIN-I becomes indented to IND. Ignore blank lines
20489 ;; and inline tasks in the process.
20490 (let ((delta (- ind min-i)))
20491 (while (< (point) end)
20492 (unless (or (looking-at "^[ \t]*$")
20493 (looking-at org-outline-regexp-bol))
20494 (org-indent-line-to (+ (org-get-indentation) delta)))
20495 (forward-line)))))))
20496 (skip-blanks
20497 (function
20498 ;; Return beginning of first non-blank line, starting from
20499 ;; line at POS.
20500 (lambda (pos)
20501 (save-excursion
20502 (goto-char pos)
20503 (skip-chars-forward " \r\t\n")
20504 (point-at-bol)))))
20505 beg end)
20506 ;; Determine boundaries of changes.
20507 (if (org-region-active-p)
20508 (setq beg (funcall skip-blanks (region-beginning))
20509 end (copy-marker (region-end)))
20510 (setq beg (funcall skip-blanks (point-at-bol))
20511 end (copy-marker (point-at-eol))))
20512 ;; Depending on the starting line, choose an action on the text
20513 ;; between BEG and END.
20514 (org-with-limited-levels
20515 (save-excursion
20516 (goto-char beg)
20517 (cond
20518 ;; Case 1. Start at an item: de-itemize. Note that it only
20519 ;; happens when a region is active: `org-ctrl-c-minus'
20520 ;; would call `org-cycle-list-bullet' otherwise.
20521 ((org-at-item-p)
20522 (while (< (point) end)
20523 (when (org-at-item-p)
20524 (skip-chars-forward " \t")
20525 (delete-region (point) (match-end 0)))
20526 (forward-line)))
20527 ;; Case 2. Start at an heading: convert to items.
20528 ((org-at-heading-p)
20529 (let* ((bul (org-list-bullet-string "-"))
20530 (bul-len (length bul))
20531 ;; Indentation of the first heading. It should be
20532 ;; relative to the indentation of its parent, if any.
20533 (start-ind (save-excursion
20534 (cond
20535 ((not org-adapt-indentation) 0)
20536 ((not (outline-previous-heading)) 0)
20537 (t (length (match-string 0))))))
20538 ;; Level of first heading. Further headings will be
20539 ;; compared to it to determine hierarchy in the list.
20540 (ref-level (org-reduced-level (org-outline-level))))
20541 (while (< (point) end)
20542 (let* ((level (org-reduced-level (org-outline-level)))
20543 (delta (max 0 (- level ref-level))))
20544 ;; If current headline is less indented than the first
20545 ;; one, set it as reference, in order to preserve
20546 ;; subtrees.
20547 (when (< level ref-level) (setq ref-level level))
20548 (replace-match bul t t)
20549 (org-indent-line-to (+ start-ind (* delta bul-len)))
20550 ;; Ensure all text down to END (or SECTION-END) belongs
20551 ;; to the newly created item.
20552 (let ((section-end (save-excursion
20553 (or (outline-next-heading) (point)))))
20554 (forward-line)
20555 (funcall shift-text
20556 (+ start-ind (* (1+ delta) bul-len))
20557 (min end section-end)))))))
20558 ;; Case 3. Normal line with ARG: make the first line of region
20559 ;; an item, and shift indentation of others lines to
20560 ;; set them as item's body.
20561 (arg (let* ((bul (org-list-bullet-string "-"))
20562 (bul-len (length bul))
20563 (ref-ind (org-get-indentation)))
20564 (skip-chars-forward " \t")
20565 (insert bul)
20566 (forward-line)
20567 (while (< (point) end)
20568 ;; Ensure that lines less indented than first one
20569 ;; still get included in item body.
20570 (funcall shift-text
20571 (+ ref-ind bul-len)
20572 (min end (save-excursion (or (outline-next-heading)
20573 (point)))))
20574 (forward-line))))
20575 ;; Case 4. Normal line without ARG: turn each non-item line
20576 ;; into an item.
20578 (while (< (point) end)
20579 (unless (or (org-at-heading-p) (org-at-item-p))
20580 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20581 (replace-match
20582 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20583 (forward-line))))))))
20585 (defun org-toggle-heading (&optional nstars)
20586 "Convert headings to normal text, or items or text to headings.
20587 If there is no active region, only convert the current line.
20589 With a \\[universal-argument] prefix, convert the whole list at
20590 point into heading.
20592 In a region:
20594 - If the first non blank line is a headline, remove the stars
20595 from all headlines in the region.
20597 - If it is a normal line, turn each and every normal line (i.e.,
20598 not an heading or an item) in the region into headings. If you
20599 want to convert only the first line of this region, use one
20600 universal prefix argument.
20602 - If it is a plain list item, turn all plain list items into headings.
20604 When converting a line into a heading, the number of stars is chosen
20605 such that the lines become children of the current entry. However,
20606 when a numeric prefix argument is given, its value determines the
20607 number of stars to add."
20608 (interactive "P")
20609 (let ((skip-blanks
20610 (function
20611 ;; Return beginning of first non-blank line, starting from
20612 ;; line at POS.
20613 (lambda (pos)
20614 (save-excursion
20615 (goto-char pos)
20616 (while (org-at-comment-p) (forward-line))
20617 (skip-chars-forward " \r\t\n")
20618 (point-at-bol)))))
20619 beg end toggled)
20620 ;; Determine boundaries of changes. If a universal prefix has
20621 ;; been given, put the list in a region. If region ends at a bol,
20622 ;; do not consider the last line to be in the region.
20624 (when (and current-prefix-arg (org-at-item-p))
20625 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20626 (org-mark-element))
20628 (if (org-region-active-p)
20629 (setq beg (funcall skip-blanks (region-beginning))
20630 end (copy-marker (save-excursion
20631 (goto-char (region-end))
20632 (if (bolp) (point) (point-at-eol)))))
20633 (setq beg (funcall skip-blanks (point-at-bol))
20634 end (copy-marker (point-at-eol))))
20635 ;; Ensure inline tasks don't count as headings.
20636 (org-with-limited-levels
20637 (save-excursion
20638 (goto-char beg)
20639 (cond
20640 ;; Case 1. Started at an heading: de-star headings.
20641 ((org-at-heading-p)
20642 (while (< (point) end)
20643 (when (org-at-heading-p t)
20644 (looking-at org-outline-regexp) (replace-match "")
20645 (setq toggled t))
20646 (forward-line)))
20647 ;; Case 2. Started at an item: change items into headlines.
20648 ;; One star will be added by `org-list-to-subtree'.
20649 ((org-at-item-p)
20650 (let* ((stars (make-string
20651 ;; subtract the star that will be added again by
20652 ;; `org-list-to-subtree'
20653 (if (numberp nstars) (1- nstars)
20654 (or (org-current-level) 0))
20655 ?*))
20656 (add-stars
20657 (cond (nstars "") ; stars from prefix only
20658 ((equal stars "") "") ; before first heading
20659 (org-odd-levels-only "*") ; inside heading, odd
20660 (t "")))) ; inside heading, oddeven
20661 (while (< (point) end)
20662 (when (org-at-item-p)
20663 ;; Pay attention to cases when region ends before list.
20664 (let* ((struct (org-list-struct))
20665 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20666 (save-restriction
20667 (narrow-to-region (point) list-end)
20668 (insert
20669 (org-list-to-subtree
20670 (org-list-parse-list t)
20671 '(:istart (concat stars add-stars (funcall get-stars depth))
20672 :icount (concat stars add-stars (funcall get-stars depth)))))))
20673 (setq toggled t))
20674 (forward-line))))
20675 ;; Case 3. Started at normal text: make every line an heading,
20676 ;; skipping headlines and items.
20677 (t (let* ((stars
20678 (make-string
20679 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20680 (add-stars
20681 (cond (nstars "") ; stars from prefix only
20682 ((equal stars "") "*") ; before first heading
20683 (org-odd-levels-only "**") ; inside heading, odd
20684 (t "*"))) ; inside heading, oddeven
20685 (rpl (concat stars add-stars " "))
20686 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20687 (while (< (point) (if (equal nstars '(4)) lend end))
20688 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20689 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20690 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20691 (forward-line)))))))
20692 (unless toggled (message "Cannot toggle heading from here"))))
20694 (defun org-meta-return (&optional arg)
20695 "Insert a new heading or wrap a region in a table.
20696 Calls `org-insert-heading' or `org-table-wrap-region', depending
20697 on context. See the individual commands for more information."
20698 (interactive "P")
20699 (org-check-before-invisible-edit 'insert)
20700 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20701 (let* ((element (org-element-at-point))
20702 (type (org-element-type element)))
20703 (when (eq type 'table-row)
20704 (setq element (org-element-property :parent element))
20705 (setq type 'table))
20706 (if (and (eq type 'table)
20707 (eq (org-element-property :type element) 'org)
20708 (>= (point) (org-element-property :contents-begin element))
20709 (< (point) (org-element-property :contents-end element)))
20710 (call-interactively 'org-table-wrap-region)
20711 (call-interactively 'org-insert-heading)))))
20713 ;;; Menu entries
20715 (defsubst org-in-subtree-not-table-p ()
20716 "Are we in a subtree and not in a table?"
20717 (and (not (org-before-first-heading-p))
20718 (not (org-at-table-p))))
20720 ;; Define the Org-mode menus
20721 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20722 '("Tbl"
20723 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20724 ["Next Field" org-cycle (org-at-table-p)]
20725 ["Previous Field" org-shifttab (org-at-table-p)]
20726 ["Next Row" org-return (org-at-table-p)]
20727 "--"
20728 ["Blank Field" org-table-blank-field (org-at-table-p)]
20729 ["Edit Field" org-table-edit-field (org-at-table-p)]
20730 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20731 "--"
20732 ("Column"
20733 ["Move Column Left" org-metaleft (org-at-table-p)]
20734 ["Move Column Right" org-metaright (org-at-table-p)]
20735 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20736 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20737 ("Row"
20738 ["Move Row Up" org-metaup (org-at-table-p)]
20739 ["Move Row Down" org-metadown (org-at-table-p)]
20740 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20741 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20742 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20743 "--"
20744 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20745 ("Rectangle"
20746 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20747 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20748 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20749 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20750 "--"
20751 ("Calculate"
20752 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20753 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20754 ["Edit Formulas" org-edit-special (org-at-table-p)]
20755 "--"
20756 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20757 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20758 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20759 "--"
20760 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20761 "--"
20762 ["Sum Column/Rectangle" org-table-sum
20763 (or (org-at-table-p) (org-region-active-p))]
20764 ["Which Column?" org-table-current-column (org-at-table-p)])
20765 ["Debug Formulas"
20766 org-table-toggle-formula-debugger
20767 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20768 ["Show Col/Row Numbers"
20769 org-table-toggle-coordinate-overlays
20770 :style toggle
20771 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20772 "--"
20773 ["Create" org-table-create (and (not (org-at-table-p))
20774 org-enable-table-editor)]
20775 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20776 ["Import from File" org-table-import (not (org-at-table-p))]
20777 ["Export to File" org-table-export (org-at-table-p)]
20778 "--"
20779 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20781 (easy-menu-define org-org-menu org-mode-map "Org menu"
20782 '("Org"
20783 ("Show/Hide"
20784 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20785 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20786 ["Sparse Tree..." org-sparse-tree t]
20787 ["Reveal Context" org-reveal t]
20788 ["Show All" show-all t]
20789 "--"
20790 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20791 "--"
20792 ["New Heading" org-insert-heading t]
20793 ("Navigate Headings"
20794 ["Up" outline-up-heading t]
20795 ["Next" outline-next-visible-heading t]
20796 ["Previous" outline-previous-visible-heading t]
20797 ["Next Same Level" outline-forward-same-level t]
20798 ["Previous Same Level" outline-backward-same-level t]
20799 "--"
20800 ["Jump" org-goto t])
20801 ("Edit Structure"
20802 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20803 "--"
20804 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20805 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20806 "--"
20807 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20808 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20809 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20810 "--"
20811 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20812 "--"
20813 ["Copy visible text" org-copy-visible t]
20814 "--"
20815 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20816 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20817 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20818 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20819 "--"
20820 ["Sort Region/Children" org-sort t]
20821 "--"
20822 ["Convert to odd levels" org-convert-to-odd-levels t]
20823 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20824 ("Editing"
20825 ["Emphasis..." org-emphasize t]
20826 ["Edit Source Example" org-edit-special t]
20827 "--"
20828 ["Footnote new/jump" org-footnote-action t]
20829 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20830 ("Archive"
20831 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20832 "--"
20833 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20834 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20835 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20837 "--"
20838 ("Hyperlinks"
20839 ["Store Link (Global)" org-store-link t]
20840 ["Find existing link to here" org-occur-link-in-agenda-files t]
20841 ["Insert Link" org-insert-link t]
20842 ["Follow Link" org-open-at-point t]
20843 "--"
20844 ["Next link" org-next-link t]
20845 ["Previous link" org-previous-link t]
20846 "--"
20847 ["Descriptive Links"
20848 org-toggle-link-display
20849 :style radio
20850 :selected org-descriptive-links
20852 ["Literal Links"
20853 org-toggle-link-display
20854 :style radio
20855 :selected (not org-descriptive-links)])
20856 "--"
20857 ("TODO Lists"
20858 ["TODO/DONE/-" org-todo t]
20859 ("Select keyword"
20860 ["Next keyword" org-shiftright (org-at-heading-p)]
20861 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20862 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20863 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20864 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20865 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20866 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20867 "--"
20868 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20869 :selected org-enforce-todo-dependencies :style toggle :active t]
20870 "Settings for tree at point"
20871 ["Do Children sequentially" org-toggle-ordered-property :style radio
20872 :selected (org-entry-get nil "ORDERED")
20873 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20874 ["Do Children parallel" org-toggle-ordered-property :style radio
20875 :selected (not (org-entry-get nil "ORDERED"))
20876 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20877 "--"
20878 ["Set Priority" org-priority t]
20879 ["Priority Up" org-shiftup t]
20880 ["Priority Down" org-shiftdown t]
20881 "--"
20882 ["Get news from all feeds" org-feed-update-all t]
20883 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20884 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20885 ("TAGS and Properties"
20886 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20887 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20888 "--"
20889 ["Set property" org-set-property (not (org-before-first-heading-p))]
20890 ["Column view of properties" org-columns t]
20891 ["Insert Column View DBlock" org-insert-columns-dblock t])
20892 ("Dates and Scheduling"
20893 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20894 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20895 ("Change Date"
20896 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20897 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20898 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20899 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20900 ["Compute Time Range" org-evaluate-time-range t]
20901 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20902 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20903 "--"
20904 ["Custom time format" org-toggle-time-stamp-overlays
20905 :style radio :selected org-display-custom-times]
20906 "--"
20907 ["Goto Calendar" org-goto-calendar t]
20908 ["Date from Calendar" org-date-from-calendar t]
20909 "--"
20910 ["Start/Restart Timer" org-timer-start t]
20911 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20912 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20913 ["Insert Timer String" org-timer t]
20914 ["Insert Timer Item" org-timer-item t])
20915 ("Logging work"
20916 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20917 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20918 ["Clock out" org-clock-out t]
20919 ["Clock cancel" org-clock-cancel t]
20920 "--"
20921 ["Mark as default task" org-clock-mark-default-task t]
20922 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20923 ["Goto running clock" org-clock-goto t]
20924 "--"
20925 ["Display times" org-clock-display t]
20926 ["Create clock table" org-clock-report t]
20927 "--"
20928 ["Record DONE time"
20929 (progn (setq org-log-done (not org-log-done))
20930 (message "Switching to %s will %s record a timestamp"
20931 (car org-done-keywords)
20932 (if org-log-done "automatically" "not")))
20933 :style toggle :selected org-log-done])
20934 "--"
20935 ["Agenda Command..." org-agenda t]
20936 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20937 ("File List for Agenda")
20938 ("Special views current file"
20939 ["TODO Tree" org-show-todo-tree t]
20940 ["Check Deadlines" org-check-deadlines t]
20941 ["Timeline" org-timeline t]
20942 ["Tags/Property tree" org-match-sparse-tree t])
20943 "--"
20944 ["Export/Publish..." org-export-dispatch t]
20945 ("LaTeX"
20946 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20947 :selected org-cdlatex-mode]
20948 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20949 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20950 ["Modify math symbol" org-cdlatex-math-modify
20951 (org-inside-LaTeX-fragment-p)]
20952 ["Insert citation" org-reftex-citation t]
20953 "--"
20954 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20955 "--"
20956 ("MobileOrg"
20957 ["Push Files and Views" org-mobile-push t]
20958 ["Get Captured and Flagged" org-mobile-pull t]
20959 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20960 "--"
20961 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20962 "--"
20963 ("Documentation"
20964 ["Show Version" org-version t]
20965 ["Info Documentation" org-info t])
20966 ("Customize"
20967 ["Browse Org Group" org-customize t]
20968 "--"
20969 ["Expand This Menu" org-create-customize-menu
20970 (fboundp 'customize-menu-create)])
20971 ["Send bug report" org-submit-bug-report t]
20972 "--"
20973 ("Refresh/Reload"
20974 ["Refresh setup current buffer" org-mode-restart t]
20975 ["Reload Org (after update)" org-reload t]
20976 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20979 (defun org-info (&optional node)
20980 "Read documentation for Org-mode in the info system.
20981 With optional NODE, go directly to that node."
20982 (interactive)
20983 (info (format "(org)%s" (or node ""))))
20985 ;;;###autoload
20986 (defun org-submit-bug-report ()
20987 "Submit a bug report on Org-mode via mail.
20989 Don't hesitate to report any problems or inaccurate documentation.
20991 If you don't have setup sending mail from (X)Emacs, please copy the
20992 output buffer into your mail program, as it gives us important
20993 information about your Org-mode version and configuration."
20994 (interactive)
20995 (require 'reporter)
20996 (org-load-modules-maybe)
20997 (org-require-autoloaded-modules)
20998 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20999 (reporter-submit-bug-report
21000 "emacs-orgmode@gnu.org"
21001 (org-version nil 'full)
21002 (let (list)
21003 (save-window-excursion
21004 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21005 (delete-other-windows)
21006 (erase-buffer)
21007 (insert "You are about to submit a bug report to the Org-mode mailing list.
21009 We would like to add your full Org-mode and Outline configuration to the
21010 bug report. This greatly simplifies the work of the maintainer and
21011 other experts on the mailing list.
21013 HOWEVER, some variables you have customized may contain private
21014 information. The names of customers, colleagues, or friends, might
21015 appear in the form of file names, tags, todo states, or search strings.
21016 If you answer yes to the prompt, you might want to check and remove
21017 such private information before sending the email.")
21018 (add-text-properties (point-min) (point-max) '(face org-warning))
21019 (when (yes-or-no-p "Include your Org-mode configuration ")
21020 (mapatoms
21021 (lambda (v)
21022 (and (boundp v)
21023 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21024 (or (and (symbol-value v)
21025 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21026 (and
21027 (get v 'custom-type) (get v 'standard-value)
21028 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21029 (push v list)))))
21030 (kill-buffer (get-buffer "*Warn about privacy*"))
21031 list))
21032 nil nil
21033 "Remember to cover the basics, that is, what you expected to happen and
21034 what in fact did happen. You don't know how to make a good report? See
21036 http://orgmode.org/manual/Feedback.html#Feedback
21038 Your bug report will be posted to the Org-mode mailing list.
21039 ------------------------------------------------------------------------")
21040 (save-excursion
21041 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21042 (replace-match "\\1Bug: \\3 [\\2]")))))
21045 (defun org-install-agenda-files-menu ()
21046 (let ((bl (buffer-list)))
21047 (save-excursion
21048 (while bl
21049 (set-buffer (pop bl))
21050 (if (derived-mode-p 'org-mode) (setq bl nil)))
21051 (when (derived-mode-p 'org-mode)
21052 (easy-menu-change
21053 '("Org") "File List for Agenda"
21054 (append
21055 (list
21056 ["Edit File List" (org-edit-agenda-file-list) t]
21057 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21058 ["Remove Current File from List" org-remove-file t]
21059 ["Cycle through agenda files" org-cycle-agenda-files t]
21060 ["Occur in all agenda files" org-occur-in-agenda-files t]
21061 "--")
21062 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21064 ;;;; Documentation
21066 (defun org-require-autoloaded-modules ()
21067 (interactive)
21068 (mapc 'require
21069 '(org-agenda org-archive org-attach org-clock org-colview org-id
21070 org-table org-timer)))
21072 ;;;###autoload
21073 (defun org-reload (&optional uncompiled)
21074 "Reload all org lisp files.
21075 With prefix arg UNCOMPILED, load the uncompiled versions."
21076 (interactive "P")
21077 (require 'loadhist)
21078 (let* ((org-dir (org-find-library-dir "org"))
21079 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21080 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21081 (remove-re (mapconcat 'identity
21082 (mapcar (lambda (f) (concat "^" f "$"))
21083 (list (if (featurep 'xemacs)
21084 "org-colview"
21085 "org-colview-xemacs")
21086 "org" "org-loaddefs" "org-version"))
21087 "\\|"))
21088 (feats (delete-dups
21089 (mapcar 'file-name-sans-extension
21090 (mapcar 'file-name-nondirectory
21091 (delq nil
21092 (mapcar 'feature-file
21093 features))))))
21094 (lfeat (append
21095 (sort
21096 (setq feats
21097 (delq nil (mapcar
21098 (lambda (f)
21099 (if (and (string-match feature-re f)
21100 (not (string-match remove-re f)))
21101 f nil))
21102 feats)))
21103 'string-lessp)
21104 (list "org-version" "org")))
21105 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21106 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21107 load-uncore load-misses)
21108 (setq load-misses
21109 (delq 't
21110 (mapcar (lambda (f)
21111 (or (org-load-noerror-mustsuffix (concat org-dir f))
21112 (and (string= org-dir contrib-dir)
21113 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21114 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21115 (add-to-list 'load-uncore f 'append)
21118 lfeat)))
21119 (if load-uncore
21120 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21121 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21122 (if load-misses
21123 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21124 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21125 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21127 ;;;###autoload
21128 (defun org-customize ()
21129 "Call the customize function with org as argument."
21130 (interactive)
21131 (org-load-modules-maybe)
21132 (org-require-autoloaded-modules)
21133 (customize-browse 'org))
21135 (defun org-create-customize-menu ()
21136 "Create a full customization menu for Org-mode, insert it into the menu."
21137 (interactive)
21138 (org-load-modules-maybe)
21139 (org-require-autoloaded-modules)
21140 (if (fboundp 'customize-menu-create)
21141 (progn
21142 (easy-menu-change
21143 '("Org") "Customize"
21144 `(["Browse Org group" org-customize t]
21145 "--"
21146 ,(customize-menu-create 'org)
21147 ["Set" Custom-set t]
21148 ["Save" Custom-save t]
21149 ["Reset to Current" Custom-reset-current t]
21150 ["Reset to Saved" Custom-reset-saved t]
21151 ["Reset to Standard Settings" Custom-reset-standard t]))
21152 (message "\"Org\"-menu now contains full customization menu"))
21153 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21155 ;;;; Miscellaneous stuff
21157 ;;; Generally useful functions
21159 (defun org-get-at-bol (property)
21160 "Get text property PROPERTY at beginning of line."
21161 (get-text-property (point-at-bol) property))
21163 (defun org-find-text-property-in-string (prop s)
21164 "Return the first non-nil value of property PROP in string S."
21165 (or (get-text-property 0 prop s)
21166 (get-text-property (or (next-single-property-change 0 prop s) 0)
21167 prop s)))
21169 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21170 "Display the given MESSAGE as a warning."
21171 (if (fboundp 'display-warning)
21172 (display-warning 'org message
21173 (if (featurep 'xemacs) 'warning :warning))
21174 (let ((buf (get-buffer-create "*Org warnings*")))
21175 (with-current-buffer buf
21176 (goto-char (point-max))
21177 (insert "Warning (Org): " message)
21178 (unless (bolp)
21179 (newline)))
21180 (display-buffer buf)
21181 (sit-for 0))))
21183 (defun org-eval (form)
21184 "Eval FORM and return result."
21185 (condition-case error
21186 (eval form)
21187 (error (format "%%![Error: %s]" error))))
21189 (defun org-in-clocktable-p ()
21190 "Check if the cursor is in a clocktable."
21191 (let ((pos (point)) start)
21192 (save-excursion
21193 (end-of-line 1)
21194 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21195 (setq start (match-beginning 0))
21196 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21197 (>= (match-end 0) pos)
21198 start))))
21200 (defun org-in-commented-line ()
21201 "Is point in a line starting with `#'?"
21202 (equal (char-after (point-at-bol)) ?#))
21204 (defun org-in-indented-comment-line ()
21205 "Is point in a line starting with `#' after some white space?"
21206 (save-excursion
21207 (save-match-data
21208 (goto-char (point-at-bol))
21209 (looking-at "[ \t]*#"))))
21211 (defun org-in-verbatim-emphasis ()
21212 (save-match-data
21213 (and (org-in-regexp org-emph-re 2)
21214 (>= (point) (match-beginning 3))
21215 (<= (point) (match-end 4))
21216 (member (match-string 3) '("=" "~")))))
21218 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21219 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21220 (if (and marker (marker-buffer marker)
21221 (buffer-live-p (marker-buffer marker)))
21222 (progn
21223 (org-pop-to-buffer-same-window (marker-buffer marker))
21224 (if (or (> marker (point-max)) (< marker (point-min)))
21225 (widen))
21226 (goto-char marker)
21227 (org-show-context 'org-goto))
21228 (if bookmark
21229 (bookmark-jump bookmark)
21230 (error "Cannot find location"))))
21232 (defun org-quote-csv-field (s)
21233 "Quote field for inclusion in CSV material."
21234 (if (string-match "[\",]" s)
21235 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21238 (defun org-force-self-insert (N)
21239 "Needed to enforce self-insert under remapping."
21240 (interactive "p")
21241 (self-insert-command N))
21243 (defun org-string-width (s)
21244 "Compute width of string, ignoring invisible characters.
21245 This ignores character with invisibility property `org-link', and also
21246 characters with property `org-cwidth', because these will become invisible
21247 upon the next fontification round."
21248 (let (b l)
21249 (when (or (eq t buffer-invisibility-spec)
21250 (assq 'org-link buffer-invisibility-spec))
21251 (while (setq b (text-property-any 0 (length s)
21252 'invisible 'org-link s))
21253 (setq s (concat (substring s 0 b)
21254 (substring s (or (next-single-property-change
21255 b 'invisible s) (length s)))))))
21256 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21257 (setq s (concat (substring s 0 b)
21258 (substring s (or (next-single-property-change
21259 b 'org-cwidth s) (length s))))))
21260 (setq l (string-width s) b -1)
21261 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21262 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21265 (defun org-shorten-string (s maxlength)
21266 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21267 If the string is shorter or has length MAXLENGTH, just return the
21268 original string. If it is longer, the functions finds a space in the
21269 string, breaks this string off at that locations and adds three dots
21270 as ellipsis. Including the ellipsis, the string will not be longer
21271 than MAXLENGTH. If finding a good breaking point in the string does
21272 not work, the string is just chopped off in the middle of a word
21273 if necessary."
21274 (if (<= (length s) maxlength)
21276 (let* ((n (max (- maxlength 4) 1))
21277 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21278 (if (string-match re s)
21279 (concat (match-string 1 s) "...")
21280 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21282 (defun org-get-indentation (&optional line)
21283 "Get the indentation of the current line, interpreting tabs.
21284 When LINE is given, assume it represents a line and compute its indentation."
21285 (if line
21286 (if (string-match "^ *" (org-remove-tabs line))
21287 (match-end 0))
21288 (save-excursion
21289 (beginning-of-line 1)
21290 (skip-chars-forward " \t")
21291 (current-column))))
21293 (defun org-get-string-indentation (s)
21294 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21295 (let ((n -1) (i 0) (w tab-width) c)
21296 (catch 'exit
21297 (while (< (setq n (1+ n)) (length s))
21298 (setq c (aref s n))
21299 (cond ((= c ?\ ) (setq i (1+ i)))
21300 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21301 (t (throw 'exit t)))))
21304 (defun org-remove-tabs (s &optional width)
21305 "Replace tabulators in S with spaces.
21306 Assumes that s is a single line, starting in column 0."
21307 (setq width (or width tab-width))
21308 (while (string-match "\t" s)
21309 (setq s (replace-match
21310 (make-string
21311 (- (* width (/ (+ (match-beginning 0) width) width))
21312 (match-beginning 0)) ?\ )
21313 t t s)))
21316 (defun org-fix-indentation (line ind)
21317 "Fix indentation in LINE.
21318 IND is a cons cell with target and minimum indentation.
21319 If the current indentation in LINE is smaller than the minimum,
21320 leave it alone. If it is larger than ind, set it to the target."
21321 (let* ((l (org-remove-tabs line))
21322 (i (org-get-indentation l))
21323 (i1 (car ind)) (i2 (cdr ind)))
21324 (if (>= i i2) (setq l (substring line i2)))
21325 (if (> i1 0)
21326 (concat (make-string i1 ?\ ) l)
21327 l)))
21329 (defun org-remove-indentation (code &optional n)
21330 "Remove the maximum common indentation from the lines in CODE.
21331 N may optionally be the number of spaces to remove."
21332 (with-temp-buffer
21333 (insert code)
21334 (org-do-remove-indentation n)
21335 (buffer-string)))
21337 (defun org-do-remove-indentation (&optional n)
21338 "Remove the maximum common indentation from the buffer."
21339 (untabify (point-min) (point-max))
21340 (let ((min 10000) re)
21341 (if n
21342 (setq min n)
21343 (goto-char (point-min))
21344 (while (re-search-forward "^ *[^ \n]" nil t)
21345 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21346 (unless (or (= min 0) (= min 10000))
21347 (setq re (format "^ \\{%d\\}" min))
21348 (goto-char (point-min))
21349 (while (re-search-forward re nil t)
21350 (replace-match "")
21351 (end-of-line 1))
21352 min)))
21354 (defun org-fill-template (template alist)
21355 "Find each %key of ALIST in TEMPLATE and replace it."
21356 (let ((case-fold-search nil)
21357 entry key value)
21358 (setq alist (sort (copy-sequence alist)
21359 (lambda (a b) (< (length (car a)) (length (car b))))))
21360 (while (setq entry (pop alist))
21361 (setq template
21362 (replace-regexp-in-string
21363 (concat "%" (regexp-quote (car entry)))
21364 (or (cdr entry) "") template t t)))
21365 template))
21367 (defun org-base-buffer (buffer)
21368 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21369 (if (not buffer)
21370 buffer
21371 (or (buffer-base-buffer buffer)
21372 buffer)))
21374 (defun org-trim (s)
21375 "Remove whitespace at beginning and end of string."
21376 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21377 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21380 (defun org-wrap (string &optional width lines)
21381 "Wrap string to either a number of lines, or a width in characters.
21382 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21383 that costs. If there is a word longer than WIDTH, the text is actually
21384 wrapped to the length of that word.
21385 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21386 many lines, whatever width that takes.
21387 The return value is a list of lines, without newlines at the end."
21388 (let* ((words (org-split-string string "[ \t\n]+"))
21389 (maxword (apply 'max (mapcar 'org-string-width words)))
21390 w ll)
21391 (cond (width
21392 (org-do-wrap words (max maxword width)))
21393 (lines
21394 (setq w maxword)
21395 (setq ll (org-do-wrap words maxword))
21396 (if (<= (length ll) lines)
21398 (setq ll words)
21399 (while (> (length ll) lines)
21400 (setq w (1+ w))
21401 (setq ll (org-do-wrap words w)))
21402 ll))
21403 (t (error "Cannot wrap this")))))
21405 (defun org-do-wrap (words width)
21406 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21407 (let (lines line)
21408 (while words
21409 (setq line (pop words))
21410 (while (and words (< (+ (length line) (length (car words))) width))
21411 (setq line (concat line " " (pop words))))
21412 (setq lines (push line lines)))
21413 (nreverse lines)))
21415 (defun org-split-string (string &optional separators)
21416 "Splits STRING into substrings at SEPARATORS.
21417 No empty strings are returned if there are matches at the beginning
21418 and end of string."
21419 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21420 (start 0)
21421 notfirst
21422 (list nil))
21423 (while (and (string-match rexp string
21424 (if (and notfirst
21425 (= start (match-beginning 0))
21426 (< start (length string)))
21427 (1+ start) start))
21428 (< (match-beginning 0) (length string)))
21429 (setq notfirst t)
21430 (or (eq (match-beginning 0) 0)
21431 (and (eq (match-beginning 0) (match-end 0))
21432 (eq (match-beginning 0) start))
21433 (setq list
21434 (cons (substring string start (match-beginning 0))
21435 list)))
21436 (setq start (match-end 0)))
21437 (or (eq start (length string))
21438 (setq list
21439 (cons (substring string start)
21440 list)))
21441 (nreverse list)))
21443 (defun org-quote-vert (s)
21444 "Replace \"|\" with \"\\vert\"."
21445 (while (string-match "|" s)
21446 (setq s (replace-match "\\vert" t t s)))
21449 (defun org-uuidgen-p (s)
21450 "Is S an ID created by UUIDGEN?"
21451 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21453 (defun org-in-src-block-p (&optional inside)
21454 "Whether point is in a code source block.
21455 When INSIDE is non-nil, don't consider we are within a src block
21456 when point is at #+BEGIN_SRC or #+END_SRC."
21457 (let ((case-fold-search t) ov)
21458 (or (and (setq ov (overlays-at (point)))
21459 (memq 'org-block-background
21460 (overlay-properties (car ov))))
21461 (and (not inside)
21462 (save-match-data
21463 (save-excursion
21464 (beginning-of-line)
21465 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21467 (defun org-context ()
21468 "Return a list of contexts of the current cursor position.
21469 If several contexts apply, all are returned.
21470 Each context entry is a list with a symbol naming the context, and
21471 two positions indicating start and end of the context. Possible
21472 contexts are:
21474 :headline anywhere in a headline
21475 :headline-stars on the leading stars in a headline
21476 :todo-keyword on a TODO keyword (including DONE) in a headline
21477 :tags on the TAGS in a headline
21478 :priority on the priority cookie in a headline
21479 :item on the first line of a plain list item
21480 :item-bullet on the bullet/number of a plain list item
21481 :checkbox on the checkbox in a plain list item
21482 :table in an org-mode table
21483 :table-special on a special filed in a table
21484 :table-table in a table.el table
21485 :clocktable in a clocktable
21486 :src-block in a source block
21487 :link on a hyperlink
21488 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21489 :target on a <<target>>
21490 :radio-target on a <<<radio-target>>>
21491 :latex-fragment on a LaTeX fragment
21492 :latex-preview on a LaTeX fragment with overlaid preview image
21494 This function expects the position to be visible because it uses font-lock
21495 faces as a help to recognize the following contexts: :table-special, :link,
21496 and :keyword."
21497 (let* ((f (get-text-property (point) 'face))
21498 (faces (if (listp f) f (list f)))
21499 (case-fold-search t)
21500 (p (point)) clist o)
21501 ;; First the large context
21502 (cond
21503 ((org-at-heading-p t)
21504 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21505 (when (progn
21506 (beginning-of-line 1)
21507 (looking-at org-todo-line-tags-regexp))
21508 (push (org-point-in-group p 1 :headline-stars) clist)
21509 (push (org-point-in-group p 2 :todo-keyword) clist)
21510 (push (org-point-in-group p 4 :tags) clist))
21511 (goto-char p)
21512 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21513 (if (looking-at "\\[#[A-Z0-9]\\]")
21514 (push (org-point-in-group p 0 :priority) clist)))
21516 ((org-at-item-p)
21517 (push (org-point-in-group p 2 :item-bullet) clist)
21518 (push (list :item (point-at-bol)
21519 (save-excursion (org-end-of-item) (point)))
21520 clist)
21521 (and (org-at-item-checkbox-p)
21522 (push (org-point-in-group p 0 :checkbox) clist)))
21524 ((org-at-table-p)
21525 (push (list :table (org-table-begin) (org-table-end)) clist)
21526 (if (memq 'org-formula faces)
21527 (push (list :table-special
21528 (previous-single-property-change p 'face)
21529 (next-single-property-change p 'face)) clist)))
21530 ((org-at-table-p 'any)
21531 (push (list :table-table) clist)))
21532 (goto-char p)
21534 (let ((case-fold-search t))
21535 ;; New the "medium" contexts: clocktables, source blocks
21536 (cond ((org-in-clocktable-p)
21537 (push (list :clocktable
21538 (and (or (looking-at "#\\+BEGIN: clocktable")
21539 (search-backward "#+BEGIN: clocktable" nil t))
21540 (match-beginning 0))
21541 (and (re-search-forward "#\\+END:?" nil t)
21542 (match-end 0))) clist))
21543 ((org-in-src-block-p)
21544 (push (list :src-block
21545 (and (or (looking-at "#\\+BEGIN_SRC")
21546 (search-backward "#+BEGIN_SRC" nil t))
21547 (match-beginning 0))
21548 (and (search-forward "#+END_SRC" nil t)
21549 (match-beginning 0))) clist))))
21550 (goto-char p)
21552 ;; Now the small context
21553 (cond
21554 ((org-at-timestamp-p)
21555 (push (org-point-in-group p 0 :timestamp) clist))
21556 ((memq 'org-link faces)
21557 (push (list :link
21558 (previous-single-property-change p 'face)
21559 (next-single-property-change p 'face)) clist))
21560 ((memq 'org-special-keyword faces)
21561 (push (list :keyword
21562 (previous-single-property-change p 'face)
21563 (next-single-property-change p 'face)) clist))
21564 ((org-at-target-p)
21565 (push (org-point-in-group p 0 :target) clist)
21566 (goto-char (1- (match-beginning 0)))
21567 (if (looking-at org-radio-target-regexp)
21568 (push (org-point-in-group p 0 :radio-target) clist))
21569 (goto-char p))
21570 ((setq o (car (delq nil
21571 (mapcar
21572 (lambda (x)
21573 (if (memq x org-latex-fragment-image-overlays) x))
21574 (overlays-at (point))))))
21575 (push (list :latex-fragment
21576 (overlay-start o) (overlay-end o)) clist)
21577 (push (list :latex-preview
21578 (overlay-start o) (overlay-end o)) clist))
21579 ((org-inside-LaTeX-fragment-p)
21580 ;; FIXME: positions wrong.
21581 (push (list :latex-fragment (point) (point)) clist)))
21583 (setq clist (nreverse (delq nil clist)))
21584 clist))
21586 ;; FIXME: Compare with at-regexp-p Do we need both?
21587 (defun org-in-regexp (re &optional nlines visually)
21588 "Check if point is inside a match of regexp.
21589 Normally only the current line is checked, but you can include NLINES extra
21590 lines both before and after point into the search.
21591 If VISUALLY is set, require that the cursor is not after the match but
21592 really on, so that the block visually is on the match."
21593 (catch 'exit
21594 (let ((pos (point))
21595 (eol (point-at-eol (+ 1 (or nlines 0))))
21596 (inc (if visually 1 0)))
21597 (save-excursion
21598 (beginning-of-line (- 1 (or nlines 0)))
21599 (while (re-search-forward re eol t)
21600 (if (and (<= (match-beginning 0) pos)
21601 (>= (+ inc (match-end 0)) pos))
21602 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21604 (defun org-at-regexp-p (regexp)
21605 "Is point inside a match of REGEXP in the current line?"
21606 (catch 'exit
21607 (save-excursion
21608 (let ((pos (point)) (end (point-at-eol)))
21609 (beginning-of-line 1)
21610 (while (re-search-forward regexp end t)
21611 (if (and (<= (match-beginning 0) pos)
21612 (>= (match-end 0) pos))
21613 (throw 'exit t)))
21614 nil))))
21616 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21617 "Non-nil when point is between matches of START-RE and END-RE.
21619 Also return a non-nil value when point is on one of the matches.
21621 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21622 buffer positions. Default values are the positions of headlines
21623 surrounding the point.
21625 The functions returns a cons cell whose car (resp. cdr) is the
21626 position before START-RE (resp. after END-RE)."
21627 (save-match-data
21628 (let ((pos (point))
21629 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21630 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21631 beg end)
21632 (save-excursion
21633 ;; Point is on a block when on START-RE or if START-RE can be
21634 ;; found before it...
21635 (and (or (org-at-regexp-p start-re)
21636 (re-search-backward start-re limit-up t))
21637 (setq beg (match-beginning 0))
21638 ;; ... and END-RE after it...
21639 (goto-char (match-end 0))
21640 (re-search-forward end-re limit-down t)
21641 (> (setq end (match-end 0)) pos)
21642 ;; ... without another START-RE in-between.
21643 (goto-char (match-beginning 0))
21644 (not (re-search-backward start-re (1+ beg) t))
21645 ;; Return value.
21646 (cons beg end))))))
21648 (defun org-in-block-p (names)
21649 "Non-nil when point belongs to a block whose name belongs to NAMES.
21651 NAMES is a list of strings containing names of blocks.
21653 Return first block name matched, or nil. Beware that in case of
21654 nested blocks, the returned name may not belong to the closest
21655 block from point."
21656 (save-match-data
21657 (catch 'exit
21658 (let ((case-fold-search t)
21659 (lim-up (save-excursion (outline-previous-heading)))
21660 (lim-down (save-excursion (outline-next-heading))))
21661 (mapc (lambda (name)
21662 (let ((n (regexp-quote name)))
21663 (when (org-between-regexps-p
21664 (concat "^[ \t]*#\\+begin_" n)
21665 (concat "^[ \t]*#\\+end_" n)
21666 lim-up lim-down)
21667 (throw 'exit n))))
21668 names))
21669 nil)))
21671 (defun org-in-drawer-p ()
21672 "Is point within a drawer?"
21673 (save-match-data
21674 (let ((case-fold-search t)
21675 (lim-up (save-excursion (outline-previous-heading)))
21676 (lim-down (save-excursion (outline-next-heading))))
21677 (org-between-regexps-p
21678 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21679 "^[ \t]*:end:.*$"
21680 lim-up lim-down))))
21682 (defun org-occur-in-agenda-files (regexp &optional nlines)
21683 "Call `multi-occur' with buffers for all agenda files."
21684 (interactive "sOrg-files matching: \np")
21685 (let* ((files (org-agenda-files))
21686 (tnames (mapcar 'file-truename files))
21687 (extra org-agenda-text-search-extra-files)
21689 (when (eq (car extra) 'agenda-archives)
21690 (setq extra (cdr extra))
21691 (setq files (org-add-archive-files files)))
21692 (while (setq f (pop extra))
21693 (unless (member (file-truename f) tnames)
21694 (add-to-list 'files f 'append)
21695 (add-to-list 'tnames (file-truename f) 'append)))
21696 (multi-occur
21697 (mapcar (lambda (x)
21698 (with-current-buffer
21699 (or (get-file-buffer x) (find-file-noselect x))
21700 (widen)
21701 (current-buffer)))
21702 files)
21703 regexp)))
21705 (if (boundp 'occur-mode-find-occurrence-hook)
21706 ;; Emacs 23
21707 (add-hook 'occur-mode-find-occurrence-hook
21708 (lambda ()
21709 (when (derived-mode-p 'org-mode)
21710 (org-reveal))))
21711 ;; Emacs 22
21712 (defadvice occur-mode-goto-occurrence
21713 (after org-occur-reveal activate)
21714 (and (derived-mode-p 'org-mode) (org-reveal)))
21715 (defadvice occur-mode-goto-occurrence-other-window
21716 (after org-occur-reveal activate)
21717 (and (derived-mode-p 'org-mode) (org-reveal)))
21718 (defadvice occur-mode-display-occurrence
21719 (after org-occur-reveal activate)
21720 (when (derived-mode-p 'org-mode)
21721 (let ((pos (occur-mode-find-occurrence)))
21722 (with-current-buffer (marker-buffer pos)
21723 (save-excursion
21724 (goto-char pos)
21725 (org-reveal)))))))
21727 (defun org-occur-link-in-agenda-files ()
21728 "Create a link and search for it in the agendas.
21729 The link is not stored in `org-stored-links', it is just created
21730 for the search purpose."
21731 (interactive)
21732 (let ((link (condition-case nil
21733 (org-store-link nil)
21734 (error "Unable to create a link to here"))))
21735 (org-occur-in-agenda-files (regexp-quote link))))
21737 (defun org-reverse-string (string)
21738 "Return the reverse of STRING."
21739 (apply 'string (reverse (string-to-list string))))
21741 (defsubst org-uniquify (list)
21742 "Non-destructively remove duplicate elements from LIST."
21743 (let ((res (copy-sequence list))) (delete-dups res)))
21745 (defun org-uniquify-alist (alist)
21746 "Merge elements of ALIST with the same key.
21748 For example, in this alist:
21750 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21751 => '((a 1 3) (b 2))
21753 merge (a 1) and (a 3) into (a 1 3).
21755 The function returns the new ALIST."
21756 (let (rtn)
21757 (mapc
21758 (lambda (e)
21759 (let (n)
21760 (if (not (assoc (car e) rtn))
21761 (push e rtn)
21762 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21763 (setq rtn (assq-delete-all (car e) rtn))
21764 (push n rtn))))
21765 alist)
21766 rtn))
21768 (defun org-delete-all (elts list)
21769 "Remove all elements in ELTS from LIST."
21770 (while elts
21771 (setq list (delete (pop elts) list)))
21772 list)
21774 (defun org-count (cl-item cl-seq)
21775 "Count the number of occurrences of ITEM in SEQ.
21776 Taken from `count' in cl-seq.el with all keyword arguments removed."
21777 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21778 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21779 (while (< cl-start cl-end)
21780 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21781 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21782 (setq cl-start (1+ cl-start)))
21783 cl-count))
21785 (defun org-remove-if (predicate seq)
21786 "Remove everything from SEQ that fulfills PREDICATE."
21787 (let (res e)
21788 (while seq
21789 (setq e (pop seq))
21790 (if (not (funcall predicate e)) (push e res)))
21791 (nreverse res)))
21793 (defun org-remove-if-not (predicate seq)
21794 "Remove everything from SEQ that does not fulfill PREDICATE."
21795 (let (res e)
21796 (while seq
21797 (setq e (pop seq))
21798 (if (funcall predicate e) (push e res)))
21799 (nreverse res)))
21801 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21802 "Reduce two-argument FUNCTION across SEQ.
21803 Taken from `reduce' in cl-seq.el with all keyword arguments but
21804 \":initial-value\" removed."
21805 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21806 (cadr (memq :initial-value cl-keys)))
21807 (cl-seq (pop cl-seq))
21808 (t (funcall cl-func)))))
21809 (while cl-seq
21810 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21811 cl-accum))
21813 (defun org-every (pred seq)
21814 "Return true if PREDICATE is true of every element of SEQ.
21815 Adapted from `every' in cl.el."
21816 (catch 'org-every
21817 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21820 (defun org-some (pred seq)
21821 "Return true if PREDICATE is true of any element of SEQ.
21822 Adapted from `some' in cl.el."
21823 (catch 'org-some
21824 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21825 nil))
21827 (defun org-back-over-empty-lines ()
21828 "Move backwards over whitespace, to the beginning of the first empty line.
21829 Returns the number of empty lines passed."
21830 (let ((pos (point)))
21831 (if (cdr (assoc 'heading org-blank-before-new-entry))
21832 (skip-chars-backward " \t\n\r")
21833 (unless (eobp)
21834 (forward-line -1)))
21835 (beginning-of-line 2)
21836 (goto-char (min (point) pos))
21837 (count-lines (point) pos)))
21839 (defun org-skip-whitespace ()
21840 (skip-chars-forward " \t\n\r"))
21842 (defun org-point-in-group (point group &optional context)
21843 "Check if POINT is in match-group GROUP.
21844 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21845 match. If the match group does not exist or point is not inside it,
21846 return nil."
21847 (and (match-beginning group)
21848 (>= point (match-beginning group))
21849 (<= point (match-end group))
21850 (if context
21851 (list context (match-beginning group) (match-end group))
21852 t)))
21854 (defun org-switch-to-buffer-other-window (&rest args)
21855 "Switch to buffer in a second window on the current frame.
21856 In particular, do not allow pop-up frames.
21857 Returns the newly created buffer."
21858 (org-no-popups
21859 (apply 'switch-to-buffer-other-window args)))
21861 (defun org-combine-plists (&rest plists)
21862 "Create a single property list from all plists in PLISTS.
21863 The process starts by copying the first list, and then setting properties
21864 from the other lists. Settings in the last list are the most significant
21865 ones and overrule settings in the other lists."
21866 (let ((rtn (copy-sequence (pop plists)))
21867 p v ls)
21868 (while plists
21869 (setq ls (pop plists))
21870 (while ls
21871 (setq p (pop ls) v (pop ls))
21872 (setq rtn (plist-put rtn p v))))
21873 rtn))
21875 (defun org-replace-escapes (string table)
21876 "Replace %-escapes in STRING with values in TABLE.
21877 TABLE is an association list with keys like \"%a\" and string values.
21878 The sequences in STRING may contain normal field width and padding information,
21879 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21880 so values can contain further %-escapes if they are define later in TABLE."
21881 (let ((tbl (copy-alist table))
21882 (case-fold-search nil)
21883 (pchg 0)
21884 e re rpl)
21885 (while (setq e (pop tbl))
21886 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21887 (when (and (cdr e) (string-match re (cdr e)))
21888 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21889 (safe "SREF"))
21890 (add-text-properties 0 3 (list 'sref sref) safe)
21891 (setcdr e (replace-match safe t t (cdr e)))))
21892 (while (string-match re string)
21893 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21894 (cdr e)))
21895 (setq string (replace-match rpl t t string))))
21896 (while (setq pchg (next-property-change pchg string))
21897 (let ((sref (get-text-property pchg 'sref string)))
21898 (when (and sref (string-match "SREF" string pchg))
21899 (setq string (replace-match sref t t string)))))
21900 string))
21902 (defun org-sublist (list start end)
21903 "Return a section of LIST, from START to END.
21904 Counting starts at 1."
21905 (let (rtn (c start))
21906 (setq list (nthcdr (1- start) list))
21907 (while (and list (<= c end))
21908 (push (pop list) rtn)
21909 (setq c (1+ c)))
21910 (nreverse rtn)))
21912 (defun org-find-base-buffer-visiting (file)
21913 "Like `find-buffer-visiting' but always return the base buffer and
21914 not an indirect buffer."
21915 (let ((buf (or (get-file-buffer file)
21916 (find-buffer-visiting file))))
21917 (if buf
21918 (or (buffer-base-buffer buf) buf)
21919 nil)))
21921 (defun org-image-file-name-regexp (&optional extensions)
21922 "Return regexp matching the file names of images.
21923 If EXTENSIONS is given, only match these."
21924 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21925 (image-file-name-regexp)
21926 (let ((image-file-name-extensions
21927 (or extensions
21928 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21929 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21930 (concat "\\."
21931 (regexp-opt (nconc (mapcar 'upcase
21932 image-file-name-extensions)
21933 image-file-name-extensions)
21935 "\\'"))))
21937 (defun org-file-image-p (file &optional extensions)
21938 "Return non-nil if FILE is an image."
21939 (save-match-data
21940 (string-match (org-image-file-name-regexp extensions) file)))
21942 (defun org-get-cursor-date (&optional with-time)
21943 "Return the date at cursor in as a time.
21944 This works in the calendar and in the agenda, anywhere else it just
21945 returns the current time.
21946 If WITH-TIME is non-nil, returns the time of the event at point (in
21947 the agenda) or the current time of the day."
21948 (let (date day defd tp tm hod mod)
21949 (when with-time
21950 (setq tp (get-text-property (point) 'time))
21951 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21952 (setq hod (string-to-number (match-string 1 tp))
21953 mod (string-to-number (match-string 2 tp))))
21954 (or tp (setq hod (nth 2 (decode-time (current-time)))
21955 mod (nth 1 (decode-time (current-time))))))
21956 (cond
21957 ((eq major-mode 'calendar-mode)
21958 (setq date (calendar-cursor-to-date)
21959 defd (encode-time 0 (or mod 0) (or hod 0)
21960 (nth 1 date) (nth 0 date) (nth 2 date))))
21961 ((eq major-mode 'org-agenda-mode)
21962 (setq day (get-text-property (point) 'day))
21963 (if day
21964 (setq date (calendar-gregorian-from-absolute day)
21965 defd (encode-time 0 (or mod 0) (or hod 0)
21966 (nth 1 date) (nth 0 date) (nth 2 date))))))
21967 (or defd (current-time))))
21969 (defun org-mark-subtree (&optional up)
21970 "Mark the current subtree.
21971 This puts point at the start of the current subtree, and mark at
21972 the end. If a numeric prefix UP is given, move up into the
21973 hierarchy of headlines by UP levels before marking the subtree."
21974 (interactive "P")
21975 (org-with-limited-levels
21976 (cond ((org-at-heading-p) (beginning-of-line))
21977 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21978 (t (outline-previous-visible-heading 1))))
21979 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21980 (if (org-called-interactively-p 'any)
21981 (call-interactively 'org-mark-element)
21982 (org-mark-element)))
21985 ;;; Indentation
21987 (defun org-indent-line ()
21988 "Indent line depending on context."
21989 (interactive)
21990 (let* ((pos (point))
21991 (itemp (org-at-item-p))
21992 (case-fold-search t)
21993 (org-drawer-regexp (or org-drawer-regexp "\000"))
21994 (inline-task-p (and (featurep 'org-inlinetask)
21995 (org-inlinetask-in-task-p)))
21996 (inline-re (and inline-task-p
21997 (org-inlinetask-outline-regexp)))
21998 column)
21999 (if (and orgstruct-is-++ (eq pos (point)))
22000 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22001 (indent-according-to-mode))
22002 (beginning-of-line 1)
22003 (cond
22004 ;; Headings
22005 ((looking-at org-outline-regexp) (setq column 0))
22006 ;; Footnote definition
22007 ((looking-at org-footnote-definition-re) (setq column 0))
22008 ;; Literal examples
22009 ((looking-at "[ \t]*:\\( \\|$\\)")
22010 (setq column (org-get-indentation))) ; do nothing
22011 ;; Lists
22012 ((ignore-errors (goto-char (org-in-item-p)))
22013 (setq column (if itemp
22014 (org-get-indentation)
22015 (org-list-item-body-column (point))))
22016 (goto-char pos))
22017 ;; Drawers
22018 ((and (looking-at "[ \t]*:END:")
22019 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22020 (save-excursion
22021 (goto-char (1- (match-beginning 1)))
22022 (setq column (current-column))))
22023 ;; Special blocks
22024 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22025 (save-excursion
22026 (re-search-backward
22027 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22028 (setq column (org-get-indentation (match-string 0))))
22029 ((and (not (looking-at "[ \t]*#\\+begin_"))
22030 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22031 (save-excursion
22032 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22033 (setq column
22034 (cond ((equal (downcase (match-string 1)) "src")
22035 ;; src blocks: let `org-edit-src-exit' handle them
22036 (org-get-indentation))
22037 ((equal (downcase (match-string 1)) "example")
22038 (max (org-get-indentation)
22039 (org-get-indentation (match-string 0))))
22041 (org-get-indentation (match-string 0))))))
22042 ;; This line has nothing special, look at the previous relevant
22043 ;; line to compute indentation
22045 (beginning-of-line 0)
22046 (while (and (not (bobp))
22047 (not (looking-at org-table-line-regexp))
22048 (not (looking-at org-drawer-regexp))
22049 ;; When point started in an inline task, do not move
22050 ;; above task starting line.
22051 (not (and inline-task-p (looking-at inline-re)))
22052 ;; Skip drawers, blocks, empty lines, verbatim,
22053 ;; comments, tables, footnotes definitions, lists,
22054 ;; inline tasks.
22055 (or (and (looking-at "[ \t]*:END:")
22056 (re-search-backward org-drawer-regexp nil t))
22057 (and (looking-at "[ \t]*#\\+end_")
22058 (re-search-backward "[ \t]*#\\+begin_"nil t))
22059 (looking-at "[ \t]*[\n:#|]")
22060 (looking-at org-footnote-definition-re)
22061 (and (not inline-task-p)
22062 (featurep 'org-inlinetask)
22063 (org-inlinetask-in-task-p)
22064 (or (org-inlinetask-goto-beginning) t))))
22065 (beginning-of-line 0))
22066 (cond
22067 ;; There was a list item above.
22068 ((ignore-errors (goto-char (org-in-item-p)))
22069 (goto-char (org-list-get-top-point (org-list-struct)))
22070 (setq column (org-get-indentation)))
22071 ;; There was an heading above.
22072 ((looking-at "\\*+[ \t]+")
22073 (if (not org-adapt-indentation)
22074 (setq column 0)
22075 (goto-char (match-end 0))
22076 (setq column (current-column))))
22077 ;; A drawer had started and is unfinished
22078 ((looking-at org-drawer-regexp)
22079 (goto-char (1- (match-beginning 1)))
22080 (setq column (current-column)))
22081 ;; Else, nothing noticeable found: get indentation and go on.
22082 (t (setq column (org-get-indentation))))))
22083 ;; Now apply indentation and move cursor accordingly
22084 (goto-char pos)
22085 (if (<= (current-column) (current-indentation))
22086 (org-indent-line-to column)
22087 (save-excursion (org-indent-line-to column)))
22088 ;; Special polishing for properties, see `org-property-format'
22089 (setq column (current-column))
22090 (beginning-of-line 1)
22091 (if (looking-at org-property-re)
22092 (replace-match (concat (match-string 4)
22093 (format org-property-format
22094 (match-string 1) (match-string 3)))
22095 t t))
22096 (org-move-to-column column))))
22098 (defun org-indent-drawer ()
22099 "Indent the drawer at point."
22100 (interactive)
22101 (let ((p (point))
22102 (e (and (save-excursion (re-search-forward ":END:" nil t))
22103 (match-end 0)))
22104 (folded
22105 (save-excursion
22106 (end-of-line)
22107 (when (overlays-at (point))
22108 (member 'invisible (overlay-properties
22109 (car (overlays-at (point)))))))))
22110 (when folded (org-cycle))
22111 (indent-for-tab-command)
22112 (while (and (move-beginning-of-line 2) (< (point) e))
22113 (indent-for-tab-command))
22114 (goto-char p)
22115 (when folded (org-cycle)))
22116 (message "Drawer at point indented"))
22118 (defun org-indent-block ()
22119 "Indent the block at point."
22120 (interactive)
22121 (let ((p (point))
22122 (case-fold-search t)
22123 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22124 (match-end 0)))
22125 (folded
22126 (save-excursion
22127 (end-of-line)
22128 (when (overlays-at (point))
22129 (member 'invisible (overlay-properties
22130 (car (overlays-at (point)))))))))
22131 (when folded (org-cycle))
22132 (indent-for-tab-command)
22133 (while (and (move-beginning-of-line 2) (< (point) e))
22134 (indent-for-tab-command))
22135 (goto-char p)
22136 (when folded (org-cycle)))
22137 (message "Block at point indented"))
22139 (defun org-indent-region (start end)
22140 "Indent region."
22141 (interactive "r")
22142 (save-excursion
22143 (let ((line-end (org-current-line end)))
22144 (goto-char start)
22145 (while (< (org-current-line) line-end)
22146 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22147 (t (call-interactively 'org-indent-line)))
22148 (move-beginning-of-line 2)))))
22151 ;;; Filling
22153 ;; We use our own fill-paragraph and auto-fill functions.
22155 ;; `org-fill-paragraph' relies on adaptive filling and context
22156 ;; checking. Appropriate `fill-prefix' is computed with
22157 ;; `org-adaptive-fill-function'.
22159 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22160 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22161 ;; `org-adaptive-fill-function' value. Internally,
22162 ;; `org-comment-line-break-function' breaks the line.
22164 ;; `org-setup-filling' installs filling and auto-filling related
22165 ;; variables during `org-mode' initialization.
22167 (defvar org-element-paragraph-separate) ; org-element.el
22168 (defun org-setup-filling ()
22169 (require 'org-element)
22170 ;; Prevent auto-fill from inserting unwanted new items.
22171 (when (boundp 'fill-nobreak-predicate)
22172 (org-set-local
22173 'fill-nobreak-predicate
22174 (org-uniquify
22175 (append fill-nobreak-predicate
22176 '(org-fill-line-break-nobreak-p
22177 org-fill-paragraph-with-timestamp-nobreak-p)))))
22178 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22179 (org-set-local 'paragraph-start paragraph-ending)
22180 (org-set-local 'paragraph-separate paragraph-ending))
22181 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22182 (org-set-local 'auto-fill-inhibit-regexp nil)
22183 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22184 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22185 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22187 (defun org-fill-line-break-nobreak-p ()
22188 "Non-nil when a new line at point would create an Org line break."
22189 (save-excursion
22190 (skip-chars-backward "[ \t]")
22191 (skip-chars-backward "\\\\")
22192 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22194 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22195 "Non-nil when a new line at point would split a timestamp."
22196 (and (org-at-timestamp-p t)
22197 (not (looking-at org-ts-regexp-both))))
22199 (declare-function message-in-body-p "message" ())
22200 (defvar orgtbl-line-start-regexp) ; From org-table.el
22201 (defun org-adaptive-fill-function ()
22202 "Compute a fill prefix for the current line.
22203 Return fill prefix, as a string, or nil if current line isn't
22204 meant to be filled. For convenience, if `adaptive-fill-regexp'
22205 matches in paragraphs or comments, use it."
22206 (catch 'exit
22207 (when (derived-mode-p 'message-mode)
22208 (save-excursion
22209 (beginning-of-line)
22210 (cond ((or (not (message-in-body-p))
22211 (looking-at orgtbl-line-start-regexp))
22212 (throw 'exit nil))
22213 ((looking-at message-cite-prefix-regexp)
22214 (throw 'exit (match-string-no-properties 0)))
22215 ((looking-at org-outline-regexp)
22216 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22217 (org-with-wide-buffer
22218 (let* ((p (line-beginning-position))
22219 (element (save-excursion
22220 (beginning-of-line)
22221 (or (ignore-errors (org-element-at-point))
22222 (user-error "An element cannot be parsed line %d"
22223 (line-number-at-pos (point))))))
22224 (type (org-element-type element))
22225 (post-affiliated (org-element-property :post-affiliated element)))
22226 (unless (and post-affiliated (< p post-affiliated))
22227 (case type
22228 (comment
22229 (save-excursion
22230 (beginning-of-line)
22231 (looking-at "[ \t]*")
22232 (concat (match-string 0) "# ")))
22233 (footnote-definition "")
22234 ((item plain-list)
22235 (make-string (org-list-item-body-column
22236 (or post-affiliated
22237 (org-element-property :begin element)))
22238 ? ))
22239 (paragraph
22240 ;; Fill prefix is usually the same as the current line,
22241 ;; unless the paragraph is at the beginning of an item.
22242 (let ((parent (org-element-property :parent element)))
22243 (save-excursion
22244 (beginning-of-line)
22245 (cond ((eq (org-element-type parent) 'item)
22246 (make-string (org-list-item-body-column
22247 (org-element-property :begin parent))
22248 ? ))
22249 ((and adaptive-fill-regexp
22250 ;; Locally disable
22251 ;; `adaptive-fill-function' to let
22252 ;; `fill-context-prefix' handle
22253 ;; `adaptive-fill-regexp' variable.
22254 (let (adaptive-fill-function)
22255 (fill-context-prefix
22256 post-affiliated
22257 (org-element-property :end element)))))
22258 ((looking-at "[ \t]+") (match-string 0))
22259 (t "")))))
22260 (comment-block
22261 ;; Only fill contents if P is within block boundaries.
22262 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22263 (forward-line)
22264 (point)))
22265 (cend (save-excursion
22266 (goto-char (org-element-property :end element))
22267 (skip-chars-backward " \r\t\n")
22268 (line-beginning-position))))
22269 (when (and (>= p cbeg) (< p cend))
22270 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22271 (match-string 0)
22272 ""))))))))))
22274 (declare-function message-goto-body "message" ())
22275 (defvar message-cite-prefix-regexp) ; From message.el
22276 (defun org-fill-paragraph (&optional justify)
22277 "Fill element at point, when applicable.
22279 This function only applies to comment blocks, comments, example
22280 blocks and paragraphs. Also, as a special case, re-align table
22281 when point is at one.
22283 If JUSTIFY is non-nil (interactively, with prefix argument),
22284 justify as well. If `sentence-end-double-space' is non-nil, then
22285 period followed by one space does not end a sentence, so don't
22286 break a line there. The variable `fill-column' controls the
22287 width for filling.
22289 For convenience, when point is at a plain list, an item or
22290 a footnote definition, try to fill the first paragraph within."
22291 (interactive)
22292 (if (and (derived-mode-p 'message-mode)
22293 (or (not (message-in-body-p))
22294 (save-excursion (move-beginning-of-line 1)
22295 (looking-at message-cite-prefix-regexp))))
22296 ;; First ensure filling is correct in message-mode.
22297 (let ((fill-paragraph-function
22298 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22299 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22300 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22301 (paragraph-separate
22302 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22303 (fill-paragraph nil))
22304 (with-syntax-table org-mode-transpose-word-syntax-table
22305 ;; Move to end of line in order to get the first paragraph
22306 ;; within a plain list or a footnote definition.
22307 (let ((element (save-excursion
22308 (end-of-line)
22309 (or (ignore-errors (org-element-at-point))
22310 (user-error "An element cannot be parsed line %d"
22311 (line-number-at-pos (point)))))))
22312 ;; First check if point is in a blank line at the beginning of
22313 ;; the buffer. In that case, ignore filling.
22314 (case (org-element-type element)
22315 ;; Use major mode filling function is src blocks.
22316 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22317 ;; Align Org tables, leave table.el tables as-is.
22318 (table-row (org-table-align) t)
22319 (table
22320 (when (eq (org-element-property :type element) 'org)
22321 (save-excursion
22322 (goto-char (org-element-property :post-affiliated element))
22323 (org-table-align)))
22325 (paragraph
22326 ;; Paragraphs may contain `line-break' type objects.
22327 (let ((beg (max (point-min)
22328 (org-element-property :contents-begin element)))
22329 (end (min (point-max)
22330 (org-element-property :contents-end element))))
22331 ;; Do nothing if point is at an affiliated keyword.
22332 (if (< (line-end-position) beg) t
22333 (when (derived-mode-p 'message-mode)
22334 ;; In `message-mode', do not fill following citation
22335 ;; in current paragraph nor text before message body.
22336 (let ((body-start (save-excursion (message-goto-body))))
22337 (when body-start (setq beg (max body-start beg))))
22338 (when (save-excursion
22339 (re-search-forward
22340 (concat "^" message-cite-prefix-regexp) end t))
22341 (setq end (match-beginning 0))))
22342 ;; Fill paragraph, taking line breaks into account.
22343 ;; For that, slice the paragraph using line breaks as
22344 ;; separators, and fill the parts in reverse order to
22345 ;; avoid messing with markers.
22346 (save-excursion
22347 (goto-char end)
22348 (mapc
22349 (lambda (pos)
22350 (fill-region-as-paragraph pos (point) justify)
22351 (goto-char pos))
22352 ;; Find the list of ending positions for line breaks
22353 ;; in the current paragraph. Add paragraph
22354 ;; beginning to include first slice.
22355 (nreverse
22356 (cons beg
22357 (org-element-map
22358 (org-element--parse-objects
22359 beg end nil (org-element-restriction 'paragraph))
22360 'line-break
22361 (lambda (lb) (org-element-property :end lb)))))))
22362 t)))
22363 ;; Contents of `comment-block' type elements should be
22364 ;; filled as plain text, but only if point is within block
22365 ;; markers.
22366 (comment-block
22367 (let* ((case-fold-search t)
22368 (beg (save-excursion
22369 (goto-char (org-element-property :begin element))
22370 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22371 (forward-line)
22372 (point)))
22373 (end (save-excursion
22374 (goto-char (org-element-property :end element))
22375 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22376 (line-beginning-position))))
22377 (if (or (< (point) beg) (> (point) end)) t
22378 (fill-region-as-paragraph
22379 (save-excursion (end-of-line)
22380 (re-search-backward "^[ \t]*$" beg 'move)
22381 (line-beginning-position))
22382 (save-excursion (beginning-of-line)
22383 (re-search-forward "^[ \t]*$" end 'move)
22384 (line-beginning-position))
22385 justify))))
22386 ;; Fill comments.
22387 (comment
22388 (let ((begin (org-element-property :post-affiliated element))
22389 (end (org-element-property :end element)))
22390 (when (and (>= (point) begin) (<= (point) end))
22391 (let ((begin (save-excursion
22392 (end-of-line)
22393 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22394 (progn (forward-line) (point))
22395 begin)))
22396 (end (save-excursion
22397 (end-of-line)
22398 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22399 (1- (line-beginning-position))
22400 (skip-chars-backward " \r\t\n")
22401 (line-end-position)))))
22402 ;; Do not fill comments when at a blank line.
22403 (when (> end begin)
22404 (let ((fill-prefix
22405 (save-excursion
22406 (beginning-of-line)
22407 (looking-at "[ \t]*#")
22408 (let ((comment-prefix (match-string 0)))
22409 (goto-char (match-end 0))
22410 (if (looking-at adaptive-fill-regexp)
22411 (concat comment-prefix (match-string 0))
22412 (concat comment-prefix " "))))))
22413 (save-excursion
22414 (fill-region-as-paragraph begin end justify))))))
22416 ;; Ignore every other element.
22417 (otherwise t))))))
22419 (defun org-auto-fill-function ()
22420 "Auto-fill function."
22421 ;; Check if auto-filling is meaningful.
22422 (let ((fc (current-fill-column)))
22423 (when (and fc (> (current-column) fc))
22424 (let* ((fill-prefix (org-adaptive-fill-function))
22425 ;; Enforce empty fill prefix, if required. Otherwise, it
22426 ;; will be computed again.
22427 (adaptive-fill-mode (not (equal fill-prefix ""))))
22428 (when fill-prefix (do-auto-fill))))))
22430 (defun org-comment-line-break-function (&optional soft)
22431 "Break line at point and indent, continuing comment if within one.
22432 The inserted newline is marked hard if variable
22433 `use-hard-newlines' is true, unless optional argument SOFT is
22434 non-nil."
22435 (if soft (insert-and-inherit ?\n) (newline 1))
22436 (save-excursion (forward-char -1) (delete-horizontal-space))
22437 (delete-horizontal-space)
22438 (indent-to-left-margin)
22439 (insert-before-markers-and-inherit fill-prefix))
22442 ;;; Comments
22444 ;; Org comments syntax is quite complex. It requires the entire line
22445 ;; to be just a comment. Also, even with the right syntax at the
22446 ;; beginning of line, some some elements (i.e. verse-block or
22447 ;; example-block) don't accept comments. Usual Emacs comment commands
22448 ;; cannot cope with those requirements. Therefore, Org replaces them.
22450 ;; Org still relies on `comment-dwim', but cannot trust
22451 ;; `comment-only-p'. So, `comment-region-function' and
22452 ;; `uncomment-region-function' both point
22453 ;; to`org-comment-or-uncomment-region'. Eventually,
22454 ;; `org-insert-comment' takes care of insertion of comments at the
22455 ;; beginning of line.
22457 ;; `org-setup-comments-handling' install comments related variables
22458 ;; during `org-mode' initialization.
22460 (defun org-setup-comments-handling ()
22461 (interactive)
22462 (org-set-local 'comment-use-syntax nil)
22463 (org-set-local 'comment-start "# ")
22464 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22465 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22466 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22467 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22469 (defun org-insert-comment ()
22470 "Insert an empty comment above current line.
22471 If the line is empty, insert comment at its beginning."
22472 (beginning-of-line)
22473 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22474 (org-indent-line)
22475 (insert "# "))
22477 (defvar comment-empty-lines) ; From newcomment.el.
22478 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22479 "Comment or uncomment each non-blank line in the region.
22480 Uncomment each non-blank line between BEG and END if it only
22481 contains commented lines. Otherwise, comment them."
22482 (save-restriction
22483 ;; Restrict region
22484 (narrow-to-region (save-excursion (goto-char beg)
22485 (skip-chars-forward " \r\t\n" end)
22486 (line-beginning-position))
22487 (save-excursion (goto-char end)
22488 (skip-chars-backward " \r\t\n" beg)
22489 (line-end-position)))
22490 (let ((uncommentp
22491 ;; UNCOMMENTP is non-nil when every non blank line between
22492 ;; BEG and END is a comment.
22493 (save-excursion
22494 (goto-char (point-min))
22495 (while (and (not (eobp))
22496 (let ((element (org-element-at-point)))
22497 (and (eq (org-element-type element) 'comment)
22498 (goto-char (min (point-max)
22499 (org-element-property
22500 :end element)))))))
22501 (eobp))))
22502 (if uncommentp
22503 ;; Only blank lines and comments in region: uncomment it.
22504 (save-excursion
22505 (goto-char (point-min))
22506 (while (not (eobp))
22507 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22508 (replace-match "" nil nil nil 1))
22509 (forward-line)))
22510 ;; Comment each line in region.
22511 (let ((min-indent (point-max)))
22512 ;; First find the minimum indentation across all lines.
22513 (save-excursion
22514 (goto-char (point-min))
22515 (while (and (not (eobp)) (not (zerop min-indent)))
22516 (unless (looking-at "[ \t]*$")
22517 (setq min-indent (min min-indent (current-indentation))))
22518 (forward-line)))
22519 ;; Then loop over all lines.
22520 (save-excursion
22521 (goto-char (point-min))
22522 (while (not (eobp))
22523 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22524 ;; Don't get fooled by invisible text (e.g. link path)
22525 ;; when moving to column MIN-INDENT.
22526 (let ((buffer-invisibility-spec nil))
22527 (org-move-to-column min-indent t))
22528 (insert comment-start))
22529 (forward-line))))))))
22532 ;;; Planning
22534 ;; This section contains tools to operate on timestamp objects, as
22535 ;; returned by, e.g. `org-element-context'.
22537 (defun org-timestamp-has-time-p (timestamp)
22538 "Non-nil when TIMESTAMP has a time specified."
22539 (org-element-property :hour-start timestamp))
22541 (defun org-timestamp-format (timestamp format &optional end utc)
22542 "Format a TIMESTAMP element into a string.
22544 FORMAT is a format specifier to be passed to
22545 `format-time-string'.
22547 When optional argument END is non-nil, use end of date-range or
22548 time-range, if possible.
22550 When optional argument UTC is non-nil, time will be expressed as
22551 Universal Time."
22552 (format-time-string
22553 format
22554 (apply 'encode-time
22555 (cons 0
22556 (mapcar
22557 (lambda (prop) (or (org-element-property prop timestamp) 0))
22558 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22559 '(:minute-start :hour-start :day-start :month-start
22560 :year-start)))))
22561 utc))
22563 (defun org-timestamp-split-range (timestamp &optional end)
22564 "Extract a timestamp object from a date or time range.
22566 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22567 the end of the range. Otherwise, extract its start.
22569 Return a new timestamp object sharing the same parent as
22570 TIMESTAMP."
22571 (let ((type (org-element-property :type timestamp)))
22572 (if (memq type '(active inactive diary)) timestamp
22573 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22574 ;; Set new type.
22575 (org-element-put-property
22576 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22577 ;; Copy start properties over end properties if END is
22578 ;; non-nil. Otherwise, copy end properties over `start' ones.
22579 (let ((p-alist '((:minute-start . :minute-end)
22580 (:hour-start . :hour-end)
22581 (:day-start . :day-end)
22582 (:month-start . :month-end)
22583 (:year-start . :year-end))))
22584 (dolist (p-cell p-alist)
22585 (org-element-put-property
22586 split-ts
22587 (funcall (if end 'car 'cdr) p-cell)
22588 (org-element-property
22589 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22590 ;; Eventually refresh `:raw-value'.
22591 (org-element-put-property split-ts :raw-value nil)
22592 (org-element-put-property
22593 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22595 (defun org-timestamp-translate (timestamp &optional boundary)
22596 "Apply `org-translate-time' on a TIMESTAMP object.
22597 When optional argument BOUNDARY is non-nil, it is either the
22598 symbol `start' or `end'. In this case, only translate the
22599 starting or ending part of TIMESTAMP if it is a date or time
22600 range. Otherwise, translate both parts."
22601 (if (and (not boundary)
22602 (memq (org-element-property :type timestamp)
22603 '(active-range inactive-range)))
22604 (concat
22605 (org-translate-time
22606 (org-element-property :raw-value
22607 (org-timestamp-split-range timestamp)))
22608 "--"
22609 (org-translate-time
22610 (org-element-property :raw-value
22611 (org-timestamp-split-range timestamp t))))
22612 (org-translate-time
22613 (org-element-property
22614 :raw-value
22615 (if (not boundary) timestamp
22616 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22620 ;;; Other stuff.
22622 (defun org-toggle-fixed-width-section (arg)
22623 "Toggle the fixed-width export.
22624 If there is no active region, the QUOTE keyword at the current headline is
22625 inserted or removed. When present, it causes the text between this headline
22626 and the next to be exported as fixed-width text, and unmodified.
22627 If there is an active region, this command adds or removes a colon as the
22628 first character of this line. If the first character of a line is a colon,
22629 this line is also exported in fixed-width font."
22630 (interactive "P")
22631 (let* ((cc 0)
22632 (regionp (org-region-active-p))
22633 (beg (if regionp (region-beginning) (point)))
22634 (end (if regionp (region-end)))
22635 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22636 (case-fold-search nil)
22637 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22638 off)
22639 (if regionp
22640 (save-excursion
22641 (goto-char beg)
22642 (setq cc (current-column))
22643 (beginning-of-line 1)
22644 (setq off (looking-at re))
22645 (while (> nlines 0)
22646 (setq nlines (1- nlines))
22647 (beginning-of-line 1)
22648 (cond
22649 (arg
22650 (org-move-to-column cc t)
22651 (insert ": \n")
22652 (forward-line -1))
22653 ((and off (looking-at re))
22654 (replace-match "" t t nil 1))
22655 ((not off) (org-move-to-column cc t) (insert ": ")))
22656 (forward-line 1)))
22657 (save-excursion
22658 (org-back-to-heading)
22659 (cond
22660 ((looking-at (format org-heading-keyword-regexp-format
22661 org-quote-string))
22662 (goto-char (match-end 1))
22663 (looking-at (concat " +" org-quote-string))
22664 (replace-match "" t t)
22665 (when (eolp) (insert " ")))
22666 ((looking-at org-outline-regexp)
22667 (goto-char (match-end 0))
22668 (insert org-quote-string " ")))))))
22670 (defun org-reftex-citation ()
22671 "Use reftex-citation to insert a citation into the buffer.
22672 This looks for a line like
22674 #+BIBLIOGRAPHY: foo plain option:-d
22676 and derives from it that foo.bib is the bibliography file relevant
22677 for this document. It then installs the necessary environment for RefTeX
22678 to work in this buffer and calls `reftex-citation' to insert a citation
22679 into the buffer.
22681 Export of such citations to both LaTeX and HTML is handled by the contributed
22682 package ox-bibtex by Taru Karttunen."
22683 (interactive)
22684 (let ((reftex-docstruct-symbol 'rds)
22685 (reftex-cite-format "\\cite{%l}")
22686 rds bib)
22687 (save-excursion
22688 (save-restriction
22689 (widen)
22690 (let ((case-fold-search t)
22691 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22692 (if (not (save-excursion
22693 (or (re-search-forward re nil t)
22694 (re-search-backward re nil t))))
22695 (error "No bibliography defined in file")
22696 (setq bib (concat (match-string 1) ".bib")
22697 rds (list (list 'bib bib)))))))
22698 (call-interactively 'reftex-citation)))
22700 ;;;; Functions extending outline functionality
22702 (defun org-beginning-of-line (&optional arg)
22703 "Go to the beginning of the current line. If that is invisible, continue
22704 to a visible line beginning. This makes the function of C-a more intuitive.
22705 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22706 first attempt, and only move to after the tags when the cursor is already
22707 beyond the end of the headline."
22708 (interactive "P")
22709 (let ((pos (point))
22710 (special (if (consp org-special-ctrl-a/e)
22711 (car org-special-ctrl-a/e)
22712 org-special-ctrl-a/e))
22713 deactivate-mark refpos)
22714 (if (org-bound-and-true-p visual-line-mode)
22715 (beginning-of-visual-line 1)
22716 (beginning-of-line 1))
22717 (if (and arg (fboundp 'move-beginning-of-line))
22718 (call-interactively 'move-beginning-of-line)
22719 (if (bobp)
22721 (backward-char 1)
22722 (if (org-truely-invisible-p)
22723 (while (and (not (bobp)) (org-truely-invisible-p))
22724 (backward-char 1)
22725 (beginning-of-line 1))
22726 (forward-char 1))))
22727 (when special
22728 (cond
22729 ((and (looking-at org-complex-heading-regexp)
22730 (= (char-after (match-end 1)) ?\ ))
22731 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22732 (point-at-eol)))
22733 (goto-char
22734 (if (eq special t)
22735 (cond ((> pos refpos) refpos)
22736 ((= pos (point)) refpos)
22737 (t (point)))
22738 (cond ((> pos (point)) (point))
22739 ((not (eq last-command this-command)) (point))
22740 (t refpos)))))
22741 ((org-at-item-p)
22742 ;; Being at an item and not looking at an the item means point
22743 ;; was previously moved to beginning of a visual line, which
22744 ;; doesn't contain the item. Therefore, do nothing special,
22745 ;; just stay here.
22746 (when (looking-at org-list-full-item-re)
22747 ;; Set special position at first white space character after
22748 ;; bullet, and check-box, if any.
22749 (let ((after-bullet
22750 (let ((box (match-end 3)))
22751 (if (not box) (match-end 1)
22752 (let ((after (char-after box)))
22753 (if (and after (= after ? )) (1+ box) box))))))
22754 ;; Special case: Move point to special position when
22755 ;; currently after it or at beginning of line.
22756 (if (eq special t)
22757 (when (or (> pos after-bullet) (= (point) pos))
22758 (goto-char after-bullet))
22759 ;; Reversed case: Move point to special position when
22760 ;; point was already at beginning of line and command is
22761 ;; repeated.
22762 (when (and (= (point) pos) (eq last-command this-command))
22763 (goto-char after-bullet))))))))
22764 (org-no-warnings
22765 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22766 (setq disable-point-adjustment
22767 (or (not (invisible-p (point)))
22768 (not (invisible-p (max (point-min) (1- (point))))))))
22770 (defun org-end-of-line (&optional arg)
22771 "Go to the end of the line.
22772 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22773 tags on the first attempt, and only move to after the tags when
22774 the cursor is already beyond the end of the headline."
22775 (interactive "P")
22776 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22777 org-special-ctrl-a/e))
22778 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22779 'end-of-visual-line)
22780 ((fboundp 'move-end-of-line) 'move-end-of-line)
22781 (t 'end-of-line)))
22782 deactivate-mark)
22783 (if (or (not special) arg) (call-interactively move-fun)
22784 (let* ((element (save-excursion (beginning-of-line)
22785 (org-element-at-point)))
22786 (type (org-element-type element)))
22787 (cond
22788 ((memq type '(headline inlinetask))
22789 (let ((pos (point)))
22790 (beginning-of-line 1)
22791 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22792 (if (eq special t)
22793 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22794 (goto-char (match-beginning 1))
22795 (goto-char (match-end 0)))
22796 (if (or (< pos (match-end 0))
22797 (not (eq this-command last-command)))
22798 (goto-char (match-end 0))
22799 (goto-char (match-beginning 1))))
22800 (call-interactively move-fun))))
22801 ((org-element-property :hiddenp element)
22802 ;; If element is hidden, `move-end-of-line' would put point
22803 ;; after it. Use `end-of-line' to stay on current line.
22804 (call-interactively 'end-of-line))
22805 (t (call-interactively move-fun)))))
22806 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22807 (setq disable-point-adjustment
22808 (or (not (invisible-p (point)))
22809 (not (invisible-p (max (point-min) (1- (point))))))))
22811 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22812 (define-key org-mode-map "\C-e" 'org-end-of-line)
22814 (defun org-backward-sentence (&optional arg)
22815 "Go to beginning of sentence, or beginning of table field.
22816 This will call `backward-sentence' or `org-table-beginning-of-field',
22817 depending on context."
22818 (interactive "P")
22819 (cond
22820 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22821 (t (call-interactively 'backward-sentence))))
22823 (defun org-forward-sentence (&optional arg)
22824 "Go to end of sentence, or end of table field.
22825 This will call `forward-sentence' or `org-table-end-of-field',
22826 depending on context."
22827 (interactive "P")
22828 (cond
22829 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22830 (t (call-interactively 'forward-sentence))))
22832 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22833 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22835 (defun org-kill-line (&optional arg)
22836 "Kill line, to tags or end of line."
22837 (interactive "P")
22838 (cond
22839 ((or (not org-special-ctrl-k)
22840 (bolp)
22841 (not (org-at-heading-p)))
22842 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22843 org-ctrl-k-protect-subtree)
22844 (if (or (eq org-ctrl-k-protect-subtree 'error)
22845 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22846 (user-error "C-k aborted as it would kill a hidden subtree")))
22847 (call-interactively
22848 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22849 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22850 (kill-region (point) (match-beginning 1))
22851 (org-set-tags nil t))
22852 (t (kill-region (point) (point-at-eol)))))
22854 (define-key org-mode-map "\C-k" 'org-kill-line)
22856 (defun org-yank (&optional arg)
22857 "Yank. If the kill is a subtree, treat it specially.
22858 This command will look at the current kill and check if is a single
22859 subtree, or a series of subtrees[1]. If it passes the test, and if the
22860 cursor is at the beginning of a line or after the stars of a currently
22861 empty headline, then the yank is handled specially. How exactly depends
22862 on the value of the following variables, both set by default.
22864 org-yank-folded-subtrees
22865 When set, the subtree(s) will be folded after insertion, but only
22866 if doing so would now swallow text after the yanked text.
22868 org-yank-adjusted-subtrees
22869 When set, the subtree will be promoted or demoted in order to
22870 fit into the local outline tree structure, which means that the level
22871 will be adjusted so that it becomes the smaller one of the two
22872 *visible* surrounding headings.
22874 Any prefix to this command will cause `yank' to be called directly with
22875 no special treatment. In particular, a simple \\[universal-argument] prefix \
22876 will just
22877 plainly yank the text as it is.
22879 \[1] The test checks if the first non-white line is a heading
22880 and if there are no other headings with fewer stars."
22881 (interactive "P")
22882 (org-yank-generic 'yank arg))
22884 (defun org-yank-generic (command arg)
22885 "Perform some yank-like command.
22887 This function implements the behavior described in the `org-yank'
22888 documentation. However, it has been generalized to work for any
22889 interactive command with similar behavior."
22891 ;; pretend to be command COMMAND
22892 (setq this-command command)
22894 (if arg
22895 (call-interactively command)
22897 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22898 (and (org-kill-is-subtree-p)
22899 (or (bolp)
22900 (and (looking-at "[ \t]*$")
22901 (string-match
22902 "\\`\\*+\\'"
22903 (buffer-substring (point-at-bol) (point)))))))
22904 swallowp)
22905 (cond
22906 ((and subtreep org-yank-folded-subtrees)
22907 (let ((beg (point))
22908 end)
22909 (if (and subtreep org-yank-adjusted-subtrees)
22910 (org-paste-subtree nil nil 'for-yank)
22911 (call-interactively command))
22913 (setq end (point))
22914 (goto-char beg)
22915 (when (and (bolp) subtreep
22916 (not (setq swallowp
22917 (org-yank-folding-would-swallow-text beg end))))
22918 (org-with-limited-levels
22919 (or (looking-at org-outline-regexp)
22920 (re-search-forward org-outline-regexp-bol end t))
22921 (while (and (< (point) end) (looking-at org-outline-regexp))
22922 (hide-subtree)
22923 (org-cycle-show-empty-lines 'folded)
22924 (condition-case nil
22925 (outline-forward-same-level 1)
22926 (error (goto-char end))))))
22927 (when swallowp
22928 (message
22929 "Inserted text not folded because that would swallow text"))
22931 (goto-char end)
22932 (skip-chars-forward " \t\n\r")
22933 (beginning-of-line 1)
22934 (push-mark beg 'nomsg)))
22935 ((and subtreep org-yank-adjusted-subtrees)
22936 (let ((beg (point-at-bol)))
22937 (org-paste-subtree nil nil 'for-yank)
22938 (push-mark beg 'nomsg)))
22940 (call-interactively command))))))
22942 (defun org-yank-folding-would-swallow-text (beg end)
22943 "Would hide-subtree at BEG swallow any text after END?"
22944 (let (level)
22945 (org-with-limited-levels
22946 (save-excursion
22947 (goto-char beg)
22948 (when (or (looking-at org-outline-regexp)
22949 (re-search-forward org-outline-regexp-bol end t))
22950 (setq level (org-outline-level)))
22951 (goto-char end)
22952 (skip-chars-forward " \t\r\n\v\f")
22953 (if (or (eobp)
22954 (and (bolp) (looking-at org-outline-regexp)
22955 (<= (org-outline-level) level)))
22956 nil ; Nothing would be swallowed
22957 t))))) ; something would swallow
22959 (define-key org-mode-map "\C-y" 'org-yank)
22961 (defun org-truely-invisible-p ()
22962 "Check if point is at a character currently not visible.
22963 This version does not only check the character property, but also
22964 `visible-mode'."
22965 ;; Early versions of noutline don't have `outline-invisible-p'.
22966 (if (org-bound-and-true-p visible-mode)
22968 (outline-invisible-p)))
22970 (defun org-invisible-p2 ()
22971 "Check if point is at a character currently not visible."
22972 (save-excursion
22973 (if (and (eolp) (not (bobp))) (backward-char 1))
22974 ;; Early versions of noutline don't have `outline-invisible-p'.
22975 (outline-invisible-p)))
22977 (defun org-back-to-heading (&optional invisible-ok)
22978 "Call `outline-back-to-heading', but provide a better error message."
22979 (condition-case nil
22980 (outline-back-to-heading invisible-ok)
22981 (error (error "Before first headline at position %d in buffer %s"
22982 (point) (current-buffer)))))
22984 (defun org-before-first-heading-p ()
22985 "Before first heading?"
22986 (save-excursion
22987 (end-of-line)
22988 (null (re-search-backward org-outline-regexp-bol nil t))))
22990 (defun org-at-heading-p (&optional ignored)
22991 (outline-on-heading-p t))
22992 ;; Compatibility alias with Org versions < 7.8.03
22993 (defalias 'org-on-heading-p 'org-at-heading-p)
22995 (defun org-at-comment-p nil
22996 "Is cursor in a line starting with a # character?"
22997 (save-excursion
22998 (beginning-of-line)
22999 (looking-at "^#")))
23001 (defun org-at-drawer-p nil
23002 "Is cursor at a drawer keyword?"
23003 (save-excursion
23004 (move-beginning-of-line 1)
23005 (looking-at org-drawer-regexp)))
23007 (defun org-at-block-p nil
23008 "Is cursor at a block keyword?"
23009 (save-excursion
23010 (move-beginning-of-line 1)
23011 (looking-at org-block-regexp)))
23013 (defun org-point-at-end-of-empty-headline ()
23014 "If point is at the end of an empty headline, return t, else nil.
23015 If the heading only contains a TODO keyword, it is still still considered
23016 empty."
23017 (and (looking-at "[ \t]*$")
23018 (when org-todo-line-regexp
23019 (save-excursion
23020 (beginning-of-line 1)
23021 (let ((case-fold-search nil))
23022 (looking-at org-todo-line-regexp)
23023 (string= (match-string 3) ""))))))
23025 (defun org-at-heading-or-item-p ()
23026 (or (org-at-heading-p) (org-at-item-p)))
23028 (defun org-at-target-p ()
23029 (or (org-in-regexp org-radio-target-regexp)
23030 (org-in-regexp org-target-regexp)))
23031 ;; Compatibility alias with Org versions < 7.8.03
23032 (defalias 'org-on-target-p 'org-at-target-p)
23034 (defun org-up-heading-all (arg)
23035 "Move to the heading line of which the present line is a subheading.
23036 This function considers both visible and invisible heading lines.
23037 With argument, move up ARG levels."
23038 (if (fboundp 'outline-up-heading-all)
23039 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23040 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23042 (defun org-up-heading-safe ()
23043 "Move to the heading line of which the present line is a subheading.
23044 This version will not throw an error. It will return the level of the
23045 headline found, or nil if no higher level is found.
23047 Also, this function will be a lot faster than `outline-up-heading',
23048 because it relies on stars being the outline starters. This can really
23049 make a significant difference in outlines with very many siblings."
23050 (let (start-level re)
23051 (org-back-to-heading t)
23052 (setq start-level (funcall outline-level))
23053 (if (equal start-level 1)
23055 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23056 (if (re-search-backward re nil t)
23057 (funcall outline-level)))))
23059 (defun org-first-sibling-p ()
23060 "Is this heading the first child of its parents?"
23061 (interactive)
23062 (let ((re org-outline-regexp-bol)
23063 level l)
23064 (unless (org-at-heading-p t)
23065 (user-error "Not at a heading"))
23066 (setq level (funcall outline-level))
23067 (save-excursion
23068 (if (not (re-search-backward re nil t))
23070 (setq l (funcall outline-level))
23071 (< l level)))))
23073 (defun org-goto-sibling (&optional previous)
23074 "Goto the next sibling, even if it is invisible.
23075 When PREVIOUS is set, go to the previous sibling instead. Returns t
23076 when a sibling was found. When none is found, return nil and don't
23077 move point."
23078 (let ((fun (if previous 're-search-backward 're-search-forward))
23079 (pos (point))
23080 (re org-outline-regexp-bol)
23081 level l)
23082 (when (condition-case nil (org-back-to-heading t) (error nil))
23083 (setq level (funcall outline-level))
23084 (catch 'exit
23085 (or previous (forward-char 1))
23086 (while (funcall fun re nil t)
23087 (setq l (funcall outline-level))
23088 (when (< l level) (goto-char pos) (throw 'exit nil))
23089 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23090 (goto-char pos)
23091 nil))))
23093 (defun org-show-siblings ()
23094 "Show all siblings of the current headline."
23095 (save-excursion
23096 (while (org-goto-sibling) (org-flag-heading nil)))
23097 (save-excursion
23098 (while (org-goto-sibling 'previous)
23099 (org-flag-heading nil))))
23101 (defun org-goto-first-child ()
23102 "Goto the first child, even if it is invisible.
23103 Return t when a child was found. Otherwise don't move point and
23104 return nil."
23105 (let (level (pos (point)) (re org-outline-regexp-bol))
23106 (when (condition-case nil (org-back-to-heading t) (error nil))
23107 (setq level (outline-level))
23108 (forward-char 1)
23109 (if (and (re-search-forward re nil t) (> (outline-level) level))
23110 (progn (goto-char (match-beginning 0)) t)
23111 (goto-char pos) nil))))
23113 (defun org-show-hidden-entry ()
23114 "Show an entry where even the heading is hidden."
23115 (save-excursion
23116 (org-show-entry)))
23118 (defun org-flag-heading (flag &optional entry)
23119 "Flag the current heading. FLAG non-nil means make invisible.
23120 When ENTRY is non-nil, show the entire entry."
23121 (save-excursion
23122 (org-back-to-heading t)
23123 ;; Check if we should show the entire entry
23124 (if entry
23125 (progn
23126 (org-show-entry)
23127 (save-excursion
23128 (and (outline-next-heading)
23129 (org-flag-heading nil))))
23130 (outline-flag-region (max (point-min) (1- (point)))
23131 (save-excursion (outline-end-of-heading) (point))
23132 flag))))
23134 (defun org-get-next-sibling ()
23135 "Move to next heading of the same level, and return point.
23136 If there is no such heading, return nil.
23137 This is like outline-next-sibling, but invisible headings are ok."
23138 (let ((level (funcall outline-level)))
23139 (outline-next-heading)
23140 (while (and (not (eobp)) (> (funcall outline-level) level))
23141 (outline-next-heading))
23142 (if (or (eobp) (< (funcall outline-level) level))
23144 (point))))
23146 (defun org-get-last-sibling ()
23147 "Move to previous heading of the same level, and return point.
23148 If there is no such heading, return nil."
23149 (let ((opoint (point))
23150 (level (funcall outline-level)))
23151 (outline-previous-heading)
23152 (when (and (/= (point) opoint) (outline-on-heading-p t))
23153 (while (and (> (funcall outline-level) level)
23154 (not (bobp)))
23155 (outline-previous-heading))
23156 (if (< (funcall outline-level) level)
23158 (point)))))
23160 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23161 "Goto to the end of a subtree."
23162 ;; This contains an exact copy of the original function, but it uses
23163 ;; `org-back-to-heading', to make it work also in invisible
23164 ;; trees. And is uses an invisible-ok argument.
23165 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23166 ;; Furthermore, when used inside Org, finding the end of a large subtree
23167 ;; with many children and grandchildren etc, this can be much faster
23168 ;; than the outline version.
23169 (org-back-to-heading invisible-ok)
23170 (let ((first t)
23171 (level (funcall outline-level)))
23172 (if (and (derived-mode-p 'org-mode) (< level 1000))
23173 ;; A true heading (not a plain list item), in Org-mode
23174 ;; This means we can easily find the end by looking
23175 ;; only for the right number of stars. Using a regexp to do
23176 ;; this is so much faster than using a Lisp loop.
23177 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23178 (forward-char 1)
23179 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23180 ;; something else, do it the slow way
23181 (while (and (not (eobp))
23182 (or first (> (funcall outline-level) level)))
23183 (setq first nil)
23184 (outline-next-heading)))
23185 (unless to-heading
23186 (if (memq (preceding-char) '(?\n ?\^M))
23187 (progn
23188 ;; Go to end of line before heading
23189 (forward-char -1)
23190 (if (memq (preceding-char) '(?\n ?\^M))
23191 ;; leave blank line before heading
23192 (forward-char -1))))))
23193 (point))
23195 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23196 "Use Org version in org-mode, for dramatic speed-up."
23197 (if (derived-mode-p 'org-mode)
23198 (progn
23199 (org-end-of-subtree nil t)
23200 (unless (eobp) (backward-char 1)))
23201 ad-do-it))
23203 (defun org-end-of-meta-data-and-drawers ()
23204 "Jump to the first text after meta data and drawers in the current entry.
23205 This will move over empty lines, lines with planning time stamps,
23206 clocking lines, and drawers."
23207 (org-back-to-heading t)
23208 (let ((end (save-excursion (outline-next-heading) (point)))
23209 (re (concat "\\(" org-drawer-regexp "\\)"
23210 "\\|" "[ \t]*" org-keyword-time-regexp)))
23211 (forward-line 1)
23212 (while (re-search-forward re end t)
23213 (if (not (match-end 1))
23214 ;; empty or planning line
23215 (forward-line 1)
23216 ;; a drawer, find the end
23217 (re-search-forward "^[ \t]*:END:" end 'move)
23218 (forward-line 1)))
23219 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23220 (point)))
23222 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23223 "Move forward to the ARG'th subheading at same level as this one.
23224 Stop at the first and last subheadings of a superior heading.
23225 Normally this only looks at visible headings, but when INVISIBLE-OK is
23226 non-nil it will also look at invisible ones."
23227 (interactive "p")
23228 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23229 (if (and arg (< arg 0))
23230 (goto-char (point-min))
23231 (outline-next-heading))
23232 (org-at-heading-p)
23233 (let ((level (- (match-end 0) (match-beginning 0) 1))
23234 (f (if (and arg (< arg 0))
23235 're-search-backward
23236 're-search-forward))
23237 (count (if arg (abs arg) 1))
23238 (result (point)))
23239 (while (and (prog1 (> count 0)
23240 (forward-char (if (and arg (< arg 0)) -1 1)))
23241 (funcall f org-outline-regexp-bol nil 'move))
23242 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23243 (cond ((< l level) (setq count 0))
23244 ((and (= l level)
23245 (or invisible-ok
23246 (progn
23247 (goto-char (line-beginning-position))
23248 (not (outline-invisible-p)))))
23249 (setq count (1- count))
23250 (when (eq l level)
23251 (setq result (point)))))))
23252 (goto-char result))
23253 (beginning-of-line 1)))
23255 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23256 "Move backward to the ARG'th subheading at same level as this one.
23257 Stop at the first and last subheadings of a superior heading."
23258 (interactive "p")
23259 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23261 (defun org-next-block (arg &optional backward block-regexp)
23262 "Jump to the next block.
23263 With a prefix argument ARG, jump forward ARG many source blocks.
23264 When BACKWARD is non-nil, jump to the previous block.
23265 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23266 (interactive "p")
23267 (let ((re (or block-regexp org-block-regexp))
23268 (re-search-fn (or (and backward 're-search-backward)
23269 're-search-forward)))
23270 (if (looking-at re) (forward-char 1))
23271 (condition-case nil
23272 (funcall re-search-fn re nil nil arg)
23273 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23274 (goto-char (match-beginning 0)) (org-show-context)))
23276 (defun org-previous-block (arg &optional block-regexp)
23277 "Jump to the previous block.
23278 With a prefix argument ARG, jump backward ARG many source blocks.
23279 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23280 (interactive "p")
23281 (org-next-block arg t block-regexp))
23283 (defun org-forward-paragraph ()
23284 "Move forward to beginning of next paragraph or equivalent.
23286 The function moves point to the beginning of the next visible
23287 structural element, which can be a paragraph, a table, a list
23288 item, etc. It also provides some special moves for convenience:
23290 - On an affiliated keyword, jump to the beginning of the
23291 relative element.
23292 - On an item or a footnote definition, move to the second
23293 element inside, if any.
23294 - On a table or a property drawer, jump after it.
23295 - On a verse or source block, stop after blank lines."
23296 (interactive)
23297 (when (eobp) (user-error "Cannot move further down"))
23298 (let* ((deactivate-mark nil)
23299 (element (org-element-at-point))
23300 (type (org-element-type element))
23301 (post-affiliated (org-element-property :post-affiliated element))
23302 (contents-begin (org-element-property :contents-begin element))
23303 (contents-end (org-element-property :contents-end element))
23304 (end (let ((end (org-element-property :end element)) (parent element))
23305 (while (and (setq parent (org-element-property :parent parent))
23306 (= (org-element-property :contents-end parent) end))
23307 (setq end (org-element-property :end parent)))
23308 end)))
23309 (cond ((not element)
23310 (skip-chars-forward " \r\t\n")
23311 (or (eobp) (beginning-of-line)))
23312 ;; On affiliated keywords, move to element's beginning.
23313 ((and post-affiliated (< (point) post-affiliated))
23314 (goto-char post-affiliated))
23315 ;; At a table row, move to the end of the table. Similarly,
23316 ;; at a node property, move to the end of the property
23317 ;; drawer.
23318 ((memq type '(node-property table-row))
23319 (goto-char (org-element-property
23320 :end (org-element-property :parent element))))
23321 ((memq type '(property-drawer table)) (goto-char end))
23322 ;; Consider blank lines as separators in verse and source
23323 ;; blocks to ease editing.
23324 ((memq type '(src-block verse-block))
23325 (when (eq type 'src-block)
23326 (setq contents-end
23327 (save-excursion (goto-char end)
23328 (skip-chars-backward " \r\t\n")
23329 (line-beginning-position))))
23330 (beginning-of-line)
23331 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23332 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23333 (goto-char end)
23334 (skip-chars-forward " \r\t\n")
23335 (if (= (point) contents-end) (goto-char end)
23336 (beginning-of-line))))
23337 ;; With no contents, just skip element.
23338 ((not contents-begin) (goto-char end))
23339 ;; If contents are invisible, skip the element altogether.
23340 ((outline-invisible-p (line-end-position))
23341 (case type
23342 (headline
23343 (org-with-limited-levels (outline-next-visible-heading 1)))
23344 ;; At a plain list, make sure we move to the next item
23345 ;; instead of skipping the whole list.
23346 (plain-list (forward-char)
23347 (org-forward-paragraph))
23348 (otherwise (goto-char end))))
23349 ((>= (point) contents-end) (goto-char end))
23350 ((>= (point) contents-begin)
23351 ;; This can only happen on paragraphs and plain lists.
23352 (case type
23353 (paragraph (goto-char end))
23354 ;; At a plain list, try to move to second element in
23355 ;; first item, if possible.
23356 (plain-list (end-of-line)
23357 (org-forward-paragraph))))
23358 ;; When contents start on the middle of a line (e.g. in
23359 ;; items and footnote definitions), try to reach first
23360 ;; element starting after current line.
23361 ((> (line-end-position) contents-begin)
23362 (end-of-line)
23363 (org-forward-paragraph))
23364 (t (goto-char contents-begin)))))
23366 (defun org-backward-paragraph ()
23367 "Move backward to start of previous paragraph or equivalent.
23369 The function moves point to the beginning of the current
23370 structural element, which can be a paragraph, a table, a list
23371 item, etc., or to the beginning of the previous visible one if
23372 point is already there. It also provides some special moves for
23373 convenience:
23375 - On an affiliated keyword, jump to the first one.
23376 - On a table or a property drawer, move to its beginning.
23377 - On a verse or source block, stop before blank lines."
23378 (interactive)
23379 (when (bobp) (user-error "Cannot move further up"))
23380 (let* ((deactivate-mark nil)
23381 (element (org-element-at-point))
23382 (type (org-element-type element))
23383 (contents-begin (org-element-property :contents-begin element))
23384 (contents-end (org-element-property :contents-end element))
23385 (post-affiliated (org-element-property :post-affiliated element))
23386 (begin (org-element-property :begin element)))
23387 (cond
23388 ((not element) (goto-char (point-min)))
23389 ((= (point) begin)
23390 (backward-char)
23391 (org-backward-paragraph))
23392 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23393 ((memq type '(node-property table-row))
23394 (goto-char (org-element-property
23395 :post-affiliated (org-element-property :parent element))))
23396 ((memq type '(property-drawer table)) (goto-char begin))
23397 ((memq type '(src-block verse-block))
23398 (when (eq type 'src-block)
23399 (setq contents-begin
23400 (save-excursion (goto-char begin) (forward-line) (point))))
23401 (if (= (point) contents-begin) (goto-char post-affiliated)
23402 ;; Inside a verse block, see blank lines as paragraph
23403 ;; separators.
23404 (let ((origin (point)))
23405 (skip-chars-backward " \r\t\n" contents-begin)
23406 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23407 (skip-chars-forward " \r\t\n" origin)
23408 (if (= (point) origin) (goto-char contents-begin)
23409 (beginning-of-line))))))
23410 ((not contents-begin) (goto-char (or post-affiliated begin)))
23411 ((eq type 'paragraph)
23412 (goto-char contents-begin)
23413 ;; When at first paragraph in an item or a footnote definition,
23414 ;; move directly to beginning of line.
23415 (let ((parent-contents
23416 (org-element-property
23417 :contents-begin (org-element-property :parent element))))
23418 (when (and parent-contents (= parent-contents contents-begin))
23419 (beginning-of-line))))
23420 ;; At the end of a greater element, move to the beginning of the
23421 ;; last element within.
23422 ((>= (point) contents-end)
23423 (goto-char (1- contents-end))
23424 (org-backward-paragraph))
23425 (t (goto-char (or post-affiliated begin))))
23426 ;; Ensure we never leave point invisible.
23427 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23429 (defun org-forward-element ()
23430 "Move forward by one element.
23431 Move to the next element at the same level, when possible."
23432 (interactive)
23433 (cond ((eobp) (user-error "Cannot move further down"))
23434 ((org-with-limited-levels (org-at-heading-p))
23435 (let ((origin (point)))
23436 (goto-char (org-end-of-subtree nil t))
23437 (unless (org-with-limited-levels (org-at-heading-p))
23438 (goto-char origin)
23439 (user-error "Cannot move further down"))))
23441 (let* ((elem (org-element-at-point))
23442 (end (org-element-property :end elem))
23443 (parent (org-element-property :parent elem)))
23444 (cond ((and parent (= (org-element-property :contents-end parent) end))
23445 (goto-char (org-element-property :end parent)))
23446 ((integer-or-marker-p end) (goto-char end))
23447 (t (message "No element at point")))))))
23449 (defun org-backward-element ()
23450 "Move backward by one element.
23451 Move to the previous element at the same level, when possible."
23452 (interactive)
23453 (cond ((bobp) (user-error "Cannot move further up"))
23454 ((org-with-limited-levels (org-at-heading-p))
23455 ;; At a headline, move to the previous one, if any, or stay
23456 ;; here.
23457 (let ((origin (point)))
23458 (org-with-limited-levels (org-backward-heading-same-level 1))
23459 ;; When current headline has no sibling above, move to its
23460 ;; parent.
23461 (when (= (point) origin)
23462 (or (org-with-limited-levels (org-up-heading-safe))
23463 (progn (goto-char origin)
23464 (user-error "Cannot move further up"))))))
23466 (let* ((trail (org-element-at-point 'keep-trail))
23467 (elem (car trail))
23468 (prev-elem (nth 1 trail))
23469 (beg (org-element-property :begin elem)))
23470 (cond
23471 ;; Move to beginning of current element if point isn't
23472 ;; there already.
23473 ((null beg) (message "No element at point"))
23474 ((/= (point) beg) (goto-char beg))
23475 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23476 ((org-before-first-heading-p) (goto-char (point-min)))
23477 (t (org-back-to-heading)))))))
23479 (defun org-up-element ()
23480 "Move to upper element."
23481 (interactive)
23482 (if (org-with-limited-levels (org-at-heading-p))
23483 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23484 (let* ((elem (org-element-at-point))
23485 (parent (org-element-property :parent elem)))
23486 (if parent (goto-char (org-element-property :begin parent))
23487 (if (org-with-limited-levels (org-before-first-heading-p))
23488 (user-error "No surrounding element")
23489 (org-with-limited-levels (org-back-to-heading)))))))
23491 (defvar org-element-greater-elements)
23492 (defun org-down-element ()
23493 "Move to inner element."
23494 (interactive)
23495 (let ((element (org-element-at-point)))
23496 (cond
23497 ((memq (org-element-type element) '(plain-list table))
23498 (goto-char (org-element-property :contents-begin element))
23499 (forward-char))
23500 ((memq (org-element-type element) org-element-greater-elements)
23501 ;; If contents are hidden, first disclose them.
23502 (when (org-element-property :hiddenp element) (org-cycle))
23503 (goto-char (or (org-element-property :contents-begin element)
23504 (user-error "No content for this element"))))
23505 (t (user-error "No inner element")))))
23507 (defun org-drag-element-backward ()
23508 "Move backward element at point."
23509 (interactive)
23510 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23511 (let* ((trail (org-element-at-point 'keep-trail))
23512 (elem (car trail))
23513 (prev-elem (nth 1 trail)))
23514 ;; Error out if no previous element or previous element is
23515 ;; a parent of the current one.
23516 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23517 (user-error "Cannot drag element backward")
23518 (let ((pos (point)))
23519 (org-element-swap-A-B prev-elem elem)
23520 (goto-char (+ (org-element-property :begin prev-elem)
23521 (- pos (org-element-property :begin elem)))))))))
23523 (defun org-drag-element-forward ()
23524 "Move forward element at point."
23525 (interactive)
23526 (let* ((pos (point))
23527 (elem (org-element-at-point)))
23528 (when (= (point-max) (org-element-property :end elem))
23529 (user-error "Cannot drag element forward"))
23530 (goto-char (org-element-property :end elem))
23531 (let ((next-elem (org-element-at-point)))
23532 (when (or (org-element-nested-p elem next-elem)
23533 (and (eq (org-element-type next-elem) 'headline)
23534 (not (eq (org-element-type elem) 'headline))))
23535 (goto-char pos)
23536 (user-error "Cannot drag element forward"))
23537 ;; Compute new position of point: it's shifted by NEXT-ELEM
23538 ;; body's length (without final blanks) and by the length of
23539 ;; blanks between ELEM and NEXT-ELEM.
23540 (let ((size-next (- (save-excursion
23541 (goto-char (org-element-property :end next-elem))
23542 (skip-chars-backward " \r\t\n")
23543 (forward-line)
23544 ;; Small correction if buffer doesn't end
23545 ;; with a newline character.
23546 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23547 (org-element-property :begin next-elem)))
23548 (size-blank (- (org-element-property :end elem)
23549 (save-excursion
23550 (goto-char (org-element-property :end elem))
23551 (skip-chars-backward " \r\t\n")
23552 (forward-line)
23553 (point)))))
23554 (org-element-swap-A-B elem next-elem)
23555 (goto-char (+ pos size-next size-blank))))))
23557 (defun org-drag-line-forward (arg)
23558 "Drag the line at point ARG lines forward."
23559 (interactive "p")
23560 (dotimes (n (abs arg))
23561 (let ((c (current-column)))
23562 (if (< 0 arg)
23563 (progn
23564 (beginning-of-line 2)
23565 (transpose-lines 1)
23566 (beginning-of-line 0))
23567 (transpose-lines 1)
23568 (beginning-of-line -1))
23569 (org-move-to-column c))))
23571 (defun org-drag-line-backward (arg)
23572 "Drag the line at point ARG lines backward."
23573 (interactive "p")
23574 (org-drag-line-forward (- arg)))
23576 (defun org-mark-element ()
23577 "Put point at beginning of this element, mark at end.
23579 Interactively, if this command is repeated or (in Transient Mark
23580 mode) if the mark is active, it marks the next element after the
23581 ones already marked."
23582 (interactive)
23583 (let (deactivate-mark)
23584 (if (and (org-called-interactively-p 'any)
23585 (or (and (eq last-command this-command) (mark t))
23586 (and transient-mark-mode mark-active)))
23587 (set-mark
23588 (save-excursion
23589 (goto-char (mark))
23590 (goto-char (org-element-property :end (org-element-at-point)))))
23591 (let ((element (org-element-at-point)))
23592 (end-of-line)
23593 (push-mark (org-element-property :end element) t t)
23594 (goto-char (org-element-property :begin element))))))
23596 (defun org-narrow-to-element ()
23597 "Narrow buffer to current element."
23598 (interactive)
23599 (let ((elem (org-element-at-point)))
23600 (cond
23601 ((eq (car elem) 'headline)
23602 (narrow-to-region
23603 (org-element-property :begin elem)
23604 (org-element-property :end elem)))
23605 ((memq (car elem) org-element-greater-elements)
23606 (narrow-to-region
23607 (org-element-property :contents-begin elem)
23608 (org-element-property :contents-end elem)))
23610 (narrow-to-region
23611 (org-element-property :begin elem)
23612 (org-element-property :end elem))))))
23614 (defun org-transpose-element ()
23615 "Transpose current and previous elements, keeping blank lines between.
23616 Point is moved after both elements."
23617 (interactive)
23618 (org-skip-whitespace)
23619 (let ((end (org-element-property :end (org-element-at-point))))
23620 (org-drag-element-backward)
23621 (goto-char end)))
23623 (defun org-unindent-buffer ()
23624 "Un-indent the visible part of the buffer.
23625 Relative indentation (between items, inside blocks, etc.) isn't
23626 modified."
23627 (interactive)
23628 (unless (eq major-mode 'org-mode)
23629 (user-error "Cannot un-indent a buffer not in Org mode"))
23630 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23631 unindent-tree ; For byte-compiler.
23632 (unindent-tree
23633 (function
23634 (lambda (contents)
23635 (mapc
23636 (lambda (element)
23637 (if (memq (org-element-type element) '(headline section))
23638 (funcall unindent-tree (org-element-contents element))
23639 (save-excursion
23640 (save-restriction
23641 (narrow-to-region
23642 (org-element-property :begin element)
23643 (org-element-property :end element))
23644 (org-do-remove-indentation)))))
23645 (reverse contents))))))
23646 (funcall unindent-tree (org-element-contents parse-tree))))
23648 (defun org-show-subtree ()
23649 "Show everything after this heading at deeper levels."
23650 (interactive)
23651 (outline-flag-region
23652 (point)
23653 (save-excursion
23654 (org-end-of-subtree t t))
23655 nil))
23657 (defun org-show-entry ()
23658 "Show the body directly following this heading.
23659 Show the heading too, if it is currently invisible."
23660 (interactive)
23661 (save-excursion
23662 (condition-case nil
23663 (progn
23664 (org-back-to-heading t)
23665 (outline-flag-region
23666 (max (point-min) (1- (point)))
23667 (save-excursion
23668 (if (re-search-forward
23669 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23670 (match-beginning 1)
23671 (point-max)))
23672 nil)
23673 (org-cycle-hide-drawers 'children))
23674 (error nil))))
23676 (defun org-make-options-regexp (kwds &optional extra)
23677 "Make a regular expression for keyword lines."
23678 (concat
23679 "^#\\+\\("
23680 (mapconcat 'regexp-quote kwds "\\|")
23681 (if extra (concat "\\|" extra))
23682 "\\):[ \t]*\\(.*\\)"))
23684 ;; Make isearch reveal the necessary context
23685 (defun org-isearch-end ()
23686 "Reveal context after isearch exits."
23687 (when isearch-success ; only if search was successful
23688 (if (featurep 'xemacs)
23689 ;; Under XEmacs, the hook is run in the correct place,
23690 ;; we directly show the context.
23691 (org-show-context 'isearch)
23692 ;; In Emacs the hook runs *before* restoring the overlays.
23693 ;; So we have to use a one-time post-command-hook to do this.
23694 ;; (Emacs 22 has a special variable, see function `org-mode')
23695 (unless (and (boundp 'isearch-mode-end-hook-quit)
23696 isearch-mode-end-hook-quit)
23697 ;; Only when the isearch was not quitted.
23698 (org-add-hook 'post-command-hook 'org-isearch-post-command
23699 'append 'local)))
23700 (org-fix-ellipsis-at-bol)))
23702 (defun org-isearch-post-command ()
23703 "Remove self from hook, and show context."
23704 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23705 (org-show-context 'isearch))
23708 ;;;; Integration with and fixes for other packages
23710 ;;; Imenu support
23712 (defvar org-imenu-markers nil
23713 "All markers currently used by Imenu.")
23714 (make-variable-buffer-local 'org-imenu-markers)
23716 (defun org-imenu-new-marker (&optional pos)
23717 "Return a new marker for use by Imenu, and remember the marker."
23718 (let ((m (make-marker)))
23719 (move-marker m (or pos (point)))
23720 (push m org-imenu-markers)
23723 (defun org-imenu-get-tree ()
23724 "Produce the index for Imenu."
23725 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23726 (setq org-imenu-markers nil)
23727 (let* ((n org-imenu-depth)
23728 (re (concat "^" (org-get-limited-outline-regexp)))
23729 (subs (make-vector (1+ n) nil))
23730 (last-level 0)
23731 m level head0 head)
23732 (save-excursion
23733 (save-restriction
23734 (widen)
23735 (goto-char (point-max))
23736 (while (re-search-backward re nil t)
23737 (setq level (org-reduced-level (funcall outline-level)))
23738 (when (and (<= level n)
23739 (looking-at org-complex-heading-regexp)
23740 (setq head0 (org-match-string-no-properties 4)))
23741 (setq head (org-link-display-format head0)
23742 m (org-imenu-new-marker))
23743 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23744 (if (>= level last-level)
23745 (push (cons head m) (aref subs level))
23746 (push (cons head (aref subs (1+ level))) (aref subs level))
23747 (loop for i from (1+ level) to n do (aset subs i nil)))
23748 (setq last-level level)))))
23749 (aref subs 1)))
23751 (eval-after-load "imenu"
23752 '(progn
23753 (add-hook 'imenu-after-jump-hook
23754 (lambda ()
23755 (if (derived-mode-p 'org-mode)
23756 (org-show-context 'org-goto))))))
23758 (defun org-link-display-format (link)
23759 "Replace a link with its the description.
23760 If there is no description, use the link target."
23761 (save-match-data
23762 (if (string-match org-bracket-link-analytic-regexp link)
23763 (replace-match (if (match-end 5)
23764 (match-string 5 link)
23765 (concat (match-string 1 link)
23766 (match-string 3 link)))
23767 nil t link)
23768 link)))
23770 (defun org-toggle-link-display ()
23771 "Toggle the literal or descriptive display of links."
23772 (interactive)
23773 (if org-descriptive-links
23774 (progn (org-remove-from-invisibility-spec '(org-link))
23775 (org-restart-font-lock)
23776 (setq org-descriptive-links nil))
23777 (progn (add-to-invisibility-spec '(org-link))
23778 (org-restart-font-lock)
23779 (setq org-descriptive-links t))))
23781 ;; Speedbar support
23783 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23784 "Overlay marking the agenda restriction line in speedbar.")
23785 (overlay-put org-speedbar-restriction-lock-overlay
23786 'face 'org-agenda-restriction-lock)
23787 (overlay-put org-speedbar-restriction-lock-overlay
23788 'help-echo "Agendas are currently limited to this item.")
23789 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23791 (defun org-speedbar-set-agenda-restriction ()
23792 "Restrict future agenda commands to the location at point in speedbar.
23793 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23794 (interactive)
23795 (require 'org-agenda)
23796 (let (p m tp np dir txt)
23797 (cond
23798 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23799 'org-imenu t))
23800 (setq m (get-text-property p 'org-imenu-marker))
23801 (with-current-buffer (marker-buffer m)
23802 (goto-char m)
23803 (org-agenda-set-restriction-lock 'subtree)))
23804 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23805 'speedbar-function 'speedbar-find-file))
23806 (setq tp (previous-single-property-change
23807 (1+ p) 'speedbar-function)
23808 np (next-single-property-change
23809 tp 'speedbar-function)
23810 dir (speedbar-line-directory)
23811 txt (buffer-substring-no-properties (or tp (point-min))
23812 (or np (point-max))))
23813 (with-current-buffer (find-file-noselect
23814 (let ((default-directory dir))
23815 (expand-file-name txt)))
23816 (unless (derived-mode-p 'org-mode)
23817 (user-error "Cannot restrict to non-Org-mode file"))
23818 (org-agenda-set-restriction-lock 'file)))
23819 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23820 (move-overlay org-speedbar-restriction-lock-overlay
23821 (point-at-bol) (point-at-eol))
23822 (setq current-prefix-arg nil)
23823 (org-agenda-maybe-redo)))
23825 (defvar speedbar-file-key-map)
23826 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23827 (eval-after-load "speedbar"
23828 '(progn
23829 (speedbar-add-supported-extension ".org")
23830 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23831 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23832 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23833 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23834 (add-hook 'speedbar-visiting-tag-hook
23835 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23837 ;;; Fixes and Hacks for problems with other packages
23839 ;; Make flyspell not check words in links, to not mess up our keymap
23840 (defvar org-element-affiliated-keywords) ; From org-element.el
23841 (defvar org-element-block-name-alist) ; From org-element.el
23842 (defun org-mode-flyspell-verify ()
23843 "Don't let flyspell put overlays at active buttons, or on
23844 {todo,all-time,additional-option-like}-keywords."
23845 (require 'org-element) ; For `org-element-affiliated-keywords'
23846 (let ((pos (max (1- (point)) (point-min)))
23847 (word (thing-at-point 'word)))
23848 (and (not (get-text-property pos 'keymap))
23849 (not (get-text-property pos 'org-no-flyspell))
23850 (not (member word org-todo-keywords-1))
23851 (not (member word org-all-time-keywords))
23852 (not (member word org-options-keywords))
23853 (not (member word (mapcar 'car org-startup-options)))
23854 (not (member-ignore-case word org-element-affiliated-keywords))
23855 (not (member-ignore-case word (org-get-export-keywords)))
23856 (not (member-ignore-case
23857 word (mapcar 'car org-element-block-name-alist)))
23858 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23859 (not (org-in-src-block-p)))))
23861 (defun org-remove-flyspell-overlays-in (beg end)
23862 "Remove flyspell overlays in region."
23863 (and (org-bound-and-true-p flyspell-mode)
23864 (fboundp 'flyspell-delete-region-overlays)
23865 (flyspell-delete-region-overlays beg end))
23866 (add-text-properties beg end '(org-no-flyspell t)))
23868 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23869 (eval-after-load "bookmark"
23870 '(if (boundp 'bookmark-after-jump-hook)
23871 ;; We can use the hook
23872 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23873 ;; Hook not available, use advice
23874 (defadvice bookmark-jump (after org-make-visible activate)
23875 "Make the position visible."
23876 (org-bookmark-jump-unhide))))
23878 ;; Make sure saveplace shows the location if it was hidden
23879 (eval-after-load "saveplace"
23880 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23881 "Make the position visible."
23882 (org-bookmark-jump-unhide)))
23884 ;; Make sure ecb shows the location if it was hidden
23885 (eval-after-load "ecb"
23886 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23887 "Make hierarchy visible when jumping into location from ECB tree buffer."
23888 (if (derived-mode-p 'org-mode)
23889 (org-show-context))))
23891 (defun org-bookmark-jump-unhide ()
23892 "Unhide the current position, to show the bookmark location."
23893 (and (derived-mode-p 'org-mode)
23894 (or (outline-invisible-p)
23895 (save-excursion (goto-char (max (point-min) (1- (point))))
23896 (outline-invisible-p)))
23897 (org-show-context 'bookmark-jump)))
23899 ;; Make session.el ignore our circular variable
23900 (defvar session-globals-exclude)
23901 (eval-after-load "session"
23902 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23904 ;;;; Finish up
23906 (provide 'org)
23908 (run-hooks 'org-load-hook)
23910 ;;; org.el ends here