Partially revert commit adcebf
[org-mode.git] / lisp / org.el
blobe7fdd19faeda87ebac1c0f897930bbe1af8ebc06
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 _version))
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 ;; Autoload the functions in org-table.el that are needed by functions here.
4252 (eval-and-compile
4253 (org-autoload "org-table"
4254 '(org-table-begin org-table-blank-field org-table-end)))
4256 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4257 "Detect a #+TBLFM line.")
4259 ;;;###autoload
4260 (defun turn-on-orgtbl ()
4261 "Unconditionally turn on `orgtbl-mode'."
4262 (require 'org-table)
4263 (orgtbl-mode 1))
4265 (defun org-at-table-p (&optional table-type)
4266 "Return t if the cursor is inside an org-type table.
4267 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4268 (if org-enable-table-editor
4269 (save-excursion
4270 (beginning-of-line 1)
4271 (looking-at (if table-type org-table-any-line-regexp
4272 org-table-line-regexp)))
4273 nil))
4274 (defsubst org-table-p () (org-at-table-p))
4276 (defun org-at-table.el-p ()
4277 "Return t if and only if we are at a table.el table."
4278 (and (org-at-table-p 'any)
4279 (save-excursion
4280 (goto-char (org-table-begin 'any))
4281 (looking-at org-table1-hline-regexp))))
4283 (defun org-table-recognize-table.el ()
4284 "If there is a table.el table nearby, recognize it and move into it."
4285 (if org-table-tab-recognizes-table.el
4286 (if (org-at-table.el-p)
4287 (progn
4288 (beginning-of-line 1)
4289 (if (looking-at org-table-dataline-regexp)
4291 (if (looking-at org-table1-hline-regexp)
4292 (progn
4293 (beginning-of-line 2)
4294 (if (looking-at org-table-any-border-regexp)
4295 (beginning-of-line -1)))))
4296 (if (re-search-forward "|" (org-table-end t) t)
4297 (progn
4298 (require 'table)
4299 (if (table--at-cell-p (point))
4301 (message "recognizing table.el table...")
4302 (table-recognize-table)
4303 (message "recognizing table.el table...done")))
4304 (error "This should not happen"))
4306 nil)
4307 nil))
4309 (defun org-at-table-hline-p ()
4310 "Return t if the cursor is inside a hline in a table."
4311 (if org-enable-table-editor
4312 (save-excursion
4313 (beginning-of-line 1)
4314 (looking-at org-table-hline-regexp))
4315 nil))
4317 (defun org-table-map-tables (function &optional quietly)
4318 "Apply FUNCTION to the start of all tables in the buffer."
4319 (save-excursion
4320 (save-restriction
4321 (widen)
4322 (goto-char (point-min))
4323 (while (re-search-forward org-table-any-line-regexp nil t)
4324 (unless quietly
4325 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4326 (beginning-of-line 1)
4327 (when (and (looking-at org-table-line-regexp)
4328 ;; Exclude tables in src/example/verbatim/clocktable blocks
4329 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4330 (save-excursion (funcall function))
4331 (or (looking-at org-table-line-regexp)
4332 (forward-char 1)))
4333 (re-search-forward org-table-any-border-regexp nil 1))))
4334 (unless quietly (message "Mapping tables: done")))
4336 ;; Declare and autoload functions from org-agenda.el
4338 (eval-and-compile
4339 (org-autoload "org-agenda"
4340 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4342 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4343 (declare-function org-clock-update-mode-line "org-clock" ())
4344 (declare-function org-resolve-clocks "org-clock"
4345 (&optional also-non-dangling-p prompt last-valid))
4347 (defun org-at-TBLFM-p (&optional pos)
4348 "Return t when point (or POS) is in #+TBLFM line."
4349 (save-excursion
4350 (let ((pos pos)))
4351 (goto-char (or pos (point)))
4352 (beginning-of-line 1)
4353 (looking-at org-TBLFM-regexp)))
4355 (defvar org-clock-start-time)
4356 (defvar org-clock-marker (make-marker)
4357 "Marker recording the last clock-in.")
4358 (defvar org-clock-hd-marker (make-marker)
4359 "Marker recording the last clock-in, but the headline position.")
4360 (defvar org-clock-heading ""
4361 "The heading of the current clock entry.")
4362 (defun org-clock-is-active ()
4363 "Return the buffer where the clock is currently running.
4364 Return nil if no clock is running."
4365 (marker-buffer org-clock-marker))
4367 (eval-and-compile
4368 (org-autoload "org-clock" '(org-clock-remove-overlays
4369 org-clock-update-time-maybe
4370 org-clocktable-shift)))
4372 (defun org-check-running-clock ()
4373 "Check if the current buffer contains the running clock.
4374 If yes, offer to stop it and to save the buffer with the changes."
4375 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4376 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4377 (buffer-name))))
4378 (org-clock-out)
4379 (when (y-or-n-p "Save changed buffer?")
4380 (save-buffer))))
4382 (defun org-clocktable-try-shift (dir n)
4383 "Check if this line starts a clock table, if yes, shift the time block."
4384 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4385 (org-clocktable-shift dir n)))
4387 ;;;###autoload
4388 (defun org-clock-persistence-insinuate ()
4389 "Set up hooks for clock persistence."
4390 (require 'org-clock)
4391 (add-hook 'org-mode-hook 'org-clock-load)
4392 (add-hook 'kill-emacs-hook 'org-clock-save))
4394 ;; Define the variable already here, to make sure we have it.
4395 (defvar org-indent-mode nil
4396 "Non-nil if Org-Indent mode is enabled.
4397 Use the command `org-indent-mode' to change this variable.")
4399 ;; Autoload archiving code
4400 ;; The stuff that is needed for cycling and tags has to be defined here.
4402 (defgroup org-archive nil
4403 "Options concerning archiving in Org-mode."
4404 :tag "Org Archive"
4405 :group 'org-structure)
4407 (defcustom org-archive-location "%s_archive::"
4408 "The location where subtrees should be archived.
4410 The value of this variable is a string, consisting of two parts,
4411 separated by a double-colon. The first part is a filename and
4412 the second part is a headline.
4414 When the filename is omitted, archiving happens in the same file.
4415 %s in the filename will be replaced by the current file
4416 name (without the directory part). Archiving to a different file
4417 is useful to keep archived entries from contributing to the
4418 Org-mode Agenda.
4420 The archived entries will be filed as subtrees of the specified
4421 headline. When the headline is omitted, the subtrees are simply
4422 filed away at the end of the file, as top-level entries. Also in
4423 the heading you can use %s to represent the file name, this can be
4424 useful when using the same archive for a number of different files.
4426 Here are a few examples:
4427 \"%s_archive::\"
4428 If the current file is Projects.org, archive in file
4429 Projects.org_archive, as top-level trees. This is the default.
4431 \"::* Archived Tasks\"
4432 Archive in the current file, under the top-level headline
4433 \"* Archived Tasks\".
4435 \"~/org/archive.org::\"
4436 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4438 \"~/org/archive.org::* From %s\"
4439 Archive in file ~/org/archive.org (absolute path), under headlines
4440 \"From FILENAME\" where file name is the current file name.
4442 \"~/org/datetree.org::datetree/* Finished Tasks\"
4443 The \"datetree/\" string is special, signifying to archive
4444 items to the datetree. Items are placed in either the CLOSED
4445 date of the item, or the current date if there is no CLOSED date.
4446 The heading will be a subentry to the current date. There doesn't
4447 need to be a heading, but there always needs to be a slash after
4448 datetree. For example, to store archived items directly in the
4449 datetree, use \"~/org/datetree.org::datetree/\".
4451 \"basement::** Finished Tasks\"
4452 Archive in file ./basement (relative path), as level 3 trees
4453 below the level 2 heading \"** Finished Tasks\".
4455 You may set this option on a per-file basis by adding to the buffer a
4456 line like
4458 #+ARCHIVE: basement::** Finished Tasks
4460 You may also define it locally for a subtree by setting an ARCHIVE property
4461 in the entry. If such a property is found in an entry, or anywhere up
4462 the hierarchy, it will be used."
4463 :group 'org-archive
4464 :type 'string)
4466 (defcustom org-archive-tag "ARCHIVE"
4467 "The tag that marks a subtree as archived.
4468 An archived subtree does not open during visibility cycling, and does
4469 not contribute to the agenda listings.
4470 After changing this, font-lock must be restarted in the relevant buffers to
4471 get the proper fontification."
4472 :group 'org-archive
4473 :group 'org-keywords
4474 :type 'string)
4476 (defcustom org-agenda-skip-archived-trees t
4477 "Non-nil means the agenda will skip any items located in archived trees.
4478 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4479 variable is no longer recommended, you should leave it at the value t.
4480 Instead, use the key `v' to cycle the archives-mode in the agenda."
4481 :group 'org-archive
4482 :group 'org-agenda-skip
4483 :type 'boolean)
4485 (defcustom org-columns-skip-archived-trees t
4486 "Non-nil means ignore archived trees when creating column view."
4487 :group 'org-archive
4488 :group 'org-properties
4489 :type 'boolean)
4491 (defcustom org-cycle-open-archived-trees nil
4492 "Non-nil means `org-cycle' will open archived trees.
4493 An archived tree is a tree marked with the tag ARCHIVE.
4494 When nil, archived trees will stay folded. You can still open them with
4495 normal outline commands like `show-all', but not with the cycling commands."
4496 :group 'org-archive
4497 :group 'org-cycle
4498 :type 'boolean)
4500 (defcustom org-sparse-tree-open-archived-trees nil
4501 "Non-nil means sparse tree construction shows matches in archived trees.
4502 When nil, matches in these trees are highlighted, but the trees are kept in
4503 collapsed state."
4504 :group 'org-archive
4505 :group 'org-sparse-trees
4506 :type 'boolean)
4508 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4509 "The default date type when building a sparse tree.
4510 When this is nil, a date is a scheduled or a deadline timestamp.
4511 Otherwise, these types are allowed:
4513 all: all timestamps
4514 active: only active timestamps (<...>)
4515 inactive: only inactive timestamps (<...)
4516 scheduled: only scheduled timestamps
4517 deadline: only deadline timestamps"
4518 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4519 (const :tag "All timestamps" all)
4520 (const :tag "Only active timestamps" active)
4521 (const :tag "Only inactive timestamps" inactive)
4522 (const :tag "Only scheduled timestamps" scheduled)
4523 (const :tag "Only deadline timestamps" deadline)
4524 (const :tag "Only closed timestamps" closed))
4525 :version "24.3"
4526 :group 'org-sparse-trees)
4528 (defun org-cycle-hide-archived-subtrees (state)
4529 "Re-hide all archived subtrees after a visibility state change."
4530 (when (and (not org-cycle-open-archived-trees)
4531 (not (memq state '(overview folded))))
4532 (save-excursion
4533 (let* ((globalp (memq state '(contents all)))
4534 (beg (if globalp (point-min) (point)))
4535 (end (if globalp (point-max) (org-end-of-subtree t))))
4536 (org-hide-archived-subtrees beg end)
4537 (goto-char beg)
4538 (if (looking-at (concat ".*:" org-archive-tag ":"))
4539 (message "%s" (substitute-command-keys
4540 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4542 (defun org-force-cycle-archived ()
4543 "Cycle subtree even if it is archived."
4544 (interactive)
4545 (setq this-command 'org-cycle)
4546 (let ((org-cycle-open-archived-trees t))
4547 (call-interactively 'org-cycle)))
4549 (defun org-hide-archived-subtrees (beg end)
4550 "Re-hide all archived subtrees after a visibility state change."
4551 (save-excursion
4552 (let* ((re (concat ":" org-archive-tag ":")))
4553 (goto-char beg)
4554 (while (re-search-forward re end t)
4555 (when (org-at-heading-p)
4556 (org-flag-subtree t)
4557 (org-end-of-subtree t))))))
4559 (declare-function outline-end-of-heading "outline" ())
4560 (declare-function outline-flag-region "outline" (from to flag))
4561 (defun org-flag-subtree (flag)
4562 (save-excursion
4563 (org-back-to-heading t)
4564 (outline-end-of-heading)
4565 (outline-flag-region (point)
4566 (progn (org-end-of-subtree t) (point))
4567 flag)))
4569 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4571 (eval-and-compile
4572 (org-autoload "org-archive"
4573 '(org-add-archive-files)))
4575 ;; Autoload Column View Code
4577 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4578 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4579 (declare-function org-columns-compute "org-colview" (property))
4581 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4582 '(org-columns-number-to-string
4583 org-columns-get-format-and-top-level
4584 org-columns-compute
4585 org-columns-remove-overlays))
4587 ;; Autoload ID code
4589 (declare-function org-id-store-link "org-id")
4590 (declare-function org-id-locations-load "org-id")
4591 (declare-function org-id-locations-save "org-id")
4592 (defvar org-id-track-globally)
4593 (org-autoload "org-id"
4594 '(org-id-new
4595 org-id-copy
4596 org-id-get-with-outline-path-completion
4597 org-id-get-with-outline-drilling))
4599 ;;; Variables for pre-computed regular expressions, all buffer local
4601 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4602 "Matches first line of a hidden block.")
4603 (make-variable-buffer-local 'org-drawer-regexp)
4604 (defvar org-todo-regexp nil
4605 "Matches any of the TODO state keywords.")
4606 (make-variable-buffer-local 'org-todo-regexp)
4607 (defvar org-not-done-regexp nil
4608 "Matches any of the TODO state keywords except the last one.")
4609 (make-variable-buffer-local 'org-not-done-regexp)
4610 (defvar org-not-done-heading-regexp nil
4611 "Matches a TODO headline that is not done.")
4612 (make-variable-buffer-local 'org-not-done-regexp)
4613 (defvar org-todo-line-regexp nil
4614 "Matches a headline and puts TODO state into group 2 if present.")
4615 (make-variable-buffer-local 'org-todo-line-regexp)
4616 (defvar org-complex-heading-regexp nil
4617 "Matches a headline and puts everything into groups:
4618 group 1: the stars
4619 group 2: The todo keyword, maybe
4620 group 3: Priority cookie
4621 group 4: True headline
4622 group 5: Tags")
4623 (make-variable-buffer-local 'org-complex-heading-regexp)
4624 (defvar org-complex-heading-regexp-format nil
4625 "Printf format to make regexp to match an exact headline.
4626 This regexp will match the headline of any node which has the
4627 exact headline text that is put into the format, but may have any
4628 TODO state, priority and tags.")
4629 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4630 (defvar org-todo-line-tags-regexp nil
4631 "Matches a headline and puts TODO state into group 2 if present.
4632 Also put tags into group 4 if tags are present.")
4633 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4634 (defvar org-ds-keyword-length 12
4635 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4636 (make-variable-buffer-local 'org-ds-keyword-length)
4637 (defvar org-deadline-regexp nil
4638 "Matches the DEADLINE keyword.")
4639 (make-variable-buffer-local 'org-deadline-regexp)
4640 (defvar org-deadline-time-regexp nil
4641 "Matches the DEADLINE keyword together with a time stamp.")
4642 (make-variable-buffer-local 'org-deadline-time-regexp)
4643 (defvar org-deadline-time-hour-regexp nil
4644 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4645 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4646 (defvar org-deadline-line-regexp nil
4647 "Matches the DEADLINE keyword and the rest of the line.")
4648 (make-variable-buffer-local 'org-deadline-line-regexp)
4649 (defvar org-scheduled-regexp nil
4650 "Matches the SCHEDULED keyword.")
4651 (make-variable-buffer-local 'org-scheduled-regexp)
4652 (defvar org-scheduled-time-regexp nil
4653 "Matches the SCHEDULED keyword together with a time stamp.")
4654 (make-variable-buffer-local 'org-scheduled-time-regexp)
4655 (defvar org-scheduled-time-hour-regexp nil
4656 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4657 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4658 (defvar org-closed-time-regexp nil
4659 "Matches the CLOSED keyword together with a time stamp.")
4660 (make-variable-buffer-local 'org-closed-time-regexp)
4662 (defvar org-keyword-time-regexp nil
4663 "Matches any of the 4 keywords, together with the time stamp.")
4664 (make-variable-buffer-local 'org-keyword-time-regexp)
4665 (defvar org-keyword-time-not-clock-regexp nil
4666 "Matches any of the 3 keywords, together with the time stamp.")
4667 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4668 (defvar org-maybe-keyword-time-regexp nil
4669 "Matches a timestamp, possibly preceded by a keyword.")
4670 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4671 (defvar org-all-time-keywords nil
4672 "List of time keywords.")
4673 (make-variable-buffer-local 'org-all-time-keywords)
4675 (defconst org-plain-time-of-day-regexp
4676 (concat
4677 "\\(\\<[012]?[0-9]"
4678 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4679 "\\(--?"
4680 "\\(\\<[012]?[0-9]"
4681 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4682 "\\)?")
4683 "Regular expression to match a plain time or time range.
4684 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4685 groups carry important information:
4686 0 the full match
4687 1 the first time, range or not
4688 8 the second time, if it is a range.")
4690 (defconst org-plain-time-extension-regexp
4691 (concat
4692 "\\(\\<[012]?[0-9]"
4693 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4694 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4695 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4696 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4697 groups carry important information:
4698 0 the full match
4699 7 hours of duration
4700 9 minutes of duration")
4702 (defconst org-stamp-time-of-day-regexp
4703 (concat
4704 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4705 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4706 "\\(--?"
4707 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4708 "Regular expression to match a timestamp time or time range.
4709 After a match, the following groups carry important information:
4710 0 the full match
4711 1 date plus weekday, for back referencing to make sure both times are on the same day
4712 2 the first time, range or not
4713 4 the second time, if it is a range.")
4715 (defconst org-startup-options
4716 '(("fold" org-startup-folded t)
4717 ("overview" org-startup-folded t)
4718 ("nofold" org-startup-folded nil)
4719 ("showall" org-startup-folded nil)
4720 ("showeverything" org-startup-folded showeverything)
4721 ("content" org-startup-folded content)
4722 ("indent" org-startup-indented t)
4723 ("noindent" org-startup-indented nil)
4724 ("hidestars" org-hide-leading-stars t)
4725 ("showstars" org-hide-leading-stars nil)
4726 ("odd" org-odd-levels-only t)
4727 ("oddeven" org-odd-levels-only nil)
4728 ("align" org-startup-align-all-tables t)
4729 ("noalign" org-startup-align-all-tables nil)
4730 ("inlineimages" org-startup-with-inline-images t)
4731 ("noinlineimages" org-startup-with-inline-images nil)
4732 ("latexpreview" org-startup-with-latex-preview t)
4733 ("nolatexpreview" org-startup-with-latex-preview nil)
4734 ("customtime" org-display-custom-times t)
4735 ("logdone" org-log-done time)
4736 ("lognotedone" org-log-done note)
4737 ("nologdone" org-log-done nil)
4738 ("lognoteclock-out" org-log-note-clock-out t)
4739 ("nolognoteclock-out" org-log-note-clock-out nil)
4740 ("logrepeat" org-log-repeat state)
4741 ("lognoterepeat" org-log-repeat note)
4742 ("logdrawer" org-log-into-drawer t)
4743 ("nologdrawer" org-log-into-drawer nil)
4744 ("logstatesreversed" org-log-states-order-reversed t)
4745 ("nologstatesreversed" org-log-states-order-reversed nil)
4746 ("nologrepeat" org-log-repeat nil)
4747 ("logreschedule" org-log-reschedule time)
4748 ("lognotereschedule" org-log-reschedule note)
4749 ("nologreschedule" org-log-reschedule nil)
4750 ("logredeadline" org-log-redeadline time)
4751 ("lognoteredeadline" org-log-redeadline note)
4752 ("nologredeadline" org-log-redeadline nil)
4753 ("logrefile" org-log-refile time)
4754 ("lognoterefile" org-log-refile note)
4755 ("nologrefile" org-log-refile nil)
4756 ("fninline" org-footnote-define-inline t)
4757 ("nofninline" org-footnote-define-inline nil)
4758 ("fnlocal" org-footnote-section nil)
4759 ("fnauto" org-footnote-auto-label t)
4760 ("fnprompt" org-footnote-auto-label nil)
4761 ("fnconfirm" org-footnote-auto-label confirm)
4762 ("fnplain" org-footnote-auto-label plain)
4763 ("fnadjust" org-footnote-auto-adjust t)
4764 ("nofnadjust" org-footnote-auto-adjust nil)
4765 ("constcgs" constants-unit-system cgs)
4766 ("constSI" constants-unit-system SI)
4767 ("noptag" org-tag-persistent-alist nil)
4768 ("hideblocks" org-hide-block-startup t)
4769 ("nohideblocks" org-hide-block-startup nil)
4770 ("beamer" org-startup-with-beamer-mode t)
4771 ("entitiespretty" org-pretty-entities t)
4772 ("entitiesplain" org-pretty-entities nil))
4773 "Variable associated with STARTUP options for org-mode.
4774 Each element is a list of three items: the startup options (as written
4775 in the #+STARTUP line), the corresponding variable, and the value to set
4776 this variable to if the option is found. An optional forth element PUSH
4777 means to push this value onto the list in the variable.")
4779 (defun org-update-property-plist (key val props)
4780 "Update PROPS with KEY and VAL."
4781 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4782 (key (if appending (substring key 0 (- (length key) 1)) key))
4783 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4784 (previous (cdr (assoc key props))))
4785 (if appending
4786 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4787 (cons (cons key val) remainder))))
4789 (defconst org-block-regexp
4790 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4791 "Regular expression for hiding blocks.")
4792 (defconst org-heading-keyword-regexp-format
4793 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4794 "Printf format for a regexp matching a headline with some keyword.
4795 This regexp will match the headline of any node which has the
4796 exact keyword that is put into the format. The keyword isn't in
4797 any group by default, but the stars and the body are.")
4798 (defconst org-heading-keyword-maybe-regexp-format
4799 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4800 "Printf format for a regexp matching a headline, possibly with some keyword.
4801 This regexp can match any headline with the specified keyword, or
4802 without a keyword. The keyword isn't in any group by default,
4803 but the stars and the body are.")
4805 (defcustom org-group-tags t
4806 "When non-nil (the default), use group tags.
4807 This can be turned on/off through `org-toggle-tags-groups'."
4808 :group 'org-tags
4809 :group 'org-startup
4810 :type 'boolean)
4812 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4814 (defun org-toggle-tags-groups ()
4815 "Toggle support for group tags.
4816 Support for group tags is controlled by the option
4817 `org-group-tags', which is non-nil by default."
4818 (interactive)
4819 (setq org-group-tags (not org-group-tags))
4820 (cond ((and (derived-mode-p 'org-agenda-mode)
4821 org-group-tags)
4822 (org-agenda-redo))
4823 ((derived-mode-p 'org-mode)
4824 (let ((org-inhibit-startup t)) (org-mode))))
4825 (message "Groups tags support has been turned %s"
4826 (if org-group-tags "on" "off")))
4828 (defun org-set-regexps-and-options-for-tags ()
4829 "Precompute variables used for tags."
4830 (when (derived-mode-p 'org-mode)
4831 (org-set-local 'org-file-tags nil)
4832 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4833 (splitre "[ \t]+")
4834 (start 0)
4835 tags ftags key value)
4836 (save-excursion
4837 (save-restriction
4838 (widen)
4839 (goto-char (point-min))
4840 (while (re-search-forward re nil t)
4841 (setq key (upcase (org-match-string-no-properties 1))
4842 value (org-match-string-no-properties 2))
4843 (if (stringp value) (setq value (org-trim value)))
4844 (cond
4845 ((equal key "TAGS")
4846 (setq tags (append tags (if tags '("\\n") nil)
4847 (org-split-string value splitre))))
4848 ((equal key "FILETAGS")
4849 (when (string-match "\\S-" value)
4850 (setq ftags
4851 (append
4852 ftags
4853 (apply 'append
4854 (mapcar (lambda (x) (org-split-string x ":"))
4855 (org-split-string value)))))))))))
4856 ;; Process the file tags.
4857 (and ftags (org-set-local 'org-file-tags
4858 (mapcar 'org-add-prop-inherited ftags)))
4859 (org-set-local 'org-tag-groups-alist nil)
4860 ;; Process the tags.
4861 (when (and (not tags) org-tag-alist)
4862 (setq tags
4863 (mapcar
4864 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4865 ((eq (car tg) :endgroup) "}")
4866 ((eq (car tg) :grouptags) ":")
4867 ((eq (car tg) :newline) "\n")
4868 (t (concat (car tg)
4869 (if (characterp (cdr tg))
4870 (format "(%s)" (char-to-string (cdr tg))) "")))))
4871 org-tag-alist)))
4872 (let (e tgs g)
4873 (while (setq e (pop tags))
4874 (cond
4875 ((equal e "{")
4876 (progn (push '(:startgroup) tgs)
4877 (when (equal (nth 1 tags) ":")
4878 (push (list (replace-regexp-in-string
4879 "(.+)$" "" (nth 0 tags)))
4880 org-tag-groups-alist)
4881 (setq g 0))))
4882 ((equal e ":") (push '(:grouptags) tgs))
4883 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4884 ((equal e "\\n") (push '(:newline) tgs))
4885 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4886 (push (cons (match-string 1 e)
4887 (string-to-char (match-string 2 e))) tgs)
4888 (if (and g (> g 0))
4889 (setcar org-tag-groups-alist
4890 (append (car org-tag-groups-alist)
4891 (list (match-string 1 e)))))
4892 (if g (setq g (1+ g))))
4893 (t (push (list e) tgs)
4894 (if (and g (> g 0))
4895 (setcar org-tag-groups-alist
4896 (append (car org-tag-groups-alist) (list e))))
4897 (if g (setq g (1+ g))))))
4898 (org-set-local 'org-tag-alist nil)
4899 (while (setq e (pop tgs))
4900 (or (and (stringp (car e))
4901 (assoc (car e) org-tag-alist))
4902 (push e org-tag-alist)))
4903 ;; Return a list with tag variables
4904 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4906 (defvar org-ota nil)
4907 (defun org-set-regexps-and-options ()
4908 "Precompute regular expressions used in the current buffer."
4909 (when (derived-mode-p 'org-mode)
4910 (org-set-local 'org-todo-kwd-alist nil)
4911 (org-set-local 'org-todo-key-alist nil)
4912 (org-set-local 'org-todo-key-trigger nil)
4913 (org-set-local 'org-todo-keywords-1 nil)
4914 (org-set-local 'org-done-keywords nil)
4915 (org-set-local 'org-todo-heads nil)
4916 (org-set-local 'org-todo-sets nil)
4917 (org-set-local 'org-todo-log-states nil)
4918 (org-set-local 'org-file-properties nil)
4919 (let ((re (org-make-options-regexp
4920 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4921 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4922 "SETUPFILE" "OPTIONS")
4923 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4924 (splitre "[ \t]+")
4925 (scripts org-use-sub-superscripts)
4926 kwds kws0 kwsa key log value cat arch const links hw dws
4927 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4928 (start 0))
4929 (save-excursion
4930 (save-restriction
4931 (widen)
4932 (goto-char (point-min))
4933 (while
4934 (or (and
4935 ext-setup-or-nil
4936 (not org-ota)
4937 (let (ret)
4938 (with-temp-buffer
4939 (insert ext-setup-or-nil)
4940 (let ((major-mode 'org-mode) org-ota)
4941 (setq ret (save-match-data
4942 (org-set-regexps-and-options-for-tags)))))
4943 ;; Append setupfile tags to existing tags
4944 (setq org-ota t)
4945 (setq org-file-tags
4946 (delq nil (append org-file-tags (nth 0 ret)))
4947 org-tag-alist
4948 (delq nil (append org-tag-alist (nth 1 ret)))
4949 org-tag-groups-alist
4950 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4951 (and ext-setup-or-nil
4952 (string-match re ext-setup-or-nil start)
4953 (setq start (match-end 0)))
4954 (and (setq ext-setup-or-nil nil start 0)
4955 (re-search-forward re nil t)))
4956 (setq key (upcase (match-string 1 ext-setup-or-nil))
4957 value (org-match-string-no-properties 2 ext-setup-or-nil))
4958 (if (stringp value) (setq value (org-trim value)))
4959 (cond
4960 ((equal key "CATEGORY")
4961 (setq cat value))
4962 ((member key '("SEQ_TODO" "TODO"))
4963 (push (cons 'sequence (org-split-string value splitre)) kwds))
4964 ((equal key "TYP_TODO")
4965 (push (cons 'type (org-split-string value splitre)) kwds))
4966 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4967 ;; general TODO-like setup
4968 (push (cons (intern (downcase (match-string 1 key)))
4969 (org-split-string value splitre)) kwds))
4970 ((equal key "COLUMNS")
4971 (org-set-local 'org-columns-default-format value))
4972 ((equal key "LINK")
4973 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4974 (push (cons (match-string 1 value)
4975 (org-trim (match-string 2 value)))
4976 links)))
4977 ((equal key "PRIORITIES")
4978 (setq prio (org-split-string value " +")))
4979 ((equal key "PROPERTY")
4980 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4981 (setq props (org-update-property-plist (match-string 1 value)
4982 (match-string 2 value)
4983 props))))
4984 ((equal key "DRAWERS")
4985 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4986 ((equal key "CONSTANTS")
4987 (org-table-set-constants))
4988 ((equal key "STARTUP")
4989 (let ((opts (org-split-string value splitre))
4990 l var val)
4991 (while (setq l (pop opts))
4992 (when (setq l (assoc l org-startup-options))
4993 (setq var (nth 1 l) val (nth 2 l))
4994 (if (not (nth 3 l))
4995 (set (make-local-variable var) val)
4996 (if (not (listp (symbol-value var)))
4997 (set (make-local-variable var) nil))
4998 (set (make-local-variable var) (symbol-value var))
4999 (add-to-list var val))))))
5000 ((equal key "ARCHIVE")
5001 (setq arch value)
5002 (remove-text-properties 0 (length arch)
5003 '(face t fontified t) arch))
5004 ((equal key "OPTIONS")
5005 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5006 (setq scripts (read (match-string 2 value)))))
5007 ((and (equal key "SETUPFILE")
5008 ;; Prevent checking in Gnus messages
5009 (not buffer-read-only))
5010 (setq setup-contents (org-file-contents
5011 (expand-file-name
5012 (org-remove-double-quotes value))
5013 'noerror))
5014 (if (not ext-setup-or-nil)
5015 (setq ext-setup-or-nil setup-contents start 0)
5016 (setq ext-setup-or-nil
5017 (concat (substring ext-setup-or-nil 0 start)
5018 "\n" setup-contents "\n"
5019 (substring ext-setup-or-nil start)))))))
5020 ;; search for property blocks
5021 (goto-char (point-min))
5022 (while (re-search-forward org-block-regexp nil t)
5023 (when (equal "PROPERTY" (upcase (match-string 1)))
5024 (setq value (replace-regexp-in-string
5025 "[\n\r]" " " (match-string 4)))
5026 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5027 (setq props (org-update-property-plist (match-string 1 value)
5028 (match-string 2 value)
5029 props)))))))
5030 (org-set-local 'org-use-sub-superscripts scripts)
5031 (when cat
5032 (org-set-local 'org-category (intern cat))
5033 (push (cons "CATEGORY" cat) props))
5034 (when prio
5035 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5036 (setq prio (mapcar 'string-to-char prio))
5037 (org-set-local 'org-highest-priority (nth 0 prio))
5038 (org-set-local 'org-lowest-priority (nth 1 prio))
5039 (org-set-local 'org-default-priority (nth 2 prio)))
5040 (and props (org-set-local 'org-file-properties (nreverse props)))
5041 (and drawers (org-set-local 'org-drawers drawers))
5042 (and arch (org-set-local 'org-archive-location arch))
5043 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5044 ;; Process the TODO keywords
5045 (unless kwds
5046 ;; Use the global values as if they had been given locally.
5047 (setq kwds (default-value 'org-todo-keywords))
5048 (if (stringp (car kwds))
5049 (setq kwds (list (cons org-todo-interpretation
5050 (default-value 'org-todo-keywords)))))
5051 (setq kwds (reverse kwds)))
5052 (setq kwds (nreverse kwds))
5053 (let (inter kws kw)
5054 (while (setq kws (pop kwds))
5055 (let ((kws (or
5056 (run-hook-with-args-until-success
5057 'org-todo-setup-filter-hook kws)
5058 kws)))
5059 (setq inter (pop kws) sep (member "|" kws)
5060 kws0 (delete "|" (copy-sequence kws))
5061 kwsa nil
5062 kws1 (mapcar
5063 (lambda (x)
5064 ;; 1 2
5065 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5066 (progn
5067 (setq kw (match-string 1 x)
5068 key (and (match-end 2) (match-string 2 x))
5069 log (org-extract-log-state-settings x))
5070 (push (cons kw (and key (string-to-char key))) kwsa)
5071 (and log (push log org-todo-log-states))
5073 (error "Invalid TODO keyword %s" x)))
5074 kws0)
5075 kwsa (if kwsa (append '((:startgroup))
5076 (nreverse kwsa)
5077 '((:endgroup))))
5078 hw (car kws1)
5079 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5080 tail (list inter hw (car dws) (org-last dws))))
5081 (add-to-list 'org-todo-heads hw 'append)
5082 (push kws1 org-todo-sets)
5083 (setq org-done-keywords (append org-done-keywords dws nil))
5084 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5085 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5086 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5087 (setq org-todo-sets (nreverse org-todo-sets)
5088 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5089 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5090 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5091 ;; Compute the regular expressions and other local variables.
5092 ;; Using `org-outline-regexp-bol' would complicate them much,
5093 ;; because of the fixed white space at the end of that string.
5094 (if (not org-done-keywords)
5095 (setq org-done-keywords (and org-todo-keywords-1
5096 (list (org-last org-todo-keywords-1)))))
5097 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5098 (length org-scheduled-string)
5099 (length org-clock-string)
5100 (length org-closed-string)))
5101 org-drawer-regexp
5102 (concat "^[ \t]*:\\("
5103 (mapconcat 'regexp-quote org-drawers "\\|")
5104 "\\):[ \t]*$")
5105 org-not-done-keywords
5106 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5107 org-todo-regexp
5108 (concat "\\("
5109 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5110 "\\)")
5111 org-not-done-regexp
5112 (concat "\\("
5113 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5114 "\\)")
5115 org-not-done-heading-regexp
5116 (format org-heading-keyword-regexp-format org-not-done-regexp)
5117 org-todo-line-regexp
5118 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5119 org-complex-heading-regexp
5120 (concat "^\\(\\*+\\)"
5121 "\\(?: +" org-todo-regexp "\\)?"
5122 "\\(?: +\\(\\[#.\\]\\)\\)?"
5123 "\\(?: +\\(.*?\\)\\)??"
5124 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5125 "[ \t]*$")
5126 org-complex-heading-regexp-format
5127 (concat "^\\(\\*+\\)"
5128 "\\(?: +" org-todo-regexp "\\)?"
5129 "\\(?: +\\(\\[#.\\]\\)\\)?"
5130 "\\(?: +"
5131 ;; Stats cookies can be stuck to body.
5132 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5133 "\\(%s\\)"
5134 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5135 "\\)"
5136 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5137 "[ \t]*$")
5138 org-todo-line-tags-regexp
5139 (concat "^\\(\\*+\\)"
5140 "\\(?: +" org-todo-regexp "\\)?"
5141 "\\(?: +\\(.*?\\)\\)??"
5142 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5143 "[ \t]*$")
5144 org-deadline-regexp (concat "\\<" org-deadline-string)
5145 org-deadline-time-regexp
5146 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5147 org-deadline-time-hour-regexp
5148 (concat "\\<" org-deadline-string
5149 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5150 org-deadline-line-regexp
5151 (concat "\\<\\(" org-deadline-string "\\).*")
5152 org-scheduled-regexp
5153 (concat "\\<" org-scheduled-string)
5154 org-scheduled-time-regexp
5155 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5156 org-scheduled-time-hour-regexp
5157 (concat "\\<" org-scheduled-string
5158 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5159 org-closed-time-regexp
5160 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5161 org-keyword-time-regexp
5162 (concat "\\<\\(" org-scheduled-string
5163 "\\|" org-deadline-string
5164 "\\|" org-closed-string
5165 "\\|" org-clock-string "\\)"
5166 " *[[<]\\([^]>]+\\)[]>]")
5167 org-keyword-time-not-clock-regexp
5168 (concat "\\<\\(" org-scheduled-string
5169 "\\|" org-deadline-string
5170 "\\|" org-closed-string
5171 "\\)"
5172 " *[[<]\\([^]>]+\\)[]>]")
5173 org-maybe-keyword-time-regexp
5174 (concat "\\(\\<\\(" org-scheduled-string
5175 "\\|" org-deadline-string
5176 "\\|" org-closed-string
5177 "\\|" org-clock-string "\\)\\)?"
5178 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5179 org-all-time-keywords
5180 (mapcar (lambda (w) (substring w 0 -1))
5181 (list org-scheduled-string org-deadline-string
5182 org-clock-string org-closed-string)))
5183 (setq org-ota nil)
5184 (org-compute-latex-and-related-regexp))))
5186 (defun org-file-contents (file &optional noerror)
5187 "Return the contents of FILE, as a string."
5188 (if (or (not file)
5189 (not (file-readable-p file)))
5190 (if noerror
5191 (message "Cannot read file \"%s\"" file)
5192 (error "Cannot read file \"%s\"" file))
5193 (with-temp-buffer
5194 (insert-file-contents file)
5195 (buffer-string))))
5197 (defun org-extract-log-state-settings (x)
5198 "Extract the log state setting from a TODO keyword string.
5199 This will extract info from a string like \"WAIT(w@/!)\"."
5200 (let (kw key log1 log2)
5201 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5202 (setq kw (match-string 1 x)
5203 key (and (match-end 2) (match-string 2 x))
5204 log1 (and (match-end 3) (match-string 3 x))
5205 log2 (and (match-end 4) (match-string 4 x)))
5206 (and (or log1 log2)
5207 (list kw
5208 (and log1 (if (equal log1 "!") 'time 'note))
5209 (and log2 (if (equal log2 "!") 'time 'note)))))))
5211 (defun org-remove-keyword-keys (list)
5212 "Remove a pair of parenthesis at the end of each string in LIST."
5213 (mapcar (lambda (x)
5214 (if (string-match "(.*)$" x)
5215 (substring x 0 (match-beginning 0))
5217 list))
5219 (defun org-assign-fast-keys (alist)
5220 "Assign fast keys to a keyword-key alist.
5221 Respect keys that are already there."
5222 (let (new e (alt ?0))
5223 (while (setq e (pop alist))
5224 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5225 (cdr e)) ;; Key already assigned.
5226 (push e new)
5227 (let ((clist (string-to-list (downcase (car e))))
5228 (used (append new alist)))
5229 (when (= (car clist) ?@)
5230 (pop clist))
5231 (while (and clist (rassoc (car clist) used))
5232 (pop clist))
5233 (unless clist
5234 (while (rassoc alt used)
5235 (incf alt)))
5236 (push (cons (car e) (or (car clist) alt)) new))))
5237 (nreverse new)))
5239 ;;; Some variables used in various places
5241 (defvar org-window-configuration nil
5242 "Used in various places to store a window configuration.")
5243 (defvar org-selected-window nil
5244 "Used in various places to store a window configuration.")
5245 (defvar org-finish-function nil
5246 "Function to be called when `C-c C-c' is used.
5247 This is for getting out of special buffers like capture.")
5250 ;; FIXME: Occasionally check by commenting these, to make sure
5251 ;; no other functions uses these, forgetting to let-bind them.
5252 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5253 (defvar org-last-state)
5254 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5256 ;; Defined somewhere in this file, but used before definition.
5257 (defvar org-entities) ;; defined in org-entities.el
5258 (defvar org-struct-menu)
5259 (defvar org-org-menu)
5260 (defvar org-tbl-menu)
5262 ;;;; Define the Org-mode
5264 ;; We use a before-change function to check if a table might need
5265 ;; an update.
5266 (defvar org-table-may-need-update t
5267 "Indicates that a table might need an update.
5268 This variable is set by `org-before-change-function'.
5269 `org-table-align' sets it back to nil.")
5270 (defun org-before-change-function (beg end)
5271 "Every change indicates that a table might need an update."
5272 (setq org-table-may-need-update t))
5273 (defvar org-mode-map)
5274 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5275 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5276 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5277 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5278 (defvar org-table-buffer-is-an nil)
5280 (defvar bidi-paragraph-direction)
5281 (defvar buffer-face-mode-face)
5283 (require 'outline)
5284 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5285 (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"))
5286 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5288 ;; Other stuff we need.
5289 (require 'time-date)
5290 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5291 (require 'easymenu)
5292 (require 'overlay)
5294 ;; (require 'org-macs) moved higher up in the file before it is first used
5295 (require 'org-entities)
5296 ;; (require 'org-compat) moved higher up in the file before it is first used
5297 (require 'org-faces)
5298 (require 'org-list)
5299 (require 'org-pcomplete)
5300 (require 'org-src)
5301 (require 'org-footnote)
5302 (require 'org-macro)
5304 ;; babel
5305 (require 'ob)
5307 ;;;###autoload
5308 (define-derived-mode org-mode outline-mode "Org"
5309 "Outline-based notes management and organizer, alias
5310 \"Carsten's outline-mode for keeping track of everything.\"
5312 Org-mode develops organizational tasks around a NOTES file which
5313 contains information about projects as plain text. Org-mode is
5314 implemented on top of outline-mode, which is ideal to keep the content
5315 of large files well structured. It supports ToDo items, deadlines and
5316 time stamps, which magically appear in the diary listing of the Emacs
5317 calendar. Tables are easily created with a built-in table editor.
5318 Plain text URL-like links connect to websites, emails (VM), Usenet
5319 messages (Gnus), BBDB entries, and any files related to the project.
5320 For printing and sharing of notes, an Org-mode file (or a part of it)
5321 can be exported as a structured ASCII or HTML file.
5323 The following commands are available:
5325 \\{org-mode-map}"
5327 ;; Get rid of Outline menus, they are not needed
5328 ;; Need to do this here because define-derived-mode sets up
5329 ;; the keymap so late. Still, it is a waste to call this each time
5330 ;; we switch another buffer into org-mode.
5331 (if (featurep 'xemacs)
5332 (when (boundp 'outline-mode-menu-heading)
5333 ;; Assume this is Greg's port, it uses easymenu
5334 (easy-menu-remove outline-mode-menu-heading)
5335 (easy-menu-remove outline-mode-menu-show)
5336 (easy-menu-remove outline-mode-menu-hide))
5337 (define-key org-mode-map [menu-bar headings] 'undefined)
5338 (define-key org-mode-map [menu-bar hide] 'undefined)
5339 (define-key org-mode-map [menu-bar show] 'undefined))
5341 (org-load-modules-maybe)
5342 (easy-menu-add org-org-menu)
5343 (easy-menu-add org-tbl-menu)
5344 (org-install-agenda-files-menu)
5345 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5346 (add-to-invisibility-spec '(org-cwidth))
5347 (add-to-invisibility-spec '(org-hide-block . t))
5348 (when (featurep 'xemacs)
5349 (org-set-local 'line-move-ignore-invisible t))
5350 (org-set-local 'outline-regexp org-outline-regexp)
5351 (org-set-local 'outline-level 'org-outline-level)
5352 (setq bidi-paragraph-direction 'left-to-right)
5353 (when (and org-ellipsis
5354 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5355 (fboundp 'make-glyph-code))
5356 (unless org-display-table
5357 (setq org-display-table (make-display-table)))
5358 (set-display-table-slot
5359 org-display-table 4
5360 (vconcat (mapcar
5361 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5362 org-ellipsis)))
5363 (if (stringp org-ellipsis) org-ellipsis "..."))))
5364 (setq buffer-display-table org-display-table))
5365 (org-set-regexps-and-options-for-tags)
5366 (org-set-regexps-and-options)
5367 (org-set-font-lock-defaults)
5368 (when (and org-tag-faces (not org-tags-special-faces-re))
5369 ;; tag faces set outside customize.... force initialization.
5370 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5371 ;; Calc embedded
5372 (org-set-local 'calc-embedded-open-mode "# ")
5373 ;; Modify a few syntax entries
5374 (modify-syntax-entry ?@ "w")
5375 (modify-syntax-entry ?\" "\"")
5376 (if org-startup-truncated (setq truncate-lines t))
5377 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5378 (org-set-local 'font-lock-unfontify-region-function
5379 'org-unfontify-region)
5380 ;; Activate before-change-function
5381 (org-set-local 'org-table-may-need-update t)
5382 (org-add-hook 'before-change-functions 'org-before-change-function nil
5383 'local)
5384 ;; Check for running clock before killing a buffer
5385 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5386 ;; Initialize macros templates.
5387 (org-macro-initialize-templates)
5388 ;; Initialize radio targets.
5389 (org-update-radio-target-regexp)
5390 ;; Indentation.
5391 (org-set-local 'indent-line-function 'org-indent-line)
5392 (org-set-local 'indent-region-function 'org-indent-region)
5393 ;; Filling and auto-filling.
5394 (org-setup-filling)
5395 ;; Comments.
5396 (org-setup-comments-handling)
5397 ;; Beginning/end of defun
5398 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5399 (org-set-local 'end-of-defun-function 'org-forward-element)
5400 ;; Next error for sparse trees
5401 (org-set-local 'next-error-function 'org-occur-next-match)
5402 ;; Make sure dependence stuff works reliably, even for users who set it
5403 ;; too late :-(
5404 (if org-enforce-todo-dependencies
5405 (add-hook 'org-blocker-hook
5406 'org-block-todo-from-children-or-siblings-or-parent)
5407 (remove-hook 'org-blocker-hook
5408 'org-block-todo-from-children-or-siblings-or-parent))
5409 (if org-enforce-todo-checkbox-dependencies
5410 (add-hook 'org-blocker-hook
5411 'org-block-todo-from-checkboxes)
5412 (remove-hook 'org-blocker-hook
5413 'org-block-todo-from-checkboxes))
5415 ;; Align options lines
5416 (org-set-local
5417 'align-mode-rules-list
5418 '((org-in-buffer-settings
5419 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5420 (modes . '(org-mode)))))
5422 ;; Imenu
5423 (org-set-local 'imenu-create-index-function
5424 'org-imenu-get-tree)
5426 ;; Make isearch reveal context
5427 (if (or (featurep 'xemacs)
5428 (not (boundp 'outline-isearch-open-invisible-function)))
5429 ;; Emacs 21 and XEmacs make use of the hook
5430 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5431 ;; Emacs 22 deals with this through a special variable
5432 (org-set-local 'outline-isearch-open-invisible-function
5433 (lambda (&rest ignore) (org-show-context 'isearch)))
5434 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5436 ;; Setup the pcomplete hooks
5437 (set (make-local-variable 'pcomplete-command-completion-function)
5438 'org-pcomplete-initial)
5439 (set (make-local-variable 'pcomplete-command-name-function)
5440 'org-command-at-point)
5441 (set (make-local-variable 'pcomplete-default-completion-function)
5442 'ignore)
5443 (set (make-local-variable 'pcomplete-parse-arguments-function)
5444 'org-parse-arguments)
5445 (set (make-local-variable 'pcomplete-termination-string) "")
5446 (when (>= emacs-major-version 23)
5447 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5449 ;; If empty file that did not turn on org-mode automatically, make it to.
5450 (if (and org-insert-mode-line-in-empty-file
5451 (org-called-interactively-p 'any)
5452 (= (point-min) (point-max)))
5453 (insert "# -*- mode: org -*-\n\n"))
5454 (unless org-inhibit-startup
5455 (org-unmodified
5456 (and org-startup-with-beamer-mode (org-beamer-mode))
5457 (when org-startup-align-all-tables
5458 (org-table-map-tables 'org-table-align 'quietly))
5459 (when org-startup-with-inline-images
5460 (org-display-inline-images))
5461 (when org-startup-with-latex-preview
5462 (org-preview-latex-fragment))
5463 (unless org-inhibit-startup-visibility-stuff
5464 (org-set-startup-visibility))))
5465 ;; Try to set org-hide correctly
5466 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5468 ;; Update `customize-package-emacs-version-alist'
5469 (add-to-list 'customize-package-emacs-version-alist
5470 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5471 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5472 ("8.0" . "24.4")))
5474 (defvar org-mode-transpose-word-syntax-table
5475 (let ((st (make-syntax-table)))
5476 (mapc (lambda(c) (modify-syntax-entry
5477 (string-to-char (car c)) "w p" st))
5478 org-emphasis-alist)
5479 st))
5481 (when (fboundp 'abbrev-table-put)
5482 (abbrev-table-put org-mode-abbrev-table
5483 :parents (list text-mode-abbrev-table)))
5485 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5487 (defsubst org-fix-ellipsis-at-bol ()
5488 (save-excursion (goto-char (window-start)) (recenter 0)))
5490 (defun org-find-invisible-foreground ()
5491 (let ((candidates (remove
5492 "unspecified-bg"
5493 (nconc
5494 (list (face-background 'default)
5495 (face-background 'org-default))
5496 (mapcar
5497 (lambda (alist)
5498 (when (boundp alist)
5499 (cdr (assoc 'background-color (symbol-value alist)))))
5500 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5501 (list (face-foreground 'org-hide))))))
5502 (car (remove nil candidates))))
5504 (defun org-current-time (&optional rounding-minutes past)
5505 "Current time, possibly rounded to ROUNDING-MINUTES.
5506 When ROUNDING-MINUTES is not an integer, fall back on the car of
5507 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5508 the rounding returns a past time."
5509 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5510 (car org-time-stamp-rounding-minutes)))
5511 (time (decode-time)) res)
5512 (if (< r 1)
5513 (current-time)
5514 (setq res
5515 (apply 'encode-time
5516 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5517 (nthcdr 2 time))))
5518 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5519 (seconds-to-time (- (org-float-time res) (* r 60)))
5520 res))))
5522 (defun org-today ()
5523 "Return today date, considering `org-extend-today-until'."
5524 (time-to-days
5525 (time-subtract (current-time)
5526 (list 0 (* 3600 org-extend-today-until) 0))))
5528 ;;;; Font-Lock stuff, including the activators
5530 (defvar org-mouse-map (make-sparse-keymap))
5531 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5532 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5533 (when org-mouse-1-follows-link
5534 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5535 (when org-tab-follows-link
5536 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5537 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5539 (require 'font-lock)
5541 (defconst org-non-link-chars "]\t\n\r<>")
5542 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5543 "shell" "elisp" "doi" "message"))
5544 (defvar org-link-types-re nil
5545 "Matches a link that has a url-like prefix like \"http:\"")
5546 (defvar org-link-re-with-space nil
5547 "Matches a link with spaces, optional angular brackets around it.")
5548 (defvar org-link-re-with-space2 nil
5549 "Matches a link with spaces, optional angular brackets around it.")
5550 (defvar org-link-re-with-space3 nil
5551 "Matches a link with spaces, only for internal part in bracket links.")
5552 (defvar org-angle-link-re nil
5553 "Matches link with angular brackets, spaces are allowed.")
5554 (defvar org-plain-link-re nil
5555 "Matches plain link, without spaces.")
5556 (defvar org-bracket-link-regexp nil
5557 "Matches a link in double brackets.")
5558 (defvar org-bracket-link-analytic-regexp nil
5559 "Regular expression used to analyze links.
5560 Here is what the match groups contain after a match:
5561 1: http:
5562 2: http
5563 3: path
5564 4: [desc]
5565 5: desc")
5566 (defvar org-bracket-link-analytic-regexp++ nil
5567 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5568 (defvar org-any-link-re nil
5569 "Regular expression matching any link.")
5571 (defconst org-match-sexp-depth 3
5572 "Number of stacked braces for sub/superscript matching.")
5574 (defun org-create-multibrace-regexp (left right n)
5575 "Create a regular expression which will match a balanced sexp.
5576 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5577 as single character strings.
5578 The regexp returned will match the entire expression including the
5579 delimiters. It will also define a single group which contains the
5580 match except for the outermost delimiters. The maximum depth of
5581 stacked delimiters is N. Escaping delimiters is not possible."
5582 (let* ((nothing (concat "[^" left right "]*?"))
5583 (or "\\|")
5584 (re nothing)
5585 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5586 (while (> n 1)
5587 (setq n (1- n)
5588 re (concat re or next)
5589 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5590 (concat left "\\(" re "\\)" right)))
5592 (defvar org-match-substring-regexp
5593 (concat
5594 "\\(\\S-\\)\\([_^]\\)\\("
5595 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5596 "\\|"
5597 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5598 "\\|"
5599 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5600 "The regular expression matching a sub- or superscript.")
5602 (defvar org-match-substring-with-braces-regexp
5603 (concat
5604 "\\(\\S-\\)\\([_^]\\)\\("
5605 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5606 "\\)")
5607 "The regular expression matching a sub- or superscript, forcing braces.")
5609 (defun org-make-link-regexps ()
5610 "Update the link regular expressions.
5611 This should be called after the variable `org-link-types' has changed."
5612 (setq org-link-types-re
5613 (concat
5614 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5615 org-link-re-with-space
5616 (concat
5617 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5618 "\\([^" org-non-link-chars " ]"
5619 "[^" org-non-link-chars "]*"
5620 "[^" org-non-link-chars " ]\\)>?")
5621 org-link-re-with-space2
5622 (concat
5623 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5624 "\\([^" org-non-link-chars " ]"
5625 "[^\t\n\r]*"
5626 "[^" org-non-link-chars " ]\\)>?")
5627 org-link-re-with-space3
5628 (concat
5629 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5630 "\\([^" org-non-link-chars " ]"
5631 "[^\t\n\r]*\\)")
5632 org-angle-link-re
5633 (concat
5634 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5635 "\\([^" org-non-link-chars " ]"
5636 "[^" org-non-link-chars "]*"
5637 "\\)>")
5638 org-plain-link-re
5639 (concat
5640 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5641 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5642 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5643 org-bracket-link-regexp
5644 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5645 org-bracket-link-analytic-regexp
5646 (concat
5647 "\\[\\["
5648 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5649 "\\([^]]+\\)"
5650 "\\]"
5651 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5652 "\\]")
5653 org-bracket-link-analytic-regexp++
5654 (concat
5655 "\\[\\["
5656 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5657 "\\([^]]+\\)"
5658 "\\]"
5659 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5660 "\\]")
5661 org-any-link-re
5662 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5663 org-angle-link-re "\\)\\|\\("
5664 org-plain-link-re "\\)")))
5666 (org-make-link-regexps)
5668 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5669 "Regular expression for fast time stamp matching.")
5670 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5671 "Regular expression for fast time stamp matching.")
5672 (defconst org-ts-regexp0
5673 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5674 "Regular expression matching time strings for analysis.
5675 This one does not require the space after the date, so it can be used
5676 on a string that terminates immediately after the date.")
5677 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5678 "Regular expression matching time strings for analysis.")
5679 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5680 "Regular expression matching time stamps, with groups.")
5681 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5682 "Regular expression matching time stamps (also [..]), with groups.")
5683 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5684 "Regular expression matching a time stamp range.")
5685 (defconst org-tr-regexp-both
5686 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5687 "Regular expression matching a time stamp range.")
5688 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5689 org-ts-regexp "\\)?")
5690 "Regular expression matching a time stamp or time stamp range.")
5691 (defconst org-tsr-regexp-both
5692 (concat org-ts-regexp-both "\\(--?-?"
5693 org-ts-regexp-both "\\)?")
5694 "Regular expression matching a time stamp or time stamp range.
5695 The time stamps may be either active or inactive.")
5697 (defvar org-emph-face nil)
5699 (defun org-do-emphasis-faces (limit)
5700 "Run through the buffer and add overlays to emphasized strings."
5701 (let (rtn a)
5702 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5703 (if (not (= (char-after (match-beginning 3))
5704 (char-after (match-beginning 4))))
5705 (progn
5706 (setq rtn t)
5707 (setq a (assoc (match-string 3) org-emphasis-alist))
5708 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5709 'face
5710 (nth 1 a))
5711 (and (nth 2 a)
5712 (org-remove-flyspell-overlays-in
5713 (match-beginning 0) (match-end 0)))
5714 (add-text-properties (match-beginning 2) (match-end 2)
5715 '(font-lock-multiline t org-emphasis t))
5716 (when org-hide-emphasis-markers
5717 (add-text-properties (match-end 4) (match-beginning 5)
5718 '(invisible org-link))
5719 (add-text-properties (match-beginning 3) (match-end 3)
5720 '(invisible org-link)))))
5721 (backward-char 1))
5722 rtn))
5724 (defun org-emphasize (&optional char)
5725 "Insert or change an emphasis, i.e. a font like bold or italic.
5726 If there is an active region, change that region to a new emphasis.
5727 If there is no region, just insert the marker characters and position
5728 the cursor between them.
5729 CHAR should be the marker character. If it is a space, it means to
5730 remove the emphasis of the selected region.
5731 If CHAR is not given (for example in an interactive call) it will be
5732 prompted for."
5733 (interactive)
5734 (let ((erc org-emphasis-regexp-components)
5735 (prompt "")
5736 (string "") beg end move c s)
5737 (if (org-region-active-p)
5738 (setq beg (region-beginning) end (region-end)
5739 string (buffer-substring beg end))
5740 (setq move t))
5742 (unless char
5743 (message "Emphasis marker or tag: [%s]"
5744 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5745 (setq char (read-char-exclusive)))
5746 (if (equal char ?\ )
5747 (setq s "" move nil)
5748 (unless (assoc (char-to-string char) org-emphasis-alist)
5749 (user-error "No such emphasis marker: \"%c\"" char))
5750 (setq s (char-to-string char)))
5751 (while (and (> (length string) 1)
5752 (equal (substring string 0 1) (substring string -1))
5753 (assoc (substring string 0 1) org-emphasis-alist))
5754 (setq string (substring string 1 -1)))
5755 (setq string (concat s string s))
5756 (if beg (delete-region beg end))
5757 (unless (or (bolp)
5758 (string-match (concat "[" (nth 0 erc) "\n]")
5759 (char-to-string (char-before (point)))))
5760 (insert " "))
5761 (unless (or (eobp)
5762 (string-match (concat "[" (nth 1 erc) "\n]")
5763 (char-to-string (char-after (point)))))
5764 (insert " ") (backward-char 1))
5765 (insert string)
5766 (and move (backward-char 1))))
5768 (defconst org-nonsticky-props
5769 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5771 (defsubst org-rear-nonsticky-at (pos)
5772 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5774 (defun org-activate-plain-links (limit)
5775 "Run through the buffer and add overlays to links."
5776 (let (f hl)
5777 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5778 (not (org-in-src-block-p)))
5779 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5780 (setq f (get-text-property (match-beginning 0) 'face))
5781 (setq hl (org-match-string-no-properties 0))
5782 (if (or (eq f 'org-tag)
5783 (and (listp f) (memq 'org-tag f)))
5785 (add-text-properties (match-beginning 0) (match-end 0)
5786 (list 'mouse-face 'highlight
5787 'face 'org-link
5788 'htmlize-link `(:uri ,hl)
5789 'keymap org-mouse-map))
5790 (org-rear-nonsticky-at (match-end 0)))
5791 t)))
5793 (defun org-activate-code (limit)
5794 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5795 (progn
5796 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5797 (remove-text-properties (match-beginning 0) (match-end 0)
5798 '(display t invisible t intangible t))
5799 t)))
5801 (defcustom org-src-fontify-natively nil
5802 "When non-nil, fontify code in code blocks."
5803 :type 'boolean
5804 :version "24.1"
5805 :group 'org-appearance
5806 :group 'org-babel)
5808 (defcustom org-allow-promoting-top-level-subtree nil
5809 "When non-nil, allow promoting a top level subtree.
5810 The leading star of the top level headline will be replaced
5811 by a #."
5812 :type 'boolean
5813 :version "24.1"
5814 :group 'org-appearance)
5816 (defun org-fontify-meta-lines-and-blocks (limit)
5817 (condition-case nil
5818 (org-fontify-meta-lines-and-blocks-1 limit)
5819 (error (message "org-mode fontification error"))))
5821 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5822 "Fontify #+ lines and blocks."
5823 (let ((case-fold-search t))
5824 (if (re-search-forward
5825 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5826 limit t)
5827 (let ((beg (match-beginning 0))
5828 (block-start (match-end 0))
5829 (block-end nil)
5830 (lang (match-string 7))
5831 (beg1 (line-beginning-position 2))
5832 (dc1 (downcase (match-string 2)))
5833 (dc3 (downcase (match-string 3)))
5834 end end1 quoting block-type ovl)
5835 (cond
5836 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5837 ;; a single line of backend-specific content
5838 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5839 (remove-text-properties (match-beginning 0) (match-end 0)
5840 '(display t invisible t intangible t))
5841 (add-text-properties (match-beginning 1) (match-end 3)
5842 '(font-lock-fontified t face org-meta-line))
5843 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5844 '(font-lock-fontified t face org-block))
5845 ; for backend-specific code
5847 ((and (match-end 4) (equal dc3 "+begin"))
5848 ;; Truly a block
5849 (setq block-type (downcase (match-string 5))
5850 quoting (member block-type org-protecting-blocks))
5851 (when (re-search-forward
5852 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5853 nil t) ;; on purpose, we look further than LIMIT
5854 (setq end (min (point-max) (match-end 0))
5855 end1 (min (point-max) (1- (match-beginning 0))))
5856 (setq block-end (match-beginning 0))
5857 (when quoting
5858 (remove-text-properties beg end
5859 '(display t invisible t intangible t)))
5860 (add-text-properties
5861 beg end
5862 '(font-lock-fontified t font-lock-multiline t))
5863 (add-text-properties beg beg1 '(face org-meta-line))
5864 (add-text-properties end1 (min (point-max) (1+ end))
5865 '(face org-meta-line)) ; for end_src
5866 (cond
5867 ((and lang (not (string= lang "")) org-src-fontify-natively)
5868 (org-src-font-lock-fontify-block lang block-start block-end)
5869 ;; remove old background overlays
5870 (mapc (lambda (ov)
5871 (if (eq (overlay-get ov 'face) 'org-block-background)
5872 (delete-overlay ov)))
5873 (overlays-at (/ (+ beg1 block-end) 2)))
5874 ;; add a background overlay
5875 (setq ovl (make-overlay beg1 block-end))
5876 (overlay-put ovl 'face 'org-block-background)
5877 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5878 (quoting
5879 (add-text-properties beg1 (min (point-max) (1+ end1))
5880 '(face org-block))) ; end of source block
5881 ((not org-fontify-quote-and-verse-blocks))
5882 ((string= block-type "quote")
5883 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5884 ((string= block-type "verse")
5885 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5886 (add-text-properties beg beg1 '(face org-block-begin-line))
5887 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5888 '(face org-block-end-line))
5890 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5891 (add-text-properties
5892 beg (match-end 3)
5893 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5894 '(font-lock-fontified t invisible t)
5895 '(font-lock-fontified t face org-document-info-keyword)))
5896 (add-text-properties
5897 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5898 (if (string-equal dc1 "+title:")
5899 '(font-lock-fontified t face org-document-title)
5900 '(font-lock-fontified t face org-document-info))))
5901 ((or (equal dc1 "+results")
5902 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5903 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5904 "+call:" "+header:" "+headers:" "+name:"))
5905 (and (match-end 4) (equal dc3 "+attr")))
5906 (add-text-properties
5907 beg (match-end 0)
5908 '(font-lock-fontified t face org-meta-line))
5910 ((member dc3 '(" " ""))
5911 (add-text-properties
5912 beg (match-end 0)
5913 '(font-lock-fontified t face font-lock-comment-face)))
5914 ((not (member (char-after beg) '(?\ ?\t)))
5915 ;; just any other in-buffer setting, but not indented
5916 (add-text-properties
5917 beg (match-end 0)
5918 '(font-lock-fontified t face org-meta-line))
5920 (t nil))))))
5922 (defun org-activate-angle-links (limit)
5923 "Run through the buffer and add overlays to links."
5924 (if (and (re-search-forward org-angle-link-re limit t)
5925 (not (org-in-src-block-p)))
5926 (progn
5927 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5928 (add-text-properties (match-beginning 0) (match-end 0)
5929 (list 'mouse-face 'highlight
5930 'keymap org-mouse-map))
5931 (org-rear-nonsticky-at (match-end 0))
5932 t)))
5934 (defun org-activate-footnote-links (limit)
5935 "Run through the buffer and add overlays to footnotes."
5936 (let ((fn (org-footnote-next-reference-or-definition limit)))
5937 (when fn
5938 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5939 (org-remove-flyspell-overlays-in beg end)
5940 (add-text-properties beg end
5941 (list 'mouse-face 'highlight
5942 'keymap org-mouse-map
5943 'help-echo
5944 (if (= (point-at-bol) beg)
5945 "Footnote definition"
5946 "Footnote reference")
5947 'font-lock-fontified t
5948 'font-lock-multiline t
5949 'face 'org-footnote))))))
5951 (defun org-activate-bracket-links (limit)
5952 "Run through the buffer and add overlays to bracketed links."
5953 (if (and (re-search-forward org-bracket-link-regexp limit t)
5954 (not (org-in-src-block-p)))
5955 (let* ((hl (org-match-string-no-properties 1))
5956 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5957 (ip (org-maybe-intangible
5958 (list 'invisible 'org-link
5959 'keymap org-mouse-map 'mouse-face 'highlight
5960 'font-lock-multiline t 'help-echo help
5961 'htmlize-link `(:uri ,hl))))
5962 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5963 'font-lock-multiline t 'help-echo help
5964 'htmlize-link `(:uri ,hl))))
5965 ;; We need to remove the invisible property here. Table narrowing
5966 ;; may have made some of this invisible.
5967 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5968 (remove-text-properties (match-beginning 0) (match-end 0)
5969 '(invisible nil))
5970 (if (match-end 3)
5971 (progn
5972 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5973 (org-rear-nonsticky-at (match-beginning 3))
5974 (add-text-properties (match-beginning 3) (match-end 3) vp)
5975 (org-rear-nonsticky-at (match-end 3))
5976 (add-text-properties (match-end 3) (match-end 0) ip)
5977 (org-rear-nonsticky-at (match-end 0)))
5978 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5979 (org-rear-nonsticky-at (match-beginning 1))
5980 (add-text-properties (match-beginning 1) (match-end 1) vp)
5981 (org-rear-nonsticky-at (match-end 1))
5982 (add-text-properties (match-end 1) (match-end 0) ip)
5983 (org-rear-nonsticky-at (match-end 0)))
5984 t)))
5986 (defun org-activate-dates (limit)
5987 "Run through the buffer and add overlays to dates."
5988 (if (and (re-search-forward org-tsr-regexp-both limit t)
5989 (not (equal (char-before (match-beginning 0)) 91)))
5990 (progn
5991 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5992 (add-text-properties (match-beginning 0) (match-end 0)
5993 (list 'mouse-face 'highlight
5994 'keymap org-mouse-map))
5995 (org-rear-nonsticky-at (match-end 0))
5996 (when org-display-custom-times
5997 (if (match-end 3)
5998 (org-display-custom-time (match-beginning 3) (match-end 3)))
5999 (org-display-custom-time (match-beginning 1) (match-end 1)))
6000 t)))
6002 (defvar org-target-link-regexp nil
6003 "Regular expression matching radio targets in plain text.")
6004 (make-variable-buffer-local 'org-target-link-regexp)
6005 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6006 "Regular expression matching a link target.")
6007 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6008 "Regular expression matching a radio target.")
6009 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6010 "Regular expression matching any target.")
6012 (defun org-activate-target-links (limit)
6013 "Run through the buffer and add overlays to target matches."
6014 (when org-target-link-regexp
6015 (let ((case-fold-search t))
6016 (if (re-search-forward org-target-link-regexp limit t)
6017 (progn
6018 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6019 (add-text-properties (match-beginning 0) (match-end 0)
6020 (list 'mouse-face 'highlight
6021 'keymap org-mouse-map
6022 'help-echo "Radio target link"
6023 'org-linked-text t))
6024 (org-rear-nonsticky-at (match-end 0))
6025 t)))))
6027 (defun org-update-radio-target-regexp ()
6028 "Find all radio targets in this file and update the regular expression."
6029 (interactive)
6030 (when (memq 'radio org-activate-links)
6031 (setq org-target-link-regexp
6032 (org-make-target-link-regexp (org-all-targets 'radio)))
6033 (org-restart-font-lock)))
6035 (defun org-hide-wide-columns (limit)
6036 (let (s e)
6037 (setq s (text-property-any (point) (or limit (point-max))
6038 'org-cwidth t))
6039 (when s
6040 (setq e (next-single-property-change s 'org-cwidth))
6041 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6042 (goto-char e)
6043 t)))
6045 (defvar org-latex-and-related-regexp nil
6046 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6047 (defvar org-match-substring-regexp)
6048 (defvar org-match-substring-with-braces-regexp)
6050 (defun org-compute-latex-and-related-regexp ()
6051 "Compute regular expression for LaTeX, entities and sub/superscript.
6052 Result depends on variable `org-highlight-latex-and-related'."
6053 (org-set-local
6054 'org-latex-and-related-regexp
6055 (let* ((re-sub
6056 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6057 ((eq org-use-sub-superscripts '{})
6058 (list org-match-substring-with-braces-regexp))
6059 (org-use-sub-superscripts (list org-match-substring-regexp))))
6060 (re-latex
6061 (when (memq 'latex org-highlight-latex-and-related)
6062 (let ((matchers (plist-get org-format-latex-options :matchers)))
6063 (delq nil
6064 (mapcar (lambda (x)
6065 (and (member (car x) matchers) (nth 1 x)))
6066 org-latex-regexps)))))
6067 (re-entities
6068 (when (memq 'entities org-highlight-latex-and-related)
6069 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6070 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6072 (defun org-do-latex-and-related (limit)
6073 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6074 LIMIT bounds the search for syntax to highlight. Stop at first
6075 highlighted object, if any. Return t if some highlighting was
6076 done, nil otherwise."
6077 (when (org-string-nw-p org-latex-and-related-regexp)
6078 (catch 'found
6079 (while (re-search-forward org-latex-and-related-regexp limit t)
6080 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6081 'face))
6082 '(org-code org-verbatim underline))
6083 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6084 '(?_ ?^))
6086 0)))
6087 (font-lock-prepend-text-property
6088 (+ offset (match-beginning 0)) (match-end 0)
6089 'face 'org-latex-and-related)
6090 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6091 '(font-lock-multiline t)))
6092 (throw 'found t)))
6093 nil)))
6095 (defun org-restart-font-lock ()
6096 "Restart `font-lock-mode', to force refontification."
6097 (when (and (boundp 'font-lock-mode) font-lock-mode)
6098 (font-lock-mode -1)
6099 (font-lock-mode 1)))
6101 (defun org-all-targets (&optional radio)
6102 "Return a list of all targets in this file.
6103 When optional argument RADIO is non-nil, only find radio
6104 targets."
6105 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6106 (save-excursion
6107 (goto-char (point-min))
6108 (while (re-search-forward re nil t)
6109 ;; Make sure point is really within the object.
6110 (backward-char)
6111 (let ((obj (org-element-context)))
6112 (when (memq (org-element-type obj) '(radio-target target))
6113 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6114 rtn)))
6116 (defun org-make-target-link-regexp (targets)
6117 "Make regular expression matching all strings in TARGETS.
6118 The regular expression finds the targets also if there is a line break
6119 between words."
6120 (and targets
6121 (concat
6122 "\\<\\("
6123 (mapconcat
6124 (lambda (x)
6125 (setq x (regexp-quote x))
6126 (while (string-match " +" x)
6127 (setq x (replace-match "\\s-+" t t x)))
6129 targets
6130 "\\|")
6131 "\\)\\>")))
6133 (defun org-activate-tags (limit)
6134 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6135 (progn
6136 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6137 (add-text-properties (match-beginning 1) (match-end 1)
6138 (list 'mouse-face 'highlight
6139 'keymap org-mouse-map))
6140 (org-rear-nonsticky-at (match-end 1))
6141 t)))
6143 (defun org-outline-level ()
6144 "Compute the outline level of the heading at point.
6145 If this is called at a normal headline, the level is the number of stars.
6146 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6147 (save-excursion
6148 (if (not (condition-case nil
6149 (org-back-to-heading t)
6150 (error nil)))
6152 (looking-at org-outline-regexp)
6153 (1- (- (match-end 0) (match-beginning 0))))))
6155 (defvar org-font-lock-keywords nil)
6157 (defsubst org-re-property (property &optional literal)
6158 "Return a regexp matching a PROPERTY line.
6159 Match group 3 will be set to the value if it exists."
6160 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6161 (if literal property (regexp-quote property))
6162 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6164 (defconst org-property-re
6165 (org-re-property ".*?" 'literal)
6166 "Regular expression matching a property line.
6167 There are four matching groups:
6168 1: :PROPKEY: including the leading and trailing colon,
6169 2: PROPKEY without the leading and trailing colon,
6170 3: PROPVAL without leading or trailing spaces,
6171 4: the indentation of the current line,
6172 5: trailing whitespace.")
6174 (defvar org-font-lock-hook nil
6175 "Functions to be called for special font lock stuff.")
6177 (defvar org-font-lock-set-keywords-hook nil
6178 "Functions that can manipulate `org-font-lock-extra-keywords'.
6179 This is called after `org-font-lock-extra-keywords' is defined, but before
6180 it is installed to be used by font lock. This can be useful if something
6181 needs to be inserted at a specific position in the font-lock sequence.")
6183 (defun org-font-lock-hook (limit)
6184 "Run `org-font-lock-hook' within LIMIT."
6185 (run-hook-with-args 'org-font-lock-hook limit))
6187 (defun org-set-font-lock-defaults ()
6188 "Set font lock defaults for the current buffer."
6189 (let* ((em org-fontify-emphasized-text)
6190 (lk org-activate-links)
6191 (org-font-lock-extra-keywords
6192 (list
6193 ;; Call the hook
6194 '(org-font-lock-hook)
6195 ;; Headlines
6196 `(,(if org-fontify-whole-heading-line
6197 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6198 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6199 (1 (org-get-level-face 1))
6200 (2 (org-get-level-face 2))
6201 (3 (org-get-level-face 3)))
6202 ;; Table lines
6203 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6204 (1 'org-table t))
6205 ;; Table internals
6206 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6207 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6208 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6209 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6210 ;; Drawers
6211 (list org-drawer-regexp '(0 'org-special-keyword t))
6212 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6213 ;; Properties
6214 (list org-property-re
6215 '(1 'org-special-keyword t)
6216 '(3 'org-property-value t))
6217 ;; Links
6218 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6219 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6220 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6221 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6222 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6223 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6224 (if (memq 'footnote lk) '(org-activate-footnote-links))
6225 ;; Targets.
6226 (list org-any-target-regexp '(0 'org-target t))
6227 ;; Diary sexps.
6228 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6229 ;; Macro
6230 '("{{{.+}}}" (0 'org-macro t))
6231 '(org-hide-wide-columns (0 nil append))
6232 ;; TODO keyword
6233 (list (format org-heading-keyword-regexp-format
6234 org-todo-regexp)
6235 '(2 (org-get-todo-face 2) t))
6236 ;; DONE
6237 (if org-fontify-done-headline
6238 (list (format org-heading-keyword-regexp-format
6239 (concat
6240 "\\(?:"
6241 (mapconcat 'regexp-quote org-done-keywords "\\|")
6242 "\\)"))
6243 '(2 'org-headline-done t))
6244 nil)
6245 ;; Priorities
6246 '(org-font-lock-add-priority-faces)
6247 ;; Tags
6248 '(org-font-lock-add-tag-faces)
6249 ;; Tags groups
6250 (if (and org-group-tags org-tag-groups-alist)
6251 (list (concat org-outline-regexp-bol ".+\\(:"
6252 (regexp-opt (mapcar 'car org-tag-groups-alist))
6253 ":\\).*$")
6254 '(1 'org-tag-group prepend)))
6255 ;; Special keywords
6256 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6257 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6258 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6259 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6260 ;; Emphasis
6261 (if em
6262 (if (featurep 'xemacs)
6263 '(org-do-emphasis-faces (0 nil append))
6264 '(org-do-emphasis-faces)))
6265 ;; Checkboxes
6266 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6267 1 'org-checkbox prepend)
6268 (if (cdr (assq 'checkbox org-list-automatic-rules))
6269 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6270 (0 (org-get-checkbox-statistics-face) t)))
6271 ;; Description list items
6272 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6273 1 'org-list-dt prepend)
6274 ;; ARCHIVEd headings
6275 (list (concat
6276 org-outline-regexp-bol
6277 "\\(.*:" org-archive-tag ":.*\\)")
6278 '(1 'org-archived prepend))
6279 ;; Specials
6280 '(org-do-latex-and-related)
6281 '(org-fontify-entities)
6282 '(org-raise-scripts)
6283 ;; Code
6284 '(org-activate-code (1 'org-code t))
6285 ;; COMMENT
6286 (list (format org-heading-keyword-regexp-format
6287 (concat "\\("
6288 org-comment-string "\\|" org-quote-string
6289 "\\)"))
6290 '(2 'org-special-keyword t))
6291 ;; Blocks and meta lines
6292 '(org-fontify-meta-lines-and-blocks))))
6293 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6294 (run-hooks 'org-font-lock-set-keywords-hook)
6295 ;; Now set the full font-lock-keywords
6296 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6297 (org-set-local 'font-lock-defaults
6298 '(org-font-lock-keywords t nil nil backward-paragraph))
6299 (kill-local-variable 'font-lock-keywords) nil))
6301 (defun org-toggle-pretty-entities ()
6302 "Toggle the composition display of entities as UTF8 characters."
6303 (interactive)
6304 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6305 (org-restart-font-lock)
6306 (if org-pretty-entities
6307 (message "Entities are now displayed as UTF8 characters")
6308 (save-restriction
6309 (widen)
6310 (org-decompose-region (point-min) (point-max))
6311 (message "Entities are now displayed as plain text"))))
6313 (defvar org-custom-properties-overlays nil
6314 "List of overlays used for custom properties.")
6315 (make-variable-buffer-local 'org-custom-properties-overlays)
6317 (defun org-toggle-custom-properties-visibility ()
6318 "Display or hide properties in `org-custom-properties'."
6319 (interactive)
6320 (if org-custom-properties-overlays
6321 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6322 (setq org-custom-properties-overlays nil))
6323 (unless (not org-custom-properties)
6324 (save-excursion
6325 (save-restriction
6326 (widen)
6327 (goto-char (point-min))
6328 (while (re-search-forward org-property-re nil t)
6329 (mapc (lambda(p)
6330 (when (equal p (substring (match-string 1) 1 -1))
6331 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6332 (overlay-put o 'invisible t)
6333 (overlay-put o 'org-custom-property t)
6334 (push o org-custom-properties-overlays))))
6335 org-custom-properties)))))))
6337 (defun org-fontify-entities (limit)
6338 "Find an entity to fontify."
6339 (let (ee)
6340 (when org-pretty-entities
6341 (catch 'match
6342 (while (re-search-forward
6343 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6344 limit t)
6345 (if (and (not (org-in-indented-comment-line))
6346 (setq ee (org-entity-get (match-string 1)))
6347 (= (length (nth 6 ee)) 1))
6348 (let*
6349 ((end (if (equal (match-string 2) "{}")
6350 (match-end 2)
6351 (match-end 1))))
6352 (add-text-properties
6353 (match-beginning 0) end
6354 (list 'font-lock-fontified t))
6355 (compose-region (match-beginning 0) end
6356 (nth 6 ee) nil)
6357 (backward-char 1)
6358 (throw 'match t))))
6359 nil))))
6361 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6362 "Fontify string S like in Org-mode."
6363 (with-temp-buffer
6364 (insert s)
6365 (let ((org-odd-levels-only odd-levels))
6366 (org-mode)
6367 (font-lock-fontify-buffer)
6368 (buffer-string))))
6370 (defvar org-m nil)
6371 (defvar org-l nil)
6372 (defvar org-f nil)
6373 (defun org-get-level-face (n)
6374 "Get the right face for match N in font-lock matching of headlines."
6375 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6376 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6377 (if org-cycle-level-faces
6378 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6379 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6380 (cond
6381 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6382 ((eq n 2) org-f)
6383 (t (if org-level-color-stars-only nil org-f))))
6386 (defun org-get-todo-face (kwd)
6387 "Get the right face for a TODO keyword KWD.
6388 If KWD is a number, get the corresponding match group."
6389 (if (numberp kwd) (setq kwd (match-string kwd)))
6390 (or (org-face-from-face-or-color
6391 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6392 (and (member kwd org-done-keywords) 'org-done)
6393 'org-todo))
6395 (defun org-face-from-face-or-color (context inherit face-or-color)
6396 "Create a face list that inherits INHERIT, but sets the foreground color.
6397 When FACE-OR-COLOR is not a string, just return it."
6398 (if (stringp face-or-color)
6399 (list :inherit inherit
6400 (cdr (assoc context org-faces-easy-properties))
6401 face-or-color)
6402 face-or-color))
6404 (defun org-font-lock-add-tag-faces (limit)
6405 "Add the special tag faces."
6406 (when (and org-tag-faces org-tags-special-faces-re)
6407 (while (re-search-forward org-tags-special-faces-re limit t)
6408 (add-text-properties (match-beginning 1) (match-end 1)
6409 (list 'face (org-get-tag-face 1)
6410 'font-lock-fontified t))
6411 (backward-char 1))))
6413 (defun org-font-lock-add-priority-faces (limit)
6414 "Add the special priority faces."
6415 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6416 (when (save-match-data (org-at-heading-p))
6417 (add-text-properties
6418 (match-beginning 0) (match-end 0)
6419 (list 'face (or (org-face-from-face-or-color
6420 'priority 'org-priority
6421 (cdr (assoc (char-after (match-beginning 1))
6422 org-priority-faces)))
6423 'org-priority)
6424 'font-lock-fontified t)))))
6426 (defun org-get-tag-face (kwd)
6427 "Get the right face for a TODO keyword KWD.
6428 If KWD is a number, get the corresponding match group."
6429 (if (numberp kwd) (setq kwd (match-string kwd)))
6430 (or (org-face-from-face-or-color
6431 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6432 'org-tag))
6434 (defun org-unfontify-region (beg end &optional maybe_loudly)
6435 "Remove fontification and activation overlays from links."
6436 (font-lock-default-unfontify-region beg end)
6437 (let* ((buffer-undo-list t)
6438 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6439 (inhibit-modification-hooks t)
6440 deactivate-mark buffer-file-name buffer-file-truename)
6441 (org-decompose-region beg end)
6442 (remove-text-properties beg end
6443 '(mouse-face t keymap t org-linked-text t
6444 invisible t intangible t
6445 org-no-flyspell t org-emphasis t))
6446 (org-remove-font-lock-display-properties beg end)))
6448 (defconst org-script-display '(((raise -0.3) (height 0.7))
6449 ((raise 0.3) (height 0.7))
6450 ((raise -0.5))
6451 ((raise 0.5)))
6452 "Display properties for showing superscripts and subscripts.")
6454 (defun org-remove-font-lock-display-properties (beg end)
6455 "Remove specific display properties that have been added by font lock.
6456 The will remove the raise properties that are used to show superscripts
6457 and subscripts."
6458 (let (next prop)
6459 (while (< beg end)
6460 (setq next (next-single-property-change beg 'display nil end)
6461 prop (get-text-property beg 'display))
6462 (if (member prop org-script-display)
6463 (put-text-property beg next 'display nil))
6464 (setq beg next))))
6466 (defun org-raise-scripts (limit)
6467 "Add raise properties to sub/superscripts."
6468 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6469 (if (re-search-forward
6470 (if (eq org-use-sub-superscripts t)
6471 org-match-substring-regexp
6472 org-match-substring-with-braces-regexp)
6473 limit t)
6474 (let* ((pos (point)) table-p comment-p
6475 (mpos (match-beginning 3))
6476 (emph-p (get-text-property mpos 'org-emphasis))
6477 (link-p (get-text-property mpos 'mouse-face))
6478 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6479 (goto-char (point-at-bol))
6480 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6481 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6482 (goto-char pos)
6483 ;; Handle a_b^c
6484 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6485 (if (or comment-p emph-p link-p keyw-p)
6487 (put-text-property (match-beginning 3) (match-end 0)
6488 'display
6489 (if (equal (char-after (match-beginning 2)) ?^)
6490 (nth (if table-p 3 1) org-script-display)
6491 (nth (if table-p 2 0) org-script-display)))
6492 (add-text-properties (match-beginning 2) (match-end 2)
6493 (list 'invisible t
6494 'org-dwidth t 'org-dwidth-n 1))
6495 (if (and (eq (char-after (match-beginning 3)) ?{)
6496 (eq (char-before (match-end 3)) ?}))
6497 (progn
6498 (add-text-properties
6499 (match-beginning 3) (1+ (match-beginning 3))
6500 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6501 (add-text-properties
6502 (1- (match-end 3)) (match-end 3)
6503 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6504 t)))))
6506 ;;;; Visibility cycling, including org-goto and indirect buffer
6508 ;;; Cycling
6510 (defvar org-cycle-global-status nil)
6511 (make-variable-buffer-local 'org-cycle-global-status)
6512 (put 'org-cycle-global-status 'org-state t)
6513 (defvar org-cycle-subtree-status nil)
6514 (make-variable-buffer-local 'org-cycle-subtree-status)
6515 (put 'org-cycle-subtree-status 'org-state t)
6517 (defvar org-inlinetask-min-level)
6519 (defun org-unlogged-message (&rest args)
6520 "Display a message, but avoid logging it in the *Messages* buffer."
6521 (let ((message-log-max nil))
6522 (apply 'message args)))
6524 ;;;###autoload
6525 (defun org-cycle (&optional arg)
6526 "TAB-action and visibility cycling for Org-mode.
6528 This is the command invoked in Org-mode by the TAB key. Its main purpose
6529 is outline visibility cycling, but it also invokes other actions
6530 in special contexts.
6532 - When this function is called with a prefix argument, rotate the entire
6533 buffer through 3 states (global cycling)
6534 1. OVERVIEW: Show only top-level headlines.
6535 2. CONTENTS: Show all headlines of all levels, but no body text.
6536 3. SHOW ALL: Show everything.
6537 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6538 determined by the variable `org-startup-folded', and by any VISIBILITY
6539 properties in the buffer.
6540 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6541 including any drawers.
6543 - When inside a table, re-align the table and move to the next field.
6545 - When point is at the beginning of a headline, rotate the subtree started
6546 by this line through 3 different states (local cycling)
6547 1. FOLDED: Only the main headline is shown.
6548 2. CHILDREN: The main headline and the direct children are shown.
6549 From this state, you can move to one of the children
6550 and zoom in further.
6551 3. SUBTREE: Show the entire subtree, including body text.
6552 If there is no subtree, switch directly from CHILDREN to FOLDED.
6554 - When point is at the beginning of an empty headline and the variable
6555 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6556 of the headline by demoting and promoting it to likely levels. This
6557 speeds up creation document structure by pressing TAB once or several
6558 times right after creating a new headline.
6560 - When there is a numeric prefix, go up to a heading with level ARG, do
6561 a `show-subtree' and return to the previous cursor position. If ARG
6562 is negative, go up that many levels.
6564 - When point is not at the beginning of a headline, execute the global
6565 binding for TAB, which is re-indenting the line. See the option
6566 `org-cycle-emulate-tab' for details.
6568 - Special case: if point is at the beginning of the buffer and there is
6569 no headline in line 1, this function will act as if called with prefix arg
6570 (C-u TAB, same as S-TAB) also when called without prefix arg.
6571 But only if also the variable `org-cycle-global-at-bob' is t."
6572 (interactive "P")
6573 (org-load-modules-maybe)
6574 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6575 (and org-cycle-level-after-item/entry-creation
6576 (or (org-cycle-level)
6577 (org-cycle-item-indentation))))
6578 (let* ((limit-level
6579 (or org-cycle-max-level
6580 (and (boundp 'org-inlinetask-min-level)
6581 org-inlinetask-min-level
6582 (1- org-inlinetask-min-level))))
6583 (nstars (and limit-level
6584 (if org-odd-levels-only
6585 (and limit-level (1- (* limit-level 2)))
6586 limit-level)))
6587 (org-outline-regexp
6588 (if (not (derived-mode-p 'org-mode))
6589 outline-regexp
6590 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6591 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6592 (not (looking-at org-outline-regexp))))
6593 (org-cycle-hook
6594 (if bob-special
6595 (delq 'org-optimize-window-after-visibility-change
6596 (copy-sequence org-cycle-hook))
6597 org-cycle-hook))
6598 (pos (point)))
6600 (if (or bob-special (equal arg '(4)))
6601 ;; special case: use global cycling
6602 (setq arg t))
6604 (cond
6606 ((equal arg '(16))
6607 (setq last-command 'dummy)
6608 (org-set-startup-visibility)
6609 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6611 ((equal arg '(64))
6612 (show-all)
6613 (org-unlogged-message "Entire buffer visible, including drawers"))
6615 ;; Table: enter it or move to the next field.
6616 ((org-at-table-p 'any)
6617 (if (org-at-table.el-p)
6618 (message "Use C-c ' to edit table.el tables")
6619 (if arg (org-table-edit-field t)
6620 (org-table-justify-field-maybe)
6621 (call-interactively 'org-table-next-field))))
6623 ((run-hook-with-args-until-success
6624 'org-tab-after-check-for-table-hook))
6626 ;; Global cycling: delegate to `org-cycle-internal-global'.
6627 ((eq arg t) (org-cycle-internal-global))
6629 ;; Drawers: delegate to `org-flag-drawer'.
6630 ((and org-drawers org-drawer-regexp
6631 (save-excursion
6632 (beginning-of-line 1)
6633 (looking-at org-drawer-regexp)))
6634 (org-flag-drawer ; toggle block visibility
6635 (not (get-char-property (match-end 0) 'invisible))))
6637 ;; Show-subtree, ARG levels up from here.
6638 ((integerp arg)
6639 (save-excursion
6640 (org-back-to-heading)
6641 (outline-up-heading (if (< arg 0) (- arg)
6642 (- (funcall outline-level) arg)))
6643 (org-show-subtree)))
6645 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6646 ((and (featurep 'org-inlinetask)
6647 (org-inlinetask-at-task-p)
6648 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6649 (org-inlinetask-toggle-visibility))
6651 ((org-try-cdlatex-tab))
6653 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6654 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6655 (save-excursion (beginning-of-line 1)
6656 (looking-at org-outline-regexp)))
6657 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6658 (org-cycle-internal-local))
6660 ;; From there: TAB emulation and template completion.
6661 (buffer-read-only (org-back-to-heading))
6663 ((run-hook-with-args-until-success
6664 'org-tab-after-check-for-cycling-hook))
6666 ((org-try-structure-completion))
6668 ((run-hook-with-args-until-success
6669 'org-tab-before-tab-emulation-hook))
6671 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6672 (or (not (bolp))
6673 (not (looking-at org-outline-regexp))))
6674 (call-interactively (global-key-binding "\t")))
6676 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6677 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6678 (or (and (eq org-cycle-emulate-tab 'white)
6679 (= (match-end 0) (point-at-eol)))
6680 (and (eq org-cycle-emulate-tab 'whitestart)
6681 (>= (match-end 0) pos))))
6683 (eq org-cycle-emulate-tab t))
6684 (call-interactively (global-key-binding "\t")))
6686 (t (save-excursion
6687 (org-back-to-heading)
6688 (org-cycle)))))))
6690 (defun org-cycle-internal-global ()
6691 "Do the global cycling action."
6692 ;; Hack to avoid display of messages for .org attachments in Gnus
6693 (let ((ga (string-match "\\*fontification" (buffer-name))))
6694 (cond
6695 ((and (eq last-command this-command)
6696 (eq org-cycle-global-status 'overview))
6697 ;; We just created the overview - now do table of contents
6698 ;; This can be slow in very large buffers, so indicate action
6699 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6700 (unless ga (org-unlogged-message "CONTENTS..."))
6701 (org-content)
6702 (unless ga (org-unlogged-message "CONTENTS...done"))
6703 (setq org-cycle-global-status 'contents)
6704 (run-hook-with-args 'org-cycle-hook 'contents))
6706 ((and (eq last-command this-command)
6707 (eq org-cycle-global-status 'contents))
6708 ;; We just showed the table of contents - now show everything
6709 (run-hook-with-args 'org-pre-cycle-hook 'all)
6710 (show-all)
6711 (unless ga (org-unlogged-message "SHOW ALL"))
6712 (setq org-cycle-global-status 'all)
6713 (run-hook-with-args 'org-cycle-hook 'all))
6716 ;; Default action: go to overview
6717 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6718 (org-overview)
6719 (unless ga (org-unlogged-message "OVERVIEW"))
6720 (setq org-cycle-global-status 'overview)
6721 (run-hook-with-args 'org-cycle-hook 'overview)))))
6723 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6725 (defun org-cycle-internal-local ()
6726 "Do the local cycling action."
6727 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6728 ;; First, determine end of headline (EOH), end of subtree or item
6729 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6730 (save-excursion
6731 (if (org-at-item-p)
6732 (progn
6733 (beginning-of-line)
6734 (setq struct (org-list-struct))
6735 (setq eoh (point-at-eol))
6736 (setq eos (org-list-get-item-end-before-blank (point) struct))
6737 (setq has-children (org-list-has-child-p (point) struct)))
6738 (org-back-to-heading)
6739 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6740 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6741 (setq has-children
6742 (or (save-excursion
6743 (let ((level (funcall outline-level)))
6744 (outline-next-heading)
6745 (and (org-at-heading-p t)
6746 (> (funcall outline-level) level))))
6747 (save-excursion
6748 (org-list-search-forward (org-item-beginning-re) eos t)))))
6749 ;; Determine end invisible part of buffer (EOL)
6750 (beginning-of-line 2)
6751 ;; XEmacs doesn't have `next-single-char-property-change'
6752 (if (featurep 'xemacs)
6753 (while (and (not (eobp)) ;; this is like `next-line'
6754 (get-char-property (1- (point)) 'invisible))
6755 (beginning-of-line 2))
6756 (while (and (not (eobp)) ;; this is like `next-line'
6757 (get-char-property (1- (point)) 'invisible))
6758 (goto-char (next-single-char-property-change (point) 'invisible))
6759 (and (eolp) (beginning-of-line 2))))
6760 (setq eol (point)))
6761 ;; Find out what to do next and set `this-command'
6762 (cond
6763 ((= eos eoh)
6764 ;; Nothing is hidden behind this heading
6765 (unless (org-before-first-heading-p)
6766 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6767 (org-unlogged-message "EMPTY ENTRY")
6768 (setq org-cycle-subtree-status nil)
6769 (save-excursion
6770 (goto-char eos)
6771 (outline-next-heading)
6772 (if (outline-invisible-p) (org-flag-heading nil))))
6773 ((and (or (>= eol eos)
6774 (not (string-match "\\S-" (buffer-substring eol eos))))
6775 (or has-children
6776 (not (setq children-skipped
6777 org-cycle-skip-children-state-if-no-children))))
6778 ;; Entire subtree is hidden in one line: children view
6779 (unless (org-before-first-heading-p)
6780 (run-hook-with-args 'org-pre-cycle-hook 'children))
6781 (if (org-at-item-p)
6782 (org-list-set-item-visibility (point-at-bol) struct 'children)
6783 (org-show-entry)
6784 (org-with-limited-levels (show-children))
6785 ;; FIXME: This slows down the func way too much.
6786 ;; How keep drawers hidden in subtree anyway?
6787 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6788 ;; (org-cycle-hide-drawers 'subtree))
6790 ;; Fold every list in subtree to top-level items.
6791 (when (eq org-cycle-include-plain-lists 'integrate)
6792 (save-excursion
6793 (org-back-to-heading)
6794 (while (org-list-search-forward (org-item-beginning-re) eos t)
6795 (beginning-of-line 1)
6796 (let* ((struct (org-list-struct))
6797 (prevs (org-list-prevs-alist struct))
6798 (end (org-list-get-bottom-point struct)))
6799 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6800 (org-list-get-all-items (point) struct prevs))
6801 (goto-char (if (< end eos) end eos)))))))
6802 (org-unlogged-message "CHILDREN")
6803 (save-excursion
6804 (goto-char eos)
6805 (outline-next-heading)
6806 (if (outline-invisible-p) (org-flag-heading nil)))
6807 (setq org-cycle-subtree-status 'children)
6808 (unless (org-before-first-heading-p)
6809 (run-hook-with-args 'org-cycle-hook 'children)))
6810 ((or children-skipped
6811 (and (eq last-command this-command)
6812 (eq org-cycle-subtree-status 'children)))
6813 ;; We just showed the children, or no children are there,
6814 ;; now show everything.
6815 (unless (org-before-first-heading-p)
6816 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6817 (outline-flag-region eoh eos nil)
6818 (org-unlogged-message
6819 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6820 (setq org-cycle-subtree-status 'subtree)
6821 (unless (org-before-first-heading-p)
6822 (run-hook-with-args 'org-cycle-hook 'subtree)))
6824 ;; Default action: hide the subtree.
6825 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6826 (outline-flag-region eoh eos t)
6827 (org-unlogged-message "FOLDED")
6828 (setq org-cycle-subtree-status 'folded)
6829 (unless (org-before-first-heading-p)
6830 (run-hook-with-args 'org-cycle-hook 'folded))))))
6832 ;;;###autoload
6833 (defun org-global-cycle (&optional arg)
6834 "Cycle the global visibility. For details see `org-cycle'.
6835 With \\[universal-argument] prefix arg, switch to startup visibility.
6836 With a numeric prefix, show all headlines up to that level."
6837 (interactive "P")
6838 (let ((org-cycle-include-plain-lists
6839 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6840 (cond
6841 ((integerp arg)
6842 (show-all)
6843 (hide-sublevels arg)
6844 (setq org-cycle-global-status 'contents))
6845 ((equal arg '(4))
6846 (org-set-startup-visibility)
6847 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6849 (org-cycle '(4))))))
6851 (defun org-set-startup-visibility ()
6852 "Set the visibility required by startup options and properties."
6853 (cond
6854 ((eq org-startup-folded t)
6855 (org-cycle '(4)))
6856 ((eq org-startup-folded 'content)
6857 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6858 (org-cycle '(4)) (org-cycle '(4)))))
6859 (unless (eq org-startup-folded 'showeverything)
6860 (if org-hide-block-startup (org-hide-block-all))
6861 (org-set-visibility-according-to-property 'no-cleanup)
6862 (org-cycle-hide-archived-subtrees 'all)
6863 (org-cycle-hide-drawers 'all)
6864 (org-cycle-show-empty-lines t)))
6866 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6867 "Switch subtree visibilities according to :VISIBILITY: property."
6868 (interactive)
6869 (let (org-show-entry-below state)
6870 (save-excursion
6871 (goto-char (point-min))
6872 (while (re-search-forward
6873 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6874 nil t)
6875 (setq state (match-string 1))
6876 (save-excursion
6877 (org-back-to-heading t)
6878 (hide-subtree)
6879 (org-reveal)
6880 (cond
6881 ((equal state '("fold" "folded"))
6882 (hide-subtree))
6883 ((equal state "children")
6884 (org-show-hidden-entry)
6885 (show-children))
6886 ((equal state "content")
6887 (save-excursion
6888 (save-restriction
6889 (org-narrow-to-subtree)
6890 (org-content))))
6891 ((member state '("all" "showall"))
6892 (show-subtree)))))
6893 (unless no-cleanup
6894 (org-cycle-hide-archived-subtrees 'all)
6895 (org-cycle-hide-drawers 'all)
6896 (org-cycle-show-empty-lines 'all)))))
6898 ;; This function uses outline-regexp instead of the more fundamental
6899 ;; org-outline-regexp so that org-cycle-global works outside of Org
6900 ;; buffers, where outline-regexp is needed.
6901 (defun org-overview ()
6902 "Switch to overview mode, showing only top-level headlines.
6903 Really, this shows all headlines with level equal or greater than the level
6904 of the first headline in the buffer. This is important, because if the
6905 first headline is not level one, then (hide-sublevels 1) gives confusing
6906 results."
6907 (interactive)
6908 (let ((pos (point))
6909 (level (save-excursion
6910 (goto-char (point-min))
6911 (if (re-search-forward (concat "^" outline-regexp) nil t)
6912 (progn
6913 (goto-char (match-beginning 0))
6914 (funcall outline-level))))))
6915 (and level (hide-sublevels level))
6916 (recenter '(4))
6917 (goto-char pos)))
6919 (defun org-content (&optional arg)
6920 "Show all headlines in the buffer, like a table of contents.
6921 With numerical argument N, show content up to level N."
6922 (interactive "P")
6923 (save-excursion
6924 ;; Visit all headings and show their offspring
6925 (and (integerp arg) (org-overview))
6926 (goto-char (point-max))
6927 (catch 'exit
6928 (while (and (progn (condition-case nil
6929 (outline-previous-visible-heading 1)
6930 (error (goto-char (point-min))))
6932 (looking-at org-outline-regexp))
6933 (if (integerp arg)
6934 (show-children (1- arg))
6935 (show-branches))
6936 (if (bobp) (throw 'exit nil))))))
6939 (defun org-optimize-window-after-visibility-change (state)
6940 "Adjust the window after a change in outline visibility.
6941 This function is the default value of the hook `org-cycle-hook'."
6942 (when (get-buffer-window (current-buffer))
6943 (cond
6944 ((eq state 'content) nil)
6945 ((eq state 'all) nil)
6946 ((eq state 'folded) nil)
6947 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6948 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6950 (defun org-remove-empty-overlays-at (pos)
6951 "Remove outline overlays that do not contain non-white stuff."
6952 (mapc
6953 (lambda (o)
6954 (and (eq 'outline (overlay-get o 'invisible))
6955 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6956 (overlay-end o))))
6957 (delete-overlay o)))
6958 (overlays-at pos)))
6960 (defun org-clean-visibility-after-subtree-move ()
6961 "Fix visibility issues after moving a subtree."
6962 ;; First, find a reasonable region to look at:
6963 ;; Start two siblings above, end three below
6964 (let* ((beg (save-excursion
6965 (and (org-get-last-sibling)
6966 (org-get-last-sibling))
6967 (point)))
6968 (end (save-excursion
6969 (and (org-get-next-sibling)
6970 (org-get-next-sibling)
6971 (org-get-next-sibling))
6972 (if (org-at-heading-p)
6973 (point-at-eol)
6974 (point))))
6975 (level (looking-at "\\*+"))
6976 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6977 (save-excursion
6978 (save-restriction
6979 (narrow-to-region beg end)
6980 (when re
6981 ;; Properly fold already folded siblings
6982 (goto-char (point-min))
6983 (while (re-search-forward re nil t)
6984 (if (and (not (outline-invisible-p))
6985 (save-excursion
6986 (goto-char (point-at-eol)) (outline-invisible-p)))
6987 (hide-entry))))
6988 (org-cycle-show-empty-lines 'overview)
6989 (org-cycle-hide-drawers 'overview)))))
6991 (defun org-cycle-show-empty-lines (state)
6992 "Show empty lines above all visible headlines.
6993 The region to be covered depends on STATE when called through
6994 `org-cycle-hook'. Lisp program can use t for STATE to get the
6995 entire buffer covered. Note that an empty line is only shown if there
6996 are at least `org-cycle-separator-lines' empty lines before the headline."
6997 (when (not (= org-cycle-separator-lines 0))
6998 (save-excursion
6999 (let* ((n (abs org-cycle-separator-lines))
7000 (re (cond
7001 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7002 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7003 (t (let ((ns (number-to-string (- n 2))))
7004 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7005 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7006 beg end b e)
7007 (cond
7008 ((memq state '(overview contents t))
7009 (setq beg (point-min) end (point-max)))
7010 ((memq state '(children folded))
7011 (setq beg (point) end (progn (org-end-of-subtree t t)
7012 (beginning-of-line 2)
7013 (point)))))
7014 (when beg
7015 (goto-char beg)
7016 (while (re-search-forward re end t)
7017 (unless (get-char-property (match-end 1) 'invisible)
7018 (setq e (match-end 1))
7019 (if (< org-cycle-separator-lines 0)
7020 (setq b (save-excursion
7021 (goto-char (match-beginning 0))
7022 (org-back-over-empty-lines)
7023 (if (save-excursion
7024 (goto-char (max (point-min) (1- (point))))
7025 (org-at-heading-p))
7026 (1- (point))
7027 (point))))
7028 (setq b (match-beginning 1)))
7029 (outline-flag-region b e nil)))))))
7030 ;; Never hide empty lines at the end of the file.
7031 (save-excursion
7032 (goto-char (point-max))
7033 (outline-previous-heading)
7034 (outline-end-of-heading)
7035 (if (and (looking-at "[ \t\n]+")
7036 (= (match-end 0) (point-max)))
7037 (outline-flag-region (point) (match-end 0) nil))))
7039 (defun org-show-empty-lines-in-parent ()
7040 "Move to the parent and re-show empty lines before visible headlines."
7041 (save-excursion
7042 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7043 (org-cycle-show-empty-lines context))))
7045 (defun org-files-list ()
7046 "Return `org-agenda-files' list, plus all open org-mode files.
7047 This is useful for operations that need to scan all of a user's
7048 open and agenda-wise Org files."
7049 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7050 (dolist (buf (buffer-list))
7051 (with-current-buffer buf
7052 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7053 (let ((file (expand-file-name (buffer-file-name))))
7054 (unless (member file files)
7055 (push file files))))))
7056 files))
7058 (defsubst org-entry-beginning-position ()
7059 "Return the beginning position of the current entry."
7060 (save-excursion (outline-back-to-heading t) (point)))
7062 (defsubst org-entry-end-position ()
7063 "Return the end position of the current entry."
7064 (save-excursion (outline-next-heading) (point)))
7066 (defun org-cycle-hide-drawers (state)
7067 "Re-hide all drawers after a visibility state change."
7068 (when (and (derived-mode-p 'org-mode)
7069 (not (memq state '(overview folded contents))))
7070 (save-excursion
7071 (let* ((globalp (memq state '(contents all)))
7072 (beg (if globalp (point-min) (point)))
7073 (end (if globalp (point-max)
7074 (if (eq state 'children)
7075 (save-excursion (outline-next-heading) (point))
7076 (org-end-of-subtree t)))))
7077 (goto-char beg)
7078 (while (re-search-forward org-drawer-regexp end t)
7079 (org-flag-drawer t))))))
7081 (defun org-cycle-hide-inline-tasks (state)
7082 "Re-hide inline tasks when switching to 'contents or 'children
7083 visibility state."
7084 (case state
7085 (contents
7086 (when (org-bound-and-true-p org-inlinetask-min-level)
7087 (hide-sublevels (1- org-inlinetask-min-level))))
7088 (children
7089 (when (featurep 'org-inlinetask)
7090 (save-excursion
7091 (while (and (outline-next-heading)
7092 (org-inlinetask-at-task-p))
7093 (org-inlinetask-toggle-visibility)
7094 (org-inlinetask-goto-end)))))))
7096 (defun org-flag-drawer (flag)
7097 "When FLAG is non-nil, hide the drawer we are within.
7098 Otherwise make it visible."
7099 (save-excursion
7100 (beginning-of-line 1)
7101 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7102 (let ((b (match-end 0)))
7103 (if (re-search-forward
7104 "^[ \t]*:END:"
7105 (save-excursion (outline-next-heading) (point)) t)
7106 (outline-flag-region b (point-at-eol) flag)
7107 (user-error ":END: line missing at position %s" b))))))
7109 (defun org-subtree-end-visible-p ()
7110 "Is the end of the current subtree visible?"
7111 (pos-visible-in-window-p
7112 (save-excursion (org-end-of-subtree t) (point))))
7114 (defun org-first-headline-recenter (&optional N)
7115 "Move cursor to the first headline and recenter the headline.
7116 Optional argument N means put the headline into the Nth line of the window."
7117 (goto-char (point-min))
7118 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7119 (beginning-of-line)
7120 (recenter (prefix-numeric-value N))))
7122 ;;; Saving and restoring visibility
7124 (defun org-outline-overlay-data (&optional use-markers)
7125 "Return a list of the locations of all outline overlays.
7126 These are overlays with the `invisible' property value `outline'.
7127 The return value is a list of cons cells, with start and stop
7128 positions for each overlay.
7129 If USE-MARKERS is set, return the positions as markers."
7130 (let (beg end)
7131 (save-excursion
7132 (save-restriction
7133 (widen)
7134 (delq nil
7135 (mapcar (lambda (o)
7136 (when (eq (overlay-get o 'invisible) 'outline)
7137 (setq beg (overlay-start o)
7138 end (overlay-end o))
7139 (and beg end (> end beg)
7140 (if use-markers
7141 (cons (move-marker (make-marker) beg)
7142 (move-marker (make-marker) end))
7143 (cons beg end)))))
7144 (overlays-in (point-min) (point-max))))))))
7146 (defun org-set-outline-overlay-data (data)
7147 "Create visibility overlays for all positions in DATA.
7148 DATA should have been made by `org-outline-overlay-data'."
7149 (let (o)
7150 (save-excursion
7151 (save-restriction
7152 (widen)
7153 (show-all)
7154 (mapc (lambda (c)
7155 (outline-flag-region (car c) (cdr c) t))
7156 data)))))
7158 ;;; Folding of blocks
7160 (defvar org-hide-block-overlays nil
7161 "Overlays hiding blocks.")
7162 (make-variable-buffer-local 'org-hide-block-overlays)
7164 (defun org-block-map (function &optional start end)
7165 "Call FUNCTION at the head of all source blocks in the current buffer.
7166 Optional arguments START and END can be used to limit the range."
7167 (let ((start (or start (point-min)))
7168 (end (or end (point-max))))
7169 (save-excursion
7170 (goto-char start)
7171 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7172 (save-excursion
7173 (save-match-data
7174 (goto-char (match-beginning 0))
7175 (funcall function)))))))
7177 (defun org-hide-block-toggle-all ()
7178 "Toggle the visibility of all blocks in the current buffer."
7179 (org-block-map #'org-hide-block-toggle))
7181 (defun org-hide-block-all ()
7182 "Fold all blocks in the current buffer."
7183 (interactive)
7184 (org-show-block-all)
7185 (org-block-map #'org-hide-block-toggle-maybe))
7187 (defun org-show-block-all ()
7188 "Unfold all blocks in the current buffer."
7189 (interactive)
7190 (mapc 'delete-overlay org-hide-block-overlays)
7191 (setq org-hide-block-overlays nil))
7193 (defun org-hide-block-toggle-maybe ()
7194 "Toggle visibility of block at point."
7195 (interactive)
7196 (let ((case-fold-search t))
7197 (if (save-excursion
7198 (beginning-of-line 1)
7199 (looking-at org-block-regexp))
7200 (progn (org-hide-block-toggle)
7201 t) ;; to signal that we took action
7202 nil))) ;; to signal that we did not
7204 (defun org-hide-block-toggle (&optional force)
7205 "Toggle the visibility of the current block."
7206 (interactive)
7207 (save-excursion
7208 (beginning-of-line)
7209 (if (re-search-forward org-block-regexp nil t)
7210 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7211 (end (match-end 0)) ;; end of entire body
7213 (if (memq t (mapcar (lambda (overlay)
7214 (eq (overlay-get overlay 'invisible)
7215 'org-hide-block))
7216 (overlays-at start)))
7217 (if (or (not force) (eq force 'off))
7218 (mapc (lambda (ov)
7219 (when (member ov org-hide-block-overlays)
7220 (setq org-hide-block-overlays
7221 (delq ov org-hide-block-overlays)))
7222 (when (eq (overlay-get ov 'invisible)
7223 'org-hide-block)
7224 (delete-overlay ov)))
7225 (overlays-at start)))
7226 (setq ov (make-overlay start end))
7227 (overlay-put ov 'invisible 'org-hide-block)
7228 ;; make the block accessible to isearch
7229 (overlay-put
7230 ov 'isearch-open-invisible
7231 (lambda (ov)
7232 (when (member ov org-hide-block-overlays)
7233 (setq org-hide-block-overlays
7234 (delq ov org-hide-block-overlays)))
7235 (when (eq (overlay-get ov 'invisible)
7236 'org-hide-block)
7237 (delete-overlay ov))))
7238 (push ov org-hide-block-overlays)))
7239 (user-error "Not looking at a source block"))))
7241 ;; org-tab-after-check-for-cycling-hook
7242 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7243 ;; Remove overlays when changing major mode
7244 (add-hook 'org-mode-hook
7245 (lambda () (org-add-hook 'change-major-mode-hook
7246 'org-show-block-all 'append 'local)))
7248 ;;; Org-goto
7250 (defvar org-goto-window-configuration nil)
7251 (defvar org-goto-marker nil)
7252 (defvar org-goto-map)
7253 (defun org-goto-map ()
7254 "Set the keymap `org-goto'."
7255 (setq org-goto-map
7256 (let ((map (make-sparse-keymap)))
7257 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7258 mouse-drag-region universal-argument org-occur))
7259 cmd)
7260 (while (setq cmd (pop cmds))
7261 (substitute-key-definition cmd cmd map global-map)))
7262 (suppress-keymap map)
7263 (org-defkey map "\C-m" 'org-goto-ret)
7264 (org-defkey map [(return)] 'org-goto-ret)
7265 (org-defkey map [(left)] 'org-goto-left)
7266 (org-defkey map [(right)] 'org-goto-right)
7267 (org-defkey map [(control ?g)] 'org-goto-quit)
7268 (org-defkey map "\C-i" 'org-cycle)
7269 (org-defkey map [(tab)] 'org-cycle)
7270 (org-defkey map [(down)] 'outline-next-visible-heading)
7271 (org-defkey map [(up)] 'outline-previous-visible-heading)
7272 (if org-goto-auto-isearch
7273 (if (fboundp 'define-key-after)
7274 (define-key-after map [t] 'org-goto-local-auto-isearch)
7275 nil)
7276 (org-defkey map "q" 'org-goto-quit)
7277 (org-defkey map "n" 'outline-next-visible-heading)
7278 (org-defkey map "p" 'outline-previous-visible-heading)
7279 (org-defkey map "f" 'outline-forward-same-level)
7280 (org-defkey map "b" 'outline-backward-same-level)
7281 (org-defkey map "u" 'outline-up-heading))
7282 (org-defkey map "/" 'org-occur)
7283 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7284 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7285 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7286 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7287 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7288 map)))
7290 (defconst org-goto-help
7291 "Browse buffer copy, to find location or copy text.%s
7292 RET=jump to location C-g=quit and return to previous location
7293 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7295 (defvar org-goto-start-pos) ; dynamically scoped parameter
7297 (defun org-goto (&optional alternative-interface)
7298 "Look up a different location in the current file, keeping current visibility.
7300 When you want look-up or go to a different location in a
7301 document, the fastest way is often to fold the entire buffer and
7302 then dive into the tree. This method has the disadvantage, that
7303 the previous location will be folded, which may not be what you
7304 want.
7306 This command works around this by showing a copy of the current
7307 buffer in an indirect buffer, in overview mode. You can dive
7308 into the tree in that copy, use org-occur and incremental search
7309 to find a location. When pressing RET or `Q', the command
7310 returns to the original buffer in which the visibility is still
7311 unchanged. After RET it will also jump to the location selected
7312 in the indirect buffer and expose the headline hierarchy above.
7314 With a prefix argument, use the alternative interface: e.g. if
7315 `org-goto-interface' is 'outline use 'outline-path-completion."
7316 (interactive "P")
7317 (org-goto-map)
7318 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7319 (org-refile-use-outline-path t)
7320 (org-refile-target-verify-function nil)
7321 (interface
7322 (if (not alternative-interface)
7323 org-goto-interface
7324 (if (eq org-goto-interface 'outline)
7325 'outline-path-completion
7326 'outline)))
7327 (org-goto-start-pos (point))
7328 (selected-point
7329 (if (eq interface 'outline)
7330 (car (org-get-location (current-buffer) org-goto-help))
7331 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7332 (org-refile-check-position pa)
7333 (nth 3 pa)))))
7334 (if selected-point
7335 (progn
7336 (org-mark-ring-push org-goto-start-pos)
7337 (goto-char selected-point)
7338 (if (or (outline-invisible-p) (org-invisible-p2))
7339 (org-show-context 'org-goto)))
7340 (message "Quit"))))
7342 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7343 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7344 (defvar org-goto-local-auto-isearch-map) ; defined below
7346 (defun org-get-location (buf help)
7347 "Let the user select a location in the Org-mode buffer BUF.
7348 This function uses a recursive edit. It returns the selected position
7349 or nil."
7350 (org-no-popups
7351 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7352 (isearch-hide-immediately nil)
7353 (isearch-search-fun-function
7354 (lambda () 'org-goto-local-search-headings))
7355 (org-goto-selected-point org-goto-exit-command))
7356 (save-excursion
7357 (save-window-excursion
7358 (delete-other-windows)
7359 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7360 (org-pop-to-buffer-same-window
7361 (condition-case nil
7362 (make-indirect-buffer (current-buffer) "*org-goto*")
7363 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7364 (with-output-to-temp-buffer "*Org Help*"
7365 (princ (format help (if org-goto-auto-isearch
7366 " Just type for auto-isearch."
7367 " n/p/f/b/u to navigate, q to quit."))))
7368 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7369 (setq buffer-read-only nil)
7370 (let ((org-startup-truncated t)
7371 (org-startup-folded nil)
7372 (org-startup-align-all-tables nil))
7373 (org-mode)
7374 (org-overview))
7375 (setq buffer-read-only t)
7376 (if (and (boundp 'org-goto-start-pos)
7377 (integer-or-marker-p org-goto-start-pos))
7378 (let ((org-show-hierarchy-above t)
7379 (org-show-siblings t)
7380 (org-show-following-heading t))
7381 (goto-char org-goto-start-pos)
7382 (and (outline-invisible-p) (org-show-context)))
7383 (goto-char (point-min)))
7384 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7385 (message "Select location and press RET")
7386 (use-local-map org-goto-map)
7387 (recursive-edit)))
7388 (kill-buffer "*org-goto*")
7389 (cons org-goto-selected-point org-goto-exit-command))))
7391 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7392 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7393 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7394 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7396 (defun org-goto-local-search-headings (string bound noerror)
7397 "Search and make sure that any matches are in headlines."
7398 (catch 'return
7399 (while (if isearch-forward
7400 (search-forward string bound noerror)
7401 (search-backward string bound noerror))
7402 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7403 (and (member :headline context)
7404 (not (member :tags context))))
7405 (throw 'return (point))))))
7407 (defun org-goto-local-auto-isearch ()
7408 "Start isearch."
7409 (interactive)
7410 (goto-char (point-min))
7411 (let ((keys (this-command-keys)))
7412 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7413 (isearch-mode t)
7414 (isearch-process-search-char (string-to-char keys)))))
7416 (defun org-goto-ret (&optional arg)
7417 "Finish `org-goto' by going to the new location."
7418 (interactive "P")
7419 (setq org-goto-selected-point (point)
7420 org-goto-exit-command 'return)
7421 (throw 'exit nil))
7423 (defun org-goto-left ()
7424 "Finish `org-goto' by going to the new location."
7425 (interactive)
7426 (if (org-at-heading-p)
7427 (progn
7428 (beginning-of-line 1)
7429 (setq org-goto-selected-point (point)
7430 org-goto-exit-command 'left)
7431 (throw 'exit nil))
7432 (user-error "Not on a heading")))
7434 (defun org-goto-right ()
7435 "Finish `org-goto' by going to the new location."
7436 (interactive)
7437 (if (org-at-heading-p)
7438 (progn
7439 (setq org-goto-selected-point (point)
7440 org-goto-exit-command 'right)
7441 (throw 'exit nil))
7442 (user-error "Not on a heading")))
7444 (defun org-goto-quit ()
7445 "Finish `org-goto' without cursor motion."
7446 (interactive)
7447 (setq org-goto-selected-point nil)
7448 (setq org-goto-exit-command 'quit)
7449 (throw 'exit nil))
7451 ;;; Indirect buffer display of subtrees
7453 (defvar org-indirect-dedicated-frame nil
7454 "This is the frame being used for indirect tree display.")
7455 (defvar org-last-indirect-buffer nil)
7457 (defun org-tree-to-indirect-buffer (&optional arg)
7458 "Create indirect buffer and narrow it to current subtree.
7459 With a numerical prefix ARG, go up to this level and then take that tree.
7460 If ARG is negative, go up that many levels.
7462 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7463 indirect buffer previously made with this command, to avoid proliferation of
7464 indirect buffers. However, when you call the command with a \
7465 \\[universal-argument] prefix, or
7466 when `org-indirect-buffer-display' is `new-frame', the last buffer
7467 is kept so that you can work with several indirect buffers at the same time.
7468 If `org-indirect-buffer-display' is `dedicated-frame', the \
7469 \\[universal-argument] prefix also
7470 requests that a new frame be made for the new buffer, so that the dedicated
7471 frame is not changed."
7472 (interactive "P")
7473 (let ((cbuf (current-buffer))
7474 (cwin (selected-window))
7475 (pos (point))
7476 beg end level heading ibuf)
7477 (save-excursion
7478 (org-back-to-heading t)
7479 (when (numberp arg)
7480 (setq level (org-outline-level))
7481 (if (< arg 0) (setq arg (+ level arg)))
7482 (while (> (setq level (org-outline-level)) arg)
7483 (org-up-heading-safe)))
7484 (setq beg (point)
7485 heading (org-get-heading))
7486 (org-end-of-subtree t t)
7487 (if (org-at-heading-p) (backward-char 1))
7488 (setq end (point)))
7489 (if (and (buffer-live-p org-last-indirect-buffer)
7490 (not (eq org-indirect-buffer-display 'new-frame))
7491 (not arg))
7492 (kill-buffer org-last-indirect-buffer))
7493 (setq ibuf (org-get-indirect-buffer cbuf)
7494 org-last-indirect-buffer ibuf)
7495 (cond
7496 ((or (eq org-indirect-buffer-display 'new-frame)
7497 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7498 (select-frame (make-frame))
7499 (delete-other-windows)
7500 (org-pop-to-buffer-same-window ibuf)
7501 (org-set-frame-title heading))
7502 ((eq org-indirect-buffer-display 'dedicated-frame)
7503 (raise-frame
7504 (select-frame (or (and org-indirect-dedicated-frame
7505 (frame-live-p org-indirect-dedicated-frame)
7506 org-indirect-dedicated-frame)
7507 (setq org-indirect-dedicated-frame (make-frame)))))
7508 (delete-other-windows)
7509 (org-pop-to-buffer-same-window ibuf)
7510 (org-set-frame-title (concat "Indirect: " heading)))
7511 ((eq org-indirect-buffer-display 'current-window)
7512 (org-pop-to-buffer-same-window ibuf))
7513 ((eq org-indirect-buffer-display 'other-window)
7514 (pop-to-buffer ibuf))
7515 (t (error "Invalid value")))
7516 (if (featurep 'xemacs)
7517 (save-excursion (org-mode) (turn-on-font-lock)))
7518 (narrow-to-region beg end)
7519 (show-all)
7520 (goto-char pos)
7521 (run-hook-with-args 'org-cycle-hook 'all)
7522 (and (window-live-p cwin) (select-window cwin))))
7524 (defun org-get-indirect-buffer (&optional buffer)
7525 (setq buffer (or buffer (current-buffer)))
7526 (let ((n 1) (base (buffer-name buffer)) bname)
7527 (while (buffer-live-p
7528 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7529 (setq n (1+ n)))
7530 (condition-case nil
7531 (make-indirect-buffer buffer bname 'clone)
7532 (error (make-indirect-buffer buffer bname)))))
7534 (defun org-set-frame-title (title)
7535 "Set the title of the current frame to the string TITLE."
7536 ;; FIXME: how to name a single frame in XEmacs???
7537 (unless (featurep 'xemacs)
7538 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7540 ;;;; Structure editing
7542 ;;; Inserting headlines
7544 (defun org-previous-line-empty-p (&optional next)
7545 "Is the previous line a blank line?
7546 When NEXT is non-nil, check the next line instead."
7547 (save-excursion
7548 (and (not (bobp))
7549 (or (beginning-of-line (if next 2 0)) t)
7550 (save-match-data
7551 (looking-at "[ \t]*$")))))
7553 (defun org-insert-heading (&optional arg invisible-ok)
7554 "Insert a new heading or item with same depth at point.
7555 If point is in a plain list and ARG is nil, create a new list item.
7556 With one universal prefix argument, insert a heading even in lists.
7557 With two universal prefix arguments, insert the heading at the end
7558 of the parent subtree.
7560 If point is at the beginning of a headline, insert a sibling before
7561 the current headline. If point is not at the beginning, split the line
7562 and create a new headline with the text in the current line after point
7563 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7565 If point is at the beginning of a normal line, turn this line into
7566 a heading.
7568 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7569 This is important for non-interactive uses of the command."
7570 (interactive "P")
7571 (if (org-called-interactively-p 'any) (org-reveal))
7572 (let ((itemp (org-in-item-p))
7573 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7574 (respect-content (or org-insert-heading-respect-content
7575 (equal arg '(16))))
7576 (initial-content "")
7577 (adjust-empty-lines t))
7579 (cond
7581 ((or (= (buffer-size) 0)
7582 (and (not (save-excursion
7583 (and (ignore-errors (org-back-to-heading invisible-ok))
7584 (org-at-heading-p))))
7585 (or arg (not itemp))))
7586 ;; At beginning of buffer or so high up that only a heading
7587 ;; makes sense.
7588 (insert
7589 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7590 (if (org-in-src-block-p) ",* " "* "))
7591 (run-hooks 'org-insert-heading-hook))
7593 ((and itemp (not (equal arg '(4))))
7594 ;; Insert an item
7595 (org-insert-item))
7598 ;; Insert a heading
7599 (save-restriction
7600 (widen)
7601 (let* ((level nil)
7602 (on-heading (org-at-heading-p))
7603 (empty-line-p (if on-heading
7604 (org-previous-line-empty-p)
7605 ;; We will decide later
7606 nil))
7607 ;; Get a level string to fall back on
7608 (fix-level
7609 (save-excursion
7610 (org-back-to-heading t)
7611 (if (org-previous-line-empty-p) (setq empty-line-p t))
7612 (looking-at org-outline-regexp)
7613 (make-string (1- (length (match-string 0))) ?*)))
7614 (stars
7615 (save-excursion
7616 (condition-case nil
7617 (progn
7618 (org-back-to-heading invisible-ok)
7619 (when (and (not on-heading)
7620 (featurep 'org-inlinetask)
7621 (integerp org-inlinetask-min-level)
7622 (>= (length (match-string 0))
7623 org-inlinetask-min-level))
7624 ;; Find a heading level before the inline task
7625 (while (and (setq level (org-up-heading-safe))
7626 (>= level org-inlinetask-min-level)))
7627 (if (org-at-heading-p)
7628 (org-back-to-heading invisible-ok)
7629 (error "This should not happen")))
7630 (unless (and (save-excursion
7631 (save-match-data
7632 (org-backward-heading-same-level
7633 1 invisible-ok))
7634 (= (point) (match-beginning 0)))
7635 (not (org-previous-line-empty-p t)))
7636 (setq empty-line-p (or empty-line-p
7637 (org-previous-line-empty-p))))
7638 (match-string 0))
7639 (error (or fix-level "* ")))))
7640 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7641 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7642 pos hide-previous previous-pos)
7644 ;; If we insert after content, move there and clean up whitespace
7645 (when respect-content
7646 (org-end-of-subtree nil t)
7647 (skip-chars-backward " \r\n")
7648 (and (looking-at "[ \t]+") (replace-match ""))
7649 (unless (eobp) (forward-char 1))
7650 (when (looking-at "^\\*")
7651 (unless (bobp) (backward-char 1))
7652 (insert "\n")))
7654 ;; If we are splitting, grab the text that should be moved to the new headline
7655 (when may-split
7656 (if (org-on-heading-p)
7657 ;; This is a heading, we split intelligently (keeping tags)
7658 (let ((pos (point)))
7659 (goto-char (point-at-bol))
7660 (unless (looking-at org-complex-heading-regexp)
7661 (error "This should not happen"))
7662 (when (and (match-beginning 4)
7663 (> pos (match-beginning 4))
7664 (< pos (match-end 4)))
7665 (setq initial-content (buffer-substring pos (match-end 4)))
7666 (goto-char pos)
7667 (delete-region (point) (match-end 4))
7668 (if (looking-at "[ \t]*$")
7669 (replace-match "")
7670 (insert (make-string (length initial-content) ?\ )))
7671 (setq initial-content (org-trim initial-content)))
7672 (goto-char pos))
7673 ;; a normal line
7674 (unless (bolp)
7675 (setq initial-content (buffer-substring (point) (point-at-eol)))
7676 (delete-region (point) (point-at-eol))
7677 (setq initial-content (org-trim initial-content)))))
7679 ;; If we are at the beginning of the line, insert before it. Else after
7680 (cond
7681 ((and (bolp) (looking-at "[ \t]*$")))
7682 ((and (bolp) (not (looking-at "[ \t]*$")))
7683 (open-line 1))
7685 (goto-char (point-at-eol))
7686 (insert "\n")))
7688 ;; Insert the new heading
7689 (insert stars)
7690 (just-one-space)
7691 (insert initial-content)
7692 (when adjust-empty-lines
7693 (if (or (not blank)
7694 (and blank (not (org-previous-line-empty-p))))
7695 (org-N-empty-lines-before-current (if blank 1 0))))
7696 (run-hooks 'org-insert-heading-hook)))))))
7698 (defun org-N-empty-lines-before-current (N)
7699 "Make the number of empty lines before current exactly N.
7700 So this will delete or add empty lines."
7701 (save-excursion
7702 (goto-char (point-at-bol))
7703 (if (looking-back "\\s-+" nil 'greedy)
7704 (replace-match ""))
7705 (or (bobp) (insert "\n"))
7706 (while (> N 0)
7707 (insert "\n")
7708 (setq N (1- N)))))
7710 (defun org-get-heading (&optional no-tags no-todo)
7711 "Return the heading of the current entry, without the stars.
7712 When NO-TAGS is non-nil, don't include tags.
7713 When NO-TODO is non-nil, don't include TODO keywords."
7714 (save-excursion
7715 (org-back-to-heading t)
7716 (cond
7717 ((and no-tags no-todo)
7718 (looking-at org-complex-heading-regexp)
7719 (match-string 4))
7720 (no-tags
7721 (looking-at (concat org-outline-regexp
7722 "\\(.*?\\)"
7723 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7724 (match-string 1))
7725 (no-todo
7726 (looking-at org-todo-line-regexp)
7727 (match-string 3))
7728 (t (looking-at org-heading-regexp)
7729 (match-string 2)))))
7731 (defvar orgstruct-mode) ; defined below
7733 (defun org-heading-components ()
7734 "Return the components of the current heading.
7735 This is a list with the following elements:
7736 - the level as an integer
7737 - the reduced level, different if `org-odd-levels-only' is set.
7738 - the TODO keyword, or nil
7739 - the priority character, like ?A, or nil if no priority is given
7740 - the headline text itself, or the tags string if no headline text
7741 - the tags string, or nil."
7742 (save-excursion
7743 (org-back-to-heading t)
7744 (if (let (case-fold-search)
7745 (looking-at
7746 (if orgstruct-mode
7747 org-heading-regexp
7748 org-complex-heading-regexp)))
7749 (if orgstruct-mode
7750 (list (length (match-string 1))
7751 (org-reduced-level (length (match-string 1)))
7754 (match-string 2)
7755 nil)
7756 (list (length (match-string 1))
7757 (org-reduced-level (length (match-string 1)))
7758 (org-match-string-no-properties 2)
7759 (and (match-end 3) (aref (match-string 3) 2))
7760 (org-match-string-no-properties 4)
7761 (org-match-string-no-properties 5))))))
7763 (defun org-get-entry ()
7764 "Get the entry text, after heading, entire subtree."
7765 (save-excursion
7766 (org-back-to-heading t)
7767 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7769 (defun org-insert-heading-after-current ()
7770 "Insert a new heading with same level as current, after current subtree."
7771 (interactive)
7772 (org-back-to-heading)
7773 (org-insert-heading)
7774 (org-move-subtree-down)
7775 (end-of-line 1))
7777 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7778 "Insert heading with `org-insert-heading-respect-content' set to t."
7779 (interactive "P")
7780 (let ((org-insert-heading-respect-content t))
7781 (org-insert-heading '(4) invisible-ok)))
7783 (defun org-insert-todo-heading-respect-content (&optional force-state)
7784 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7785 (interactive "P")
7786 (let ((org-insert-heading-respect-content t))
7787 (org-insert-todo-heading force-state '(4))))
7789 (defun org-insert-todo-heading (arg &optional force-heading)
7790 "Insert a new heading with the same level and TODO state as current heading.
7791 If the heading has no TODO state, or if the state is DONE, use the first
7792 state (TODO by default). Also one prefix arg, force first state. With two
7793 prefix args, force inserting at the end of the parent subtree."
7794 (interactive "P")
7795 (when (or force-heading (not (org-insert-item 'checkbox)))
7796 (org-insert-heading (or (and (equal arg '(16)) '(16))
7797 force-heading))
7798 (save-excursion
7799 (org-back-to-heading)
7800 (outline-previous-heading)
7801 (looking-at org-todo-line-regexp))
7802 (let*
7803 ((new-mark-x
7804 (if (or arg
7805 (not (match-beginning 2))
7806 (member (match-string 2) org-done-keywords))
7807 (car org-todo-keywords-1)
7808 (match-string 2)))
7809 (new-mark
7811 (run-hook-with-args-until-success
7812 'org-todo-get-default-hook new-mark-x nil)
7813 new-mark-x)))
7814 (beginning-of-line 1)
7815 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7816 (if org-treat-insert-todo-heading-as-state-change
7817 (org-todo new-mark)
7818 (insert new-mark " "))))
7819 (when org-provide-todo-statistics
7820 (org-update-parent-todo-statistics))))
7822 (defun org-insert-subheading (arg)
7823 "Insert a new subheading and demote it.
7824 Works for outline headings and for plain lists alike."
7825 (interactive "P")
7826 (org-insert-heading arg)
7827 (cond
7828 ((org-at-heading-p) (org-do-demote))
7829 ((org-at-item-p) (org-indent-item))))
7831 (defun org-insert-todo-subheading (arg)
7832 "Insert a new subheading with TODO keyword or checkbox and demote it.
7833 Works for outline headings and for plain lists alike."
7834 (interactive "P")
7835 (org-insert-todo-heading arg)
7836 (cond
7837 ((org-at-heading-p) (org-do-demote))
7838 ((org-at-item-p) (org-indent-item))))
7840 ;;; Promotion and Demotion
7842 (defvar org-after-demote-entry-hook nil
7843 "Hook run after an entry has been demoted.
7844 The cursor will be at the beginning of the entry.
7845 When a subtree is being demoted, the hook will be called for each node.")
7847 (defvar org-after-promote-entry-hook nil
7848 "Hook run after an entry has been promoted.
7849 The cursor will be at the beginning of the entry.
7850 When a subtree is being promoted, the hook will be called for each node.")
7852 (defun org-promote-subtree ()
7853 "Promote the entire subtree.
7854 See also `org-promote'."
7855 (interactive)
7856 (save-excursion
7857 (org-with-limited-levels (org-map-tree 'org-promote)))
7858 (org-fix-position-after-promote))
7860 (defun org-demote-subtree ()
7861 "Demote the entire subtree. See `org-demote'.
7862 See also `org-promote'."
7863 (interactive)
7864 (save-excursion
7865 (org-with-limited-levels (org-map-tree 'org-demote)))
7866 (org-fix-position-after-promote))
7869 (defun org-do-promote ()
7870 "Promote the current heading higher up the tree.
7871 If the region is active in `transient-mark-mode', promote all headings
7872 in the region."
7873 (interactive)
7874 (save-excursion
7875 (if (org-region-active-p)
7876 (org-map-region 'org-promote (region-beginning) (region-end))
7877 (org-promote)))
7878 (org-fix-position-after-promote))
7880 (defun org-do-demote ()
7881 "Demote the current heading lower down the tree.
7882 If the region is active in `transient-mark-mode', demote all headings
7883 in the region."
7884 (interactive)
7885 (save-excursion
7886 (if (org-region-active-p)
7887 (org-map-region 'org-demote (region-beginning) (region-end))
7888 (org-demote)))
7889 (org-fix-position-after-promote))
7891 (defun org-fix-position-after-promote ()
7892 "Make sure that after pro/demotion cursor position is right."
7893 (let ((pos (point)))
7894 (when (save-excursion
7895 (beginning-of-line 1)
7896 (looking-at org-todo-line-regexp)
7897 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7898 (cond ((eobp) (insert " "))
7899 ((eolp) (insert " "))
7900 ((equal (char-after) ?\ ) (forward-char 1))))))
7902 (defun org-current-level ()
7903 "Return the level of the current entry, or nil if before the first headline.
7904 The level is the number of stars at the beginning of the headline."
7905 (save-excursion
7906 (org-with-limited-levels
7907 (if (ignore-errors (org-back-to-heading t))
7908 (funcall outline-level)))))
7910 (defun org-get-previous-line-level ()
7911 "Return the outline depth of the last headline before the current line.
7912 Returns 0 for the first headline in the buffer, and nil if before the
7913 first headline."
7914 (let ((current-level (org-current-level))
7915 (prev-level (when (> (line-number-at-pos) 1)
7916 (save-excursion
7917 (beginning-of-line 0)
7918 (org-current-level)))))
7919 (cond ((null current-level) nil) ; Before first headline
7920 ((null prev-level) 0) ; At first headline
7921 (prev-level))))
7923 (defun org-reduced-level (l)
7924 "Compute the effective level of a heading.
7925 This takes into account the setting of `org-odd-levels-only'."
7926 (cond
7927 ((zerop l) 0)
7928 (org-odd-levels-only (1+ (floor (/ l 2))))
7929 (t l)))
7931 (defun org-level-increment ()
7932 "Return the number of stars that will be added or removed at a
7933 time to headlines when structure editing, based on the value of
7934 `org-odd-levels-only'."
7935 (if org-odd-levels-only 2 1))
7937 (defun org-get-valid-level (level &optional change)
7938 "Rectify a level change under the influence of `org-odd-levels-only'
7939 LEVEL is a current level, CHANGE is by how much the level should be
7940 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7941 even level numbers will become the next higher odd number."
7942 (if org-odd-levels-only
7943 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7944 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7945 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7946 (max 1 (+ level (or change 0)))))
7948 (if (boundp 'define-obsolete-function-alias)
7949 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7950 (define-obsolete-function-alias 'org-get-legal-level
7951 'org-get-valid-level)
7952 (define-obsolete-function-alias 'org-get-legal-level
7953 'org-get-valid-level "23.1")))
7955 (defun org-promote ()
7956 "Promote the current heading higher up the tree.
7957 If the region is active in `transient-mark-mode', promote all headings
7958 in the region."
7959 (org-back-to-heading t)
7960 (let* ((level (save-match-data (funcall outline-level)))
7961 (after-change-functions (remove 'flyspell-after-change-function
7962 after-change-functions))
7963 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7964 (diff (abs (- level (length up-head) -1))))
7965 (cond ((and (= level 1) org-called-with-limited-levels
7966 org-allow-promoting-top-level-subtree)
7967 (replace-match "# " nil t))
7968 ((= level 1)
7969 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7970 (t (replace-match up-head nil t)))
7971 ;; Fixup tag positioning
7972 (unless (= level 1)
7973 (and org-auto-align-tags (org-set-tags nil t))
7974 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7975 (run-hooks 'org-after-promote-entry-hook)))
7977 (defun org-demote ()
7978 "Demote the current heading lower down the tree.
7979 If the region is active in `transient-mark-mode', demote all headings
7980 in the region."
7981 (org-back-to-heading t)
7982 (let* ((level (save-match-data (funcall outline-level)))
7983 (after-change-functions (remove 'flyspell-after-change-function
7984 after-change-functions))
7985 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7986 (diff (abs (- level (length down-head) -1))))
7987 (replace-match down-head nil t)
7988 ;; Fixup tag positioning
7989 (and org-auto-align-tags (org-set-tags nil t))
7990 (if org-adapt-indentation (org-fixup-indentation diff))
7991 (run-hooks 'org-after-demote-entry-hook)))
7993 (defun org-cycle-level ()
7994 "Cycle the level of an empty headline through possible states.
7995 This goes first to child, then to parent, level, then up the hierarchy.
7996 After top level, it switches back to sibling level."
7997 (interactive)
7998 (let ((org-adapt-indentation nil))
7999 (when (org-point-at-end-of-empty-headline)
8000 (setq this-command 'org-cycle-level) ; Only needed for caching
8001 (let ((cur-level (org-current-level))
8002 (prev-level (org-get-previous-line-level)))
8003 (cond
8004 ;; If first headline in file, promote to top-level.
8005 ((= prev-level 0)
8006 (loop repeat (/ (- cur-level 1) (org-level-increment))
8007 do (org-do-promote)))
8008 ;; If same level as prev, demote one.
8009 ((= prev-level cur-level)
8010 (org-do-demote))
8011 ;; If parent is top-level, promote to top level if not already.
8012 ((= prev-level 1)
8013 (loop repeat (/ (- cur-level 1) (org-level-increment))
8014 do (org-do-promote)))
8015 ;; If top-level, return to prev-level.
8016 ((= cur-level 1)
8017 (loop repeat (/ (- prev-level 1) (org-level-increment))
8018 do (org-do-demote)))
8019 ;; If less than prev-level, promote one.
8020 ((< cur-level prev-level)
8021 (org-do-promote))
8022 ;; If deeper than prev-level, promote until higher than
8023 ;; prev-level.
8024 ((> cur-level prev-level)
8025 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8026 do (org-do-promote))))
8027 t))))
8029 (defun org-map-tree (fun)
8030 "Call FUN for every heading underneath the current one."
8031 (org-back-to-heading)
8032 (let ((level (funcall outline-level)))
8033 (save-excursion
8034 (funcall fun)
8035 (while (and (progn
8036 (outline-next-heading)
8037 (> (funcall outline-level) level))
8038 (not (eobp)))
8039 (funcall fun)))))
8041 (defun org-map-region (fun beg end)
8042 "Call FUN for every heading between BEG and END."
8043 (let ((org-ignore-region t))
8044 (save-excursion
8045 (setq end (copy-marker end))
8046 (goto-char beg)
8047 (if (and (re-search-forward org-outline-regexp-bol nil t)
8048 (< (point) end))
8049 (funcall fun))
8050 (while (and (progn
8051 (outline-next-heading)
8052 (< (point) end))
8053 (not (eobp)))
8054 (funcall fun)))))
8056 (defvar org-property-end-re) ; silence byte-compiler
8057 (defun org-fixup-indentation (diff)
8058 "Change the indentation in the current entry by DIFF.
8059 However, if any line in the current entry has no indentation, or if it
8060 would end up with no indentation after the change, nothing at all is done."
8061 (save-excursion
8062 (let ((end (save-excursion (outline-next-heading)
8063 (point-marker)))
8064 (prohibit (if (> diff 0)
8065 "^\\S-"
8066 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8067 col)
8068 (unless (save-excursion (end-of-line 1)
8069 (re-search-forward prohibit end t))
8070 (while (and (< (point) end)
8071 (re-search-forward "^[ \t]+" end t))
8072 (goto-char (match-end 0))
8073 (setq col (current-column))
8074 (if (< diff 0) (replace-match ""))
8075 (org-indent-to-column (+ diff col))))
8076 (move-marker end nil))))
8078 (defun org-convert-to-odd-levels ()
8079 "Convert an org-mode file with all levels allowed to one with odd levels.
8080 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8081 level 5 etc."
8082 (interactive)
8083 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8084 (let ((outline-level 'org-outline-level)
8085 (org-odd-levels-only nil) n)
8086 (save-excursion
8087 (goto-char (point-min))
8088 (while (re-search-forward "^\\*\\*+ " nil t)
8089 (setq n (- (length (match-string 0)) 2))
8090 (while (>= (setq n (1- n)) 0)
8091 (org-demote))
8092 (end-of-line 1))))))
8094 (defun org-convert-to-oddeven-levels ()
8095 "Convert an org-mode file with only odd levels to one with odd/even levels.
8096 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8097 file contains a section with an even level, conversion would
8098 destroy the structure of the file. An error is signaled in this
8099 case."
8100 (interactive)
8101 (goto-char (point-min))
8102 ;; First check if there are no even levels
8103 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8104 (org-show-context t)
8105 (error "Not all levels are odd in this file. Conversion not possible"))
8106 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8107 (let ((outline-regexp org-outline-regexp)
8108 (outline-level 'org-outline-level)
8109 (org-odd-levels-only nil) n)
8110 (save-excursion
8111 (goto-char (point-min))
8112 (while (re-search-forward "^\\*\\*+ " nil t)
8113 (setq n (/ (1- (length (match-string 0))) 2))
8114 (while (>= (setq n (1- n)) 0)
8115 (org-promote))
8116 (end-of-line 1))))))
8118 (defun org-tr-level (n)
8119 "Make N odd if required."
8120 (if org-odd-levels-only (1+ (/ n 2)) n))
8122 ;;; Vertical tree motion, cutting and pasting of subtrees
8124 (defun org-move-subtree-up (&optional arg)
8125 "Move the current subtree up past ARG headlines of the same level."
8126 (interactive "p")
8127 (org-move-subtree-down (- (prefix-numeric-value arg))))
8129 (defun org-move-subtree-down (&optional arg)
8130 "Move the current subtree down past ARG headlines of the same level."
8131 (interactive "p")
8132 (setq arg (prefix-numeric-value arg))
8133 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8134 'org-get-last-sibling))
8135 (ins-point (make-marker))
8136 (cnt (abs arg))
8137 (col (current-column))
8138 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8139 ;; Select the tree
8140 (org-back-to-heading)
8141 (setq beg0 (point))
8142 (save-excursion
8143 (setq ne-beg (org-back-over-empty-lines))
8144 (setq beg (point)))
8145 (save-match-data
8146 (save-excursion (outline-end-of-heading)
8147 (setq folded (outline-invisible-p)))
8148 (outline-end-of-subtree))
8149 (outline-next-heading)
8150 (setq ne-end (org-back-over-empty-lines))
8151 (setq end (point))
8152 (goto-char beg0)
8153 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8154 ;; include less whitespace
8155 (save-excursion
8156 (goto-char beg)
8157 (forward-line (- ne-beg ne-end))
8158 (setq beg (point))))
8159 ;; Find insertion point, with error handling
8160 (while (> cnt 0)
8161 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8162 (progn (goto-char beg0)
8163 (user-error "Cannot move past superior level or buffer limit")))
8164 (setq cnt (1- cnt)))
8165 (if (> arg 0)
8166 ;; Moving forward - still need to move over subtree
8167 (progn (org-end-of-subtree t t)
8168 (save-excursion
8169 (org-back-over-empty-lines)
8170 (or (bolp) (newline)))))
8171 (setq ne-ins (org-back-over-empty-lines))
8172 (move-marker ins-point (point))
8173 (setq txt (buffer-substring beg end))
8174 (org-save-markers-in-region beg end)
8175 (delete-region beg end)
8176 (org-remove-empty-overlays-at beg)
8177 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8178 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8179 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8180 (let ((bbb (point)))
8181 (insert-before-markers txt)
8182 (org-reinstall-markers-in-region bbb)
8183 (move-marker ins-point bbb))
8184 (or (bolp) (insert "\n"))
8185 (setq ins-end (point))
8186 (goto-char ins-point)
8187 (org-skip-whitespace)
8188 (when (and (< arg 0)
8189 (org-first-sibling-p)
8190 (> ne-ins ne-beg))
8191 ;; Move whitespace back to beginning
8192 (save-excursion
8193 (goto-char ins-end)
8194 (let ((kill-whole-line t))
8195 (kill-line (- ne-ins ne-beg)) (point)))
8196 (insert (make-string (- ne-ins ne-beg) ?\n)))
8197 (move-marker ins-point nil)
8198 (if folded
8199 (hide-subtree)
8200 (org-show-entry)
8201 (show-children)
8202 (org-cycle-hide-drawers 'children))
8203 (org-clean-visibility-after-subtree-move)
8204 ;; move back to the initial column we were at
8205 (move-to-column col)))
8207 (defvar org-subtree-clip ""
8208 "Clipboard for cut and paste of subtrees.
8209 This is actually only a copy of the kill, because we use the normal kill
8210 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8212 (defvar org-subtree-clip-folded nil
8213 "Was the last copied subtree folded?
8214 This is used to fold the tree back after pasting.")
8216 (defun org-cut-subtree (&optional n)
8217 "Cut the current subtree into the clipboard.
8218 With prefix arg N, cut this many sequential subtrees.
8219 This is a short-hand for marking the subtree and then cutting it."
8220 (interactive "p")
8221 (org-copy-subtree n 'cut))
8223 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8224 "Copy the current subtree it in the clipboard.
8225 With prefix arg N, copy this many sequential subtrees.
8226 This is a short-hand for marking the subtree and then copying it.
8227 If CUT is non-nil, actually cut the subtree.
8228 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8229 of some markers in the region, even if CUT is non-nil. This is
8230 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8231 (interactive "p")
8232 (let (beg end folded (beg0 (point)))
8233 (if (org-called-interactively-p 'any)
8234 (org-back-to-heading nil) ; take what looks like a subtree
8235 (org-back-to-heading t)) ; take what is really there
8236 (setq beg (point))
8237 (skip-chars-forward " \t\r\n")
8238 (save-match-data
8239 (if nosubtrees
8240 (outline-next-heading)
8241 (save-excursion (outline-end-of-heading)
8242 (setq folded (outline-invisible-p)))
8243 (condition-case nil
8244 (org-forward-heading-same-level (1- n) t)
8245 (error nil))
8246 (org-end-of-subtree t t)))
8247 (setq end (point))
8248 (goto-char beg0)
8249 (when (> end beg)
8250 (setq org-subtree-clip-folded folded)
8251 (when (or cut force-store-markers)
8252 (org-save-markers-in-region beg end))
8253 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8254 (setq org-subtree-clip (current-kill 0))
8255 (message "%s: Subtree(s) with %d characters"
8256 (if cut "Cut" "Copied")
8257 (length org-subtree-clip)))))
8259 (defun org-paste-subtree (&optional level tree for-yank)
8260 "Paste the clipboard as a subtree, with modification of headline level.
8261 The entire subtree is promoted or demoted in order to match a new headline
8262 level.
8264 If the cursor is at the beginning of a headline, the same level as
8265 that headline is used to paste the tree.
8267 If not, the new level is derived from the *visible* headings
8268 before and after the insertion point, and taken to be the inferior headline
8269 level of the two. So if the previous visible heading is level 3 and the
8270 next is level 4 (or vice versa), level 4 will be used for insertion.
8271 This makes sure that the subtree remains an independent subtree and does
8272 not swallow low level entries.
8274 You can also force a different level, either by using a numeric prefix
8275 argument, or by inserting the heading marker by hand. For example, if the
8276 cursor is after \"*****\", then the tree will be shifted to level 5.
8278 If optional TREE is given, use this text instead of the kill ring.
8280 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8281 move back over whitespace before inserting, and move point to the end of
8282 the inserted text when done."
8283 (interactive "P")
8284 (setq tree (or tree (and kill-ring (current-kill 0))))
8285 (unless (org-kill-is-subtree-p tree)
8286 (user-error "%s"
8287 (substitute-command-keys
8288 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8289 (org-with-limited-levels
8290 (let* ((visp (not (outline-invisible-p)))
8291 (txt tree)
8292 (^re_ "\\(\\*+\\)[ \t]*")
8293 (old-level (if (string-match org-outline-regexp-bol txt)
8294 (- (match-end 0) (match-beginning 0) 1)
8295 -1))
8296 (force-level (cond (level (prefix-numeric-value level))
8297 ((and (looking-at "[ \t]*$")
8298 (string-match
8299 "^\\*+$" (buffer-substring
8300 (point-at-bol) (point))))
8301 (- (match-end 1) (match-beginning 1)))
8302 ((and (bolp)
8303 (looking-at org-outline-regexp))
8304 (- (match-end 0) (point) 1))))
8305 (previous-level (save-excursion
8306 (condition-case nil
8307 (progn
8308 (outline-previous-visible-heading 1)
8309 (if (looking-at ^re_)
8310 (- (match-end 0) (match-beginning 0) 1)
8312 (error 1))))
8313 (next-level (save-excursion
8314 (condition-case nil
8315 (progn
8316 (or (looking-at org-outline-regexp)
8317 (outline-next-visible-heading 1))
8318 (if (looking-at ^re_)
8319 (- (match-end 0) (match-beginning 0) 1)
8321 (error 1))))
8322 (new-level (or force-level (max previous-level next-level)))
8323 (shift (if (or (= old-level -1)
8324 (= new-level -1)
8325 (= old-level new-level))
8327 (- new-level old-level)))
8328 (delta (if (> shift 0) -1 1))
8329 (func (if (> shift 0) 'org-demote 'org-promote))
8330 (org-odd-levels-only nil)
8331 beg end newend)
8332 ;; Remove the forced level indicator
8333 (if force-level
8334 (delete-region (point-at-bol) (point)))
8335 ;; Paste
8336 (beginning-of-line (if (bolp) 1 2))
8337 (setq beg (point))
8338 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8339 (insert-before-markers txt)
8340 (unless (string-match "\n\\'" txt) (insert "\n"))
8341 (setq newend (point))
8342 (org-reinstall-markers-in-region beg)
8343 (setq end (point))
8344 (goto-char beg)
8345 (skip-chars-forward " \t\n\r")
8346 (setq beg (point))
8347 (if (and (outline-invisible-p) visp)
8348 (save-excursion (outline-show-heading)))
8349 ;; Shift if necessary
8350 (unless (= shift 0)
8351 (save-restriction
8352 (narrow-to-region beg end)
8353 (while (not (= shift 0))
8354 (org-map-region func (point-min) (point-max))
8355 (setq shift (+ delta shift)))
8356 (goto-char (point-min))
8357 (setq newend (point-max))))
8358 (when (or (org-called-interactively-p 'interactive) for-yank)
8359 (message "Clipboard pasted as level %d subtree" new-level))
8360 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8361 kill-ring
8362 (eq org-subtree-clip (current-kill 0))
8363 org-subtree-clip-folded)
8364 ;; The tree was folded before it was killed/copied
8365 (hide-subtree))
8366 (and for-yank (goto-char newend)))))
8368 (defun org-kill-is-subtree-p (&optional txt)
8369 "Check if the current kill is an outline subtree, or a set of trees.
8370 Returns nil if kill does not start with a headline, or if the first
8371 headline level is not the largest headline level in the tree.
8372 So this will actually accept several entries of equal levels as well,
8373 which is OK for `org-paste-subtree'.
8374 If optional TXT is given, check this string instead of the current kill."
8375 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8376 (re (org-get-limited-outline-regexp))
8377 (^re (concat "^" re))
8378 (start-level (and kill
8379 (string-match
8380 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8381 kill)
8382 (- (match-end 2) (match-beginning 2) 1)))
8383 (start (1+ (or (match-beginning 2) -1))))
8384 (if (not start-level)
8385 (progn
8386 nil) ;; does not even start with a heading
8387 (catch 'exit
8388 (while (setq start (string-match ^re kill (1+ start)))
8389 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8390 (throw 'exit nil)))
8391 t))))
8393 (defvar org-markers-to-move nil
8394 "Markers that should be moved with a cut-and-paste operation.
8395 Those markers are stored together with their positions relative to
8396 the start of the region.")
8398 (defun org-save-markers-in-region (beg end)
8399 "Check markers in region.
8400 If these markers are between BEG and END, record their position relative
8401 to BEG, so that after moving the block of text, we can put the markers back
8402 into place.
8403 This function gets called just before an entry or tree gets cut from the
8404 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8405 called immediately, to move the markers with the entries."
8406 (setq org-markers-to-move nil)
8407 (when (featurep 'org-clock)
8408 (org-clock-save-markers-for-cut-and-paste beg end))
8409 (when (featurep 'org-agenda)
8410 (org-agenda-save-markers-for-cut-and-paste beg end)))
8412 (defun org-check-and-save-marker (marker beg end)
8413 "Check if MARKER is between BEG and END.
8414 If yes, remember the marker and the distance to BEG."
8415 (when (and (marker-buffer marker)
8416 (equal (marker-buffer marker) (current-buffer)))
8417 (if (and (>= marker beg) (< marker end))
8418 (push (cons marker (- marker beg)) org-markers-to-move))))
8420 (defun org-reinstall-markers-in-region (beg)
8421 "Move all remembered markers to their position relative to BEG."
8422 (mapc (lambda (x)
8423 (move-marker (car x) (+ beg (cdr x))))
8424 org-markers-to-move)
8425 (setq org-markers-to-move nil))
8427 (defun org-narrow-to-subtree ()
8428 "Narrow buffer to the current subtree."
8429 (interactive)
8430 (save-excursion
8431 (save-match-data
8432 (org-with-limited-levels
8433 (narrow-to-region
8434 (progn (org-back-to-heading t) (point))
8435 (progn (org-end-of-subtree t t)
8436 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8437 (point)))))))
8439 (defun org-narrow-to-block ()
8440 "Narrow buffer to the current block."
8441 (interactive)
8442 (let* ((case-fold-search t)
8443 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8444 "^[ \t]*#\\+end_.*")))
8445 (if blockp
8446 (narrow-to-region (car blockp) (cdr blockp))
8447 (user-error "Not in a block"))))
8449 (eval-when-compile
8450 (defvar org-property-drawer-re))
8452 (defvar org-property-start-re) ;; defined below
8453 (defun org-clone-subtree-with-time-shift (n &optional shift)
8454 "Clone the task (subtree) at point N times.
8455 The clones will be inserted as siblings.
8457 In interactive use, the user will be prompted for the number of
8458 clones to be produced. If the entry has a timestamp, the user
8459 will also be prompted for a time shift, which may be a repeater
8460 as used in time stamps, for example `+3d'. To disable this,
8461 you can call the function with a universal prefix argument.
8463 When a valid repeater is given and the entry contains any time
8464 stamps, the clones will become a sequence in time, with time
8465 stamps in the subtree shifted for each clone produced. If SHIFT
8466 is nil or the empty string, time stamps will be left alone. The
8467 ID property of the original subtree is removed.
8469 If the original subtree did contain time stamps with a repeater,
8470 the following will happen:
8471 - the repeater will be removed in each clone
8472 - an additional clone will be produced, with the current, unshifted
8473 date(s) in the entry.
8474 - the original entry will be placed *after* all the clones, with
8475 repeater intact.
8476 - the start days in the repeater in the original entry will be shifted
8477 to past the last clone.
8478 In this way you can spell out a number of instances of a repeating task,
8479 and still retain the repeater to cover future instances of the task."
8480 (interactive "nNumber of clones to produce: ")
8481 (let ((shift
8482 (or shift
8483 (if (and (not (equal current-prefix-arg '(4)))
8484 (save-excursion
8485 (re-search-forward org-ts-regexp-both
8486 (save-excursion
8487 (org-end-of-subtree t)
8488 (point)) t)))
8489 (read-from-minibuffer
8490 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8491 ""))) ;; No time shift
8492 (n-no-remove -1)
8493 (drawer-re org-drawer-regexp)
8494 beg end template task idprop
8495 shift-n shift-what doshift nmin nmax)
8496 (if (not (and (integerp n) (> n 0)))
8497 (error "Invalid number of replications %s" n))
8498 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8499 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8500 shift)))
8501 (error "Invalid shift specification %s" shift))
8502 (when doshift
8503 (setq shift-n (string-to-number (match-string 1 shift))
8504 shift-what (cdr (assoc (match-string 2 shift)
8505 '(("d" . day) ("w" . week)
8506 ("m" . month) ("y" . year))))))
8507 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8508 (setq nmin 1 nmax n)
8509 (org-back-to-heading t)
8510 (setq beg (point))
8511 (setq idprop (org-entry-get nil "ID"))
8512 (org-end-of-subtree t t)
8513 (or (bolp) (insert "\n"))
8514 (setq end (point))
8515 (setq template (buffer-substring beg end))
8516 (when (and doshift
8517 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8518 (delete-region beg end)
8519 (setq end beg)
8520 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8521 (goto-char end)
8522 (loop for n from nmin to nmax do
8523 ;; prepare clone
8524 (with-temp-buffer
8525 (insert template)
8526 (org-mode)
8527 (goto-char (point-min))
8528 (org-show-subtree)
8529 (and idprop (if org-clone-delete-id
8530 (org-entry-delete nil "ID")
8531 (org-id-get-create t)))
8532 (unless (= n 0)
8533 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8534 (kill-whole-line))
8535 (goto-char (point-min))
8536 (while (re-search-forward drawer-re nil t)
8537 (mapc (lambda (d)
8538 (org-remove-empty-drawer-at d (point))) org-drawers)))
8539 (goto-char (point-min))
8540 (when doshift
8541 (while (re-search-forward org-ts-regexp-both nil t)
8542 (org-timestamp-change (* n shift-n) shift-what))
8543 (unless (= n n-no-remove)
8544 (goto-char (point-min))
8545 (while (re-search-forward org-ts-regexp nil t)
8546 (save-excursion
8547 (goto-char (match-beginning 0))
8548 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8549 (delete-region (match-beginning 1) (match-end 1)))))))
8550 (setq task (buffer-string)))
8551 (insert task))
8552 (goto-char beg)))
8554 ;;; Outline Sorting
8556 (defun org-sort (with-case)
8557 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8558 Optional argument WITH-CASE means sort case-sensitively."
8559 (interactive "P")
8560 (cond
8561 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8562 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8564 (org-call-with-arg 'org-sort-entries with-case))))
8566 (defun org-sort-remove-invisible (s)
8567 "Remove invisible links from string S."
8568 (remove-text-properties 0 (length s) org-rm-props s)
8569 (while (string-match org-bracket-link-regexp s)
8570 (setq s (replace-match (if (match-end 2)
8571 (match-string 3 s)
8572 (match-string 1 s)) t t s)))
8573 (let ((st (format " %s " s)))
8574 (while (string-match org-emph-re st)
8575 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8576 (setq s (substring st 1 -1)))
8579 (defvar org-priority-regexp) ; defined later in the file
8581 (defvar org-after-sorting-entries-or-items-hook nil
8582 "Hook that is run after a bunch of entries or items have been sorted.
8583 When children are sorted, the cursor is in the parent line when this
8584 hook gets called. When a region or a plain list is sorted, the cursor
8585 will be in the first entry of the sorted region/list.")
8587 (defun org-sort-entries
8588 (&optional with-case sorting-type getkey-func compare-func property)
8589 "Sort entries on a certain level of an outline tree.
8590 If there is an active region, the entries in the region are sorted.
8591 Else, if the cursor is before the first entry, sort the top-level items.
8592 Else, the children of the entry at point are sorted.
8594 Sorting can be alphabetically, numerically, by date/time as given by
8595 a time stamp, by a property, by priority order, or by a custom function.
8597 The command prompts for the sorting type unless it has been given to the
8598 function through the SORTING-TYPE argument, which needs to be a character,
8599 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8600 precise meaning of each character:
8602 n Numerically, by converting the beginning of the entry/item to a number.
8603 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8604 o By order of TODO keywords.
8605 t By date/time, either the first active time stamp in the entry, or, if
8606 none exist, by the first inactive one.
8607 s By the scheduled date/time.
8608 d By deadline date/time.
8609 c By creation time, which is assumed to be the first inactive time stamp
8610 at the beginning of a line.
8611 p By priority according to the cookie.
8612 r By the value of a property.
8614 Capital letters will reverse the sort order.
8616 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8617 called with point at the beginning of the record. It must return either
8618 a string or a number that should serve as the sorting key for that record.
8620 Comparing entries ignores case by default. However, with an optional argument
8621 WITH-CASE, the sorting considers case as well.
8623 Sorting is done against the visible part of the headlines, it ignores hidden
8624 links."
8625 (interactive "P")
8626 (let ((case-func (if with-case 'identity 'downcase))
8627 (cmstr
8628 ;; The clock marker is lost when using `sort-subr', let's
8629 ;; store the clocking string.
8630 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8631 (save-excursion
8632 (goto-char org-clock-marker)
8633 (looking-back "^.*") (match-string-no-properties 0))))
8634 start beg end stars re re2
8635 txt what tmp)
8636 ;; Find beginning and end of region to sort
8637 (cond
8638 ((org-region-active-p)
8639 ;; we will sort the region
8640 (setq end (region-end)
8641 what "region")
8642 (goto-char (region-beginning))
8643 (if (not (org-at-heading-p)) (outline-next-heading))
8644 (setq start (point)))
8645 ((or (org-at-heading-p)
8646 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8647 ;; we will sort the children of the current headline
8648 (org-back-to-heading)
8649 (setq start (point)
8650 end (progn (org-end-of-subtree t t)
8651 (or (bolp) (insert "\n"))
8652 (org-back-over-empty-lines)
8653 (point))
8654 what "children")
8655 (goto-char start)
8656 (show-subtree)
8657 (outline-next-heading))
8659 ;; we will sort the top-level entries in this file
8660 (goto-char (point-min))
8661 (or (org-at-heading-p) (outline-next-heading))
8662 (setq start (point))
8663 (goto-char (point-max))
8664 (beginning-of-line 1)
8665 (when (looking-at ".*?\\S-")
8666 ;; File ends in a non-white line
8667 (end-of-line 1)
8668 (insert "\n"))
8669 (setq end (point-max))
8670 (setq what "top-level")
8671 (goto-char start)
8672 (show-all)))
8674 (setq beg (point))
8675 (if (>= beg end) (user-error "Nothing to sort"))
8677 (looking-at "\\(\\*+\\)")
8678 (setq stars (match-string 1)
8679 re (concat "^" (regexp-quote stars) " +")
8680 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8681 txt (buffer-substring beg end))
8682 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8683 (if (and (not (equal stars "*")) (string-match re2 txt))
8684 (user-error "Region to sort contains a level above the first entry"))
8686 (unless sorting-type
8687 (message
8688 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8689 [t]ime [s]cheduled [d]eadline [c]reated
8690 A/N/P/R/O/F/T/S/D/C means reversed:"
8691 what)
8692 (setq sorting-type (read-char-exclusive))
8694 (unless getkey-func
8695 (and (= (downcase sorting-type) ?f)
8696 (setq getkey-func
8697 (org-icompleting-read "Sort using function: "
8698 obarray 'fboundp t nil nil))
8699 (setq getkey-func (intern getkey-func))))
8701 (and (= (downcase sorting-type) ?r)
8702 (not property)
8703 (setq property
8704 (org-icompleting-read "Property: "
8705 (mapcar 'list (org-buffer-property-keys t))
8706 nil t))))
8708 (message "Sorting entries...")
8710 (save-restriction
8711 (narrow-to-region start end)
8712 (let ((dcst (downcase sorting-type))
8713 (case-fold-search nil)
8714 (now (current-time)))
8715 (sort-subr
8716 (/= dcst sorting-type)
8717 ;; This function moves to the beginning character of the "record" to
8718 ;; be sorted.
8719 (lambda nil
8720 (if (re-search-forward re nil t)
8721 (goto-char (match-beginning 0))
8722 (goto-char (point-max))))
8723 ;; This function moves to the last character of the "record" being
8724 ;; sorted.
8725 (lambda nil
8726 (save-match-data
8727 (condition-case nil
8728 (outline-forward-same-level 1)
8729 (error
8730 (goto-char (point-max))))))
8731 ;; This function returns the value that gets sorted against.
8732 (lambda nil
8733 (cond
8734 ((= dcst ?n)
8735 (if (looking-at org-complex-heading-regexp)
8736 (string-to-number (org-sort-remove-invisible (match-string 4)))
8737 nil))
8738 ((= dcst ?a)
8739 (if (looking-at org-complex-heading-regexp)
8740 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8741 nil))
8742 ((= dcst ?t)
8743 (let ((end (save-excursion (outline-next-heading) (point))))
8744 (if (or (re-search-forward org-ts-regexp end t)
8745 (re-search-forward org-ts-regexp-both end t))
8746 (org-time-string-to-seconds (match-string 0))
8747 (org-float-time now))))
8748 ((= dcst ?c)
8749 (let ((end (save-excursion (outline-next-heading) (point))))
8750 (if (re-search-forward
8751 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8752 end t)
8753 (org-time-string-to-seconds (match-string 0))
8754 (org-float-time now))))
8755 ((= dcst ?s)
8756 (let ((end (save-excursion (outline-next-heading) (point))))
8757 (if (re-search-forward org-scheduled-time-regexp end t)
8758 (org-time-string-to-seconds (match-string 1))
8759 (org-float-time now))))
8760 ((= dcst ?d)
8761 (let ((end (save-excursion (outline-next-heading) (point))))
8762 (if (re-search-forward org-deadline-time-regexp end t)
8763 (org-time-string-to-seconds (match-string 1))
8764 (org-float-time now))))
8765 ((= dcst ?p)
8766 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8767 (string-to-char (match-string 2))
8768 org-default-priority))
8769 ((= dcst ?r)
8770 (or (org-entry-get nil property) ""))
8771 ((= dcst ?o)
8772 (if (looking-at org-complex-heading-regexp)
8773 (- 9999 (length (member (match-string 2)
8774 org-todo-keywords-1)))))
8775 ((= dcst ?f)
8776 (if getkey-func
8777 (progn
8778 (setq tmp (funcall getkey-func))
8779 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8780 tmp)
8781 (error "Invalid key function `%s'" getkey-func)))
8782 (t (error "Invalid sorting type `%c'" sorting-type))))
8784 (cond
8785 ((= dcst ?a) 'string<)
8786 ((= dcst ?f) compare-func)
8787 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8788 (run-hooks 'org-after-sorting-entries-or-items-hook)
8789 ;; Reset the clock marker if needed
8790 (when cmstr
8791 (save-excursion
8792 (goto-char start)
8793 (search-forward cmstr nil t)
8794 (move-marker org-clock-marker (point))))
8795 (message "Sorting entries...done")))
8797 (defun org-do-sort (table what &optional with-case sorting-type)
8798 "Sort TABLE of WHAT according to SORTING-TYPE.
8799 The user will be prompted for the SORTING-TYPE if the call to this
8800 function does not specify it. WHAT is only for the prompt, to indicate
8801 what is being sorted. The sorting key will be extracted from
8802 the car of the elements of the table.
8803 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8804 (unless sorting-type
8805 (message
8806 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8807 what)
8808 (setq sorting-type (read-char-exclusive)))
8809 (let ((dcst (downcase sorting-type))
8810 extractfun comparefun)
8811 ;; Define the appropriate functions
8812 (cond
8813 ((= dcst ?n)
8814 (setq extractfun 'string-to-number
8815 comparefun (if (= dcst sorting-type) '< '>)))
8816 ((= dcst ?a)
8817 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8818 (lambda(x) (downcase (org-sort-remove-invisible x))))
8819 comparefun (if (= dcst sorting-type)
8820 'string<
8821 (lambda (a b) (and (not (string< a b))
8822 (not (string= a b)))))))
8823 ((= dcst ?t)
8824 (setq extractfun
8825 (lambda (x)
8826 (if (or (string-match org-ts-regexp x)
8827 (string-match org-ts-regexp-both x))
8828 (org-float-time
8829 (org-time-string-to-time (match-string 0 x)))
8831 comparefun (if (= dcst sorting-type) '< '>)))
8832 (t (error "Invalid sorting type `%c'" sorting-type)))
8834 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8835 table)
8836 (lambda (a b) (funcall comparefun (car a) (car b))))))
8839 ;;; The orgstruct minor mode
8841 ;; Define a minor mode which can be used in other modes in order to
8842 ;; integrate the org-mode structure editing commands.
8844 ;; This is really a hack, because the org-mode structure commands use
8845 ;; keys which normally belong to the major mode. Here is how it
8846 ;; works: The minor mode defines all the keys necessary to operate the
8847 ;; structure commands, but wraps the commands into a function which
8848 ;; tests if the cursor is currently at a headline or a plain list
8849 ;; item. If that is the case, the structure command is used,
8850 ;; temporarily setting many Org-mode variables like regular
8851 ;; expressions for filling etc. However, when any of those keys is
8852 ;; used at a different location, function uses `key-binding' to look
8853 ;; up if the key has an associated command in another currently active
8854 ;; keymap (minor modes, major mode, global), and executes that
8855 ;; command. There might be problems if any of the keys is otherwise
8856 ;; used as a prefix key.
8858 (defcustom orgstruct-heading-prefix-regexp ""
8859 "Regexp that matches the custom prefix of Org headlines in
8860 orgstruct(++)-mode."
8861 :group 'org
8862 :version "24.4"
8863 :package-version '(Org . "8.3")
8864 :type 'regexp)
8865 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8867 (defcustom orgstruct-setup-hook nil
8868 "Hook run after orgstruct-mode-map is filled."
8869 :group 'org
8870 :version "24.4"
8871 :package-version '(Org . "8.0")
8872 :type 'hook)
8874 (defvar orgstruct-initialized nil)
8876 (defvar org-local-vars nil
8877 "List of local variables, for use by `orgstruct-mode'.")
8879 ;;;###autoload
8880 (define-minor-mode orgstruct-mode
8881 "Toggle the minor mode `orgstruct-mode'.
8882 This mode is for using Org-mode structure commands in other
8883 modes. The following keys behave as if Org-mode were active, if
8884 the cursor is on a headline, or on a plain list item (both as
8885 defined by Org-mode)."
8886 nil " OrgStruct" (make-sparse-keymap)
8887 (funcall (if orgstruct-mode
8888 'add-to-invisibility-spec
8889 'remove-from-invisibility-spec)
8890 '(outline . t))
8891 (when orgstruct-mode
8892 (org-load-modules-maybe)
8893 (unless orgstruct-initialized
8894 (orgstruct-setup)
8895 (setq orgstruct-initialized t))))
8897 ;;;###autoload
8898 (defun turn-on-orgstruct ()
8899 "Unconditionally turn on `orgstruct-mode'."
8900 (orgstruct-mode 1))
8902 (defvar org-fb-vars nil)
8903 (make-variable-buffer-local 'org-fb-vars)
8904 (defun orgstruct++-mode (&optional arg)
8905 "Toggle `orgstruct-mode', the enhanced version of it.
8906 In addition to setting orgstruct-mode, this also exports all
8907 indentation and autofilling variables from org-mode into the
8908 buffer. It will also recognize item context in multiline items."
8909 (interactive "P")
8910 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8911 (if (< arg 1)
8912 (progn (orgstruct-mode -1)
8913 (mapc (lambda(v)
8914 (org-set-local (car v)
8915 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8916 org-fb-vars))
8917 (orgstruct-mode 1)
8918 (setq org-fb-vars nil)
8919 (unless org-local-vars
8920 (setq org-local-vars (org-get-local-variables)))
8921 (let (var val)
8922 (mapc
8923 (lambda (x)
8924 (when (string-match
8925 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8926 (symbol-name (car x)))
8927 (setq var (car x) val (nth 1 x))
8928 (push (list var `(quote ,(eval var))) org-fb-vars)
8929 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8930 org-local-vars)
8931 (org-set-local 'orgstruct-is-++ t))))
8933 (defvar orgstruct-is-++ nil
8934 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8935 (make-variable-buffer-local 'orgstruct-is-++)
8937 ;;;###autoload
8938 (defun turn-on-orgstruct++ ()
8939 "Unconditionally turn on `orgstruct++-mode'."
8940 (orgstruct++-mode 1))
8942 (defun orgstruct-error ()
8943 "Error when there is no default binding for a structure key."
8944 (interactive)
8945 (funcall (if (fboundp 'user-error)
8946 'user-error
8947 'error)
8948 "This key has no function outside structure elements"))
8950 (defun orgstruct-setup ()
8951 "Setup orgstruct keymap."
8952 (dolist (cell '((org-demote . t)
8953 (org-metaleft . t)
8954 (org-metaright . t)
8955 (org-promote . t)
8956 (org-shiftmetaleft . t)
8957 (org-shiftmetaright . t)
8958 org-backward-element
8959 org-backward-heading-same-level
8960 org-ctrl-c-ret
8961 org-ctrl-c-minus
8962 org-ctrl-c-star
8963 org-cycle
8964 org-forward-heading-same-level
8965 org-insert-heading
8966 org-insert-heading-respect-content
8967 org-kill-note-or-show-branches
8968 org-mark-subtree
8969 org-meta-return
8970 org-metadown
8971 org-metaup
8972 org-narrow-to-subtree
8973 org-promote-subtree
8974 org-reveal
8975 org-shiftdown
8976 org-shiftleft
8977 org-shiftmetadown
8978 org-shiftmetaup
8979 org-shiftright
8980 org-shifttab
8981 org-shifttab
8982 org-shiftup
8983 org-show-subtree
8984 org-sort
8985 org-up-element
8986 outline-demote
8987 outline-next-visible-heading
8988 outline-previous-visible-heading
8989 outline-promote
8990 outline-up-heading
8991 show-children))
8992 (let ((f (or (car-safe cell) cell))
8993 (disable-when-heading-prefix (cdr-safe cell)))
8994 (when (fboundp f)
8995 (let ((new-bindings))
8996 (dolist (binding (nconc (where-is-internal f org-mode-map)
8997 (where-is-internal f outline-mode-map)))
8998 (push binding new-bindings)
8999 ;; TODO use local-function-key-map
9000 (dolist (rep '(("<tab>" . "TAB")
9001 ("<return>" . "RET")
9002 ("<escape>" . "ESC")
9003 ("<delete>" . "DEL")))
9004 (setq binding (read-kbd-macro
9005 (let ((case-fold-search))
9006 (replace-regexp-in-string
9007 (regexp-quote (cdr rep))
9008 (car rep)
9009 (key-description binding)))))
9010 (pushnew binding new-bindings :test 'equal)))
9011 (dolist (binding new-bindings)
9012 (let ((key (lookup-key orgstruct-mode-map binding)))
9013 (when (or (not key) (numberp key))
9014 (condition-case nil
9015 (org-defkey orgstruct-mode-map
9016 binding
9017 (orgstruct-make-binding f binding disable-when-heading-prefix))
9018 (error nil)))))))))
9019 (run-hooks 'orgstruct-setup-hook))
9021 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9022 "Create a function for binding in the structure minor mode.
9023 FUN is the command to call inside a table. KEY is the key that
9024 should be checked in for a command to execute outside of tables.
9025 Non-nil `disable-when-heading-prefix' means to disable the command
9026 if `orgstruct-heading-prefix-regexp' is not empty."
9027 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9028 (let ((nname name)
9029 (i 0))
9030 (while (fboundp (intern nname))
9031 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9032 (setq name (intern nname)))
9033 (eval
9034 (let ((bindings '((org-heading-regexp
9035 (concat "^"
9036 orgstruct-heading-prefix-regexp
9037 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9038 (org-outline-regexp
9039 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9040 (org-outline-regexp-bol
9041 (concat "^" org-outline-regexp))
9042 (outline-regexp org-outline-regexp)
9043 (outline-heading-end-regexp "\n")
9044 (outline-level 'org-outline-level)
9045 (outline-heading-alist))))
9046 `(defun ,name (arg)
9047 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9048 "Outside of structure, run the binding of `"
9049 (key-description key) "'."
9050 (when disable-when-heading-prefix
9051 (concat
9052 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9053 "back to the default binding due to limitations of Org's implementation of\n"
9054 "`" (symbol-name fun) "'.")))
9055 (interactive "p")
9056 (let* ((disable
9057 ,(and disable-when-heading-prefix
9058 '(not (string= orgstruct-heading-prefix-regexp ""))))
9059 (fallback
9060 (or disable
9061 (not
9062 (let* ,bindings
9063 (org-context-p 'headline 'item
9064 ,(when (memq fun
9065 '(org-insert-heading
9066 org-insert-heading-respect-content
9067 org-meta-return))
9068 '(when orgstruct-is-++
9069 'item-body))))))))
9070 (if fallback
9071 (let* ((orgstruct-mode)
9072 (binding
9073 (loop with key = ,key
9074 for rep in
9075 '(nil
9076 ("<\\([^>]*\\)tab>" . "\\1TAB")
9077 ("<\\([^>]*\\)return>" . "\\1RET")
9078 ("<\\([^>]*\\)escape>" . "\\1ESC")
9079 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9081 (when rep
9082 (setq key (read-kbd-macro
9083 (let ((case-fold-search))
9084 (replace-regexp-in-string
9085 (car rep)
9086 (cdr rep)
9087 (key-description key))))))
9088 thereis (key-binding key))))
9089 (if (keymapp binding)
9090 (set-temporary-overlay-map binding)
9091 (let ((func (or binding
9092 (unless disable
9093 'orgstruct-error))))
9094 (when func
9095 (call-interactively func)))))
9096 (org-run-like-in-org-mode
9097 (lambda ()
9098 (interactive)
9099 (let* ,bindings
9100 (call-interactively ',fun)))))))))
9101 name))
9103 (defun org-contextualize-keys (alist contexts)
9104 "Return valid elements in ALIST depending on CONTEXTS.
9106 `org-agenda-custom-commands' or `org-capture-templates' are the
9107 values used for ALIST, and `org-agenda-custom-commands-contexts'
9108 or `org-capture-templates-contexts' are the associated contexts
9109 definitions."
9110 (let ((contexts
9111 ;; normalize contexts
9112 (mapcar
9113 (lambda(c) (cond ((listp (cadr c))
9114 (list (car c) (car c) (cadr c)))
9115 ((string= "" (cadr c))
9116 (list (car c) (car c) (caddr c)))
9117 (t c))) contexts))
9118 (a alist) c r s)
9119 ;; loop over all commands or templates
9120 (while (setq c (pop a))
9121 (let (vrules repl)
9122 (cond
9123 ((not (assoc (car c) contexts))
9124 (push c r))
9125 ((and (assoc (car c) contexts)
9126 (setq vrules (org-contextualize-validate-key
9127 (car c) contexts)))
9128 (mapc (lambda (vr)
9129 (when (not (equal (car vr) (cadr vr)))
9130 (setq repl vr))) vrules)
9131 (if (not repl) (push c r)
9132 (push (cadr repl) s)
9133 (push
9134 (cons (car c)
9135 (cdr (or (assoc (cadr repl) alist)
9136 (error "Undefined key `%s' as contextual replacement for `%s'"
9137 (cadr repl) (car c)))))
9138 r))))))
9139 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9140 (delq
9142 (delete-dups
9143 (mapcar (lambda (x)
9144 (let ((tpl (car x)))
9145 (when (not (delq
9147 (mapcar (lambda(y)
9148 (equal y tpl)) s))) x)))
9149 (reverse r))))))
9151 (defun org-contextualize-validate-key (key contexts)
9152 "Check CONTEXTS for agenda or capture KEY."
9153 (let (r rr res)
9154 (while (setq r (pop contexts))
9155 (mapc
9156 (lambda (rr)
9157 (when
9158 (and (equal key (car r))
9159 (if (functionp rr) (funcall rr)
9160 (or (and (eq (car rr) 'in-file)
9161 (buffer-file-name)
9162 (string-match (cdr rr) (buffer-file-name)))
9163 (and (eq (car rr) 'in-mode)
9164 (string-match (cdr rr) (symbol-name major-mode)))
9165 (and (eq (car rr) 'in-buffer)
9166 (string-match (cdr rr) (buffer-name)))
9167 (when (and (eq (car rr) 'not-in-file)
9168 (buffer-file-name))
9169 (not (string-match (cdr rr) (buffer-file-name))))
9170 (when (eq (car rr) 'not-in-mode)
9171 (not (string-match (cdr rr) (symbol-name major-mode))))
9172 (when (eq (car rr) 'not-in-buffer)
9173 (not (string-match (cdr rr) (buffer-name)))))))
9174 (push r res)))
9175 (car (last r))))
9176 (delete-dups (delq nil res))))
9178 (defun org-context-p (&rest contexts)
9179 "Check if local context is any of CONTEXTS.
9180 Possible values in the list of contexts are `table', `headline', and `item'."
9181 (let ((pos (point)))
9182 (goto-char (point-at-bol))
9183 (prog1 (or (and (memq 'table contexts)
9184 (looking-at "[ \t]*|"))
9185 (and (memq 'headline contexts)
9186 (looking-at org-outline-regexp))
9187 (and (memq 'item contexts)
9188 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9189 (and (memq 'item-body contexts)
9190 (org-in-item-p)))
9191 (goto-char pos))))
9193 (defun org-get-local-variables ()
9194 "Return a list of all local variables in an Org mode buffer."
9195 (let (varlist)
9196 (with-current-buffer (get-buffer-create "*Org tmp*")
9197 (erase-buffer)
9198 (org-mode)
9199 (setq varlist (buffer-local-variables)))
9200 (kill-buffer "*Org tmp*")
9201 (delq nil
9202 (mapcar
9203 (lambda (x)
9204 (setq x
9205 (if (symbolp x)
9206 (list x)
9207 (list (car x) (cdr x))))
9208 (if (and (not (get (car x) 'org-state))
9209 (string-match
9210 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9211 (symbol-name (car x))))
9212 x nil))
9213 varlist))))
9215 (defun org-clone-local-variables (from-buffer &optional regexp)
9216 "Clone local variables from FROM-BUFFER.
9217 Optional argument REGEXP selects variables to clone."
9218 (mapc
9219 (lambda (pair)
9220 (and (symbolp (car pair))
9221 (or (null regexp)
9222 (string-match regexp (symbol-name (car pair))))
9223 (set (make-local-variable (car pair))
9224 (cdr pair))))
9225 (buffer-local-variables from-buffer)))
9227 ;;;###autoload
9228 (defun org-run-like-in-org-mode (cmd)
9229 "Run a command, pretending that the current buffer is in Org-mode.
9230 This will temporarily bind local variables that are typically bound in
9231 Org-mode to the values they have in Org-mode, and then interactively
9232 call CMD."
9233 (org-load-modules-maybe)
9234 (unless org-local-vars
9235 (setq org-local-vars (org-get-local-variables)))
9236 (let (binds)
9237 (dolist (var org-local-vars)
9238 (when (or (not (boundp (car var)))
9239 (eq (symbol-value (car var))
9240 (default-value (car var))))
9241 (push (list (car var) `(quote ,(cadr var))) binds)))
9242 (eval `(let ,binds
9243 (call-interactively (quote ,cmd))))))
9245 ;;;; Archiving
9247 (defun org-get-category (&optional pos force-refresh)
9248 "Get the category applying to position POS."
9249 (save-match-data
9250 (if force-refresh (org-refresh-category-properties))
9251 (let ((pos (or pos (point))))
9252 (or (get-text-property pos 'org-category)
9253 (progn (org-refresh-category-properties)
9254 (get-text-property pos 'org-category))))))
9256 (defun org-refresh-category-properties ()
9257 "Refresh category text properties in the buffer."
9258 (let ((case-fold-search t)
9259 (inhibit-read-only t)
9260 (def-cat (cond
9261 ((null org-category)
9262 (if buffer-file-name
9263 (file-name-sans-extension
9264 (file-name-nondirectory buffer-file-name))
9265 "???"))
9266 ((symbolp org-category) (symbol-name org-category))
9267 (t org-category)))
9268 beg end cat pos optionp)
9269 (org-with-silent-modifications
9270 (save-excursion
9271 (save-restriction
9272 (widen)
9273 (goto-char (point-min))
9274 (put-text-property (point) (point-max) 'org-category def-cat)
9275 (while (re-search-forward
9276 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9277 (setq pos (match-end 0)
9278 optionp (equal (char-after (match-beginning 0)) ?#)
9279 cat (org-trim (match-string 2)))
9280 (if optionp
9281 (setq beg (point-at-bol) end (point-max))
9282 (org-back-to-heading t)
9283 (setq beg (point) end (org-end-of-subtree t t)))
9284 (put-text-property beg end 'org-category cat)
9285 (put-text-property beg end 'org-category-position beg)
9286 (goto-char pos)))))))
9288 (defun org-refresh-properties (dprop tprop)
9289 "Refresh buffer text properties.
9290 DPROP is the drawer property and TPROP is the corresponding text
9291 property to set."
9292 (let ((case-fold-search t)
9293 (inhibit-read-only t) p)
9294 (org-with-silent-modifications
9295 (save-excursion
9296 (save-restriction
9297 (widen)
9298 (goto-char (point-min))
9299 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9300 (setq p (org-match-string-no-properties 1))
9301 (save-excursion
9302 (org-back-to-heading t)
9303 (put-text-property
9304 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9307 ;;;; Link Stuff
9309 ;;; Link abbreviations
9311 (defun org-link-expand-abbrev (link)
9312 "Apply replacements as defined in `org-link-abbrev-alist'."
9313 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9314 (let* ((key (match-string 1 link))
9315 (as (or (assoc key org-link-abbrev-alist-local)
9316 (assoc key org-link-abbrev-alist)))
9317 (tag (and (match-end 2) (match-string 3 link)))
9318 rpl)
9319 (if (not as)
9320 link
9321 (setq rpl (cdr as))
9322 (cond
9323 ((symbolp rpl) (funcall rpl tag))
9324 ((string-match "%(\\([^)]+\\))" rpl)
9325 (replace-match
9326 (save-match-data
9327 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9328 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9329 ((string-match "%h" rpl)
9330 (replace-match (url-hexify-string (or tag "")) t t rpl))
9331 (t (concat rpl tag)))))
9332 link))
9334 ;;; Storing and inserting links
9336 (defvar org-insert-link-history nil
9337 "Minibuffer history for links inserted with `org-insert-link'.")
9339 (defvar org-stored-links nil
9340 "Contains the links stored with `org-store-link'.")
9342 (defvar org-store-link-plist nil
9343 "Plist with info about the most recently link created with `org-store-link'.")
9345 (defvar org-link-protocols nil
9346 "Link protocols added to Org-mode using `org-add-link-type'.")
9348 (defvar org-store-link-functions nil
9349 "List of functions that are called to create and store a link.
9350 Each function will be called in turn until one returns a non-nil
9351 value. Each function should check if it is responsible for creating
9352 this link (for example by looking at the major mode).
9353 If not, it must exit and return nil.
9354 If yes, it should return a non-nil value after a calling
9355 `org-store-link-props' with a list of properties and values.
9356 Special properties are:
9358 :type The link prefix, like \"http\". This must be given.
9359 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9360 This is obligatory as well.
9361 :description Optional default description for the second pair
9362 of brackets in an Org-mode link. The user can still change
9363 this when inserting this link into an Org-mode buffer.
9365 In addition to these, any additional properties can be specified
9366 and then used in capture templates.")
9368 (defun org-add-link-type (type &optional follow export)
9369 "Add TYPE to the list of `org-link-types'.
9370 Re-compute all regular expressions depending on `org-link-types'
9372 FOLLOW and EXPORT are two functions.
9374 FOLLOW should take the link path as the single argument and do whatever
9375 is necessary to follow the link, for example find a file or display
9376 a mail message.
9378 EXPORT should format the link path for export to one of the export formats.
9379 It should be a function accepting three arguments:
9381 path the path of the link, the text after the prefix (like \"http:\")
9382 desc the description of the link, if any, or a description added by
9383 org-export-normalize-links if there is none
9384 format the export format, a symbol like `html' or `latex' or `ascii'..
9386 The function may use the FORMAT information to return different values
9387 depending on the format. The return value will be put literally into
9388 the exported file. If the return value is nil, this means Org should
9389 do what it normally does with links which do not have EXPORT defined.
9391 Org-mode has a built-in default for exporting links. If you are happy with
9392 this default, there is no need to define an export function for the link
9393 type. For a simple example of an export function, see `org-bbdb.el'."
9394 (add-to-list 'org-link-types type t)
9395 (org-make-link-regexps)
9396 (if (assoc type org-link-protocols)
9397 (setcdr (assoc type org-link-protocols) (list follow export))
9398 (push (list type follow export) org-link-protocols)))
9400 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9401 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9403 ;;;###autoload
9404 (defun org-store-link (arg)
9405 "\\<org-mode-map>Store an org-link to the current location.
9406 This link is added to `org-stored-links' and can later be inserted
9407 into an org-buffer with \\[org-insert-link].
9409 For some link types, a prefix arg is interpreted.
9410 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9411 For file links, arg negates `org-context-in-file-links'.
9413 A double prefix arg force skipping storing functions that are not
9414 part of Org's core.
9416 A triple prefix arg force storing a link for each line in the
9417 active region."
9418 (interactive "P")
9419 (org-load-modules-maybe)
9420 (if (and (equal arg '(64)) (org-region-active-p))
9421 (save-excursion
9422 (let ((end (region-end)))
9423 (goto-char (region-beginning))
9424 (set-mark (point))
9425 (while (< (point-at-eol) end)
9426 (move-end-of-line 1) (activate-mark)
9427 (let (current-prefix-arg)
9428 (call-interactively 'org-store-link))
9429 (move-beginning-of-line 2)
9430 (set-mark (point)))))
9431 (org-with-limited-levels
9432 (setq org-store-link-plist nil)
9433 (let (link cpltxt desc description search
9434 txt custom-id agenda-link sfuns sfunsn)
9435 (cond
9437 ;; Store a link using an external link type
9438 ((and (not (equal arg '(16)))
9439 (setq sfuns
9440 (delq
9441 nil (mapcar (lambda (f)
9442 (let (fs) (if (funcall f) (push f fs))))
9443 org-store-link-functions))
9444 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9445 (or (and (cdr sfuns)
9446 (funcall (intern
9447 (completing-read
9448 "Which function for creating the link? "
9449 sfunsn t (car sfunsn)))))
9450 (funcall (caar sfuns)))
9451 (setq link (plist-get org-store-link-plist :link)
9452 desc (or (plist-get org-store-link-plist
9453 :description) link))))
9455 ;; Store a link from a source code buffer
9456 ((org-src-edit-buffer-p)
9457 (let (label gc)
9458 (while (or (not label)
9459 (save-excursion
9460 (save-restriction
9461 (widen)
9462 (goto-char (point-min))
9463 (re-search-forward
9464 (regexp-quote (format org-coderef-label-format label))
9465 nil t))))
9466 (when label (message "Label exists already") (sit-for 2))
9467 (setq label (read-string "Code line label: " label)))
9468 (end-of-line 1)
9469 (setq link (format org-coderef-label-format label))
9470 (setq gc (- 79 (length link)))
9471 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9472 (insert link)
9473 (setq link (concat "(" label ")") desc nil)))
9475 ;; We are in the agenda, link to referenced location
9476 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9477 (let ((m (or (get-text-property (point) 'org-hd-marker)
9478 (get-text-property (point) 'org-marker))))
9479 (when m
9480 (org-with-point-at m
9481 (setq agenda-link
9482 (if (org-called-interactively-p 'any)
9483 (call-interactively 'org-store-link)
9484 (org-store-link nil)))))))
9486 ((eq major-mode 'calendar-mode)
9487 (let ((cd (calendar-cursor-to-date)))
9488 (setq link
9489 (format-time-string
9490 (car org-time-stamp-formats)
9491 (apply 'encode-time
9492 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9493 nil nil nil))))
9494 (org-store-link-props :type "calendar" :date cd)))
9496 ((eq major-mode 'help-mode)
9497 (setq link (concat "help:" (save-excursion
9498 (goto-char (point-min))
9499 (looking-at "^[^ ]+")
9500 (match-string 0))))
9501 (org-store-link-props :type "help"))
9503 ((eq major-mode 'w3-mode)
9504 (setq cpltxt (if (and (buffer-name)
9505 (not (string-match "Untitled" (buffer-name))))
9506 (buffer-name)
9507 (url-view-url t))
9508 link (url-view-url t))
9509 (org-store-link-props :type "w3" :url (url-view-url t)))
9511 ((eq major-mode 'image-mode)
9512 (setq cpltxt (concat "file:"
9513 (abbreviate-file-name buffer-file-name))
9514 link cpltxt)
9515 (org-store-link-props :type "image" :file buffer-file-name))
9517 ;; In dired, store a link to the file of the current line
9518 ((eq major-mode 'dired-mode)
9519 (let ((file (dired-get-filename nil t)))
9520 (setq file (if file
9521 (abbreviate-file-name
9522 (expand-file-name (dired-get-filename nil t)))
9523 ;; otherwise, no file so use current directory.
9524 default-directory))
9525 (setq cpltxt (concat "file:" file)
9526 link cpltxt)))
9528 ((setq search (run-hook-with-args-until-success
9529 'org-create-file-search-functions))
9530 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9531 "::" search))
9532 (setq cpltxt (or description link)))
9534 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9535 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9536 (cond
9537 ;; Store a link using the target at point
9538 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9539 (setq cpltxt
9540 (concat "file:"
9541 (abbreviate-file-name
9542 (buffer-file-name (buffer-base-buffer)))
9543 "::" (match-string 1))
9544 link cpltxt))
9545 ((and (featurep 'org-id)
9546 (or (eq org-id-link-to-org-use-id t)
9547 (and (org-called-interactively-p 'any)
9548 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9549 (and (eq org-id-link-to-org-use-id
9550 'create-if-interactive-and-no-custom-id)
9551 (not custom-id))))
9552 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9553 ;; Store a link using the ID at point
9554 (setq link (condition-case nil
9555 (prog1 (org-id-store-link)
9556 (setq desc (plist-get org-store-link-plist
9557 :description)))
9558 (error
9559 ;; Probably before first headline, link only to file
9560 (concat "file:"
9561 (abbreviate-file-name
9562 (buffer-file-name (buffer-base-buffer))))))))
9564 ;; Just link to current headline
9565 (setq cpltxt (concat "file:"
9566 (abbreviate-file-name
9567 (buffer-file-name (buffer-base-buffer)))))
9568 ;; Add a context search string
9569 (when (org-xor org-context-in-file-links arg)
9570 (let* ((ee (org-element-at-point))
9571 (et (org-element-type ee))
9572 (ev (plist-get (cadr ee) :value))
9573 (ek (plist-get (cadr ee) :key))
9574 (eok (and (stringp ek) (string-match "name" ek))))
9575 (setq txt (cond
9576 ((org-at-heading-p) nil)
9577 ((and (eq et 'keyword) eok) ev)
9578 ((org-region-active-p)
9579 (buffer-substring (region-beginning) (region-end)))))
9580 (when (or (null txt) (string-match "\\S-" txt))
9581 (setq cpltxt
9582 (concat cpltxt "::"
9583 (condition-case nil
9584 (org-make-org-heading-search-string txt)
9585 (error "")))
9586 desc (or (and (eq et 'keyword) eok ev)
9587 (nth 4 (ignore-errors (org-heading-components)))
9588 "NONE")))))
9589 (if (string-match "::\\'" cpltxt)
9590 (setq cpltxt (substring cpltxt 0 -2)))
9591 (setq link cpltxt))))
9593 ((buffer-file-name (buffer-base-buffer))
9594 ;; Just link to this file here.
9595 (setq cpltxt (concat "file:"
9596 (abbreviate-file-name
9597 (buffer-file-name (buffer-base-buffer)))))
9598 ;; Add a context string.
9599 (when (org-xor org-context-in-file-links arg)
9600 (setq txt (if (org-region-active-p)
9601 (buffer-substring (region-beginning) (region-end))
9602 (buffer-substring (point-at-bol) (point-at-eol))))
9603 ;; Only use search option if there is some text.
9604 (when (string-match "\\S-" txt)
9605 (setq cpltxt
9606 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9607 desc "NONE")))
9608 (setq link cpltxt))
9610 ((org-called-interactively-p 'interactive)
9611 (user-error "No method for storing a link from this buffer"))
9613 (t (setq link nil)))
9615 ;; We're done setting link and desc, clean up
9616 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9617 (setq link (or link cpltxt)
9618 desc (or desc cpltxt))
9619 (cond ((equal desc "NONE") (setq desc nil))
9620 ((string-match org-bracket-link-analytic-regexp desc)
9621 (let ((d0 (match-string 3 desc))
9622 (p0 (match-string 5 desc)))
9623 (setq desc
9624 (replace-regexp-in-string
9625 org-bracket-link-regexp
9626 (concat (or p0 d0)
9627 (if (equal (length (match-string 0 desc))
9628 (length desc)) "*" "")) desc)))))
9630 ;; Return the link
9631 (if (not (and (or (org-called-interactively-p 'any)
9632 executing-kbd-macro) link))
9633 (or agenda-link (and link (org-make-link-string link desc)))
9634 (push (list link desc) org-stored-links)
9635 (message "Stored: %s" (or desc link))
9636 (when custom-id
9637 (setq link (concat "file:" (abbreviate-file-name
9638 (buffer-file-name)) "::#" custom-id))
9639 (push (list link desc) org-stored-links)))))))
9641 (defun org-store-link-props (&rest plist)
9642 "Store link properties, extract names and addresses."
9643 (let (x adr)
9644 (when (setq x (plist-get plist :from))
9645 (setq adr (mail-extract-address-components x))
9646 (setq plist (plist-put plist :fromname (car adr)))
9647 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9648 (when (setq x (plist-get plist :to))
9649 (setq adr (mail-extract-address-components x))
9650 (setq plist (plist-put plist :toname (car adr)))
9651 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9652 (let ((from (plist-get plist :from))
9653 (to (plist-get plist :to)))
9654 (when (and from to org-from-is-user-regexp)
9655 (setq plist
9656 (plist-put plist :fromto
9657 (if (string-match org-from-is-user-regexp from)
9658 (concat "to %t")
9659 (concat "from %f"))))))
9660 (setq org-store-link-plist plist))
9662 (defun org-add-link-props (&rest plist)
9663 "Add these properties to the link property list."
9664 (let (key value)
9665 (while plist
9666 (setq key (pop plist) value (pop plist))
9667 (setq org-store-link-plist
9668 (plist-put org-store-link-plist key value)))))
9670 (defun org-email-link-description (&optional fmt)
9671 "Return the description part of an email link.
9672 This takes information from `org-store-link-plist' and formats it
9673 according to FMT (default from `org-email-link-description-format')."
9674 (setq fmt (or fmt org-email-link-description-format))
9675 (let* ((p org-store-link-plist)
9676 (to (plist-get p :toaddress))
9677 (from (plist-get p :fromaddress))
9678 (table
9679 (list
9680 (cons "%c" (plist-get p :fromto))
9681 (cons "%F" (plist-get p :from))
9682 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9683 (cons "%T" (plist-get p :to))
9684 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9685 (cons "%s" (plist-get p :subject))
9686 (cons "%d" (plist-get p :date))
9687 (cons "%m" (plist-get p :message-id)))))
9688 (when (string-match "%c" fmt)
9689 ;; Check if the user wrote this message
9690 (if (and org-from-is-user-regexp from to
9691 (save-match-data (string-match org-from-is-user-regexp from)))
9692 (setq fmt (replace-match "to %t" t t fmt))
9693 (setq fmt (replace-match "from %f" t t fmt))))
9694 (org-replace-escapes fmt table)))
9696 (defun org-make-org-heading-search-string (&optional string)
9697 "Make search string for the current headline or STRING."
9698 (let ((s (or string
9699 (and (derived-mode-p 'org-mode)
9700 (save-excursion
9701 (org-back-to-heading t)
9702 (org-element-property :raw-value (org-element-at-point))))))
9703 (lines org-context-in-file-links))
9704 (or string (setq s (concat "*" s))) ; Add * for headlines
9705 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9706 (when (and string (integerp lines) (> lines 0))
9707 (let ((slines (org-split-string s "\n")))
9708 (when (< lines (length slines))
9709 (setq s (mapconcat
9710 'identity
9711 (reverse (nthcdr (- (length slines) lines)
9712 (reverse slines))) "\n")))))
9713 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9715 (defun org-make-link-string (link &optional description)
9716 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9717 (unless (string-match "\\S-" link)
9718 (error "Empty link"))
9719 (when (and description
9720 (stringp description)
9721 (not (string-match "\\S-" description)))
9722 (setq description nil))
9723 (when (stringp description)
9724 ;; Remove brackets from the description, they are fatal.
9725 (while (string-match "\\[" description)
9726 (setq description (replace-match "{" t t description)))
9727 (while (string-match "\\]" description)
9728 (setq description (replace-match "}" t t description))))
9729 (when (equal link description)
9730 ;; No description needed, it is identical
9731 (setq description nil))
9732 (when (and (not description)
9733 (not (string-match (org-image-file-name-regexp) link))
9734 (not (equal link (org-link-escape link))))
9735 (setq description (org-extract-attributes link)))
9736 (setq link
9737 (cond ((string-match (org-image-file-name-regexp) link) link)
9738 ((string-match org-link-types-re link)
9739 (concat (match-string 1 link)
9740 (org-link-escape (substring link (match-end 1)))))
9741 (t (org-link-escape link))))
9742 (concat "[[" link "]"
9743 (if description (concat "[" description "]") "")
9744 "]"))
9746 (defconst org-link-escape-chars
9747 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9748 "List of characters that should be escaped in link.
9749 This is the list that is used for internal purposes.")
9751 (defconst org-link-escape-chars-browser
9752 '(?\ ?\")
9753 "List of escapes for characters that are problematic in links.
9754 This is the list that is used before handing over to the browser.")
9756 (defun org-link-escape (text &optional table merge)
9757 "Return percent escaped representation of TEXT.
9758 TEXT is a string with the text to escape.
9759 Optional argument TABLE is a list with characters that should be
9760 escaped. When nil, `org-link-escape-chars' is used.
9761 If optional argument MERGE is set, merge TABLE into
9762 `org-link-escape-chars'."
9763 (cond
9764 ((and table merge)
9765 (mapc (lambda (defchr)
9766 (unless (member defchr table)
9767 (setq table (cons defchr table)))) org-link-escape-chars))
9768 ((null table)
9769 (setq table org-link-escape-chars)))
9770 (mapconcat
9771 (lambda (char)
9772 (if (or (member char table)
9773 (and (or (< char 32) (= char 37) (> char 126))
9774 org-url-hexify-p))
9775 (mapconcat (lambda (sequence-element)
9776 (format "%%%.2X" sequence-element))
9777 (or (encode-coding-char char 'utf-8)
9778 (error "Unable to percent escape character: %s"
9779 (char-to-string char))) "")
9780 (char-to-string char))) text ""))
9782 (defun org-link-unescape (str)
9783 "Unhex hexified Unicode strings as returned from the JavaScript function
9784 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9785 (unless (and (null str) (string= "" str))
9786 (let ((pos 0) (case-fold-search t) unhexed)
9787 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9788 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9789 (setq str (replace-match unhexed t t str))
9790 (setq pos (+ pos (length unhexed))))))
9791 str)
9793 (defun org-link-unescape-compound (hex)
9794 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9795 Note: this function also decodes single byte encodings like
9796 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9797 (save-match-data
9798 (let* ((bytes (cdr (split-string hex "%")))
9799 (ret "")
9800 (eat 0)
9801 (sum 0))
9802 (while bytes
9803 (let* ((val (string-to-number (pop bytes) 16))
9804 (shift-xor
9805 (if (= 0 eat)
9806 (cond
9807 ((>= val 252) (cons 6 252))
9808 ((>= val 248) (cons 5 248))
9809 ((>= val 240) (cons 4 240))
9810 ((>= val 224) (cons 3 224))
9811 ((>= val 192) (cons 2 192))
9812 (t (cons 0 0)))
9813 (cons 6 128))))
9814 (if (>= val 192) (setq eat (car shift-xor)))
9815 (setq val (logxor val (cdr shift-xor)))
9816 (setq sum (+ (lsh sum (car shift-xor)) val))
9817 (if (> eat 0) (setq eat (- eat 1)))
9818 (cond
9819 ((= 0 eat) ;multi byte
9820 (setq ret (concat ret (org-char-to-string sum)))
9821 (setq sum 0))
9822 ((not bytes) ; single byte(s)
9823 (setq ret (org-link-unescape-single-byte-sequence hex))))
9824 )) ;; end (while bytes
9825 ret )))
9827 (defun org-link-unescape-single-byte-sequence (hex)
9828 "Unhexify hex-encoded single byte character sequences."
9829 (mapconcat (lambda (byte)
9830 (char-to-string (string-to-number byte 16)))
9831 (cdr (split-string hex "%")) ""))
9833 (defun org-xor (a b)
9834 "Exclusive or."
9835 (if a (not b) b))
9837 (defun org-fixup-message-id-for-http (s)
9838 "Replace special characters in a message id, so it can be used in an http query."
9839 (when (string-match "%" s)
9840 (setq s (mapconcat (lambda (c)
9841 (if (eq c ?%)
9842 "%25"
9843 (char-to-string c)))
9844 s "")))
9845 (while (string-match "<" s)
9846 (setq s (replace-match "%3C" t t s)))
9847 (while (string-match ">" s)
9848 (setq s (replace-match "%3E" t t s)))
9849 (while (string-match "@" s)
9850 (setq s (replace-match "%40" t t s)))
9853 (defun org-link-prettify (link)
9854 "Return a human-readable representation of LINK.
9855 The car of LINK must be a raw link the cdr of LINK must be either
9856 a link description or nil."
9857 (let ((desc (or (cadr link) "<no description>")))
9858 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9859 "<" (car link) ">")))
9861 ;;;###autoload
9862 (defun org-insert-link-global ()
9863 "Insert a link like Org-mode does.
9864 This command can be called in any mode to insert a link in Org-mode syntax."
9865 (interactive)
9866 (org-load-modules-maybe)
9867 (org-run-like-in-org-mode 'org-insert-link))
9869 (defun org-insert-all-links (&optional keep)
9870 "Insert all links in `org-stored-links'."
9871 (interactive "P")
9872 (let ((links (copy-sequence org-stored-links)) l)
9873 (while (setq l (if keep (pop links) (pop org-stored-links)))
9874 (insert "- ")
9875 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9876 (insert "\n"))))
9878 (defun org-link-fontify-links-to-this-file ()
9879 "Fontify links to the current file in `org-stored-links'."
9880 (let ((f (buffer-file-name)) a b)
9881 (setq a (mapcar (lambda(l)
9882 (let ((ll (car l)))
9883 (when (and (string-match "^file:\\(.+\\)::" ll)
9884 (equal f (expand-file-name (match-string 1 ll))))
9885 ll)))
9886 org-stored-links))
9887 (when (featurep 'org-id)
9888 (setq b (mapcar (lambda(l)
9889 (let ((ll (car l)))
9890 (when (and (string-match "^id:\\(.+\\)$" ll)
9891 (equal f (expand-file-name
9892 (or (org-id-find-id-file
9893 (match-string 1 ll)) ""))))
9894 ll)))
9895 org-stored-links)))
9896 (mapcar (lambda(l)
9897 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9898 (delq nil (append a b)))))
9900 (defvar org-link-links-in-this-file nil)
9901 (defun org-insert-link (&optional complete-file link-location default-description)
9902 "Insert a link. At the prompt, enter the link.
9904 Completion can be used to insert any of the link protocol prefixes like
9905 http or ftp in use.
9907 The history can be used to select a link previously stored with
9908 `org-store-link'. When the empty string is entered (i.e. if you just
9909 press RET at the prompt), the link defaults to the most recently
9910 stored link. As SPC triggers completion in the minibuffer, you need to
9911 use M-SPC or C-q SPC to force the insertion of a space character.
9913 You will also be prompted for a description, and if one is given, it will
9914 be displayed in the buffer instead of the link.
9916 If there is already a link at point, this command will allow you to edit link
9917 and description parts.
9919 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9920 be selected using completion. The path to the file will be relative to the
9921 current directory if the file is in the current directory or a subdirectory.
9922 Otherwise, the link will be the absolute path as completed in the minibuffer
9923 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9924 option `org-link-file-path-type'.
9926 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9927 the current directory or below.
9929 With three \\[universal-argument] prefixes, negate the meaning of
9930 `org-keep-stored-link-after-insertion'.
9932 If `org-make-link-description-function' is non-nil, this function will be
9933 called with the link target, and the result will be the default
9934 link description.
9936 If the LINK-LOCATION parameter is non-nil, this value will be
9937 used as the link location instead of reading one interactively.
9939 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9940 be used as the default description."
9941 (interactive "P")
9942 (let* ((wcf (current-window-configuration))
9943 (origbuf (current-buffer))
9944 (region (if (org-region-active-p)
9945 (buffer-substring (region-beginning) (region-end))))
9946 (remove (and region (list (region-beginning) (region-end))))
9947 (desc region)
9948 tmphist ; byte-compile incorrectly complains about this
9949 (link link-location)
9950 (abbrevs org-link-abbrev-alist-local)
9951 entry file all-prefixes auto-desc)
9952 (cond
9953 (link-location) ; specified by arg, just use it.
9954 ((org-in-regexp org-bracket-link-regexp 1)
9955 ;; We do have a link at point, and we are going to edit it.
9956 (setq remove (list (match-beginning 0) (match-end 0)))
9957 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9958 (setq link (read-string "Link: "
9959 (org-link-unescape
9960 (org-match-string-no-properties 1)))))
9961 ((or (org-in-regexp org-angle-link-re)
9962 (org-in-regexp org-plain-link-re))
9963 ;; Convert to bracket link
9964 (setq remove (list (match-beginning 0) (match-end 0))
9965 link (read-string "Link: "
9966 (org-remove-angle-brackets (match-string 0)))))
9967 ((member complete-file '((4) (16)))
9968 ;; Completing read for file names.
9969 (setq link (org-file-complete-link complete-file)))
9971 ;; Read link, with completion for stored links.
9972 (org-link-fontify-links-to-this-file)
9973 (org-switch-to-buffer-other-window "*Org Links*")
9974 (with-current-buffer "*Org Links*"
9975 (erase-buffer)
9976 (insert "Insert a link.
9977 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9978 (when org-stored-links
9979 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9980 (insert (mapconcat 'org-link-prettify
9981 (reverse org-stored-links) "\n")))
9982 (goto-char (point-min)))
9983 (let ((cw (selected-window)))
9984 (select-window (get-buffer-window "*Org Links*" 'visible))
9985 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9986 (unless (pos-visible-in-window-p (point-max))
9987 (org-fit-window-to-buffer))
9988 (and (window-live-p cw) (select-window cw)))
9989 ;; Fake a link history, containing the stored links.
9990 (setq tmphist (append (mapcar 'car org-stored-links)
9991 org-insert-link-history))
9992 (setq all-prefixes (append (mapcar 'car abbrevs)
9993 (mapcar 'car org-link-abbrev-alist)
9994 org-link-types))
9995 (unwind-protect
9996 (progn
9997 (setq link
9998 (org-completing-read
9999 "Link: "
10000 (append
10001 (mapcar (lambda (x) (concat x ":"))
10002 all-prefixes)
10003 (mapcar 'car org-stored-links))
10004 nil nil nil
10005 'tmphist
10006 (caar org-stored-links)))
10007 (if (not (string-match "\\S-" link))
10008 (user-error "No link selected"))
10009 (mapc (lambda(l)
10010 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10011 org-stored-links)
10012 (if (or (member link all-prefixes)
10013 (and (equal ":" (substring link -1))
10014 (member (substring link 0 -1) all-prefixes)
10015 (setq link (substring link 0 -1))))
10016 (setq link (with-current-buffer origbuf
10017 (org-link-try-special-completion link)))))
10018 (set-window-configuration wcf)
10019 (kill-buffer "*Org Links*"))
10020 (setq entry (assoc link org-stored-links))
10021 (or entry (push link org-insert-link-history))
10022 (setq desc (or desc (nth 1 entry)))))
10024 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10025 (not org-keep-stored-link-after-insertion))
10026 (setq org-stored-links (delq (assoc link org-stored-links)
10027 org-stored-links)))
10029 (if (and (string-match org-plain-link-re link)
10030 (not (string-match org-ts-regexp link)))
10031 ;; URL-like link, normalize the use of angular brackets.
10032 (setq link (org-remove-angle-brackets link)))
10034 ;; Check if we are linking to the current file with a search
10035 ;; option If yes, simplify the link by using only the search
10036 ;; option.
10037 (when (and buffer-file-name
10038 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10039 (let* ((path (match-string 1 link))
10040 (case-fold-search nil)
10041 (search (match-string 2 link)))
10042 (save-match-data
10043 (if (equal (file-truename buffer-file-name) (file-truename path))
10044 ;; We are linking to this same file, with a search option
10045 (setq link search)))))
10047 ;; Check if we can/should use a relative path. If yes, simplify the link
10048 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10049 (let* ((type (match-string 1 link))
10050 (path (match-string 2 link))
10051 (origpath path)
10052 (case-fold-search nil))
10053 (cond
10054 ((or (eq org-link-file-path-type 'absolute)
10055 (equal complete-file '(16)))
10056 (setq path (abbreviate-file-name (expand-file-name path))))
10057 ((eq org-link-file-path-type 'noabbrev)
10058 (setq path (expand-file-name path)))
10059 ((eq org-link-file-path-type 'relative)
10060 (setq path (file-relative-name path)))
10062 (save-match-data
10063 (if (string-match (concat "^" (regexp-quote
10064 (expand-file-name
10065 (file-name-as-directory
10066 default-directory))))
10067 (expand-file-name path))
10068 ;; We are linking a file with relative path name.
10069 (setq path (substring (expand-file-name path)
10070 (match-end 0)))
10071 (setq path (abbreviate-file-name (expand-file-name path)))))))
10072 (setq link (concat type path))
10073 (if (equal desc origpath)
10074 (setq desc path))))
10076 (if org-make-link-description-function
10077 (setq desc
10078 (or (condition-case nil
10079 (funcall org-make-link-description-function link desc)
10080 (error (progn (message "Can't get link description from `%s'"
10081 (symbol-name org-make-link-description-function))
10082 (sit-for 2) nil)))
10083 (read-string "Description: " default-description)))
10084 (if default-description (setq desc default-description)
10085 (setq desc (or (and auto-desc desc)
10086 (read-string "Description: " desc)))))
10088 (unless (string-match "\\S-" desc) (setq desc nil))
10089 (if remove (apply 'delete-region remove))
10090 (insert (org-make-link-string link desc))))
10092 (defun org-link-try-special-completion (type)
10093 "If there is completion support for link type TYPE, offer it."
10094 (let ((fun (intern (concat "org-" type "-complete-link"))))
10095 (if (functionp fun)
10096 (funcall fun)
10097 (read-string "Link (no completion support): " (concat type ":")))))
10099 (defun org-file-complete-link (&optional arg)
10100 "Create a file link using completion."
10101 (let (file link)
10102 (setq file (org-iread-file-name "File: "))
10103 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10104 (pwd1 (file-name-as-directory (abbreviate-file-name
10105 (expand-file-name ".")))))
10106 (cond
10107 ((equal arg '(16))
10108 (setq link (concat
10109 "file:"
10110 (abbreviate-file-name (expand-file-name file)))))
10111 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10112 (setq link (concat "file:" (match-string 1 file))))
10113 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10114 (expand-file-name file))
10115 (setq link (concat
10116 "file:" (match-string 1 (expand-file-name file)))))
10117 (t (setq link (concat "file:" file)))))
10118 link))
10120 (defun org-iread-file-name (&rest args)
10121 "Read-file-name using `ido-mode' speedup if available.
10122 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10123 See `read-file-name' for a description of parameters."
10124 (org-without-partial-completion
10125 (if (and org-completion-use-ido
10126 (fboundp 'ido-read-file-name)
10127 (boundp 'ido-mode) ido-mode
10128 (listp (second args)))
10129 (let ((ido-enter-matching-directory nil))
10130 (apply 'ido-read-file-name args))
10131 (apply 'read-file-name args))))
10133 (defun org-completing-read (&rest args)
10134 "Completing-read with SPACE being a normal character."
10135 (let ((enable-recursive-minibuffers t)
10136 (minibuffer-local-completion-map
10137 (copy-keymap minibuffer-local-completion-map)))
10138 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10139 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10140 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10141 (apply 'org-icompleting-read args)))
10143 (defun org-completing-read-no-i (&rest args)
10144 (let (org-completion-use-ido org-completion-use-iswitchb)
10145 (apply 'org-completing-read args)))
10147 (defun org-iswitchb-completing-read (prompt choices &rest args)
10148 "Use iswitch as a completing-read replacement to choose from choices.
10149 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10150 from."
10151 (let* ((iswitchb-use-virtual-buffers nil)
10152 (iswitchb-make-buflist-hook
10153 (lambda ()
10154 (setq iswitchb-temp-buflist choices))))
10155 (iswitchb-read-buffer prompt)))
10157 (defun org-icompleting-read (&rest args)
10158 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10159 (org-without-partial-completion
10160 (if (and org-completion-use-ido
10161 (fboundp 'ido-completing-read)
10162 (boundp 'ido-mode) ido-mode
10163 (listp (second args)))
10164 (let ((ido-enter-matching-directory nil))
10165 (apply 'ido-completing-read (concat (car args))
10166 (if (consp (car (nth 1 args)))
10167 (mapcar 'car (nth 1 args))
10168 (nth 1 args))
10169 (cddr args)))
10170 (if (and org-completion-use-iswitchb
10171 (boundp 'iswitchb-mode) iswitchb-mode
10172 (listp (second args)))
10173 (apply 'org-iswitchb-completing-read (concat (car args))
10174 (if (consp (car (nth 1 args)))
10175 (mapcar 'car (nth 1 args))
10176 (nth 1 args))
10177 (cddr args))
10178 (apply 'completing-read args)))))
10180 (defun org-extract-attributes (s)
10181 "Extract the attributes cookie from a string and set as text property."
10182 (let (a attr (start 0) key value)
10183 (save-match-data
10184 (when (string-match "{{\\([^}]+\\)}}$" s)
10185 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10186 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10187 (setq key (match-string 1 a) value (match-string 2 a)
10188 start (match-end 0)
10189 attr (plist-put attr (intern key) value))))
10190 (org-add-props s nil 'org-attr attr))
10193 ;;; Opening/following a link
10195 (defvar org-link-search-failed nil)
10197 (defvar org-open-link-functions nil
10198 "Hook for functions finding a plain text link.
10199 These functions must take a single argument, the link content.
10200 They will be called for links that look like [[link text][description]]
10201 when LINK TEXT does not have a protocol like \"http:\" and does not look
10202 like a filename (e.g. \"./blue.png\").
10204 These functions will be called *before* Org attempts to resolve the
10205 link by doing text searches in the current buffer - so if you want a
10206 link \"[[target]]\" to still find \"<<target>>\", your function should
10207 handle this as a special case.
10209 When the function does handle the link, it must return a non-nil value.
10210 If it decides that it is not responsible for this link, it must return
10211 nil to indicate that that Org-mode can continue with other options
10212 like exact and fuzzy text search.")
10214 (defun org-next-link (&optional search-backward)
10215 "Move forward to the next link.
10216 If the link is in hidden text, expose it."
10217 (interactive "P")
10218 (when (and org-link-search-failed (eq this-command last-command))
10219 (goto-char (point-min))
10220 (message "Link search wrapped back to beginning of buffer"))
10221 (setq org-link-search-failed nil)
10222 (let* ((pos (point))
10223 (ct (org-context))
10224 (a (assoc :link ct))
10225 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10226 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10227 ((looking-at org-any-link-re)
10228 ;; Don't stay stuck at link without an org-link face
10229 (forward-char (if search-backward -1 1))))
10230 (if (funcall srch-fun org-any-link-re nil t)
10231 (progn
10232 (goto-char (match-beginning 0))
10233 (if (outline-invisible-p) (org-show-context)))
10234 (goto-char pos)
10235 (setq org-link-search-failed t)
10236 (message "No further link found"))))
10238 (defun org-previous-link ()
10239 "Move backward to the previous link.
10240 If the link is in hidden text, expose it."
10241 (interactive)
10242 (funcall 'org-next-link t))
10244 (defun org-translate-link (s)
10245 "Translate a link string if a translation function has been defined."
10246 (if (and org-link-translation-function
10247 (fboundp org-link-translation-function)
10248 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10249 (progn
10250 (setq s (funcall org-link-translation-function
10251 (match-string 1 s) (match-string 2 s)))
10252 (concat (car s) ":" (cdr s)))
10255 (defun org-translate-link-from-planner (type path)
10256 "Translate a link from Emacs Planner syntax so that Org can follow it.
10257 This is still an experimental function, your mileage may vary."
10258 (cond
10259 ((member type '("http" "https" "news" "ftp"))
10260 ;; standard Internet links are the same.
10261 nil)
10262 ((and (equal type "irc") (string-match "^//" path))
10263 ;; Planner has two / at the beginning of an irc link, we have 1.
10264 ;; We should have zero, actually....
10265 (setq path (substring path 1)))
10266 ((and (equal type "lisp") (string-match "^/" path))
10267 ;; Planner has a slash, we do not.
10268 (setq type "elisp" path (substring path 1)))
10269 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10270 ;; A typical message link. Planner has the id after the final slash,
10271 ;; we separate it with a hash mark
10272 (setq path (concat (match-string 1 path) "#"
10273 (org-remove-angle-brackets (match-string 2 path))))))
10274 (cons type path))
10276 (defun org-find-file-at-mouse (ev)
10277 "Open file link or URL at mouse."
10278 (interactive "e")
10279 (mouse-set-point ev)
10280 (org-open-at-point 'in-emacs))
10282 (defun org-open-at-mouse (ev)
10283 "Open file link or URL at mouse.
10284 See the docstring of `org-open-file' for details."
10285 (interactive "e")
10286 (mouse-set-point ev)
10287 (if (eq major-mode 'org-agenda-mode)
10288 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10289 (org-open-at-point))
10291 (defvar org-window-config-before-follow-link nil
10292 "The window configuration before following a link.
10293 This is saved in case the need arises to restore it.")
10295 (defvar org-open-link-marker (make-marker)
10296 "Marker pointing to the location where `org-open-at-point; was called.")
10298 ;;;###autoload
10299 (defun org-open-at-point-global ()
10300 "Follow a link like Org-mode does.
10301 This command can be called in any mode to follow a link that has
10302 Org-mode syntax."
10303 (interactive)
10304 (org-run-like-in-org-mode 'org-open-at-point))
10306 ;;;###autoload
10307 (defun org-open-link-from-string (s &optional arg reference-buffer)
10308 "Open a link in the string S, as if it was in Org-mode."
10309 (interactive "sLink: \nP")
10310 (let ((reference-buffer (or reference-buffer (current-buffer))))
10311 (with-temp-buffer
10312 (let ((org-inhibit-startup (not reference-buffer)))
10313 (org-mode)
10314 (insert s)
10315 (goto-char (point-min))
10316 (when reference-buffer
10317 (setq org-link-abbrev-alist-local
10318 (with-current-buffer reference-buffer
10319 org-link-abbrev-alist-local)))
10320 (org-open-at-point arg reference-buffer)))))
10322 (defvar org-open-at-point-functions nil
10323 "Hook that is run when following a link at point.
10325 Functions in this hook must return t if they identify and follow
10326 a link at point. If they don't find anything interesting at point,
10327 they must return nil.")
10329 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10330 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10331 (defun org-open-at-point (&optional arg reference-buffer)
10332 "Open link at or after point.
10333 If there is no link at point, this function will search forward up to
10334 the end of the current line.
10335 Normally, files will be opened by an appropriate application. If the
10336 optional prefix argument ARG is non-nil, Emacs will visit the file.
10337 With a double prefix argument, try to open outside of Emacs, in the
10338 application the system uses for this file type."
10339 (interactive "P")
10340 ;; if in a code block, then open the block's results
10341 (unless (call-interactively #'org-babel-open-src-block-result)
10342 (org-load-modules-maybe)
10343 (move-marker org-open-link-marker (point))
10344 (setq org-window-config-before-follow-link (current-window-configuration))
10345 (org-remove-occur-highlights nil nil t)
10346 (cond
10347 ((and (org-at-heading-p)
10348 (not (org-at-timestamp-p t))
10349 (not (org-in-regexp
10350 (concat org-plain-link-re "\\|"
10351 org-bracket-link-regexp "\\|"
10352 org-angle-link-re "\\|"
10353 "[ \t]:[^ \t\n]+:[ \t]*$")))
10354 (not (get-text-property (point) 'org-linked-text)))
10355 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10356 (lk0 (car lkall))
10357 (lk (if (stringp lk0) (list lk0) lk0))
10358 (lkend (cdr lkall)))
10359 (mapcar (lambda(l)
10360 (search-forward l nil lkend)
10361 (goto-char (match-beginning 0))
10362 (org-open-at-point))
10363 lk))
10364 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10365 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10366 ((and (org-at-timestamp-p t)
10367 (not (org-in-regexp org-bracket-link-regexp)))
10368 (org-follow-timestamp-link))
10369 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10370 (not (org-in-regexp org-any-link-re)))
10371 (org-footnote-action))
10373 (let (type path link line search (pos (point)))
10374 (catch 'match
10375 (save-excursion
10376 (skip-chars-forward "^]\n\r")
10377 (when (org-in-regexp org-bracket-link-regexp 1)
10378 (setq link (org-extract-attributes
10379 (org-link-unescape (org-match-string-no-properties 1))))
10380 (while (string-match " *\n *" link)
10381 (setq link (replace-match " " t t link)))
10382 (setq link (org-link-expand-abbrev link))
10383 (cond
10384 ((or (file-name-absolute-p link)
10385 (string-match "^\\.\\.?/" link))
10386 (setq type "file" path link))
10387 ((string-match org-link-re-with-space3 link)
10388 (setq type (match-string 1 link) path (match-string 2 link)))
10389 ((string-match "^help:+\\(.+\\)" link)
10390 (setq type "help" path (match-string 1 link)))
10391 (t (setq type "thisfile" path link)))
10392 (throw 'match t)))
10394 (when (get-text-property (point) 'org-linked-text)
10395 (setq type "thisfile"
10396 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10397 (1+ (point)) (point))
10398 path (buffer-substring
10399 (or (previous-single-property-change pos 'org-linked-text)
10400 (point-min))
10401 (or (next-single-property-change pos 'org-linked-text)
10402 (point-max)))
10403 ;; Ensure we will search for a <<<radio>>> link, not
10404 ;; a simple reference like <<ref>>
10405 path (concat "<" path))
10406 (throw 'match t))
10408 (save-excursion
10409 (when (or (org-in-regexp org-angle-link-re)
10410 (let ((match (org-in-regexp org-plain-link-re)))
10411 ;; Check a plain link is not within a bracket link
10412 (and match
10413 (save-excursion
10414 (progn
10415 (goto-char (car match))
10416 (not (org-in-regexp org-bracket-link-regexp))))))
10417 (let ((line_ending (save-excursion (end-of-line) (point))))
10418 ;; We are in a line before a plain or bracket link
10419 (or (re-search-forward org-plain-link-re line_ending t)
10420 (re-search-forward org-bracket-link-regexp line_ending t))))
10421 (setq type (match-string 1)
10422 path (org-link-unescape (match-string 2)))
10423 (throw 'match t)))
10424 (save-excursion
10425 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10426 (setq type "tags"
10427 path (match-string 1))
10428 (while (string-match ":" path)
10429 (setq path (replace-match "+" t t path)))
10430 (throw 'match t)))
10431 (when (org-in-regexp "<\\([^><\n]+\\)>")
10432 (setq type "tree-match"
10433 path (match-string 1))
10434 (throw 'match t)))
10435 (unless path
10436 (user-error "No link found"))
10438 ;; switch back to reference buffer
10439 ;; needed when if called in a temporary buffer through
10440 ;; org-open-link-from-string
10441 (with-current-buffer (or reference-buffer (current-buffer))
10443 ;; Remove any trailing spaces in path
10444 (if (string-match " +\\'" path)
10445 (setq path (replace-match "" t t path)))
10446 (if (and org-link-translation-function
10447 (fboundp org-link-translation-function))
10448 ;; Check if we need to translate the link
10449 (let ((tmp (funcall org-link-translation-function type path)))
10450 (setq type (car tmp) path (cdr tmp))))
10452 (cond
10454 ((assoc type org-link-protocols)
10455 (funcall (nth 1 (assoc type org-link-protocols)) path))
10457 ((equal type "help")
10458 (let ((f-or-v (intern path)))
10459 (cond ((fboundp f-or-v)
10460 (describe-function f-or-v))
10461 ((boundp f-or-v)
10462 (describe-variable f-or-v))
10463 (t (error "Not a known function or variable")))))
10465 ((equal type "mailto")
10466 (let ((cmd (car org-link-mailto-program))
10467 (args (cdr org-link-mailto-program)) args1
10468 (address path) (subject "") a)
10469 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10470 (setq address (match-string 1 path)
10471 subject (org-link-escape (match-string 2 path))))
10472 (while args
10473 (cond
10474 ((not (stringp (car args))) (push (pop args) args1))
10475 (t (setq a (pop args))
10476 (if (string-match "%a" a)
10477 (setq a (replace-match address t t a)))
10478 (if (string-match "%s" a)
10479 (setq a (replace-match subject t t a)))
10480 (push a args1))))
10481 (apply cmd (nreverse args1))))
10483 ((member type '("http" "https" "ftp" "news"))
10484 (browse-url
10485 (concat type ":"
10486 (if (org-string-match-p
10487 (concat "[[:nonascii:]"
10488 org-link-escape-chars-browser "]")
10489 path)
10490 (org-link-escape path org-link-escape-chars-browser)
10491 path))))
10493 ((string= type "doi")
10494 (browse-url
10495 (concat org-doi-server-url
10496 (if (org-string-match-p
10497 (concat "[[:nonascii:]"
10498 org-link-escape-chars-browser "]")
10499 path)
10500 (org-link-escape path org-link-escape-chars-browser)
10501 path))))
10503 ((member type '("message"))
10504 (browse-url (concat type ":" path)))
10506 ((string= type "tags")
10507 (org-tags-view arg path))
10509 ((string= type "tree-match")
10510 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10512 ((string= type "file")
10513 (if (string-match "::\\([0-9]+\\)\\'" path)
10514 (setq line (string-to-number (match-string 1 path))
10515 path (substring path 0 (match-beginning 0)))
10516 (if (string-match "::\\(.+\\)\\'" path)
10517 (setq search (match-string 1 path)
10518 path (substring path 0 (match-beginning 0)))))
10519 (if (string-match "[*?{]" (file-name-nondirectory path))
10520 (dired path)
10521 (org-open-file path arg line search)))
10523 ((string= type "shell")
10524 (let ((buf (generate-new-buffer "*Org Shell Output"))
10525 (cmd path))
10526 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10527 (string-match org-confirm-shell-link-not-regexp cmd))
10528 (not org-confirm-shell-link-function)
10529 (funcall org-confirm-shell-link-function
10530 (format "Execute \"%s\" in shell? "
10531 (org-add-props cmd nil
10532 'face 'org-warning))))
10533 (progn
10534 (message "Executing %s" cmd)
10535 (shell-command cmd buf)
10536 (if (featurep 'midnight)
10537 (setq clean-buffer-list-kill-buffer-names
10538 (cons buf clean-buffer-list-kill-buffer-names))))
10539 (error "Abort"))))
10541 ((string= type "elisp")
10542 (let ((cmd path))
10543 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10544 (string-match org-confirm-elisp-link-not-regexp cmd))
10545 (not org-confirm-elisp-link-function)
10546 (funcall org-confirm-elisp-link-function
10547 (format "Execute \"%s\" as elisp? "
10548 (org-add-props cmd nil
10549 'face 'org-warning))))
10550 (message "%s => %s" cmd
10551 (if (equal (string-to-char cmd) ?\()
10552 (eval (read cmd))
10553 (call-interactively (read cmd))))
10554 (error "Abort"))))
10556 ((and (string= type "thisfile")
10557 (or (run-hook-with-args-until-success
10558 'org-open-link-functions path)
10559 (and link
10560 (string-match "^id:" link)
10561 (or (featurep 'org-id) (require 'org-id))
10562 (progn
10563 (funcall (nth 1 (assoc "id" org-link-protocols))
10564 (substring path 3))
10565 t)))))
10567 ((string= type "thisfile")
10568 (if arg
10569 (switch-to-buffer-other-window
10570 (org-get-buffer-for-internal-link (current-buffer)))
10571 (org-mark-ring-push))
10572 (let ((cmd `(org-link-search
10573 ,path
10574 ,(cond ((equal arg '(4)) ''occur)
10575 ((equal arg '(16)) ''org-occur))
10576 ,pos)))
10577 (condition-case nil (let ((org-link-search-inhibit-query t))
10578 (eval cmd))
10579 (error (progn (widen) (eval cmd))))))
10581 (t (browse-url-at-point)))))))
10582 (move-marker org-open-link-marker nil)
10583 (run-hook-with-args 'org-follow-link-hook)))
10585 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10586 "Offer links in the current entry and return the selected link.
10587 If there is only one link, return it.
10588 If NTH is an integer, return the NTH link found.
10589 If ZERO is a string, check also this string for a link, and if
10590 there is one, return it."
10591 (with-current-buffer buffer
10592 (save-excursion
10593 (save-restriction
10594 (widen)
10595 (goto-char marker)
10596 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10597 "\\(" org-angle-link-re "\\)\\|"
10598 "\\(" org-plain-link-re "\\)"))
10599 (cnt ?0)
10600 (in-emacs (if (integerp nth) nil nth))
10601 have-zero end links link c)
10602 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10603 (push (match-string 0 zero) links)
10604 (setq cnt (1- cnt) have-zero t))
10605 (save-excursion
10606 (org-back-to-heading t)
10607 (setq end (save-excursion (outline-next-heading) (point)))
10608 (while (re-search-forward re end t)
10609 (push (match-string 0) links))
10610 (setq links (org-uniquify (reverse links))))
10611 (cond
10612 ((null links)
10613 (message "No links"))
10614 ((equal (length links) 1)
10615 (setq link (car links)))
10616 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10617 (setq link (nth (if have-zero nth (1- nth)) links)))
10618 (t ; we have to select a link
10619 (save-excursion
10620 (save-window-excursion
10621 (delete-other-windows)
10622 (with-output-to-temp-buffer "*Select Link*"
10623 (mapc (lambda (l)
10624 (if (not (string-match org-bracket-link-regexp l))
10625 (princ (format "[%c] %s\n" (incf cnt)
10626 (org-remove-angle-brackets l)))
10627 (if (match-end 3)
10628 (princ (format "[%c] %s (%s)\n" (incf cnt)
10629 (match-string 3 l) (match-string 1 l)))
10630 (princ (format "[%c] %s\n" (incf cnt)
10631 (match-string 1 l))))))
10632 links))
10633 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10634 (message "Select link to open, RET to open all:")
10635 (setq c (read-char-exclusive))
10636 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10637 (when (equal c ?q) (error "Abort"))
10638 (if (equal c ?\C-m)
10639 (setq link links)
10640 (setq nth (- c ?0))
10641 (if have-zero (setq nth (1+ nth)))
10642 (unless (and (integerp nth) (>= (length links) nth))
10643 (user-error "Invalid link selection"))
10644 (setq link (nth (1- nth) links)))))
10645 (cons link end))))))
10647 ;; Add special file links that specify the way of opening
10649 (org-add-link-type "file+sys" 'org-open-file-with-system)
10650 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10651 (defun org-open-file-with-system (path)
10652 "Open file at PATH using the system way of opening it."
10653 (org-open-file path 'system))
10654 (defun org-open-file-with-emacs (path)
10655 "Open file at PATH in Emacs."
10656 (org-open-file path 'emacs))
10659 ;;; File search
10661 (defvar org-create-file-search-functions nil
10662 "List of functions to construct the right search string for a file link.
10663 These functions are called in turn with point at the location to
10664 which the link should point.
10666 A function in the hook should first test if it would like to
10667 handle this file type, for example by checking the `major-mode'
10668 or the file extension. If it decides not to handle this file, it
10669 should just return nil to give other functions a chance. If it
10670 does handle the file, it must return the search string to be used
10671 when following the link. The search string will be part of the
10672 file link, given after a double colon, and `org-open-at-point'
10673 will automatically search for it. If special measures must be
10674 taken to make the search successful, another function should be
10675 added to the companion hook `org-execute-file-search-functions',
10676 which see.
10678 A function in this hook may also use `setq' to set the variable
10679 `description' to provide a suggestion for the descriptive text to
10680 be used for this link when it gets inserted into an Org-mode
10681 buffer with \\[org-insert-link].")
10683 (defvar org-execute-file-search-functions nil
10684 "List of functions to execute a file search triggered by a link.
10686 Functions added to this hook must accept a single argument, the
10687 search string that was part of the file link, the part after the
10688 double colon. The function must first check if it would like to
10689 handle this search, for example by checking the `major-mode' or
10690 the file extension. If it decides not to handle this search, it
10691 should just return nil to give other functions a chance. If it
10692 does handle the search, it must return a non-nil value to keep
10693 other functions from trying.
10695 Each function can access the current prefix argument through the
10696 variable `current-prefix-arg'. Note that a single prefix is used
10697 to force opening a link in Emacs, so it may be good to only use a
10698 numeric or double prefix to guide the search function.
10700 In case this is needed, a function in this hook can also restore
10701 the window configuration before `org-open-at-point' was called using:
10703 (set-window-configuration org-window-config-before-follow-link)")
10705 (defun org-link-search (s &optional type avoid-pos stealth)
10706 "Search for a link search option.
10707 If S is surrounded by forward slashes, it is interpreted as a
10708 regular expression. In org-mode files, this will create an `org-occur'
10709 sparse tree. In ordinary files, `occur' will be used to list matches.
10710 If the current buffer is in `dired-mode', grep will be used to search
10711 in all files. If AVOID-POS is given, ignore matches near that position.
10713 When optional argument STEALTH is non-nil, do not modify
10714 visibility around point, thus ignoring
10715 `org-show-hierarchy-above', `org-show-following-heading' and
10716 `org-show-siblings' variables."
10717 (let ((case-fold-search t)
10718 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10719 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10720 (append '(("") (" ") ("\t") ("\n"))
10721 org-emphasis-alist)
10722 "\\|") "\\)"))
10723 (pos (point))
10724 (pre nil) (post nil)
10725 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10726 (cond
10727 ;; First check if there are any special search functions
10728 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10729 ;; Now try the builtin stuff
10730 ((and (equal (string-to-char s0) ?#)
10731 (> (length s0) 1)
10732 (save-excursion
10733 (goto-char (point-min))
10734 (and
10735 (re-search-forward
10736 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10737 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10738 (setq type 'dedicated
10739 pos (match-beginning 0))))
10740 ;; There is an exact target for this
10741 (goto-char pos)
10742 (org-back-to-heading t)))
10743 ((save-excursion
10744 (goto-char (point-min))
10745 (and
10746 (re-search-forward
10747 (concat "<<" (regexp-quote s0) ">>") nil t)
10748 (setq type 'dedicated
10749 pos (match-beginning 0))))
10750 ;; There is an exact target for this
10751 (goto-char pos))
10752 ((save-excursion
10753 (goto-char (point-min))
10754 (and
10755 (re-search-forward
10756 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10757 (setq type 'dedicated pos (match-beginning 0))))
10758 ;; Found an element with a matching #+name affiliated keyword.
10759 (goto-char pos))
10760 ((and (string-match "^(\\(.*\\))$" s0)
10761 (save-excursion
10762 (goto-char (point-min))
10763 (and
10764 (re-search-forward
10765 (concat "[^[]" (regexp-quote
10766 (format org-coderef-label-format
10767 (match-string 1 s0))))
10768 nil t)
10769 (setq type 'dedicated
10770 pos (1+ (match-beginning 0))))))
10771 ;; There is a coderef target for this
10772 (goto-char pos))
10773 ((string-match "^/\\(.*\\)/$" s)
10774 ;; A regular expression
10775 (cond
10776 ((derived-mode-p 'org-mode)
10777 (org-occur (match-string 1 s)))
10778 (t (org-do-occur (match-string 1 s)))))
10779 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10780 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10781 (goto-char (point-min))
10782 (cond
10783 ((let (case-fold-search)
10784 (re-search-forward (format org-complex-heading-regexp-format
10785 (regexp-quote s))
10786 nil t))
10787 ;; OK, found a match
10788 (setq type 'dedicated)
10789 (goto-char (match-beginning 0)))
10790 ((and (not org-link-search-inhibit-query)
10791 (eq org-link-search-must-match-exact-headline 'query-to-create)
10792 (y-or-n-p "No match - create this as a new heading? "))
10793 (goto-char (point-max))
10794 (or (bolp) (newline))
10795 (insert "* " s "\n")
10796 (beginning-of-line 0))
10798 (goto-char pos)
10799 (error "No match"))))
10801 ;; A normal search string
10802 (when (equal (string-to-char s) ?*)
10803 ;; Anchor on headlines, post may include tags.
10804 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10805 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10806 s (substring s 1)))
10807 (remove-text-properties
10808 0 (length s)
10809 '(face nil mouse-face nil keymap nil fontified nil) s)
10810 ;; Make a series of regular expressions to find a match
10811 (setq words (org-split-string s "[ \n\r\t]+")
10813 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10814 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10815 "\\)" markers)
10816 re2a_ (concat "\\(" (mapconcat 'downcase words
10817 "[ \t\r\n]+") "\\)[ \t\r\n]")
10818 re2a (concat "[ \t\r\n]" re2a_)
10819 re4_ (concat "\\(" (mapconcat 'downcase words
10820 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10821 re4 (concat "[^a-zA-Z_]" re4_)
10823 re1 (concat pre re2 post)
10824 re3 (concat pre (if pre re4_ re4) post)
10825 re5 (concat pre ".*" re4)
10826 re2 (concat pre re2)
10827 re2a (concat pre (if pre re2a_ re2a))
10828 re4 (concat pre (if pre re4_ re4))
10829 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10830 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10831 re5 "\\)"))
10832 (cond
10833 ((eq type 'org-occur) (org-occur reall))
10834 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10835 (t (goto-char (point-min))
10836 (setq type 'fuzzy)
10837 (if (or (and (org-search-not-self 1 re0 nil t)
10838 (setq type 'dedicated))
10839 (org-search-not-self 1 re1 nil t)
10840 (org-search-not-self 1 re2 nil t)
10841 (org-search-not-self 1 re2a nil t)
10842 (org-search-not-self 1 re3 nil t)
10843 (org-search-not-self 1 re4 nil t)
10844 (org-search-not-self 1 re5 nil t))
10845 (goto-char (match-beginning 1))
10846 (goto-char pos)
10847 (error "No match"))))))
10848 (and (derived-mode-p 'org-mode)
10849 (not stealth)
10850 (org-show-context 'link-search))
10851 type))
10853 (defun org-search-not-self (group &rest args)
10854 "Execute `re-search-forward', but only accept matches that do not
10855 enclose the position of `org-open-link-marker'."
10856 (let ((m org-open-link-marker))
10857 (catch 'exit
10858 (while (apply 're-search-forward args)
10859 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10860 (goto-char (match-end group))
10861 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10862 (> (match-beginning 0) (marker-position m))
10863 (< (match-end 0) (marker-position m)))
10864 (save-match-data
10865 (or (not (org-in-regexp
10866 org-bracket-link-analytic-regexp 1))
10867 (not (match-end 4)) ; no description
10868 (and (<= (match-beginning 4) (point))
10869 (>= (match-end 4) (point))))))
10870 (throw 'exit (point))))))))
10872 (defun org-get-buffer-for-internal-link (buffer)
10873 "Return a buffer to be used for displaying the link target of internal links."
10874 (cond
10875 ((not org-display-internal-link-with-indirect-buffer)
10876 buffer)
10877 ((string-match "(Clone)$" (buffer-name buffer))
10878 (message "Buffer is already a clone, not making another one")
10879 ;; we also do not modify visibility in this case
10880 buffer)
10881 (t ; make a new indirect buffer for displaying the link
10882 (let* ((bn (buffer-name buffer))
10883 (ibn (concat bn "(Clone)"))
10884 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10885 (with-current-buffer ib (org-overview))
10886 ib))))
10888 (defun org-do-occur (regexp &optional cleanup)
10889 "Call the Emacs command `occur'.
10890 If CLEANUP is non-nil, remove the printout of the regular expression
10891 in the *Occur* buffer. This is useful if the regex is long and not useful
10892 to read."
10893 (occur regexp)
10894 (when cleanup
10895 (let ((cwin (selected-window)) win beg end)
10896 (when (setq win (get-buffer-window "*Occur*"))
10897 (select-window win))
10898 (goto-char (point-min))
10899 (when (re-search-forward "match[a-z]+" nil t)
10900 (setq beg (match-end 0))
10901 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10902 (setq end (1- (match-beginning 0)))))
10903 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10904 (goto-char (point-min))
10905 (select-window cwin))))
10907 ;;; The mark ring for links jumps
10909 (defvar org-mark-ring nil
10910 "Mark ring for positions before jumps in Org-mode.")
10911 (defvar org-mark-ring-last-goto nil
10912 "Last position in the mark ring used to go back.")
10913 ;; Fill and close the ring
10914 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10915 (loop for i from 1 to org-mark-ring-length do
10916 (push (make-marker) org-mark-ring))
10917 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10918 org-mark-ring)
10920 (defun org-mark-ring-push (&optional pos buffer)
10921 "Put the current position or POS into the mark ring and rotate it."
10922 (interactive)
10923 (setq pos (or pos (point)))
10924 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10925 (move-marker (car org-mark-ring)
10926 (or pos (point))
10927 (or buffer (current-buffer)))
10928 (message "%s"
10929 (substitute-command-keys
10930 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10932 (defun org-mark-ring-goto (&optional n)
10933 "Jump to the previous position in the mark ring.
10934 With prefix arg N, jump back that many stored positions. When
10935 called several times in succession, walk through the entire ring.
10936 Org-mode commands jumping to a different position in the current file,
10937 or to another Org-mode file, automatically push the old position
10938 onto the ring."
10939 (interactive "p")
10940 (let (p m)
10941 (if (eq last-command this-command)
10942 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10943 (setq p org-mark-ring))
10944 (setq org-mark-ring-last-goto p)
10945 (setq m (car p))
10946 (org-pop-to-buffer-same-window (marker-buffer m))
10947 (goto-char m)
10948 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10950 (defun org-remove-angle-brackets (s)
10951 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10952 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10954 (defun org-add-angle-brackets (s)
10955 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10956 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10958 (defun org-remove-double-quotes (s)
10959 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10960 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10963 ;;; Following specific links
10965 (defun org-follow-timestamp-link ()
10966 "Open an agenda view for the time-stamp date/range at point."
10967 (cond
10968 ((org-at-date-range-p t)
10969 (let ((org-agenda-start-on-weekday)
10970 (t1 (match-string 1))
10971 (t2 (match-string 2)) tt1 tt2)
10972 (setq tt1 (time-to-days (org-time-string-to-time t1))
10973 tt2 (time-to-days (org-time-string-to-time t2)))
10974 (let ((org-agenda-buffer-tmp-name
10975 (format "*Org Agenda(a:%s)"
10976 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10977 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10978 ((org-at-timestamp-p t)
10979 (let ((org-agenda-buffer-tmp-name
10980 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10981 (org-agenda-list nil (time-to-days (org-time-string-to-time
10982 (substring (match-string 1) 0 10)))
10983 1)))
10984 (t (error "This should not happen"))))
10987 ;;; Following file links
10988 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10989 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10990 (declare-function mailcap-mime-info
10991 "mailcap" (string &optional request no-decode))
10992 (defvar org-wait nil)
10993 (defun org-open-file (path &optional in-emacs line search)
10994 "Open the file at PATH.
10995 First, this expands any special file name abbreviations. Then the
10996 configuration variable `org-file-apps' is checked if it contains an
10997 entry for this file type, and if yes, the corresponding command is launched.
10999 If no application is found, Emacs simply visits the file.
11001 With optional prefix argument IN-EMACS, Emacs will visit the file.
11002 With a double \\[universal-argument] \\[universal-argument] \
11003 prefix arg, Org tries to avoid opening in Emacs
11004 and to use an external application to visit the file.
11006 Optional LINE specifies a line to go to, optional SEARCH a string
11007 to search for. If LINE or SEARCH is given, the file will be
11008 opened in Emacs, unless an entry from org-file-apps that makes
11009 use of groups in a regexp matches.
11011 If you want to change the way frames are used when following a
11012 link, please customize `org-link-frame-setup'.
11014 If the file does not exist, an error is thrown."
11015 (let* ((file (if (equal path "")
11016 buffer-file-name
11017 (substitute-in-file-name (expand-file-name path))))
11018 (file-apps (append org-file-apps (org-default-apps)))
11019 (apps (org-remove-if
11020 'org-file-apps-entry-match-against-dlink-p file-apps))
11021 (apps-dlink (org-remove-if-not
11022 'org-file-apps-entry-match-against-dlink-p file-apps))
11023 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11024 (dirp (if remp nil (file-directory-p file)))
11025 (file (if (and dirp org-open-directory-means-index-dot-org)
11026 (concat (file-name-as-directory file) "index.org")
11027 file))
11028 (a-m-a-p (assq 'auto-mode apps))
11029 (dfile (downcase file))
11030 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11031 (link (cond ((and (eq line nil)
11032 (eq search nil))
11033 file)
11034 (line
11035 (concat file "::" (number-to-string line)))
11036 (search
11037 (concat file "::" search))))
11038 (dlink (downcase link))
11039 (old-buffer (current-buffer))
11040 (old-pos (point))
11041 (old-mode major-mode)
11042 ext cmd link-match-data)
11043 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11044 (setq ext (match-string 1 dfile))
11045 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11046 (setq ext (match-string 1 dfile))))
11047 (cond
11048 ((member in-emacs '((16) system))
11049 (setq cmd (cdr (assoc 'system apps))))
11050 (in-emacs (setq cmd 'emacs))
11052 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11053 (and dirp (cdr (assoc 'directory apps)))
11054 ; first, try matching against apps-dlink
11055 ; if we get a match here, store the match data for later
11056 (let ((match (assoc-default dlink apps-dlink
11057 'string-match)))
11058 (if match
11059 (progn (setq link-match-data (match-data))
11060 match)
11061 (progn (setq in-emacs (or in-emacs line search))
11062 nil))) ; if we have no match in apps-dlink,
11063 ; always open the file in emacs if line or search
11064 ; is given (for backwards compatibility)
11065 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11066 'string-match)
11067 (cdr (assoc ext apps))
11068 (cdr (assoc t apps))))))
11069 (when (eq cmd 'system)
11070 (setq cmd (cdr (assoc 'system apps))))
11071 (when (eq cmd 'default)
11072 (setq cmd (cdr (assoc t apps))))
11073 (when (eq cmd 'mailcap)
11074 (require 'mailcap)
11075 (mailcap-parse-mailcaps)
11076 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11077 (command (mailcap-mime-info mime-type)))
11078 (if (stringp command)
11079 (setq cmd command)
11080 (setq cmd 'emacs))))
11081 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11082 (not (file-exists-p file))
11083 (not org-open-non-existing-files))
11084 (user-error "No such file: %s" file))
11085 (cond
11086 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11087 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11088 (while (string-match "['\"]%s['\"]" cmd)
11089 (setq cmd (replace-match "%s" t t cmd)))
11090 (while (string-match "%s" cmd)
11091 (setq cmd (replace-match
11092 (save-match-data
11093 (shell-quote-argument
11094 (convert-standard-filename file)))
11095 t t cmd)))
11097 ;; Replace "%1", "%2" etc. in command with group matches from regex
11098 (save-match-data
11099 (let ((match-index 1)
11100 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11101 (set-match-data link-match-data)
11102 (while (<= match-index number-of-groups)
11103 (let ((regex (concat "%" (number-to-string match-index)))
11104 (replace-with (match-string match-index dlink)))
11105 (while (string-match regex cmd)
11106 (setq cmd (replace-match replace-with t t cmd))))
11107 (setq match-index (+ match-index 1)))))
11109 (save-window-excursion
11110 (message "Running %s...done" cmd)
11111 (start-process-shell-command cmd nil cmd)
11112 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11113 ((or (stringp cmd)
11114 (eq cmd 'emacs))
11115 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11116 (widen)
11117 (if line (org-goto-line line)
11118 (if search (org-link-search search))))
11119 ((consp cmd)
11120 (let ((file (convert-standard-filename file)))
11121 (save-match-data
11122 (set-match-data link-match-data)
11123 (eval cmd))))
11124 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11125 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11126 (or (not (equal old-buffer (current-buffer)))
11127 (not (equal old-pos (point))))
11128 (org-mark-ring-push old-pos old-buffer))))
11130 (defun org-file-apps-entry-match-against-dlink-p (entry)
11131 "This function returns non-nil if `entry' uses a regular
11132 expression which should be matched against the whole link by
11133 org-open-file.
11135 It assumes that is the case when the entry uses a regular
11136 expression which has at least one grouping construct and the
11137 action is either a lisp form or a command string containing
11138 '%1', i.e. using at least one subexpression match as a
11139 parameter."
11140 (let ((selector (car entry))
11141 (action (cdr entry)))
11142 (if (stringp selector)
11143 (and (> (regexp-opt-depth selector) 0)
11144 (or (and (stringp action)
11145 (string-match "%[0-9]" action))
11146 (consp action)))
11147 nil)))
11149 (defun org-default-apps ()
11150 "Return the default applications for this operating system."
11151 (cond
11152 ((eq system-type 'darwin)
11153 org-file-apps-defaults-macosx)
11154 ((eq system-type 'windows-nt)
11155 org-file-apps-defaults-windowsnt)
11156 (t org-file-apps-defaults-gnu)))
11158 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11159 "Convert extensions to regular expressions in the cars of LIST.
11160 Also, weed out any non-string entries, because the return value is used
11161 only for regexp matching.
11162 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11163 point to the symbol `emacs', indicating that the file should
11164 be opened in Emacs."
11165 (append
11166 (delq nil
11167 (mapcar (lambda (x)
11168 (if (not (stringp (car x)))
11170 (if (string-match "\\W" (car x))
11172 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11173 list))
11174 (if add-auto-mode
11175 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11177 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11178 (defun org-file-remote-p (file)
11179 "Test whether FILE specifies a location on a remote system.
11180 Return non-nil if the location is indeed remote.
11182 For example, the filename \"/user@host:/foo\" specifies a location
11183 on the system \"/user@host:\"."
11184 (cond ((fboundp 'file-remote-p)
11185 (file-remote-p file))
11186 ((fboundp 'tramp-handle-file-remote-p)
11187 (tramp-handle-file-remote-p file))
11188 ((and (boundp 'ange-ftp-name-format)
11189 (string-match (car ange-ftp-name-format) file))
11190 t)))
11193 ;;;; Refiling
11195 (defun org-get-org-file ()
11196 "Read a filename, with default directory `org-directory'."
11197 (let ((default (or org-default-notes-file remember-data-file)))
11198 (read-file-name (format "File name [%s]: " default)
11199 (file-name-as-directory org-directory)
11200 default)))
11202 (defun org-notes-order-reversed-p ()
11203 "Check if the current file should receive notes in reversed order."
11204 (cond
11205 ((not org-reverse-note-order) nil)
11206 ((eq t org-reverse-note-order) t)
11207 ((not (listp org-reverse-note-order)) nil)
11208 (t (catch 'exit
11209 (let ((all org-reverse-note-order)
11210 entry)
11211 (while (setq entry (pop all))
11212 (if (string-match (car entry) buffer-file-name)
11213 (throw 'exit (cdr entry))))
11214 nil)))))
11216 (defvar org-refile-target-table nil
11217 "The list of refile targets, created by `org-refile'.")
11219 (defvar org-agenda-new-buffers nil
11220 "Buffers created to visit agenda files.")
11222 (defvar org-refile-cache nil
11223 "Cache for refile targets.")
11225 (defvar org-refile-markers nil
11226 "All the markers used for caching refile locations.")
11228 (defun org-refile-marker (pos)
11229 "Get a new refile marker, but only if caching is in use."
11230 (if (not org-refile-use-cache)
11232 (let ((m (make-marker)))
11233 (move-marker m pos)
11234 (push m org-refile-markers)
11235 m)))
11237 (defun org-refile-cache-clear ()
11238 "Clear the refile cache and disable all the markers."
11239 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11240 (setq org-refile-markers nil)
11241 (setq org-refile-cache nil)
11242 (message "Refile cache has been cleared"))
11244 (defun org-refile-cache-check-set (set)
11245 "Check if all the markers in the cache still have live buffers."
11246 (let (marker)
11247 (catch 'exit
11248 (while (and set (setq marker (nth 3 (pop set))))
11249 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11250 (when (and marker (null (marker-buffer marker)))
11251 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11252 (sit-for 3)
11253 (throw 'exit nil)))
11254 t)))
11256 (defun org-refile-cache-put (set &rest identifiers)
11257 "Push the refile targets SET into the cache, under IDENTIFIERS."
11258 (let* ((key (sha1 (prin1-to-string identifiers)))
11259 (entry (assoc key org-refile-cache)))
11260 (if entry
11261 (setcdr entry set)
11262 (push (cons key set) org-refile-cache))))
11264 (defun org-refile-cache-get (&rest identifiers)
11265 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11266 (cond
11267 ((not org-refile-cache) nil)
11268 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11270 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11271 org-refile-cache))))
11272 (and set (org-refile-cache-check-set set) set)))))
11274 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11275 "Produce a table with refile targets."
11276 (let ((case-fold-search nil)
11277 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11278 (entries (or org-refile-targets '((nil . (:level . 1)))))
11279 targets tgs txt re files f desc descre fast-path-p level pos0)
11280 (message "Getting targets...")
11281 (with-current-buffer (or default-buffer (current-buffer))
11282 (while (setq entry (pop entries))
11283 (setq files (car entry) desc (cdr entry))
11284 (setq fast-path-p nil)
11285 (cond
11286 ((null files) (setq files (list (current-buffer))))
11287 ((eq files 'org-agenda-files)
11288 (setq files (org-agenda-files 'unrestricted)))
11289 ((and (symbolp files) (fboundp files))
11290 (setq files (funcall files)))
11291 ((and (symbolp files) (boundp files))
11292 (setq files (symbol-value files))))
11293 (if (stringp files) (setq files (list files)))
11294 (cond
11295 ((eq (car desc) :tag)
11296 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11297 ((eq (car desc) :todo)
11298 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11299 ((eq (car desc) :regexp)
11300 (setq descre (cdr desc)))
11301 ((eq (car desc) :level)
11302 (setq descre (concat "^\\*\\{" (number-to-string
11303 (if org-odd-levels-only
11304 (1- (* 2 (cdr desc)))
11305 (cdr desc)))
11306 "\\}[ \t]")))
11307 ((eq (car desc) :maxlevel)
11308 (setq fast-path-p t)
11309 (setq descre (concat "^\\*\\{1," (number-to-string
11310 (if org-odd-levels-only
11311 (1- (* 2 (cdr desc)))
11312 (cdr desc)))
11313 "\\}[ \t]")))
11314 (t (error "Bad refiling target description %s" desc)))
11315 (while (setq f (pop files))
11316 (with-current-buffer
11317 (if (bufferp f) f (org-get-agenda-file-buffer f))
11319 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11320 (progn
11321 (if (bufferp f) (setq f (buffer-file-name
11322 (buffer-base-buffer f))))
11323 (setq f (and f (expand-file-name f)))
11324 (if (eq org-refile-use-outline-path 'file)
11325 (push (list (file-name-nondirectory f) f nil nil) tgs))
11326 (save-excursion
11327 (save-restriction
11328 (widen)
11329 (goto-char (point-min))
11330 (while (re-search-forward descre nil t)
11331 (goto-char (setq pos0 (point-at-bol)))
11332 (catch 'next
11333 (when org-refile-target-verify-function
11334 (save-match-data
11335 (or (funcall org-refile-target-verify-function)
11336 (throw 'next t))))
11337 (when (and (looking-at org-complex-heading-regexp)
11338 (not (member (match-string 4) excluded-entries))
11339 (match-string 4))
11340 (setq level (org-reduced-level
11341 (- (match-end 1) (match-beginning 1)))
11342 txt (org-link-display-format (match-string 4))
11343 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11344 re (format org-complex-heading-regexp-format
11345 (regexp-quote (match-string 4))))
11346 (when org-refile-use-outline-path
11347 (setq txt (mapconcat
11348 'org-protect-slash
11349 (append
11350 (if (eq org-refile-use-outline-path
11351 'file)
11352 (list (file-name-nondirectory
11353 (buffer-file-name
11354 (buffer-base-buffer))))
11355 (if (eq org-refile-use-outline-path
11356 'full-file-path)
11357 (list (buffer-file-name
11358 (buffer-base-buffer)))))
11359 (org-get-outline-path fast-path-p
11360 level txt)
11361 (list txt))
11362 "/")))
11363 (push (list txt f re (org-refile-marker (point)))
11364 tgs)))
11365 (when (= (point) pos0)
11366 ;; verification function has not moved point
11367 (goto-char (point-at-eol))))))))
11368 (when org-refile-use-cache
11369 (org-refile-cache-put tgs (buffer-file-name) descre))
11370 (setq targets (append tgs targets))))))
11371 (message "Getting targets...done")
11372 (nreverse targets)))
11374 (defun org-protect-slash (s)
11375 (while (string-match "/" s)
11376 (setq s (replace-match "\\" t t s)))
11379 (defvar org-olpa (make-vector 20 nil))
11381 (defun org-get-outline-path (&optional fastp level heading)
11382 "Return the outline path to the current entry, as a list.
11384 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11385 routine which makes outline path derivations for an entire file,
11386 avoiding backtracing. Refile target collection makes use of that."
11387 (if fastp
11388 (progn
11389 (if (> level 19)
11390 (error "Outline path failure, more than 19 levels"))
11391 (loop for i from level upto 19 do
11392 (aset org-olpa i nil))
11393 (prog1
11394 (delq nil (append org-olpa nil))
11395 (aset org-olpa level heading)))
11396 (let (rtn case-fold-search)
11397 (save-excursion
11398 (save-restriction
11399 (widen)
11400 (while (org-up-heading-safe)
11401 (when (looking-at org-complex-heading-regexp)
11402 (push (org-trim
11403 (replace-regexp-in-string
11404 ;; Remove statistical/checkboxes cookies
11405 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11406 (org-match-string-no-properties 4)))
11407 rtn)))
11408 rtn)))))
11410 (defun org-format-outline-path (path &optional width prefix separator)
11411 "Format the outline path PATH for display.
11412 WIDTH is the maximum number of characters that is available.
11413 PREFIX is a prefix to be included in the returned string,
11414 such as the file name.
11415 SEPARATOR is inserted between the different parts of the path,
11416 the default is \"/\"."
11417 (setq width (or width 79))
11418 (if prefix (setq width (- width (length prefix))))
11419 (if (not path)
11420 (or prefix "")
11421 (let* ((nsteps (length path))
11422 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11423 (maxwidth (if (<= total-width width)
11424 10000 ;; everything fits
11425 ;; we need to shorten the level headings
11426 (/ (- width nsteps) nsteps)))
11427 (org-odd-levels-only nil)
11428 (n 0)
11429 (total (1+ (length prefix))))
11430 (setq maxwidth (max maxwidth 10))
11431 (concat prefix
11432 (if prefix (or separator "/"))
11433 (mapconcat
11434 (lambda (h)
11435 (setq n (1+ n))
11436 (if (and (= n nsteps) (< maxwidth 10000))
11437 (setq maxwidth (- total-width total)))
11438 (if (< (length h) maxwidth)
11439 (progn (setq total (+ total (length h) 1)) h)
11440 (setq h (substring h 0 (- maxwidth 2))
11441 total (+ total maxwidth 1))
11442 (if (string-match "[ \t]+\\'" h)
11443 (setq h (substring h 0 (match-beginning 0))))
11444 (setq h (concat h "..")))
11445 (org-add-props h nil 'face
11446 (nth (% (1- n) org-n-level-faces)
11447 org-level-faces))
11449 path (or separator "/"))))))
11451 (defun org-display-outline-path (&optional file current separator just-return-string)
11452 "Display the current outline path in the echo area.
11454 If FILE is non-nil, prepend the output with the file name.
11455 If CURRENT is non-nil, append the current heading to the output.
11456 SEPARATOR is passed through to `org-format-outline-path'. It separates
11457 the different parts of the path and defaults to \"/\".
11458 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11459 (interactive "P")
11460 (let* (case-fold-search
11461 (bfn (buffer-file-name (buffer-base-buffer)))
11462 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11463 res)
11464 (if current (setq path (append path
11465 (save-excursion
11466 (org-back-to-heading t)
11467 (if (looking-at org-complex-heading-regexp)
11468 (list (match-string 4)))))))
11469 (setq res
11470 (org-format-outline-path
11471 path
11472 (1- (frame-width))
11473 (and file bfn (concat (file-name-nondirectory bfn) separator))
11474 separator))
11475 (if just-return-string
11476 (org-no-properties res)
11477 (org-unlogged-message "%s" res))))
11479 (defvar org-refile-history nil
11480 "History for refiling operations.")
11482 (defvar org-after-refile-insert-hook nil
11483 "Hook run after `org-refile' has inserted its stuff at the new location.
11484 Note that this is still *before* the stuff will be removed from
11485 the *old* location.")
11487 (defvar org-capture-last-stored-marker)
11488 (defvar org-refile-keep nil
11489 "Non-nil means `org-refile' will copy instead of refile.")
11491 (defun org-copy ()
11492 "Like `org-refile', but copy."
11493 (interactive)
11494 (let ((org-refile-keep t))
11495 (funcall 'org-refile nil nil nil "Copy")))
11497 (defun org-refile (&optional goto default-buffer rfloc msg)
11498 "Move the entry or entries at point to another heading.
11499 The list of target headings is compiled using the information in
11500 `org-refile-targets', which see.
11502 At the target location, the entry is filed as a subitem of the target
11503 heading. Depending on `org-reverse-note-order', the new subitem will
11504 either be the first or the last subitem.
11506 If there is an active region, all entries in that region will be moved.
11507 However, the region must fulfill the requirement that the first heading
11508 is the first one sets the top-level of the moved text - at most siblings
11509 below it are allowed.
11511 With prefix arg GOTO, the command will only visit the target location
11512 and not actually move anything.
11514 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11515 go to the location where the last refiling operation has put the subtree.
11517 With a numeric prefix argument of `2', refile to the running clock.
11519 With a numeric prefix argument of `3', emulate `org-refile-keep'
11520 being set to `t' and copy to the target location, don't move it.
11521 Beware that keeping refiled entries may result in duplicated ID
11522 properties.
11524 RFLOC can be a refile location obtained in a different way.
11526 MSG is a string to replace \"Refile\" in the default prompt with
11527 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11529 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11531 If you are using target caching (see `org-refile-use-cache'),
11532 you have to clear the target cache in order to find new targets.
11533 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11534 prefix argument (`C-u C-u C-u C-c C-w')."
11536 (interactive "P")
11537 (if (member goto '(0 (64)))
11538 (org-refile-cache-clear)
11539 (let* ((actionmsg (or msg "Refile"))
11540 (cbuf (current-buffer))
11541 (regionp (org-region-active-p))
11542 (region-start (and regionp (region-beginning)))
11543 (region-end (and regionp (region-end)))
11544 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11545 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11546 pos it nbuf file re level reversed)
11547 (setq last-command nil)
11548 (when regionp
11549 (goto-char region-start)
11550 (or (bolp) (goto-char (point-at-bol)))
11551 (setq region-start (point))
11552 (unless (or (org-kill-is-subtree-p
11553 (buffer-substring region-start region-end))
11554 (prog1 org-refile-active-region-within-subtree
11555 (let ((s (point-at-eol)))
11556 (org-toggle-heading)
11557 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11558 (user-error "The region is not a (sequence of) subtree(s)")))
11559 (if (equal goto '(16))
11560 (org-refile-goto-last-stored)
11561 (when (or
11562 (and (equal goto 2)
11563 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11564 (prog1
11565 (setq it (list (or org-clock-heading "running clock")
11566 (buffer-file-name
11567 (marker-buffer org-clock-hd-marker))
11569 (marker-position org-clock-hd-marker)))
11570 (setq goto nil)))
11571 (setq it (or rfloc
11572 (let (heading-text)
11573 (save-excursion
11574 (unless goto
11575 (org-back-to-heading t)
11576 (setq heading-text
11577 (nth 4 (org-heading-components))))
11579 (org-refile-get-location
11580 (cond (goto "Goto")
11581 (regionp (concat actionmsg " region to"))
11582 (t (concat actionmsg " subtree \""
11583 heading-text "\" to")))
11584 default-buffer
11585 (and (not (equal '(4) goto))
11586 org-refile-allow-creating-parent-nodes)
11587 goto))))))
11588 (setq file (nth 1 it)
11589 re (nth 2 it)
11590 pos (nth 3 it))
11591 (if (and (not goto)
11593 (equal (buffer-file-name) file)
11594 (if regionp
11595 (and (>= pos region-start)
11596 (<= pos region-end))
11597 (and (>= pos (point))
11598 (< pos (save-excursion
11599 (org-end-of-subtree t t))))))
11600 (error "Cannot refile to position inside the tree or region"))
11602 (setq nbuf (or (find-buffer-visiting file)
11603 (find-file-noselect file)))
11604 (if (and goto (not (equal goto 3)))
11605 (progn
11606 (org-pop-to-buffer-same-window nbuf)
11607 (goto-char pos)
11608 (org-show-context 'org-goto))
11609 (if regionp
11610 (progn
11611 (org-kill-new (buffer-substring region-start region-end))
11612 (org-save-markers-in-region region-start region-end))
11613 (org-copy-subtree 1 nil t))
11614 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11615 (find-file-noselect file)))
11616 (setq reversed (org-notes-order-reversed-p))
11617 (save-excursion
11618 (save-restriction
11619 (widen)
11620 (if pos
11621 (progn
11622 (goto-char pos)
11623 (looking-at org-outline-regexp)
11624 (setq level (org-get-valid-level (funcall outline-level) 1))
11625 (goto-char
11626 (if reversed
11627 (or (outline-next-heading) (point-max))
11628 (or (save-excursion (org-get-next-sibling))
11629 (org-end-of-subtree t t)
11630 (point-max)))))
11631 (setq level 1)
11632 (if (not reversed)
11633 (goto-char (point-max))
11634 (goto-char (point-min))
11635 (or (outline-next-heading) (goto-char (point-max)))))
11636 (if (not (bolp)) (newline))
11637 (org-paste-subtree level)
11638 (when org-log-refile
11639 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11640 (unless (eq org-log-refile 'note)
11641 (save-excursion (org-add-log-note))))
11642 (and org-auto-align-tags
11643 (let ((org-loop-over-headlines-in-active-region nil))
11644 (org-set-tags nil t)))
11645 (let ((bookmark-name (plist-get org-bookmark-names-plist
11646 :last-refile)))
11647 (when bookmark-name
11648 (with-demoted-errors
11649 (bookmark-set bookmark-name))))
11650 ;; If we are refiling for capture, make sure that the
11651 ;; last-capture pointers point here
11652 (when (org-bound-and-true-p org-refile-for-capture)
11653 (let ((bookmark-name (plist-get org-bookmark-names-plist
11654 :last-capture-marker)))
11655 (when bookmark-name
11656 (with-demoted-errors
11657 (bookmark-set bookmark-name))))
11658 (move-marker org-capture-last-stored-marker (point)))
11659 (if (fboundp 'deactivate-mark) (deactivate-mark))
11660 (run-hooks 'org-after-refile-insert-hook))))
11661 (unless org-refile-keep
11662 (if regionp
11663 (delete-region (point) (+ (point) (- region-end region-start)))
11664 (delete-region
11665 (and (org-back-to-heading t) (point))
11666 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11667 (when (featurep 'org-inlinetask)
11668 (org-inlinetask-remove-END-maybe))
11669 (setq org-markers-to-move nil)
11670 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11672 (defun org-refile-goto-last-stored ()
11673 "Go to the location where the last refile was stored."
11674 (interactive)
11675 (bookmark-jump "org-refile-last-stored")
11676 (message "This is the location of the last refile"))
11678 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11679 no-exclude)
11680 "Prompt the user for a refile location, using PROMPT.
11681 PROMPT should not be suffixed with a colon and a space, because
11682 this function appends the default value from
11683 `org-refile-history' automatically, if that is not empty.
11684 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11685 this is used for the GOTO interface."
11686 (let ((org-refile-targets org-refile-targets)
11687 (org-refile-use-outline-path org-refile-use-outline-path)
11688 excluded-entries)
11689 (when (and (derived-mode-p 'org-mode)
11690 (not org-refile-use-cache)
11691 (not no-exclude))
11692 (org-map-tree
11693 (lambda()
11694 (setq excluded-entries
11695 (append excluded-entries (list (org-get-heading t t)))))))
11696 (setq org-refile-target-table
11697 (org-refile-get-targets default-buffer excluded-entries)))
11698 (unless org-refile-target-table
11699 (user-error "No refile targets"))
11700 (let* ((cbuf (current-buffer))
11701 (partial-completion-mode nil)
11702 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11703 (cfunc (if (and org-refile-use-outline-path
11704 org-outline-path-complete-in-steps)
11705 'org-olpath-completing-read
11706 'org-icompleting-read))
11707 (extra (if org-refile-use-outline-path "/" ""))
11708 (cbnex (concat (buffer-name) extra))
11709 (filename (and cfn (expand-file-name cfn)))
11710 (tbl (mapcar
11711 (lambda (x)
11712 (if (and (not (member org-refile-use-outline-path
11713 '(file full-file-path)))
11714 (not (equal filename (nth 1 x))))
11715 (cons (concat (car x) extra " ("
11716 (file-name-nondirectory (nth 1 x)) ")")
11717 (cdr x))
11718 (cons (concat (car x) extra) (cdr x))))
11719 org-refile-target-table))
11720 (completion-ignore-case t)
11721 cdef
11722 (prompt (concat prompt
11723 (or (and (car org-refile-history)
11724 (concat " (default " (car org-refile-history) ")"))
11725 (and (assoc cbnex tbl) (setq cdef cbnex)
11726 (concat " (default " cbnex ")"))) ": "))
11727 pa answ parent-target child parent old-hist)
11728 (setq old-hist org-refile-history)
11729 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11730 nil 'org-refile-history (or cdef (car org-refile-history))))
11731 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11732 (org-refile-check-position pa)
11733 (if pa
11734 (progn
11735 (when (or (not org-refile-history)
11736 (not (eq old-hist org-refile-history))
11737 (not (equal (car pa) (car org-refile-history))))
11738 (setq org-refile-history
11739 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11740 org-refile-history
11741 (cdr org-refile-history))))
11742 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11743 (pop org-refile-history)))
11745 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11746 (progn
11747 (setq parent (match-string 1 answ)
11748 child (match-string 2 answ))
11749 (setq parent-target (or (assoc parent tbl)
11750 (assoc (concat parent "/") tbl)))
11751 (when (and parent-target
11752 (or (eq new-nodes t)
11753 (and (eq new-nodes 'confirm)
11754 (y-or-n-p (format "Create new node \"%s\"? "
11755 child)))))
11756 (org-refile-new-child parent-target child)))
11757 (user-error "Invalid target location")))))
11759 (declare-function org-string-nw-p "org-macs" (s))
11760 (defun org-refile-check-position (refile-pointer)
11761 "Check if the refile pointer matches the headline to which it points."
11762 (let* ((file (nth 1 refile-pointer))
11763 (re (nth 2 refile-pointer))
11764 (pos (nth 3 refile-pointer))
11765 buffer)
11766 (if (and (not (markerp pos)) (not file))
11767 (user-error "Please save the buffer to a file before refiling")
11768 (when (org-string-nw-p re)
11769 (setq buffer (if (markerp pos)
11770 (marker-buffer pos)
11771 (or (find-buffer-visiting file)
11772 (find-file-noselect file))))
11773 (with-current-buffer buffer
11774 (save-excursion
11775 (save-restriction
11776 (widen)
11777 (goto-char pos)
11778 (beginning-of-line 1)
11779 (unless (org-looking-at-p re)
11780 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11782 (defun org-refile-new-child (parent-target child)
11783 "Use refile target PARENT-TARGET to add new CHILD below it."
11784 (unless parent-target
11785 (error "Cannot find parent for new node"))
11786 (let ((file (nth 1 parent-target))
11787 (pos (nth 3 parent-target))
11788 level)
11789 (with-current-buffer (or (find-buffer-visiting file)
11790 (find-file-noselect file))
11791 (save-excursion
11792 (save-restriction
11793 (widen)
11794 (if pos
11795 (goto-char pos)
11796 (goto-char (point-max))
11797 (if (not (bolp)) (newline)))
11798 (when (looking-at org-outline-regexp)
11799 (setq level (funcall outline-level))
11800 (org-end-of-subtree t t))
11801 (org-back-over-empty-lines)
11802 (insert "\n" (make-string
11803 (if pos (org-get-valid-level level 1) 1) ?*)
11804 " " child "\n")
11805 (beginning-of-line 0)
11806 (list (concat (car parent-target) "/" child) file "" (point)))))))
11808 (defun org-olpath-completing-read (prompt collection &rest args)
11809 "Read an outline path like a file name."
11810 (let ((thetable collection)
11811 (org-completion-use-ido nil) ; does not work with ido.
11812 (org-completion-use-iswitchb nil)) ; or iswitchb
11813 (apply
11814 'org-icompleting-read prompt
11815 (lambda (string predicate &optional flag)
11816 (let (rtn r f (l (length string)))
11817 (cond
11818 ((eq flag nil)
11819 ;; try completion
11820 (try-completion string thetable))
11821 ((eq flag t)
11822 ;; all-completions
11823 (setq rtn (all-completions string thetable predicate))
11824 (mapcar
11825 (lambda (x)
11826 (setq r (substring x l))
11827 (if (string-match " ([^)]*)$" x)
11828 (setq f (match-string 0 x))
11829 (setq f ""))
11830 (if (string-match "/" r)
11831 (concat string (substring r 0 (match-end 0)) f)
11833 rtn))
11834 ((eq flag 'lambda)
11835 ;; exact match?
11836 (assoc string thetable)))))
11837 args)))
11839 ;;;; Dynamic blocks
11841 (defun org-find-dblock (name)
11842 "Find the first dynamic block with name NAME in the buffer.
11843 If not found, stay at current position and return nil."
11844 (let ((case-fold-search t) pos)
11845 (save-excursion
11846 (goto-char (point-min))
11847 (setq pos (and (re-search-forward
11848 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11849 (match-beginning 0))))
11850 (if pos (goto-char pos))
11851 pos))
11853 (defconst org-dblock-start-re
11854 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11855 "Matches the start line of a dynamic block, with parameters.")
11857 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11858 "Matches the end of a dynamic block.")
11860 (defun org-create-dblock (plist)
11861 "Create a dynamic block section, with parameters taken from PLIST.
11862 PLIST must contain a :name entry which is used as name of the block."
11863 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11864 (end-of-line 1)
11865 (newline))
11866 (let ((col (current-column))
11867 (name (plist-get plist :name)))
11868 (insert "#+BEGIN: " name)
11869 (while plist
11870 (if (eq (car plist) :name)
11871 (setq plist (cddr plist))
11872 (insert " " (prin1-to-string (pop plist)))))
11873 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11874 (beginning-of-line -2)))
11876 (defun org-prepare-dblock ()
11877 "Prepare dynamic block for refresh.
11878 This empties the block, puts the cursor at the insert position and returns
11879 the property list including an extra property :name with the block name."
11880 (unless (looking-at org-dblock-start-re)
11881 (user-error "Not at a dynamic block"))
11882 (let* ((begdel (1+ (match-end 0)))
11883 (name (org-no-properties (match-string 1)))
11884 (params (append (list :name name)
11885 (read (concat "(" (match-string 3) ")")))))
11886 (save-excursion
11887 (beginning-of-line 1)
11888 (skip-chars-forward " \t")
11889 (setq params (plist-put params :indentation-column (current-column))))
11890 (unless (re-search-forward org-dblock-end-re nil t)
11891 (error "Dynamic block not terminated"))
11892 (setq params
11893 (append params
11894 (list :content (buffer-substring
11895 begdel (match-beginning 0)))))
11896 (delete-region begdel (match-beginning 0))
11897 (goto-char begdel)
11898 (open-line 1)
11899 params))
11901 (defun org-map-dblocks (&optional command)
11902 "Apply COMMAND to all dynamic blocks in the current buffer.
11903 If COMMAND is not given, use `org-update-dblock'."
11904 (let ((cmd (or command 'org-update-dblock)))
11905 (save-excursion
11906 (goto-char (point-min))
11907 (while (re-search-forward org-dblock-start-re nil t)
11908 (goto-char (match-beginning 0))
11909 (save-excursion
11910 (condition-case nil
11911 (funcall cmd)
11912 (error (message "Error during update of dynamic block"))))
11913 (unless (re-search-forward org-dblock-end-re nil t)
11914 (error "Dynamic block not terminated"))))))
11916 (defun org-dblock-update (&optional arg)
11917 "User command for updating dynamic blocks.
11918 Update the dynamic block at point. With prefix ARG, update all dynamic
11919 blocks in the buffer."
11920 (interactive "P")
11921 (if arg
11922 (org-update-all-dblocks)
11923 (or (looking-at org-dblock-start-re)
11924 (org-beginning-of-dblock))
11925 (org-update-dblock)))
11927 (defun org-update-dblock ()
11928 "Update the dynamic block at point.
11929 This means to empty the block, parse for parameters and then call
11930 the correct writing function."
11931 (interactive)
11932 (save-window-excursion
11933 (let* ((pos (point))
11934 (line (org-current-line))
11935 (params (org-prepare-dblock))
11936 (name (plist-get params :name))
11937 (indent (plist-get params :indentation-column))
11938 (cmd (intern (concat "org-dblock-write:" name))))
11939 (message "Updating dynamic block `%s' at line %d..." name line)
11940 (funcall cmd params)
11941 (message "Updating dynamic block `%s' at line %d...done" name line)
11942 (goto-char pos)
11943 (when (and indent (> indent 0))
11944 (setq indent (make-string indent ?\ ))
11945 (save-excursion
11946 (org-beginning-of-dblock)
11947 (forward-line 1)
11948 (while (not (looking-at org-dblock-end-re))
11949 (insert indent)
11950 (beginning-of-line 2))
11951 (when (looking-at org-dblock-end-re)
11952 (and (looking-at "[ \t]+")
11953 (replace-match ""))
11954 (insert indent)))))))
11956 (defun org-beginning-of-dblock ()
11957 "Find the beginning of the dynamic block at point.
11958 Error if there is no such block at point."
11959 (let ((pos (point))
11960 beg)
11961 (end-of-line 1)
11962 (if (and (re-search-backward org-dblock-start-re nil t)
11963 (setq beg (match-beginning 0))
11964 (re-search-forward org-dblock-end-re nil t)
11965 (> (match-end 0) pos))
11966 (goto-char beg)
11967 (goto-char pos)
11968 (error "Not in a dynamic block"))))
11970 (defun org-update-all-dblocks ()
11971 "Update all dynamic blocks in the buffer.
11972 This function can be used in a hook."
11973 (interactive)
11974 (when (derived-mode-p 'org-mode)
11975 (org-map-dblocks 'org-update-dblock)))
11978 ;;;; Completion
11980 (declare-function org-export-backend-name "org-export" (cl-x))
11981 (declare-function org-export-backend-options "org-export" (cl-x))
11982 (defun org-get-export-keywords ()
11983 "Return a list of all currently understood export keywords.
11984 Export keywords include options, block names, attributes and
11985 keywords relative to each registered export back-end."
11986 (let (keywords)
11987 (dolist (backend
11988 (org-bound-and-true-p org-export--registered-backends)
11989 (delq nil keywords))
11990 ;; Back-end name (for keywords, like #+LATEX:)
11991 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11992 (dolist (option-entry (org-export-backend-options backend))
11993 ;; Back-end options.
11994 (push (nth 1 option-entry) keywords)))))
11996 (defconst org-options-keywords
11997 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11998 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11999 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12000 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12001 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12003 (defcustom org-structure-template-alist
12004 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12005 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12006 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12007 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12008 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12009 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12010 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12011 "<literal style=\"latex\">\n?\n</literal>")
12012 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12013 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12014 "<literal style=\"html\">\n?\n</literal>")
12015 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12016 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12017 ("A" "#+ASCII: " "")
12018 ("i" "#+INDEX: ?" "#+INDEX: ?")
12019 ("I" "#+INCLUDE: %file ?"
12020 "<include file=%file markup=\"?\">"))
12021 "Structure completion elements.
12022 This is a list of abbreviation keys and values. The value gets inserted
12023 if you type `<' followed by the key and then press the completion key,
12024 usually `M-TAB'. %file will be replaced by a file name after prompting
12025 for the file using completion. The cursor will be placed at the position
12026 of the `?` in the template.
12027 There are two templates for each key, the first uses the original Org syntax,
12028 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12029 the default when the /org-mtags.el/ module has been loaded. See also the
12030 variable `org-mtags-prefer-muse-templates'."
12031 :group 'org-completion
12032 :type '(repeat
12033 (list
12034 (string :tag "Key")
12035 (string :tag "Template")
12036 (string :tag "Muse Template"))))
12038 (defun org-try-structure-completion ()
12039 "Try to complete a structure template before point.
12040 This looks for strings like \"<e\" on an otherwise empty line and
12041 expands them."
12042 (let ((l (buffer-substring (point-at-bol) (point)))
12044 (when (and (looking-at "[ \t]*$")
12045 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12046 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12047 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12048 (match-beginning 1)) a)
12049 t)))
12051 (defun org-complete-expand-structure-template (start cell)
12052 "Expand a structure template."
12053 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12054 (rpl (nth (if musep 2 1) cell))
12055 (ind ""))
12056 (delete-region start (point))
12057 (when (string-match "\\`#\\+" rpl)
12058 (cond
12059 ((bolp))
12060 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12061 (setq ind (buffer-substring (point-at-bol) (point))))
12062 (t (newline))))
12063 (setq start (point))
12064 (if (string-match "%file" rpl)
12065 (setq rpl (replace-match
12066 (concat
12067 "\""
12068 (save-match-data
12069 (abbreviate-file-name (read-file-name "Include file: ")))
12070 "\"")
12071 t t rpl)))
12072 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12073 (concat "\n" ind)))
12074 (insert rpl)
12075 (if (re-search-backward "\\?" start t) (delete-char 1))))
12077 ;;;; TODO, DEADLINE, Comments
12079 (defun org-toggle-comment ()
12080 "Change the COMMENT state of an entry."
12081 (interactive)
12082 (save-excursion
12083 (org-back-to-heading)
12084 (let (case-fold-search)
12085 (cond
12086 ((looking-at (format org-heading-keyword-regexp-format
12087 org-comment-string))
12088 (goto-char (match-end 1))
12089 (looking-at (concat " +" org-comment-string))
12090 (replace-match "" t t)
12091 (when (eolp) (insert " ")))
12092 ((looking-at org-outline-regexp)
12093 (goto-char (match-end 0))
12094 (insert org-comment-string " "))))))
12096 (defvar org-last-todo-state-is-todo nil
12097 "This is non-nil when the last TODO state change led to a TODO state.
12098 If the last change removed the TODO tag or switched to DONE, then
12099 this is nil.")
12101 (defvar org-setting-tags nil) ; dynamically skipped
12103 (defvar org-todo-setup-filter-hook nil
12104 "Hook for functions that pre-filter todo specs.
12105 Each function takes a todo spec and returns either nil or the spec
12106 transformed into canonical form." )
12108 (defvar org-todo-get-default-hook nil
12109 "Hook for functions that get a default item for todo.
12110 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12111 nil or a string to be used for the todo mark." )
12113 (defvar org-agenda-headline-snapshot-before-repeat)
12115 (defun org-current-effective-time ()
12116 "Return current time adjusted for `org-extend-today-until' variable."
12117 (let* ((ct (org-current-time))
12118 (dct (decode-time ct))
12119 (ct1
12120 (cond
12121 (org-use-last-clock-out-time-as-effective-time
12122 (or (org-clock-get-last-clock-out-time) ct))
12123 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12124 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12125 (t ct))))
12126 ct1))
12128 (defun org-todo-yesterday (&optional arg)
12129 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12130 (interactive "P")
12131 (if (eq major-mode 'org-agenda-mode)
12132 (apply 'org-agenda-todo-yesterday arg)
12133 (let* ((hour (third (decode-time
12134 (org-current-time))))
12135 (org-extend-today-until (1+ hour)))
12136 (org-todo arg))))
12138 (defvar org-block-entry-blocking ""
12139 "First entry preventing the TODO state change.")
12141 (defun org-todo (&optional arg)
12142 "Change the TODO state of an item.
12143 The state of an item is given by a keyword at the start of the heading,
12144 like
12145 *** TODO Write paper
12146 *** DONE Call mom
12148 The different keywords are specified in the variable `org-todo-keywords'.
12149 By default the available states are \"TODO\" and \"DONE\".
12150 So for this example: when the item starts with TODO, it is changed to DONE.
12151 When it starts with DONE, the DONE is removed. And when neither TODO nor
12152 DONE are present, add TODO at the beginning of the heading.
12154 With \\[universal-argument] prefix arg, use completion to determine the new \
12155 state.
12156 With numeric prefix arg, switch to that state.
12157 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12158 keywords (nextset).
12159 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12160 With a numeric prefix arg of 0, inhibit note taking for the change.
12162 For calling through lisp, arg is also interpreted in the following way:
12163 'none -> empty state
12164 \"\"(empty string) -> switch to empty state
12165 'done -> switch to DONE
12166 'nextset -> switch to the next set of keywords
12167 'previousset -> switch to the previous set of keywords
12168 \"WAITING\" -> switch to the specified keyword, but only if it
12169 really is a member of `org-todo-keywords'."
12170 (interactive "P")
12171 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12172 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12173 'region-start-level 'region))
12174 org-loop-over-headlines-in-active-region)
12175 (org-map-entries
12176 `(org-todo ,arg)
12177 org-loop-over-headlines-in-active-region
12178 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12179 (if (equal arg '(16)) (setq arg 'nextset))
12180 (let ((org-blocker-hook org-blocker-hook)
12181 commentp
12182 case-fold-search)
12183 (when (equal arg '(64))
12184 (setq arg nil org-blocker-hook nil))
12185 (when (and org-blocker-hook
12186 (or org-inhibit-blocking
12187 (org-entry-get nil "NOBLOCKING")))
12188 (setq org-blocker-hook nil))
12189 (save-excursion
12190 (catch 'exit
12191 (org-back-to-heading t)
12192 (when (looking-at (concat "^\\*+ " org-comment-string))
12193 (org-toggle-comment)
12194 (setq commentp t))
12195 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12196 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12197 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12198 (let* ((match-data (match-data))
12199 (startpos (point-at-bol))
12200 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12201 (org-log-done org-log-done)
12202 (org-log-repeat org-log-repeat)
12203 (org-todo-log-states org-todo-log-states)
12204 (org-inhibit-logging
12205 (if (equal arg 0)
12206 (progn (setq arg nil) 'note) org-inhibit-logging))
12207 (this (match-string 1))
12208 (hl-pos (match-beginning 0))
12209 (head (org-get-todo-sequence-head this))
12210 (ass (assoc head org-todo-kwd-alist))
12211 (interpret (nth 1 ass))
12212 (done-word (nth 3 ass))
12213 (final-done-word (nth 4 ass))
12214 (org-last-state (or this ""))
12215 (completion-ignore-case t)
12216 (member (member this org-todo-keywords-1))
12217 (tail (cdr member))
12218 (org-state (cond
12219 ((and org-todo-key-trigger
12220 (or (and (equal arg '(4))
12221 (eq org-use-fast-todo-selection 'prefix))
12222 (and (not arg) org-use-fast-todo-selection
12223 (not (eq org-use-fast-todo-selection
12224 'prefix)))))
12225 ;; Use fast selection
12226 (org-fast-todo-selection))
12227 ((and (equal arg '(4))
12228 (or (not org-use-fast-todo-selection)
12229 (not org-todo-key-trigger)))
12230 ;; Read a state with completion
12231 (org-icompleting-read
12232 "State: " (mapcar 'list org-todo-keywords-1)
12233 nil t))
12234 ((eq arg 'right)
12235 (if this
12236 (if tail (car tail) nil)
12237 (car org-todo-keywords-1)))
12238 ((eq arg 'left)
12239 (if (equal member org-todo-keywords-1)
12241 (if this
12242 (nth (- (length org-todo-keywords-1)
12243 (length tail) 2)
12244 org-todo-keywords-1)
12245 (org-last org-todo-keywords-1))))
12246 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12247 (setq arg nil))) ; hack to fall back to cycling
12248 (arg
12249 ;; user or caller requests a specific state
12250 (cond
12251 ((equal arg "") nil)
12252 ((eq arg 'none) nil)
12253 ((eq arg 'done) (or done-word (car org-done-keywords)))
12254 ((eq arg 'nextset)
12255 (or (car (cdr (member head org-todo-heads)))
12256 (car org-todo-heads)))
12257 ((eq arg 'previousset)
12258 (let ((org-todo-heads (reverse org-todo-heads)))
12259 (or (car (cdr (member head org-todo-heads)))
12260 (car org-todo-heads))))
12261 ((car (member arg org-todo-keywords-1)))
12262 ((stringp arg)
12263 (user-error "State `%s' not valid in this file" arg))
12264 ((nth (1- (prefix-numeric-value arg))
12265 org-todo-keywords-1))))
12266 ((null member) (or head (car org-todo-keywords-1)))
12267 ((equal this final-done-word) nil) ;; -> make empty
12268 ((null tail) nil) ;; -> first entry
12269 ((memq interpret '(type priority))
12270 (if (eq this-command last-command)
12271 (car tail)
12272 (if (> (length tail) 0)
12273 (or done-word (car org-done-keywords))
12274 nil)))
12276 (car tail))))
12277 (org-state (or
12278 (run-hook-with-args-until-success
12279 'org-todo-get-default-hook org-state org-last-state)
12280 org-state))
12281 (next (if org-state (concat " " org-state " ") " "))
12282 (change-plist (list :type 'todo-state-change :from this :to org-state
12283 :position startpos))
12284 dolog now-done-p)
12285 (when org-blocker-hook
12286 (setq org-last-todo-state-is-todo
12287 (not (member this org-done-keywords)))
12288 (unless (save-excursion
12289 (save-match-data
12290 (org-with-wide-buffer
12291 (run-hook-with-args-until-failure
12292 'org-blocker-hook change-plist))))
12293 (if (org-called-interactively-p 'interactive)
12294 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12295 this org-state org-block-entry-blocking)
12296 ;; fail silently
12297 (message "TODO state change from %s to %s blocked (by \"%s\")"
12298 this org-state org-block-entry-blocking)
12299 (throw 'exit nil))))
12300 (store-match-data match-data)
12301 (replace-match next t t)
12302 (unless (pos-visible-in-window-p hl-pos)
12303 (message "TODO state changed to %s" (org-trim next)))
12304 (unless head
12305 (setq head (org-get-todo-sequence-head org-state)
12306 ass (assoc head org-todo-kwd-alist)
12307 interpret (nth 1 ass)
12308 done-word (nth 3 ass)
12309 final-done-word (nth 4 ass)))
12310 (when (memq arg '(nextset previousset))
12311 (message "Keyword-Set %d/%d: %s"
12312 (- (length org-todo-sets) -1
12313 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12314 (length org-todo-sets)
12315 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12316 (setq org-last-todo-state-is-todo
12317 (not (member org-state org-done-keywords)))
12318 (setq now-done-p (and (member org-state org-done-keywords)
12319 (not (member this org-done-keywords))))
12320 (and logging (org-local-logging logging))
12321 (when (and (or org-todo-log-states org-log-done)
12322 (not (eq org-inhibit-logging t))
12323 (not (memq arg '(nextset previousset))))
12324 ;; we need to look at recording a time and note
12325 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12326 (nth 2 (assoc this org-todo-log-states))))
12327 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12328 (setq dolog 'time))
12329 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12330 (and org-state
12331 (member org-state org-not-done-keywords)
12332 (not (member this org-not-done-keywords))))
12333 ;; This is now a todo state and was not one before
12334 ;; If there was a CLOSED time stamp, get rid of it.
12335 (org-add-planning-info nil nil 'closed))
12336 (when (and now-done-p org-log-done)
12337 ;; It is now done, and it was not done before
12338 (org-add-planning-info 'closed (org-current-effective-time))
12339 (if (and (not dolog) (eq 'note org-log-done))
12340 (org-add-log-setup 'done org-state this 'findpos 'note)))
12341 (when (and org-state dolog)
12342 ;; This is a non-nil state, and we need to log it
12343 (org-add-log-setup 'state org-state this 'findpos dolog)))
12344 ;; Fixup tag positioning
12345 (org-todo-trigger-tag-changes org-state)
12346 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12347 (when org-provide-todo-statistics
12348 (org-update-parent-todo-statistics))
12349 (run-hooks 'org-after-todo-state-change-hook)
12350 (if (and arg (not (member org-state org-done-keywords)))
12351 (setq head (org-get-todo-sequence-head org-state)))
12352 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12353 ;; Do we need to trigger a repeat?
12354 (when now-done-p
12355 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12356 ;; This is for the agenda, take a snapshot of the headline.
12357 (save-match-data
12358 (setq org-agenda-headline-snapshot-before-repeat
12359 (org-get-heading))))
12360 (org-auto-repeat-maybe org-state))
12361 ;; Fixup cursor location if close to the keyword
12362 (if (and (outline-on-heading-p)
12363 (not (bolp))
12364 (save-excursion (beginning-of-line 1)
12365 (looking-at org-todo-line-regexp))
12366 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12367 (progn
12368 (goto-char (or (match-end 2) (match-end 1)))
12369 (and (looking-at " ") (just-one-space))))
12370 (when org-trigger-hook
12371 (save-excursion
12372 (run-hook-with-args 'org-trigger-hook change-plist)))
12373 (when commentp (org-toggle-comment))))))))
12375 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12376 "Block turning an entry into a TODO, using the hierarchy.
12377 This checks whether the current task should be blocked from state
12378 changes. Such blocking occurs when:
12380 1. The task has children which are not all in a completed state.
12382 2. A task has a parent with the property :ORDERED:, and there
12383 are siblings prior to the current task with incomplete
12384 status.
12386 3. The parent of the task is blocked because it has siblings that should
12387 be done first, or is child of a block grandparent TODO entry."
12389 (if (not org-enforce-todo-dependencies)
12390 t ; if locally turned off don't block
12391 (catch 'dont-block
12392 ;; If this is not a todo state change, or if this entry is already DONE,
12393 ;; do not block
12394 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12395 (member (plist-get change-plist :from)
12396 (cons 'done org-done-keywords))
12397 (member (plist-get change-plist :to)
12398 (cons 'todo org-not-done-keywords))
12399 (not (plist-get change-plist :to)))
12400 (throw 'dont-block t))
12401 ;; If this task has children, and any are undone, it's blocked
12402 (save-excursion
12403 (org-back-to-heading t)
12404 (let ((this-level (funcall outline-level)))
12405 (outline-next-heading)
12406 (let ((child-level (funcall outline-level)))
12407 (while (and (not (eobp))
12408 (> child-level this-level))
12409 ;; this todo has children, check whether they are all
12410 ;; completed
12411 (if (and (not (org-entry-is-done-p))
12412 (org-entry-is-todo-p))
12413 (progn (setq org-block-entry-blocking (org-get-heading))
12414 (throw 'dont-block nil)))
12415 (outline-next-heading)
12416 (setq child-level (funcall outline-level))))))
12417 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12418 ;; any previous siblings are undone, it's blocked
12419 (save-excursion
12420 (org-back-to-heading t)
12421 (let* ((pos (point))
12422 (parent-pos (and (org-up-heading-safe) (point))))
12423 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12424 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12425 (forward-line 1)
12426 (re-search-forward org-not-done-heading-regexp pos t))
12427 (setq org-block-entry-blocking (match-string 0))
12428 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12429 ;; Search further up the hierarchy, to see if an ancestor is blocked
12430 (while t
12431 (goto-char parent-pos)
12432 (if (not (looking-at org-not-done-heading-regexp))
12433 (throw 'dont-block t)) ; do not block, parent is not a TODO
12434 (setq pos (point))
12435 (setq parent-pos (and (org-up-heading-safe) (point)))
12436 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12437 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12438 (forward-line 1)
12439 (re-search-forward org-not-done-heading-regexp pos t)
12440 (setq org-block-entry-blocking (org-get-heading)))
12441 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12443 (defcustom org-track-ordered-property-with-tag nil
12444 "Should the ORDERED property also be shown as a tag?
12445 The ORDERED property decides if an entry should require subtasks to be
12446 completed in sequence. Since a property is not very visible, setting
12447 this option means that toggling the ORDERED property with the command
12448 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12449 not relevant for the behavior, but it makes things more visible.
12451 Note that toggling the tag with tags commands will not change the property
12452 and therefore not influence behavior!
12454 This can be t, meaning the tag ORDERED should be used, It can also be a
12455 string to select a different tag for this task."
12456 :group 'org-todo
12457 :type '(choice
12458 (const :tag "No tracking" nil)
12459 (const :tag "Track with ORDERED tag" t)
12460 (string :tag "Use other tag")))
12462 (defun org-toggle-ordered-property ()
12463 "Toggle the ORDERED property of the current entry.
12464 For better visibility, you can track the value of this property with a tag.
12465 See variable `org-track-ordered-property-with-tag'."
12466 (interactive)
12467 (let* ((t1 org-track-ordered-property-with-tag)
12468 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12469 (save-excursion
12470 (org-back-to-heading)
12471 (if (org-entry-get nil "ORDERED")
12472 (progn
12473 (org-delete-property "ORDERED" "PROPERTIES")
12474 (and tag (org-toggle-tag tag 'off))
12475 (message "Subtasks can be completed in arbitrary order"))
12476 (org-entry-put nil "ORDERED" "t")
12477 (and tag (org-toggle-tag tag 'on))
12478 (message "Subtasks must be completed in sequence")))))
12480 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12481 (defun org-block-todo-from-checkboxes (change-plist)
12482 "Block turning an entry into a TODO, using checkboxes.
12483 This checks whether the current task should be blocked from state
12484 changes because there are unchecked boxes in this entry."
12485 (if (not org-enforce-todo-checkbox-dependencies)
12486 t ; if locally turned off don't block
12487 (catch 'dont-block
12488 ;; If this is not a todo state change, or if this entry is already DONE,
12489 ;; do not block
12490 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12491 (member (plist-get change-plist :from)
12492 (cons 'done org-done-keywords))
12493 (member (plist-get change-plist :to)
12494 (cons 'todo org-not-done-keywords))
12495 (not (plist-get change-plist :to)))
12496 (throw 'dont-block t))
12497 ;; If this task has checkboxes that are not checked, it's blocked
12498 (save-excursion
12499 (org-back-to-heading t)
12500 (let ((beg (point)) end)
12501 (outline-next-heading)
12502 (setq end (point))
12503 (goto-char beg)
12504 (if (org-list-search-forward
12505 (concat (org-item-beginning-re)
12506 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12507 "\\[[- ]\\]")
12508 end t)
12509 (progn
12510 (if (boundp 'org-blocked-by-checkboxes)
12511 (setq org-blocked-by-checkboxes t))
12512 (throw 'dont-block nil)))))
12513 t))) ; do not block
12515 (defun org-entry-blocked-p ()
12516 "Is the current entry blocked?"
12517 (org-with-silent-modifications
12518 (if (org-entry-get nil "NOBLOCKING")
12519 nil ;; Never block this entry
12520 (not (run-hook-with-args-until-failure
12521 'org-blocker-hook
12522 (list :type 'todo-state-change
12523 :position (point)
12524 :from 'todo
12525 :to 'done))))))
12527 (defun org-update-statistics-cookies (all)
12528 "Update the statistics cookie, either from TODO or from checkboxes.
12529 This should be called with the cursor in a line with a statistics cookie."
12530 (interactive "P")
12531 (if all
12532 (progn
12533 (org-update-checkbox-count 'all)
12534 (org-map-entries 'org-update-parent-todo-statistics))
12535 (if (not (org-at-heading-p))
12536 (org-update-checkbox-count)
12537 (let ((pos (point-marker))
12538 end l1 l2)
12539 (ignore-errors (org-back-to-heading t))
12540 (if (not (org-at-heading-p))
12541 (org-update-checkbox-count)
12542 (setq l1 (org-outline-level))
12543 (setq end (save-excursion
12544 (outline-next-heading)
12545 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12546 (point)))
12547 (if (and (save-excursion
12548 (re-search-forward
12549 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12550 (not (save-excursion (re-search-forward
12551 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12552 (org-update-checkbox-count)
12553 (if (and l2 (> l2 l1))
12554 (progn
12555 (goto-char end)
12556 (org-update-parent-todo-statistics))
12557 (goto-char pos)
12558 (beginning-of-line 1)
12559 (while (re-search-forward
12560 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12561 (point-at-eol) t)
12562 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12563 (goto-char pos)
12564 (move-marker pos nil)))))
12566 (defvar org-entry-property-inherited-from) ;; defined below
12567 (defun org-update-parent-todo-statistics ()
12568 "Update any statistics cookie in the parent of the current headline.
12569 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12570 the entire subtree and this will travel up the hierarchy and update
12571 statistics everywhere."
12572 (let* ((prop (save-excursion (org-up-heading-safe)
12573 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12574 (recursive (or (not org-hierarchical-todo-statistics)
12575 (and prop (string-match "\\<recursive\\>" prop))))
12576 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12578 (first t)
12579 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12580 level ltoggle l1 new ndel
12581 (cnt-all 0) (cnt-done 0) is-percent kwd
12582 checkbox-beg ov ovs ove cookie-present)
12583 (catch 'exit
12584 (save-excursion
12585 (beginning-of-line 1)
12586 (setq ltoggle (funcall outline-level))
12587 ;; Three situations are to consider:
12589 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12590 ;; to the top-level ancestor on the headline;
12592 ;; 2. If parent has "recursive" property, repeat up to the
12593 ;; headline setting that property, taking inheritance into
12594 ;; account;
12596 ;; 3. Else, move up to direct parent and proceed only once.
12597 (while (and (setq level (org-up-heading-safe))
12598 (or recursive first)
12599 (>= (point) lim))
12600 (setq first nil cookie-present nil)
12601 (unless (and level
12602 (not (string-match
12603 "\\<checkbox\\>"
12604 (downcase (or (org-entry-get nil "COOKIE_DATA")
12605 "")))))
12606 (throw 'exit nil))
12607 (while (re-search-forward box-re (point-at-eol) t)
12608 (setq cnt-all 0 cnt-done 0 cookie-present t)
12609 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12610 (save-match-data
12611 (unless (outline-next-heading) (throw 'exit nil))
12612 (while (and (looking-at org-complex-heading-regexp)
12613 (> (setq l1 (length (match-string 1))) level))
12614 (setq kwd (and (or recursive (= l1 ltoggle))
12615 (match-string 2)))
12616 (if (or (eq org-provide-todo-statistics 'all-headlines)
12617 (and (listp org-provide-todo-statistics)
12618 (or (member kwd org-provide-todo-statistics)
12619 (member kwd org-done-keywords))))
12620 (setq cnt-all (1+ cnt-all))
12621 (if (eq org-provide-todo-statistics t)
12622 (and kwd (setq cnt-all (1+ cnt-all)))))
12623 (and (member kwd org-done-keywords)
12624 (setq cnt-done (1+ cnt-done)))
12625 (outline-next-heading)))
12626 (setq new
12627 (if is-percent
12628 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12629 (format "[%d/%d]" cnt-done cnt-all))
12630 ndel (- (match-end 0) checkbox-beg))
12631 ;; handle overlays when updating cookie from column view
12632 (when (setq ov (car (overlays-at checkbox-beg)))
12633 (setq ovs (overlay-start ov) ove (overlay-end ov))
12634 (delete-overlay ov))
12635 (goto-char checkbox-beg)
12636 (insert new)
12637 (delete-region (point) (+ (point) ndel))
12638 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12639 (when ov (move-overlay ov ovs ove)))
12640 (when cookie-present
12641 (run-hook-with-args 'org-after-todo-statistics-hook
12642 cnt-done (- cnt-all cnt-done))))))
12643 (run-hooks 'org-todo-statistics-hook)))
12645 (defvar org-after-todo-statistics-hook nil
12646 "Hook that is called after a TODO statistics cookie has been updated.
12647 Each function is called with two arguments: the number of not-done entries
12648 and the number of done entries.
12650 For example, the following function, when added to this hook, will switch
12651 an entry to DONE when all children are done, and back to TODO when new
12652 entries are set to a TODO status. Note that this hook is only called
12653 when there is a statistics cookie in the headline!
12655 (defun org-summary-todo (n-done n-not-done)
12656 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12657 (let (org-log-done org-log-states) ; turn off logging
12658 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12661 (defvar org-todo-statistics-hook nil
12662 "Hook that is run whenever Org thinks TODO statistics should be updated.
12663 This hook runs even if there is no statistics cookie present, in which case
12664 `org-after-todo-statistics-hook' would not run.")
12666 (defun org-todo-trigger-tag-changes (state)
12667 "Apply the changes defined in `org-todo-state-tags-triggers'."
12668 (let ((l org-todo-state-tags-triggers)
12669 changes)
12670 (when (or (not state) (equal state ""))
12671 (setq changes (append changes (cdr (assoc "" l)))))
12672 (when (and (stringp state) (> (length state) 0))
12673 (setq changes (append changes (cdr (assoc state l)))))
12674 (when (member state org-not-done-keywords)
12675 (setq changes (append changes (cdr (assoc 'todo l)))))
12676 (when (member state org-done-keywords)
12677 (setq changes (append changes (cdr (assoc 'done l)))))
12678 (dolist (c changes)
12679 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12681 (defun org-local-logging (value)
12682 "Get logging settings from a property VALUE."
12683 (let* (words w a)
12684 ;; directly set the variables, they are already local.
12685 (setq org-log-done nil
12686 org-log-repeat nil
12687 org-todo-log-states nil)
12688 (setq words (org-split-string value))
12689 (while (setq w (pop words))
12690 (cond
12691 ((setq a (assoc w org-startup-options))
12692 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12693 (set (nth 1 a) (nth 2 a))))
12694 ((setq a (org-extract-log-state-settings w))
12695 (and (member (car a) org-todo-keywords-1)
12696 (push a org-todo-log-states)))))))
12698 (defun org-get-todo-sequence-head (kwd)
12699 "Return the head of the TODO sequence to which KWD belongs.
12700 If KWD is not set, check if there is a text property remembering the
12701 right sequence."
12702 (let (p)
12703 (cond
12704 ((not kwd)
12705 (or (get-text-property (point-at-bol) 'org-todo-head)
12706 (progn
12707 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12708 nil (point-at-eol)))
12709 (get-text-property p 'org-todo-head))))
12710 ((not (member kwd org-todo-keywords-1))
12711 (car org-todo-keywords-1))
12712 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12714 (defun org-fast-todo-selection ()
12715 "Fast TODO keyword selection with single keys.
12716 Returns the new TODO keyword, or nil if no state change should occur."
12717 (let* ((fulltable org-todo-key-alist)
12718 (done-keywords org-done-keywords) ;; needed for the faces.
12719 (maxlen (apply 'max (mapcar
12720 (lambda (x)
12721 (if (stringp (car x)) (string-width (car x)) 0))
12722 fulltable)))
12723 (expert nil)
12724 (fwidth (+ maxlen 3 1 3))
12725 (ncol (/ (- (window-width) 4) fwidth))
12726 tg cnt e c tbl
12727 groups ingroup)
12728 (save-excursion
12729 (save-window-excursion
12730 (if expert
12731 (set-buffer (get-buffer-create " *Org todo*"))
12732 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12733 (erase-buffer)
12734 (org-set-local 'org-done-keywords done-keywords)
12735 (setq tbl fulltable cnt 0)
12736 (while (setq e (pop tbl))
12737 (cond
12738 ((equal e '(:startgroup))
12739 (push '() groups) (setq ingroup t)
12740 (when (not (= cnt 0))
12741 (setq cnt 0)
12742 (insert "\n"))
12743 (insert "{ "))
12744 ((equal e '(:endgroup))
12745 (setq ingroup nil cnt 0)
12746 (insert "}\n"))
12747 ((equal e '(:newline))
12748 (when (not (= cnt 0))
12749 (setq cnt 0)
12750 (insert "\n")
12751 (setq e (car tbl))
12752 (while (equal (car tbl) '(:newline))
12753 (insert "\n")
12754 (setq tbl (cdr tbl)))))
12756 (setq tg (car e) c (cdr e))
12757 (if ingroup (push tg (car groups)))
12758 (setq tg (org-add-props tg nil 'face
12759 (org-get-todo-face tg)))
12760 (if (and (= cnt 0) (not ingroup)) (insert " "))
12761 (insert "[" c "] " tg (make-string
12762 (- fwidth 4 (length tg)) ?\ ))
12763 (when (= (setq cnt (1+ cnt)) ncol)
12764 (insert "\n")
12765 (if ingroup (insert " "))
12766 (setq cnt 0)))))
12767 (insert "\n")
12768 (goto-char (point-min))
12769 (if (not expert) (org-fit-window-to-buffer))
12770 (message "[a-z..]:Set [SPC]:clear")
12771 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12772 (cond
12773 ((or (= c ?\C-g)
12774 (and (= c ?q) (not (rassoc c fulltable))))
12775 (setq quit-flag t))
12776 ((= c ?\ ) nil)
12777 ((setq e (rassoc c fulltable) tg (car e))
12779 (t (setq quit-flag t)))))))
12781 (defun org-entry-is-todo-p ()
12782 (member (org-get-todo-state) org-not-done-keywords))
12784 (defun org-entry-is-done-p ()
12785 (member (org-get-todo-state) org-done-keywords))
12787 (defun org-get-todo-state ()
12788 "Return the TODO keyword of the current subtree."
12789 (save-excursion
12790 (org-back-to-heading t)
12791 (and (looking-at org-todo-line-regexp)
12792 (match-end 2)
12793 (match-string 2))))
12795 (defun org-at-date-range-p (&optional inactive-ok)
12796 "Is the cursor inside a date range?"
12797 (interactive)
12798 (save-excursion
12799 (catch 'exit
12800 (let ((pos (point)))
12801 (skip-chars-backward "^[<\r\n")
12802 (skip-chars-backward "<[")
12803 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12804 (>= (match-end 0) pos)
12805 (throw 'exit t))
12806 (skip-chars-backward "^<[\r\n")
12807 (skip-chars-backward "<[")
12808 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12809 (>= (match-end 0) pos)
12810 (throw 'exit t)))
12811 nil)))
12813 (defun org-get-repeat (&optional tagline)
12814 "Check if there is a deadline/schedule with repeater in this entry."
12815 (save-match-data
12816 (save-excursion
12817 (org-back-to-heading t)
12818 (and (re-search-forward (if tagline
12819 (concat tagline "\\s-*" org-repeat-re)
12820 org-repeat-re)
12821 (org-entry-end-position) t)
12822 (match-string-no-properties 1)))))
12824 (defvar org-last-changed-timestamp)
12825 (defvar org-last-inserted-timestamp)
12826 (defvar org-log-post-message)
12827 (defvar org-log-note-purpose)
12828 (defvar org-log-note-how)
12829 (defvar org-log-note-extra)
12830 (defun org-auto-repeat-maybe (done-word)
12831 "Check if the current headline contains a repeated deadline/schedule.
12832 If yes, set TODO state back to what it was and change the base date
12833 of repeating deadline/scheduled time stamps to new date.
12834 This function is run automatically after each state change to a DONE state."
12835 ;; last-state is dynamically scoped into this function
12836 (let* ((repeat (org-get-repeat))
12837 (aa (assoc org-last-state org-todo-kwd-alist))
12838 (interpret (nth 1 aa))
12839 (head (nth 2 aa))
12840 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12841 (msg "Entry repeats: ")
12842 (org-log-done nil)
12843 (org-todo-log-states nil)
12844 re type n what ts time to-state)
12845 (when repeat
12846 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12847 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12848 org-todo-repeat-to-state))
12849 (unless (and to-state (member to-state org-todo-keywords-1))
12850 (setq to-state (if (eq interpret 'type) org-last-state head)))
12851 (org-todo to-state)
12852 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12853 (org-entry-put nil "LAST_REPEAT" (format-time-string
12854 (org-time-stamp-format t t))))
12855 (when org-log-repeat
12856 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12857 (memq 'org-add-log-note post-command-hook))
12858 ;; OK, we are already setup for some record
12859 (if (eq org-log-repeat 'note)
12860 ;; make sure we take a note, not only a time stamp
12861 (setq org-log-note-how 'note))
12862 ;; Set up for taking a record
12863 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12864 org-last-state
12865 'findpos org-log-repeat)))
12866 (org-back-to-heading t)
12867 (org-add-planning-info nil nil 'closed)
12868 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12869 org-deadline-time-regexp "\\)\\|\\("
12870 org-ts-regexp "\\)"))
12871 (while (re-search-forward
12872 re (save-excursion (outline-next-heading) (point)) t)
12873 (setq type (if (match-end 1) org-scheduled-string
12874 (if (match-end 3) org-deadline-string "Plain:"))
12875 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12876 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12877 (setq n (string-to-number (match-string 2 ts))
12878 what (match-string 3 ts))
12879 (if (equal what "w") (setq n (* n 7) what "d"))
12880 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12881 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12882 ;; Preparation, see if we need to modify the start date for the change
12883 (when (match-end 1)
12884 (setq time (save-match-data (org-time-string-to-time ts)))
12885 (cond
12886 ((equal (match-string 1 ts) ".")
12887 ;; Shift starting date to today
12888 (org-timestamp-change
12889 (- (org-today) (time-to-days time))
12890 'day))
12891 ((equal (match-string 1 ts) "+")
12892 (let ((nshiftmax 10) (nshift 0))
12893 (while (or (= nshift 0)
12894 (<= (time-to-days time)
12895 (time-to-days (current-time))))
12896 (when (= (incf nshift) nshiftmax)
12897 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12898 (error "Abort")))
12899 (org-timestamp-change n (cdr (assoc what whata)))
12900 (org-at-timestamp-p t)
12901 (setq ts (match-string 1))
12902 (setq time (save-match-data (org-time-string-to-time ts)))))
12903 (org-timestamp-change (- n) (cdr (assoc what whata)))
12904 ;; rematch, so that we have everything in place for the real shift
12905 (org-at-timestamp-p t)
12906 (setq ts (match-string 1))
12907 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12908 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12909 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12910 (setq org-log-post-message msg)
12911 (message "%s" msg))))
12913 (defun org-show-todo-tree (arg)
12914 "Make a compact tree which shows all headlines marked with TODO.
12915 The tree will show the lines where the regexp matches, and all higher
12916 headlines above the match.
12917 With a \\[universal-argument] prefix, prompt for a regexp to match.
12918 With a numeric prefix N, construct a sparse tree for the Nth element
12919 of `org-todo-keywords-1'."
12920 (interactive "P")
12921 (let ((case-fold-search nil)
12922 (kwd-re
12923 (cond ((null arg) org-not-done-regexp)
12924 ((equal arg '(4))
12925 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12926 (mapcar 'list org-todo-keywords-1))))
12927 (concat "\\("
12928 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12929 "\\)\\>")))
12930 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12931 (regexp-quote (nth (1- (prefix-numeric-value arg))
12932 org-todo-keywords-1)))
12933 (t (user-error "Invalid prefix argument: %s" arg)))))
12934 (message "%d TODO entries found"
12935 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12937 (defun org-deadline (arg &optional time)
12938 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12939 With one universal prefix argument, remove any deadline from the item.
12940 With two universal prefix arguments, prompt for a warning delay.
12941 With argument TIME, set the deadline at the corresponding date. TIME
12942 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12943 (interactive "P")
12944 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12945 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12946 'region-start-level 'region))
12947 org-loop-over-headlines-in-active-region)
12948 (org-map-entries
12949 `(org-deadline ',arg ,time)
12950 org-loop-over-headlines-in-active-region
12951 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12952 (let* ((old-date (org-entry-get nil "DEADLINE"))
12953 (old-date-time (if old-date (org-time-string-to-time old-date)))
12954 (repeater (and old-date
12955 (string-match
12956 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12957 old-date)
12958 (match-string 1 old-date))))
12959 (cond
12960 ((equal arg '(4))
12961 (when (and old-date org-log-redeadline)
12962 (org-add-log-setup 'deldeadline nil old-date 'findpos
12963 org-log-redeadline))
12964 (org-remove-timestamp-with-keyword org-deadline-string)
12965 (message "Item no longer has a deadline."))
12966 ((equal arg '(16))
12967 (save-excursion
12968 (org-back-to-heading t)
12969 (if (re-search-forward
12970 org-deadline-time-regexp
12971 (save-excursion (outline-next-heading) (point)) t)
12972 (let* ((rpl0 (match-string 1))
12973 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12974 (replace-match
12975 (concat org-deadline-string
12976 " <" rpl
12977 (format " -%dd"
12978 (abs
12979 (- (time-to-days
12980 (save-match-data
12981 (org-read-date nil t nil "Warn starting from" old-date-time)))
12982 (time-to-days old-date-time))))
12983 ">") t t))
12984 (user-error "No deadline information to update"))))
12986 (org-add-planning-info 'deadline time 'closed)
12987 (when (and old-date org-log-redeadline
12988 (not (equal old-date
12989 (substring org-last-inserted-timestamp 1 -1))))
12990 (org-add-log-setup 'redeadline nil old-date 'findpos
12991 org-log-redeadline))
12992 (when repeater
12993 (save-excursion
12994 (org-back-to-heading t)
12995 (when (re-search-forward (concat org-deadline-string " "
12996 org-last-inserted-timestamp)
12997 (save-excursion
12998 (outline-next-heading) (point)) t)
12999 (goto-char (1- (match-end 0)))
13000 (insert " " repeater)
13001 (setq org-last-inserted-timestamp
13002 (concat (substring org-last-inserted-timestamp 0 -1)
13003 " " repeater
13004 (substring org-last-inserted-timestamp -1))))))
13005 (message "Deadline on %s" org-last-inserted-timestamp))))))
13007 (defun org-schedule (arg &optional time)
13008 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13009 With one universal prefix argument, remove any scheduling date from the item.
13010 With two universal prefix arguments, prompt for a delay cookie.
13011 With argument TIME, scheduled at the corresponding date. TIME can
13012 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13013 (interactive "P")
13014 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13015 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13016 'region-start-level 'region))
13017 org-loop-over-headlines-in-active-region)
13018 (org-map-entries
13019 `(org-schedule ',arg ,time)
13020 org-loop-over-headlines-in-active-region
13021 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13022 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13023 (old-date-time (if old-date (org-time-string-to-time old-date)))
13024 (repeater (and old-date
13025 (string-match
13026 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13027 old-date)
13028 (match-string 1 old-date))))
13029 (cond
13030 ((equal arg '(4))
13031 (progn
13032 (when (and old-date org-log-reschedule)
13033 (org-add-log-setup 'delschedule nil old-date 'findpos
13034 org-log-reschedule))
13035 (org-remove-timestamp-with-keyword org-scheduled-string)
13036 (message "Item is no longer scheduled.")))
13037 ((equal arg '(16))
13038 (save-excursion
13039 (org-back-to-heading t)
13040 (if (re-search-forward
13041 org-scheduled-time-regexp
13042 (save-excursion (outline-next-heading) (point)) t)
13043 (let* ((rpl0 (match-string 1))
13044 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13045 (replace-match
13046 (concat org-scheduled-string
13047 " <" rpl
13048 (format " -%dd"
13049 (abs
13050 (- (time-to-days
13051 (save-match-data
13052 (org-read-date nil t nil "Delay until" old-date-time)))
13053 (time-to-days old-date-time))))
13054 ">") t t))
13055 (user-error "No scheduled information to update"))))
13057 (org-add-planning-info 'scheduled time 'closed)
13058 (when (and old-date org-log-reschedule
13059 (not (equal old-date
13060 (substring org-last-inserted-timestamp 1 -1))))
13061 (org-add-log-setup 'reschedule nil old-date 'findpos
13062 org-log-reschedule))
13063 (when repeater
13064 (save-excursion
13065 (org-back-to-heading t)
13066 (when (re-search-forward (concat org-scheduled-string " "
13067 org-last-inserted-timestamp)
13068 (save-excursion
13069 (outline-next-heading) (point)) t)
13070 (goto-char (1- (match-end 0)))
13071 (insert " " repeater)
13072 (setq org-last-inserted-timestamp
13073 (concat (substring org-last-inserted-timestamp 0 -1)
13074 " " repeater
13075 (substring org-last-inserted-timestamp -1))))))
13076 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13078 (defun org-get-scheduled-time (pom &optional inherit)
13079 "Get the scheduled time as a time tuple, of a format suitable
13080 for calling org-schedule with, or if there is no scheduling,
13081 returns nil."
13082 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13083 (when time
13084 (apply 'encode-time (org-parse-time-string time)))))
13086 (defun org-get-deadline-time (pom &optional inherit)
13087 "Get the deadline as a time tuple, of a format suitable for
13088 calling org-deadline with, or if there is no scheduling, returns
13089 nil."
13090 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13091 (when time
13092 (apply 'encode-time (org-parse-time-string time)))))
13094 (defun org-remove-timestamp-with-keyword (keyword)
13095 "Remove all time stamps with KEYWORD in the current entry."
13096 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13097 beg)
13098 (save-excursion
13099 (org-back-to-heading t)
13100 (setq beg (point))
13101 (outline-next-heading)
13102 (while (re-search-backward re beg t)
13103 (replace-match "")
13104 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13105 (equal (char-before) ?\ ))
13106 (backward-delete-char 1)
13107 (if (string-match "^[ \t]*$" (buffer-substring
13108 (point-at-bol) (point-at-eol)))
13109 (delete-region (point-at-bol)
13110 (min (point-max) (1+ (point-at-eol))))))))))
13112 (defvar org-time-was-given) ; dynamically scoped parameter
13113 (defvar org-end-time-was-given) ; dynamically scoped parameter
13115 (defun org-add-planning-info (what &optional time &rest remove)
13116 "Insert new timestamp with keyword in the line directly after the headline.
13117 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13118 If non is given, the user is prompted for a date.
13119 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13120 be removed."
13121 (interactive)
13122 (let (org-time-was-given org-end-time-was-given ts
13123 end default-time default-input)
13125 (catch 'exit
13126 (when (and (memq what '(scheduled deadline))
13127 (or (not time)
13128 (and (stringp time)
13129 (string-match "^[-+]+[0-9]" time))))
13130 ;; Try to get a default date/time from existing timestamp
13131 (save-excursion
13132 (org-back-to-heading t)
13133 (setq end (save-excursion (outline-next-heading) (point)))
13134 (when (re-search-forward (if (eq what 'scheduled)
13135 org-scheduled-time-regexp
13136 org-deadline-time-regexp)
13137 end t)
13138 (setq ts (match-string 1)
13139 default-time
13140 (apply 'encode-time (org-parse-time-string ts))
13141 default-input (and ts (org-get-compact-tod ts))))))
13142 (when what
13143 (setq time
13144 (if (stringp time)
13145 ;; This is a string (relative or absolute), set proper date
13146 (apply 'encode-time
13147 (org-read-date-analyze
13148 time default-time (decode-time default-time)))
13149 ;; If necessary, get the time from the user
13150 (or time (org-read-date nil 'to-time nil nil
13151 default-time default-input)))))
13153 (when (and org-insert-labeled-timestamps-at-point
13154 (member what '(scheduled deadline)))
13155 (insert
13156 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13157 (org-insert-time-stamp time org-time-was-given
13158 nil nil nil (list org-end-time-was-given))
13159 (setq what nil))
13160 (save-excursion
13161 (save-restriction
13162 (let (col list elt ts buffer-invisibility-spec)
13163 (org-back-to-heading t)
13164 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13165 (goto-char (match-end 1))
13166 (setq col (current-column))
13167 (goto-char (match-end 0))
13168 (if (eobp) (insert "\n") (forward-char 1))
13169 (when (and (not what)
13170 (not (looking-at
13171 (concat "[ \t]*"
13172 org-keyword-time-not-clock-regexp))))
13173 ;; Nothing to add, nothing to remove...... :-)
13174 (throw 'exit nil))
13175 (if (and (not (looking-at org-outline-regexp))
13176 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13177 "[^\r\n]*"))
13178 (not (equal (match-string 1) org-clock-string)))
13179 (narrow-to-region (match-beginning 0) (match-end 0))
13180 (insert-before-markers "\n")
13181 (backward-char 1)
13182 (narrow-to-region (point) (point))
13183 (and org-adapt-indentation (org-indent-to-column col)))
13184 ;; Check if we have to remove something.
13185 (setq list (cons what remove))
13186 (while list
13187 (setq elt (pop list))
13188 (when (or (and (eq elt 'scheduled)
13189 (re-search-forward org-scheduled-time-regexp nil t))
13190 (and (eq elt 'deadline)
13191 (re-search-forward org-deadline-time-regexp nil t))
13192 (and (eq elt 'closed)
13193 (re-search-forward org-closed-time-regexp nil t)))
13194 (replace-match "")
13195 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13196 (and (looking-at "[ \t]+") (replace-match ""))
13197 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13198 (when what
13199 (insert
13200 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13201 (cond ((eq what 'scheduled) org-scheduled-string)
13202 ((eq what 'deadline) org-deadline-string)
13203 ((eq what 'closed) org-closed-string))
13204 " ")
13205 (setq ts (org-insert-time-stamp
13206 time
13207 (or org-time-was-given
13208 (and (eq what 'closed) org-log-done-with-time))
13209 (eq what 'closed)
13210 nil nil (list org-end-time-was-given)))
13211 (insert
13212 (if (not (or (bolp) (eq (char-before) ?\ )
13213 (memq (char-after) '(32 10))
13214 (eobp))) " " ""))
13215 (end-of-line 1))
13216 (goto-char (point-min))
13217 (widen)
13218 (if (and (looking-at "[ \t]*\n")
13219 (equal (char-before) ?\n))
13220 (delete-region (1- (point)) (point-at-eol)))
13221 ts))))))
13223 (defvar org-log-note-marker (make-marker))
13224 (defvar org-log-note-purpose nil)
13225 (defvar org-log-note-state nil)
13226 (defvar org-log-note-previous-state nil)
13227 (defvar org-log-note-how nil)
13228 (defvar org-log-note-extra nil)
13229 (defvar org-log-note-window-configuration nil)
13230 (defvar org-log-note-return-to (make-marker))
13231 (defvar org-log-note-effective-time nil
13232 "Remembered current time so that dynamically scoped
13233 `org-extend-today-until' affects tha timestamps in state change
13234 log")
13236 (defvar org-log-post-message nil
13237 "Message to be displayed after a log note has been stored.
13238 The auto-repeater uses this.")
13240 (defun org-add-note ()
13241 "Add a note to the current entry.
13242 This is done in the same way as adding a state change note."
13243 (interactive)
13244 (org-add-log-setup 'note nil nil 'findpos nil))
13246 (defvar org-property-end-re)
13247 (defun org-add-log-setup (&optional purpose state prev-state
13248 findpos how extra)
13249 "Set up the post command hook to take a note.
13250 If this is about to TODO state change, the new state is expected in STATE.
13251 When FINDPOS is non-nil, find the correct position for the note in
13252 the current entry. If not, assume that it can be inserted at point.
13253 HOW is an indicator what kind of note should be created.
13254 EXTRA is additional text that will be inserted into the notes buffer."
13255 (let* ((org-log-into-drawer (org-log-into-drawer))
13256 (drawer (cond ((stringp org-log-into-drawer)
13257 org-log-into-drawer)
13258 (org-log-into-drawer "LOGBOOK"))))
13259 (save-restriction
13260 (save-excursion
13261 (when findpos
13262 (org-back-to-heading t)
13263 (narrow-to-region (point) (save-excursion
13264 (outline-next-heading) (point)))
13265 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13266 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13267 "[^\r\n]*\\)?"))
13268 (goto-char (match-end 0))
13269 (cond
13270 (drawer
13271 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13272 nil t)
13273 (progn
13274 (goto-char (match-end 0))
13275 (or org-log-states-order-reversed
13276 (and (re-search-forward org-property-end-re nil t)
13277 (goto-char (1- (match-beginning 0))))))
13278 (insert "\n:" drawer ":\n:END:")
13279 (beginning-of-line 0)
13280 (org-indent-line)
13281 (beginning-of-line 2)
13282 (org-indent-line)
13283 (end-of-line 0)))
13284 ((and org-log-state-notes-insert-after-drawers
13285 (save-excursion
13286 (forward-line) (looking-at org-drawer-regexp)))
13287 (forward-line)
13288 (while (looking-at org-drawer-regexp)
13289 (goto-char (match-end 0))
13290 (re-search-forward org-property-end-re (point-max) t)
13291 (forward-line))
13292 (forward-line -1)))
13293 (unless org-log-states-order-reversed
13294 (and (= (char-after) ?\n) (forward-char 1))
13295 (org-skip-over-state-notes)
13296 (skip-chars-backward " \t\n\r")))
13297 (move-marker org-log-note-marker (point))
13298 (setq org-log-note-purpose purpose
13299 org-log-note-state state
13300 org-log-note-previous-state prev-state
13301 org-log-note-how how
13302 org-log-note-extra extra
13303 org-log-note-effective-time (org-current-effective-time))
13304 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13306 (defun org-skip-over-state-notes ()
13307 "Skip past the list of State notes in an entry."
13308 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13309 (when (ignore-errors (goto-char (org-in-item-p)))
13310 (let* ((struct (org-list-struct))
13311 (prevs (org-list-prevs-alist struct)))
13312 (while (looking-at "[ \t]*- State")
13313 (goto-char (or (org-list-get-next-item (point) struct prevs)
13314 (org-list-get-item-end (point) struct)))))))
13316 (defun org-add-log-note (&optional purpose)
13317 "Pop up a window for taking a note, and add this note later at point."
13318 (remove-hook 'post-command-hook 'org-add-log-note)
13319 (setq org-log-note-window-configuration (current-window-configuration))
13320 (delete-other-windows)
13321 (move-marker org-log-note-return-to (point))
13322 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13323 (goto-char org-log-note-marker)
13324 (org-switch-to-buffer-other-window "*Org Note*")
13325 (erase-buffer)
13326 (if (memq org-log-note-how '(time state))
13327 (let (current-prefix-arg) (org-store-log-note))
13328 (let ((org-inhibit-startup t)) (org-mode))
13329 (insert (format "# Insert note for %s.
13330 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13331 (cond
13332 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13333 ((eq org-log-note-purpose 'done) "closed todo item")
13334 ((eq org-log-note-purpose 'state)
13335 (format "state change from \"%s\" to \"%s\""
13336 (or org-log-note-previous-state "")
13337 (or org-log-note-state "")))
13338 ((eq org-log-note-purpose 'reschedule)
13339 "rescheduling")
13340 ((eq org-log-note-purpose 'delschedule)
13341 "no longer scheduled")
13342 ((eq org-log-note-purpose 'redeadline)
13343 "changing deadline")
13344 ((eq org-log-note-purpose 'deldeadline)
13345 "removing deadline")
13346 ((eq org-log-note-purpose 'refile)
13347 "refiling")
13348 ((eq org-log-note-purpose 'note)
13349 "this entry")
13350 (t (error "This should not happen")))))
13351 (if org-log-note-extra (insert org-log-note-extra))
13352 (org-set-local 'org-finish-function 'org-store-log-note)
13353 (run-hooks 'org-log-buffer-setup-hook)))
13355 (defvar org-note-abort nil) ; dynamically scoped
13356 (defun org-store-log-note ()
13357 "Finish taking a log note, and insert it to where it belongs."
13358 (let ((txt (buffer-string)))
13359 (kill-buffer (current-buffer))
13360 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13361 lines ind bul)
13362 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13363 (setq txt (replace-match "" t t txt)))
13364 (if (string-match "\\s-+\\'" txt)
13365 (setq txt (replace-match "" t t txt)))
13366 (setq lines (org-split-string txt "\n"))
13367 (when (and note (string-match "\\S-" note))
13368 (setq note
13369 (org-replace-escapes
13370 note
13371 (list (cons "%u" (user-login-name))
13372 (cons "%U" user-full-name)
13373 (cons "%t" (format-time-string
13374 (org-time-stamp-format 'long 'inactive)
13375 org-log-note-effective-time))
13376 (cons "%T" (format-time-string
13377 (org-time-stamp-format 'long nil)
13378 org-log-note-effective-time))
13379 (cons "%d" (format-time-string
13380 (org-time-stamp-format nil 'inactive)
13381 org-log-note-effective-time))
13382 (cons "%D" (format-time-string
13383 (org-time-stamp-format nil nil)
13384 org-log-note-effective-time))
13385 (cons "%s" (if org-log-note-state
13386 (concat "\"" org-log-note-state "\"")
13387 ""))
13388 (cons "%S" (if org-log-note-previous-state
13389 (concat "\"" org-log-note-previous-state "\"")
13390 "\"\"")))))
13391 (if lines (setq note (concat note " \\\\")))
13392 (push note lines))
13393 (when (or current-prefix-arg org-note-abort)
13394 (when org-log-into-drawer
13395 (org-remove-empty-drawer-at
13396 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13397 org-log-note-marker))
13398 (setq lines nil))
13399 (when lines
13400 (with-current-buffer (marker-buffer org-log-note-marker)
13401 (save-excursion
13402 (goto-char org-log-note-marker)
13403 (move-marker org-log-note-marker nil)
13404 (end-of-line 1)
13405 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13406 (setq ind (save-excursion
13407 (if (ignore-errors (goto-char (org-in-item-p)))
13408 (let ((struct (org-list-struct)))
13409 (org-list-get-ind
13410 (org-list-get-top-point struct) struct))
13411 (skip-chars-backward " \r\t\n")
13412 (cond
13413 ((and (org-at-heading-p)
13414 org-adapt-indentation)
13415 (1+ (org-current-level)))
13416 ((org-at-heading-p) 0)
13417 (t (org-get-indentation))))))
13418 (setq bul (org-list-bullet-string "-"))
13419 (org-indent-line-to ind)
13420 (insert bul (pop lines))
13421 (let ((ind-body (+ (length bul) ind)))
13422 (while lines
13423 (insert "\n")
13424 (org-indent-line-to ind-body)
13425 (insert (pop lines))))
13426 (message "Note stored")
13427 (org-back-to-heading t)
13428 (org-cycle-hide-drawers 'children))
13429 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13430 ;; from within `org-add-log-note' because `buffer-undo-list'
13431 ;; is then modified outside of `org-with-remote-undo'.
13432 (when (eq this-command 'org-agenda-todo)
13433 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13434 ;; Don't add undo information when called from `org-agenda-todo'
13435 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13436 (set-window-configuration org-log-note-window-configuration)
13437 (with-current-buffer (marker-buffer org-log-note-return-to)
13438 (goto-char org-log-note-return-to))
13439 (move-marker org-log-note-return-to nil)
13440 (and org-log-post-message (message "%s" org-log-post-message))))
13442 (defun org-remove-empty-drawer-at (drawer pos)
13443 "Remove an empty drawer DRAWER at position POS.
13444 POS may also be a marker."
13445 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13446 (save-excursion
13447 (save-restriction
13448 (widen)
13449 (goto-char pos)
13450 (if (org-in-regexp
13451 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13452 (replace-match ""))))))
13454 (defvar org-ts-type nil)
13455 (defun org-sparse-tree (&optional arg type)
13456 "Create a sparse tree, prompt for the details.
13457 This command can create sparse trees. You first need to select the type
13458 of match used to create the tree:
13460 t Show all TODO entries.
13461 T Show entries with a specific TODO keyword.
13462 m Show entries selected by a tags/property match.
13463 p Enter a property name and its value (both with completion on existing
13464 names/values) and show entries with that property.
13465 r Show entries matching a regular expression (`/' can be used as well).
13466 b Show deadlines and scheduled items before a date.
13467 a Show deadlines and scheduled items after a date.
13468 d Show deadlines due within `org-deadline-warning-days'.
13469 D Show deadlines and scheduled items between a date range."
13470 (interactive "P")
13471 (let (ans kwd value ts-type)
13472 (setq type (or type org-sparse-tree-default-date-type))
13473 (setq org-ts-type type)
13474 (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"
13475 (cond ((eq type 'all) "all timestamps")
13476 ((eq type 'scheduled) "only scheduled")
13477 ((eq type 'deadline) "only deadline")
13478 ((eq type 'active) "only active timestamps")
13479 ((eq type 'inactive) "only inactive timestamps")
13480 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13481 ((eq type 'closed) "with a closed time-stamp")
13482 (t "scheduled/deadline")))
13483 (setq ans (read-char-exclusive))
13484 (cond
13485 ((equal ans ?c)
13486 (org-sparse-tree
13487 arg (cadr (member type '(scheduled-or-deadline
13488 all scheduled deadline active inactive closed)))))
13489 ((equal ans ?d)
13490 (call-interactively 'org-check-deadlines))
13491 ((equal ans ?b)
13492 (call-interactively 'org-check-before-date))
13493 ((equal ans ?a)
13494 (call-interactively 'org-check-after-date))
13495 ((equal ans ?D)
13496 (call-interactively 'org-check-dates-range))
13497 ((equal ans ?t)
13498 (call-interactively 'org-show-todo-tree))
13499 ((equal ans ?T)
13500 (org-show-todo-tree '(4)))
13501 ((member ans '(?T ?m))
13502 (call-interactively 'org-match-sparse-tree))
13503 ((member ans '(?p ?P))
13504 (setq kwd (org-icompleting-read "Property: "
13505 (mapcar 'list (org-buffer-property-keys))))
13506 (setq value (org-icompleting-read "Value: "
13507 (mapcar 'list (org-property-values kwd))))
13508 (unless (string-match "\\`{.*}\\'" value)
13509 (setq value (concat "\"" value "\"")))
13510 (org-match-sparse-tree arg (concat kwd "=" value)))
13511 ((member ans '(?r ?R ?/))
13512 (call-interactively 'org-occur))
13513 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13515 (defvar org-occur-highlights nil
13516 "List of overlays used for occur matches.")
13517 (make-variable-buffer-local 'org-occur-highlights)
13518 (defvar org-occur-parameters nil
13519 "Parameters of the active org-occur calls.
13520 This is a list, each call to org-occur pushes as cons cell,
13521 containing the regular expression and the callback, onto the list.
13522 The list can contain several entries if `org-occur' has been called
13523 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13524 will only contain one set of parameters. When the highlights are
13525 removed (for example with `C-c C-c', or with the next edit (depending
13526 on `org-remove-highlights-with-change'), this variable is emptied
13527 as well.")
13528 (make-variable-buffer-local 'org-occur-parameters)
13530 (defun org-occur (regexp &optional keep-previous callback)
13531 "Make a compact tree which shows all matches of REGEXP.
13532 The tree will show the lines where the regexp matches, and all higher
13533 headlines above the match. It will also show the heading after the match,
13534 to make sure editing the matching entry is easy.
13535 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13536 call to `org-occur' will be kept, to allow stacking of calls to this
13537 command.
13538 If CALLBACK is non-nil, it is a function which is called to confirm
13539 that the match should indeed be shown."
13540 (interactive "sRegexp: \nP")
13541 (when (equal regexp "")
13542 (user-error "Regexp cannot be empty"))
13543 (unless keep-previous
13544 (org-remove-occur-highlights nil nil t))
13545 (push (cons regexp callback) org-occur-parameters)
13546 (let ((cnt 0))
13547 (save-excursion
13548 (goto-char (point-min))
13549 (if (or (not keep-previous) ; do not want to keep
13550 (not org-occur-highlights)) ; no previous matches
13551 ;; hide everything
13552 (org-overview))
13553 (while (re-search-forward regexp nil t)
13554 (when (or (not callback)
13555 (save-match-data (funcall callback)))
13556 (setq cnt (1+ cnt))
13557 (when org-highlight-sparse-tree-matches
13558 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13559 (org-show-context 'occur-tree))))
13560 (when org-remove-highlights-with-change
13561 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13562 nil 'local))
13563 (unless org-sparse-tree-open-archived-trees
13564 (org-hide-archived-subtrees (point-min) (point-max)))
13565 (run-hooks 'org-occur-hook)
13566 (if (org-called-interactively-p 'interactive)
13567 (message "%d match(es) for regexp %s" cnt regexp))
13568 cnt))
13570 (defun org-occur-next-match (&optional n reset)
13571 "Function for `next-error-function' to find sparse tree matches.
13572 N is the number of matches to move, when negative move backwards.
13573 RESET is entirely ignored - this function always goes back to the
13574 starting point when no match is found."
13575 (let* ((limit (if (< n 0) (point-min) (point-max)))
13576 (search-func (if (< n 0)
13577 'previous-single-char-property-change
13578 'next-single-char-property-change))
13579 (n (abs n))
13580 (pos (point))
13582 (catch 'exit
13583 (while (setq p1 (funcall search-func (point) 'org-type))
13584 (when (equal p1 limit)
13585 (goto-char pos)
13586 (error "No more matches"))
13587 (when (equal (get-char-property p1 'org-type) 'org-occur)
13588 (setq n (1- n))
13589 (when (= n 0)
13590 (goto-char p1)
13591 (throw 'exit (point))))
13592 (goto-char p1))
13593 (goto-char p1)
13594 (error "No more matches"))))
13596 (defun org-show-context (&optional key)
13597 "Make sure point and context are visible.
13598 How much context is shown depends upon the variables
13599 `org-show-hierarchy-above', `org-show-following-heading',
13600 `org-show-entry-below' and `org-show-siblings'."
13601 (let ((heading-p (org-at-heading-p t))
13602 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13603 (following-p (org-get-alist-option org-show-following-heading key))
13604 (entry-p (org-get-alist-option org-show-entry-below key))
13605 (siblings-p (org-get-alist-option org-show-siblings key)))
13606 ;; Show heading or entry text
13607 (if (and heading-p (not entry-p))
13608 (org-flag-heading nil) ; only show the heading
13609 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13610 (org-show-hidden-entry))) ; show entire entry
13611 (when following-p
13612 ;; Show next sibling, or heading below text
13613 (save-excursion
13614 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13615 (org-flag-heading nil))))
13616 (when siblings-p (org-show-siblings))
13617 (when hierarchy-p
13618 ;; show all higher headings, possibly with siblings
13619 (save-excursion
13620 (while (and (condition-case nil
13621 (progn (org-up-heading-all 1) t)
13622 (error nil))
13623 (not (bobp)))
13624 (org-flag-heading nil)
13625 (when siblings-p (org-show-siblings)))))
13626 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13628 (defvar org-reveal-start-hook nil
13629 "Hook run before revealing a location.")
13631 (defun org-reveal (&optional siblings)
13632 "Show current entry, hierarchy above it, and the following headline.
13633 This can be used to show a consistent set of context around locations
13634 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13635 not t for the search context.
13637 With optional argument SIBLINGS, on each level of the hierarchy all
13638 siblings are shown. This repairs the tree structure to what it would
13639 look like when opened with hierarchical calls to `org-cycle'.
13640 With double optional argument \\[universal-argument] \\[universal-argument], \
13641 go to the parent and show the
13642 entire tree."
13643 (interactive "P")
13644 (run-hooks 'org-reveal-start-hook)
13645 (let ((org-show-hierarchy-above t)
13646 (org-show-following-heading t)
13647 (org-show-siblings (if siblings t org-show-siblings)))
13648 (org-show-context nil))
13649 (when (equal siblings '(16))
13650 (save-excursion
13651 (when (org-up-heading-safe)
13652 (org-show-subtree)
13653 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13655 (defun org-highlight-new-match (beg end)
13656 "Highlight from BEG to END and mark the highlight is an occur headline."
13657 (let ((ov (make-overlay beg end)))
13658 (overlay-put ov 'face 'secondary-selection)
13659 (overlay-put ov 'org-type 'org-occur)
13660 (push ov org-occur-highlights)))
13662 (defun org-remove-occur-highlights (&optional beg end noremove)
13663 "Remove the occur highlights from the buffer.
13664 BEG and END are ignored. If NOREMOVE is nil, remove this function
13665 from the `before-change-functions' in the current buffer."
13666 (interactive)
13667 (unless org-inhibit-highlight-removal
13668 (mapc 'delete-overlay org-occur-highlights)
13669 (setq org-occur-highlights nil)
13670 (setq org-occur-parameters nil)
13671 (unless noremove
13672 (remove-hook 'before-change-functions
13673 'org-remove-occur-highlights 'local))))
13675 ;;;; Priorities
13677 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13678 "Regular expression matching the priority indicator.")
13680 (defvar org-remove-priority-next-time nil)
13682 (defun org-priority-up ()
13683 "Increase the priority of the current item."
13684 (interactive)
13685 (org-priority 'up))
13687 (defun org-priority-down ()
13688 "Decrease the priority of the current item."
13689 (interactive)
13690 (org-priority 'down))
13692 (defun org-priority (&optional action show)
13693 "Change the priority of an item.
13694 ACTION can be `set', `up', `down', or a character."
13695 (interactive "P")
13696 (if (equal action '(4))
13697 (org-show-priority)
13698 (unless org-enable-priority-commands
13699 (user-error "Priority commands are disabled"))
13700 (setq action (or action 'set))
13701 (let (current new news have remove)
13702 (save-excursion
13703 (org-back-to-heading t)
13704 (if (looking-at org-priority-regexp)
13705 (setq current (string-to-char (match-string 2))
13706 have t))
13707 (cond
13708 ((eq action 'remove)
13709 (setq remove t new ?\ ))
13710 ((or (eq action 'set)
13711 (if (featurep 'xemacs) (characterp action) (integerp action)))
13712 (if (not (eq action 'set))
13713 (setq new action)
13714 (message "Priority %c-%c, SPC to remove: "
13715 org-highest-priority org-lowest-priority)
13716 (save-match-data
13717 (setq new (read-char-exclusive))))
13718 (if (and (= (upcase org-highest-priority) org-highest-priority)
13719 (= (upcase org-lowest-priority) org-lowest-priority))
13720 (setq new (upcase new)))
13721 (cond ((equal new ?\ ) (setq remove t))
13722 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13723 (user-error "Priority must be between `%c' and `%c'"
13724 org-highest-priority org-lowest-priority))))
13725 ((eq action 'up)
13726 (setq new (if have
13727 (1- current) ; normal cycling
13728 ;; last priority was empty
13729 (if (eq last-command this-command)
13730 org-lowest-priority ; wrap around empty to lowest
13731 ;; default
13732 (if org-priority-start-cycle-with-default
13733 org-default-priority
13734 (1- org-default-priority))))))
13735 ((eq action 'down)
13736 (setq new (if have
13737 (1+ current) ; normal cycling
13738 ;; last priority was empty
13739 (if (eq last-command this-command)
13740 org-highest-priority ; wrap around empty to highest
13741 ;; default
13742 (if org-priority-start-cycle-with-default
13743 org-default-priority
13744 (1+ org-default-priority))))))
13745 (t (user-error "Invalid action")))
13746 (if (or (< (upcase new) org-highest-priority)
13747 (> (upcase new) org-lowest-priority))
13748 (if (and (memq action '(up down))
13749 (not have) (not (eq last-command this-command)))
13750 ;; `new' is from default priority
13751 (error
13752 "The default can not be set, see `org-default-priority' why")
13753 ;; normal cycling: `new' is beyond highest/lowest priority
13754 ;; and is wrapped around to the empty priority
13755 (setq remove t)))
13756 (setq news (format "%c" new))
13757 (if have
13758 (if remove
13759 (replace-match "" t t nil 1)
13760 (replace-match news t t nil 2))
13761 (if remove
13762 (user-error "No priority cookie found in line")
13763 (let ((case-fold-search nil))
13764 (looking-at org-todo-line-regexp))
13765 (if (match-end 2)
13766 (progn
13767 (goto-char (match-end 2))
13768 (insert " [#" news "]"))
13769 (goto-char (match-beginning 3))
13770 (insert "[#" news "] "))))
13771 (org-preserve-lc (org-set-tags nil 'align)))
13772 (if remove
13773 (message "Priority removed")
13774 (message "Priority of current item set to %s" news)))))
13776 (defun org-show-priority ()
13777 "Show the priority of the current item.
13778 This priority is composed of the main priority given with the [#A] cookies,
13779 and by additional input from the age of a schedules or deadline entry."
13780 (interactive)
13781 (let ((pri (if (eq major-mode 'org-agenda-mode)
13782 (org-get-at-bol 'priority)
13783 (save-excursion
13784 (save-match-data
13785 (beginning-of-line)
13786 (and (looking-at org-heading-regexp)
13787 (org-get-priority (match-string 0))))))))
13788 (message "Priority is %d" (if pri pri -1000))))
13790 (defun org-get-priority (s)
13791 "Find priority cookie and return priority."
13792 (save-match-data
13793 (if (functionp org-get-priority-function)
13794 (funcall org-get-priority-function)
13795 (if (not (string-match org-priority-regexp s))
13796 (* 1000 (- org-lowest-priority org-default-priority))
13797 (* 1000 (- org-lowest-priority
13798 (string-to-char (match-string 2 s))))))))
13800 ;;;; Tags
13802 (defvar org-agenda-archives-mode)
13803 (defvar org-map-continue-from nil
13804 "Position from where mapping should continue.
13805 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13807 (defvar org-scanner-tags nil
13808 "The current tag list while the tags scanner is running.")
13809 (defvar org-trust-scanner-tags nil
13810 "Should `org-get-tags-at' use the tags for the scanner.
13811 This is for internal dynamical scoping only.
13812 When this is non-nil, the function `org-get-tags-at' will return the value
13813 of `org-scanner-tags' instead of building the list by itself. This
13814 can lead to large speed-ups when the tags scanner is used in a file with
13815 many entries, and when the list of tags is retrieved, for example to
13816 obtain a list of properties. Building the tags list for each entry in such
13817 a file becomes an N^2 operation - but with this variable set, it scales
13818 as N.")
13820 (defun org-scan-tags (action matcher todo-only &optional start-level)
13821 "Sca headline tags with inheritance and produce output ACTION.
13823 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13824 or `agenda' to produce an entry list for an agenda view. It can also be
13825 a Lisp form or a function that should be called at each matched headline, in
13826 this case the return value is a list of all return values from these calls.
13828 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13829 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13830 only lines with a not-done TODO keyword are included in the output.
13831 This should be the same variable that was scoped into
13832 and set by `org-make-tags-matcher' when it constructed MATCHER.
13834 START-LEVEL can be a string with asterisks, reducing the scope to
13835 headlines matching this string."
13836 (require 'org-agenda)
13837 (let* ((re (concat "^"
13838 (if start-level
13839 ;; Get the correct level to match
13840 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13841 org-outline-regexp)
13842 " *\\(\\<\\("
13843 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13844 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13845 (props (list 'face 'default
13846 'done-face 'org-agenda-done
13847 'undone-face 'default
13848 'mouse-face 'highlight
13849 'org-not-done-regexp org-not-done-regexp
13850 'org-todo-regexp org-todo-regexp
13851 'org-complex-heading-regexp org-complex-heading-regexp
13852 'help-echo
13853 (format "mouse-2 or RET jump to org file %s"
13854 (abbreviate-file-name
13855 (or (buffer-file-name (buffer-base-buffer))
13856 (buffer-name (buffer-base-buffer)))))))
13857 (org-map-continue-from nil)
13858 lspos tags tags-list
13859 (tags-alist (list (cons 0 org-file-tags)))
13860 (llast 0) rtn rtn1 level category i txt
13861 todo marker entry priority)
13862 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13863 (setq action (list 'lambda nil action)))
13864 (save-excursion
13865 (goto-char (point-min))
13866 (when (eq action 'sparse-tree)
13867 (org-overview)
13868 (org-remove-occur-highlights))
13869 (while (let (case-fold-search)
13870 (re-search-forward re nil t))
13871 (setq org-map-continue-from nil)
13872 (catch :skip
13873 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13874 tags (if (match-end 4) (org-match-string-no-properties 4)))
13875 (goto-char (setq lspos (match-beginning 0)))
13876 (setq level (org-reduced-level (org-outline-level))
13877 category (org-get-category))
13878 (setq i llast llast level)
13879 ;; remove tag lists from same and sublevels
13880 (while (>= i level)
13881 (when (setq entry (assoc i tags-alist))
13882 (setq tags-alist (delete entry tags-alist)))
13883 (setq i (1- i)))
13884 ;; add the next tags
13885 (when tags
13886 (setq tags (org-split-string tags ":")
13887 tags-alist
13888 (cons (cons level tags) tags-alist)))
13889 ;; compile tags for current headline
13890 (setq tags-list
13891 (if org-use-tag-inheritance
13892 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13893 tags)
13894 org-scanner-tags tags-list)
13895 (when org-use-tag-inheritance
13896 (setcdr (car tags-alist)
13897 (mapcar (lambda (x)
13898 (setq x (copy-sequence x))
13899 (org-add-prop-inherited x))
13900 (cdar tags-alist))))
13901 (when (and tags org-use-tag-inheritance
13902 (or (not (eq t org-use-tag-inheritance))
13903 org-tags-exclude-from-inheritance))
13904 ;; selective inheritance, remove uninherited ones
13905 (setcdr (car tags-alist)
13906 (org-remove-uninherited-tags (cdar tags-alist))))
13907 (when (and
13909 ;; eval matcher only when the todo condition is OK
13910 (and (or (not todo-only) (member todo org-not-done-keywords))
13911 (let ((case-fold-search t) (org-trust-scanner-tags t))
13912 (eval matcher)))
13914 ;; Call the skipper, but return t if it does not skip,
13915 ;; so that the `and' form continues evaluating
13916 (progn
13917 (unless (eq action 'sparse-tree) (org-agenda-skip))
13920 ;; Check if timestamps are deselecting this entry
13921 (or (not todo-only)
13922 (and (member todo org-not-done-keywords)
13923 (or (not org-agenda-tags-todo-honor-ignore-options)
13924 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13926 ;; select this headline
13927 (cond
13928 ((eq action 'sparse-tree)
13929 (and org-highlight-sparse-tree-matches
13930 (org-get-heading) (match-end 0)
13931 (org-highlight-new-match
13932 (match-beginning 1) (match-end 1)))
13933 (org-show-context 'tags-tree))
13934 ((eq action 'agenda)
13935 (setq txt (org-agenda-format-item
13937 (concat
13938 (if (eq org-tags-match-list-sublevels 'indented)
13939 (make-string (1- level) ?.) "")
13940 (org-get-heading))
13941 level category
13942 tags-list)
13943 priority (org-get-priority txt))
13944 (goto-char lspos)
13945 (setq marker (org-agenda-new-marker))
13946 (org-add-props txt props
13947 'org-marker marker 'org-hd-marker marker 'org-category category
13948 'todo-state todo
13949 'priority priority 'type "tagsmatch")
13950 (push txt rtn))
13951 ((functionp action)
13952 (setq org-map-continue-from nil)
13953 (save-excursion
13954 (setq rtn1 (funcall action))
13955 (push rtn1 rtn)))
13956 (t (user-error "Invalid action")))
13958 ;; if we are to skip sublevels, jump to end of subtree
13959 (unless org-tags-match-list-sublevels
13960 (org-end-of-subtree t)
13961 (backward-char 1))))
13962 ;; Get the correct position from where to continue
13963 (if org-map-continue-from
13964 (goto-char org-map-continue-from)
13965 (and (= (point) lspos) (end-of-line 1)))))
13966 (when (and (eq action 'sparse-tree)
13967 (not org-sparse-tree-open-archived-trees))
13968 (org-hide-archived-subtrees (point-min) (point-max)))
13969 (nreverse rtn)))
13971 (defun org-remove-uninherited-tags (tags)
13972 "Remove all tags that are not inherited from the list TAGS."
13973 (cond
13974 ((eq org-use-tag-inheritance t)
13975 (if org-tags-exclude-from-inheritance
13976 (org-delete-all org-tags-exclude-from-inheritance tags)
13977 tags))
13978 ((not org-use-tag-inheritance) nil)
13979 ((stringp org-use-tag-inheritance)
13980 (delq nil (mapcar
13981 (lambda (x)
13982 (if (and (string-match org-use-tag-inheritance x)
13983 (not (member x org-tags-exclude-from-inheritance)))
13984 x nil))
13985 tags)))
13986 ((listp org-use-tag-inheritance)
13987 (delq nil (mapcar
13988 (lambda (x)
13989 (if (member x org-use-tag-inheritance) x nil))
13990 tags)))))
13992 (defun org-match-sparse-tree (&optional todo-only match)
13993 "Create a sparse tree according to tags string MATCH.
13994 MATCH can contain positive and negative selection of tags, like
13995 \"+WORK+URGENT-WITHBOSS\".
13996 If optional argument TODO-ONLY is non-nil, only select lines that are
13997 also TODO lines."
13998 (interactive "P")
13999 (org-agenda-prepare-buffers (list (current-buffer)))
14000 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14002 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14004 (defvar org-cached-props nil)
14005 (defun org-cached-entry-get (pom property)
14006 (if (or (eq t org-use-property-inheritance)
14007 (and (stringp org-use-property-inheritance)
14008 (string-match org-use-property-inheritance property))
14009 (and (listp org-use-property-inheritance)
14010 (member property org-use-property-inheritance)))
14011 ;; Caching is not possible, check it directly
14012 (org-entry-get pom property 'inherit)
14013 ;; Get all properties, so that we can do complicated checks easily
14014 (cdr (assoc property (or org-cached-props
14015 (setq org-cached-props
14016 (org-entry-properties pom)))))))
14018 (defun org-global-tags-completion-table (&optional files)
14019 "Return the list of all tags in all agenda buffer/files.
14020 Optional FILES argument is a list of files which can be used
14021 instead of the agenda files."
14022 (save-excursion
14023 (org-uniquify
14024 (delq nil
14025 (apply 'append
14026 (mapcar
14027 (lambda (file)
14028 (set-buffer (find-file-noselect file))
14029 (append (org-get-buffer-tags)
14030 (mapcar (lambda (x) (if (stringp (car-safe x))
14031 (list (car-safe x)) nil))
14032 org-tag-alist)))
14033 (if (and files (car files))
14034 files
14035 (org-agenda-files))))))))
14037 (defun org-make-tags-matcher (match)
14038 "Create the TAGS/TODO matcher form for the selection string MATCH.
14040 The variable `todo-only' is scoped dynamically into this function.
14041 It will be set to t if the matcher restricts matching to TODO entries,
14042 otherwise will not be touched.
14044 Returns a cons of the selection string MATCH and the constructed
14045 lisp form implementing the matcher. The matcher is to be evaluated
14046 at an Org entry, with point on the headline, and returns t if the
14047 entry matches the selection string MATCH. The returned lisp form
14048 references two variables with information about the entry, which
14049 must be bound around the form's evaluation: todo, the TODO keyword
14050 at the entry (or nil of none); and tags-list, the list of all tags
14051 at the entry including inherited ones. Additionally, the category
14052 of the entry (if any) must be specified as the text property
14053 'org-category on the headline.
14055 See also `org-scan-tags'.
14057 (declare (special todo-only))
14058 (unless (boundp 'todo-only)
14059 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14060 (unless match
14061 ;; Get a new match request, with completion against the global
14062 ;; tags table and the local tags in current buffer
14063 (let ((org-last-tags-completion-table
14064 (org-uniquify
14065 (delq nil (append (org-get-buffer-tags)
14066 (org-global-tags-completion-table))))))
14067 (setq match (org-completing-read-no-i
14068 "Match: " 'org-tags-completion-function nil nil nil
14069 'org-tags-history))))
14071 ;; Parse the string and create a lisp form
14072 (let ((match0 match)
14073 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14074 minus tag mm
14075 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14076 orterms term orlist re-p str-p level-p level-op time-p
14077 prop-p pn pv po gv rest (start 0) (ss 0))
14078 ;; Expand group tags
14079 (setq match (org-tags-expand match))
14081 ;; Check if there is a TODO part of this match, which would be the
14082 ;; part after a "/". TO make sure that this slash is not part of
14083 ;; a property value to be matched against, we also check that there
14084 ;; is no " after that slash.
14085 ;; First, find the last slash
14086 (while (string-match "/+" match ss)
14087 (setq start (match-beginning 0) ss (match-end 0)))
14088 (if (and (string-match "/+" match start)
14089 (not (save-match-data (string-match "\"" match start))))
14090 ;; match contains also a todo-matching request
14091 (progn
14092 (setq tagsmatch (substring match 0 (match-beginning 0))
14093 todomatch (substring match (match-end 0)))
14094 (if (string-match "^!" todomatch)
14095 (setq todo-only t todomatch (substring todomatch 1)))
14096 (if (string-match "^\\s-*$" todomatch)
14097 (setq todomatch nil)))
14098 ;; only matching tags
14099 (setq tagsmatch match todomatch nil))
14101 ;; Make the tags matcher
14102 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14103 (setq tagsmatcher t)
14104 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14105 (while (setq term (pop orterms))
14106 (while (and (equal (substring term -1) "\\") orterms)
14107 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14108 (while (string-match re term)
14109 (setq rest (substring term (match-end 0))
14110 minus (and (match-end 1)
14111 (equal (match-string 1 term) "-"))
14112 tag (save-match-data (replace-regexp-in-string
14113 "\\\\-" "-"
14114 (match-string 2 term)))
14115 re-p (equal (string-to-char tag) ?{)
14116 level-p (match-end 4)
14117 prop-p (match-end 5)
14118 mm (cond
14119 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14120 (level-p
14121 (setq level-op (org-op-to-function (match-string 3 term)))
14122 `(,level-op level ,(string-to-number
14123 (match-string 4 term))))
14124 (prop-p
14125 (setq pn (match-string 5 term)
14126 po (match-string 6 term)
14127 pv (match-string 7 term)
14128 re-p (equal (string-to-char pv) ?{)
14129 str-p (equal (string-to-char pv) ?\")
14130 time-p (save-match-data
14131 (string-match "^\"[[<].*[]>]\"$" pv))
14132 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14133 (if time-p (setq pv (org-matcher-time pv)))
14134 (setq po (org-op-to-function po (if time-p 'time str-p)))
14135 (cond
14136 ((equal pn "CATEGORY")
14137 (setq gv '(get-text-property (point) 'org-category)))
14138 ((equal pn "TODO")
14139 (setq gv 'todo))
14141 (setq gv `(org-cached-entry-get nil ,pn))))
14142 (if re-p
14143 (if (eq po 'org<>)
14144 `(not (string-match ,pv (or ,gv "")))
14145 `(string-match ,pv (or ,gv "")))
14146 (if str-p
14147 `(,po (or ,gv "") ,pv)
14148 `(,po (string-to-number (or ,gv ""))
14149 ,(string-to-number pv) ))))
14150 (t `(member ,tag tags-list)))
14151 mm (if minus (list 'not mm) mm)
14152 term rest)
14153 (push mm tagsmatcher))
14154 (push (if (> (length tagsmatcher) 1)
14155 (cons 'and tagsmatcher)
14156 (car tagsmatcher))
14157 orlist)
14158 (setq tagsmatcher nil))
14159 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14160 (setq tagsmatcher
14161 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14162 ;; Make the todo matcher
14163 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14164 (setq todomatcher t)
14165 (setq orterms (org-split-string todomatch "|") orlist nil)
14166 (while (setq term (pop orterms))
14167 (while (string-match re term)
14168 (setq minus (and (match-end 1)
14169 (equal (match-string 1 term) "-"))
14170 kwd (match-string 2 term)
14171 re-p (equal (string-to-char kwd) ?{)
14172 term (substring term (match-end 0))
14173 mm (if re-p
14174 `(string-match ,(substring kwd 1 -1) todo)
14175 (list 'equal 'todo kwd))
14176 mm (if minus (list 'not mm) mm))
14177 (push mm todomatcher))
14178 (push (if (> (length todomatcher) 1)
14179 (cons 'and todomatcher)
14180 (car todomatcher))
14181 orlist)
14182 (setq todomatcher nil))
14183 (setq todomatcher (if (> (length orlist) 1)
14184 (cons 'or orlist) (car orlist))))
14186 ;; Return the string and lisp forms of the matcher
14187 (setq matcher (if todomatcher
14188 (list 'and tagsmatcher todomatcher)
14189 tagsmatcher))
14190 (when todo-only
14191 (setq matcher (list 'and '(member todo org-not-done-keywords)
14192 matcher)))
14193 (cons match0 matcher)))
14195 (defun org-tags-expand (match &optional single-as-list downcased)
14196 "Expand group tags in MATCH.
14198 This replaces every group tag in MATCH with a regexp tag search.
14199 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14200 will be replaced like this:
14202 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14203 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14204 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14206 Replacing by a regexp preserves the structure of the match.
14207 E.g., this expansion
14209 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14211 will match anything tagged with \"Lab\" and \"Home\", or tagged
14212 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14214 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14215 assumed to be a single group tag, and the function will return
14216 the list of tags in this group.
14218 When DOWNCASE is non-nil, expand downcased TAGS."
14219 (if org-group-tags
14220 (let* ((case-fold-search t)
14221 (stable org-mode-syntax-table)
14222 (tal (or org-tag-groups-alist-for-agenda
14223 org-tag-groups-alist))
14224 (tal (if downcased
14225 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14226 (tml (mapcar 'car tal))
14227 (rtnmatch match) rpl)
14228 ;; @ and _ are allowed as word-components in tags
14229 (modify-syntax-entry ?@ "w" stable)
14230 (modify-syntax-entry ?_ "w" stable)
14231 (while (and tml
14232 (with-syntax-table stable
14233 (string-match
14234 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14235 (regexp-opt tml) "\\>\\)") rtnmatch)))
14236 (let* ((dir (match-string 1 rtnmatch))
14237 (tag (match-string 2 rtnmatch))
14238 (tag (if downcased (downcase tag) tag)))
14239 (setq tml (delete tag tml))
14240 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14241 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14242 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14243 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14244 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14245 (if single-as-list
14246 (or (reverse rpl) (list rtnmatch))
14247 rtnmatch))
14248 (if single-as-list (list (if downcased (downcase match) match))
14249 match)))
14251 (defun org-op-to-function (op &optional stringp)
14252 "Turn an operator into the appropriate function."
14253 (setq op
14254 (cond
14255 ((equal op "<" ) '(< string< org-time<))
14256 ((equal op ">" ) '(> org-string> org-time>))
14257 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14258 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14259 ((member op '("=" "==")) '(= string= org-time=))
14260 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14261 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14263 (defun org<> (a b) (not (= a b)))
14264 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14265 (defun org-string>= (a b) (not (string< a b)))
14266 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14267 (defun org-string<> (a b) (not (string= a b)))
14268 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14269 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14270 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14271 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14272 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14273 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14274 (defun org-2ft (s)
14275 "Convert S to a floating point time.
14276 If S is already a number, just return it. If it is a string, parse
14277 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14278 (cond
14279 ((numberp s) s)
14280 ((stringp s)
14281 (condition-case nil
14282 (float-time (apply 'encode-time (org-parse-time-string s)))
14283 (error 0.)))
14284 (t 0.)))
14286 (defun org-time-today ()
14287 "Time in seconds today at 0:00.
14288 Returns the float number of seconds since the beginning of the
14289 epoch to the beginning of today (00:00)."
14290 (float-time (apply 'encode-time
14291 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14293 (defun org-matcher-time (s)
14294 "Interpret a time comparison value."
14295 (save-match-data
14296 (cond
14297 ((string= s "<now>") (float-time))
14298 ((string= s "<today>") (org-time-today))
14299 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14300 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14301 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14302 (+ (org-time-today)
14303 (* (string-to-number (match-string 1 s))
14304 (cdr (assoc (match-string 2 s)
14305 '(("d" . 86400.0) ("w" . 604800.0)
14306 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14307 (t (org-2ft s)))))
14309 (defun org-match-any-p (re list)
14310 "Does re match any element of list?"
14311 (setq list (mapcar (lambda (x) (string-match re x)) list))
14312 (delq nil list))
14314 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14315 (defvar org-tags-overlay (make-overlay 1 1))
14316 (org-detach-overlay org-tags-overlay)
14318 (defun org-get-local-tags-at (&optional pos)
14319 "Get a list of tags defined in the current headline."
14320 (org-get-tags-at pos 'local))
14322 (defun org-get-local-tags ()
14323 "Get a list of tags defined in the current headline."
14324 (org-get-tags-at nil 'local))
14326 (defun org-get-tags-at (&optional pos local)
14327 "Get a list of all headline tags applicable at POS.
14328 POS defaults to point. If tags are inherited, the list contains
14329 the targets in the same sequence as the headlines appear, i.e.
14330 the tags of the current headline come last.
14331 When LOCAL is non-nil, only return tags from the current headline,
14332 ignore inherited ones."
14333 (interactive)
14334 (if (and org-trust-scanner-tags
14335 (or (not pos) (equal pos (point)))
14336 (not local))
14337 org-scanner-tags
14338 (let (tags ltags lastpos parent)
14339 (save-excursion
14340 (save-restriction
14341 (widen)
14342 (goto-char (or pos (point)))
14343 (save-match-data
14344 (catch 'done
14345 (condition-case nil
14346 (progn
14347 (org-back-to-heading t)
14348 (while (not (equal lastpos (point)))
14349 (setq lastpos (point))
14350 (when (looking-at
14351 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14352 (setq ltags (org-split-string
14353 (org-match-string-no-properties 1) ":"))
14354 (when parent
14355 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14356 (setq tags (append
14357 (if parent
14358 (org-remove-uninherited-tags ltags)
14359 ltags)
14360 tags)))
14361 (or org-use-tag-inheritance (throw 'done t))
14362 (if local (throw 'done t))
14363 (or (org-up-heading-safe) (error nil))
14364 (setq parent t)))
14365 (error nil)))))
14366 (if local
14367 tags
14368 (reverse (delete-dups
14369 (reverse (append
14370 (org-remove-uninherited-tags
14371 org-file-tags) tags)))))))))
14373 (defun org-add-prop-inherited (s)
14374 (add-text-properties 0 (length s) '(inherited t) s)
14377 (defun org-toggle-tag (tag &optional onoff)
14378 "Toggle the tag TAG for the current line.
14379 If ONOFF is `on' or `off', don't toggle but set to this state."
14380 (let (res current)
14381 (save-excursion
14382 (org-back-to-heading t)
14383 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14384 (point-at-eol) t)
14385 (progn
14386 (setq current (match-string 1))
14387 (replace-match ""))
14388 (setq current ""))
14389 (setq current (nreverse (org-split-string current ":")))
14390 (cond
14391 ((eq onoff 'on)
14392 (setq res t)
14393 (or (member tag current) (push tag current)))
14394 ((eq onoff 'off)
14395 (or (not (member tag current)) (setq current (delete tag current))))
14396 (t (if (member tag current)
14397 (setq current (delete tag current))
14398 (setq res t)
14399 (push tag current))))
14400 (end-of-line 1)
14401 (if current
14402 (progn
14403 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14404 (org-set-tags nil t))
14405 (delete-horizontal-space))
14406 (run-hooks 'org-after-tags-change-hook))
14407 res))
14409 (defun org-align-tags-here (to-col)
14410 ;; Assumes that this is a headline
14411 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14412 (beginning-of-line 1)
14413 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14414 (< pos (match-beginning 2)))
14415 (progn
14416 (setq tags-l (- (match-end 2) (match-beginning 2)))
14417 (goto-char (match-beginning 1))
14418 (insert " ")
14419 (delete-region (point) (1+ (match-beginning 2)))
14420 (setq ncol (max (current-column)
14421 (1+ col)
14422 (if (> to-col 0)
14423 to-col
14424 (- (abs to-col) tags-l))))
14425 (setq p (point))
14426 (insert (make-string (- ncol (current-column)) ?\ ))
14427 (setq ncol (current-column))
14428 (when indent-tabs-mode (tabify p (point-at-eol)))
14429 (org-move-to-column (min ncol col) t nil t))
14430 (goto-char pos))))
14432 (defun org-set-tags-command (&optional arg just-align)
14433 "Call the set-tags command for the current entry."
14434 (interactive "P")
14435 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14436 (org-set-tags arg just-align)
14437 (save-excursion
14438 (unless (and (org-region-active-p)
14439 org-loop-over-headlines-in-active-region)
14440 (org-back-to-heading t))
14441 (org-set-tags arg just-align))))
14443 (defun org-set-tags-to (data)
14444 "Set the tags of the current entry to DATA, replacing the current tags.
14445 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14446 If DATA is nil or the empty string, any tags will be removed."
14447 (interactive "sTags: ")
14448 (setq data
14449 (cond
14450 ((eq data nil) "")
14451 ((equal data "") "")
14452 ((stringp data)
14453 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14454 ":"))
14455 ((listp data)
14456 (concat ":" (mapconcat 'identity data ":") ":"))))
14457 (when data
14458 (save-excursion
14459 (org-back-to-heading t)
14460 (when (looking-at org-complex-heading-regexp)
14461 (if (match-end 5)
14462 (progn
14463 (goto-char (match-beginning 5))
14464 (insert data)
14465 (delete-region (point) (point-at-eol))
14466 (org-set-tags nil 'align))
14467 (goto-char (point-at-eol))
14468 (insert " " data)
14469 (org-set-tags nil 'align)))
14470 (beginning-of-line 1)
14471 (if (looking-at ".*?\\([ \t]+\\)$")
14472 (delete-region (match-beginning 1) (match-end 1))))))
14474 (defun org-align-all-tags ()
14475 "Align the tags i all headings."
14476 (interactive)
14477 (save-excursion
14478 (or (ignore-errors (org-back-to-heading t))
14479 (outline-next-heading))
14480 (if (org-at-heading-p)
14481 (org-set-tags t)
14482 (message "No headings"))))
14484 (defvar org-indent-indentation-per-level)
14485 (defun org-set-tags (&optional arg just-align)
14486 "Set the tags for the current headline.
14487 With prefix ARG, realign all tags in headings in the current buffer."
14488 (interactive "P")
14489 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14490 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14491 'region-start-level 'region))
14492 org-loop-over-headlines-in-active-region)
14493 (org-map-entries
14494 ;; We don't use ARG and JUST-ALIGN here these args are not
14495 ;; useful when looping over headlines
14496 `(org-set-tags)
14497 org-loop-over-headlines-in-active-region
14498 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14499 (let* ((re org-outline-regexp-bol)
14500 (current (unless arg (org-get-tags-string)))
14501 (col (current-column))
14502 (org-setting-tags t)
14503 table current-tags inherited-tags ; computed below when needed
14504 tags p0 c0 c1 rpl di tc level)
14505 (if arg
14506 (save-excursion
14507 (goto-char (point-min))
14508 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14509 (while (re-search-forward re nil t)
14510 (org-set-tags nil t)
14511 (end-of-line 1)))
14512 (message "All tags realigned to column %d" org-tags-column))
14513 (if just-align
14514 (setq tags current)
14515 ;; Get a new set of tags from the user
14516 (save-excursion
14517 (setq table (append org-tag-persistent-alist
14518 (or org-tag-alist (org-get-buffer-tags))
14519 (and
14520 org-complete-tags-always-offer-all-agenda-tags
14521 (org-global-tags-completion-table
14522 (org-agenda-files))))
14523 org-last-tags-completion-table table
14524 current-tags (org-split-string current ":")
14525 inherited-tags (nreverse
14526 (nthcdr (length current-tags)
14527 (nreverse (org-get-tags-at))))
14528 tags
14529 (if (or (eq t org-use-fast-tag-selection)
14530 (and org-use-fast-tag-selection
14531 (delq nil (mapcar 'cdr table))))
14532 (org-fast-tag-selection
14533 current-tags inherited-tags table
14534 (if org-fast-tag-selection-include-todo
14535 org-todo-key-alist))
14536 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14537 (org-trim
14538 (org-icompleting-read "Tags: "
14539 'org-tags-completion-function
14540 nil nil current 'org-tags-history))))))
14541 (while (string-match "[-+&]+" tags)
14542 ;; No boolean logic, just a list
14543 (setq tags (replace-match ":" t t tags))))
14545 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14547 (if org-tags-sort-function
14548 (setq tags (mapconcat 'identity
14549 (sort (org-split-string
14550 tags (org-re "[^[:alnum:]_@#%]+"))
14551 org-tags-sort-function) ":")))
14553 (if (string-match "\\`[\t ]*\\'" tags)
14554 (setq tags "")
14555 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14556 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14558 ;; Insert new tags at the correct column
14559 (beginning-of-line 1)
14560 (setq level (or (and (looking-at org-outline-regexp)
14561 (- (match-end 0) (point) 1))
14563 (cond
14564 ((and (equal current "") (equal tags "")))
14565 ((re-search-forward
14566 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14567 (point-at-eol) t)
14568 (if (equal tags "")
14569 (setq rpl "")
14570 (goto-char (match-beginning 0))
14571 (setq c0 (current-column)
14572 ;; compute offset for the case of org-indent-mode active
14573 di (if org-indent-mode
14574 (* (1- org-indent-indentation-per-level) (1- level))
14576 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14577 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14578 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14579 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14580 (replace-match rpl t t)
14581 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14582 tags)
14583 (t (error "Tags alignment failed")))
14584 (org-move-to-column col)
14585 (unless just-align
14586 (run-hooks 'org-after-tags-change-hook))))))
14588 (defun org-change-tag-in-region (beg end tag off)
14589 "Add or remove TAG for each entry in the region.
14590 This works in the agenda, and also in an org-mode buffer."
14591 (interactive
14592 (list (region-beginning) (region-end)
14593 (let ((org-last-tags-completion-table
14594 (if (derived-mode-p 'org-mode)
14595 (org-uniquify
14596 (delq nil (append (org-get-buffer-tags)
14597 (org-global-tags-completion-table))))
14598 (org-global-tags-completion-table))))
14599 (org-icompleting-read
14600 "Tag: " 'org-tags-completion-function nil nil nil
14601 'org-tags-history))
14602 (progn
14603 (message "[s]et or [r]emove? ")
14604 (equal (read-char-exclusive) ?r))))
14605 (if (fboundp 'deactivate-mark) (deactivate-mark))
14606 (let ((agendap (equal major-mode 'org-agenda-mode))
14607 l1 l2 m buf pos newhead (cnt 0))
14608 (goto-char end)
14609 (setq l2 (1- (org-current-line)))
14610 (goto-char beg)
14611 (setq l1 (org-current-line))
14612 (loop for l from l1 to l2 do
14613 (org-goto-line l)
14614 (setq m (get-text-property (point) 'org-hd-marker))
14615 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14616 (and agendap m))
14617 (setq buf (if agendap (marker-buffer m) (current-buffer))
14618 pos (if agendap m (point)))
14619 (with-current-buffer buf
14620 (save-excursion
14621 (save-restriction
14622 (goto-char pos)
14623 (setq cnt (1+ cnt))
14624 (org-toggle-tag tag (if off 'off 'on))
14625 (setq newhead (org-get-heading)))))
14626 (and agendap (org-agenda-change-all-lines newhead m))))
14627 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14629 (defun org-tags-completion-function (string predicate &optional flag)
14630 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14631 (confirm (lambda (x) (stringp (car x)))))
14632 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14633 (setq s1 (match-string 1 string)
14634 s2 (match-string 2 string))
14635 (setq s1 "" s2 string))
14636 (cond
14637 ((eq flag nil)
14638 ;; try completion
14639 (setq rtn (try-completion s2 ctable confirm))
14640 (if (stringp rtn)
14641 (setq rtn
14642 (concat s1 s2 (substring rtn (length s2))
14643 (if (and org-add-colon-after-tag-completion
14644 (assoc rtn ctable))
14645 ":" ""))))
14646 rtn)
14647 ((eq flag t)
14648 ;; all-completions
14649 (all-completions s2 ctable confirm))
14650 ((eq flag 'lambda)
14651 ;; exact match?
14652 (assoc s2 ctable)))))
14654 (defun org-fast-tag-insert (kwd tags face &optional end)
14655 "Insert KDW, and the TAGS, the latter with face FACE.
14656 Also insert END."
14657 (insert (format "%-12s" (concat kwd ":"))
14658 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14659 (or end "")))
14661 (defun org-fast-tag-show-exit (flag)
14662 (save-excursion
14663 (org-goto-line 3)
14664 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14665 (replace-match ""))
14666 (when flag
14667 (end-of-line 1)
14668 (org-move-to-column (- (window-width) 19) t)
14669 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14671 (defun org-set-current-tags-overlay (current prefix)
14672 "Add an overlay to CURRENT tag with PREFIX."
14673 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14674 (if (featurep 'xemacs)
14675 (org-overlay-display org-tags-overlay (concat prefix s)
14676 'secondary-selection)
14677 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14678 (org-overlay-display org-tags-overlay (concat prefix s)))))
14680 (defvar org-last-tag-selection-key nil)
14681 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14682 "Fast tag selection with single keys.
14683 CURRENT is the current list of tags in the headline, INHERITED is the
14684 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14685 possibly with grouping information. TODO-TABLE is a similar table with
14686 TODO keywords, should these have keys assigned to them.
14687 If the keys are nil, a-z are automatically assigned.
14688 Returns the new tags string, or nil to not change the current settings."
14689 (let* ((fulltable (append table todo-table))
14690 (maxlen (apply 'max (mapcar
14691 (lambda (x)
14692 (if (stringp (car x)) (string-width (car x)) 0))
14693 fulltable)))
14694 (buf (current-buffer))
14695 (expert (eq org-fast-tag-selection-single-key 'expert))
14696 (buffer-tags nil)
14697 (fwidth (+ maxlen 3 1 3))
14698 (ncol (/ (- (window-width) 4) fwidth))
14699 (i-face 'org-done)
14700 (c-face 'org-todo)
14701 tg cnt e c char c1 c2 ntable tbl rtn
14702 ov-start ov-end ov-prefix
14703 (exit-after-next org-fast-tag-selection-single-key)
14704 (done-keywords org-done-keywords)
14705 groups ingroup)
14706 (save-excursion
14707 (beginning-of-line 1)
14708 (if (looking-at
14709 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14710 (setq ov-start (match-beginning 1)
14711 ov-end (match-end 1)
14712 ov-prefix "")
14713 (setq ov-start (1- (point-at-eol))
14714 ov-end (1+ ov-start))
14715 (skip-chars-forward "^\n\r")
14716 (setq ov-prefix
14717 (concat
14718 (buffer-substring (1- (point)) (point))
14719 (if (> (current-column) org-tags-column)
14721 (make-string (- org-tags-column (current-column)) ?\ ))))))
14722 (move-overlay org-tags-overlay ov-start ov-end)
14723 (save-window-excursion
14724 (if expert
14725 (set-buffer (get-buffer-create " *Org tags*"))
14726 (delete-other-windows)
14727 (split-window-vertically)
14728 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14729 (erase-buffer)
14730 (org-set-local 'org-done-keywords done-keywords)
14731 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14732 (org-fast-tag-insert "Current" current c-face "\n\n")
14733 (org-fast-tag-show-exit exit-after-next)
14734 (org-set-current-tags-overlay current ov-prefix)
14735 (setq tbl fulltable char ?a cnt 0)
14736 (while (setq e (pop tbl))
14737 (cond
14738 ((equal (car e) :startgroup)
14739 (push '() groups) (setq ingroup t)
14740 (when (not (= cnt 0))
14741 (setq cnt 0)
14742 (insert "\n"))
14743 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14744 ((equal (car e) :endgroup)
14745 (setq ingroup nil cnt 0)
14746 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14747 ((equal e '(:newline))
14748 (when (not (= cnt 0))
14749 (setq cnt 0)
14750 (insert "\n")
14751 (setq e (car tbl))
14752 (while (equal (car tbl) '(:newline))
14753 (insert "\n")
14754 (setq tbl (cdr tbl)))))
14755 ((equal e '(:grouptags)) nil)
14757 (setq tg (copy-sequence (car e)) c2 nil)
14758 (if (cdr e)
14759 (setq c (cdr e))
14760 ;; automatically assign a character.
14761 (setq c1 (string-to-char
14762 (downcase (substring
14763 tg (if (= (string-to-char tg) ?@) 1 0)))))
14764 (if (or (rassoc c1 ntable) (rassoc c1 table))
14765 (while (or (rassoc char ntable) (rassoc char table))
14766 (setq char (1+ char)))
14767 (setq c2 c1))
14768 (setq c (or c2 char)))
14769 (if ingroup (push tg (car groups)))
14770 (setq tg (org-add-props tg nil 'face
14771 (cond
14772 ((not (assoc tg table))
14773 (org-get-todo-face tg))
14774 ((member tg current) c-face)
14775 ((member tg inherited) i-face))))
14776 (if (equal (caar tbl) :grouptags)
14777 (org-add-props tg nil 'face 'org-tag-group))
14778 (if (and (= cnt 0) (not ingroup)) (insert " "))
14779 (insert "[" c "] " tg (make-string
14780 (- fwidth 4 (length tg)) ?\ ))
14781 (push (cons tg c) ntable)
14782 (when (= (setq cnt (1+ cnt)) ncol)
14783 (insert "\n")
14784 (if ingroup (insert " "))
14785 (setq cnt 0)))))
14786 (setq ntable (nreverse ntable))
14787 (insert "\n")
14788 (goto-char (point-min))
14789 (if (not expert) (org-fit-window-to-buffer))
14790 (setq rtn
14791 (catch 'exit
14792 (while t
14793 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14794 (if (not groups) "no " "")
14795 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14796 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14797 (setq org-last-tag-selection-key c)
14798 (cond
14799 ((= c ?\r) (throw 'exit t))
14800 ((= c ?!)
14801 (setq groups (not groups))
14802 (goto-char (point-min))
14803 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14804 ((= c ?\C-c)
14805 (if (not expert)
14806 (org-fast-tag-show-exit
14807 (setq exit-after-next (not exit-after-next)))
14808 (setq expert nil)
14809 (delete-other-windows)
14810 (set-window-buffer (split-window-vertically) " *Org tags*")
14811 (org-switch-to-buffer-other-window " *Org tags*")
14812 (org-fit-window-to-buffer)))
14813 ((or (= c ?\C-g)
14814 (and (= c ?q) (not (rassoc c ntable))))
14815 (org-detach-overlay org-tags-overlay)
14816 (setq quit-flag t))
14817 ((= c ?\ )
14818 (setq current nil)
14819 (if exit-after-next (setq exit-after-next 'now)))
14820 ((= c ?\t)
14821 (condition-case nil
14822 (setq tg (org-icompleting-read
14823 "Tag: "
14824 (or buffer-tags
14825 (with-current-buffer buf
14826 (org-get-buffer-tags)))))
14827 (quit (setq tg "")))
14828 (when (string-match "\\S-" tg)
14829 (add-to-list 'buffer-tags (list tg))
14830 (if (member tg current)
14831 (setq current (delete tg current))
14832 (push tg current)))
14833 (if exit-after-next (setq exit-after-next 'now)))
14834 ((setq e (rassoc c todo-table) tg (car e))
14835 (with-current-buffer buf
14836 (save-excursion (org-todo tg)))
14837 (if exit-after-next (setq exit-after-next 'now)))
14838 ((setq e (rassoc c ntable) tg (car e))
14839 (if (member tg current)
14840 (setq current (delete tg current))
14841 (loop for g in groups do
14842 (if (member tg g)
14843 (mapc (lambda (x)
14844 (setq current (delete x current)))
14845 g)))
14846 (push tg current))
14847 (if exit-after-next (setq exit-after-next 'now))))
14849 ;; Create a sorted list
14850 (setq current
14851 (sort current
14852 (lambda (a b)
14853 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14854 (if (eq exit-after-next 'now) (throw 'exit t))
14855 (goto-char (point-min))
14856 (beginning-of-line 2)
14857 (delete-region (point) (point-at-eol))
14858 (org-fast-tag-insert "Current" current c-face)
14859 (org-set-current-tags-overlay current ov-prefix)
14860 (while (re-search-forward
14861 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14862 (setq tg (match-string 1))
14863 (add-text-properties
14864 (match-beginning 1) (match-end 1)
14865 (list 'face
14866 (cond
14867 ((member tg current) c-face)
14868 ((member tg inherited) i-face)
14869 (t (get-text-property (match-beginning 1) 'face))))))
14870 (goto-char (point-min)))))
14871 (org-detach-overlay org-tags-overlay)
14872 (if rtn
14873 (mapconcat 'identity current ":")
14874 nil))))
14876 (defun org-get-tags-string ()
14877 "Get the TAGS string in the current headline."
14878 (unless (org-at-heading-p t)
14879 (user-error "Not on a heading"))
14880 (save-excursion
14881 (beginning-of-line 1)
14882 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14883 (org-match-string-no-properties 1)
14884 "")))
14886 (defun org-get-tags ()
14887 "Get the list of tags specified in the current headline."
14888 (org-split-string (org-get-tags-string) ":"))
14890 (defun org-get-buffer-tags ()
14891 "Get a table of all tags used in the buffer, for completion."
14892 (let (tags)
14893 (save-excursion
14894 (goto-char (point-min))
14895 (while (re-search-forward
14896 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14897 (when (equal (char-after (point-at-bol 0)) ?*)
14898 (mapc (lambda (x) (add-to-list 'tags x))
14899 (org-split-string (org-match-string-no-properties 1) ":")))))
14900 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14901 (mapcar 'list tags)))
14903 ;;;; The mapping API
14905 (defun org-map-entries (func &optional match scope &rest skip)
14906 "Call FUNC at each headline selected by MATCH in SCOPE.
14908 FUNC is a function or a lisp form. The function will be called without
14909 arguments, with the cursor positioned at the beginning of the headline.
14910 The return values of all calls to the function will be collected and
14911 returned as a list.
14913 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14914 does not need to preserve point. After evaluation, the cursor will be
14915 moved to the end of the line (presumably of the headline of the
14916 processed entry) and search continues from there. Under some
14917 circumstances, this may not produce the wanted results. For example,
14918 if you have removed (e.g. archived) the current (sub)tree it could
14919 mean that the next entry will be skipped entirely. In such cases, you
14920 can specify the position from where search should continue by making
14921 FUNC set the variable `org-map-continue-from' to the desired buffer
14922 position.
14924 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14925 Only headlines that are matched by this query will be considered during
14926 the iteration. When MATCH is nil or t, all headlines will be
14927 visited by the iteration.
14929 SCOPE determines the scope of this command. It can be any of:
14931 nil The current buffer, respecting the restriction if any
14932 tree The subtree started with the entry at point
14933 region The entries within the active region, if any
14934 region-start-level
14935 The entries within the active region, but only those at
14936 the same level than the first one.
14937 file The current buffer, without restriction
14938 file-with-archives
14939 The current buffer, and any archives associated with it
14940 agenda All agenda files
14941 agenda-with-archives
14942 All agenda files with any archive files associated with them
14943 \(file1 file2 ...)
14944 If this is a list, all files in the list will be scanned
14946 The remaining args are treated as settings for the skipping facilities of
14947 the scanner. The following items can be given here:
14949 archive skip trees with the archive tag
14950 comment skip trees with the COMMENT keyword
14951 function or Emacs Lisp form:
14952 will be used as value for `org-agenda-skip-function', so
14953 whenever the function returns a position, FUNC will not be
14954 called for that entry and search will continue from the
14955 position returned
14957 If your function needs to retrieve the tags including inherited tags
14958 at the *current* entry, you can use the value of the variable
14959 `org-scanner-tags' which will be much faster than getting the value
14960 with `org-get-tags-at'. If your function gets properties with
14961 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14962 to t around the call to `org-entry-properties' to get the same speedup.
14963 Note that if your function moves around to retrieve tags and properties at
14964 a *different* entry, you cannot use these techniques."
14965 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14966 (not (org-region-active-p)))
14967 (let* ((org-agenda-archives-mode nil) ; just to make sure
14968 (org-agenda-skip-archived-trees (memq 'archive skip))
14969 (org-agenda-skip-comment-trees (memq 'comment skip))
14970 (org-agenda-skip-function
14971 (car (org-delete-all '(comment archive) skip)))
14972 (org-tags-match-list-sublevels t)
14973 (start-level (eq scope 'region-start-level))
14974 matcher file res
14975 org-todo-keywords-for-agenda
14976 org-done-keywords-for-agenda
14977 org-todo-keyword-alist-for-agenda
14978 org-drawers-for-agenda
14979 org-tag-alist-for-agenda
14980 todo-only)
14982 (cond
14983 ((eq match t) (setq matcher t))
14984 ((eq match nil) (setq matcher t))
14985 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14987 (save-window-excursion
14988 (save-restriction
14989 (cond ((eq scope 'tree)
14990 (org-back-to-heading t)
14991 (org-narrow-to-subtree)
14992 (setq scope nil))
14993 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14994 (org-region-active-p))
14995 ;; If needed, set start-level to a string like "2"
14996 (when start-level
14997 (save-excursion
14998 (goto-char (region-beginning))
14999 (unless (org-at-heading-p) (outline-next-heading))
15000 (setq start-level (org-current-level))))
15001 (narrow-to-region (region-beginning)
15002 (save-excursion
15003 (goto-char (region-end))
15004 (unless (and (bolp) (org-at-heading-p))
15005 (outline-next-heading))
15006 (point)))
15007 (setq scope nil)))
15009 (if (not scope)
15010 (progn
15011 (org-agenda-prepare-buffers
15012 (list (buffer-file-name (current-buffer))))
15013 (setq res (org-scan-tags func matcher todo-only start-level)))
15014 ;; Get the right scope
15015 (cond
15016 ((and scope (listp scope) (symbolp (car scope)))
15017 (setq scope (eval scope)))
15018 ((eq scope 'agenda)
15019 (setq scope (org-agenda-files t)))
15020 ((eq scope 'agenda-with-archives)
15021 (setq scope (org-agenda-files t))
15022 (setq scope (org-add-archive-files scope)))
15023 ((eq scope 'file)
15024 (setq scope (list (buffer-file-name))))
15025 ((eq scope 'file-with-archives)
15026 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15027 (org-agenda-prepare-buffers scope)
15028 (while (setq file (pop scope))
15029 (with-current-buffer (org-find-base-buffer-visiting file)
15030 (save-excursion
15031 (save-restriction
15032 (widen)
15033 (goto-char (point-min))
15034 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15035 res)))
15037 ;;;; Properties
15039 ;;; Setting and retrieving properties
15041 (defconst org-special-properties
15042 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15043 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15044 "The special properties valid in Org-mode.
15046 These are properties that are not defined in the property drawer,
15047 but in some other way.")
15049 (defconst org-default-properties
15050 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15051 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15052 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15053 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15054 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15055 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15056 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15057 "Some properties that are used by Org-mode for various purposes.
15058 Being in this list makes sure that they are offered for completion.")
15060 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15061 "Regular expression matching the first line of a property drawer.")
15063 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15064 "Regular expression matching the last line of a property drawer.")
15066 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15067 "Regular expression matching the first line of a property drawer.")
15069 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15070 "Regular expression matching the first line of a property drawer.")
15072 (defconst org-property-drawer-re
15073 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15074 org-property-end-re "\\)\n?")
15075 "Matches an entire property drawer.")
15077 (defconst org-clock-drawer-re
15078 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15079 org-property-end-re "\\)\n?")
15080 "Matches an entire clock drawer.")
15082 (defun org-property-action ()
15083 "Do an action on properties."
15084 (interactive)
15085 (let (c)
15086 (org-at-property-p)
15087 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15088 (setq c (read-char-exclusive))
15089 (cond
15090 ((equal c ?s)
15091 (call-interactively 'org-set-property))
15092 ((equal c ?d)
15093 (call-interactively 'org-delete-property))
15094 ((equal c ?D)
15095 (call-interactively 'org-delete-property-globally))
15096 ((equal c ?c)
15097 (call-interactively 'org-compute-property-at-point))
15098 (t (user-error "No such property action %c" c)))))
15100 (defun org-inc-effort ()
15101 "Increment the value of the effort property in the current entry."
15102 (interactive)
15103 (org-set-effort nil t))
15105 (defvar org-clock-effort) ;; Defined in org-clock.el
15106 (defvar org-clock-current-task) ;; Defined in org-clock.el
15107 (defun org-set-effort (&optional value increment)
15108 "Set the effort property of the current entry.
15109 With numerical prefix arg, use the nth allowed value, 0 stands for the
15110 10th allowed value.
15112 When INCREMENT is non-nil, set the property to the next allowed value."
15113 (interactive "P")
15114 (if (equal value 0) (setq value 10))
15115 (let* ((completion-ignore-case t)
15116 (prop org-effort-property)
15117 (cur (org-entry-get nil prop))
15118 (allowed (org-property-get-allowed-values nil prop 'table))
15119 (existing (mapcar 'list (org-property-values prop)))
15120 (heading (nth 4 (org-heading-components)))
15122 (val (cond
15123 ((stringp value) value)
15124 ((and allowed (integerp value))
15125 (or (car (nth (1- value) allowed))
15126 (car (org-last allowed))))
15127 ((and allowed increment)
15128 (or (caadr (member (list cur) allowed))
15129 (user-error "Allowed effort values are not set")))
15130 (allowed
15131 (message "Select 1-9,0, [RET%s]: %s"
15132 (if cur (concat "=" cur) "")
15133 (mapconcat 'car allowed " "))
15134 (setq rpl (read-char-exclusive))
15135 (if (equal rpl ?\r)
15137 (setq rpl (- rpl ?0))
15138 (if (equal rpl 0) (setq rpl 10))
15139 (if (and (> rpl 0) (<= rpl (length allowed)))
15140 (car (nth (1- rpl) allowed))
15141 (org-completing-read "Effort: " allowed nil))))
15143 (let (org-completion-use-ido org-completion-use-iswitchb)
15144 (org-completing-read
15145 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15146 (concat "[" cur "]") "")
15147 ": ")
15148 existing nil nil "" nil cur))))))
15149 (unless (equal (org-entry-get nil prop) val)
15150 (org-entry-put nil prop val))
15151 (save-excursion
15152 (org-back-to-heading t)
15153 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15154 (when (string= heading org-clock-current-task)
15155 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15156 (org-clock-update-mode-line))
15157 (message "%s is now %s" prop val)))
15159 (defun org-at-property-p ()
15160 "Is cursor inside a property drawer?"
15161 (save-excursion
15162 (when (equal 'node-property (car (org-element-at-point)))
15163 (beginning-of-line 1)
15164 (looking-at org-property-re))))
15166 (defun org-get-property-block (&optional beg end force)
15167 "Return the (beg . end) range of the body of the property drawer.
15168 BEG and END are the beginning and end of the current subtree, or of
15169 the part before the first headline. If they are not given, they will
15170 be found. If the drawer does not exist and FORCE is non-nil, create
15171 the drawer."
15172 (catch 'exit
15173 (save-excursion
15174 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15175 (progn (org-back-to-heading t) (point))))
15176 (end (or end (and (not (outline-next-heading)) (point-max))
15177 (point))))
15178 (goto-char beg)
15179 (if (re-search-forward org-property-start-re end t)
15180 (setq beg (1+ (match-end 0)))
15181 (if force
15182 (save-excursion
15183 (org-insert-property-drawer)
15184 (setq end (progn (outline-next-heading) (point))))
15185 (throw 'exit nil))
15186 (goto-char beg)
15187 (if (re-search-forward org-property-start-re end t)
15188 (setq beg (1+ (match-end 0)))))
15189 (if (re-search-forward org-property-end-re end t)
15190 (setq end (match-beginning 0))
15191 (or force (throw 'exit nil))
15192 (goto-char beg)
15193 (setq end beg)
15194 (org-indent-line)
15195 (insert ":END:\n"))
15196 (cons beg end)))))
15198 (defun org-entry-properties (&optional pom which specific)
15199 "Get all properties of the entry at point-or-marker POM.
15200 This includes the TODO keyword, the tags, time strings for deadline,
15201 scheduled, and clocking, and any additional properties defined in the
15202 entry. The return value is an alist, keys may occur multiple times
15203 if the property key was used several times.
15204 POM may also be nil, in which case the current entry is used.
15205 If WHICH is nil or `all', get all properties. If WHICH is
15206 `special' or `standard', only get that subclass. If WHICH
15207 is a string only get exactly this property. SPECIFIC can be a string, the
15208 specific property we are interested in. Specifying it can speed
15209 things up because then unnecessary parsing is avoided."
15210 (setq which (or which 'all))
15211 (org-with-point-at pom
15212 (let ((clockstr (substring org-clock-string 0 -1))
15213 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15214 (case-fold-search nil)
15215 beg end range props sum-props key key1 value string clocksum clocksumt)
15216 (save-excursion
15217 (when (condition-case nil
15218 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15219 (error nil))
15220 (setq beg (point))
15221 (setq sum-props (get-text-property (point) 'org-summaries))
15222 (setq clocksum (get-text-property (point) :org-clock-minutes)
15223 clocksumt (get-text-property (point) :org-clock-minutes-today))
15224 (outline-next-heading)
15225 (setq end (point))
15226 (when (memq which '(all special))
15227 ;; Get the special properties, like TODO and tags
15228 (goto-char beg)
15229 (when (and (or (not specific) (string= specific "TODO"))
15230 (looking-at org-todo-line-regexp) (match-end 2))
15231 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15232 (when (and (or (not specific) (string= specific "PRIORITY"))
15233 (looking-at org-priority-regexp))
15234 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15235 (when (or (not specific) (string= specific "FILE"))
15236 (push (cons "FILE" buffer-file-name) props))
15237 (when (and (or (not specific) (string= specific "TAGS"))
15238 (setq value (org-get-tags-string))
15239 (string-match "\\S-" value))
15240 (push (cons "TAGS" value) props))
15241 (when (and (or (not specific) (string= specific "ALLTAGS"))
15242 (setq value (org-get-tags-at)))
15243 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15244 ":"))
15245 props))
15246 (when (or (not specific) (string= specific "BLOCKED"))
15247 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15248 (when (or (not specific)
15249 (member specific
15250 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15251 "TIMESTAMP" "TIMESTAMP_IA")))
15252 (catch 'match
15253 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15254 (setq key (if (match-end 1)
15255 (substring (org-match-string-no-properties 1)
15256 0 -1))
15257 string (if (equal key clockstr)
15258 (org-trim
15259 (buffer-substring-no-properties
15260 (match-beginning 3) (goto-char
15261 (point-at-eol))))
15262 (substring (org-match-string-no-properties 3)
15263 1 -1)))
15264 ;; Get the correct property name from the key. This is
15265 ;; necessary if the user has configured time keywords.
15266 (setq key1 (concat key ":"))
15267 (cond
15268 ((not key)
15269 (setq key
15270 (if (= (char-after (match-beginning 3)) ?\[)
15271 "TIMESTAMP_IA" "TIMESTAMP")))
15272 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15273 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15274 ((equal key1 org-closed-string) (setq key "CLOSED"))
15275 ((equal key1 org-clock-string) (setq key "CLOCK")))
15276 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15277 (progn
15278 (push (cons key string) props)
15279 ;; no need to search further if match is found
15280 (throw 'match t))
15281 (when (or (equal key "CLOCK") (not (assoc key props)))
15282 (push (cons key string) props)))))))
15284 (when (memq which '(all standard))
15285 ;; Get the standard properties, like :PROP: ...
15286 (setq range (org-get-property-block beg end))
15287 (when range
15288 (goto-char (car range))
15289 (while (re-search-forward org-property-re
15290 (cdr range) t)
15291 (setq key (org-match-string-no-properties 2)
15292 value (org-trim (or (org-match-string-no-properties 3) "")))
15293 (unless (member key excluded)
15294 (push (cons key (or value "")) props)))))
15295 (if clocksum
15296 (push (cons "CLOCKSUM"
15297 (org-columns-number-to-string (/ (float clocksum) 60.)
15298 'add_times))
15299 props))
15300 (if clocksumt
15301 (push (cons "CLOCKSUM_T"
15302 (org-columns-number-to-string (/ (float clocksumt) 60.)
15303 'add_times))
15304 props))
15305 (unless (assoc "CATEGORY" props)
15306 (push (cons "CATEGORY" (org-get-category)) props))
15307 (append sum-props (nreverse props)))))))
15309 (defun org-entry-get (pom property &optional inherit literal-nil)
15310 "Get value of PROPERTY for entry or content at point-or-marker POM.
15311 If INHERIT is non-nil and the entry does not have the property,
15312 then also check higher levels of the hierarchy.
15313 If INHERIT is the symbol `selective', use inheritance only if the setting
15314 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15315 If the property is present but empty, the return value is the empty string.
15316 If the property is not present at all, nil is returned.
15318 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15319 do not interpret it as the list atom nil. This is used for inheritance
15320 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15321 (org-with-point-at pom
15322 (if (and inherit (if (eq inherit 'selective)
15323 (org-property-inherit-p property)
15325 (org-entry-get-with-inheritance property literal-nil)
15326 (if (member property org-special-properties)
15327 ;; We need a special property. Use `org-entry-properties' to
15328 ;; retrieve it, but specify the wanted property
15329 (cdr (assoc property (org-entry-properties nil 'special property)))
15330 (let ((range (org-get-property-block)))
15331 (when (and range (not (eq (car range) (cdr range))))
15332 (let* ((props (list (or (assoc property org-file-properties)
15333 (assoc property org-global-properties)
15334 (assoc property org-global-properties-fixed))))
15335 (ap (lambda (key)
15336 (when (re-search-forward
15337 (org-re-property key) (cdr range) t)
15338 (setq props
15339 (org-update-property-plist
15341 (if (match-end 3)
15342 (org-match-string-no-properties 3) "")
15343 props)))))
15344 val)
15345 (goto-char (car range))
15346 (funcall ap property)
15347 (goto-char (car range))
15348 (while (funcall ap (concat property "+")))
15349 (setq val (cdr (assoc property props)))
15350 (when val (if literal-nil val (org-not-nil val))))))))))
15352 (defun org-property-or-variable-value (var &optional inherit)
15353 "Check if there is a property fixing the value of VAR.
15354 If yes, return this value. If not, return the current value of the variable."
15355 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15356 (if (and prop (stringp prop) (string-match "\\S-" prop))
15357 (read prop)
15358 (symbol-value var))))
15360 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15361 "Delete the property PROPERTY from entry at point-or-marker POM.
15362 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15363 an empty drawer to delete."
15364 (org-with-point-at pom
15365 (if (member property org-special-properties)
15366 nil ; cannot delete these properties.
15367 (let ((range (org-get-property-block)))
15368 (if (and range
15369 (goto-char (car range))
15370 (re-search-forward
15371 (org-re-property property)
15372 (cdr range) t))
15373 (progn
15374 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15375 (and delete-empty-drawer
15376 (org-remove-empty-drawer-at
15377 delete-empty-drawer (car range)))
15379 nil)))))
15381 ;; Multi-values properties are properties that contain multiple values
15382 ;; These values are assumed to be single words, separated by whitespace.
15383 (defun org-entry-add-to-multivalued-property (pom property value)
15384 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15385 (let* ((old (org-entry-get pom property))
15386 (values (and old (org-split-string old "[ \t]"))))
15387 (setq value (org-entry-protect-space value))
15388 (unless (member value values)
15389 (setq values (append values (list value)))
15390 (org-entry-put pom property
15391 (mapconcat 'identity values " ")))))
15393 (defun org-entry-remove-from-multivalued-property (pom property value)
15394 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15395 (let* ((old (org-entry-get pom property))
15396 (values (and old (org-split-string old "[ \t]"))))
15397 (setq value (org-entry-protect-space value))
15398 (when (member value values)
15399 (setq values (delete value values))
15400 (org-entry-put pom property
15401 (mapconcat 'identity values " ")))))
15403 (defun org-entry-member-in-multivalued-property (pom property value)
15404 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15405 (let* ((old (org-entry-get pom property))
15406 (values (and old (org-split-string old "[ \t]"))))
15407 (setq value (org-entry-protect-space value))
15408 (member value values)))
15410 (defun org-entry-get-multivalued-property (pom property)
15411 "Return a list of values in a multivalued property."
15412 (let* ((value (org-entry-get pom property))
15413 (values (and value (org-split-string value "[ \t]"))))
15414 (mapcar 'org-entry-restore-space values)))
15416 (defun org-entry-put-multivalued-property (pom property &rest values)
15417 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15418 VALUES should be a list of strings. Spaces will be protected."
15419 (org-entry-put pom property
15420 (mapconcat 'org-entry-protect-space values " "))
15421 (let* ((value (org-entry-get pom property))
15422 (values (and value (org-split-string value "[ \t]"))))
15423 (mapcar 'org-entry-restore-space values)))
15425 (defun org-entry-protect-space (s)
15426 "Protect spaces and newline in string S."
15427 (while (string-match " " s)
15428 (setq s (replace-match "%20" t t s)))
15429 (while (string-match "\n" s)
15430 (setq s (replace-match "%0A" t t s)))
15433 (defun org-entry-restore-space (s)
15434 "Restore spaces and newline in string S."
15435 (while (string-match "%20" s)
15436 (setq s (replace-match " " t t s)))
15437 (while (string-match "%0A" s)
15438 (setq s (replace-match "\n" t t s)))
15441 (defvar org-entry-property-inherited-from (make-marker)
15442 "Marker pointing to the entry from where a property was inherited.
15443 Each call to `org-entry-get-with-inheritance' will set this marker to the
15444 location of the entry where the inheritance search matched. If there was
15445 no match, the marker will point nowhere.
15446 Note that also `org-entry-get' calls this function, if the INHERIT flag
15447 is set.")
15449 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15450 "Get PROPERTY of entry or content at point, search higher levels if needed.
15451 The search will stop at the first ancestor which has the property defined.
15452 If the value found is \"nil\", return nil to show that the property
15453 should be considered as undefined (this is the meaning of nil here).
15454 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15455 (move-marker org-entry-property-inherited-from nil)
15456 (let (tmp)
15457 (save-excursion
15458 (save-restriction
15459 (widen)
15460 (catch 'ex
15461 (while t
15462 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15463 (or (ignore-errors (org-back-to-heading t))
15464 (goto-char (point-min)))
15465 (move-marker org-entry-property-inherited-from (point))
15466 (throw 'ex tmp))
15467 (or (ignore-errors (org-up-heading-safe))
15468 (throw 'ex nil))))))
15469 (setq tmp (or tmp
15470 (cdr (assoc property org-file-properties))
15471 (cdr (assoc property org-global-properties))
15472 (cdr (assoc property org-global-properties-fixed))))
15473 (if literal-nil tmp (org-not-nil tmp))))
15475 (defvar org-property-changed-functions nil
15476 "Hook called when the value of a property has changed.
15477 Each hook function should accept two arguments, the name of the property
15478 and the new value.")
15480 (defun org-entry-put (pom property value)
15481 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15482 (org-with-point-at pom
15483 (org-back-to-heading t)
15484 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15485 range)
15486 (cond
15487 ((equal property "TODO")
15488 (when (and (stringp value) (string-match "\\S-" value)
15489 (not (member value org-todo-keywords-1)))
15490 (user-error "\"%s\" is not a valid TODO state" value))
15491 (if (or (not value)
15492 (not (string-match "\\S-" value)))
15493 (setq value 'none))
15494 (org-todo value)
15495 (org-set-tags nil 'align))
15496 ((equal property "PRIORITY")
15497 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15498 (string-to-char value) ?\ ))
15499 (org-set-tags nil 'align))
15500 ((equal property "CLOCKSUM")
15501 (if (not (re-search-forward
15502 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15503 (error "Cannot find a clock log")
15504 (goto-char (- (match-end 1) 2))
15505 (cond
15506 ((eq value 'earlier) (org-timestamp-down))
15507 ((eq value 'later) (org-timestamp-up)))
15508 (org-clock-sum-current-item)))
15509 ((equal property "SCHEDULED")
15510 (if (re-search-forward org-scheduled-time-regexp end t)
15511 (cond
15512 ((eq value 'earlier) (org-timestamp-change -1 'day))
15513 ((eq value 'later) (org-timestamp-change 1 'day))
15514 (t (call-interactively 'org-schedule)))
15515 (call-interactively 'org-schedule)))
15516 ((equal property "DEADLINE")
15517 (if (re-search-forward org-deadline-time-regexp end t)
15518 (cond
15519 ((eq value 'earlier) (org-timestamp-change -1 'day))
15520 ((eq value 'later) (org-timestamp-change 1 'day))
15521 (t (call-interactively 'org-deadline)))
15522 (call-interactively 'org-deadline)))
15523 ((member property org-special-properties)
15524 (error "The %s property can not yet be set with `org-entry-put'"
15525 property))
15526 (t ; a non-special property
15527 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15528 (setq range (org-get-property-block beg end 'force))
15529 (goto-char (car range))
15530 (if (re-search-forward
15531 (org-re-property property) (cdr range) t)
15532 (progn
15533 (delete-region (match-beginning 0) (match-end 0))
15534 (goto-char (match-beginning 0)))
15535 (goto-char (cdr range))
15536 (insert "\n")
15537 (backward-char 1)
15538 (org-indent-line))
15539 (insert ":" property ":")
15540 (and value (insert " " value))
15541 (org-indent-line)))))
15542 (run-hook-with-args 'org-property-changed-functions property value)))
15544 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15545 "Get all property keys in the current buffer.
15546 With INCLUDE-SPECIALS, also list the special properties that reflect things
15547 like tags and TODO state.
15548 With INCLUDE-DEFAULTS, also include properties that has special meaning
15549 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15550 and others.
15551 With INCLUDE-COLUMNS, also include property names given in COLUMN
15552 formats in the current buffer."
15553 (let (rtn range cfmt s p)
15554 (save-excursion
15555 (save-restriction
15556 (widen)
15557 (goto-char (point-min))
15558 (while (re-search-forward org-property-start-re nil t)
15559 (setq range (org-get-property-block))
15560 (goto-char (car range))
15561 (while (re-search-forward org-property-re
15562 (cdr range) t)
15563 (add-to-list 'rtn (org-match-string-no-properties 2)))
15564 (outline-next-heading))))
15566 (when include-specials
15567 (setq rtn (append org-special-properties rtn)))
15569 (when include-defaults
15570 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15571 (add-to-list 'rtn org-effort-property))
15573 (when include-columns
15574 (save-excursion
15575 (save-restriction
15576 (widen)
15577 (goto-char (point-min))
15578 (while (re-search-forward
15579 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15580 nil t)
15581 (setq cfmt (match-string 2) s 0)
15582 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15583 cfmt s)
15584 (setq s (match-end 0)
15585 p (match-string 1 cfmt))
15586 (unless (or (equal p "ITEM")
15587 (member p org-special-properties))
15588 (add-to-list 'rtn (match-string 1 cfmt))))))))
15590 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15592 (defun org-property-values (key)
15593 "Return a list of all values of property KEY in the current buffer."
15594 (save-excursion
15595 (save-restriction
15596 (widen)
15597 (goto-char (point-min))
15598 (let ((re (org-re-property key))
15599 values)
15600 (while (re-search-forward re nil t)
15601 (add-to-list 'values (org-trim (match-string 3))))
15602 (delete "" values)))))
15604 (defun org-insert-property-drawer ()
15605 "Insert a property drawer into the current entry."
15606 (org-back-to-heading t)
15607 (looking-at org-outline-regexp)
15608 (let ((indent (if org-adapt-indentation
15609 (- (match-end 0) (match-beginning 0))
15611 (beg (point))
15612 (re (concat "^[ \t]*" org-keyword-time-regexp))
15613 end hiddenp)
15614 (outline-next-heading)
15615 (setq end (point))
15616 (goto-char beg)
15617 (while (re-search-forward re end t))
15618 (setq hiddenp (outline-invisible-p))
15619 (end-of-line 1)
15620 (and (equal (char-after) ?\n) (forward-char 1))
15621 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15622 (if (member (match-string 1) '("CLOCK:" ":END:"))
15623 ;; just skip this line
15624 (beginning-of-line 2)
15625 ;; Drawer start, find the end
15626 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15627 (beginning-of-line 1)))
15628 (org-skip-over-state-notes)
15629 (skip-chars-backward " \t\n\r")
15630 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15631 (forward-char 1))
15632 (goto-char (point-at-eol))
15633 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15634 (beginning-of-line 0)
15635 (org-indent-to-column indent)
15636 (beginning-of-line 2)
15637 (org-indent-to-column indent)
15638 (beginning-of-line 0)
15639 (if hiddenp
15640 (save-excursion
15641 (org-back-to-heading t)
15642 (hide-entry))
15643 (org-flag-drawer t))))
15645 (defun org-insert-drawer (&optional arg drawer)
15646 "Insert a drawer at point.
15648 Optional argument DRAWER, when non-nil, is a string representing
15649 drawer's name. Otherwise, the user is prompted for a name.
15651 If a region is active, insert the drawer around that region
15652 instead.
15654 Point is left between drawer's boundaries."
15655 (interactive "P")
15656 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15657 "LOGBOOK"))
15658 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15659 ;; internally by Org. They are meant to be inserted
15660 ;; automatically.
15661 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15662 ;; Remove system drawers from list. Note: For some reason,
15663 ;; `org-completing-read' ignores the predicate while
15664 ;; `completing-read' handles it fine.
15665 (drawer (if arg "PROPERTIES"
15666 (or drawer
15667 (completing-read
15668 "Drawer: " org-drawers
15669 (lambda (d) (not (member d system-drawers))))))))
15670 (cond
15671 ;; With C-u, fall back on `org-insert-property-drawer'
15672 (arg (org-insert-property-drawer))
15673 ;; With an active region, insert a drawer at point.
15674 ((not (org-region-active-p))
15675 (progn
15676 (unless (bolp) (insert "\n"))
15677 (insert (format ":%s:\n\n:END:\n" drawer))
15678 (forward-line -2)))
15679 ;; Otherwise, insert the drawer at point
15681 (let ((rbeg (region-beginning))
15682 (rend (copy-marker (region-end))))
15683 (unwind-protect
15684 (progn
15685 (goto-char rbeg)
15686 (beginning-of-line)
15687 (when (save-excursion
15688 (re-search-forward org-outline-regexp-bol rend t))
15689 (user-error "Drawers cannot contain headlines"))
15690 ;; Position point at the beginning of the first
15691 ;; non-blank line in region. Insert drawer's opening
15692 ;; there, then indent it.
15693 (org-skip-whitespace)
15694 (beginning-of-line)
15695 (insert ":" drawer ":\n")
15696 (forward-line -1)
15697 (indent-for-tab-command)
15698 ;; Move point to the beginning of the first blank line
15699 ;; after the last non-blank line in region. Insert
15700 ;; drawer's closing, then indent it.
15701 (goto-char rend)
15702 (skip-chars-backward " \r\t\n")
15703 (insert "\n:END:")
15704 (deactivate-mark t)
15705 (indent-for-tab-command)
15706 (unless (eolp) (insert "\n")))
15707 ;; Clear marker, whatever the outcome of insertion is.
15708 (set-marker rend nil)))))))
15710 (defvar org-property-set-functions-alist nil
15711 "Property set function alist.
15712 Each entry should have the following format:
15714 (PROPERTY . READ-FUNCTION)
15716 The read function will be called with the same argument as
15717 `org-completing-read'.")
15719 (defun org-set-property-function (property)
15720 "Get the function that should be used to set PROPERTY.
15721 This is computed according to `org-property-set-functions-alist'."
15722 (or (cdr (assoc property org-property-set-functions-alist))
15723 'org-completing-read))
15725 (defun org-read-property-value (property)
15726 "Read PROPERTY value from user."
15727 (let* ((completion-ignore-case t)
15728 (allowed (org-property-get-allowed-values nil property 'table))
15729 (cur (org-entry-get nil property))
15730 (prompt (concat property " value"
15731 (if (and cur (string-match "\\S-" cur))
15732 (concat " [" cur "]") "") ": "))
15733 (set-function (org-set-property-function property))
15734 (val (if allowed
15735 (funcall set-function prompt allowed nil
15736 (not (get-text-property 0 'org-unrestricted
15737 (caar allowed))))
15738 (let (org-completion-use-ido org-completion-use-iswitchb)
15739 (funcall set-function prompt
15740 (mapcar 'list (org-property-values property))
15741 nil nil "" nil cur)))))
15742 (if (equal val "")
15744 val)))
15746 (defvar org-last-set-property nil)
15747 (defvar org-last-set-property-value nil)
15748 (defun org-read-property-name ()
15749 "Read a property name."
15750 (let* ((completion-ignore-case t)
15751 (keys (org-buffer-property-keys nil t t))
15752 (default-prop (or (save-excursion
15753 (save-match-data
15754 (beginning-of-line)
15755 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15756 (null (string= (match-string 1) "END"))
15757 (match-string 1))))
15758 org-last-set-property))
15759 (property (org-icompleting-read
15760 (concat "Property"
15761 (if default-prop (concat " [" default-prop "]") "")
15762 ": ")
15763 (mapcar 'list keys)
15764 nil nil nil nil
15765 default-prop)))
15766 (if (member property keys)
15767 property
15768 (or (cdr (assoc (downcase property)
15769 (mapcar (lambda (x) (cons (downcase x) x))
15770 keys)))
15771 property))))
15773 (defun org-set-property-and-value (use-last)
15774 "Allow to set [PROPERTY]: [value] direction from prompt.
15775 When use-default, don't even ask, just use the last
15776 \"[PROPERTY]: [value]\" string from the history."
15777 (interactive "P")
15778 (let* ((completion-ignore-case t)
15779 (pv (or (and use-last org-last-set-property-value)
15780 (org-completing-read
15781 "Enter a \"[Property]: [value]\" pair: "
15782 nil nil nil nil nil
15783 org-last-set-property-value)))
15784 prop val)
15785 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15786 (setq prop (match-string 1 pv)
15787 val (match-string 2 pv))
15788 (org-set-property prop val))))
15790 (defun org-set-property (property value)
15791 "In the current entry, set PROPERTY to VALUE.
15792 When called interactively, this will prompt for a property name, offering
15793 completion on existing and default properties. And then it will prompt
15794 for a value, offering completion either on allowed values (via an inherited
15795 xxx_ALL property) or on existing values in other instances of this property
15796 in the current file."
15797 (interactive (list nil nil))
15798 (let* ((property (or property (org-read-property-name)))
15799 (value (or value (org-read-property-value property)))
15800 (fn (cdr (assoc property org-properties-postprocess-alist))))
15801 (setq org-last-set-property property)
15802 (setq org-last-set-property-value (concat property ": " value))
15803 ;; Possibly postprocess the inserted value:
15804 (when fn (setq value (funcall fn value)))
15805 (unless (equal (org-entry-get nil property) value)
15806 (org-entry-put nil property value))))
15808 (defun org-delete-property (property &optional delete-empty-drawer)
15809 "In the current entry, delete PROPERTY.
15810 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15811 an empty drawer to delete."
15812 (interactive
15813 (let* ((completion-ignore-case t)
15814 (prop (org-icompleting-read "Property: "
15815 (org-entry-properties nil 'standard))))
15816 (list prop)))
15817 (message "Property %s %s" property
15818 (if (org-entry-delete nil property delete-empty-drawer)
15819 "deleted"
15820 "was not present in the entry")))
15822 (defun org-delete-property-globally (property)
15823 "Remove PROPERTY globally, from all entries."
15824 (interactive
15825 (let* ((completion-ignore-case t)
15826 (prop (org-icompleting-read
15827 "Globally remove property: "
15828 (mapcar 'list (org-buffer-property-keys)))))
15829 (list prop)))
15830 (save-excursion
15831 (save-restriction
15832 (widen)
15833 (goto-char (point-min))
15834 (let ((cnt 0))
15835 (while (re-search-forward
15836 (org-re-property property)
15837 nil t)
15838 (setq cnt (1+ cnt))
15839 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15840 (message "Property \"%s\" removed from %d entries" property cnt)))))
15842 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15844 (defun org-compute-property-at-point ()
15845 "Compute the property at point.
15846 This looks for an enclosing column format, extracts the operator and
15847 then applies it to the property in the column format's scope."
15848 (interactive)
15849 (unless (org-at-property-p)
15850 (user-error "Not at a property"))
15851 (let ((prop (org-match-string-no-properties 2)))
15852 (org-columns-get-format-and-top-level)
15853 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15854 (user-error "No operator defined for property %s" prop))
15855 (org-columns-compute prop)))
15857 (defvar org-property-allowed-value-functions nil
15858 "Hook for functions supplying allowed values for a specific property.
15859 The functions must take a single argument, the name of the property, and
15860 return a flat list of allowed values. If \":ETC\" is one of
15861 the values, this means that these values are intended as defaults for
15862 completion, but that other values should be allowed too.
15863 The functions must return nil if they are not responsible for this
15864 property.")
15866 (defun org-property-get-allowed-values (pom property &optional table)
15867 "Get allowed values for the property PROPERTY.
15868 When TABLE is non-nil, return an alist that can directly be used for
15869 completion."
15870 (let (vals)
15871 (cond
15872 ((equal property "TODO")
15873 (setq vals (org-with-point-at pom
15874 (append org-todo-keywords-1 '("")))))
15875 ((equal property "PRIORITY")
15876 (let ((n org-lowest-priority))
15877 (while (>= n org-highest-priority)
15878 (push (char-to-string n) vals)
15879 (setq n (1- n)))))
15880 ((member property org-special-properties))
15881 ((setq vals (run-hook-with-args-until-success
15882 'org-property-allowed-value-functions property)))
15884 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15885 (when (and vals (string-match "\\S-" vals))
15886 (setq vals (car (read-from-string (concat "(" vals ")"))))
15887 (setq vals (mapcar (lambda (x)
15888 (cond ((stringp x) x)
15889 ((numberp x) (number-to-string x))
15890 ((symbolp x) (symbol-name x))
15891 (t "???")))
15892 vals)))))
15893 (when (member ":ETC" vals)
15894 (setq vals (remove ":ETC" vals))
15895 (org-add-props (car vals) '(org-unrestricted t)))
15896 (if table (mapcar 'list vals) vals)))
15898 (defun org-property-previous-allowed-value (&optional previous)
15899 "Switch to the next allowed value for this property."
15900 (interactive)
15901 (org-property-next-allowed-value t))
15903 (defun org-property-next-allowed-value (&optional previous)
15904 "Switch to the next allowed value for this property."
15905 (interactive)
15906 (unless (org-at-property-p)
15907 (user-error "Not at a property"))
15908 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15909 (key (match-string 2))
15910 (value (match-string 3))
15911 (allowed (or (org-property-get-allowed-values (point) key)
15912 (and (member value '("[ ]" "[-]" "[X]"))
15913 '("[ ]" "[X]"))))
15914 (heading (save-match-data (nth 4 (org-heading-components))))
15915 nval)
15916 (unless allowed
15917 (user-error "Allowed values for this property have not been defined"))
15918 (if previous (setq allowed (reverse allowed)))
15919 (if (member value allowed)
15920 (setq nval (car (cdr (member value allowed)))))
15921 (setq nval (or nval (car allowed)))
15922 (if (equal nval value)
15923 (user-error "Only one allowed value for this property"))
15924 (org-at-property-p)
15925 (replace-match (concat " :" key ": " nval) t t)
15926 (org-indent-line)
15927 (beginning-of-line 1)
15928 (skip-chars-forward " \t")
15929 (when (equal prop org-effort-property)
15930 (save-excursion
15931 (org-back-to-heading t)
15932 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15933 (when (string= org-clock-current-task heading)
15934 (setq org-clock-effort nval)
15935 (org-clock-update-mode-line)))
15936 (run-hook-with-args 'org-property-changed-functions key nval)))
15938 (defun org-find-olp (path &optional this-buffer)
15939 "Return a marker pointing to the entry at outline path OLP.
15940 If anything goes wrong, throw an error.
15941 You can wrap this call to catch the error like this:
15943 (condition-case msg
15944 (org-mobile-locate-entry (match-string 4))
15945 (error (nth 1 msg)))
15947 The return value will then be either a string with the error message,
15948 or a marker if everything is OK.
15950 If THIS-BUFFER is set, the outline path does not contain a file,
15951 only headings."
15952 (let* ((file (if this-buffer buffer-file-name (pop path)))
15953 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15954 (level 1)
15955 (lmin 1)
15956 (lmax 1)
15957 limit re end found pos heading cnt flevel)
15958 (unless buffer (error "File not found :%s" file))
15959 (with-current-buffer buffer
15960 (save-excursion
15961 (save-restriction
15962 (widen)
15963 (setq limit (point-max))
15964 (goto-char (point-min))
15965 (while (setq heading (pop path))
15966 (setq re (format org-complex-heading-regexp-format
15967 (regexp-quote heading)))
15968 (setq cnt 0 pos (point))
15969 (while (re-search-forward re end t)
15970 (setq level (- (match-end 1) (match-beginning 1)))
15971 (if (and (>= level lmin) (<= level lmax))
15972 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15973 (when (= cnt 0) (error "Heading not found on level %d: %s"
15974 lmax heading))
15975 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15976 lmax heading))
15977 (goto-char found)
15978 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15979 (setq end (save-excursion (org-end-of-subtree t t))))
15980 (when (org-at-heading-p)
15981 (point-marker)))))))
15983 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15984 "Find node HEADING in BUFFER.
15985 Return a marker to the heading if it was found, or nil if not.
15986 If POS-ONLY is set, return just the position instead of a marker.
15988 The heading text must match exact, but it may have a TODO keyword,
15989 a priority cookie and tags in the standard locations."
15990 (with-current-buffer (or buffer (current-buffer))
15991 (save-excursion
15992 (save-restriction
15993 (widen)
15994 (goto-char (point-min))
15995 (let (case-fold-search)
15996 (if (re-search-forward
15997 (format org-complex-heading-regexp-format
15998 (regexp-quote heading)) nil t)
15999 (if pos-only
16000 (match-beginning 0)
16001 (move-marker (make-marker) (match-beginning 0)))))))))
16003 (defun org-find-exact-heading-in-directory (heading &optional dir)
16004 "Find Org node headline HEADING in all .org files in directory DIR.
16005 When the target headline is found, return a marker to this location."
16006 (let ((files (directory-files (or dir default-directory)
16007 nil "\\`[^.#].*\\.org\\'"))
16008 file visiting m buffer)
16009 (catch 'found
16010 (while (setq file (pop files))
16011 (message "trying %s" file)
16012 (setq visiting (org-find-base-buffer-visiting file))
16013 (setq buffer (or visiting (find-file-noselect file)))
16014 (setq m (org-find-exact-headline-in-buffer
16015 heading buffer))
16016 (when (and (not m) (not visiting)) (kill-buffer buffer))
16017 (and m (throw 'found m))))))
16019 (defun org-find-entry-with-id (ident)
16020 "Locate the entry that contains the ID property with exact value IDENT.
16021 IDENT can be a string, a symbol or a number, this function will search for
16022 the string representation of it.
16023 Return the position where this entry starts, or nil if there is no such entry."
16024 (interactive "sID: ")
16025 (let ((id (cond
16026 ((stringp ident) ident)
16027 ((symbol-name ident) (symbol-name ident))
16028 ((numberp ident) (number-to-string ident))
16029 (t (error "IDENT %s must be a string, symbol or number" ident))))
16030 (case-fold-search nil))
16031 (save-excursion
16032 (save-restriction
16033 (widen)
16034 (goto-char (point-min))
16035 (when (re-search-forward
16036 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16037 nil t)
16038 (org-back-to-heading t)
16039 (point))))))
16041 ;;;; Timestamps
16043 (defvar org-last-changed-timestamp nil)
16044 (defvar org-last-inserted-timestamp nil
16045 "The last time stamp inserted with `org-insert-time-stamp'.")
16046 (defvar org-ts-what) ; dynamically scoped parameter
16048 (defun org-time-stamp (arg &optional inactive)
16049 "Prompt for a date/time and insert a time stamp.
16050 If the user specifies a time like HH:MM or if this command is
16051 called with at least one prefix argument, the time stamp contains
16052 the date and the time. Otherwise, only the date is be included.
16054 All parts of a date not specified by the user is filled in from
16055 the current date/time. So if you just press return without
16056 typing anything, the time stamp will represent the current
16057 date/time.
16059 If there is already a timestamp at the cursor, it will be
16060 modified.
16062 With two universal prefix arguments, insert an active timestamp
16063 with the current time without prompting the user.
16065 When called from lisp, the timestamp is inactive if INACTIVE is
16066 non-nil."
16067 (interactive "P")
16068 (let* ((ts nil)
16069 (default-time
16070 ;; Default time is either today, or, when entering a range,
16071 ;; the range start.
16072 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16073 (save-excursion
16074 (re-search-backward
16075 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16076 (- (point) 20) t)))
16077 (apply 'encode-time (org-parse-time-string (match-string 1)))
16078 (current-time)))
16079 (default-input (and ts (org-get-compact-tod ts)))
16080 (repeater (save-excursion
16081 (save-match-data
16082 (beginning-of-line)
16083 (when (re-search-forward
16084 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16085 (save-excursion (progn (end-of-line) (point))) t)
16086 (match-string 0)))))
16087 org-time-was-given org-end-time-was-given time)
16088 (cond
16089 ((and (org-at-timestamp-p t)
16090 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16091 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16092 (insert "--")
16093 (setq time (let ((this-command this-command))
16094 (org-read-date arg 'totime nil nil
16095 default-time default-input inactive)))
16096 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16097 ((org-at-timestamp-p t)
16098 (setq time (let ((this-command this-command))
16099 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16100 (when (org-at-timestamp-p t) ; just to get the match data
16101 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16102 (replace-match "")
16103 (setq org-last-changed-timestamp
16104 (org-insert-time-stamp
16105 time (or org-time-was-given arg)
16106 inactive nil nil (list org-end-time-was-given)))
16107 (when repeater (goto-char (1- (point))) (insert " " repeater)
16108 (setq org-last-changed-timestamp
16109 (concat (substring org-last-inserted-timestamp 0 -1)
16110 " " repeater ">"))))
16111 (message "Timestamp updated"))
16112 ((equal arg '(16))
16113 (org-insert-time-stamp (current-time) t inactive))
16115 (setq time (let ((this-command this-command))
16116 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16117 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16118 nil nil (list org-end-time-was-given))))))
16120 ;; FIXME: can we use this for something else, like computing time differences?
16121 (defun org-get-compact-tod (s)
16122 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16123 (let* ((t1 (match-string 1 s))
16124 (h1 (string-to-number (match-string 2 s)))
16125 (m1 (string-to-number (match-string 3 s)))
16126 (t2 (and (match-end 4) (match-string 5 s)))
16127 (h2 (and t2 (string-to-number (match-string 6 s))))
16128 (m2 (and t2 (string-to-number (match-string 7 s))))
16129 dh dm)
16130 (if (not t2)
16132 (setq dh (- h2 h1) dm (- m2 m1))
16133 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16134 (concat t1 "+" (number-to-string dh)
16135 (and (/= 0 dm) (format ":%02d" dm)))))))
16137 (defun org-time-stamp-inactive (&optional arg)
16138 "Insert an inactive time stamp.
16139 An inactive time stamp is enclosed in square brackets instead of angle
16140 brackets. It is inactive in the sense that it does not trigger agenda entries,
16141 does not link to the calendar and cannot be changed with the S-cursor keys.
16142 So these are more for recording a certain time/date."
16143 (interactive "P")
16144 (org-time-stamp arg 'inactive))
16146 (defvar org-date-ovl (make-overlay 1 1))
16147 (overlay-put org-date-ovl 'face 'org-date-selected)
16148 (org-detach-overlay org-date-ovl)
16150 (defvar org-ans1) ; dynamically scoped parameter
16151 (defvar org-ans2) ; dynamically scoped parameter
16153 (defvar org-plain-time-of-day-regexp) ; defined below
16155 (defvar org-overriding-default-time nil) ; dynamically scoped
16156 (defvar org-read-date-overlay nil)
16157 (defvar org-dcst nil) ; dynamically scoped
16158 (defvar org-read-date-history nil)
16159 (defvar org-read-date-final-answer nil)
16160 (defvar org-read-date-analyze-futurep nil)
16161 (defvar org-read-date-analyze-forced-year nil)
16162 (defvar org-read-date-inactive)
16164 (defvar org-read-date-minibuffer-local-map
16165 (let* ((org-replace-disputed-keys nil)
16166 (map (make-sparse-keymap)))
16167 (set-keymap-parent map minibuffer-local-map)
16168 (org-defkey map (kbd ".")
16169 (lambda () (interactive)
16170 ;; Are we at the beginning of the prompt?
16171 (if (looking-back "^[^:]+: ")
16172 (org-eval-in-calendar '(calendar-goto-today))
16173 (insert "."))))
16174 (org-defkey map (kbd "C-.")
16175 (lambda () (interactive)
16176 (org-eval-in-calendar '(calendar-goto-today))))
16177 (org-defkey map [(meta shift left)]
16178 (lambda () (interactive)
16179 (org-eval-in-calendar '(calendar-backward-month 1))))
16180 (org-defkey map [(meta shift right)]
16181 (lambda () (interactive)
16182 (org-eval-in-calendar '(calendar-forward-month 1))))
16183 (org-defkey map [(meta shift up)]
16184 (lambda () (interactive)
16185 (org-eval-in-calendar '(calendar-backward-year 1))))
16186 (org-defkey map [(meta shift down)]
16187 (lambda () (interactive)
16188 (org-eval-in-calendar '(calendar-forward-year 1))))
16189 (org-defkey map [?\e (shift left)]
16190 (lambda () (interactive)
16191 (org-eval-in-calendar '(calendar-backward-month 1))))
16192 (org-defkey map [?\e (shift right)]
16193 (lambda () (interactive)
16194 (org-eval-in-calendar '(calendar-forward-month 1))))
16195 (org-defkey map [?\e (shift up)]
16196 (lambda () (interactive)
16197 (org-eval-in-calendar '(calendar-backward-year 1))))
16198 (org-defkey map [?\e (shift down)]
16199 (lambda () (interactive)
16200 (org-eval-in-calendar '(calendar-forward-year 1))))
16201 (org-defkey map [(shift up)]
16202 (lambda () (interactive)
16203 (org-eval-in-calendar '(calendar-backward-week 1))))
16204 (org-defkey map [(shift down)]
16205 (lambda () (interactive)
16206 (org-eval-in-calendar '(calendar-forward-week 1))))
16207 (org-defkey map [(shift left)]
16208 (lambda () (interactive)
16209 (org-eval-in-calendar '(calendar-backward-day 1))))
16210 (org-defkey map [(shift right)]
16211 (lambda () (interactive)
16212 (org-eval-in-calendar '(calendar-forward-day 1))))
16213 (org-defkey map "!"
16214 (lambda () (interactive)
16215 (org-eval-in-calendar '(diary-view-entries))
16216 (message "")))
16217 (org-defkey map ">"
16218 (lambda () (interactive)
16219 (org-eval-in-calendar '(scroll-calendar-left 1))))
16220 (org-defkey map "<"
16221 (lambda () (interactive)
16222 (org-eval-in-calendar '(scroll-calendar-right 1))))
16223 (org-defkey map "\C-v"
16224 (lambda () (interactive)
16225 (org-eval-in-calendar
16226 '(calendar-scroll-left-three-months 1))))
16227 (org-defkey map "\M-v"
16228 (lambda () (interactive)
16229 (org-eval-in-calendar
16230 '(calendar-scroll-right-three-months 1))))
16231 map)
16232 "Keymap for minibuffer commands when using `org-read-date'.")
16234 (defvar org-def)
16235 (defvar org-defdecode)
16236 (defvar org-with-time)
16238 (defun org-read-date (&optional org-with-time to-time from-string prompt
16239 default-time default-input inactive)
16240 "Read a date, possibly a time, and make things smooth for the user.
16241 The prompt will suggest to enter an ISO date, but you can also enter anything
16242 which will at least partially be understood by `parse-time-string'.
16243 Unrecognized parts of the date will default to the current day, month, year,
16244 hour and minute. If this command is called to replace a timestamp at point,
16245 or to enter the second timestamp of a range, the default time is taken
16246 from the existing stamp. Furthermore, the command prefers the future,
16247 so if you are giving a date where the year is not given, and the day-month
16248 combination is already past in the current year, it will assume you
16249 mean next year. For details, see the manual. A few examples:
16251 3-2-5 --> 2003-02-05
16252 feb 15 --> currentyear-02-15
16253 2/15 --> currentyear-02-15
16254 sep 12 9 --> 2009-09-12
16255 12:45 --> today 12:45
16256 22 sept 0:34 --> currentyear-09-22 0:34
16257 12 --> currentyear-currentmonth-12
16258 Fri --> nearest Friday after today
16259 -Tue --> last Tuesday
16260 etc.
16262 Furthermore you can specify a relative date by giving, as the *first* thing
16263 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16264 change in days weeks, months, years.
16265 With a single plus or minus, the date is relative to today. With a double
16266 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16267 +4d --> four days from today
16268 +4 --> same as above
16269 +2w --> two weeks from today
16270 ++5 --> five days from default date
16272 The function understands only English month and weekday abbreviations.
16274 While prompting, a calendar is popped up - you can also select the
16275 date with the mouse (button 1). The calendar shows a period of three
16276 months. To scroll it to other months, use the keys `>' and `<'.
16277 If you don't like the calendar, turn it off with
16278 \(setq org-read-date-popup-calendar nil)
16280 With optional argument TO-TIME, the date will immediately be converted
16281 to an internal time.
16282 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16283 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16284 still enter a time, and this function will inform the calling routine
16285 about this change. The calling routine may then choose to change the
16286 format used to insert the time stamp into the buffer to include the time.
16287 With optional argument FROM-STRING, read from this string instead from
16288 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16289 the time/date that is used for everything that is not specified by the
16290 user."
16291 (require 'parse-time)
16292 (let* ((org-time-stamp-rounding-minutes
16293 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16294 (org-dcst org-display-custom-times)
16295 (ct (org-current-time))
16296 (org-def (or org-overriding-default-time default-time ct))
16297 (org-defdecode (decode-time org-def))
16298 (dummy (progn
16299 (when (< (nth 2 org-defdecode) org-extend-today-until)
16300 (setcar (nthcdr 2 org-defdecode) -1)
16301 (setcar (nthcdr 1 org-defdecode) 59)
16302 (setq org-def (apply 'encode-time org-defdecode)
16303 org-defdecode (decode-time org-def)))))
16304 (mouse-autoselect-window nil) ; Don't let the mouse jump
16305 (calendar-frame-setup nil)
16306 (calendar-setup nil)
16307 (calendar-move-hook nil)
16308 (calendar-view-diary-initially-flag nil)
16309 (calendar-view-holidays-initially-flag nil)
16310 (timestr (format-time-string
16311 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16312 (prompt (concat (if prompt (concat prompt " ") "")
16313 (format "Date+time [%s]: " timestr)))
16314 ans (org-ans0 "") org-ans1 org-ans2 final)
16316 (cond
16317 (from-string (setq ans from-string))
16318 (org-read-date-popup-calendar
16319 (save-excursion
16320 (save-window-excursion
16321 (calendar)
16322 (org-eval-in-calendar '(setq cursor-type nil) t)
16323 (unwind-protect
16324 (progn
16325 (calendar-forward-day (- (time-to-days org-def)
16326 (calendar-absolute-from-gregorian
16327 (calendar-current-date))))
16328 (org-eval-in-calendar nil t)
16329 (let* ((old-map (current-local-map))
16330 (map (copy-keymap calendar-mode-map))
16331 (minibuffer-local-map
16332 (copy-keymap org-read-date-minibuffer-local-map)))
16333 (org-defkey map (kbd "RET") 'org-calendar-select)
16334 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16335 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16336 (unwind-protect
16337 (progn
16338 (use-local-map map)
16339 (setq org-read-date-inactive inactive)
16340 (add-hook 'post-command-hook 'org-read-date-display)
16341 (setq org-ans0 (read-string prompt default-input
16342 'org-read-date-history nil))
16343 ;; org-ans0: from prompt
16344 ;; org-ans1: from mouse click
16345 ;; org-ans2: from calendar motion
16346 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16347 (remove-hook 'post-command-hook 'org-read-date-display)
16348 (use-local-map old-map)
16349 (when org-read-date-overlay
16350 (delete-overlay org-read-date-overlay)
16351 (setq org-read-date-overlay nil)))))
16352 (bury-buffer "*Calendar*")))))
16354 (t ; Naked prompt only
16355 (unwind-protect
16356 (setq ans (read-string prompt default-input
16357 'org-read-date-history timestr))
16358 (when org-read-date-overlay
16359 (delete-overlay org-read-date-overlay)
16360 (setq org-read-date-overlay nil)))))
16362 (setq final (org-read-date-analyze ans org-def org-defdecode))
16364 (when org-read-date-analyze-forced-year
16365 (message "Year was forced into %s"
16366 (if org-read-date-force-compatible-dates
16367 "compatible range (1970-2037)"
16368 "range representable on this machine"))
16369 (ding))
16371 ;; One round trip to get rid of 34th of August and stuff like that....
16372 (setq final (decode-time (apply 'encode-time final)))
16374 (setq org-read-date-final-answer ans)
16376 (if to-time
16377 (apply 'encode-time final)
16378 (if (and (boundp 'org-time-was-given) org-time-was-given)
16379 (format "%04d-%02d-%02d %02d:%02d"
16380 (nth 5 final) (nth 4 final) (nth 3 final)
16381 (nth 2 final) (nth 1 final))
16382 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16384 (defun org-read-date-display ()
16385 "Display the current date prompt interpretation in the minibuffer."
16386 (when org-read-date-display-live
16387 (when org-read-date-overlay
16388 (delete-overlay org-read-date-overlay))
16389 (when (minibufferp (current-buffer))
16390 (save-excursion
16391 (end-of-line 1)
16392 (while (not (equal (buffer-substring
16393 (max (point-min) (- (point) 4)) (point))
16394 " "))
16395 (insert " ")))
16396 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16397 " " (or org-ans1 org-ans2)))
16398 (org-end-time-was-given nil)
16399 (f (org-read-date-analyze ans org-def org-defdecode))
16400 (fmts (if org-dcst
16401 org-time-stamp-custom-formats
16402 org-time-stamp-formats))
16403 (fmt (if (or org-with-time
16404 (and (boundp 'org-time-was-given) org-time-was-given))
16405 (cdr fmts)
16406 (car fmts)))
16407 (txt (format-time-string fmt (apply 'encode-time f)))
16408 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16409 (txt (concat "=> " txt)))
16410 (when (and org-end-time-was-given
16411 (string-match org-plain-time-of-day-regexp txt))
16412 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16413 org-end-time-was-given
16414 (substring txt (match-end 0)))))
16415 (when org-read-date-analyze-futurep
16416 (setq txt (concat txt " (=>F)")))
16417 (setq org-read-date-overlay
16418 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16419 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16421 (defun org-read-date-analyze (ans org-def org-defdecode)
16422 "Analyze the combined answer of the date prompt."
16423 ;; FIXME: cleanup and comment
16424 (let ((nowdecode (decode-time (current-time)))
16425 delta deltan deltaw deltadef year month day
16426 hour minute second wday pm h2 m2 tl wday1
16427 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16428 (setq org-read-date-analyze-futurep nil
16429 org-read-date-analyze-forced-year nil)
16430 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16431 (setq ans "+0"))
16433 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16434 (setq ans (replace-match "" t t ans)
16435 deltan (car delta)
16436 deltaw (nth 1 delta)
16437 deltadef (nth 2 delta)))
16439 ;; Check if there is an iso week date in there. If yes, store the
16440 ;; info and postpone interpreting it until the rest of the parsing
16441 ;; is done.
16442 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16443 (setq iso-year (if (match-end 1)
16444 (org-small-year-to-year
16445 (string-to-number (match-string 1 ans))))
16446 iso-weekday (if (match-end 3)
16447 (string-to-number (match-string 3 ans)))
16448 iso-week (string-to-number (match-string 2 ans)))
16449 (setq ans (replace-match "" t t ans)))
16451 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16452 (when (string-match
16453 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16454 (setq year (if (match-end 2)
16455 (string-to-number (match-string 2 ans))
16456 (progn (setq kill-year t)
16457 (string-to-number (format-time-string "%Y"))))
16458 month (string-to-number (match-string 3 ans))
16459 day (string-to-number (match-string 4 ans)))
16460 (if (< year 100) (setq year (+ 2000 year)))
16461 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16462 t nil ans)))
16464 ;; Help matching dotted european dates
16465 (when (string-match
16466 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16467 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16468 (setq kill-year t)
16469 (string-to-number (format-time-string "%Y")))
16470 day (string-to-number (match-string 1 ans))
16471 month (string-to-number (match-string 2 ans))
16472 ans (replace-match (format "%04d-%02d-%02d" year month day)
16473 t nil ans)))
16475 ;; Help matching american dates, like 5/30 or 5/30/7
16476 (when (string-match
16477 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16478 (setq year (if (match-end 4)
16479 (string-to-number (match-string 4 ans))
16480 (progn (setq kill-year t)
16481 (string-to-number (format-time-string "%Y"))))
16482 month (string-to-number (match-string 1 ans))
16483 day (string-to-number (match-string 2 ans)))
16484 (if (< year 100) (setq year (+ 2000 year)))
16485 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16486 t nil ans)))
16487 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16488 ;; If there is a time with am/pm, and *no* time without it, we convert
16489 ;; so that matching will be successful.
16490 (loop for i from 1 to 2 do ; twice, for end time as well
16491 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16492 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16493 (setq hour (string-to-number (match-string 1 ans))
16494 minute (if (match-end 3)
16495 (string-to-number (match-string 3 ans))
16497 pm (equal ?p
16498 (string-to-char (downcase (match-string 4 ans)))))
16499 (if (and (= hour 12) (not pm))
16500 (setq hour 0)
16501 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16502 (setq ans (replace-match (format "%02d:%02d" hour minute)
16503 t t ans))))
16505 ;; Check if a time range is given as a duration
16506 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16507 (setq hour (string-to-number (match-string 1 ans))
16508 h2 (+ hour (string-to-number (match-string 3 ans)))
16509 minute (string-to-number (match-string 2 ans))
16510 m2 (+ minute (if (match-end 5) (string-to-number
16511 (match-string 5 ans))0)))
16512 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16513 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16514 t t ans)))
16516 ;; Check if there is a time range
16517 (when (boundp 'org-end-time-was-given)
16518 (setq org-time-was-given nil)
16519 (when (and (string-match org-plain-time-of-day-regexp ans)
16520 (match-end 8))
16521 (setq org-end-time-was-given (match-string 8 ans))
16522 (setq ans (concat (substring ans 0 (match-beginning 7))
16523 (substring ans (match-end 7))))))
16525 (setq tl (parse-time-string ans)
16526 day (or (nth 3 tl) (nth 3 org-defdecode))
16527 month (or (nth 4 tl)
16528 (if (and org-read-date-prefer-future
16529 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16530 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16531 (nth 4 org-defdecode)))
16532 year (or (and (not kill-year) (nth 5 tl))
16533 (if (and org-read-date-prefer-future
16534 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16535 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16536 (nth 5 org-defdecode)))
16537 hour (or (nth 2 tl) (nth 2 org-defdecode))
16538 minute (or (nth 1 tl) (nth 1 org-defdecode))
16539 second (or (nth 0 tl) 0)
16540 wday (nth 6 tl))
16542 (when (and (eq org-read-date-prefer-future 'time)
16543 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16544 (equal day (nth 3 nowdecode))
16545 (equal month (nth 4 nowdecode))
16546 (equal year (nth 5 nowdecode))
16547 (nth 2 tl)
16548 (or (< (nth 2 tl) (nth 2 nowdecode))
16549 (and (= (nth 2 tl) (nth 2 nowdecode))
16550 (nth 1 tl)
16551 (< (nth 1 tl) (nth 1 nowdecode)))))
16552 (setq day (1+ day)
16553 futurep t))
16555 ;; Special date definitions below
16556 (cond
16557 (iso-week
16558 ;; There was an iso week
16559 (require 'cal-iso)
16560 (setq futurep nil)
16561 (setq year (or iso-year year)
16562 day (or iso-weekday wday 1)
16563 wday nil ; to make sure that the trigger below does not match
16564 iso-date (calendar-gregorian-from-absolute
16565 (calendar-absolute-from-iso
16566 (list iso-week day year))))
16567 ; FIXME: Should we also push ISO weeks into the future?
16568 ; (when (and org-read-date-prefer-future
16569 ; (not iso-year)
16570 ; (< (calendar-absolute-from-gregorian iso-date)
16571 ; (time-to-days (current-time))))
16572 ; (setq year (1+ year)
16573 ; iso-date (calendar-gregorian-from-absolute
16574 ; (calendar-absolute-from-iso
16575 ; (list iso-week day year)))))
16576 (setq month (car iso-date)
16577 year (nth 2 iso-date)
16578 day (nth 1 iso-date)))
16579 (deltan
16580 (setq futurep nil)
16581 (unless deltadef
16582 (let ((now (decode-time (current-time))))
16583 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16584 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16585 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16586 ((equal deltaw "m") (setq month (+ month deltan)))
16587 ((equal deltaw "y") (setq year (+ year deltan)))))
16588 ((and wday (not (nth 3 tl)))
16589 ;; Weekday was given, but no day, so pick that day in the week
16590 ;; on or after the derived date.
16591 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16592 (unless (equal wday wday1)
16593 (setq day (+ day (% (- wday wday1 -7) 7))))))
16594 (if (and (boundp 'org-time-was-given)
16595 (nth 2 tl))
16596 (setq org-time-was-given t))
16597 (if (< year 100) (setq year (+ 2000 year)))
16598 ;; Check of the date is representable
16599 (if org-read-date-force-compatible-dates
16600 (progn
16601 (if (< year 1970)
16602 (setq year 1970 org-read-date-analyze-forced-year t))
16603 (if (> year 2037)
16604 (setq year 2037 org-read-date-analyze-forced-year t)))
16605 (condition-case nil
16606 (ignore (encode-time second minute hour day month year))
16607 (error
16608 (setq year (nth 5 org-defdecode))
16609 (setq org-read-date-analyze-forced-year t))))
16610 (setq org-read-date-analyze-futurep futurep)
16611 (list second minute hour day month year)))
16613 (defvar parse-time-weekdays)
16614 (defun org-read-date-get-relative (s today default)
16615 "Check string S for special relative date string.
16616 TODAY and DEFAULT are internal times, for today and for a default.
16617 Return shift list (N what def-flag)
16618 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16619 N is the number of WHATs to shift.
16620 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16621 the DEFAULT date rather than TODAY."
16622 (require 'parse-time)
16623 (when (and
16624 (string-match
16625 (concat
16626 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16627 "\\([0-9]+\\)?"
16628 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16629 "\\([ \t]\\|$\\)") s)
16630 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16631 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16632 (string-to-char (substring (match-string 1 s) -1))
16633 ?+))
16634 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16635 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16636 (what (if (match-end 3) (match-string 3 s) "d"))
16637 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16638 (date (if rel default today))
16639 (wday (nth 6 (decode-time date)))
16640 delta)
16641 (if wday1
16642 (progn
16643 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16644 (if (= delta 0) (setq delta 7))
16645 (if (= dir ?-)
16646 (progn
16647 (setq delta (- delta 7))
16648 (if (= delta 0) (setq delta -7))))
16649 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16650 (list delta "d" rel))
16651 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16653 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16654 "Turn a user-specified date into the internal representation.
16655 The internal representation needed by the calendar is (month day year).
16656 This is a wrapper to handle the brain-dead convention in calendar that
16657 user function argument order change dependent on argument order."
16658 (if (boundp 'calendar-date-style)
16659 (cond
16660 ((eq calendar-date-style 'american)
16661 (list arg1 arg2 arg3))
16662 ((eq calendar-date-style 'european)
16663 (list arg2 arg1 arg3))
16664 ((eq calendar-date-style 'iso)
16665 (list arg2 arg3 arg1)))
16666 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16667 (if (org-bound-and-true-p european-calendar-style)
16668 (list arg2 arg1 arg3)
16669 (list arg1 arg2 arg3)))))
16671 (defun org-eval-in-calendar (form &optional keepdate)
16672 "Eval FORM in the calendar window and return to current window.
16673 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16674 otherwise stick to the current value of `org-ans2'."
16675 (let ((sf (selected-frame))
16676 (sw (selected-window)))
16677 (select-window (get-buffer-window "*Calendar*" t))
16678 (eval form)
16679 (when (and (not keepdate) (calendar-cursor-to-date))
16680 (let* ((date (calendar-cursor-to-date))
16681 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16682 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16683 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16684 (select-window sw)
16685 (org-select-frame-set-input-focus sf)))
16687 (defun org-calendar-select ()
16688 "Return to `org-read-date' with the date currently selected.
16689 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16690 (interactive)
16691 (when (calendar-cursor-to-date)
16692 (let* ((date (calendar-cursor-to-date))
16693 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16694 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16695 (if (active-minibuffer-window) (exit-minibuffer))))
16697 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16698 "Insert a date stamp for the date given by the internal TIME.
16699 WITH-HM means use the stamp format that includes the time of the day.
16700 INACTIVE means use square brackets instead of angular ones, so that the
16701 stamp will not contribute to the agenda.
16702 PRE and POST are optional strings to be inserted before and after the
16703 stamp.
16704 The command returns the inserted time stamp."
16705 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16706 stamp)
16707 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16708 (insert-before-markers (or pre ""))
16709 (when (listp extra)
16710 (setq extra (car extra))
16711 (if (and (stringp extra)
16712 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16713 (setq extra (format "-%02d:%02d"
16714 (string-to-number (match-string 1 extra))
16715 (string-to-number (match-string 2 extra))))
16716 (setq extra nil)))
16717 (when extra
16718 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16719 (insert-before-markers (setq stamp (format-time-string fmt time)))
16720 (insert-before-markers (or post ""))
16721 (setq org-last-inserted-timestamp stamp)))
16723 (defun org-toggle-time-stamp-overlays ()
16724 "Toggle the use of custom time stamp formats."
16725 (interactive)
16726 (setq org-display-custom-times (not org-display-custom-times))
16727 (unless org-display-custom-times
16728 (let ((p (point-min)) (bmp (buffer-modified-p)))
16729 (while (setq p (next-single-property-change p 'display))
16730 (if (and (get-text-property p 'display)
16731 (eq (get-text-property p 'face) 'org-date))
16732 (remove-text-properties
16733 p (setq p (next-single-property-change p 'display))
16734 '(display t))))
16735 (set-buffer-modified-p bmp)))
16736 (if (featurep 'xemacs)
16737 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16738 (org-restart-font-lock)
16739 (setq org-table-may-need-update t)
16740 (if org-display-custom-times
16741 (message "Time stamps are overlaid with custom format")
16742 (message "Time stamp overlays removed")))
16744 (defun org-display-custom-time (beg end)
16745 "Overlay modified time stamp format over timestamp between BEG and END."
16746 (let* ((ts (buffer-substring beg end))
16747 t1 w1 with-hm tf time str w2 (off 0))
16748 (save-match-data
16749 (setq t1 (org-parse-time-string ts t))
16750 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16751 (setq off (- (match-end 0) (match-beginning 0)))))
16752 (setq end (- end off))
16753 (setq w1 (- end beg)
16754 with-hm (and (nth 1 t1) (nth 2 t1))
16755 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16756 time (org-fix-decoded-time t1)
16757 str (org-add-props
16758 (format-time-string
16759 (substring tf 1 -1) (apply 'encode-time time))
16760 nil 'mouse-face 'highlight)
16761 w2 (length str))
16762 (if (not (= w2 w1))
16763 (add-text-properties (1+ beg) (+ 2 beg)
16764 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16765 (if (featurep 'xemacs)
16766 (progn
16767 (put-text-property beg end 'invisible t)
16768 (put-text-property beg end 'end-glyph (make-glyph str)))
16769 (put-text-property beg end 'display str))))
16771 (defun org-translate-time (string)
16772 "Translate all timestamps in STRING to custom format.
16773 But do this only if the variable `org-display-custom-times' is set."
16774 (when org-display-custom-times
16775 (save-match-data
16776 (let* ((start 0)
16777 (re org-ts-regexp-both)
16778 t1 with-hm inactive tf time str beg end)
16779 (while (setq start (string-match re string start))
16780 (setq beg (match-beginning 0)
16781 end (match-end 0)
16782 t1 (save-match-data
16783 (org-parse-time-string (substring string beg end) t))
16784 with-hm (and (nth 1 t1) (nth 2 t1))
16785 inactive (equal (substring string beg (1+ beg)) "[")
16786 tf (funcall (if with-hm 'cdr 'car)
16787 org-time-stamp-custom-formats)
16788 time (org-fix-decoded-time t1)
16789 str (format-time-string
16790 (concat
16791 (if inactive "[" "<") (substring tf 1 -1)
16792 (if inactive "]" ">"))
16793 (apply 'encode-time time))
16794 string (replace-match str t t string)
16795 start (+ start (length str)))))))
16796 string)
16798 (defun org-fix-decoded-time (time)
16799 "Set 0 instead of nil for the first 6 elements of time.
16800 Don't touch the rest."
16801 (let ((n 0))
16802 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16804 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16806 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16807 "Difference between TIMESTAMP-STRING and now in days.
16808 If SECONDS is non-nil, return the difference in seconds."
16809 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16810 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16811 (funcall fdiff (current-time)))))
16813 (defun org-deadline-close (timestamp-string &optional ndays)
16814 "Is the time in TIMESTAMP-STRING close to the current date?"
16815 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16816 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16817 (not (org-entry-is-done-p))))
16819 (defun org-get-wdays (ts &optional delay zero-delay)
16820 "Get the deadline lead time appropriate for timestring TS.
16821 When DELAY is non-nil, get the delay time for scheduled items
16822 instead of the deadline lead time. When ZERO-DELAY is non-nil
16823 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16824 don't try to find the delay cookie in the scheduled timestamp."
16825 (let ((tv (if delay org-scheduled-delay-days
16826 org-deadline-warning-days)))
16827 (cond
16828 ((or (and delay (< tv 0))
16829 (and delay zero-delay (<= tv 0))
16830 (and (not delay) (<= tv 0)))
16831 ;; Enforce this value no matter what
16832 (- tv))
16833 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16834 ;; lead time is specified.
16835 (floor (* (string-to-number (match-string 1 ts))
16836 (cdr (assoc (match-string 2 ts)
16837 '(("d" . 1) ("w" . 7)
16838 ("m" . 30.4) ("y" . 365.25)
16839 ("h" . 0.041667)))))))
16840 ;; go for the default.
16841 (t tv))))
16843 (defun org-calendar-select-mouse (ev)
16844 "Return to `org-read-date' with the date currently selected.
16845 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16846 (interactive "e")
16847 (mouse-set-point ev)
16848 (when (calendar-cursor-to-date)
16849 (let* ((date (calendar-cursor-to-date))
16850 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16851 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16852 (if (active-minibuffer-window) (exit-minibuffer))))
16854 (defun org-check-deadlines (ndays)
16855 "Check if there are any deadlines due or past due.
16856 A deadline is considered due if it happens within `org-deadline-warning-days'
16857 days from today's date. If the deadline appears in an entry marked DONE,
16858 it is not shown. The prefix arg NDAYS can be used to test that many
16859 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16860 (interactive "P")
16861 (let* ((org-warn-days
16862 (cond
16863 ((equal ndays '(4)) 100000)
16864 (ndays (prefix-numeric-value ndays))
16865 (t (abs org-deadline-warning-days))))
16866 (case-fold-search nil)
16867 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16868 (callback
16869 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16871 (message "%d deadlines past-due or due within %d days"
16872 (org-occur regexp nil callback)
16873 org-warn-days)))
16875 (defsubst org-re-timestamp (type)
16876 "Return a regexp for timestamp TYPE.
16877 Allowed values for TYPE are:
16879 all: all timestamps
16880 active: only active timestamps (<...>)
16881 inactive: only inactive timestamps ([...])
16882 scheduled: only scheduled timestamps
16883 deadline: only deadline timestamps
16884 closed: only closed time-stamps
16886 When TYPE is nil, fall back on returning a regexp that matches
16887 both scheduled and deadline timestamps."
16888 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16889 ((eq type 'active) org-ts-regexp)
16890 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16891 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16892 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16893 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16894 ((eq type 'scheduled-or-deadline)
16895 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16897 (defun org-check-before-date (date)
16898 "Check if there are deadlines or scheduled entries before DATE."
16899 (interactive (list (org-read-date)))
16900 (let ((case-fold-search nil)
16901 (regexp (org-re-timestamp org-ts-type))
16902 (callback
16903 (lambda () (time-less-p
16904 (org-time-string-to-time (match-string 1))
16905 (org-time-string-to-time date)))))
16906 (message "%d entries before %s"
16907 (org-occur regexp nil callback) date)))
16909 (defun org-check-after-date (date)
16910 "Check if there are deadlines or scheduled entries after DATE."
16911 (interactive (list (org-read-date)))
16912 (let ((case-fold-search nil)
16913 (regexp (org-re-timestamp org-ts-type))
16914 (callback
16915 (lambda () (not
16916 (time-less-p
16917 (org-time-string-to-time (match-string 1))
16918 (org-time-string-to-time date))))))
16919 (message "%d entries after %s"
16920 (org-occur regexp nil callback) date)))
16922 (defun org-check-dates-range (start-date end-date)
16923 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16924 (interactive (list (org-read-date nil nil nil "Range starts")
16925 (org-read-date nil nil nil "Range end")))
16926 (let ((case-fold-search nil)
16927 (regexp (org-re-timestamp org-ts-type))
16928 (callback
16929 (lambda ()
16930 (let ((match (match-string 1)))
16931 (and
16932 (not (time-less-p
16933 (org-time-string-to-time match)
16934 (org-time-string-to-time start-date)))
16935 (time-less-p
16936 (org-time-string-to-time match)
16937 (org-time-string-to-time end-date)))))))
16938 (message "%d entries between %s and %s"
16939 (org-occur regexp nil callback) start-date end-date)))
16941 (defun org-evaluate-time-range (&optional to-buffer)
16942 "Evaluate a time range by computing the difference between start and end.
16943 Normally the result is just printed in the echo area, but with prefix arg
16944 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16945 If the time range is actually in a table, the result is inserted into the
16946 next column.
16947 For time difference computation, a year is assumed to be exactly 365
16948 days in order to avoid rounding problems."
16949 (interactive "P")
16951 (org-clock-update-time-maybe)
16952 (save-excursion
16953 (unless (org-at-date-range-p t)
16954 (goto-char (point-at-bol))
16955 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16956 (if (not (org-at-date-range-p t))
16957 (user-error "Not at a time-stamp range, and none found in current line")))
16958 (let* ((ts1 (match-string 1))
16959 (ts2 (match-string 2))
16960 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16961 (match-end (match-end 0))
16962 (time1 (org-time-string-to-time ts1))
16963 (time2 (org-time-string-to-time ts2))
16964 (t1 (org-float-time time1))
16965 (t2 (org-float-time time2))
16966 (diff (abs (- t2 t1)))
16967 (negative (< (- t2 t1) 0))
16968 ;; (ys (floor (* 365 24 60 60)))
16969 (ds (* 24 60 60))
16970 (hs (* 60 60))
16971 (fy "%dy %dd %02d:%02d")
16972 (fy1 "%dy %dd")
16973 (fd "%dd %02d:%02d")
16974 (fd1 "%dd")
16975 (fh "%02d:%02d")
16976 y d h m align)
16977 (if havetime
16978 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16980 d (floor (/ diff ds)) diff (mod diff ds)
16981 h (floor (/ diff hs)) diff (mod diff hs)
16982 m (floor (/ diff 60)))
16983 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16985 d (floor (+ (/ diff ds) 0.5))
16986 h 0 m 0))
16987 (if (not to-buffer)
16988 (message "%s" (org-make-tdiff-string y d h m))
16989 (if (org-at-table-p)
16990 (progn
16991 (goto-char match-end)
16992 (setq align t)
16993 (and (looking-at " *|") (goto-char (match-end 0))))
16994 (goto-char match-end))
16995 (if (looking-at
16996 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16997 (replace-match ""))
16998 (if negative (insert " -"))
16999 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17000 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17001 (insert " " (format fh h m))))
17002 (if align (org-table-align))
17003 (message "Time difference inserted")))))
17005 (defun org-make-tdiff-string (y d h m)
17006 (let ((fmt "")
17007 (l nil))
17008 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17009 l (push y l)))
17010 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17011 l (push d l)))
17012 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17013 l (push h l)))
17014 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17015 l (push m l)))
17016 (apply 'format fmt (nreverse l))))
17018 (defun org-time-string-to-time (s &optional buffer pos)
17019 "Convert a timestamp string into internal time."
17020 (condition-case errdata
17021 (apply 'encode-time (org-parse-time-string s))
17022 (error (error "Bad timestamp `%s'%s\nError was: %s"
17023 s (if (not (and buffer pos))
17025 (format " at %d in buffer `%s'" pos buffer))
17026 (cdr errdata)))))
17028 (defun org-time-string-to-seconds (s)
17029 "Convert a timestamp string to a number of seconds."
17030 (org-float-time (org-time-string-to-time s)))
17032 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17033 "Convert a time stamp to an absolute day number.
17034 If there is a specifier for a cyclic time stamp, get the closest
17035 date to DAYNR.
17036 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17037 The variable `date' is bound by the calendar when this is called."
17038 (cond
17039 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17040 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17041 daynr
17042 (+ daynr 1000)))
17043 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17044 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17045 (time-to-days (current-time))) (match-string 0 s)
17046 prefer show-all))
17047 (t (time-to-days
17048 (condition-case errdata
17049 (apply 'encode-time (org-parse-time-string s))
17050 (error (error "Bad timestamp `%s'%s\nError was: %s"
17051 s (if (not (and buffer pos))
17053 (format " at %d in buffer `%s'" pos buffer))
17054 (cdr errdata))))))))
17056 (defun org-days-to-iso-week (days)
17057 "Return the iso week number."
17058 (require 'cal-iso)
17059 (car (calendar-iso-from-absolute days)))
17061 (defun org-small-year-to-year (year)
17062 "Convert 2-digit years into 4-digit years.
17063 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17064 The year 2000 cannot be abbreviated. Any year larger than 99
17065 is returned unchanged."
17066 (if (< year 38)
17067 (setq year (+ 2000 year))
17068 (if (< year 100)
17069 (setq year (+ 1900 year))))
17070 year)
17072 (defun org-time-from-absolute (d)
17073 "Return the time corresponding to date D.
17074 D may be an absolute day number, or a calendar-type list (month day year)."
17075 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17076 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17078 (defun org-calendar-holiday ()
17079 "List of holidays, for Diary display in Org-mode."
17080 (require 'holidays)
17081 (let ((hl (funcall
17082 (if (fboundp 'calendar-check-holidays)
17083 'calendar-check-holidays 'check-calendar-holidays) date)))
17084 (if hl (mapconcat 'identity hl "; "))))
17086 (defun org-diary-sexp-entry (sexp entry date)
17087 "Process a SEXP diary ENTRY for DATE."
17088 (require 'diary-lib)
17089 (let ((result (if calendar-debug-sexp
17090 (let ((stack-trace-on-error t))
17091 (eval (car (read-from-string sexp))))
17092 (condition-case nil
17093 (eval (car (read-from-string sexp)))
17094 (error
17095 (beep)
17096 (message "Bad sexp at line %d in %s: %s"
17097 (org-current-line)
17098 (buffer-file-name) sexp)
17099 (sleep-for 2))))))
17100 (cond ((stringp result) (split-string result "; "))
17101 ((and (consp result)
17102 (not (consp (cdr result)))
17103 (stringp (cdr result))) (cdr result))
17104 ((and (consp result)
17105 (stringp (car result))) result)
17106 (result entry))))
17108 (defun org-diary-to-ical-string (frombuf)
17109 "Get iCalendar entries from diary entries in buffer FROMBUF.
17110 This uses the icalendar.el library."
17111 (let* ((tmpdir (if (featurep 'xemacs)
17112 (temp-directory)
17113 temporary-file-directory))
17114 (tmpfile (make-temp-name
17115 (expand-file-name "orgics" tmpdir)))
17116 buf rtn b e)
17117 (with-current-buffer frombuf
17118 (icalendar-export-region (point-min) (point-max) tmpfile)
17119 (setq buf (find-buffer-visiting tmpfile))
17120 (set-buffer buf)
17121 (goto-char (point-min))
17122 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17123 (setq b (match-beginning 0)))
17124 (goto-char (point-max))
17125 (if (re-search-backward "^END:VEVENT" nil t)
17126 (setq e (match-end 0)))
17127 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17128 (kill-buffer buf)
17129 (delete-file tmpfile)
17130 rtn))
17132 (defun org-closest-date (start current change prefer show-all)
17133 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17134 When PREFER is `past', return a date that is either CURRENT or past.
17135 When PREFER is `future', return a date that is either CURRENT or future.
17136 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17137 ;; Make the proper lists from the dates
17138 (catch 'exit
17139 (let ((a1 '(("h" . hour)
17140 ("d" . day)
17141 ("w" . week)
17142 ("m" . month)
17143 ("y" . year)))
17144 (shour (nth 2 (org-parse-time-string start)))
17145 dn dw sday cday n1 n2 n0
17146 d m y y1 y2 date1 date2 nmonths nm ny m2)
17148 (setq start (org-date-to-gregorian start)
17149 current (org-date-to-gregorian
17150 (if show-all
17151 current
17152 (time-to-days (current-time))))
17153 sday (calendar-absolute-from-gregorian start)
17154 cday (calendar-absolute-from-gregorian current))
17156 (if (<= cday sday) (throw 'exit sday))
17158 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17159 (setq dn (string-to-number (match-string 1 change))
17160 dw (cdr (assoc (match-string 2 change) a1)))
17161 (user-error "Invalid change specifier: %s" change))
17162 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17163 (cond
17164 ((eq dw 'hour)
17165 (let ((missing-hours
17166 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17167 dn)))
17168 (setq n1 (if (zerop missing-hours) cday
17169 (- cday (1+ (floor (/ missing-hours 24)))))
17170 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17171 ((eq dw 'day)
17172 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17173 n2 (+ n1 dn)))
17174 ((eq dw 'year)
17175 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17176 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17177 (setq date1 (list m d y1)
17178 n1 (calendar-absolute-from-gregorian date1)
17179 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17180 n2 (calendar-absolute-from-gregorian date2)))
17181 ((eq dw 'month)
17182 ;; approx number of month between the two dates
17183 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17184 ;; How often does dn fit in there?
17185 (setq d (nth 1 start) m (car start) y (nth 2 start)
17186 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17187 m (+ m nm)
17188 ny (floor (/ m 12))
17189 y (+ y ny)
17190 m (- m (* ny 12)))
17191 (while (> m 12) (setq m (- m 12) y (1+ y)))
17192 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17193 (setq m2 (+ m dn) y2 y)
17194 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17195 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17196 (while (<= n2 cday)
17197 (setq n1 n2 m m2 y y2)
17198 (setq m2 (+ m dn) y2 y)
17199 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17200 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17201 ;; Make sure n1 is the earlier date
17202 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17203 (if show-all
17204 (cond
17205 ((eq prefer 'past) (if (= cday n2) n2 n1))
17206 ((eq prefer 'future) (if (= cday n1) n1 n2))
17207 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17208 (cond
17209 ((eq prefer 'past) (if (= cday n2) n2 n1))
17210 ((eq prefer 'future) (if (= cday n1) n1 n2))
17211 (t (if (= cday n1) n1 n2)))))))
17213 (defun org-date-to-gregorian (date)
17214 "Turn any specification of DATE into a Gregorian date for the calendar."
17215 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17216 ((and (listp date) (= (length date) 3)) date)
17217 ((stringp date)
17218 (setq date (org-parse-time-string date))
17219 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17220 ((listp date)
17221 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17223 (defun org-parse-time-string (s &optional nodefault)
17224 "Parse the standard Org-mode time string.
17225 This should be a lot faster than the normal `parse-time-string'.
17226 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17227 hour and minute fields will be nil if not given."
17228 (cond ((string-match org-ts-regexp0 s)
17229 (list 0
17230 (if (or (match-beginning 8) (not nodefault))
17231 (string-to-number (or (match-string 8 s) "0")))
17232 (if (or (match-beginning 7) (not nodefault))
17233 (string-to-number (or (match-string 7 s) "0")))
17234 (string-to-number (match-string 4 s))
17235 (string-to-number (match-string 3 s))
17236 (string-to-number (match-string 2 s))
17237 nil nil nil))
17238 ((string-match "^<[^>]+>$" s)
17239 (decode-time (seconds-to-time (org-matcher-time s))))
17240 (t (error "Not a standard Org-mode time string: %s" s))))
17242 (defun org-timestamp-up (&optional arg)
17243 "Increase the date item at the cursor by one.
17244 If the cursor is on the year, change the year. If it is on the month,
17245 the day or the time, change that.
17246 With prefix ARG, change by that many units."
17247 (interactive "p")
17248 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17250 (defun org-timestamp-down (&optional arg)
17251 "Decrease the date item at the cursor by one.
17252 If the cursor is on the year, change the year. If it is on the month,
17253 the day or the time, change that.
17254 With prefix ARG, change by that many units."
17255 (interactive "p")
17256 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17258 (defun org-timestamp-up-day (&optional arg)
17259 "Increase the date in the time stamp by one day.
17260 With prefix ARG, change that many days."
17261 (interactive "p")
17262 (if (and (not (org-at-timestamp-p t))
17263 (org-at-heading-p))
17264 (org-todo 'up)
17265 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17267 (defun org-timestamp-down-day (&optional arg)
17268 "Decrease the date in the time stamp by one day.
17269 With prefix ARG, change that many days."
17270 (interactive "p")
17271 (if (and (not (org-at-timestamp-p t))
17272 (org-at-heading-p))
17273 (org-todo 'down)
17274 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17276 (defun org-at-timestamp-p (&optional inactive-ok)
17277 "Determine if the cursor is in or at a timestamp."
17278 (interactive)
17279 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17280 (pos (point))
17281 (ans (or (looking-at tsr)
17282 (save-excursion
17283 (skip-chars-backward "^[<\n\r\t")
17284 (if (> (point) (point-min)) (backward-char 1))
17285 (and (looking-at tsr)
17286 (> (- (match-end 0) pos) -1))))))
17287 (and ans
17288 (boundp 'org-ts-what)
17289 (setq org-ts-what
17290 (cond
17291 ((= pos (match-beginning 0)) 'bracket)
17292 ;; Point is considered to be "on the bracket" whether
17293 ;; it's really on it or right after it.
17294 ((= pos (1- (match-end 0))) 'bracket)
17295 ((= pos (match-end 0)) 'after)
17296 ((org-pos-in-match-range pos 2) 'year)
17297 ((org-pos-in-match-range pos 3) 'month)
17298 ((org-pos-in-match-range pos 7) 'hour)
17299 ((org-pos-in-match-range pos 8) 'minute)
17300 ((or (org-pos-in-match-range pos 4)
17301 (org-pos-in-match-range pos 5)) 'day)
17302 ((and (> pos (or (match-end 8) (match-end 5)))
17303 (< pos (match-end 0)))
17304 (- pos (or (match-end 8) (match-end 5))))
17305 (t 'day))))
17306 ans))
17308 (defun org-toggle-timestamp-type ()
17309 "Toggle the type (<active> or [inactive]) of a time stamp."
17310 (interactive)
17311 (when (org-at-timestamp-p t)
17312 (let ((beg (match-beginning 0)) (end (match-end 0))
17313 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17314 (save-excursion
17315 (goto-char beg)
17316 (while (re-search-forward "[][<>]" end t)
17317 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17318 t t)))
17319 (message "Timestamp is now %sactive"
17320 (if (equal (char-after beg) ?<) "" "in")))))
17322 (defun org-at-clock-log-p nil
17323 "Is the cursor on the clock log line?"
17324 (save-excursion
17325 (move-beginning-of-line 1)
17326 (looking-at "^[ \t]*CLOCK:")))
17328 (defvar org-clock-history) ; defined in org-clock.el
17329 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17330 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17331 "Change the date in the time stamp at point.
17332 The date will be changed by N times WHAT. WHAT can be `day', `month',
17333 `year', `minute', `second'. If WHAT is not given, the cursor position
17334 in the timestamp determines what will be changed.
17335 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17336 (let ((origin (point)) origin-cat
17337 with-hm inactive
17338 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17339 org-ts-what
17340 extra rem
17341 ts time time0 fixnext clrgx)
17342 (if (not (org-at-timestamp-p t))
17343 (user-error "Not at a timestamp"))
17344 (if (and (not what) (eq org-ts-what 'bracket))
17345 (org-toggle-timestamp-type)
17346 ;; Point isn't on brackets. Remember the part of the time-stamp
17347 ;; the point was in. Indeed, size of time-stamps may change,
17348 ;; but point must be kept in the same category nonetheless.
17349 (setq origin-cat org-ts-what)
17350 (if (and (not what) (not (eq org-ts-what 'day))
17351 org-display-custom-times
17352 (get-text-property (point) 'display)
17353 (not (get-text-property (1- (point)) 'display)))
17354 (setq org-ts-what 'day))
17355 (setq org-ts-what (or what org-ts-what)
17356 inactive (= (char-after (match-beginning 0)) ?\[)
17357 ts (match-string 0))
17358 (replace-match "")
17359 (when (string-match
17360 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17362 (setq extra (match-string 1 ts))
17363 (if suppress-tmp-delay
17364 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17365 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17366 (setq with-hm t))
17367 (setq time0 (org-parse-time-string ts))
17368 (when (and updown
17369 (eq org-ts-what 'minute)
17370 (not current-prefix-arg))
17371 ;; This looks like s-up and s-down. Change by one rounding step.
17372 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17373 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17374 (setcar (cdr time0) (+ (nth 1 time0)
17375 (if (> n 0) (- rem) (- dm rem))))))
17376 (setq time
17377 (encode-time (or (car time0) 0)
17378 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17379 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17380 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17381 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17382 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17383 (nthcdr 6 time0)))
17384 (when (and (member org-ts-what '(hour minute))
17385 extra
17386 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17387 (setq extra (org-modify-ts-extra
17388 extra
17389 (if (eq org-ts-what 'hour) 2 5)
17390 n dm)))
17391 (when (integerp org-ts-what)
17392 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17393 (if (eq what 'calendar)
17394 (let ((cal-date (org-get-date-from-calendar)))
17395 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17396 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17397 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17398 (setcar time0 (or (car time0) 0))
17399 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17400 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17401 (setq time (apply 'encode-time time0))))
17402 ;; Insert the new time-stamp, and ensure point stays in the same
17403 ;; category as before (i.e. not after the last position in that
17404 ;; category).
17405 (let ((pos (point)))
17406 ;; Stay before inserted string. `save-excursion' is of no use.
17407 (setq org-last-changed-timestamp
17408 (org-insert-time-stamp time with-hm inactive nil nil extra))
17409 (goto-char pos))
17410 (save-match-data
17411 (looking-at org-ts-regexp3)
17412 (goto-char (cond
17413 ;; `day' category ends before `hour' if any, or at
17414 ;; the end of the day name.
17415 ((eq origin-cat 'day)
17416 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17417 ((eq origin-cat 'hour) (min (match-end 7) origin))
17418 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17419 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17420 ;; `year' and `month' have both fixed size: point
17421 ;; couldn't have moved into another part.
17422 (t origin))))
17423 ;; Update clock if on a CLOCK line.
17424 (org-clock-update-time-maybe)
17425 ;; Maybe adjust the closest clock in `org-clock-history'
17426 (when org-clock-adjust-closest
17427 (if (not (and (org-at-clock-log-p)
17428 (< 1 (length (delq nil (mapcar 'marker-position
17429 org-clock-history))))))
17430 (message "No clock to adjust")
17431 (cond ((save-excursion ; fix previous clock?
17432 (re-search-backward org-ts-regexp0 nil t)
17433 (org-looking-back (concat org-clock-string " \\[")))
17434 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17435 ((save-excursion ; fix next clock?
17436 (re-search-backward org-ts-regexp0 nil t)
17437 (looking-at (concat org-ts-regexp0 "\\] =>")))
17438 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17439 (save-window-excursion
17440 ;; Find closest clock to point, adjust the previous/next one in history
17441 (let* ((p (save-excursion (org-back-to-heading t)))
17442 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17443 (clfixnth
17444 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17445 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17446 (if (not clfixpos)
17447 (message "No clock to adjust")
17448 (save-excursion
17449 (org-goto-marker-or-bmk clfixpos)
17450 (org-show-subtree)
17451 (when (re-search-forward clrgx nil t)
17452 (goto-char (match-beginning 1))
17453 (let (org-clock-adjust-closest)
17454 (org-timestamp-change n org-ts-what updown))
17455 (message "Clock adjusted in %s for heading: %s"
17456 (file-name-nondirectory (buffer-file-name))
17457 (org-get-heading t t)))))))))
17458 ;; Try to recenter the calendar window, if any.
17459 (if (and org-calendar-follow-timestamp-change
17460 (get-buffer-window "*Calendar*" t)
17461 (memq org-ts-what '(day month year)))
17462 (org-recenter-calendar (time-to-days time))))))
17464 (defun org-modify-ts-extra (s pos n dm)
17465 "Change the different parts of the lead-time and repeat fields in timestamp."
17466 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17467 ng h m new rem)
17468 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17469 (cond
17470 ((or (org-pos-in-match-range pos 2)
17471 (org-pos-in-match-range pos 3))
17472 (setq m (string-to-number (match-string 3 s))
17473 h (string-to-number (match-string 2 s)))
17474 (if (org-pos-in-match-range pos 2)
17475 (setq h (+ h n))
17476 (setq n (* dm (org-no-warnings (signum n))))
17477 (when (not (= 0 (setq rem (% m dm))))
17478 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17479 (setq m (+ m n)))
17480 (if (< m 0) (setq m (+ m 60) h (1- h)))
17481 (if (> m 59) (setq m (- m 60) h (1+ h)))
17482 (setq h (min 24 (max 0 h)))
17483 (setq ng 1 new (format "-%02d:%02d" h m)))
17484 ((org-pos-in-match-range pos 6)
17485 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17486 ((org-pos-in-match-range pos 5)
17487 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17489 ((org-pos-in-match-range pos 9)
17490 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17491 ((org-pos-in-match-range pos 8)
17492 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17494 (when ng
17495 (setq s (concat
17496 (substring s 0 (match-beginning ng))
17498 (substring s (match-end ng))))))
17501 (defun org-recenter-calendar (date)
17502 "If the calendar is visible, recenter it to DATE."
17503 (let ((cwin (get-buffer-window "*Calendar*" t)))
17504 (when cwin
17505 (let ((calendar-move-hook nil))
17506 (with-selected-window cwin
17507 (calendar-goto-date (if (listp date) date
17508 (calendar-gregorian-from-absolute date))))))))
17510 (defun org-goto-calendar (&optional arg)
17511 "Go to the Emacs calendar at the current date.
17512 If there is a time stamp in the current line, go to that date.
17513 A prefix ARG can be used to force the current date."
17514 (interactive "P")
17515 (let ((tsr org-ts-regexp) diff
17516 (calendar-move-hook nil)
17517 (calendar-view-holidays-initially-flag nil)
17518 (calendar-view-diary-initially-flag nil))
17519 (if (or (org-at-timestamp-p)
17520 (save-excursion
17521 (beginning-of-line 1)
17522 (looking-at (concat ".*" tsr))))
17523 (let ((d1 (time-to-days (current-time)))
17524 (d2 (time-to-days
17525 (org-time-string-to-time (match-string 1)))))
17526 (setq diff (- d2 d1))))
17527 (calendar)
17528 (calendar-goto-today)
17529 (if (and diff (not arg)) (calendar-forward-day diff))))
17531 (defun org-get-date-from-calendar ()
17532 "Return a list (month day year) of date at point in calendar."
17533 (with-current-buffer "*Calendar*"
17534 (save-match-data
17535 (calendar-cursor-to-date))))
17537 (defun org-date-from-calendar ()
17538 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17539 If there is already a time stamp at the cursor position, update it."
17540 (interactive)
17541 (if (org-at-timestamp-p t)
17542 (org-timestamp-change 0 'calendar)
17543 (let ((cal-date (org-get-date-from-calendar)))
17544 (org-insert-time-stamp
17545 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17547 (defcustom org-effort-durations
17548 `(("h" . 60)
17549 ("d" . ,(* 60 8))
17550 ("w" . ,(* 60 8 5))
17551 ("m" . ,(* 60 8 5 4))
17552 ("y" . ,(* 60 8 5 40)))
17553 "Conversion factor to minutes for an effort modifier.
17555 Each entry has the form (MODIFIER . MINUTES).
17557 In an effort string, a number followed by MODIFIER is multiplied
17558 by the specified number of MINUTES to obtain an effort in
17559 minutes.
17561 For example, if the value of this variable is ((\"hours\" . 60)), then an
17562 effort string \"2hours\" is equivalent to 120 minutes."
17563 :group 'org-agenda
17564 :version "24.1"
17565 :type '(alist :key-type (string :tag "Modifier")
17566 :value-type (number :tag "Minutes")))
17568 (defun org-minutes-to-clocksum-string (m)
17569 "Format number of minutes as a clocksum string.
17570 The format is determined by `org-time-clocksum-format',
17571 `org-time-clocksum-use-fractional' and
17572 `org-time-clocksum-fractional-format' and
17573 `org-time-clocksum-use-effort-durations'."
17574 (let ((clocksum "")
17575 (m (round m)) ; Don't allow fractions of minutes
17576 h d w mo y fmt n)
17577 (setq h (if org-time-clocksum-use-effort-durations
17578 (cdr (assoc "h" org-effort-durations)) 60)
17579 d (if org-time-clocksum-use-effort-durations
17580 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17581 w (if org-time-clocksum-use-effort-durations
17582 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17583 mo (if org-time-clocksum-use-effort-durations
17584 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17585 y (if org-time-clocksum-use-effort-durations
17586 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17587 ;; fractional format
17588 (if org-time-clocksum-use-fractional
17589 (cond
17590 ;; single format string
17591 ((stringp org-time-clocksum-fractional-format)
17592 (format org-time-clocksum-fractional-format (/ m (float h))))
17593 ;; choice of fractional formats for different time units
17594 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17595 (> (/ (truncate m) (* y d h)) 0))
17596 (format fmt (/ m (* y d (float h)))))
17597 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17598 (> (/ (truncate m) (* mo d h)) 0))
17599 (format fmt (/ m (* mo d (float h)))))
17600 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17601 (> (/ (truncate m) (* w d h)) 0))
17602 (format fmt (/ m (* w d (float h)))))
17603 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17604 (> (/ (truncate m) (* d h)) 0))
17605 (format fmt (/ m (* d (float h)))))
17606 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17607 (> (/ (truncate m) h) 0))
17608 (format fmt (/ m (float h))))
17609 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17610 (format fmt m))
17611 ;; fall back to smallest time unit with a format
17612 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17613 (format fmt (/ m (float h))))
17614 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17615 (format fmt (/ m (* d (float h)))))
17616 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17617 (format fmt (/ m (* w d (float h)))))
17618 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17619 (format fmt (/ m (* mo d (float h)))))
17620 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17621 (format fmt (/ m (* y d (float h))))))
17622 ;; standard (non-fractional) format, with single format string
17623 (if (stringp org-time-clocksum-format)
17624 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17625 ;; separate formats components
17626 (and (setq fmt (plist-get org-time-clocksum-format :years))
17627 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17628 (plist-get org-time-clocksum-format :require-years))
17629 (setq clocksum (concat clocksum (format fmt n))
17630 m (- m (* n y d h))))
17631 (and (setq fmt (plist-get org-time-clocksum-format :months))
17632 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17633 (plist-get org-time-clocksum-format :require-months))
17634 (setq clocksum (concat clocksum (format fmt n))
17635 m (- m (* n mo d h))))
17636 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17637 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17638 (plist-get org-time-clocksum-format :require-weeks))
17639 (setq clocksum (concat clocksum (format fmt n))
17640 m (- m (* n w d h))))
17641 (and (setq fmt (plist-get org-time-clocksum-format :days))
17642 (or (> (setq n (/ (truncate m) (* d h))) 0)
17643 (plist-get org-time-clocksum-format :require-days))
17644 (setq clocksum (concat clocksum (format fmt n))
17645 m (- m (* n d h))))
17646 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17647 (or (> (setq n (/ (truncate m) h)) 0)
17648 (plist-get org-time-clocksum-format :require-hours))
17649 (setq clocksum (concat clocksum (format fmt n))
17650 m (- m (* n h))))
17651 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17652 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17653 (setq clocksum (concat clocksum (format fmt m))))
17654 ;; return formatted time duration
17655 clocksum))))
17657 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17658 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17659 "Org mode version 8.0")
17661 (defun org-hours-to-clocksum-string (n)
17662 (org-minutes-to-clocksum-string (* n 60)))
17664 (defun org-hh:mm-string-to-minutes (s)
17665 "Convert a string H:MM to a number of minutes.
17666 If the string is just a number, interpret it as minutes.
17667 In fact, the first hh:mm or number in the string will be taken,
17668 there can be extra stuff in the string.
17669 If no number is found, the return value is 0."
17670 (cond
17671 ((integerp s) s)
17672 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17673 (+ (* (string-to-number (match-string 1 s)) 60)
17674 (string-to-number (match-string 2 s))))
17675 ((string-match "\\([0-9]+\\)" s)
17676 (string-to-number (match-string 1 s)))
17677 (t 0)))
17679 (defcustom org-image-actual-width t
17680 "Should we use the actual width of images when inlining them?
17682 When set to `t', always use the image width.
17684 When set to a number, use imagemagick (when available) to set
17685 the image's width to this value.
17687 When set to a number in a list, try to get the width from any
17688 #+ATTR.* keyword if it matches a width specification like
17690 #+ATTR_HTML: :width 300px
17692 and fall back on that number if none is found.
17694 When set to nil, try to get the width from an #+ATTR.* keyword
17695 and fall back on the original width if none is found.
17697 This requires Emacs >= 24.1, build with imagemagick support."
17698 :group 'org-appearance
17699 :version "24.4"
17700 :package-version '(Org . "8.0")
17701 :type '(choice
17702 (const :tag "Use the image width" t)
17703 (integer :tag "Use a number of pixels")
17704 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17705 (const :tag "Use #+ATTR* or don't resize" nil)))
17707 (defcustom org-agenda-inhibit-startup nil
17708 "Inhibit startup when preparing agenda buffers.
17709 When this variable is `t' (the default), the initialization of
17710 the Org agenda buffers is inhibited: e.g. the visibility state
17711 is not set, the tables are not re-aligned, etc."
17712 :type 'boolean
17713 :version "24.3"
17714 :group 'org-agenda)
17716 (defcustom org-agenda-ignore-drawer-properties nil
17717 "Avoid updating text properties when building the agenda.
17718 Properties are used to prepare buffers for effort estimates, appointments,
17719 and subtree-local categories.
17720 If you don't use these in the agenda, you can add them to this list and
17721 agenda building will be a bit faster.
17722 The value is a list, with zero or more of the symbols `effort', `appt',
17723 or `category'."
17724 :type '(set :greedy t
17725 (const effort)
17726 (const appt)
17727 (const category))
17728 :version "24.3"
17729 :group 'org-agenda)
17731 (defun org-duration-string-to-minutes (s &optional output-to-string)
17732 "Convert a duration string S to minutes.
17734 A bare number is interpreted as minutes, modifiers can be set by
17735 customizing `org-effort-durations' (which see).
17737 Entries containing a colon are interpreted as H:MM by
17738 `org-hh:mm-string-to-minutes'."
17739 (let ((result 0)
17740 (re (concat "\\([0-9.]+\\) *\\("
17741 (regexp-opt (mapcar 'car org-effort-durations))
17742 "\\)")))
17743 (while (string-match re s)
17744 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17745 (string-to-number (match-string 1 s))))
17746 (setq s (replace-match "" nil t s)))
17747 (setq result (floor result))
17748 (incf result (org-hh:mm-string-to-minutes s))
17749 (if output-to-string (number-to-string result) result)))
17751 ;;;; Files
17753 (defun org-save-all-org-buffers ()
17754 "Save all Org-mode buffers without user confirmation."
17755 (interactive)
17756 (message "Saving all Org-mode buffers...")
17757 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17758 (when (featurep 'org-id) (org-id-locations-save))
17759 (message "Saving all Org-mode buffers... done"))
17761 (defun org-revert-all-org-buffers ()
17762 "Revert all Org-mode buffers.
17763 Prompt for confirmation when there are unsaved changes.
17764 Be sure you know what you are doing before letting this function
17765 overwrite your changes.
17767 This function is useful in a setup where one tracks org files
17768 with a version control system, to revert on one machine after pulling
17769 changes from another. I believe the procedure must be like this:
17771 1. M-x org-save-all-org-buffers
17772 2. Pull changes from the other machine, resolve conflicts
17773 3. M-x org-revert-all-org-buffers"
17774 (interactive)
17775 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17776 (user-error "Abort"))
17777 (save-excursion
17778 (save-window-excursion
17779 (mapc
17780 (lambda (b)
17781 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17782 (with-current-buffer b buffer-file-name))
17783 (org-pop-to-buffer-same-window b)
17784 (revert-buffer t 'no-confirm)))
17785 (buffer-list))
17786 (when (and (featurep 'org-id) org-id-track-globally)
17787 (org-id-locations-load)))))
17789 ;;;; Agenda files
17791 ;;;###autoload
17792 (defun org-switchb (&optional arg)
17793 "Switch between Org buffers.
17794 With one prefix argument, restrict available buffers to files.
17795 With two prefix arguments, restrict available buffers to agenda files.
17797 Defaults to `iswitchb' for buffer name completion.
17798 Set `org-completion-use-ido' to make it use ido instead."
17799 (interactive "P")
17800 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17801 ((equal arg '(16)) (org-buffer-list 'agenda))
17802 (t (org-buffer-list))))
17803 (org-completion-use-iswitchb org-completion-use-iswitchb)
17804 (org-completion-use-ido org-completion-use-ido))
17805 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17806 (setq org-completion-use-iswitchb t))
17807 (org-pop-to-buffer-same-window
17808 (org-icompleting-read "Org buffer: "
17809 (mapcar 'list (mapcar 'buffer-name blist))
17810 nil t))))
17812 ;;; Define some older names previously used for this functionality
17813 ;;;###autoload
17814 (defalias 'org-ido-switchb 'org-switchb)
17815 ;;;###autoload
17816 (defalias 'org-iswitchb 'org-switchb)
17818 (defun org-buffer-list (&optional predicate exclude-tmp)
17819 "Return a list of Org buffers.
17820 PREDICATE can be `export', `files' or `agenda'.
17822 export restrict the list to Export buffers.
17823 files restrict the list to buffers visiting Org files.
17824 agenda restrict the list to buffers visiting agenda files.
17826 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17827 (let* ((bfn nil)
17828 (agenda-files (and (eq predicate 'agenda)
17829 (mapcar 'file-truename (org-agenda-files t))))
17830 (filter
17831 (cond
17832 ((eq predicate 'files)
17833 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17834 ((eq predicate 'export)
17835 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17836 ((eq predicate 'agenda)
17837 (lambda (b)
17838 (with-current-buffer b
17839 (and (derived-mode-p 'org-mode)
17840 (setq bfn (buffer-file-name b))
17841 (member (file-truename bfn) agenda-files)))))
17842 (t (lambda (b) (with-current-buffer b
17843 (or (derived-mode-p 'org-mode)
17844 (string-match "\*Org .*Export"
17845 (buffer-name b)))))))))
17846 (delq nil
17847 (mapcar
17848 (lambda(b)
17849 (if (and (funcall filter b)
17850 (or (not exclude-tmp)
17851 (not (string-match "tmp" (buffer-name b)))))
17853 nil))
17854 (buffer-list)))))
17856 (defun org-agenda-files (&optional unrestricted archives)
17857 "Get the list of agenda files.
17858 Optional UNRESTRICTED means return the full list even if a restriction
17859 is currently in place.
17860 When ARCHIVES is t, include all archive files that are really being
17861 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17862 `org-agenda-archives-mode' is t."
17863 (let ((files
17864 (cond
17865 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17866 ((stringp org-agenda-files) (org-read-agenda-file-list))
17867 ((listp org-agenda-files) org-agenda-files)
17868 (t (error "Invalid value of `org-agenda-files'")))))
17869 (setq files (apply 'append
17870 (mapcar (lambda (f)
17871 (if (file-directory-p f)
17872 (directory-files
17873 f t org-agenda-file-regexp)
17874 (list f)))
17875 files)))
17876 (when org-agenda-skip-unavailable-files
17877 (setq files (delq nil
17878 (mapcar (function
17879 (lambda (file)
17880 (and (file-readable-p file) file)))
17881 files))))
17882 (when (or (eq archives t)
17883 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17884 (setq files (org-add-archive-files files)))
17885 files))
17887 (defun org-agenda-file-p (&optional file)
17888 "Return non-nil, if FILE is an agenda file.
17889 If FILE is omitted, use the file associated with the current
17890 buffer."
17891 (member (or file (buffer-file-name))
17892 (org-agenda-files t)))
17894 (defun org-edit-agenda-file-list ()
17895 "Edit the list of agenda files.
17896 Depending on setup, this either uses customize to edit the variable
17897 `org-agenda-files', or it visits the file that is holding the list. In the
17898 latter case, the buffer is set up in a way that saving it automatically kills
17899 the buffer and restores the previous window configuration."
17900 (interactive)
17901 (if (stringp org-agenda-files)
17902 (let ((cw (current-window-configuration)))
17903 (find-file org-agenda-files)
17904 (org-set-local 'org-window-configuration cw)
17905 (org-add-hook 'after-save-hook
17906 (lambda ()
17907 (set-window-configuration
17908 (prog1 org-window-configuration
17909 (kill-buffer (current-buffer))))
17910 (org-install-agenda-files-menu)
17911 (message "New agenda file list installed"))
17912 nil 'local)
17913 (message "%s" (substitute-command-keys
17914 "Edit list and finish with \\[save-buffer]")))
17915 (customize-variable 'org-agenda-files)))
17917 (defun org-store-new-agenda-file-list (list)
17918 "Set new value for the agenda file list and save it correctly."
17919 (if (stringp org-agenda-files)
17920 (let ((fe (org-read-agenda-file-list t)) b u)
17921 (while (setq b (find-buffer-visiting org-agenda-files))
17922 (kill-buffer b))
17923 (with-temp-file org-agenda-files
17924 (insert
17925 (mapconcat
17926 (lambda (f) ;; Keep un-expanded entries.
17927 (if (setq u (assoc f fe))
17928 (cdr u)
17930 list "\n")
17931 "\n")))
17932 (let ((org-mode-hook nil) (org-inhibit-startup t)
17933 (org-insert-mode-line-in-empty-file nil))
17934 (setq org-agenda-files list)
17935 (customize-save-variable 'org-agenda-files org-agenda-files))))
17937 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17938 "Read the list of agenda files from a file.
17939 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17940 filenames, used by `org-store-new-agenda-file-list' to write back
17941 un-expanded file names."
17942 (when (file-directory-p org-agenda-files)
17943 (error "`org-agenda-files' cannot be a single directory"))
17944 (when (stringp org-agenda-files)
17945 (with-temp-buffer
17946 (insert-file-contents org-agenda-files)
17947 (mapcar
17948 (lambda (f)
17949 (let ((e (expand-file-name (substitute-in-file-name f)
17950 org-directory)))
17951 (if pair-with-expansion
17952 (cons e f)
17953 e)))
17954 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17956 ;;;###autoload
17957 (defun org-cycle-agenda-files ()
17958 "Cycle through the files in `org-agenda-files'.
17959 If the current buffer visits an agenda file, find the next one in the list.
17960 If the current buffer does not, find the first agenda file."
17961 (interactive)
17962 (let* ((fs (org-agenda-files t))
17963 (files (append fs (list (car fs))))
17964 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17965 file)
17966 (unless files (user-error "No agenda files"))
17967 (catch 'exit
17968 (while (setq file (pop files))
17969 (if (equal (file-truename file) tcf)
17970 (when (car files)
17971 (find-file (car files))
17972 (throw 'exit t))))
17973 (find-file (car fs)))
17974 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17976 (defun org-agenda-file-to-front (&optional to-end)
17977 "Move/add the current file to the top of the agenda file list.
17978 If the file is not present in the list, it is added to the front. If it is
17979 present, it is moved there. With optional argument TO-END, add/move to the
17980 end of the list."
17981 (interactive "P")
17982 (let ((org-agenda-skip-unavailable-files nil)
17983 (file-alist (mapcar (lambda (x)
17984 (cons (file-truename x) x))
17985 (org-agenda-files t)))
17986 (ctf (file-truename
17987 (or buffer-file-name
17988 (user-error "Please save the current buffer to a file"))))
17989 x had)
17990 (setq x (assoc ctf file-alist) had x)
17992 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17993 (if to-end
17994 (setq file-alist (append (delq x file-alist) (list x)))
17995 (setq file-alist (cons x (delq x file-alist))))
17996 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17997 (org-install-agenda-files-menu)
17998 (message "File %s to %s of agenda file list"
17999 (if had "moved" "added") (if to-end "end" "front"))))
18001 (defun org-remove-file (&optional file)
18002 "Remove current file from the list of files in variable `org-agenda-files'.
18003 These are the files which are being checked for agenda entries.
18004 Optional argument FILE means use this file instead of the current."
18005 (interactive)
18006 (let* ((org-agenda-skip-unavailable-files nil)
18007 (file (or file buffer-file-name
18008 (user-error "Current buffer does not visit a file")))
18009 (true-file (file-truename file))
18010 (afile (abbreviate-file-name file))
18011 (files (delq nil (mapcar
18012 (lambda (x)
18013 (if (equal true-file
18014 (file-truename x))
18015 nil x))
18016 (org-agenda-files t)))))
18017 (if (not (= (length files) (length (org-agenda-files t))))
18018 (progn
18019 (org-store-new-agenda-file-list files)
18020 (org-install-agenda-files-menu)
18021 (message "Removed file: %s" afile))
18022 (message "File was not in list: %s (not removed)" afile))))
18024 (defun org-file-menu-entry (file)
18025 (vector file (list 'find-file file) t))
18027 (defun org-check-agenda-file (file)
18028 "Make sure FILE exists. If not, ask user what to do."
18029 (when (not (file-exists-p file))
18030 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18031 (abbreviate-file-name file))
18032 (let ((r (downcase (read-char-exclusive))))
18033 (cond
18034 ((equal r ?r)
18035 (org-remove-file file)
18036 (throw 'nextfile t))
18037 (t (error "Abort"))))))
18039 (defun org-get-agenda-file-buffer (file)
18040 "Get a buffer visiting FILE. If the buffer needs to be created, add
18041 it to the list of buffers which might be released later."
18042 (let ((buf (org-find-base-buffer-visiting file)))
18043 (if buf
18044 buf ; just return it
18045 ;; Make a new buffer and remember it
18046 (setq buf (find-file-noselect file))
18047 (if buf (push buf org-agenda-new-buffers))
18048 buf)))
18050 (defun org-release-buffers (blist)
18051 "Release all buffers in list, asking the user for confirmation when needed.
18052 When a buffer is unmodified, it is just killed. When modified, it is saved
18053 \(if the user agrees) and then killed."
18054 (let (buf file)
18055 (while (setq buf (pop blist))
18056 (setq file (buffer-file-name buf))
18057 (when (and (buffer-modified-p buf)
18058 file
18059 (y-or-n-p (format "Save file %s? " file)))
18060 (with-current-buffer buf (save-buffer)))
18061 (kill-buffer buf))))
18063 (defun org-agenda-prepare-buffers (files)
18064 "Create buffers for all agenda files, protect archived trees and comments."
18065 (interactive)
18066 (let ((pa '(:org-archived t))
18067 (pc '(:org-comment t))
18068 (pall '(:org-archived t :org-comment t))
18069 (inhibit-read-only t)
18070 (org-inhibit-startup org-agenda-inhibit-startup)
18071 (rea (concat ":" org-archive-tag ":"))
18072 file re pos)
18073 (setq org-tag-alist-for-agenda nil
18074 org-tag-groups-alist-for-agenda nil)
18075 (save-window-excursion
18076 (save-restriction
18077 (while (setq file (pop files))
18078 (catch 'nextfile
18079 (if (bufferp file)
18080 (set-buffer file)
18081 (org-check-agenda-file file)
18082 (set-buffer (org-get-agenda-file-buffer file)))
18083 (widen)
18084 (org-set-regexps-and-options-for-tags)
18085 (setq pos (point))
18086 (goto-char (point-min))
18087 (let ((case-fold-search t))
18088 (when (search-forward "#+setupfile" nil t)
18089 ;; Don't set all regexps and options systematically as
18090 ;; this is only run for setting agenda tags from setup
18091 ;; file
18092 (org-set-regexps-and-options)))
18093 (or (memq 'category org-agenda-ignore-drawer-properties)
18094 (org-refresh-category-properties))
18095 (or (memq 'effort org-agenda-ignore-drawer-properties)
18096 (org-refresh-properties org-effort-property 'org-effort))
18097 (or (memq 'appt org-agenda-ignore-drawer-properties)
18098 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18099 (setq org-todo-keywords-for-agenda
18100 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18101 (setq org-done-keywords-for-agenda
18102 (append org-done-keywords-for-agenda org-done-keywords))
18103 (setq org-todo-keyword-alist-for-agenda
18104 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18105 (setq org-drawers-for-agenda
18106 (append org-drawers-for-agenda org-drawers))
18107 (setq org-tag-alist-for-agenda
18108 (org-uniquify
18109 (append org-tag-alist-for-agenda
18110 org-tag-alist
18111 org-tag-persistent-alist)))
18112 (if org-group-tags
18113 (setq org-tag-groups-alist-for-agenda
18114 (org-uniquify-alist
18115 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18116 (org-with-silent-modifications
18117 (save-excursion
18118 (remove-text-properties (point-min) (point-max) pall)
18119 (when org-agenda-skip-archived-trees
18120 (goto-char (point-min))
18121 (while (re-search-forward rea nil t)
18122 (if (org-at-heading-p t)
18123 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18124 (goto-char (point-min))
18125 (setq re (format org-heading-keyword-regexp-format
18126 org-comment-string))
18127 (while (re-search-forward re nil t)
18128 (add-text-properties
18129 (match-beginning 0) (org-end-of-subtree t) pc))))
18130 (goto-char pos)))))
18131 (setq org-todo-keywords-for-agenda
18132 (org-uniquify org-todo-keywords-for-agenda))
18133 (setq org-todo-keyword-alist-for-agenda
18134 (org-uniquify org-todo-keyword-alist-for-agenda))))
18137 ;;;; CDLaTeX minor mode
18139 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18140 "Keymap for the minor `org-cdlatex-mode'.")
18142 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18143 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18144 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18145 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18146 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18148 (defvar org-cdlatex-texmathp-advice-is-done nil
18149 "Flag remembering if we have applied the advice to texmathp already.")
18151 (define-minor-mode org-cdlatex-mode
18152 "Toggle the minor `org-cdlatex-mode'.
18153 This mode supports entering LaTeX environment and math in LaTeX fragments
18154 in Org-mode.
18155 \\{org-cdlatex-mode-map}"
18156 nil " OCDL" nil
18157 (when org-cdlatex-mode
18158 (require 'cdlatex)
18159 (run-hooks 'cdlatex-mode-hook)
18160 (cdlatex-compute-tables))
18161 (unless org-cdlatex-texmathp-advice-is-done
18162 (setq org-cdlatex-texmathp-advice-is-done t)
18163 (defadvice texmathp (around org-math-always-on activate)
18164 "Always return t in org-mode buffers.
18165 This is because we want to insert math symbols without dollars even outside
18166 the LaTeX math segments. If Orgmode thinks that point is actually inside
18167 an embedded LaTeX fragment, let texmathp do its job.
18168 \\[org-cdlatex-mode-map]"
18169 (interactive)
18170 (let (p)
18171 (cond
18172 ((not (derived-mode-p 'org-mode)) ad-do-it)
18173 ((eq this-command 'cdlatex-math-symbol)
18174 (setq ad-return-value t
18175 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18177 (let ((p (org-inside-LaTeX-fragment-p)))
18178 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18179 (setq ad-return-value t
18180 texmathp-why '("Org-mode embedded math" . 0))
18181 (if p ad-do-it)))))))))
18183 (defun turn-on-org-cdlatex ()
18184 "Unconditionally turn on `org-cdlatex-mode'."
18185 (org-cdlatex-mode 1))
18187 (defun org-try-cdlatex-tab ()
18188 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18189 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18190 - inside a LaTeX fragment, or
18191 - after the first word in a line, where an abbreviation expansion could
18192 insert a LaTeX environment."
18193 (when org-cdlatex-mode
18194 (cond
18195 ;; Before any word on the line: No expansion possible.
18196 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18197 ;; Just after first word on the line: Expand it. Make sure it
18198 ;; cannot happen on headlines, though.
18199 ((save-excursion
18200 (skip-chars-backward "a-zA-Z0-9*")
18201 (skip-chars-backward " \t")
18202 (and (bolp) (not (org-at-heading-p))))
18203 (cdlatex-tab) t)
18204 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18206 (defun org-cdlatex-underscore-caret (&optional arg)
18207 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18208 Revert to the normal definition outside of these fragments."
18209 (interactive "P")
18210 (if (org-inside-LaTeX-fragment-p)
18211 (call-interactively 'cdlatex-sub-superscript)
18212 (let (org-cdlatex-mode)
18213 (call-interactively (key-binding (vector last-input-event))))))
18215 (defun org-cdlatex-math-modify (&optional arg)
18216 "Execute `cdlatex-math-modify' in LaTeX fragments.
18217 Revert to the normal definition outside of these fragments."
18218 (interactive "P")
18219 (if (org-inside-LaTeX-fragment-p)
18220 (call-interactively 'cdlatex-math-modify)
18221 (let (org-cdlatex-mode)
18222 (call-interactively (key-binding (vector last-input-event))))))
18226 ;;;; LaTeX fragments
18228 (defvar org-latex-regexps
18229 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18230 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18231 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18232 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18233 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18234 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18235 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18236 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18237 "Regular expressions for matching embedded LaTeX.")
18239 (defun org-inside-LaTeX-fragment-p ()
18240 "Test if point is inside a LaTeX fragment.
18241 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18242 sequence appearing also before point.
18243 Even though the matchers for math are configurable, this function assumes
18244 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18245 delimiters are skipped when they have been removed by customization.
18246 The return value is nil, or a cons cell with the delimiter and the
18247 position of this delimiter.
18249 This function does a reasonably good job, but can locally be fooled by
18250 for example currency specifications. For example it will assume being in
18251 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18252 fragments that are properly closed, but during editing, we have to live
18253 with the uncertainty caused by missing closing delimiters. This function
18254 looks only before point, not after."
18255 (catch 'exit
18256 (let ((pos (point))
18257 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18258 (lim (progn
18259 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18260 (point)))
18261 dd-on str (start 0) m re)
18262 (goto-char pos)
18263 (when dodollar
18264 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18265 re (nth 1 (assoc "$" org-latex-regexps)))
18266 (while (string-match re str start)
18267 (cond
18268 ((= (match-end 0) (length str))
18269 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18270 ((= (match-end 0) (- (length str) 5))
18271 (throw 'exit nil))
18272 (t (setq start (match-end 0))))))
18273 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18274 (goto-char pos)
18275 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18276 (and (match-beginning 2) (throw 'exit nil))
18277 ;; count $$
18278 (while (re-search-backward "\\$\\$" lim t)
18279 (setq dd-on (not dd-on)))
18280 (goto-char pos)
18281 (if dd-on (cons "$$" m))))))
18283 (defun org-inside-latex-macro-p ()
18284 "Is point inside a LaTeX macro or its arguments?"
18285 (save-match-data
18286 (org-in-regexp
18287 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18289 (defvar org-latex-fragment-image-overlays nil
18290 "List of overlays carrying the images of latex fragments.")
18291 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18293 (defun org-remove-latex-fragment-image-overlays ()
18294 "Remove all overlays with LaTeX fragment images in current buffer."
18295 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18296 (setq org-latex-fragment-image-overlays nil))
18298 (defun org-preview-latex-fragment (&optional subtree)
18299 "Preview the LaTeX fragment at point, or all locally or globally.
18300 If the cursor is in a LaTeX fragment, create the image and overlay
18301 it over the source code. If there is no fragment at point, display
18302 all fragments in the current text, from one headline to the next. With
18303 prefix SUBTREE, display all fragments in the current subtree. With a
18304 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18305 the cursor is before the first headline,
18306 display all fragments in the buffer.
18307 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18308 (interactive "P")
18309 (unless buffer-file-name
18310 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18311 (when (display-graphic-p)
18312 (org-remove-latex-fragment-image-overlays)
18313 (save-excursion
18314 (save-restriction
18315 (let (beg end at msg)
18316 (cond
18317 ((or (equal subtree '(16))
18318 (not (save-excursion
18319 (re-search-backward org-outline-regexp-bol nil t))))
18320 (setq beg (point-min) end (point-max)
18321 msg "Creating images for buffer...%s"))
18322 ((equal subtree '(4))
18323 (org-back-to-heading)
18324 (setq beg (point) end (org-end-of-subtree t)
18325 msg "Creating images for subtree...%s"))
18327 (if (setq at (org-inside-LaTeX-fragment-p))
18328 (goto-char (max (point-min) (- (cdr at) 2)))
18329 (org-back-to-heading))
18330 (setq beg (point) end (progn (outline-next-heading) (point))
18331 msg (if at "Creating image...%s"
18332 "Creating images for entry...%s"))))
18333 (message msg "")
18334 (narrow-to-region beg end)
18335 (goto-char beg)
18336 (org-format-latex
18337 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18338 (file-name-nondirectory
18339 buffer-file-name)))
18340 default-directory 'overlays msg at 'forbuffer
18341 org-latex-create-formula-image-program)
18342 (message msg "done. Use `C-c C-c' to remove images."))))))
18344 (defun org-format-latex (prefix &optional dir overlays msg at
18345 forbuffer processing-type)
18346 "Replace LaTeX fragments with links to an image, and produce images.
18347 Some of the options can be changed using the variable
18348 `org-format-latex-options'."
18349 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18350 (let* ((prefixnodir (file-name-nondirectory prefix))
18351 (absprefix (expand-file-name prefix dir))
18352 (todir (file-name-directory absprefix))
18353 (opt org-format-latex-options)
18354 (optnew org-format-latex-options)
18355 (matchers (plist-get opt :matchers))
18356 (re-list org-latex-regexps)
18357 (cnt 0) txt hash link beg end re e checkdir
18358 string
18359 m n block-type block linkfile movefile ov)
18360 ;; Check the different regular expressions
18361 (while (setq e (pop re-list))
18362 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18363 block (if block-type "\n\n" ""))
18364 (when (member m matchers)
18365 (goto-char (point-min))
18366 (while (re-search-forward re nil t)
18367 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18368 (or (not overlays)
18369 (not (eq (get-char-property (match-beginning n)
18370 'org-overlay-type)
18371 'org-latex-overlay))))
18372 (cond
18373 ((eq processing-type 'verbatim))
18374 ((eq processing-type 'mathjax)
18375 ;; Prepare for MathJax processing.
18376 (setq string (match-string n))
18377 (when (member m '("$" "$1"))
18378 (save-excursion
18379 (delete-region (match-beginning n) (match-end n))
18380 (goto-char (match-beginning n))
18381 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18382 ((or (eq processing-type 'dvipng)
18383 (eq processing-type 'imagemagick))
18384 ;; Process to an image.
18385 (setq txt (match-string n)
18386 beg (match-beginning n) end (match-end n)
18387 cnt (1+ cnt))
18388 (let ((face (face-at-point))
18389 (fg (plist-get opt :foreground))
18390 (bg (plist-get opt :background))
18391 ;; Ensure full list is printed.
18392 print-length print-level)
18393 (when forbuffer
18394 ;; Get the colors from the face at point.
18395 (goto-char beg)
18396 (when (eq fg 'auto)
18397 (setq fg (face-attribute face :foreground nil 'default)))
18398 (when (eq bg 'auto)
18399 (setq bg (face-attribute face :background nil 'default)))
18400 (setq optnew (copy-sequence opt))
18401 (plist-put optnew :foreground fg)
18402 (plist-put optnew :background bg))
18403 (setq hash (sha1 (prin1-to-string
18404 (list org-format-latex-header
18405 org-latex-default-packages-alist
18406 org-latex-packages-alist
18407 org-format-latex-options
18408 forbuffer txt fg bg)))
18409 linkfile (format "%s_%s.png" prefix hash)
18410 movefile (format "%s_%s.png" absprefix hash)))
18411 (setq link (concat block "[[file:" linkfile "]]" block))
18412 (if msg (message msg cnt))
18413 (goto-char beg)
18414 (unless checkdir ; Ensure the directory exists.
18415 (setq checkdir t)
18416 (or (file-directory-p todir) (make-directory todir t)))
18417 (unless (file-exists-p movefile)
18418 (org-create-formula-image
18419 txt movefile optnew forbuffer processing-type))
18420 (if overlays
18421 (progn
18422 (mapc (lambda (o)
18423 (if (eq (overlay-get o 'org-overlay-type)
18424 'org-latex-overlay)
18425 (delete-overlay o)))
18426 (overlays-in beg end))
18427 (setq ov (make-overlay beg end))
18428 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18429 (if (featurep 'xemacs)
18430 (progn
18431 (overlay-put ov 'invisible t)
18432 (overlay-put
18433 ov 'end-glyph
18434 (make-glyph (vector 'png :file movefile))))
18435 (overlay-put
18436 ov 'display
18437 (list 'image :type 'png :file movefile :ascent 'center)))
18438 (push ov org-latex-fragment-image-overlays)
18439 (goto-char end))
18440 (delete-region beg end)
18441 (insert (org-add-props link
18442 (list 'org-latex-src
18443 (replace-regexp-in-string
18444 "\"" "" txt)
18445 'org-latex-src-embed-type
18446 (if block-type 'paragraph 'character))))))
18447 ((eq processing-type 'mathml)
18448 ;; Process to MathML
18449 (unless (save-match-data (org-format-latex-mathml-available-p))
18450 (user-error "LaTeX to MathML converter not configured"))
18451 (setq txt (match-string n)
18452 beg (match-beginning n) end (match-end n)
18453 cnt (1+ cnt))
18454 (if msg (message msg cnt))
18455 (goto-char beg)
18456 (delete-region beg end)
18457 (insert (org-format-latex-as-mathml
18458 txt block-type prefix dir)))
18460 (error "Unknown conversion type %s for LaTeX fragments"
18461 processing-type)))))))))
18463 (defun org-create-math-formula (latex-frag &optional mathml-file)
18464 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18465 Use `org-latex-to-mathml-convert-command'. If the conversion is
18466 sucessful, return the portion between \"<math...> </math>\"
18467 elements otherwise return nil. When MATHML-FILE is specified,
18468 write the results in to that file. When invoked as an
18469 interactive command, prompt for LATEX-FRAG, with initial value
18470 set to the current active region and echo the results for user
18471 inspection."
18472 (interactive (list (let ((frag (when (org-region-active-p)
18473 (buffer-substring-no-properties
18474 (region-beginning) (region-end)))))
18475 (read-string "LaTeX Fragment: " frag nil frag))))
18476 (unless latex-frag (error "Invalid LaTeX fragment"))
18477 (let* ((tmp-in-file (file-relative-name
18478 (make-temp-name (expand-file-name "ltxmathml-in"))))
18479 (ignore (write-region latex-frag nil tmp-in-file))
18480 (tmp-out-file (file-relative-name
18481 (make-temp-name (expand-file-name "ltxmathml-out"))))
18482 (cmd (format-spec
18483 org-latex-to-mathml-convert-command
18484 `((?j . ,(shell-quote-argument
18485 (expand-file-name org-latex-to-mathml-jar-file)))
18486 (?I . ,(shell-quote-argument tmp-in-file))
18487 (?o . ,(shell-quote-argument tmp-out-file)))))
18488 mathml shell-command-output)
18489 (when (org-called-interactively-p 'any)
18490 (unless (org-format-latex-mathml-available-p)
18491 (user-error "LaTeX to MathML converter not configured")))
18492 (message "Running %s" cmd)
18493 (setq shell-command-output (shell-command-to-string cmd))
18494 (setq mathml
18495 (when (file-readable-p tmp-out-file)
18496 (with-current-buffer (find-file-noselect tmp-out-file t)
18497 (goto-char (point-min))
18498 (when (re-search-forward
18499 (concat
18500 (regexp-quote
18501 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18502 "\\(.\\|\n\\)*"
18503 (regexp-quote "</math>")) nil t)
18504 (prog1 (match-string 0) (kill-buffer))))))
18505 (cond
18506 (mathml
18507 (setq mathml
18508 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18509 (when mathml-file
18510 (write-region mathml nil mathml-file))
18511 (when (org-called-interactively-p 'any)
18512 (message mathml)))
18513 ((message "LaTeX to MathML conversion failed")
18514 (message shell-command-output)))
18515 (delete-file tmp-in-file)
18516 (when (file-exists-p tmp-out-file)
18517 (delete-file tmp-out-file))
18518 mathml))
18520 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18521 prefix &optional dir)
18522 "Use `org-create-math-formula' but check local cache first."
18523 (let* ((absprefix (expand-file-name prefix dir))
18524 (print-length nil) (print-level nil)
18525 (formula-id (concat
18526 "formula-"
18527 (sha1
18528 (prin1-to-string
18529 (list latex-frag
18530 org-latex-to-mathml-convert-command)))))
18531 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18532 (formula-cache-dir (file-name-directory formula-cache)))
18534 (unless (file-directory-p formula-cache-dir)
18535 (make-directory formula-cache-dir t))
18537 (unless (file-exists-p formula-cache)
18538 (org-create-math-formula latex-frag formula-cache))
18540 (if (file-exists-p formula-cache)
18541 ;; Successful conversion. Return the link to MathML file.
18542 (org-add-props
18543 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18544 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18545 'org-latex-src-embed-type (if latex-frag-type
18546 'paragraph 'character)))
18547 ;; Failed conversion. Return the LaTeX fragment verbatim
18548 latex-frag)))
18550 (defun org-create-formula-image (string tofile options buffer &optional type)
18551 "Create an image from LaTeX source using dvipng or convert.
18552 This function calls either `org-create-formula-image-with-dvipng'
18553 or `org-create-formula-image-with-imagemagick' depending on the
18554 value of `org-latex-create-formula-image-program' or on the value
18555 of the optional TYPE variable.
18557 Note: ultimately these two function should be combined as they
18558 share a good deal of logic."
18559 (org-check-external-command
18560 "latex" "needed to convert LaTeX fragments to images")
18561 (funcall
18562 (case (or type org-latex-create-formula-image-program)
18563 ('dvipng
18564 (org-check-external-command
18565 "dvipng" "needed to convert LaTeX fragments to images")
18566 #'org-create-formula-image-with-dvipng)
18567 ('imagemagick
18568 (org-check-external-command
18569 "convert" "you need to install imagemagick")
18570 #'org-create-formula-image-with-imagemagick)
18571 (t (error
18572 "Invalid value of `org-latex-create-formula-image-program'")))
18573 string tofile options buffer))
18575 (declare-function org-export-get-backend "ox" (name))
18576 (declare-function org-export--get-global-options "ox" (&optional backend))
18577 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18578 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18579 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18580 (defun org-create-formula--latex-header ()
18581 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18582 (let ((info (org-combine-plists (org-export--get-global-options
18583 (org-export-get-backend 'latex))
18584 (org-export--get-inbuffer-options
18585 (org-export-get-backend 'latex)))))
18586 (org-latex-guess-babel-language
18587 (org-latex-guess-inputenc
18588 (org-splice-latex-header
18589 org-format-latex-header
18590 org-latex-default-packages-alist
18591 org-latex-packages-alist t
18592 (plist-get info :latex-header)))
18593 info)))
18595 ;; This function borrows from Ganesh Swami's latex2png.el
18596 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18597 "This calls dvipng."
18598 (require 'ox-latex)
18599 (let* ((tmpdir (if (featurep 'xemacs)
18600 (temp-directory)
18601 temporary-file-directory))
18602 (texfilebase (make-temp-name
18603 (expand-file-name "orgtex" tmpdir)))
18604 (texfile (concat texfilebase ".tex"))
18605 (dvifile (concat texfilebase ".dvi"))
18606 (pngfile (concat texfilebase ".png"))
18607 (fnh (if (featurep 'xemacs)
18608 (font-height (face-font 'default))
18609 (face-attribute 'default :height nil)))
18610 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18611 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18612 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18613 "Black"))
18614 (bg (or (plist-get options (if buffer :background :html-background))
18615 "Transparent")))
18616 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18617 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18618 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18619 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18620 (let ((latex-header (org-create-formula--latex-header)))
18621 (with-temp-file texfile
18622 (insert latex-header)
18623 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18624 (let ((dir default-directory))
18625 (condition-case nil
18626 (progn
18627 (cd tmpdir)
18628 (call-process "latex" nil nil nil texfile))
18629 (error nil))
18630 (cd dir))
18631 (if (not (file-exists-p dvifile))
18632 (progn (message "Failed to create dvi file from %s" texfile) nil)
18633 (condition-case nil
18634 (if (featurep 'xemacs)
18635 (call-process "dvipng" nil nil nil
18636 "-fg" fg "-bg" bg
18637 "-T" "tight"
18638 "-o" pngfile
18639 dvifile)
18640 (call-process "dvipng" nil nil nil
18641 "-fg" fg "-bg" bg
18642 "-D" dpi
18643 ;;"-x" scale "-y" scale
18644 "-T" "tight"
18645 "-o" pngfile
18646 dvifile))
18647 (error nil))
18648 (if (not (file-exists-p pngfile))
18649 (if org-format-latex-signal-error
18650 (error "Failed to create png file from %s" texfile)
18651 (message "Failed to create png file from %s" texfile)
18652 nil)
18653 ;; Use the requested file name and clean up
18654 (copy-file pngfile tofile 'replace)
18655 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18656 (if (file-exists-p (concat texfilebase e))
18657 (delete-file (concat texfilebase e))))
18658 pngfile))))
18660 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18661 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18662 "This calls convert, which is included into imagemagick."
18663 (require 'ox-latex)
18664 (let* ((tmpdir (if (featurep 'xemacs)
18665 (temp-directory)
18666 temporary-file-directory))
18667 (texfilebase (make-temp-name
18668 (expand-file-name "orgtex" tmpdir)))
18669 (texfile (concat texfilebase ".tex"))
18670 (pdffile (concat texfilebase ".pdf"))
18671 (pngfile (concat texfilebase ".png"))
18672 (fnh (if (featurep 'xemacs)
18673 (font-height (face-font 'default))
18674 (face-attribute 'default :height nil)))
18675 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18676 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18677 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18678 "black"))
18679 (bg (or (plist-get options (if buffer :background :html-background))
18680 "white")))
18681 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18682 (setq fg (org-latex-color-format fg)))
18683 (if (eq bg 'default) (setq bg (org-latex-color :background))
18684 (setq bg (org-latex-color-format
18685 (if (string= bg "Transparent") "white" bg))))
18686 (let ((latex-header (org-create-formula--latex-header)))
18687 (with-temp-file texfile
18688 (insert latex-header)
18689 (insert "\n\\begin{document}\n"
18690 "\\definecolor{fg}{rgb}{" fg "}\n"
18691 "\\definecolor{bg}{rgb}{" bg "}\n"
18692 "\n\\pagecolor{bg}\n"
18693 "\n{\\color{fg}\n"
18694 string
18695 "\n}\n"
18696 "\n\\end{document}\n")))
18697 (org-latex-compile texfile t)
18698 (if (not (file-exists-p pdffile))
18699 (progn (message "Failed to create pdf file from %s" texfile) nil)
18700 (condition-case nil
18701 (if (featurep 'xemacs)
18702 (call-process "convert" nil nil nil
18703 "-density" "96"
18704 "-trim"
18705 "-antialias"
18706 pdffile
18707 "-quality" "100"
18708 ;; "-sharpen" "0x1.0"
18709 pngfile)
18710 (call-process "convert" nil nil nil
18711 "-density" dpi
18712 "-trim"
18713 "-antialias"
18714 pdffile
18715 "-quality" "100"
18716 ;; "-sharpen" "0x1.0"
18717 pngfile))
18718 (error nil))
18719 (if (not (file-exists-p pngfile))
18720 (if org-format-latex-signal-error
18721 (error "Failed to create png file from %s" texfile)
18722 (message "Failed to create png file from %s" texfile)
18723 nil)
18724 ;; Use the requested file name and clean up
18725 (copy-file pngfile tofile 'replace)
18726 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18727 (if (file-exists-p (concat texfilebase e))
18728 (delete-file (concat texfilebase e))))
18729 pngfile))))
18731 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18732 "Fill a LaTeX header template TPL.
18733 In the template, the following place holders will be recognized:
18735 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18736 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18737 [PACKAGES] \\usepackage statements for PKG
18738 [NO-PACKAGES] do not include PKG
18739 [EXTRA] the string EXTRA
18740 [NO-EXTRA] do not include EXTRA
18742 For backward compatibility, if both the positive and the negative place
18743 holder is missing, the positive one (without the \"NO-\") will be
18744 assumed to be present at the end of the template.
18745 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18746 EXTRA is a string.
18747 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18748 (let (rpl (end ""))
18749 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18750 (setq rpl (if (or (match-end 1) (not def-pkg))
18751 "" (org-latex-packages-to-string def-pkg snippets-p t))
18752 tpl (replace-match rpl t t tpl))
18753 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18755 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18756 (setq rpl (if (or (match-end 1) (not pkg))
18757 "" (org-latex-packages-to-string pkg snippets-p t))
18758 tpl (replace-match rpl t t tpl))
18759 (if pkg (setq end
18760 (concat end "\n"
18761 (org-latex-packages-to-string pkg snippets-p)))))
18763 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18764 (setq rpl (if (or (match-end 1) (not extra))
18765 "" (concat extra "\n"))
18766 tpl (replace-match rpl t t tpl))
18767 (if (and extra (string-match "\\S-" extra))
18768 (setq end (concat end "\n" extra))))
18770 (if (string-match "\\S-" end)
18771 (concat tpl "\n" end)
18772 tpl)))
18774 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18775 "Turn an alist of packages into a string with the \\usepackage macros."
18776 (setq pkg (mapconcat (lambda(p)
18777 (cond
18778 ((stringp p) p)
18779 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18780 (format "%% Package %s omitted" (cadr p)))
18781 ((equal "" (car p))
18782 (format "\\usepackage{%s}" (cadr p)))
18784 (format "\\usepackage[%s]{%s}"
18785 (car p) (cadr p)))))
18787 "\n"))
18788 (if newline (concat pkg "\n") pkg))
18790 (defun org-dvipng-color (attr)
18791 "Return a RGB color specification for dvipng."
18792 (apply 'format "rgb %s %s %s"
18793 (mapcar 'org-normalize-color
18794 (if (featurep 'xemacs)
18795 (color-rgb-components
18796 (face-property 'default
18797 (cond ((eq attr :foreground) 'foreground)
18798 ((eq attr :background) 'background))))
18799 (color-values (face-attribute 'default attr nil))))))
18801 (defun org-dvipng-color-format (color-name)
18802 "Convert COLOR-NAME to a RGB color value for dvipng."
18803 (apply 'format "rgb %s %s %s"
18804 (mapcar 'org-normalize-color
18805 (color-values color-name))))
18807 (defun org-latex-color (attr)
18808 "Return a RGB color for the LaTeX color package."
18809 (apply 'format "%s,%s,%s"
18810 (mapcar 'org-normalize-color
18811 (if (featurep 'xemacs)
18812 (color-rgb-components
18813 (face-property 'default
18814 (cond ((eq attr :foreground) 'foreground)
18815 ((eq attr :background) 'background))))
18816 (color-values (face-attribute 'default attr nil))))))
18818 (defun org-latex-color-format (color-name)
18819 "Convert COLOR-NAME to a RGB color value."
18820 (apply 'format "%s,%s,%s"
18821 (mapcar 'org-normalize-color
18822 (color-values color-name))))
18824 (defun org-normalize-color (value)
18825 "Return string to be used as color value for an RGB component."
18826 (format "%g" (/ value 65535.0)))
18830 ;; Image display
18832 (defvar org-inline-image-overlays nil)
18833 (make-variable-buffer-local 'org-inline-image-overlays)
18835 (defun org-toggle-inline-images (&optional include-linked)
18836 "Toggle the display of inline images.
18837 INCLUDE-LINKED is passed to `org-display-inline-images'."
18838 (interactive "P")
18839 (if org-inline-image-overlays
18840 (progn
18841 (org-remove-inline-images)
18842 (message "Inline image display turned off"))
18843 (org-display-inline-images include-linked)
18844 (if (and (org-called-interactively-p)
18845 org-inline-image-overlays)
18846 (message "%d images displayed inline"
18847 (length org-inline-image-overlays))
18848 (message "No images to display inline"))))
18850 (defun org-redisplay-inline-images ()
18851 "Refresh the display of inline images."
18852 (interactive)
18853 (if (not org-inline-image-overlays)
18854 (org-toggle-inline-images)
18855 (org-toggle-inline-images)
18856 (org-toggle-inline-images)))
18858 (defun org-display-inline-images (&optional include-linked refresh beg end)
18859 "Display inline images.
18860 Normally only links without a description part are inlined, because this
18861 is how it will work for export. When INCLUDE-LINKED is set, also links
18862 with a description part will be inlined. This can be nice for a quick
18863 look at those images, but it does not reflect what exported files will look
18864 like.
18865 When REFRESH is set, refresh existing images between BEG and END.
18866 This will create new image displays only if necessary.
18867 BEG and END default to the buffer boundaries."
18868 (interactive "P")
18869 (when (display-graphic-p)
18870 (unless refresh
18871 (org-remove-inline-images)
18872 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18873 (save-excursion
18874 (save-restriction
18875 (widen)
18876 (setq beg (or beg (point-min)) end (or end (point-max)))
18877 (goto-char beg)
18878 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18879 (substring (org-image-file-name-regexp) 0 -2)
18880 "\\)\\]" (if include-linked "" "\\]")))
18881 (case-fold-search t)
18882 old file ov img type attrwidth width)
18883 (while (re-search-forward re end t)
18884 (setq old (get-char-property-and-overlay (match-beginning 1)
18885 'org-image-overlay)
18886 file (expand-file-name
18887 (concat (or (match-string 3) "") (match-string 4))))
18888 (when (image-type-available-p 'imagemagick)
18889 (setq attrwidth (if (or (listp org-image-actual-width)
18890 (null org-image-actual-width))
18891 (save-excursion
18892 (save-match-data
18893 (when (re-search-backward
18894 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18895 (save-excursion
18896 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18897 (string-to-number (match-string 1))))))
18898 width (cond ((eq org-image-actual-width t) nil)
18899 ((null org-image-actual-width) attrwidth)
18900 ((numberp org-image-actual-width)
18901 org-image-actual-width)
18902 ((listp org-image-actual-width)
18903 (or attrwidth (car org-image-actual-width))))
18904 type (if width 'imagemagick)))
18905 (when (file-exists-p file)
18906 (if (and (car-safe old) refresh)
18907 (image-refresh (overlay-get (cdr old) 'display))
18908 (setq img (save-match-data (create-image file type nil :width width)))
18909 (when img
18910 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18911 (overlay-put ov 'display img)
18912 (overlay-put ov 'face 'default)
18913 (overlay-put ov 'org-image-overlay t)
18914 (overlay-put ov 'modification-hooks
18915 (list 'org-display-inline-remove-overlay))
18916 (push ov org-inline-image-overlays))))))))))
18918 (define-obsolete-function-alias
18919 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18921 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18922 "Remove inline-display overlay if a corresponding region is modified."
18923 (let ((inhibit-modification-hooks t))
18924 (when (and ov after)
18925 (delete ov org-inline-image-overlays)
18926 (delete-overlay ov))))
18928 (defun org-remove-inline-images ()
18929 "Remove inline display of images."
18930 (interactive)
18931 (mapc 'delete-overlay org-inline-image-overlays)
18932 (setq org-inline-image-overlays nil))
18934 ;;;; Key bindings
18936 ;; Outline functions from `outline-mode-prefix-map'
18937 ;; that can be remapped in Org:
18938 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18939 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18940 (define-key org-mode-map [remap outline-forward-same-level]
18941 'org-forward-heading-same-level)
18942 (define-key org-mode-map [remap outline-backward-same-level]
18943 'org-backward-heading-same-level)
18944 (define-key org-mode-map [remap show-branches]
18945 'org-kill-note-or-show-branches)
18946 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18947 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18948 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18950 ;; Outline functions from `outline-mode-prefix-map' that can not
18951 ;; be remapped in Org:
18953 ;; - the column "key binding" shows whether the Outline function is still
18954 ;; available in Org mode on the same key that it has been bound to in
18955 ;; Outline mode:
18956 ;; - "overridden": key used for a different functionality in Org mode
18957 ;; - else: key still bound to the same Outline function in Org mode
18959 ;; | Outline function | key binding | Org replacement |
18960 ;; |------------------------------------+-------------+-----------------------|
18961 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18962 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18963 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18964 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18965 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18966 ;; | `show-entry' | overridden | no replacement |
18967 ;; | `show-children' | `C-c C-i' | visibility cycling |
18968 ;; | `show-branches' | `C-c C-k' | still same function |
18969 ;; | `show-subtree' | overridden | visibility cycling |
18970 ;; | `show-all' | overridden | no replacement |
18971 ;; | `hide-subtree' | overridden | visibility cycling |
18972 ;; | `hide-body' | overridden | no replacement |
18973 ;; | `hide-entry' | overridden | visibility cycling |
18974 ;; | `hide-leaves' | overridden | no replacement |
18975 ;; | `hide-sublevels' | overridden | no replacement |
18976 ;; | `hide-other' | overridden | no replacement |
18978 ;; Make `C-c C-x' a prefix key
18979 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18981 ;; TAB key with modifiers
18982 (org-defkey org-mode-map "\C-i" 'org-cycle)
18983 (org-defkey org-mode-map [(tab)] 'org-cycle)
18984 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18985 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18986 ;; The following line is necessary under Suse GNU/Linux
18987 (unless (featurep 'xemacs)
18988 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18989 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18990 (define-key org-mode-map [backtab] 'org-shifttab)
18992 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18993 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18994 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18996 ;; Cursor keys with modifiers
18997 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18998 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18999 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19000 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19002 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19003 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19004 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19005 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19007 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19008 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19009 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19010 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19012 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19013 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19014 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19015 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19017 ;; Babel keys
19018 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19019 (mapc (lambda (pair)
19020 (define-key org-babel-map (car pair) (cdr pair)))
19021 org-babel-key-bindings)
19023 ;;; Extra keys for tty access.
19024 ;; We only set them when really needed because otherwise the
19025 ;; menus don't show the simple keys
19027 (when (or org-use-extra-keys
19028 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19029 (not window-system))
19030 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19031 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19032 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19033 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19034 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19035 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19036 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19037 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19038 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19039 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19040 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19041 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19042 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19043 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19044 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19045 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19046 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19047 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19048 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19049 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19050 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19051 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19052 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19053 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19054 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19055 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19056 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19057 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19059 ;; All the other keys
19061 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19062 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19063 (if (boundp 'narrow-map)
19064 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19065 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19066 (if (boundp 'narrow-map)
19067 (org-defkey narrow-map "b" 'org-narrow-to-block)
19068 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19069 (if (boundp 'narrow-map)
19070 (org-defkey narrow-map "e" 'org-narrow-to-element)
19071 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19072 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19073 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19074 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19075 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19076 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19077 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19078 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19079 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19080 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19081 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19082 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19083 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19084 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19085 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19086 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19087 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19088 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19089 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19090 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19091 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19092 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19093 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19094 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19095 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19096 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19097 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19098 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19099 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19100 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19101 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19102 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19103 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19104 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19105 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19106 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19107 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19108 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19109 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19110 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19111 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19112 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19113 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19114 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19115 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19116 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19117 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19118 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19119 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19120 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19121 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19122 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19123 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19124 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19125 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19126 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19127 (org-defkey org-mode-map "\C-c^" 'org-sort)
19128 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19129 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19130 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19131 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19132 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19133 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19134 (org-defkey org-mode-map "\C-m" 'org-return)
19135 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19136 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19137 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19138 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19139 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19140 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19141 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19142 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19143 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19144 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19145 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19146 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19147 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19148 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19149 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19150 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19151 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19152 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19153 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19154 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19155 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19156 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19157 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19159 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19160 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19161 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19163 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19164 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19165 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19166 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19167 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19168 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19169 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19170 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19171 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19172 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19173 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19174 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19175 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19176 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19177 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19178 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19179 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19180 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19181 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19182 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19183 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19184 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19185 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19187 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19188 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19189 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19190 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19191 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19193 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19195 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19197 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19198 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19200 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19203 (when (featurep 'xemacs)
19204 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19207 (defconst org-speed-commands-default
19209 ("Outline Navigation")
19210 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19211 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19212 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19213 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19214 ("F" . org-next-block)
19215 ("B" . org-previous-block)
19216 ("u" . (org-speed-move-safe 'outline-up-heading))
19217 ("j" . org-goto)
19218 ("g" . (org-refile t))
19219 ("Outline Visibility")
19220 ("c" . org-cycle)
19221 ("C" . org-shifttab)
19222 (" " . org-display-outline-path)
19223 ("s" . org-narrow-to-subtree)
19224 ("=" . org-columns)
19225 ("Outline Structure Editing")
19226 ("U" . org-shiftmetaup)
19227 ("D" . org-shiftmetadown)
19228 ("r" . org-metaright)
19229 ("l" . org-metaleft)
19230 ("R" . org-shiftmetaright)
19231 ("L" . org-shiftmetaleft)
19232 ("i" . (progn (forward-char 1) (call-interactively
19233 'org-insert-heading-respect-content)))
19234 ("^" . org-sort)
19235 ("w" . org-refile)
19236 ("a" . org-archive-subtree-default-with-confirmation)
19237 ("@" . org-mark-subtree)
19238 ("#" . org-toggle-comment)
19239 ("Clock Commands")
19240 ("I" . org-clock-in)
19241 ("O" . org-clock-out)
19242 ("Meta Data Editing")
19243 ("t" . org-todo)
19244 ("," . (org-priority))
19245 ("0" . (org-priority ?\ ))
19246 ("1" . (org-priority ?A))
19247 ("2" . (org-priority ?B))
19248 ("3" . (org-priority ?C))
19249 (":" . org-set-tags-command)
19250 ("e" . org-set-effort)
19251 ("E" . org-inc-effort)
19252 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19253 (org-entry-put (point) "APPT_WARNTIME" m)))
19254 ("Agenda Views etc")
19255 ("v" . org-agenda)
19256 ("/" . org-sparse-tree)
19257 ("Misc")
19258 ("o" . org-open-at-point)
19259 ("?" . org-speed-command-help)
19260 ("<" . (org-agenda-set-restriction-lock 'subtree))
19261 (">" . (org-agenda-remove-restriction-lock))
19263 "The default speed commands.")
19265 (defun org-print-speed-command (e)
19266 (if (> (length (car e)) 1)
19267 (progn
19268 (princ "\n")
19269 (princ (car e))
19270 (princ "\n")
19271 (princ (make-string (length (car e)) ?-))
19272 (princ "\n"))
19273 (princ (car e))
19274 (princ " ")
19275 (if (symbolp (cdr e))
19276 (princ (symbol-name (cdr e)))
19277 (prin1 (cdr e)))
19278 (princ "\n")))
19280 (defun org-speed-command-help ()
19281 "Show the available speed commands."
19282 (interactive)
19283 (if (not org-use-speed-commands)
19284 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19285 (with-output-to-temp-buffer "*Help*"
19286 (princ "User-defined Speed commands\n===========================\n")
19287 (mapc 'org-print-speed-command org-speed-commands-user)
19288 (princ "\n")
19289 (princ "Built-in Speed commands\n=======================\n")
19290 (mapc 'org-print-speed-command org-speed-commands-default))
19291 (with-current-buffer "*Help*"
19292 (setq truncate-lines t))))
19294 (defun org-speed-move-safe (cmd)
19295 "Execute CMD, but make sure that the cursor always ends up in a headline.
19296 If not, return to the original position and throw an error."
19297 (interactive)
19298 (let ((pos (point)))
19299 (call-interactively cmd)
19300 (unless (and (bolp) (org-at-heading-p))
19301 (goto-char pos)
19302 (error "Boundary reached while executing %s" cmd))))
19304 (defvar org-self-insert-command-undo-counter 0)
19306 (defvar org-table-auto-blank-field) ; defined in org-table.el
19307 (defvar org-speed-command nil)
19309 (define-obsolete-function-alias
19310 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19312 (defun org-speed-command-activate (keys)
19313 "Hook for activating single-letter speed commands.
19314 `org-speed-commands-default' specifies a minimal command set.
19315 Use `org-speed-commands-user' for further customization."
19316 (when (or (and (bolp) (looking-at org-outline-regexp))
19317 (and (functionp org-use-speed-commands)
19318 (funcall org-use-speed-commands)))
19319 (cdr (assoc keys (append org-speed-commands-user
19320 org-speed-commands-default)))))
19322 (define-obsolete-function-alias
19323 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19325 (defun org-babel-speed-command-activate (keys)
19326 "Hook for activating single-letter code block commands."
19327 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19328 (cdr (assoc keys org-babel-key-bindings))))
19330 (defcustom org-speed-command-hook
19331 '(org-speed-command-default-hook org-babel-speed-command-hook)
19332 "Hook for activating speed commands at strategic locations.
19333 Hook functions are called in sequence until a valid handler is
19334 found.
19336 Each hook takes a single argument, a user-pressed command key
19337 which is also a `self-insert-command' from the global map.
19339 Within the hook, examine the cursor position and the command key
19340 and return nil or a valid handler as appropriate. Handler could
19341 be one of an interactive command, a function, or a form.
19343 Set `org-use-speed-commands' to non-nil value to enable this
19344 hook. The default setting is `org-speed-command-activate'."
19345 :group 'org-structure
19346 :version "24.1"
19347 :type 'hook)
19349 (defun org-self-insert-command (N)
19350 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19351 If the cursor is in a table looking at whitespace, the whitespace is
19352 overwritten, and the table is not marked as requiring realignment."
19353 (interactive "p")
19354 (org-check-before-invisible-edit 'insert)
19355 (cond
19356 ((and org-use-speed-commands
19357 (setq org-speed-command
19358 (run-hook-with-args-until-success
19359 'org-speed-command-hook (this-command-keys))))
19360 (cond
19361 ((commandp org-speed-command)
19362 (setq this-command org-speed-command)
19363 (call-interactively org-speed-command))
19364 ((functionp org-speed-command)
19365 (funcall org-speed-command))
19366 ((and org-speed-command (listp org-speed-command))
19367 (eval org-speed-command))
19368 (t (let (org-use-speed-commands)
19369 (call-interactively 'org-self-insert-command)))))
19370 ((and
19371 (org-table-p)
19372 (progn
19373 ;; check if we blank the field, and if that triggers align
19374 (and (featurep 'org-table) org-table-auto-blank-field
19375 (member last-command
19376 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19377 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19378 ;; got extra space, this field does not determine column width
19379 (let (org-table-may-need-update) (org-table-blank-field))
19380 ;; no extra space, this field may determine column width
19381 (org-table-blank-field)))
19383 (eq N 1)
19384 (looking-at "[^|\n]* |"))
19385 (let (org-table-may-need-update)
19386 (goto-char (1- (match-end 0)))
19387 (backward-delete-char 1)
19388 (goto-char (match-beginning 0))
19389 (self-insert-command N)))
19391 (setq org-table-may-need-update t)
19392 (self-insert-command N)
19393 (org-fix-tags-on-the-fly)
19394 (if org-self-insert-cluster-for-undo
19395 (if (not (eq last-command 'org-self-insert-command))
19396 (setq org-self-insert-command-undo-counter 1)
19397 (if (>= org-self-insert-command-undo-counter 20)
19398 (setq org-self-insert-command-undo-counter 1)
19399 (and (> org-self-insert-command-undo-counter 0)
19400 buffer-undo-list (listp buffer-undo-list)
19401 (not (cadr buffer-undo-list)) ; remove nil entry
19402 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19403 (setq org-self-insert-command-undo-counter
19404 (1+ org-self-insert-command-undo-counter))))))))
19406 (defun org-check-before-invisible-edit (kind)
19407 "Check is editing if kind KIND would be dangerous with invisible text around.
19408 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19409 ;; First, try to get out of here as quickly as possible, to reduce overhead
19410 (if (and org-catch-invisible-edits
19411 (or (not (boundp 'visible-mode)) (not visible-mode))
19412 (or (get-char-property (point) 'invisible)
19413 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19414 ;; OK, we need to take a closer look
19415 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19416 (invisible-before-point (if (bobp) nil (get-char-property
19417 (1- (point)) 'invisible)))
19418 (border-and-ok-direction
19420 ;; Check if we are acting predictably before invisible text
19421 (and invisible-at-point (not invisible-before-point)
19422 (memq kind '(insert delete-backward)))
19423 ;; Check if we are acting predictably after invisible text
19424 ;; This works not well, and I have turned it off. It seems
19425 ;; better to always show and stop after invisible text.
19426 ;; (and (not invisible-at-point) invisible-before-point
19427 ;; (memq kind '(insert delete)))
19429 (when (or (memq invisible-at-point '(outline org-hide-block t))
19430 (memq invisible-before-point '(outline org-hide-block t)))
19431 (if (eq org-catch-invisible-edits 'error)
19432 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19433 (if (and org-custom-properties-overlays
19434 (y-or-n-p "Display invisible properties in this buffer? "))
19435 (org-toggle-custom-properties-visibility)
19436 ;; Make the area visible
19437 (save-excursion
19438 (if invisible-before-point
19439 (goto-char (previous-single-char-property-change
19440 (point) 'invisible)))
19441 (org-cycle))
19442 (cond
19443 ((eq org-catch-invisible-edits 'show)
19444 ;; That's it, we do the edit after showing
19445 (message
19446 "Unfolding invisible region around point before editing")
19447 (sit-for 1))
19448 ((and (eq org-catch-invisible-edits 'smart)
19449 border-and-ok-direction)
19450 (message "Unfolding invisible region around point before editing"))
19452 ;; Don't do the edit, make the user repeat it in full visibility
19453 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19455 (defun org-fix-tags-on-the-fly ()
19456 (when (and (equal (char-after (point-at-bol)) ?*)
19457 (org-at-heading-p))
19458 (org-align-tags-here org-tags-column)))
19460 (defun org-delete-backward-char (N)
19461 "Like `delete-backward-char', insert whitespace at field end in tables.
19462 When deleting backwards, in tables this function will insert whitespace in
19463 front of the next \"|\" separator, to keep the table aligned. The table will
19464 still be marked for re-alignment if the field did fill the entire column,
19465 because, in this case the deletion might narrow the column."
19466 (interactive "p")
19467 (save-match-data
19468 (org-check-before-invisible-edit 'delete-backward)
19469 (if (and (org-table-p)
19470 (eq N 1)
19471 (string-match "|" (buffer-substring (point-at-bol) (point)))
19472 (looking-at ".*?|"))
19473 (let ((pos (point))
19474 (noalign (looking-at "[^|\n\r]* |"))
19475 (c org-table-may-need-update))
19476 (backward-delete-char N)
19477 (if (not overwrite-mode)
19478 (progn
19479 (skip-chars-forward "^|")
19480 (insert " ")
19481 (goto-char (1- pos))))
19482 ;; noalign: if there were two spaces at the end, this field
19483 ;; does not determine the width of the column.
19484 (if noalign (setq org-table-may-need-update c)))
19485 (backward-delete-char N)
19486 (org-fix-tags-on-the-fly))))
19488 (defun org-delete-char (N)
19489 "Like `delete-char', but insert whitespace at field end in tables.
19490 When deleting characters, in tables this function will insert whitespace in
19491 front of the next \"|\" separator, to keep the table aligned. The table will
19492 still be marked for re-alignment if the field did fill the entire column,
19493 because, in this case the deletion might narrow the column."
19494 (interactive "p")
19495 (save-match-data
19496 (org-check-before-invisible-edit 'delete)
19497 (if (and (org-table-p)
19498 (not (bolp))
19499 (not (= (char-after) ?|))
19500 (eq N 1))
19501 (if (looking-at ".*?|")
19502 (let ((pos (point))
19503 (noalign (looking-at "[^|\n\r]* |"))
19504 (c org-table-may-need-update))
19505 (replace-match
19506 (concat (substring (match-string 0) 1 -1) " |") nil t)
19507 (goto-char pos)
19508 ;; noalign: if there were two spaces at the end, this field
19509 ;; does not determine the width of the column.
19510 (if noalign (setq org-table-may-need-update c)))
19511 (delete-char N))
19512 (delete-char N)
19513 (org-fix-tags-on-the-fly))))
19515 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19516 (put 'org-self-insert-command 'delete-selection t)
19517 (put 'orgtbl-self-insert-command 'delete-selection t)
19518 (put 'org-delete-char 'delete-selection 'supersede)
19519 (put 'org-delete-backward-char 'delete-selection 'supersede)
19520 (put 'org-yank 'delete-selection 'yank)
19522 ;; Make `flyspell-mode' delay after some commands
19523 (put 'org-self-insert-command 'flyspell-delayed t)
19524 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19525 (put 'org-delete-char 'flyspell-delayed t)
19526 (put 'org-delete-backward-char 'flyspell-delayed t)
19528 ;; Make pabbrev-mode expand after org-mode commands
19529 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19530 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19532 ;; How to do this: Measure non-white length of current string
19533 ;; If equal to column width, we should realign.
19535 (defun org-remap (map &rest commands)
19536 "In MAP, remap the functions given in COMMANDS.
19537 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19538 (let (new old)
19539 (while commands
19540 (setq old (pop commands) new (pop commands))
19541 (if (fboundp 'command-remapping)
19542 (org-defkey map (vector 'remap old) new)
19543 (substitute-key-definition old new map global-map)))))
19545 (defun org-transpose-words ()
19546 "Transpose words for Org.
19547 This uses the `org-mode-transpose-word-syntax-table' syntax
19548 table, which interprets characters in `org-emphasis-alist' as
19549 word constituants."
19550 (interactive)
19551 (with-syntax-table org-mode-transpose-word-syntax-table
19552 (call-interactively 'transpose-words)))
19553 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19555 (when (eq org-enable-table-editor 'optimized)
19556 ;; If the user wants maximum table support, we need to hijack
19557 ;; some standard editing functions
19558 (org-remap org-mode-map
19559 'self-insert-command 'org-self-insert-command
19560 'delete-char 'org-delete-char
19561 'delete-backward-char 'org-delete-backward-char)
19562 (org-defkey org-mode-map "|" 'org-force-self-insert))
19564 (defvar org-ctrl-c-ctrl-c-hook nil
19565 "Hook for functions attaching themselves to `C-c C-c'.
19567 This can be used to add additional functionality to the C-c C-c
19568 key which executes context-dependent commands. This hook is run
19569 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19570 run after the last test.
19572 Each function will be called with no arguments. The function
19573 must check if the context is appropriate for it to act. If yes,
19574 it should do its thing and then return a non-nil value. If the
19575 context is wrong, just do nothing and return nil.")
19577 (defvar org-ctrl-c-ctrl-c-final-hook nil
19578 "Hook for functions attaching themselves to `C-c C-c'.
19580 This can be used to add additional functionality to the C-c C-c
19581 key which executes context-dependent commands. This hook is run
19582 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19583 before the first test.
19585 Each function will be called with no arguments. The function
19586 must check if the context is appropriate for it to act. If yes,
19587 it should do its thing and then return a non-nil value. If the
19588 context is wrong, just do nothing and return nil.")
19590 (defvar org-tab-first-hook nil
19591 "Hook for functions to attach themselves to TAB.
19592 See `org-ctrl-c-ctrl-c-hook' for more information.
19593 This hook runs as the first action when TAB is pressed, even before
19594 `org-cycle' messes around with the `outline-regexp' to cater for
19595 inline tasks and plain list item folding.
19596 If any function in this hook returns t, any other actions that
19597 would have been caused by TAB (such as table field motion or visibility
19598 cycling) will not occur.")
19600 (defvar org-tab-after-check-for-table-hook nil
19601 "Hook for functions to attach themselves to TAB.
19602 See `org-ctrl-c-ctrl-c-hook' for more information.
19603 This hook runs after it has been established that the cursor is not in a
19604 table, but before checking if the cursor is in a headline or if global cycling
19605 should be done.
19606 If any function in this hook returns t, not other actions like visibility
19607 cycling will be done.")
19609 (defvar org-tab-after-check-for-cycling-hook nil
19610 "Hook for functions to attach themselves to TAB.
19611 See `org-ctrl-c-ctrl-c-hook' for more information.
19612 This hook runs after it has been established that not table field motion and
19613 not visibility should be done because of current context. This is probably
19614 the place where a package like yasnippets can hook in.")
19616 (defvar org-tab-before-tab-emulation-hook nil
19617 "Hook for functions to attach themselves to TAB.
19618 See `org-ctrl-c-ctrl-c-hook' for more information.
19619 This hook runs after every other options for TAB have been exhausted, but
19620 before indentation and \t insertion takes place.")
19622 (defvar org-metaleft-hook nil
19623 "Hook for functions attaching themselves to `M-left'.
19624 See `org-ctrl-c-ctrl-c-hook' for more information.")
19625 (defvar org-metaright-hook nil
19626 "Hook for functions attaching themselves to `M-right'.
19627 See `org-ctrl-c-ctrl-c-hook' for more information.")
19628 (defvar org-metaup-hook nil
19629 "Hook for functions attaching themselves to `M-up'.
19630 See `org-ctrl-c-ctrl-c-hook' for more information.")
19631 (defvar org-metadown-hook nil
19632 "Hook for functions attaching themselves to `M-down'.
19633 See `org-ctrl-c-ctrl-c-hook' for more information.")
19634 (defvar org-shiftmetaleft-hook nil
19635 "Hook for functions attaching themselves to `M-S-left'.
19636 See `org-ctrl-c-ctrl-c-hook' for more information.")
19637 (defvar org-shiftmetaright-hook nil
19638 "Hook for functions attaching themselves to `M-S-right'.
19639 See `org-ctrl-c-ctrl-c-hook' for more information.")
19640 (defvar org-shiftmetaup-hook nil
19641 "Hook for functions attaching themselves to `M-S-up'.
19642 See `org-ctrl-c-ctrl-c-hook' for more information.")
19643 (defvar org-shiftmetadown-hook nil
19644 "Hook for functions attaching themselves to `M-S-down'.
19645 See `org-ctrl-c-ctrl-c-hook' for more information.")
19646 (defvar org-metareturn-hook nil
19647 "Hook for functions attaching themselves to `M-RET'.
19648 See `org-ctrl-c-ctrl-c-hook' for more information.")
19649 (defvar org-shiftup-hook nil
19650 "Hook for functions attaching themselves to `S-up'.
19651 See `org-ctrl-c-ctrl-c-hook' for more information.")
19652 (defvar org-shiftup-final-hook nil
19653 "Hook for functions attaching themselves to `S-up'.
19654 This one runs after all other options except shift-select have been excluded.
19655 See `org-ctrl-c-ctrl-c-hook' for more information.")
19656 (defvar org-shiftdown-hook nil
19657 "Hook for functions attaching themselves to `S-down'.
19658 See `org-ctrl-c-ctrl-c-hook' for more information.")
19659 (defvar org-shiftdown-final-hook nil
19660 "Hook for functions attaching themselves to `S-down'.
19661 This one runs after all other options except shift-select have been excluded.
19662 See `org-ctrl-c-ctrl-c-hook' for more information.")
19663 (defvar org-shiftleft-hook nil
19664 "Hook for functions attaching themselves to `S-left'.
19665 See `org-ctrl-c-ctrl-c-hook' for more information.")
19666 (defvar org-shiftleft-final-hook nil
19667 "Hook for functions attaching themselves to `S-left'.
19668 This one runs after all other options except shift-select have been excluded.
19669 See `org-ctrl-c-ctrl-c-hook' for more information.")
19670 (defvar org-shiftright-hook nil
19671 "Hook for functions attaching themselves to `S-right'.
19672 See `org-ctrl-c-ctrl-c-hook' for more information.")
19673 (defvar org-shiftright-final-hook nil
19674 "Hook for functions attaching themselves to `S-right'.
19675 This one runs after all other options except shift-select have been excluded.
19676 See `org-ctrl-c-ctrl-c-hook' for more information.")
19678 (defun org-modifier-cursor-error ()
19679 "Throw an error, a modified cursor command was applied in wrong context."
19680 (user-error "This command is active in special context like tables, headlines or items"))
19682 (defun org-shiftselect-error ()
19683 "Throw an error because Shift-Cursor command was applied in wrong context."
19684 (if (and (boundp 'shift-select-mode) shift-select-mode)
19685 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19686 (user-error "This command works only in special context like headlines or timestamps")))
19688 (defun org-call-for-shift-select (cmd)
19689 (let ((this-command-keys-shift-translated t))
19690 (call-interactively cmd)))
19692 (defun org-shifttab (&optional arg)
19693 "Global visibility cycling or move to previous table field.
19694 Call `org-table-previous-field' within a table.
19695 When ARG is nil, cycle globally through visibility states.
19696 When ARG is a numeric prefix, show contents of this level."
19697 (interactive "P")
19698 (cond
19699 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19700 ((integerp arg)
19701 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19702 (message "Content view to level: %d" arg)
19703 (org-content (prefix-numeric-value arg2))
19704 (org-cycle-show-empty-lines t)
19705 (setq org-cycle-global-status 'overview)))
19706 (t (call-interactively 'org-global-cycle))))
19708 (defun org-shiftmetaleft ()
19709 "Promote subtree or delete table column.
19710 Calls `org-promote-subtree', `org-outdent-item-tree', or
19711 `org-table-delete-column', depending on context. See the
19712 individual commands for more information."
19713 (interactive)
19714 (cond
19715 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19716 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19717 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19718 ((if (not (org-region-active-p)) (org-at-item-p)
19719 (save-excursion (goto-char (region-beginning))
19720 (org-at-item-p)))
19721 (call-interactively 'org-outdent-item-tree))
19722 (t (org-modifier-cursor-error))))
19724 (defun org-shiftmetaright ()
19725 "Demote subtree or insert table column.
19726 Calls `org-demote-subtree', `org-indent-item-tree', or
19727 `org-table-insert-column', depending on context. See the
19728 individual commands for more information."
19729 (interactive)
19730 (cond
19731 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19732 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19733 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19734 ((if (not (org-region-active-p)) (org-at-item-p)
19735 (save-excursion (goto-char (region-beginning))
19736 (org-at-item-p)))
19737 (call-interactively 'org-indent-item-tree))
19738 (t (org-modifier-cursor-error))))
19740 (defun org-shiftmetaup (&optional arg)
19741 "Move subtree up or kill table row.
19742 Calls `org-move-subtree-up' or `org-table-kill-row' or
19743 `org-move-item-up' or `org-timestamp-up', depending on context.
19744 See the individual commands for more information."
19745 (interactive "P")
19746 (cond
19747 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19748 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19749 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19750 ((org-at-item-p) (call-interactively 'org-move-item-up))
19751 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19752 (call-interactively 'org-timestamp-up)))
19753 (t (call-interactively 'org-drag-line-backward))))
19755 (defun org-shiftmetadown (&optional arg)
19756 "Move subtree down or insert table row.
19757 Calls `org-move-subtree-down' or `org-table-insert-row' or
19758 `org-move-item-down' or `org-timestamp-up', depending on context.
19759 See the individual commands for more information."
19760 (interactive "P")
19761 (cond
19762 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19763 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19764 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19765 ((org-at-item-p) (call-interactively 'org-move-item-down))
19766 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19767 (call-interactively 'org-timestamp-down)))
19768 (t (call-interactively 'org-drag-line-forward))))
19770 (defsubst org-hidden-tree-error ()
19771 (user-error
19772 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19774 (defun org-metaleft (&optional arg)
19775 "Promote heading or move table column to left.
19776 Calls `org-do-promote' or `org-table-move-column', depending on context.
19777 With no specific context, calls the Emacs default `backward-word'.
19778 See the individual commands for more information."
19779 (interactive "P")
19780 (cond
19781 ((run-hook-with-args-until-success 'org-metaleft-hook))
19782 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19783 ((org-with-limited-levels
19784 (or (org-at-heading-p)
19785 (and (org-region-active-p)
19786 (save-excursion
19787 (goto-char (region-beginning))
19788 (org-at-heading-p)))))
19789 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19790 (call-interactively 'org-do-promote))
19791 ;; At an inline task.
19792 ((org-at-heading-p)
19793 (call-interactively 'org-inlinetask-promote))
19794 ((or (org-at-item-p)
19795 (and (org-region-active-p)
19796 (save-excursion
19797 (goto-char (region-beginning))
19798 (org-at-item-p))))
19799 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19800 (call-interactively 'org-outdent-item))
19801 (t (call-interactively 'backward-word))))
19803 (defun org-metaright (&optional arg)
19804 "Demote a subtree, a list item or move table column to right.
19805 In front of a drawer or a block keyword, indent it correctly.
19806 With no specific context, calls the Emacs default `forward-word'.
19807 See the individual commands for more information."
19808 (interactive "P")
19809 (cond
19810 ((run-hook-with-args-until-success 'org-metaright-hook))
19811 ((org-at-table-p) (call-interactively 'org-table-move-column))
19812 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19813 ((org-at-block-p) (call-interactively 'org-indent-block))
19814 ((org-with-limited-levels
19815 (or (org-at-heading-p)
19816 (and (org-region-active-p)
19817 (save-excursion
19818 (goto-char (region-beginning))
19819 (org-at-heading-p)))))
19820 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19821 (call-interactively 'org-do-demote))
19822 ;; At an inline task.
19823 ((org-at-heading-p)
19824 (call-interactively 'org-inlinetask-demote))
19825 ((or (org-at-item-p)
19826 (and (org-region-active-p)
19827 (save-excursion
19828 (goto-char (region-beginning))
19829 (org-at-item-p))))
19830 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19831 (call-interactively 'org-indent-item))
19832 (t (call-interactively 'forward-word))))
19834 (defun org-check-for-hidden (what)
19835 "Check if there are hidden headlines/items in the current visual line.
19836 WHAT can be either `headlines' or `items'. If the current line is
19837 an outline or item heading and it has a folded subtree below it,
19838 this function returns t, nil otherwise."
19839 (let ((re (cond
19840 ((eq what 'headlines) org-outline-regexp-bol)
19841 ((eq what 'items) (org-item-beginning-re))
19842 (t (error "This should not happen"))))
19843 beg end)
19844 (save-excursion
19845 (catch 'exit
19846 (unless (org-region-active-p)
19847 (setq beg (point-at-bol))
19848 (beginning-of-line 2)
19849 (while (and (not (eobp)) ;; this is like `next-line'
19850 (get-char-property (1- (point)) 'invisible))
19851 (beginning-of-line 2))
19852 (setq end (point))
19853 (goto-char beg)
19854 (goto-char (point-at-eol))
19855 (setq end (max end (point)))
19856 (while (re-search-forward re end t)
19857 (if (get-char-property (match-beginning 0) 'invisible)
19858 (throw 'exit t))))
19859 nil))))
19861 (defun org-metaup (&optional arg)
19862 "Move subtree up or move table row up.
19863 Calls `org-move-subtree-up' or `org-table-move-row' or
19864 `org-move-item-up', depending on context. See the individual commands
19865 for more information."
19866 (interactive "P")
19867 (cond
19868 ((run-hook-with-args-until-success 'org-metaup-hook))
19869 ((org-region-active-p)
19870 (let* ((a (min (region-beginning) (region-end)))
19871 (b (1- (max (region-beginning) (region-end))))
19872 (c (save-excursion (goto-char a)
19873 (move-beginning-of-line 0)))
19874 (d (save-excursion (goto-char a)
19875 (move-end-of-line 0) (point))))
19876 (transpose-regions a b c d)
19877 (goto-char c)))
19878 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19879 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19880 ((org-at-item-p) (call-interactively 'org-move-item-up))
19881 (t (org-drag-element-backward))))
19883 (defun org-metadown (&optional arg)
19884 "Move subtree down or move table row down.
19885 Calls `org-move-subtree-down' or `org-table-move-row' or
19886 `org-move-item-down', depending on context. See the individual
19887 commands for more information."
19888 (interactive "P")
19889 (cond
19890 ((run-hook-with-args-until-success 'org-metadown-hook))
19891 ((org-region-active-p)
19892 (let* ((a (min (region-beginning) (region-end)))
19893 (b (max (region-beginning) (region-end)))
19894 (c (save-excursion (goto-char b)
19895 (move-beginning-of-line 1)))
19896 (d (save-excursion (goto-char b)
19897 (move-end-of-line 1) (1+ (point)))))
19898 (transpose-regions a b c d)
19899 (goto-char d)))
19900 ((org-at-table-p) (call-interactively 'org-table-move-row))
19901 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19902 ((org-at-item-p) (call-interactively 'org-move-item-down))
19903 (t (org-drag-element-forward))))
19905 (defun org-shiftup (&optional arg)
19906 "Increase item in timestamp or increase priority of current headline.
19907 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19908 depending on context. See the individual commands for more information."
19909 (interactive "P")
19910 (cond
19911 ((run-hook-with-args-until-success 'org-shiftup-hook))
19912 ((and org-support-shift-select (org-region-active-p))
19913 (org-call-for-shift-select 'previous-line))
19914 ((org-at-timestamp-p t)
19915 (call-interactively (if org-edit-timestamp-down-means-later
19916 'org-timestamp-down 'org-timestamp-up)))
19917 ((and (not (eq org-support-shift-select 'always))
19918 org-enable-priority-commands
19919 (org-at-heading-p))
19920 (call-interactively 'org-priority-up))
19921 ((and (not org-support-shift-select) (org-at-item-p))
19922 (call-interactively 'org-previous-item))
19923 ((org-clocktable-try-shift 'up arg))
19924 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19925 (org-support-shift-select
19926 (org-call-for-shift-select 'previous-line))
19927 (t (org-shiftselect-error))))
19929 (defun org-shiftdown (&optional arg)
19930 "Decrease item in timestamp or decrease priority of current headline.
19931 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19932 depending on context. See the individual commands for more information."
19933 (interactive "P")
19934 (cond
19935 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19936 ((and org-support-shift-select (org-region-active-p))
19937 (org-call-for-shift-select 'next-line))
19938 ((org-at-timestamp-p t)
19939 (call-interactively (if org-edit-timestamp-down-means-later
19940 'org-timestamp-up 'org-timestamp-down)))
19941 ((and (not (eq org-support-shift-select 'always))
19942 org-enable-priority-commands
19943 (org-at-heading-p))
19944 (call-interactively 'org-priority-down))
19945 ((and (not org-support-shift-select) (org-at-item-p))
19946 (call-interactively 'org-next-item))
19947 ((org-clocktable-try-shift 'down arg))
19948 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19949 (org-support-shift-select
19950 (org-call-for-shift-select 'next-line))
19951 (t (org-shiftselect-error))))
19953 (defun org-shiftright (&optional arg)
19954 "Cycle the thing at point or in the current line, depending on context.
19955 Depending on context, this does one of the following:
19957 - switch a timestamp at point one day into the future
19958 - on a headline, switch to the next TODO keyword.
19959 - on an item, switch entire list to the next bullet type
19960 - on a property line, switch to the next allowed value
19961 - on a clocktable definition line, move time block into the future"
19962 (interactive "P")
19963 (cond
19964 ((run-hook-with-args-until-success 'org-shiftright-hook))
19965 ((and org-support-shift-select (org-region-active-p))
19966 (org-call-for-shift-select 'forward-char))
19967 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19968 ((and (not (eq org-support-shift-select 'always))
19969 (org-at-heading-p))
19970 (let ((org-inhibit-logging
19971 (not org-treat-S-cursor-todo-selection-as-state-change))
19972 (org-inhibit-blocking
19973 (not org-treat-S-cursor-todo-selection-as-state-change)))
19974 (org-call-with-arg 'org-todo 'right)))
19975 ((or (and org-support-shift-select
19976 (not (eq org-support-shift-select 'always))
19977 (org-at-item-bullet-p))
19978 (and (not org-support-shift-select) (org-at-item-p)))
19979 (org-call-with-arg 'org-cycle-list-bullet nil))
19980 ((and (not (eq org-support-shift-select 'always))
19981 (org-at-property-p))
19982 (call-interactively 'org-property-next-allowed-value))
19983 ((org-clocktable-try-shift 'right arg))
19984 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19985 (org-support-shift-select
19986 (org-call-for-shift-select 'forward-char))
19987 (t (org-shiftselect-error))))
19989 (defun org-shiftleft (&optional arg)
19990 "Cycle the thing at point or in the current line, depending on context.
19991 Depending on context, this does one of the following:
19993 - switch a timestamp at point one day into the past
19994 - on a headline, switch to the previous TODO keyword.
19995 - on an item, switch entire list to the previous bullet type
19996 - on a property line, switch to the previous allowed value
19997 - on a clocktable definition line, move time block into the past"
19998 (interactive "P")
19999 (cond
20000 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20001 ((and org-support-shift-select (org-region-active-p))
20002 (org-call-for-shift-select 'backward-char))
20003 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20004 ((and (not (eq org-support-shift-select 'always))
20005 (org-at-heading-p))
20006 (let ((org-inhibit-logging
20007 (not org-treat-S-cursor-todo-selection-as-state-change))
20008 (org-inhibit-blocking
20009 (not org-treat-S-cursor-todo-selection-as-state-change)))
20010 (org-call-with-arg 'org-todo 'left)))
20011 ((or (and org-support-shift-select
20012 (not (eq org-support-shift-select 'always))
20013 (org-at-item-bullet-p))
20014 (and (not org-support-shift-select) (org-at-item-p)))
20015 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20016 ((and (not (eq org-support-shift-select 'always))
20017 (org-at-property-p))
20018 (call-interactively 'org-property-previous-allowed-value))
20019 ((org-clocktable-try-shift 'left arg))
20020 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20021 (org-support-shift-select
20022 (org-call-for-shift-select 'backward-char))
20023 (t (org-shiftselect-error))))
20025 (defun org-shiftcontrolright ()
20026 "Switch to next TODO set."
20027 (interactive)
20028 (cond
20029 ((and org-support-shift-select (org-region-active-p))
20030 (org-call-for-shift-select 'forward-word))
20031 ((and (not (eq org-support-shift-select 'always))
20032 (org-at-heading-p))
20033 (org-call-with-arg 'org-todo 'nextset))
20034 (org-support-shift-select
20035 (org-call-for-shift-select 'forward-word))
20036 (t (org-shiftselect-error))))
20038 (defun org-shiftcontrolleft ()
20039 "Switch to previous TODO set."
20040 (interactive)
20041 (cond
20042 ((and org-support-shift-select (org-region-active-p))
20043 (org-call-for-shift-select 'backward-word))
20044 ((and (not (eq org-support-shift-select 'always))
20045 (org-at-heading-p))
20046 (org-call-with-arg 'org-todo 'previousset))
20047 (org-support-shift-select
20048 (org-call-for-shift-select 'backward-word))
20049 (t (org-shiftselect-error))))
20051 (defun org-shiftcontrolup (&optional n)
20052 "Change timestamps synchronously up in CLOCK log lines.
20053 Optional argument N tells to change by that many units."
20054 (interactive "P")
20055 (cond ((and (not org-support-shift-select)
20056 (org-at-clock-log-p)
20057 (org-at-timestamp-p t))
20058 (org-clock-timestamps-up n))
20059 (t (org-shiftselect-error))))
20061 (defun org-shiftcontroldown (&optional n)
20062 "Change timestamps synchronously down in CLOCK log lines.
20063 Optional argument N tells to change by that many units."
20064 (interactive "P")
20065 (cond ((and (not org-support-shift-select)
20066 (org-at-clock-log-p)
20067 (org-at-timestamp-p t))
20068 (org-clock-timestamps-down n))
20069 (t (org-shiftselect-error))))
20071 (defun org-ctrl-c-ret ()
20072 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20073 (interactive)
20074 (cond
20075 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20076 (t (call-interactively 'org-insert-heading))))
20078 (defun org-find-visible ()
20079 (let ((s (point)))
20080 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20081 (get-char-property s 'invisible)))
20083 (defun org-find-invisible ()
20084 (let ((s (point)))
20085 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20086 (not (get-char-property s 'invisible))))
20089 (defun org-copy-visible (beg end)
20090 "Copy the visible parts of the region."
20091 (interactive "r")
20092 (let (snippets s)
20093 (save-excursion
20094 (save-restriction
20095 (narrow-to-region beg end)
20096 (setq s (goto-char (point-min)))
20097 (while (not (= (point) (point-max)))
20098 (goto-char (org-find-invisible))
20099 (push (buffer-substring s (point)) snippets)
20100 (setq s (goto-char (org-find-visible))))))
20101 (kill-new (apply 'concat (nreverse snippets)))))
20103 (defun org-copy-special ()
20104 "Copy region in table or copy current subtree.
20105 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20106 See the individual commands for more information."
20107 (interactive)
20108 (call-interactively
20109 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20111 (defun org-cut-special ()
20112 "Cut region in table or cut current subtree.
20113 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20114 See the individual commands for more information."
20115 (interactive)
20116 (call-interactively
20117 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20119 (defun org-paste-special (arg)
20120 "Paste rectangular region into table, or past subtree relative to level.
20121 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20122 See the individual commands for more information."
20123 (interactive "P")
20124 (if (org-at-table-p)
20125 (org-table-paste-rectangle)
20126 (org-paste-subtree arg)))
20128 (defsubst org-in-fixed-width-region-p ()
20129 "Is point in a fixed-width region?"
20130 (save-match-data
20131 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20133 (defun org-edit-special (&optional arg)
20134 "Call a special editor for the element at point.
20135 When at a table, call the formula editor with `org-table-edit-formulas'.
20136 When in a source code block, call `org-edit-src-code'.
20137 When in a fixed-width region, call `org-edit-fixed-width-region'.
20138 When at an #+INCLUDE keyword, visit the included file.
20139 On a link, call `ffap' to visit the link at point.
20140 Otherwise, return a user error."
20141 (interactive "P")
20142 (let ((element (org-element-at-point)))
20143 (assert (not buffer-read-only) nil
20144 "Buffer is read-only: %s" (buffer-name))
20145 (case (org-element-type element)
20146 (src-block
20147 (if (not arg) (org-edit-src-code)
20148 (let* ((info (org-babel-get-src-block-info))
20149 (lang (nth 0 info))
20150 (params (nth 2 info))
20151 (session (cdr (assq :session params))))
20152 (if (not session) (org-edit-src-code)
20153 ;; At a src-block with a session and function called with
20154 ;; an ARG: switch to the buffer related to the inferior
20155 ;; process.
20156 (switch-to-buffer
20157 (funcall (intern (concat "org-babel-prep-session:" lang))
20158 session params))))))
20159 (keyword
20160 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20161 (find-file
20162 (org-remove-double-quotes
20163 (car (org-split-string (org-element-property :value element)))))
20164 (user-error "No special environment to edit here")))
20165 (table
20166 (if (eq (org-element-property :type element) 'table.el)
20167 (org-edit-src-code)
20168 (call-interactively 'org-table-edit-formulas)))
20169 ;; Only Org tables contain `table-row' type elements.
20170 (table-row (call-interactively 'org-table-edit-formulas))
20171 ((example-block export-block) (org-edit-src-code))
20172 (fixed-width (org-edit-fixed-width-region))
20173 (otherwise
20174 ;; No notable element at point. Though, we may be at a link,
20175 ;; which is an object. Thus, scan deeper.
20176 (if (eq (org-element-type (org-element-context element)) 'link)
20177 (call-interactively 'ffap)
20178 (user-error "No special environment to edit here"))))))
20180 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20181 (defun org-ctrl-c-ctrl-c (&optional arg)
20182 "Set tags in headline, or update according to changed information at point.
20184 This command does many different things, depending on context:
20186 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20187 this is what we do.
20189 - If the cursor is on a statistics cookie, update it.
20191 - If the cursor is in a headline, prompt for tags and insert them
20192 into the current line, aligned to `org-tags-column'. When called
20193 with prefix arg, realign all tags in the current buffer.
20195 - If the cursor is in one of the special #+KEYWORD lines, this
20196 triggers scanning the buffer for these lines and updating the
20197 information.
20199 - If the cursor is inside a table, realign the table. This command
20200 works even if the automatic table editor has been turned off.
20202 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20203 the entire table.
20205 - If the cursor is at a footnote reference or definition, jump to
20206 the corresponding definition or references, respectively.
20208 - If the cursor is a the beginning of a dynamic block, update it.
20210 - If the current buffer is a capture buffer, close note and file it.
20212 - If the cursor is on a <<<target>>>, update radio targets and
20213 corresponding links in this buffer.
20215 - If the cursor is on a numbered item in a plain list, renumber the
20216 ordered list.
20218 - If the cursor is on a checkbox, toggle it.
20220 - If the cursor is on a code block, evaluate it. The variable
20221 `org-confirm-babel-evaluate' can be used to control prompting
20222 before code block evaluation, by default every code block
20223 evaluation requires confirmation. Code block evaluation can be
20224 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20225 (interactive "P")
20226 (cond
20227 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20228 org-occur-highlights
20229 org-latex-fragment-image-overlays)
20230 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20231 (org-remove-occur-highlights)
20232 (org-remove-latex-fragment-image-overlays)
20233 (message "Temporary highlights/overlays removed from current buffer"))
20234 ((and (local-variable-p 'org-finish-function (current-buffer))
20235 (fboundp org-finish-function))
20236 (funcall org-finish-function))
20237 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20239 (let* ((context (org-element-context)) (type (org-element-type context)))
20240 ;; Test if point is within a blank line.
20241 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20242 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20243 (user-error "C-c C-c can do nothing useful at this location"))
20244 ;; When at a link, act according to the parent instead.
20245 (when (eq type 'link)
20246 (setq context (org-element-property :parent context))
20247 (setq type (org-element-type context)))
20248 ;; For convenience: at the first line of a paragraph on the
20249 ;; same line as an item, apply function on that item instead.
20250 (when (eq type 'paragraph)
20251 (let ((parent (org-element-property :parent context)))
20252 (when (and (eq (org-element-type parent) 'item)
20253 (= (point-at-bol) (org-element-property :begin parent)))
20254 (setq context parent type 'item))))
20255 ;; Act according to type of element or object at point.
20256 (case type
20257 (clock (org-clock-update-time-maybe))
20258 (dynamic-block
20259 (save-excursion
20260 (goto-char (org-element-property :post-affiliated context))
20261 (org-update-dblock)))
20262 (footnote-definition
20263 (goto-char (org-element-property :post-affiliated context))
20264 (call-interactively 'org-footnote-action))
20265 (footnote-reference (call-interactively 'org-footnote-action))
20266 ((headline inlinetask)
20267 (save-excursion (goto-char (org-element-property :begin context))
20268 (call-interactively 'org-set-tags)))
20269 (item
20270 ;; At an item: a double C-u set checkbox to "[-]"
20271 ;; unconditionally, whereas a single one will toggle its
20272 ;; presence. Without an universal argument, if the item
20273 ;; has a checkbox, toggle it. Otherwise repair the list.
20274 (let* ((box (org-element-property :checkbox context))
20275 (struct (org-element-property :structure context))
20276 (old-struct (copy-tree struct))
20277 (parents (org-list-parents-alist struct))
20278 (prevs (org-list-prevs-alist struct))
20279 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20280 (org-list-set-checkbox
20281 (org-element-property :begin context) struct
20282 (cond ((equal arg '(16)) "[-]")
20283 ((and (not box) (equal arg '(4))) "[ ]")
20284 ((or (not box) (equal arg '(4))) nil)
20285 ((eq box 'on) "[ ]")
20286 (t "[X]")))
20287 ;; Mimic `org-list-write-struct' but with grabbing
20288 ;; a return value from `org-list-struct-fix-box'.
20289 (org-list-struct-fix-ind struct parents 2)
20290 (org-list-struct-fix-item-end struct)
20291 (org-list-struct-fix-bul struct prevs)
20292 (org-list-struct-fix-ind struct parents)
20293 (let ((block-item
20294 (org-list-struct-fix-box struct parents prevs orderedp)))
20295 (if (and box (equal struct old-struct))
20296 (if (equal arg '(16))
20297 (message "Checkboxes already reset")
20298 (user-error "Cannot toggle this checkbox: %s"
20299 (if (eq box 'on)
20300 "all subitems checked"
20301 "unchecked subitems")))
20302 (org-list-struct-apply-struct struct old-struct)
20303 (org-update-checkbox-count-maybe))
20304 (when block-item
20305 (message "Checkboxes were removed due to empty box at line %d"
20306 (org-current-line block-item))))))
20307 (keyword
20308 (let ((org-inhibit-startup-visibility-stuff t)
20309 (org-startup-align-all-tables nil))
20310 (when (boundp 'org-table-coordinate-overlays)
20311 (mapc 'delete-overlay org-table-coordinate-overlays)
20312 (setq org-table-coordinate-overlays nil))
20313 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20314 (message "Local setup has been refreshed"))
20315 (plain-list
20316 ;; At a plain list, with a double C-u argument, set
20317 ;; checkboxes of each item to "[-]", whereas a single one
20318 ;; will toggle their presence according to the state of the
20319 ;; first item in the list. Without an argument, repair the
20320 ;; list.
20321 (let* ((begin (org-element-property :contents-begin context))
20322 (beginm (move-marker (make-marker) begin))
20323 (struct (org-element-property :structure context))
20324 (old-struct (copy-tree struct))
20325 (first-box (save-excursion
20326 (goto-char begin)
20327 (looking-at org-list-full-item-re)
20328 (match-string-no-properties 3)))
20329 (new-box (cond ((equal arg '(16)) "[-]")
20330 ((equal arg '(4)) (unless first-box "[ ]"))
20331 ((equal first-box "[X]") "[ ]")
20332 (t "[X]"))))
20333 (cond
20334 (arg
20335 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20336 (org-list-get-all-items
20337 begin struct (org-list-prevs-alist struct))))
20338 ((and first-box (eq (point) begin))
20339 ;; For convenience, when point is at bol on the first
20340 ;; item of the list and no argument is provided, simply
20341 ;; toggle checkbox of that item, if any.
20342 (org-list-set-checkbox begin struct new-box)))
20343 (org-list-write-struct
20344 struct (org-list-parents-alist struct) old-struct)
20345 (org-update-checkbox-count-maybe)
20346 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20347 ((property-drawer node-property)
20348 (call-interactively 'org-property-action))
20349 ((radio-target target)
20350 (call-interactively 'org-update-radio-target-regexp))
20351 (statistics-cookie
20352 (call-interactively 'org-update-statistics-cookies))
20353 ((table table-cell table-row)
20354 ;; At a table, recalculate every field and align it. Also
20355 ;; send the table if necessary. If the table has
20356 ;; a `table.el' type, just give up. At a table row or
20357 ;; cell, maybe recalculate line but always align table.
20358 (if (eq (org-element-property :type context) 'table.el)
20359 (message "Use C-c ' to edit table.el tables")
20360 (let ((org-enable-table-editor t))
20361 (if (or (eq type 'table)
20362 ;; Check if point is at a TBLFM line.
20363 (and (eq type 'table-row)
20364 (= (point) (org-element-property :end context))))
20365 (save-excursion
20366 (if (org-at-TBLFM-p)
20367 (progn (require 'org-table)
20368 (org-table-calc-current-TBLFM))
20369 (goto-char (org-element-property :contents-begin context))
20370 (org-call-with-arg 'org-table-recalculate (or arg t))
20371 (orgtbl-send-table 'maybe)))
20372 (org-table-maybe-eval-formula)
20373 (cond (arg (call-interactively 'org-table-recalculate))
20374 ((org-table-maybe-recalculate-line))
20375 (t (org-table-align)))))))
20376 (timestamp (org-timestamp-change 0 'day))
20377 (otherwise
20378 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20379 (user-error
20380 "C-c C-c can do nothing useful at this location")))))))))
20382 (defun org-mode-restart ()
20383 "Restart Org-mode, to scan again for special lines.
20384 Also updates the keyword regular expressions."
20385 (interactive)
20386 (org-mode)
20387 (message "Org-mode restarted"))
20389 (defun org-kill-note-or-show-branches ()
20390 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20391 (interactive)
20392 (if (not org-finish-function)
20393 (progn
20394 (hide-subtree)
20395 (call-interactively 'show-branches))
20396 (let ((org-note-abort t))
20397 (funcall org-finish-function))))
20399 (defun org-open-line (n)
20400 "Insert a new row in tables, call `open-line' elsewhere.
20401 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20402 (interactive "*p")
20403 (cond
20404 ((not org-special-ctrl-o)
20405 (open-line n))
20406 ((org-at-table-p)
20407 (org-table-insert-row))
20409 (open-line n))))
20411 (defun org-return (&optional indent)
20412 "Goto next table row or insert a newline.
20413 Calls `org-table-next-row' or `newline', depending on context.
20414 See the individual commands for more information."
20415 (interactive)
20416 (let (org-ts-what)
20417 (cond
20418 ((or (bobp) (org-in-src-block-p))
20419 (if indent (newline-and-indent) (newline)))
20420 ((org-at-table-p)
20421 (org-table-justify-field-maybe)
20422 (call-interactively 'org-table-next-row))
20423 ;; when `newline-and-indent' is called within a list, make sure
20424 ;; text moved stays inside the item.
20425 ((and (org-in-item-p) indent)
20426 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20427 (progn
20428 (save-match-data (newline))
20429 (org-indent-line-to (length (match-string 0))))
20430 (let ((ind (org-get-indentation)))
20431 (newline)
20432 (if (org-looking-back org-list-end-re)
20433 (org-indent-line)
20434 (org-indent-line-to ind)))))
20435 ((and org-return-follows-link
20436 (org-at-timestamp-p t)
20437 (not (eq org-ts-what 'after)))
20438 (org-follow-timestamp-link))
20439 ((and org-return-follows-link
20440 (let ((tprop (get-text-property (point) 'face)))
20441 (or (eq tprop 'org-link)
20442 (and (listp tprop) (memq 'org-link tprop)))))
20443 (call-interactively 'org-open-at-point))
20444 ((and (org-at-heading-p)
20445 (looking-at
20446 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20447 (org-show-entry)
20448 (end-of-line 1)
20449 (newline))
20450 (t (if indent (newline-and-indent) (newline))))))
20452 (defun org-return-indent ()
20453 "Goto next table row or insert a newline and indent.
20454 Calls `org-table-next-row' or `newline-and-indent', depending on
20455 context. See the individual commands for more information."
20456 (interactive)
20457 (org-return t))
20459 (defun org-ctrl-c-star ()
20460 "Compute table, or change heading status of lines.
20461 Calls `org-table-recalculate' or `org-toggle-heading',
20462 depending on context."
20463 (interactive)
20464 (cond
20465 ((org-at-table-p)
20466 (call-interactively 'org-table-recalculate))
20468 ;; Convert all lines in region to list items
20469 (call-interactively 'org-toggle-heading))))
20471 (defun org-ctrl-c-minus ()
20472 "Insert separator line in table or modify bullet status of line.
20473 Also turns a plain line or a region of lines into list items.
20474 Calls `org-table-insert-hline', `org-toggle-item', or
20475 `org-cycle-list-bullet', depending on context."
20476 (interactive)
20477 (cond
20478 ((org-at-table-p)
20479 (call-interactively 'org-table-insert-hline))
20480 ((org-region-active-p)
20481 (call-interactively 'org-toggle-item))
20482 ((org-in-item-p)
20483 (call-interactively 'org-cycle-list-bullet))
20485 (call-interactively 'org-toggle-item))))
20487 (defun org-toggle-item (arg)
20488 "Convert headings or normal lines to items, items to normal lines.
20489 If there is no active region, only the current line is considered.
20491 If the first non blank line in the region is a headline, convert
20492 all headlines to items, shifting text accordingly.
20494 If it is an item, convert all items to normal lines.
20496 If it is normal text, change region into a list of items.
20497 With a prefix argument ARG, change the region in a single item."
20498 (interactive "P")
20499 (let ((shift-text
20500 (function
20501 ;; Shift text in current section to IND, from point to END.
20502 ;; The function leaves point to END line.
20503 (lambda (ind end)
20504 (let ((min-i 1000) (end (copy-marker end)))
20505 ;; First determine the minimum indentation (MIN-I) of
20506 ;; the text.
20507 (save-excursion
20508 (catch 'exit
20509 (while (< (point) end)
20510 (let ((i (org-get-indentation)))
20511 (cond
20512 ;; Skip blank lines and inline tasks.
20513 ((looking-at "^[ \t]*$"))
20514 ((looking-at org-outline-regexp-bol))
20515 ;; We can't find less than 0 indentation.
20516 ((zerop i) (throw 'exit (setq min-i 0)))
20517 ((< i min-i) (setq min-i i))))
20518 (forward-line))))
20519 ;; Then indent each line so that a line indented to
20520 ;; MIN-I becomes indented to IND. Ignore blank lines
20521 ;; and inline tasks in the process.
20522 (let ((delta (- ind min-i)))
20523 (while (< (point) end)
20524 (unless (or (looking-at "^[ \t]*$")
20525 (looking-at org-outline-regexp-bol))
20526 (org-indent-line-to (+ (org-get-indentation) delta)))
20527 (forward-line)))))))
20528 (skip-blanks
20529 (function
20530 ;; Return beginning of first non-blank line, starting from
20531 ;; line at POS.
20532 (lambda (pos)
20533 (save-excursion
20534 (goto-char pos)
20535 (skip-chars-forward " \r\t\n")
20536 (point-at-bol)))))
20537 beg end)
20538 ;; Determine boundaries of changes.
20539 (if (org-region-active-p)
20540 (setq beg (funcall skip-blanks (region-beginning))
20541 end (copy-marker (region-end)))
20542 (setq beg (funcall skip-blanks (point-at-bol))
20543 end (copy-marker (point-at-eol))))
20544 ;; Depending on the starting line, choose an action on the text
20545 ;; between BEG and END.
20546 (org-with-limited-levels
20547 (save-excursion
20548 (goto-char beg)
20549 (cond
20550 ;; Case 1. Start at an item: de-itemize. Note that it only
20551 ;; happens when a region is active: `org-ctrl-c-minus'
20552 ;; would call `org-cycle-list-bullet' otherwise.
20553 ((org-at-item-p)
20554 (while (< (point) end)
20555 (when (org-at-item-p)
20556 (skip-chars-forward " \t")
20557 (delete-region (point) (match-end 0)))
20558 (forward-line)))
20559 ;; Case 2. Start at an heading: convert to items.
20560 ((org-at-heading-p)
20561 (let* ((bul (org-list-bullet-string "-"))
20562 (bul-len (length bul))
20563 ;; Indentation of the first heading. It should be
20564 ;; relative to the indentation of its parent, if any.
20565 (start-ind (save-excursion
20566 (cond
20567 ((not org-adapt-indentation) 0)
20568 ((not (outline-previous-heading)) 0)
20569 (t (length (match-string 0))))))
20570 ;; Level of first heading. Further headings will be
20571 ;; compared to it to determine hierarchy in the list.
20572 (ref-level (org-reduced-level (org-outline-level))))
20573 (while (< (point) end)
20574 (let* ((level (org-reduced-level (org-outline-level)))
20575 (delta (max 0 (- level ref-level))))
20576 ;; If current headline is less indented than the first
20577 ;; one, set it as reference, in order to preserve
20578 ;; subtrees.
20579 (when (< level ref-level) (setq ref-level level))
20580 (replace-match bul t t)
20581 (org-indent-line-to (+ start-ind (* delta bul-len)))
20582 ;; Ensure all text down to END (or SECTION-END) belongs
20583 ;; to the newly created item.
20584 (let ((section-end (save-excursion
20585 (or (outline-next-heading) (point)))))
20586 (forward-line)
20587 (funcall shift-text
20588 (+ start-ind (* (1+ delta) bul-len))
20589 (min end section-end)))))))
20590 ;; Case 3. Normal line with ARG: make the first line of region
20591 ;; an item, and shift indentation of others lines to
20592 ;; set them as item's body.
20593 (arg (let* ((bul (org-list-bullet-string "-"))
20594 (bul-len (length bul))
20595 (ref-ind (org-get-indentation)))
20596 (skip-chars-forward " \t")
20597 (insert bul)
20598 (forward-line)
20599 (while (< (point) end)
20600 ;; Ensure that lines less indented than first one
20601 ;; still get included in item body.
20602 (funcall shift-text
20603 (+ ref-ind bul-len)
20604 (min end (save-excursion (or (outline-next-heading)
20605 (point)))))
20606 (forward-line))))
20607 ;; Case 4. Normal line without ARG: turn each non-item line
20608 ;; into an item.
20610 (while (< (point) end)
20611 (unless (or (org-at-heading-p) (org-at-item-p))
20612 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20613 (replace-match
20614 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20615 (forward-line))))))))
20617 (defun org-toggle-heading (&optional nstars)
20618 "Convert headings to normal text, or items or text to headings.
20619 If there is no active region, only convert the current line.
20621 With a \\[universal-argument] prefix, convert the whole list at
20622 point into heading.
20624 In a region:
20626 - If the first non blank line is a headline, remove the stars
20627 from all headlines in the region.
20629 - If it is a normal line, turn each and every normal line (i.e.,
20630 not an heading or an item) in the region into headings. If you
20631 want to convert only the first line of this region, use one
20632 universal prefix argument.
20634 - If it is a plain list item, turn all plain list items into headings.
20636 When converting a line into a heading, the number of stars is chosen
20637 such that the lines become children of the current entry. However,
20638 when a numeric prefix argument is given, its value determines the
20639 number of stars to add."
20640 (interactive "P")
20641 (let ((skip-blanks
20642 (function
20643 ;; Return beginning of first non-blank line, starting from
20644 ;; line at POS.
20645 (lambda (pos)
20646 (save-excursion
20647 (goto-char pos)
20648 (while (org-at-comment-p) (forward-line))
20649 (skip-chars-forward " \r\t\n")
20650 (point-at-bol)))))
20651 beg end toggled)
20652 ;; Determine boundaries of changes. If a universal prefix has
20653 ;; been given, put the list in a region. If region ends at a bol,
20654 ;; do not consider the last line to be in the region.
20656 (when (and current-prefix-arg (org-at-item-p))
20657 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20658 (org-mark-element))
20660 (if (org-region-active-p)
20661 (setq beg (funcall skip-blanks (region-beginning))
20662 end (copy-marker (save-excursion
20663 (goto-char (region-end))
20664 (if (bolp) (point) (point-at-eol)))))
20665 (setq beg (funcall skip-blanks (point-at-bol))
20666 end (copy-marker (point-at-eol))))
20667 ;; Ensure inline tasks don't count as headings.
20668 (org-with-limited-levels
20669 (save-excursion
20670 (goto-char beg)
20671 (cond
20672 ;; Case 1. Started at an heading: de-star headings.
20673 ((org-at-heading-p)
20674 (while (< (point) end)
20675 (when (org-at-heading-p t)
20676 (looking-at org-outline-regexp) (replace-match "")
20677 (setq toggled t))
20678 (forward-line)))
20679 ;; Case 2. Started at an item: change items into headlines.
20680 ;; One star will be added by `org-list-to-subtree'.
20681 ((org-at-item-p)
20682 (let* ((stars (make-string
20683 ;; subtract the star that will be added again by
20684 ;; `org-list-to-subtree'
20685 (if (numberp nstars) (1- nstars)
20686 (or (org-current-level) 0))
20687 ?*))
20688 (add-stars
20689 (cond (nstars "") ; stars from prefix only
20690 ((equal stars "") "") ; before first heading
20691 (org-odd-levels-only "*") ; inside heading, odd
20692 (t "")))) ; inside heading, oddeven
20693 (while (< (point) end)
20694 (when (org-at-item-p)
20695 ;; Pay attention to cases when region ends before list.
20696 (let* ((struct (org-list-struct))
20697 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20698 (save-restriction
20699 (narrow-to-region (point) list-end)
20700 (insert
20701 (org-list-to-subtree
20702 (org-list-parse-list t)
20703 '(:istart (concat stars add-stars (funcall get-stars depth))
20704 :icount (concat stars add-stars (funcall get-stars depth)))))))
20705 (setq toggled t))
20706 (forward-line))))
20707 ;; Case 3. Started at normal text: make every line an heading,
20708 ;; skipping headlines and items.
20709 (t (let* ((stars
20710 (make-string
20711 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20712 (add-stars
20713 (cond (nstars "") ; stars from prefix only
20714 ((equal stars "") "*") ; before first heading
20715 (org-odd-levels-only "**") ; inside heading, odd
20716 (t "*"))) ; inside heading, oddeven
20717 (rpl (concat stars add-stars " "))
20718 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20719 (while (< (point) (if (equal nstars '(4)) lend end))
20720 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20721 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20722 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20723 (forward-line)))))))
20724 (unless toggled (message "Cannot toggle heading from here"))))
20726 (defun org-meta-return (&optional arg)
20727 "Insert a new heading or wrap a region in a table.
20728 Calls `org-insert-heading' or `org-table-wrap-region', depending
20729 on context. See the individual commands for more information."
20730 (interactive "P")
20731 (org-check-before-invisible-edit 'insert)
20732 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20733 (let* ((element (org-element-at-point))
20734 (type (org-element-type element)))
20735 (when (eq type 'table-row)
20736 (setq element (org-element-property :parent element))
20737 (setq type 'table))
20738 (if (and (eq type 'table)
20739 (eq (org-element-property :type element) 'org)
20740 (>= (point) (org-element-property :contents-begin element))
20741 (< (point) (org-element-property :contents-end element)))
20742 (call-interactively 'org-table-wrap-region)
20743 (call-interactively 'org-insert-heading)))))
20745 ;;; Menu entries
20747 (defsubst org-in-subtree-not-table-p ()
20748 "Are we in a subtree and not in a table?"
20749 (and (not (org-before-first-heading-p))
20750 (not (org-at-table-p))))
20752 ;; Define the Org-mode menus
20753 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20754 '("Tbl"
20755 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20756 ["Next Field" org-cycle (org-at-table-p)]
20757 ["Previous Field" org-shifttab (org-at-table-p)]
20758 ["Next Row" org-return (org-at-table-p)]
20759 "--"
20760 ["Blank Field" org-table-blank-field (org-at-table-p)]
20761 ["Edit Field" org-table-edit-field (org-at-table-p)]
20762 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20763 "--"
20764 ("Column"
20765 ["Move Column Left" org-metaleft (org-at-table-p)]
20766 ["Move Column Right" org-metaright (org-at-table-p)]
20767 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20768 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20769 ("Row"
20770 ["Move Row Up" org-metaup (org-at-table-p)]
20771 ["Move Row Down" org-metadown (org-at-table-p)]
20772 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20773 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20774 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20775 "--"
20776 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20777 ("Rectangle"
20778 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20779 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20780 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20781 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20782 "--"
20783 ("Calculate"
20784 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20785 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20786 ["Edit Formulas" org-edit-special (org-at-table-p)]
20787 "--"
20788 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20789 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20790 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20791 "--"
20792 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20793 "--"
20794 ["Sum Column/Rectangle" org-table-sum
20795 (or (org-at-table-p) (org-region-active-p))]
20796 ["Which Column?" org-table-current-column (org-at-table-p)])
20797 ["Debug Formulas"
20798 org-table-toggle-formula-debugger
20799 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20800 ["Show Col/Row Numbers"
20801 org-table-toggle-coordinate-overlays
20802 :style toggle
20803 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20804 "--"
20805 ["Create" org-table-create (and (not (org-at-table-p))
20806 org-enable-table-editor)]
20807 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20808 ["Import from File" org-table-import (not (org-at-table-p))]
20809 ["Export to File" org-table-export (org-at-table-p)]
20810 "--"
20811 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20813 (easy-menu-define org-org-menu org-mode-map "Org menu"
20814 '("Org"
20815 ("Show/Hide"
20816 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20817 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20818 ["Sparse Tree..." org-sparse-tree t]
20819 ["Reveal Context" org-reveal t]
20820 ["Show All" show-all t]
20821 "--"
20822 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20823 "--"
20824 ["New Heading" org-insert-heading t]
20825 ("Navigate Headings"
20826 ["Up" outline-up-heading t]
20827 ["Next" outline-next-visible-heading t]
20828 ["Previous" outline-previous-visible-heading t]
20829 ["Next Same Level" outline-forward-same-level t]
20830 ["Previous Same Level" outline-backward-same-level t]
20831 "--"
20832 ["Jump" org-goto t])
20833 ("Edit Structure"
20834 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20835 "--"
20836 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20837 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20838 "--"
20839 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20840 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20841 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20842 "--"
20843 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20844 "--"
20845 ["Copy visible text" org-copy-visible t]
20846 "--"
20847 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20848 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20849 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20850 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20851 "--"
20852 ["Sort Region/Children" org-sort t]
20853 "--"
20854 ["Convert to odd levels" org-convert-to-odd-levels t]
20855 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20856 ("Editing"
20857 ["Emphasis..." org-emphasize t]
20858 ["Edit Source Example" org-edit-special t]
20859 "--"
20860 ["Footnote new/jump" org-footnote-action t]
20861 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20862 ("Archive"
20863 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20864 "--"
20865 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20866 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20867 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20869 "--"
20870 ("Hyperlinks"
20871 ["Store Link (Global)" org-store-link t]
20872 ["Find existing link to here" org-occur-link-in-agenda-files t]
20873 ["Insert Link" org-insert-link t]
20874 ["Follow Link" org-open-at-point t]
20875 "--"
20876 ["Next link" org-next-link t]
20877 ["Previous link" org-previous-link t]
20878 "--"
20879 ["Descriptive Links"
20880 org-toggle-link-display
20881 :style radio
20882 :selected org-descriptive-links
20884 ["Literal Links"
20885 org-toggle-link-display
20886 :style radio
20887 :selected (not org-descriptive-links)])
20888 "--"
20889 ("TODO Lists"
20890 ["TODO/DONE/-" org-todo t]
20891 ("Select keyword"
20892 ["Next keyword" org-shiftright (org-at-heading-p)]
20893 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20894 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20895 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20896 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20897 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20898 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20899 "--"
20900 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20901 :selected org-enforce-todo-dependencies :style toggle :active t]
20902 "Settings for tree at point"
20903 ["Do Children sequentially" org-toggle-ordered-property :style radio
20904 :selected (org-entry-get nil "ORDERED")
20905 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20906 ["Do Children parallel" org-toggle-ordered-property :style radio
20907 :selected (not (org-entry-get nil "ORDERED"))
20908 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20909 "--"
20910 ["Set Priority" org-priority t]
20911 ["Priority Up" org-shiftup t]
20912 ["Priority Down" org-shiftdown t]
20913 "--"
20914 ["Get news from all feeds" org-feed-update-all t]
20915 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20916 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20917 ("TAGS and Properties"
20918 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20919 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20920 "--"
20921 ["Set property" org-set-property (not (org-before-first-heading-p))]
20922 ["Column view of properties" org-columns t]
20923 ["Insert Column View DBlock" org-insert-columns-dblock t])
20924 ("Dates and Scheduling"
20925 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20926 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20927 ("Change Date"
20928 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20929 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20930 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20931 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20932 ["Compute Time Range" org-evaluate-time-range t]
20933 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20934 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20935 "--"
20936 ["Custom time format" org-toggle-time-stamp-overlays
20937 :style radio :selected org-display-custom-times]
20938 "--"
20939 ["Goto Calendar" org-goto-calendar t]
20940 ["Date from Calendar" org-date-from-calendar t]
20941 "--"
20942 ["Start/Restart Timer" org-timer-start t]
20943 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20944 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20945 ["Insert Timer String" org-timer t]
20946 ["Insert Timer Item" org-timer-item t])
20947 ("Logging work"
20948 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20949 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20950 ["Clock out" org-clock-out t]
20951 ["Clock cancel" org-clock-cancel t]
20952 "--"
20953 ["Mark as default task" org-clock-mark-default-task t]
20954 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20955 ["Goto running clock" org-clock-goto t]
20956 "--"
20957 ["Display times" org-clock-display t]
20958 ["Create clock table" org-clock-report t]
20959 "--"
20960 ["Record DONE time"
20961 (progn (setq org-log-done (not org-log-done))
20962 (message "Switching to %s will %s record a timestamp"
20963 (car org-done-keywords)
20964 (if org-log-done "automatically" "not")))
20965 :style toggle :selected org-log-done])
20966 "--"
20967 ["Agenda Command..." org-agenda t]
20968 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20969 ("File List for Agenda")
20970 ("Special views current file"
20971 ["TODO Tree" org-show-todo-tree t]
20972 ["Check Deadlines" org-check-deadlines t]
20973 ["Timeline" org-timeline t]
20974 ["Tags/Property tree" org-match-sparse-tree t])
20975 "--"
20976 ["Export/Publish..." org-export-dispatch t]
20977 ("LaTeX"
20978 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20979 :selected org-cdlatex-mode]
20980 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20981 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20982 ["Modify math symbol" org-cdlatex-math-modify
20983 (org-inside-LaTeX-fragment-p)]
20984 ["Insert citation" org-reftex-citation t]
20985 "--"
20986 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20987 "--"
20988 ("MobileOrg"
20989 ["Push Files and Views" org-mobile-push t]
20990 ["Get Captured and Flagged" org-mobile-pull t]
20991 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20992 "--"
20993 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20994 "--"
20995 ("Documentation"
20996 ["Show Version" org-version t]
20997 ["Info Documentation" org-info t])
20998 ("Customize"
20999 ["Browse Org Group" org-customize t]
21000 "--"
21001 ["Expand This Menu" org-create-customize-menu
21002 (fboundp 'customize-menu-create)])
21003 ["Send bug report" org-submit-bug-report t]
21004 "--"
21005 ("Refresh/Reload"
21006 ["Refresh setup current buffer" org-mode-restart t]
21007 ["Reload Org (after update)" org-reload t]
21008 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21011 (defun org-info (&optional node)
21012 "Read documentation for Org-mode in the info system.
21013 With optional NODE, go directly to that node."
21014 (interactive)
21015 (info (format "(org)%s" (or node ""))))
21017 ;;;###autoload
21018 (defun org-submit-bug-report ()
21019 "Submit a bug report on Org-mode via mail.
21021 Don't hesitate to report any problems or inaccurate documentation.
21023 If you don't have setup sending mail from (X)Emacs, please copy the
21024 output buffer into your mail program, as it gives us important
21025 information about your Org-mode version and configuration."
21026 (interactive)
21027 (require 'reporter)
21028 (org-load-modules-maybe)
21029 (org-require-autoloaded-modules)
21030 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21031 (reporter-submit-bug-report
21032 "emacs-orgmode@gnu.org"
21033 (org-version nil 'full)
21034 (let (list)
21035 (save-window-excursion
21036 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21037 (delete-other-windows)
21038 (erase-buffer)
21039 (insert "You are about to submit a bug report to the Org-mode mailing list.
21041 We would like to add your full Org-mode and Outline configuration to the
21042 bug report. This greatly simplifies the work of the maintainer and
21043 other experts on the mailing list.
21045 HOWEVER, some variables you have customized may contain private
21046 information. The names of customers, colleagues, or friends, might
21047 appear in the form of file names, tags, todo states, or search strings.
21048 If you answer yes to the prompt, you might want to check and remove
21049 such private information before sending the email.")
21050 (add-text-properties (point-min) (point-max) '(face org-warning))
21051 (when (yes-or-no-p "Include your Org-mode configuration ")
21052 (mapatoms
21053 (lambda (v)
21054 (and (boundp v)
21055 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21056 (or (and (symbol-value v)
21057 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21058 (and
21059 (get v 'custom-type) (get v 'standard-value)
21060 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21061 (push v list)))))
21062 (kill-buffer (get-buffer "*Warn about privacy*"))
21063 list))
21064 nil nil
21065 "Remember to cover the basics, that is, what you expected to happen and
21066 what in fact did happen. You don't know how to make a good report? See
21068 http://orgmode.org/manual/Feedback.html#Feedback
21070 Your bug report will be posted to the Org-mode mailing list.
21071 ------------------------------------------------------------------------")
21072 (save-excursion
21073 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21074 (replace-match "\\1Bug: \\3 [\\2]")))))
21077 (defun org-install-agenda-files-menu ()
21078 (let ((bl (buffer-list)))
21079 (save-excursion
21080 (while bl
21081 (set-buffer (pop bl))
21082 (if (derived-mode-p 'org-mode) (setq bl nil)))
21083 (when (derived-mode-p 'org-mode)
21084 (easy-menu-change
21085 '("Org") "File List for Agenda"
21086 (append
21087 (list
21088 ["Edit File List" (org-edit-agenda-file-list) t]
21089 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21090 ["Remove Current File from List" org-remove-file t]
21091 ["Cycle through agenda files" org-cycle-agenda-files t]
21092 ["Occur in all agenda files" org-occur-in-agenda-files t]
21093 "--")
21094 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21096 ;;;; Documentation
21098 (defun org-require-autoloaded-modules ()
21099 (interactive)
21100 (mapc 'require
21101 '(org-agenda org-archive org-attach org-clock org-colview org-id
21102 org-table org-timer)))
21104 ;;;###autoload
21105 (defun org-reload (&optional uncompiled)
21106 "Reload all org lisp files.
21107 With prefix arg UNCOMPILED, load the uncompiled versions."
21108 (interactive "P")
21109 (require 'loadhist)
21110 (let* ((org-dir (org-find-library-dir "org"))
21111 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21112 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21113 (remove-re (mapconcat 'identity
21114 (mapcar (lambda (f) (concat "^" f "$"))
21115 (list (if (featurep 'xemacs)
21116 "org-colview"
21117 "org-colview-xemacs")
21118 "org" "org-loaddefs" "org-version"))
21119 "\\|"))
21120 (feats (delete-dups
21121 (mapcar 'file-name-sans-extension
21122 (mapcar 'file-name-nondirectory
21123 (delq nil
21124 (mapcar 'feature-file
21125 features))))))
21126 (lfeat (append
21127 (sort
21128 (setq feats
21129 (delq nil (mapcar
21130 (lambda (f)
21131 (if (and (string-match feature-re f)
21132 (not (string-match remove-re f)))
21133 f nil))
21134 feats)))
21135 'string-lessp)
21136 (list "org-version" "org")))
21137 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21138 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21139 load-uncore load-misses)
21140 (setq load-misses
21141 (delq 't
21142 (mapcar (lambda (f)
21143 (or (org-load-noerror-mustsuffix (concat org-dir f))
21144 (and (string= org-dir contrib-dir)
21145 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21146 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21147 (add-to-list 'load-uncore f 'append)
21150 lfeat)))
21151 (if load-uncore
21152 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21153 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21154 (if load-misses
21155 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21156 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21157 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21159 ;;;###autoload
21160 (defun org-customize ()
21161 "Call the customize function with org as argument."
21162 (interactive)
21163 (org-load-modules-maybe)
21164 (org-require-autoloaded-modules)
21165 (customize-browse 'org))
21167 (defun org-create-customize-menu ()
21168 "Create a full customization menu for Org-mode, insert it into the menu."
21169 (interactive)
21170 (org-load-modules-maybe)
21171 (org-require-autoloaded-modules)
21172 (if (fboundp 'customize-menu-create)
21173 (progn
21174 (easy-menu-change
21175 '("Org") "Customize"
21176 `(["Browse Org group" org-customize t]
21177 "--"
21178 ,(customize-menu-create 'org)
21179 ["Set" Custom-set t]
21180 ["Save" Custom-save t]
21181 ["Reset to Current" Custom-reset-current t]
21182 ["Reset to Saved" Custom-reset-saved t]
21183 ["Reset to Standard Settings" Custom-reset-standard t]))
21184 (message "\"Org\"-menu now contains full customization menu"))
21185 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21187 ;;;; Miscellaneous stuff
21189 ;;; Generally useful functions
21191 (defun org-get-at-bol (property)
21192 "Get text property PROPERTY at beginning of line."
21193 (get-text-property (point-at-bol) property))
21195 (defun org-find-text-property-in-string (prop s)
21196 "Return the first non-nil value of property PROP in string S."
21197 (or (get-text-property 0 prop s)
21198 (get-text-property (or (next-single-property-change 0 prop s) 0)
21199 prop s)))
21201 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21202 "Display the given MESSAGE as a warning."
21203 (if (fboundp 'display-warning)
21204 (display-warning 'org message
21205 (if (featurep 'xemacs) 'warning :warning))
21206 (let ((buf (get-buffer-create "*Org warnings*")))
21207 (with-current-buffer buf
21208 (goto-char (point-max))
21209 (insert "Warning (Org): " message)
21210 (unless (bolp)
21211 (newline)))
21212 (display-buffer buf)
21213 (sit-for 0))))
21215 (defun org-eval (form)
21216 "Eval FORM and return result."
21217 (condition-case error
21218 (eval form)
21219 (error (format "%%![Error: %s]" error))))
21221 (defun org-in-clocktable-p ()
21222 "Check if the cursor is in a clocktable."
21223 (let ((pos (point)) start)
21224 (save-excursion
21225 (end-of-line 1)
21226 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21227 (setq start (match-beginning 0))
21228 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21229 (>= (match-end 0) pos)
21230 start))))
21232 (defun org-in-commented-line ()
21233 "Is point in a line starting with `#'?"
21234 (equal (char-after (point-at-bol)) ?#))
21236 (defun org-in-indented-comment-line ()
21237 "Is point in a line starting with `#' after some white space?"
21238 (save-excursion
21239 (save-match-data
21240 (goto-char (point-at-bol))
21241 (looking-at "[ \t]*#"))))
21243 (defun org-in-verbatim-emphasis ()
21244 (save-match-data
21245 (and (org-in-regexp org-emph-re 2)
21246 (>= (point) (match-beginning 3))
21247 (<= (point) (match-end 4))
21248 (member (match-string 3) '("=" "~")))))
21250 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21251 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21252 (if (and marker (marker-buffer marker)
21253 (buffer-live-p (marker-buffer marker)))
21254 (progn
21255 (org-pop-to-buffer-same-window (marker-buffer marker))
21256 (if (or (> marker (point-max)) (< marker (point-min)))
21257 (widen))
21258 (goto-char marker)
21259 (org-show-context 'org-goto))
21260 (if bookmark
21261 (bookmark-jump bookmark)
21262 (error "Cannot find location"))))
21264 (defun org-quote-csv-field (s)
21265 "Quote field for inclusion in CSV material."
21266 (if (string-match "[\",]" s)
21267 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21270 (defun org-force-self-insert (N)
21271 "Needed to enforce self-insert under remapping."
21272 (interactive "p")
21273 (self-insert-command N))
21275 (defun org-string-width (s)
21276 "Compute width of string, ignoring invisible characters.
21277 This ignores character with invisibility property `org-link', and also
21278 characters with property `org-cwidth', because these will become invisible
21279 upon the next fontification round."
21280 (let (b l)
21281 (when (or (eq t buffer-invisibility-spec)
21282 (assq 'org-link buffer-invisibility-spec))
21283 (while (setq b (text-property-any 0 (length s)
21284 'invisible 'org-link s))
21285 (setq s (concat (substring s 0 b)
21286 (substring s (or (next-single-property-change
21287 b 'invisible s) (length s)))))))
21288 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21289 (setq s (concat (substring s 0 b)
21290 (substring s (or (next-single-property-change
21291 b 'org-cwidth s) (length s))))))
21292 (setq l (string-width s) b -1)
21293 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21294 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21297 (defun org-shorten-string (s maxlength)
21298 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21299 If the string is shorter or has length MAXLENGTH, just return the
21300 original string. If it is longer, the functions finds a space in the
21301 string, breaks this string off at that locations and adds three dots
21302 as ellipsis. Including the ellipsis, the string will not be longer
21303 than MAXLENGTH. If finding a good breaking point in the string does
21304 not work, the string is just chopped off in the middle of a word
21305 if necessary."
21306 (if (<= (length s) maxlength)
21308 (let* ((n (max (- maxlength 4) 1))
21309 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21310 (if (string-match re s)
21311 (concat (match-string 1 s) "...")
21312 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21314 (defun org-get-indentation (&optional line)
21315 "Get the indentation of the current line, interpreting tabs.
21316 When LINE is given, assume it represents a line and compute its indentation."
21317 (if line
21318 (if (string-match "^ *" (org-remove-tabs line))
21319 (match-end 0))
21320 (save-excursion
21321 (beginning-of-line 1)
21322 (skip-chars-forward " \t")
21323 (current-column))))
21325 (defun org-get-string-indentation (s)
21326 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21327 (let ((n -1) (i 0) (w tab-width) c)
21328 (catch 'exit
21329 (while (< (setq n (1+ n)) (length s))
21330 (setq c (aref s n))
21331 (cond ((= c ?\ ) (setq i (1+ i)))
21332 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21333 (t (throw 'exit t)))))
21336 (defun org-remove-tabs (s &optional width)
21337 "Replace tabulators in S with spaces.
21338 Assumes that s is a single line, starting in column 0."
21339 (setq width (or width tab-width))
21340 (while (string-match "\t" s)
21341 (setq s (replace-match
21342 (make-string
21343 (- (* width (/ (+ (match-beginning 0) width) width))
21344 (match-beginning 0)) ?\ )
21345 t t s)))
21348 (defun org-fix-indentation (line ind)
21349 "Fix indentation in LINE.
21350 IND is a cons cell with target and minimum indentation.
21351 If the current indentation in LINE is smaller than the minimum,
21352 leave it alone. If it is larger than ind, set it to the target."
21353 (let* ((l (org-remove-tabs line))
21354 (i (org-get-indentation l))
21355 (i1 (car ind)) (i2 (cdr ind)))
21356 (if (>= i i2) (setq l (substring line i2)))
21357 (if (> i1 0)
21358 (concat (make-string i1 ?\ ) l)
21359 l)))
21361 (defun org-remove-indentation (code &optional n)
21362 "Remove the maximum common indentation from the lines in CODE.
21363 N may optionally be the number of spaces to remove."
21364 (with-temp-buffer
21365 (insert code)
21366 (org-do-remove-indentation n)
21367 (buffer-string)))
21369 (defun org-do-remove-indentation (&optional n)
21370 "Remove the maximum common indentation from the buffer."
21371 (untabify (point-min) (point-max))
21372 (let ((min 10000) re)
21373 (if n
21374 (setq min n)
21375 (goto-char (point-min))
21376 (while (re-search-forward "^ *[^ \n]" nil t)
21377 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21378 (unless (or (= min 0) (= min 10000))
21379 (setq re (format "^ \\{%d\\}" min))
21380 (goto-char (point-min))
21381 (while (re-search-forward re nil t)
21382 (replace-match "")
21383 (end-of-line 1))
21384 min)))
21386 (defun org-fill-template (template alist)
21387 "Find each %key of ALIST in TEMPLATE and replace it."
21388 (let ((case-fold-search nil)
21389 entry key value)
21390 (setq alist (sort (copy-sequence alist)
21391 (lambda (a b) (< (length (car a)) (length (car b))))))
21392 (while (setq entry (pop alist))
21393 (setq template
21394 (replace-regexp-in-string
21395 (concat "%" (regexp-quote (car entry)))
21396 (or (cdr entry) "") template t t)))
21397 template))
21399 (defun org-base-buffer (buffer)
21400 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21401 (if (not buffer)
21402 buffer
21403 (or (buffer-base-buffer buffer)
21404 buffer)))
21406 (defun org-trim (s)
21407 "Remove whitespace at beginning and end of string."
21408 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21409 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21412 (defun org-wrap (string &optional width lines)
21413 "Wrap string to either a number of lines, or a width in characters.
21414 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21415 that costs. If there is a word longer than WIDTH, the text is actually
21416 wrapped to the length of that word.
21417 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21418 many lines, whatever width that takes.
21419 The return value is a list of lines, without newlines at the end."
21420 (let* ((words (org-split-string string "[ \t\n]+"))
21421 (maxword (apply 'max (mapcar 'org-string-width words)))
21422 w ll)
21423 (cond (width
21424 (org-do-wrap words (max maxword width)))
21425 (lines
21426 (setq w maxword)
21427 (setq ll (org-do-wrap words maxword))
21428 (if (<= (length ll) lines)
21430 (setq ll words)
21431 (while (> (length ll) lines)
21432 (setq w (1+ w))
21433 (setq ll (org-do-wrap words w)))
21434 ll))
21435 (t (error "Cannot wrap this")))))
21437 (defun org-do-wrap (words width)
21438 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21439 (let (lines line)
21440 (while words
21441 (setq line (pop words))
21442 (while (and words (< (+ (length line) (length (car words))) width))
21443 (setq line (concat line " " (pop words))))
21444 (setq lines (push line lines)))
21445 (nreverse lines)))
21447 (defun org-split-string (string &optional separators)
21448 "Splits STRING into substrings at SEPARATORS.
21449 No empty strings are returned if there are matches at the beginning
21450 and end of string."
21451 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21452 (start 0)
21453 notfirst
21454 (list nil))
21455 (while (and (string-match rexp string
21456 (if (and notfirst
21457 (= start (match-beginning 0))
21458 (< start (length string)))
21459 (1+ start) start))
21460 (< (match-beginning 0) (length string)))
21461 (setq notfirst t)
21462 (or (eq (match-beginning 0) 0)
21463 (and (eq (match-beginning 0) (match-end 0))
21464 (eq (match-beginning 0) start))
21465 (setq list
21466 (cons (substring string start (match-beginning 0))
21467 list)))
21468 (setq start (match-end 0)))
21469 (or (eq start (length string))
21470 (setq list
21471 (cons (substring string start)
21472 list)))
21473 (nreverse list)))
21475 (defun org-quote-vert (s)
21476 "Replace \"|\" with \"\\vert\"."
21477 (while (string-match "|" s)
21478 (setq s (replace-match "\\vert" t t s)))
21481 (defun org-uuidgen-p (s)
21482 "Is S an ID created by UUIDGEN?"
21483 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21485 (defun org-in-src-block-p (&optional inside)
21486 "Whether point is in a code source block.
21487 When INSIDE is non-nil, don't consider we are within a src block
21488 when point is at #+BEGIN_SRC or #+END_SRC."
21489 (let ((case-fold-search t) ov)
21490 (or (and (setq ov (overlays-at (point)))
21491 (memq 'org-block-background
21492 (overlay-properties (car ov))))
21493 (and (not inside)
21494 (save-match-data
21495 (save-excursion
21496 (beginning-of-line)
21497 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21499 (defun org-context ()
21500 "Return a list of contexts of the current cursor position.
21501 If several contexts apply, all are returned.
21502 Each context entry is a list with a symbol naming the context, and
21503 two positions indicating start and end of the context. Possible
21504 contexts are:
21506 :headline anywhere in a headline
21507 :headline-stars on the leading stars in a headline
21508 :todo-keyword on a TODO keyword (including DONE) in a headline
21509 :tags on the TAGS in a headline
21510 :priority on the priority cookie in a headline
21511 :item on the first line of a plain list item
21512 :item-bullet on the bullet/number of a plain list item
21513 :checkbox on the checkbox in a plain list item
21514 :table in an org-mode table
21515 :table-special on a special filed in a table
21516 :table-table in a table.el table
21517 :clocktable in a clocktable
21518 :src-block in a source block
21519 :link on a hyperlink
21520 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21521 :target on a <<target>>
21522 :radio-target on a <<<radio-target>>>
21523 :latex-fragment on a LaTeX fragment
21524 :latex-preview on a LaTeX fragment with overlaid preview image
21526 This function expects the position to be visible because it uses font-lock
21527 faces as a help to recognize the following contexts: :table-special, :link,
21528 and :keyword."
21529 (let* ((f (get-text-property (point) 'face))
21530 (faces (if (listp f) f (list f)))
21531 (case-fold-search t)
21532 (p (point)) clist o)
21533 ;; First the large context
21534 (cond
21535 ((org-at-heading-p t)
21536 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21537 (when (progn
21538 (beginning-of-line 1)
21539 (looking-at org-todo-line-tags-regexp))
21540 (push (org-point-in-group p 1 :headline-stars) clist)
21541 (push (org-point-in-group p 2 :todo-keyword) clist)
21542 (push (org-point-in-group p 4 :tags) clist))
21543 (goto-char p)
21544 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21545 (if (looking-at "\\[#[A-Z0-9]\\]")
21546 (push (org-point-in-group p 0 :priority) clist)))
21548 ((org-at-item-p)
21549 (push (org-point-in-group p 2 :item-bullet) clist)
21550 (push (list :item (point-at-bol)
21551 (save-excursion (org-end-of-item) (point)))
21552 clist)
21553 (and (org-at-item-checkbox-p)
21554 (push (org-point-in-group p 0 :checkbox) clist)))
21556 ((org-at-table-p)
21557 (push (list :table (org-table-begin) (org-table-end)) clist)
21558 (if (memq 'org-formula faces)
21559 (push (list :table-special
21560 (previous-single-property-change p 'face)
21561 (next-single-property-change p 'face)) clist)))
21562 ((org-at-table-p 'any)
21563 (push (list :table-table) clist)))
21564 (goto-char p)
21566 (let ((case-fold-search t))
21567 ;; New the "medium" contexts: clocktables, source blocks
21568 (cond ((org-in-clocktable-p)
21569 (push (list :clocktable
21570 (and (or (looking-at "#\\+BEGIN: clocktable")
21571 (search-backward "#+BEGIN: clocktable" nil t))
21572 (match-beginning 0))
21573 (and (re-search-forward "#\\+END:?" nil t)
21574 (match-end 0))) clist))
21575 ((org-in-src-block-p)
21576 (push (list :src-block
21577 (and (or (looking-at "#\\+BEGIN_SRC")
21578 (search-backward "#+BEGIN_SRC" nil t))
21579 (match-beginning 0))
21580 (and (search-forward "#+END_SRC" nil t)
21581 (match-beginning 0))) clist))))
21582 (goto-char p)
21584 ;; Now the small context
21585 (cond
21586 ((org-at-timestamp-p)
21587 (push (org-point-in-group p 0 :timestamp) clist))
21588 ((memq 'org-link faces)
21589 (push (list :link
21590 (previous-single-property-change p 'face)
21591 (next-single-property-change p 'face)) clist))
21592 ((memq 'org-special-keyword faces)
21593 (push (list :keyword
21594 (previous-single-property-change p 'face)
21595 (next-single-property-change p 'face)) clist))
21596 ((org-at-target-p)
21597 (push (org-point-in-group p 0 :target) clist)
21598 (goto-char (1- (match-beginning 0)))
21599 (if (looking-at org-radio-target-regexp)
21600 (push (org-point-in-group p 0 :radio-target) clist))
21601 (goto-char p))
21602 ((setq o (car (delq nil
21603 (mapcar
21604 (lambda (x)
21605 (if (memq x org-latex-fragment-image-overlays) x))
21606 (overlays-at (point))))))
21607 (push (list :latex-fragment
21608 (overlay-start o) (overlay-end o)) clist)
21609 (push (list :latex-preview
21610 (overlay-start o) (overlay-end o)) clist))
21611 ((org-inside-LaTeX-fragment-p)
21612 ;; FIXME: positions wrong.
21613 (push (list :latex-fragment (point) (point)) clist)))
21615 (setq clist (nreverse (delq nil clist)))
21616 clist))
21618 ;; FIXME: Compare with at-regexp-p Do we need both?
21619 (defun org-in-regexp (re &optional nlines visually)
21620 "Check if point is inside a match of regexp.
21621 Normally only the current line is checked, but you can include NLINES extra
21622 lines both before and after point into the search.
21623 If VISUALLY is set, require that the cursor is not after the match but
21624 really on, so that the block visually is on the match."
21625 (catch 'exit
21626 (let ((pos (point))
21627 (eol (point-at-eol (+ 1 (or nlines 0))))
21628 (inc (if visually 1 0)))
21629 (save-excursion
21630 (beginning-of-line (- 1 (or nlines 0)))
21631 (while (re-search-forward re eol t)
21632 (if (and (<= (match-beginning 0) pos)
21633 (>= (+ inc (match-end 0)) pos))
21634 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21636 (defun org-at-regexp-p (regexp)
21637 "Is point inside a match of REGEXP in the current line?"
21638 (catch 'exit
21639 (save-excursion
21640 (let ((pos (point)) (end (point-at-eol)))
21641 (beginning-of-line 1)
21642 (while (re-search-forward regexp end t)
21643 (if (and (<= (match-beginning 0) pos)
21644 (>= (match-end 0) pos))
21645 (throw 'exit t)))
21646 nil))))
21648 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21649 "Non-nil when point is between matches of START-RE and END-RE.
21651 Also return a non-nil value when point is on one of the matches.
21653 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21654 buffer positions. Default values are the positions of headlines
21655 surrounding the point.
21657 The functions returns a cons cell whose car (resp. cdr) is the
21658 position before START-RE (resp. after END-RE)."
21659 (save-match-data
21660 (let ((pos (point))
21661 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21662 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21663 beg end)
21664 (save-excursion
21665 ;; Point is on a block when on START-RE or if START-RE can be
21666 ;; found before it...
21667 (and (or (org-at-regexp-p start-re)
21668 (re-search-backward start-re limit-up t))
21669 (setq beg (match-beginning 0))
21670 ;; ... and END-RE after it...
21671 (goto-char (match-end 0))
21672 (re-search-forward end-re limit-down t)
21673 (> (setq end (match-end 0)) pos)
21674 ;; ... without another START-RE in-between.
21675 (goto-char (match-beginning 0))
21676 (not (re-search-backward start-re (1+ beg) t))
21677 ;; Return value.
21678 (cons beg end))))))
21680 (defun org-in-block-p (names)
21681 "Non-nil when point belongs to a block whose name belongs to NAMES.
21683 NAMES is a list of strings containing names of blocks.
21685 Return first block name matched, or nil. Beware that in case of
21686 nested blocks, the returned name may not belong to the closest
21687 block from point."
21688 (save-match-data
21689 (catch 'exit
21690 (let ((case-fold-search t)
21691 (lim-up (save-excursion (outline-previous-heading)))
21692 (lim-down (save-excursion (outline-next-heading))))
21693 (mapc (lambda (name)
21694 (let ((n (regexp-quote name)))
21695 (when (org-between-regexps-p
21696 (concat "^[ \t]*#\\+begin_" n)
21697 (concat "^[ \t]*#\\+end_" n)
21698 lim-up lim-down)
21699 (throw 'exit n))))
21700 names))
21701 nil)))
21703 (defun org-in-drawer-p ()
21704 "Is point within a drawer?"
21705 (save-match-data
21706 (let ((case-fold-search t)
21707 (lim-up (save-excursion (outline-previous-heading)))
21708 (lim-down (save-excursion (outline-next-heading))))
21709 (org-between-regexps-p
21710 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21711 "^[ \t]*:end:.*$"
21712 lim-up lim-down))))
21714 (defun org-occur-in-agenda-files (regexp &optional nlines)
21715 "Call `multi-occur' with buffers for all agenda files."
21716 (interactive "sOrg-files matching: \np")
21717 (let* ((files (org-agenda-files))
21718 (tnames (mapcar 'file-truename files))
21719 (extra org-agenda-text-search-extra-files)
21721 (when (eq (car extra) 'agenda-archives)
21722 (setq extra (cdr extra))
21723 (setq files (org-add-archive-files files)))
21724 (while (setq f (pop extra))
21725 (unless (member (file-truename f) tnames)
21726 (add-to-list 'files f 'append)
21727 (add-to-list 'tnames (file-truename f) 'append)))
21728 (multi-occur
21729 (mapcar (lambda (x)
21730 (with-current-buffer
21731 (or (get-file-buffer x) (find-file-noselect x))
21732 (widen)
21733 (current-buffer)))
21734 files)
21735 regexp)))
21737 (if (boundp 'occur-mode-find-occurrence-hook)
21738 ;; Emacs 23
21739 (add-hook 'occur-mode-find-occurrence-hook
21740 (lambda ()
21741 (when (derived-mode-p 'org-mode)
21742 (org-reveal))))
21743 ;; Emacs 22
21744 (defadvice occur-mode-goto-occurrence
21745 (after org-occur-reveal activate)
21746 (and (derived-mode-p 'org-mode) (org-reveal)))
21747 (defadvice occur-mode-goto-occurrence-other-window
21748 (after org-occur-reveal activate)
21749 (and (derived-mode-p 'org-mode) (org-reveal)))
21750 (defadvice occur-mode-display-occurrence
21751 (after org-occur-reveal activate)
21752 (when (derived-mode-p 'org-mode)
21753 (let ((pos (occur-mode-find-occurrence)))
21754 (with-current-buffer (marker-buffer pos)
21755 (save-excursion
21756 (goto-char pos)
21757 (org-reveal)))))))
21759 (defun org-occur-link-in-agenda-files ()
21760 "Create a link and search for it in the agendas.
21761 The link is not stored in `org-stored-links', it is just created
21762 for the search purpose."
21763 (interactive)
21764 (let ((link (condition-case nil
21765 (org-store-link nil)
21766 (error "Unable to create a link to here"))))
21767 (org-occur-in-agenda-files (regexp-quote link))))
21769 (defun org-reverse-string (string)
21770 "Return the reverse of STRING."
21771 (apply 'string (reverse (string-to-list string))))
21773 (defsubst org-uniquify (list)
21774 "Non-destructively remove duplicate elements from LIST."
21775 (let ((res (copy-sequence list))) (delete-dups res)))
21777 (defun org-uniquify-alist (alist)
21778 "Merge elements of ALIST with the same key.
21780 For example, in this alist:
21782 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21783 => '((a 1 3) (b 2))
21785 merge (a 1) and (a 3) into (a 1 3).
21787 The function returns the new ALIST."
21788 (let (rtn)
21789 (mapc
21790 (lambda (e)
21791 (let (n)
21792 (if (not (assoc (car e) rtn))
21793 (push e rtn)
21794 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21795 (setq rtn (assq-delete-all (car e) rtn))
21796 (push n rtn))))
21797 alist)
21798 rtn))
21800 (defun org-delete-all (elts list)
21801 "Remove all elements in ELTS from LIST."
21802 (while elts
21803 (setq list (delete (pop elts) list)))
21804 list)
21806 (defun org-count (cl-item cl-seq)
21807 "Count the number of occurrences of ITEM in SEQ.
21808 Taken from `count' in cl-seq.el with all keyword arguments removed."
21809 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21810 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21811 (while (< cl-start cl-end)
21812 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21813 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21814 (setq cl-start (1+ cl-start)))
21815 cl-count))
21817 (defun org-remove-if (predicate seq)
21818 "Remove everything from SEQ that fulfills PREDICATE."
21819 (let (res e)
21820 (while seq
21821 (setq e (pop seq))
21822 (if (not (funcall predicate e)) (push e res)))
21823 (nreverse res)))
21825 (defun org-remove-if-not (predicate seq)
21826 "Remove everything from SEQ that does not fulfill PREDICATE."
21827 (let (res e)
21828 (while seq
21829 (setq e (pop seq))
21830 (if (funcall predicate e) (push e res)))
21831 (nreverse res)))
21833 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21834 "Reduce two-argument FUNCTION across SEQ.
21835 Taken from `reduce' in cl-seq.el with all keyword arguments but
21836 \":initial-value\" removed."
21837 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21838 (cadr (memq :initial-value cl-keys)))
21839 (cl-seq (pop cl-seq))
21840 (t (funcall cl-func)))))
21841 (while cl-seq
21842 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21843 cl-accum))
21845 (defun org-every (pred seq)
21846 "Return true if PREDICATE is true of every element of SEQ.
21847 Adapted from `every' in cl.el."
21848 (catch 'org-every
21849 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21852 (defun org-some (pred seq)
21853 "Return true if PREDICATE is true of any element of SEQ.
21854 Adapted from `some' in cl.el."
21855 (catch 'org-some
21856 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21857 nil))
21859 (defun org-back-over-empty-lines ()
21860 "Move backwards over whitespace, to the beginning of the first empty line.
21861 Returns the number of empty lines passed."
21862 (let ((pos (point)))
21863 (if (cdr (assoc 'heading org-blank-before-new-entry))
21864 (skip-chars-backward " \t\n\r")
21865 (unless (eobp)
21866 (forward-line -1)))
21867 (beginning-of-line 2)
21868 (goto-char (min (point) pos))
21869 (count-lines (point) pos)))
21871 (defun org-skip-whitespace ()
21872 (skip-chars-forward " \t\n\r"))
21874 (defun org-point-in-group (point group &optional context)
21875 "Check if POINT is in match-group GROUP.
21876 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21877 match. If the match group does not exist or point is not inside it,
21878 return nil."
21879 (and (match-beginning group)
21880 (>= point (match-beginning group))
21881 (<= point (match-end group))
21882 (if context
21883 (list context (match-beginning group) (match-end group))
21884 t)))
21886 (defun org-switch-to-buffer-other-window (&rest args)
21887 "Switch to buffer in a second window on the current frame.
21888 In particular, do not allow pop-up frames.
21889 Returns the newly created buffer."
21890 (org-no-popups
21891 (apply 'switch-to-buffer-other-window args)))
21893 (defun org-combine-plists (&rest plists)
21894 "Create a single property list from all plists in PLISTS.
21895 The process starts by copying the first list, and then setting properties
21896 from the other lists. Settings in the last list are the most significant
21897 ones and overrule settings in the other lists."
21898 (let ((rtn (copy-sequence (pop plists)))
21899 p v ls)
21900 (while plists
21901 (setq ls (pop plists))
21902 (while ls
21903 (setq p (pop ls) v (pop ls))
21904 (setq rtn (plist-put rtn p v))))
21905 rtn))
21907 (defun org-replace-escapes (string table)
21908 "Replace %-escapes in STRING with values in TABLE.
21909 TABLE is an association list with keys like \"%a\" and string values.
21910 The sequences in STRING may contain normal field width and padding information,
21911 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21912 so values can contain further %-escapes if they are define later in TABLE."
21913 (let ((tbl (copy-alist table))
21914 (case-fold-search nil)
21915 (pchg 0)
21916 e re rpl)
21917 (while (setq e (pop tbl))
21918 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21919 (when (and (cdr e) (string-match re (cdr e)))
21920 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21921 (safe "SREF"))
21922 (add-text-properties 0 3 (list 'sref sref) safe)
21923 (setcdr e (replace-match safe t t (cdr e)))))
21924 (while (string-match re string)
21925 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21926 (cdr e)))
21927 (setq string (replace-match rpl t t string))))
21928 (while (setq pchg (next-property-change pchg string))
21929 (let ((sref (get-text-property pchg 'sref string)))
21930 (when (and sref (string-match "SREF" string pchg))
21931 (setq string (replace-match sref t t string)))))
21932 string))
21934 (defun org-sublist (list start end)
21935 "Return a section of LIST, from START to END.
21936 Counting starts at 1."
21937 (let (rtn (c start))
21938 (setq list (nthcdr (1- start) list))
21939 (while (and list (<= c end))
21940 (push (pop list) rtn)
21941 (setq c (1+ c)))
21942 (nreverse rtn)))
21944 (defun org-find-base-buffer-visiting (file)
21945 "Like `find-buffer-visiting' but always return the base buffer and
21946 not an indirect buffer."
21947 (let ((buf (or (get-file-buffer file)
21948 (find-buffer-visiting file))))
21949 (if buf
21950 (or (buffer-base-buffer buf) buf)
21951 nil)))
21953 (defun org-image-file-name-regexp (&optional extensions)
21954 "Return regexp matching the file names of images.
21955 If EXTENSIONS is given, only match these."
21956 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21957 (image-file-name-regexp)
21958 (let ((image-file-name-extensions
21959 (or extensions
21960 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21961 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21962 (concat "\\."
21963 (regexp-opt (nconc (mapcar 'upcase
21964 image-file-name-extensions)
21965 image-file-name-extensions)
21967 "\\'"))))
21969 (defun org-file-image-p (file &optional extensions)
21970 "Return non-nil if FILE is an image."
21971 (save-match-data
21972 (string-match (org-image-file-name-regexp extensions) file)))
21974 (defun org-get-cursor-date (&optional with-time)
21975 "Return the date at cursor in as a time.
21976 This works in the calendar and in the agenda, anywhere else it just
21977 returns the current time.
21978 If WITH-TIME is non-nil, returns the time of the event at point (in
21979 the agenda) or the current time of the day."
21980 (let (date day defd tp tm hod mod)
21981 (when with-time
21982 (setq tp (get-text-property (point) 'time))
21983 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21984 (setq hod (string-to-number (match-string 1 tp))
21985 mod (string-to-number (match-string 2 tp))))
21986 (or tp (setq hod (nth 2 (decode-time (current-time)))
21987 mod (nth 1 (decode-time (current-time))))))
21988 (cond
21989 ((eq major-mode 'calendar-mode)
21990 (setq date (calendar-cursor-to-date)
21991 defd (encode-time 0 (or mod 0) (or hod 0)
21992 (nth 1 date) (nth 0 date) (nth 2 date))))
21993 ((eq major-mode 'org-agenda-mode)
21994 (setq day (get-text-property (point) 'day))
21995 (if day
21996 (setq date (calendar-gregorian-from-absolute day)
21997 defd (encode-time 0 (or mod 0) (or hod 0)
21998 (nth 1 date) (nth 0 date) (nth 2 date))))))
21999 (or defd (current-time))))
22001 (defun org-mark-subtree (&optional up)
22002 "Mark the current subtree.
22003 This puts point at the start of the current subtree, and mark at
22004 the end. If a numeric prefix UP is given, move up into the
22005 hierarchy of headlines by UP levels before marking the subtree."
22006 (interactive "P")
22007 (org-with-limited-levels
22008 (cond ((org-at-heading-p) (beginning-of-line))
22009 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22010 (t (outline-previous-visible-heading 1))))
22011 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22012 (if (org-called-interactively-p 'any)
22013 (call-interactively 'org-mark-element)
22014 (org-mark-element)))
22017 ;;; Indentation
22019 (defun org-indent-line ()
22020 "Indent line depending on context."
22021 (interactive)
22022 (let* ((pos (point))
22023 (itemp (org-at-item-p))
22024 (case-fold-search t)
22025 (org-drawer-regexp (or org-drawer-regexp "\000"))
22026 (inline-task-p (and (featurep 'org-inlinetask)
22027 (org-inlinetask-in-task-p)))
22028 (inline-re (and inline-task-p
22029 (org-inlinetask-outline-regexp)))
22030 column)
22031 (if (and orgstruct-is-++ (eq pos (point)))
22032 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22033 (indent-according-to-mode))
22034 (beginning-of-line 1)
22035 (cond
22036 ;; Headings
22037 ((looking-at org-outline-regexp) (setq column 0))
22038 ;; Footnote definition
22039 ((looking-at org-footnote-definition-re) (setq column 0))
22040 ;; Literal examples
22041 ((looking-at "[ \t]*:\\( \\|$\\)")
22042 (setq column (org-get-indentation))) ; do nothing
22043 ;; Lists
22044 ((ignore-errors (goto-char (org-in-item-p)))
22045 (setq column (if itemp
22046 (org-get-indentation)
22047 (org-list-item-body-column (point))))
22048 (goto-char pos))
22049 ;; Drawers
22050 ((and (looking-at "[ \t]*:END:")
22051 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22052 (save-excursion
22053 (goto-char (1- (match-beginning 1)))
22054 (setq column (current-column))))
22055 ;; Special blocks
22056 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22057 (save-excursion
22058 (re-search-backward
22059 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22060 (setq column (org-get-indentation (match-string 0))))
22061 ((and (not (looking-at "[ \t]*#\\+begin_"))
22062 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22063 (save-excursion
22064 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22065 (setq column
22066 (cond ((equal (downcase (match-string 1)) "src")
22067 ;; src blocks: let `org-edit-src-exit' handle them
22068 (org-get-indentation))
22069 ((equal (downcase (match-string 1)) "example")
22070 (max (org-get-indentation)
22071 (org-get-indentation (match-string 0))))
22073 (org-get-indentation (match-string 0))))))
22074 ;; This line has nothing special, look at the previous relevant
22075 ;; line to compute indentation
22077 (beginning-of-line 0)
22078 (while (and (not (bobp))
22079 (not (looking-at org-table-line-regexp))
22080 (not (looking-at org-drawer-regexp))
22081 ;; When point started in an inline task, do not move
22082 ;; above task starting line.
22083 (not (and inline-task-p (looking-at inline-re)))
22084 ;; Skip drawers, blocks, empty lines, verbatim,
22085 ;; comments, tables, footnotes definitions, lists,
22086 ;; inline tasks.
22087 (or (and (looking-at "[ \t]*:END:")
22088 (re-search-backward org-drawer-regexp nil t))
22089 (and (looking-at "[ \t]*#\\+end_")
22090 (re-search-backward "[ \t]*#\\+begin_"nil t))
22091 (looking-at "[ \t]*[\n:#|]")
22092 (looking-at org-footnote-definition-re)
22093 (and (not inline-task-p)
22094 (featurep 'org-inlinetask)
22095 (org-inlinetask-in-task-p)
22096 (or (org-inlinetask-goto-beginning) t))))
22097 (beginning-of-line 0))
22098 (cond
22099 ;; There was a list item above.
22100 ((ignore-errors (goto-char (org-in-item-p)))
22101 (goto-char (org-list-get-top-point (org-list-struct)))
22102 (setq column (org-get-indentation)))
22103 ;; There was an heading above.
22104 ((looking-at "\\*+[ \t]+")
22105 (if (not org-adapt-indentation)
22106 (setq column 0)
22107 (goto-char (match-end 0))
22108 (setq column (current-column))))
22109 ;; A drawer had started and is unfinished
22110 ((looking-at org-drawer-regexp)
22111 (goto-char (1- (match-beginning 1)))
22112 (setq column (current-column)))
22113 ;; Else, nothing noticeable found: get indentation and go on.
22114 (t (setq column (org-get-indentation))))))
22115 ;; Now apply indentation and move cursor accordingly
22116 (goto-char pos)
22117 (if (<= (current-column) (current-indentation))
22118 (org-indent-line-to column)
22119 (save-excursion (org-indent-line-to column)))
22120 ;; Special polishing for properties, see `org-property-format'
22121 (setq column (current-column))
22122 (beginning-of-line 1)
22123 (if (looking-at org-property-re)
22124 (replace-match (concat (match-string 4)
22125 (format org-property-format
22126 (match-string 1) (match-string 3)))
22127 t t))
22128 (org-move-to-column column))))
22130 (defun org-indent-drawer ()
22131 "Indent the drawer at point."
22132 (interactive)
22133 (let ((p (point))
22134 (e (and (save-excursion (re-search-forward ":END:" nil t))
22135 (match-end 0)))
22136 (folded
22137 (save-excursion
22138 (end-of-line)
22139 (when (overlays-at (point))
22140 (member 'invisible (overlay-properties
22141 (car (overlays-at (point)))))))))
22142 (when folded (org-cycle))
22143 (indent-for-tab-command)
22144 (while (and (move-beginning-of-line 2) (< (point) e))
22145 (indent-for-tab-command))
22146 (goto-char p)
22147 (when folded (org-cycle)))
22148 (message "Drawer at point indented"))
22150 (defun org-indent-block ()
22151 "Indent the block at point."
22152 (interactive)
22153 (let ((p (point))
22154 (case-fold-search t)
22155 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22156 (match-end 0)))
22157 (folded
22158 (save-excursion
22159 (end-of-line)
22160 (when (overlays-at (point))
22161 (member 'invisible (overlay-properties
22162 (car (overlays-at (point)))))))))
22163 (when folded (org-cycle))
22164 (indent-for-tab-command)
22165 (while (and (move-beginning-of-line 2) (< (point) e))
22166 (indent-for-tab-command))
22167 (goto-char p)
22168 (when folded (org-cycle)))
22169 (message "Block at point indented"))
22171 (defun org-indent-region (start end)
22172 "Indent region."
22173 (interactive "r")
22174 (save-excursion
22175 (let ((line-end (org-current-line end)))
22176 (goto-char start)
22177 (while (< (org-current-line) line-end)
22178 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22179 (t (call-interactively 'org-indent-line)))
22180 (move-beginning-of-line 2)))))
22183 ;;; Filling
22185 ;; We use our own fill-paragraph and auto-fill functions.
22187 ;; `org-fill-paragraph' relies on adaptive filling and context
22188 ;; checking. Appropriate `fill-prefix' is computed with
22189 ;; `org-adaptive-fill-function'.
22191 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22192 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22193 ;; `org-adaptive-fill-function' value. Internally,
22194 ;; `org-comment-line-break-function' breaks the line.
22196 ;; `org-setup-filling' installs filling and auto-filling related
22197 ;; variables during `org-mode' initialization.
22199 (defvar org-element-paragraph-separate) ; org-element.el
22200 (defun org-setup-filling ()
22201 (require 'org-element)
22202 ;; Prevent auto-fill from inserting unwanted new items.
22203 (when (boundp 'fill-nobreak-predicate)
22204 (org-set-local
22205 'fill-nobreak-predicate
22206 (org-uniquify
22207 (append fill-nobreak-predicate
22208 '(org-fill-line-break-nobreak-p
22209 org-fill-paragraph-with-timestamp-nobreak-p)))))
22210 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22211 (org-set-local 'paragraph-start paragraph-ending)
22212 (org-set-local 'paragraph-separate paragraph-ending))
22213 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22214 (org-set-local 'auto-fill-inhibit-regexp nil)
22215 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22216 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22217 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22219 (defun org-fill-line-break-nobreak-p ()
22220 "Non-nil when a new line at point would create an Org line break."
22221 (save-excursion
22222 (skip-chars-backward "[ \t]")
22223 (skip-chars-backward "\\\\")
22224 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22226 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22227 "Non-nil when a new line at point would split a timestamp."
22228 (and (org-at-timestamp-p t)
22229 (not (looking-at org-ts-regexp-both))))
22231 (declare-function message-in-body-p "message" ())
22232 (defvar orgtbl-line-start-regexp) ; From org-table.el
22233 (defun org-adaptive-fill-function ()
22234 "Compute a fill prefix for the current line.
22235 Return fill prefix, as a string, or nil if current line isn't
22236 meant to be filled. For convenience, if `adaptive-fill-regexp'
22237 matches in paragraphs or comments, use it."
22238 (catch 'exit
22239 (when (derived-mode-p 'message-mode)
22240 (save-excursion
22241 (beginning-of-line)
22242 (cond ((or (not (message-in-body-p))
22243 (looking-at orgtbl-line-start-regexp))
22244 (throw 'exit nil))
22245 ((looking-at message-cite-prefix-regexp)
22246 (throw 'exit (match-string-no-properties 0)))
22247 ((looking-at org-outline-regexp)
22248 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22249 (org-with-wide-buffer
22250 (let* ((p (line-beginning-position))
22251 (element (save-excursion
22252 (beginning-of-line)
22253 (or (ignore-errors (org-element-at-point))
22254 (user-error "An element cannot be parsed line %d"
22255 (line-number-at-pos (point))))))
22256 (type (org-element-type element))
22257 (post-affiliated (org-element-property :post-affiliated element)))
22258 (unless (and post-affiliated (< p post-affiliated))
22259 (case type
22260 (comment
22261 (save-excursion
22262 (beginning-of-line)
22263 (looking-at "[ \t]*")
22264 (concat (match-string 0) "# ")))
22265 (footnote-definition "")
22266 ((item plain-list)
22267 (make-string (org-list-item-body-column
22268 (or post-affiliated
22269 (org-element-property :begin element)))
22270 ? ))
22271 (paragraph
22272 ;; Fill prefix is usually the same as the current line,
22273 ;; unless the paragraph is at the beginning of an item.
22274 (let ((parent (org-element-property :parent element)))
22275 (save-excursion
22276 (beginning-of-line)
22277 (cond ((eq (org-element-type parent) 'item)
22278 (make-string (org-list-item-body-column
22279 (org-element-property :begin parent))
22280 ? ))
22281 ((and adaptive-fill-regexp
22282 ;; Locally disable
22283 ;; `adaptive-fill-function' to let
22284 ;; `fill-context-prefix' handle
22285 ;; `adaptive-fill-regexp' variable.
22286 (let (adaptive-fill-function)
22287 (fill-context-prefix
22288 post-affiliated
22289 (org-element-property :end element)))))
22290 ((looking-at "[ \t]+") (match-string 0))
22291 (t "")))))
22292 (comment-block
22293 ;; Only fill contents if P is within block boundaries.
22294 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22295 (forward-line)
22296 (point)))
22297 (cend (save-excursion
22298 (goto-char (org-element-property :end element))
22299 (skip-chars-backward " \r\t\n")
22300 (line-beginning-position))))
22301 (when (and (>= p cbeg) (< p cend))
22302 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22303 (match-string 0)
22304 ""))))))))))
22306 (declare-function message-goto-body "message" ())
22307 (defvar message-cite-prefix-regexp) ; From message.el
22308 (defun org-fill-paragraph (&optional justify)
22309 "Fill element at point, when applicable.
22311 This function only applies to comment blocks, comments, example
22312 blocks and paragraphs. Also, as a special case, re-align table
22313 when point is at one.
22315 If JUSTIFY is non-nil (interactively, with prefix argument),
22316 justify as well. If `sentence-end-double-space' is non-nil, then
22317 period followed by one space does not end a sentence, so don't
22318 break a line there. The variable `fill-column' controls the
22319 width for filling.
22321 For convenience, when point is at a plain list, an item or
22322 a footnote definition, try to fill the first paragraph within."
22323 (interactive)
22324 (if (and (derived-mode-p 'message-mode)
22325 (or (not (message-in-body-p))
22326 (save-excursion (move-beginning-of-line 1)
22327 (looking-at message-cite-prefix-regexp))))
22328 ;; First ensure filling is correct in message-mode.
22329 (let ((fill-paragraph-function
22330 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22331 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22332 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22333 (paragraph-separate
22334 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22335 (fill-paragraph nil))
22336 (with-syntax-table org-mode-transpose-word-syntax-table
22337 ;; Move to end of line in order to get the first paragraph
22338 ;; within a plain list or a footnote definition.
22339 (let ((element (save-excursion
22340 (end-of-line)
22341 (or (ignore-errors (org-element-at-point))
22342 (user-error "An element cannot be parsed line %d"
22343 (line-number-at-pos (point)))))))
22344 ;; First check if point is in a blank line at the beginning of
22345 ;; the buffer. In that case, ignore filling.
22346 (case (org-element-type element)
22347 ;; Use major mode filling function is src blocks.
22348 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22349 ;; Align Org tables, leave table.el tables as-is.
22350 (table-row (org-table-align) t)
22351 (table
22352 (when (eq (org-element-property :type element) 'org)
22353 (save-excursion
22354 (goto-char (org-element-property :post-affiliated element))
22355 (org-table-align)))
22357 (paragraph
22358 ;; Paragraphs may contain `line-break' type objects.
22359 (let ((beg (max (point-min)
22360 (org-element-property :contents-begin element)))
22361 (end (min (point-max)
22362 (org-element-property :contents-end element))))
22363 ;; Do nothing if point is at an affiliated keyword.
22364 (if (< (line-end-position) beg) t
22365 (when (derived-mode-p 'message-mode)
22366 ;; In `message-mode', do not fill following citation
22367 ;; in current paragraph nor text before message body.
22368 (let ((body-start (save-excursion (message-goto-body))))
22369 (when body-start (setq beg (max body-start beg))))
22370 (when (save-excursion
22371 (re-search-forward
22372 (concat "^" message-cite-prefix-regexp) end t))
22373 (setq end (match-beginning 0))))
22374 ;; Fill paragraph, taking line breaks into account.
22375 ;; For that, slice the paragraph using line breaks as
22376 ;; separators, and fill the parts in reverse order to
22377 ;; avoid messing with markers.
22378 (save-excursion
22379 (goto-char end)
22380 (mapc
22381 (lambda (pos)
22382 (fill-region-as-paragraph pos (point) justify)
22383 (goto-char pos))
22384 ;; Find the list of ending positions for line breaks
22385 ;; in the current paragraph. Add paragraph
22386 ;; beginning to include first slice.
22387 (nreverse
22388 (cons beg
22389 (org-element-map
22390 (org-element--parse-objects
22391 beg end nil (org-element-restriction 'paragraph))
22392 'line-break
22393 (lambda (lb) (org-element-property :end lb)))))))
22394 t)))
22395 ;; Contents of `comment-block' type elements should be
22396 ;; filled as plain text, but only if point is within block
22397 ;; markers.
22398 (comment-block
22399 (let* ((case-fold-search t)
22400 (beg (save-excursion
22401 (goto-char (org-element-property :begin element))
22402 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22403 (forward-line)
22404 (point)))
22405 (end (save-excursion
22406 (goto-char (org-element-property :end element))
22407 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22408 (line-beginning-position))))
22409 (if (or (< (point) beg) (> (point) end)) t
22410 (fill-region-as-paragraph
22411 (save-excursion (end-of-line)
22412 (re-search-backward "^[ \t]*$" beg 'move)
22413 (line-beginning-position))
22414 (save-excursion (beginning-of-line)
22415 (re-search-forward "^[ \t]*$" end 'move)
22416 (line-beginning-position))
22417 justify))))
22418 ;; Fill comments.
22419 (comment
22420 (let ((begin (org-element-property :post-affiliated element))
22421 (end (org-element-property :end element)))
22422 (when (and (>= (point) begin) (<= (point) end))
22423 (let ((begin (save-excursion
22424 (end-of-line)
22425 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22426 (progn (forward-line) (point))
22427 begin)))
22428 (end (save-excursion
22429 (end-of-line)
22430 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22431 (1- (line-beginning-position))
22432 (skip-chars-backward " \r\t\n")
22433 (line-end-position)))))
22434 ;; Do not fill comments when at a blank line.
22435 (when (> end begin)
22436 (let ((fill-prefix
22437 (save-excursion
22438 (beginning-of-line)
22439 (looking-at "[ \t]*#")
22440 (let ((comment-prefix (match-string 0)))
22441 (goto-char (match-end 0))
22442 (if (looking-at adaptive-fill-regexp)
22443 (concat comment-prefix (match-string 0))
22444 (concat comment-prefix " "))))))
22445 (save-excursion
22446 (fill-region-as-paragraph begin end justify))))))
22448 ;; Ignore every other element.
22449 (otherwise t))))))
22451 (defun org-auto-fill-function ()
22452 "Auto-fill function."
22453 ;; Check if auto-filling is meaningful.
22454 (let ((fc (current-fill-column)))
22455 (when (and fc (> (current-column) fc))
22456 (let* ((fill-prefix (org-adaptive-fill-function))
22457 ;; Enforce empty fill prefix, if required. Otherwise, it
22458 ;; will be computed again.
22459 (adaptive-fill-mode (not (equal fill-prefix ""))))
22460 (when fill-prefix (do-auto-fill))))))
22462 (defun org-comment-line-break-function (&optional soft)
22463 "Break line at point and indent, continuing comment if within one.
22464 The inserted newline is marked hard if variable
22465 `use-hard-newlines' is true, unless optional argument SOFT is
22466 non-nil."
22467 (if soft (insert-and-inherit ?\n) (newline 1))
22468 (save-excursion (forward-char -1) (delete-horizontal-space))
22469 (delete-horizontal-space)
22470 (indent-to-left-margin)
22471 (insert-before-markers-and-inherit fill-prefix))
22474 ;;; Comments
22476 ;; Org comments syntax is quite complex. It requires the entire line
22477 ;; to be just a comment. Also, even with the right syntax at the
22478 ;; beginning of line, some some elements (i.e. verse-block or
22479 ;; example-block) don't accept comments. Usual Emacs comment commands
22480 ;; cannot cope with those requirements. Therefore, Org replaces them.
22482 ;; Org still relies on `comment-dwim', but cannot trust
22483 ;; `comment-only-p'. So, `comment-region-function' and
22484 ;; `uncomment-region-function' both point
22485 ;; to`org-comment-or-uncomment-region'. Eventually,
22486 ;; `org-insert-comment' takes care of insertion of comments at the
22487 ;; beginning of line.
22489 ;; `org-setup-comments-handling' install comments related variables
22490 ;; during `org-mode' initialization.
22492 (defun org-setup-comments-handling ()
22493 (interactive)
22494 (org-set-local 'comment-use-syntax nil)
22495 (org-set-local 'comment-start "# ")
22496 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22497 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22498 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22499 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22501 (defun org-insert-comment ()
22502 "Insert an empty comment above current line.
22503 If the line is empty, insert comment at its beginning."
22504 (beginning-of-line)
22505 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22506 (org-indent-line)
22507 (insert "# "))
22509 (defvar comment-empty-lines) ; From newcomment.el.
22510 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22511 "Comment or uncomment each non-blank line in the region.
22512 Uncomment each non-blank line between BEG and END if it only
22513 contains commented lines. Otherwise, comment them."
22514 (save-restriction
22515 ;; Restrict region
22516 (narrow-to-region (save-excursion (goto-char beg)
22517 (skip-chars-forward " \r\t\n" end)
22518 (line-beginning-position))
22519 (save-excursion (goto-char end)
22520 (skip-chars-backward " \r\t\n" beg)
22521 (line-end-position)))
22522 (let ((uncommentp
22523 ;; UNCOMMENTP is non-nil when every non blank line between
22524 ;; BEG and END is a comment.
22525 (save-excursion
22526 (goto-char (point-min))
22527 (while (and (not (eobp))
22528 (let ((element (org-element-at-point)))
22529 (and (eq (org-element-type element) 'comment)
22530 (goto-char (min (point-max)
22531 (org-element-property
22532 :end element)))))))
22533 (eobp))))
22534 (if uncommentp
22535 ;; Only blank lines and comments in region: uncomment it.
22536 (save-excursion
22537 (goto-char (point-min))
22538 (while (not (eobp))
22539 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22540 (replace-match "" nil nil nil 1))
22541 (forward-line)))
22542 ;; Comment each line in region.
22543 (let ((min-indent (point-max)))
22544 ;; First find the minimum indentation across all lines.
22545 (save-excursion
22546 (goto-char (point-min))
22547 (while (and (not (eobp)) (not (zerop min-indent)))
22548 (unless (looking-at "[ \t]*$")
22549 (setq min-indent (min min-indent (current-indentation))))
22550 (forward-line)))
22551 ;; Then loop over all lines.
22552 (save-excursion
22553 (goto-char (point-min))
22554 (while (not (eobp))
22555 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22556 ;; Don't get fooled by invisible text (e.g. link path)
22557 ;; when moving to column MIN-INDENT.
22558 (let ((buffer-invisibility-spec nil))
22559 (org-move-to-column min-indent t))
22560 (insert comment-start))
22561 (forward-line))))))))
22564 ;;; Planning
22566 ;; This section contains tools to operate on timestamp objects, as
22567 ;; returned by, e.g. `org-element-context'.
22569 (defun org-timestamp-has-time-p (timestamp)
22570 "Non-nil when TIMESTAMP has a time specified."
22571 (org-element-property :hour-start timestamp))
22573 (defun org-timestamp-format (timestamp format &optional end utc)
22574 "Format a TIMESTAMP element into a string.
22576 FORMAT is a format specifier to be passed to
22577 `format-time-string'.
22579 When optional argument END is non-nil, use end of date-range or
22580 time-range, if possible.
22582 When optional argument UTC is non-nil, time will be expressed as
22583 Universal Time."
22584 (format-time-string
22585 format
22586 (apply 'encode-time
22587 (cons 0
22588 (mapcar
22589 (lambda (prop) (or (org-element-property prop timestamp) 0))
22590 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22591 '(:minute-start :hour-start :day-start :month-start
22592 :year-start)))))
22593 utc))
22595 (defun org-timestamp-split-range (timestamp &optional end)
22596 "Extract a timestamp object from a date or time range.
22598 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22599 the end of the range. Otherwise, extract its start.
22601 Return a new timestamp object sharing the same parent as
22602 TIMESTAMP."
22603 (let ((type (org-element-property :type timestamp)))
22604 (if (memq type '(active inactive diary)) timestamp
22605 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22606 ;; Set new type.
22607 (org-element-put-property
22608 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22609 ;; Copy start properties over end properties if END is
22610 ;; non-nil. Otherwise, copy end properties over `start' ones.
22611 (let ((p-alist '((:minute-start . :minute-end)
22612 (:hour-start . :hour-end)
22613 (:day-start . :day-end)
22614 (:month-start . :month-end)
22615 (:year-start . :year-end))))
22616 (dolist (p-cell p-alist)
22617 (org-element-put-property
22618 split-ts
22619 (funcall (if end 'car 'cdr) p-cell)
22620 (org-element-property
22621 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22622 ;; Eventually refresh `:raw-value'.
22623 (org-element-put-property split-ts :raw-value nil)
22624 (org-element-put-property
22625 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22627 (defun org-timestamp-translate (timestamp &optional boundary)
22628 "Apply `org-translate-time' on a TIMESTAMP object.
22629 When optional argument BOUNDARY is non-nil, it is either the
22630 symbol `start' or `end'. In this case, only translate the
22631 starting or ending part of TIMESTAMP if it is a date or time
22632 range. Otherwise, translate both parts."
22633 (if (and (not boundary)
22634 (memq (org-element-property :type timestamp)
22635 '(active-range inactive-range)))
22636 (concat
22637 (org-translate-time
22638 (org-element-property :raw-value
22639 (org-timestamp-split-range timestamp)))
22640 "--"
22641 (org-translate-time
22642 (org-element-property :raw-value
22643 (org-timestamp-split-range timestamp t))))
22644 (org-translate-time
22645 (org-element-property
22646 :raw-value
22647 (if (not boundary) timestamp
22648 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22652 ;;; Other stuff.
22654 (defun org-toggle-fixed-width-section (arg)
22655 "Toggle the fixed-width export.
22656 If there is no active region, the QUOTE keyword at the current headline is
22657 inserted or removed. When present, it causes the text between this headline
22658 and the next to be exported as fixed-width text, and unmodified.
22659 If there is an active region, this command adds or removes a colon as the
22660 first character of this line. If the first character of a line is a colon,
22661 this line is also exported in fixed-width font."
22662 (interactive "P")
22663 (let* ((cc 0)
22664 (regionp (org-region-active-p))
22665 (beg (if regionp (region-beginning) (point)))
22666 (end (if regionp (region-end)))
22667 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22668 (case-fold-search nil)
22669 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22670 off)
22671 (if regionp
22672 (save-excursion
22673 (goto-char beg)
22674 (setq cc (current-column))
22675 (beginning-of-line 1)
22676 (setq off (looking-at re))
22677 (while (> nlines 0)
22678 (setq nlines (1- nlines))
22679 (beginning-of-line 1)
22680 (cond
22681 (arg
22682 (org-move-to-column cc t)
22683 (insert ": \n")
22684 (forward-line -1))
22685 ((and off (looking-at re))
22686 (replace-match "" t t nil 1))
22687 ((not off) (org-move-to-column cc t) (insert ": ")))
22688 (forward-line 1)))
22689 (save-excursion
22690 (org-back-to-heading)
22691 (cond
22692 ((looking-at (format org-heading-keyword-regexp-format
22693 org-quote-string))
22694 (goto-char (match-end 1))
22695 (looking-at (concat " +" org-quote-string))
22696 (replace-match "" t t)
22697 (when (eolp) (insert " ")))
22698 ((looking-at org-outline-regexp)
22699 (goto-char (match-end 0))
22700 (insert org-quote-string " ")))))))
22702 (defun org-reftex-citation ()
22703 "Use reftex-citation to insert a citation into the buffer.
22704 This looks for a line like
22706 #+BIBLIOGRAPHY: foo plain option:-d
22708 and derives from it that foo.bib is the bibliography file relevant
22709 for this document. It then installs the necessary environment for RefTeX
22710 to work in this buffer and calls `reftex-citation' to insert a citation
22711 into the buffer.
22713 Export of such citations to both LaTeX and HTML is handled by the contributed
22714 package ox-bibtex by Taru Karttunen."
22715 (interactive)
22716 (let ((reftex-docstruct-symbol 'rds)
22717 (reftex-cite-format "\\cite{%l}")
22718 rds bib)
22719 (save-excursion
22720 (save-restriction
22721 (widen)
22722 (let ((case-fold-search t)
22723 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22724 (if (not (save-excursion
22725 (or (re-search-forward re nil t)
22726 (re-search-backward re nil t))))
22727 (error "No bibliography defined in file")
22728 (setq bib (concat (match-string 1) ".bib")
22729 rds (list (list 'bib bib)))))))
22730 (call-interactively 'reftex-citation)))
22732 ;;;; Functions extending outline functionality
22734 (defun org-beginning-of-line (&optional arg)
22735 "Go to the beginning of the current line. If that is invisible, continue
22736 to a visible line beginning. This makes the function of C-a more intuitive.
22737 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22738 first attempt, and only move to after the tags when the cursor is already
22739 beyond the end of the headline."
22740 (interactive "P")
22741 (let ((pos (point))
22742 (special (if (consp org-special-ctrl-a/e)
22743 (car org-special-ctrl-a/e)
22744 org-special-ctrl-a/e))
22745 deactivate-mark refpos)
22746 (if (org-bound-and-true-p visual-line-mode)
22747 (beginning-of-visual-line 1)
22748 (beginning-of-line 1))
22749 (if (and arg (fboundp 'move-beginning-of-line))
22750 (call-interactively 'move-beginning-of-line)
22751 (if (bobp)
22753 (backward-char 1)
22754 (if (org-truely-invisible-p)
22755 (while (and (not (bobp)) (org-truely-invisible-p))
22756 (backward-char 1)
22757 (beginning-of-line 1))
22758 (forward-char 1))))
22759 (when special
22760 (cond
22761 ((and (looking-at org-complex-heading-regexp)
22762 (= (char-after (match-end 1)) ?\ ))
22763 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22764 (point-at-eol)))
22765 (goto-char
22766 (if (eq special t)
22767 (cond ((> pos refpos) refpos)
22768 ((= pos (point)) refpos)
22769 (t (point)))
22770 (cond ((> pos (point)) (point))
22771 ((not (eq last-command this-command)) (point))
22772 (t refpos)))))
22773 ((org-at-item-p)
22774 ;; Being at an item and not looking at an the item means point
22775 ;; was previously moved to beginning of a visual line, which
22776 ;; doesn't contain the item. Therefore, do nothing special,
22777 ;; just stay here.
22778 (when (looking-at org-list-full-item-re)
22779 ;; Set special position at first white space character after
22780 ;; bullet, and check-box, if any.
22781 (let ((after-bullet
22782 (let ((box (match-end 3)))
22783 (if (not box) (match-end 1)
22784 (let ((after (char-after box)))
22785 (if (and after (= after ? )) (1+ box) box))))))
22786 ;; Special case: Move point to special position when
22787 ;; currently after it or at beginning of line.
22788 (if (eq special t)
22789 (when (or (> pos after-bullet) (= (point) pos))
22790 (goto-char after-bullet))
22791 ;; Reversed case: Move point to special position when
22792 ;; point was already at beginning of line and command is
22793 ;; repeated.
22794 (when (and (= (point) pos) (eq last-command this-command))
22795 (goto-char after-bullet))))))))
22796 (org-no-warnings
22797 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22798 (setq disable-point-adjustment
22799 (or (not (invisible-p (point)))
22800 (not (invisible-p (max (point-min) (1- (point))))))))
22802 (defun org-end-of-line (&optional arg)
22803 "Go to the end of the line.
22804 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22805 tags on the first attempt, and only move to after the tags when
22806 the cursor is already beyond the end of the headline."
22807 (interactive "P")
22808 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22809 org-special-ctrl-a/e))
22810 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22811 'end-of-visual-line)
22812 ((fboundp 'move-end-of-line) 'move-end-of-line)
22813 (t 'end-of-line)))
22814 deactivate-mark)
22815 (if (or (not special) arg) (call-interactively move-fun)
22816 (let* ((element (save-excursion (beginning-of-line)
22817 (org-element-at-point)))
22818 (type (org-element-type element)))
22819 (cond
22820 ((memq type '(headline inlinetask))
22821 (let ((pos (point)))
22822 (beginning-of-line 1)
22823 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22824 (if (eq special t)
22825 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22826 (goto-char (match-beginning 1))
22827 (goto-char (match-end 0)))
22828 (if (or (< pos (match-end 0))
22829 (not (eq this-command last-command)))
22830 (goto-char (match-end 0))
22831 (goto-char (match-beginning 1))))
22832 (call-interactively move-fun))))
22833 ((org-element-property :hiddenp element)
22834 ;; If element is hidden, `move-end-of-line' would put point
22835 ;; after it. Use `end-of-line' to stay on current line.
22836 (call-interactively 'end-of-line))
22837 (t (call-interactively move-fun)))))
22838 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22839 (setq disable-point-adjustment
22840 (or (not (invisible-p (point)))
22841 (not (invisible-p (max (point-min) (1- (point))))))))
22843 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22844 (define-key org-mode-map "\C-e" 'org-end-of-line)
22846 (defun org-backward-sentence (&optional arg)
22847 "Go to beginning of sentence, or beginning of table field.
22848 This will call `backward-sentence' or `org-table-beginning-of-field',
22849 depending on context."
22850 (interactive "P")
22851 (cond
22852 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22853 (t (call-interactively 'backward-sentence))))
22855 (defun org-forward-sentence (&optional arg)
22856 "Go to end of sentence, or end of table field.
22857 This will call `forward-sentence' or `org-table-end-of-field',
22858 depending on context."
22859 (interactive "P")
22860 (cond
22861 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22862 (t (call-interactively 'forward-sentence))))
22864 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22865 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22867 (defun org-kill-line (&optional arg)
22868 "Kill line, to tags or end of line."
22869 (interactive "P")
22870 (cond
22871 ((or (not org-special-ctrl-k)
22872 (bolp)
22873 (not (org-at-heading-p)))
22874 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22875 org-ctrl-k-protect-subtree)
22876 (if (or (eq org-ctrl-k-protect-subtree 'error)
22877 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22878 (user-error "C-k aborted as it would kill a hidden subtree")))
22879 (call-interactively
22880 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22881 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22882 (kill-region (point) (match-beginning 1))
22883 (org-set-tags nil t))
22884 (t (kill-region (point) (point-at-eol)))))
22886 (define-key org-mode-map "\C-k" 'org-kill-line)
22888 (defun org-yank (&optional arg)
22889 "Yank. If the kill is a subtree, treat it specially.
22890 This command will look at the current kill and check if is a single
22891 subtree, or a series of subtrees[1]. If it passes the test, and if the
22892 cursor is at the beginning of a line or after the stars of a currently
22893 empty headline, then the yank is handled specially. How exactly depends
22894 on the value of the following variables, both set by default.
22896 org-yank-folded-subtrees
22897 When set, the subtree(s) will be folded after insertion, but only
22898 if doing so would now swallow text after the yanked text.
22900 org-yank-adjusted-subtrees
22901 When set, the subtree will be promoted or demoted in order to
22902 fit into the local outline tree structure, which means that the level
22903 will be adjusted so that it becomes the smaller one of the two
22904 *visible* surrounding headings.
22906 Any prefix to this command will cause `yank' to be called directly with
22907 no special treatment. In particular, a simple \\[universal-argument] prefix \
22908 will just
22909 plainly yank the text as it is.
22911 \[1] The test checks if the first non-white line is a heading
22912 and if there are no other headings with fewer stars."
22913 (interactive "P")
22914 (org-yank-generic 'yank arg))
22916 (defun org-yank-generic (command arg)
22917 "Perform some yank-like command.
22919 This function implements the behavior described in the `org-yank'
22920 documentation. However, it has been generalized to work for any
22921 interactive command with similar behavior."
22923 ;; pretend to be command COMMAND
22924 (setq this-command command)
22926 (if arg
22927 (call-interactively command)
22929 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22930 (and (org-kill-is-subtree-p)
22931 (or (bolp)
22932 (and (looking-at "[ \t]*$")
22933 (string-match
22934 "\\`\\*+\\'"
22935 (buffer-substring (point-at-bol) (point)))))))
22936 swallowp)
22937 (cond
22938 ((and subtreep org-yank-folded-subtrees)
22939 (let ((beg (point))
22940 end)
22941 (if (and subtreep org-yank-adjusted-subtrees)
22942 (org-paste-subtree nil nil 'for-yank)
22943 (call-interactively command))
22945 (setq end (point))
22946 (goto-char beg)
22947 (when (and (bolp) subtreep
22948 (not (setq swallowp
22949 (org-yank-folding-would-swallow-text beg end))))
22950 (org-with-limited-levels
22951 (or (looking-at org-outline-regexp)
22952 (re-search-forward org-outline-regexp-bol end t))
22953 (while (and (< (point) end) (looking-at org-outline-regexp))
22954 (hide-subtree)
22955 (org-cycle-show-empty-lines 'folded)
22956 (condition-case nil
22957 (outline-forward-same-level 1)
22958 (error (goto-char end))))))
22959 (when swallowp
22960 (message
22961 "Inserted text not folded because that would swallow text"))
22963 (goto-char end)
22964 (skip-chars-forward " \t\n\r")
22965 (beginning-of-line 1)
22966 (push-mark beg 'nomsg)))
22967 ((and subtreep org-yank-adjusted-subtrees)
22968 (let ((beg (point-at-bol)))
22969 (org-paste-subtree nil nil 'for-yank)
22970 (push-mark beg 'nomsg)))
22972 (call-interactively command))))))
22974 (defun org-yank-folding-would-swallow-text (beg end)
22975 "Would hide-subtree at BEG swallow any text after END?"
22976 (let (level)
22977 (org-with-limited-levels
22978 (save-excursion
22979 (goto-char beg)
22980 (when (or (looking-at org-outline-regexp)
22981 (re-search-forward org-outline-regexp-bol end t))
22982 (setq level (org-outline-level)))
22983 (goto-char end)
22984 (skip-chars-forward " \t\r\n\v\f")
22985 (if (or (eobp)
22986 (and (bolp) (looking-at org-outline-regexp)
22987 (<= (org-outline-level) level)))
22988 nil ; Nothing would be swallowed
22989 t))))) ; something would swallow
22991 (define-key org-mode-map "\C-y" 'org-yank)
22993 (defun org-truely-invisible-p ()
22994 "Check if point is at a character currently not visible.
22995 This version does not only check the character property, but also
22996 `visible-mode'."
22997 ;; Early versions of noutline don't have `outline-invisible-p'.
22998 (if (org-bound-and-true-p visible-mode)
23000 (outline-invisible-p)))
23002 (defun org-invisible-p2 ()
23003 "Check if point is at a character currently not visible."
23004 (save-excursion
23005 (if (and (eolp) (not (bobp))) (backward-char 1))
23006 ;; Early versions of noutline don't have `outline-invisible-p'.
23007 (outline-invisible-p)))
23009 (defun org-back-to-heading (&optional invisible-ok)
23010 "Call `outline-back-to-heading', but provide a better error message."
23011 (condition-case nil
23012 (outline-back-to-heading invisible-ok)
23013 (error (error "Before first headline at position %d in buffer %s"
23014 (point) (current-buffer)))))
23016 (defun org-before-first-heading-p ()
23017 "Before first heading?"
23018 (save-excursion
23019 (end-of-line)
23020 (null (re-search-backward org-outline-regexp-bol nil t))))
23022 (defun org-at-heading-p (&optional ignored)
23023 (outline-on-heading-p t))
23024 ;; Compatibility alias with Org versions < 7.8.03
23025 (defalias 'org-on-heading-p 'org-at-heading-p)
23027 (defun org-at-comment-p nil
23028 "Is cursor in a line starting with a # character?"
23029 (save-excursion
23030 (beginning-of-line)
23031 (looking-at "^#")))
23033 (defun org-at-drawer-p nil
23034 "Is cursor at a drawer keyword?"
23035 (save-excursion
23036 (move-beginning-of-line 1)
23037 (looking-at org-drawer-regexp)))
23039 (defun org-at-block-p nil
23040 "Is cursor at a block keyword?"
23041 (save-excursion
23042 (move-beginning-of-line 1)
23043 (looking-at org-block-regexp)))
23045 (defun org-point-at-end-of-empty-headline ()
23046 "If point is at the end of an empty headline, return t, else nil.
23047 If the heading only contains a TODO keyword, it is still still considered
23048 empty."
23049 (and (looking-at "[ \t]*$")
23050 (when org-todo-line-regexp
23051 (save-excursion
23052 (beginning-of-line 1)
23053 (let ((case-fold-search nil))
23054 (looking-at org-todo-line-regexp)
23055 (string= (match-string 3) ""))))))
23057 (defun org-at-heading-or-item-p ()
23058 (or (org-at-heading-p) (org-at-item-p)))
23060 (defun org-at-target-p ()
23061 (or (org-in-regexp org-radio-target-regexp)
23062 (org-in-regexp org-target-regexp)))
23063 ;; Compatibility alias with Org versions < 7.8.03
23064 (defalias 'org-on-target-p 'org-at-target-p)
23066 (defun org-up-heading-all (arg)
23067 "Move to the heading line of which the present line is a subheading.
23068 This function considers both visible and invisible heading lines.
23069 With argument, move up ARG levels."
23070 (if (fboundp 'outline-up-heading-all)
23071 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23072 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23074 (defun org-up-heading-safe ()
23075 "Move to the heading line of which the present line is a subheading.
23076 This version will not throw an error. It will return the level of the
23077 headline found, or nil if no higher level is found.
23079 Also, this function will be a lot faster than `outline-up-heading',
23080 because it relies on stars being the outline starters. This can really
23081 make a significant difference in outlines with very many siblings."
23082 (let (start-level re)
23083 (org-back-to-heading t)
23084 (setq start-level (funcall outline-level))
23085 (if (equal start-level 1)
23087 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23088 (if (re-search-backward re nil t)
23089 (funcall outline-level)))))
23091 (defun org-first-sibling-p ()
23092 "Is this heading the first child of its parents?"
23093 (interactive)
23094 (let ((re org-outline-regexp-bol)
23095 level l)
23096 (unless (org-at-heading-p t)
23097 (user-error "Not at a heading"))
23098 (setq level (funcall outline-level))
23099 (save-excursion
23100 (if (not (re-search-backward re nil t))
23102 (setq l (funcall outline-level))
23103 (< l level)))))
23105 (defun org-goto-sibling (&optional previous)
23106 "Goto the next sibling, even if it is invisible.
23107 When PREVIOUS is set, go to the previous sibling instead. Returns t
23108 when a sibling was found. When none is found, return nil and don't
23109 move point."
23110 (let ((fun (if previous 're-search-backward 're-search-forward))
23111 (pos (point))
23112 (re org-outline-regexp-bol)
23113 level l)
23114 (when (condition-case nil (org-back-to-heading t) (error nil))
23115 (setq level (funcall outline-level))
23116 (catch 'exit
23117 (or previous (forward-char 1))
23118 (while (funcall fun re nil t)
23119 (setq l (funcall outline-level))
23120 (when (< l level) (goto-char pos) (throw 'exit nil))
23121 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23122 (goto-char pos)
23123 nil))))
23125 (defun org-show-siblings ()
23126 "Show all siblings of the current headline."
23127 (save-excursion
23128 (while (org-goto-sibling) (org-flag-heading nil)))
23129 (save-excursion
23130 (while (org-goto-sibling 'previous)
23131 (org-flag-heading nil))))
23133 (defun org-goto-first-child ()
23134 "Goto the first child, even if it is invisible.
23135 Return t when a child was found. Otherwise don't move point and
23136 return nil."
23137 (let (level (pos (point)) (re org-outline-regexp-bol))
23138 (when (condition-case nil (org-back-to-heading t) (error nil))
23139 (setq level (outline-level))
23140 (forward-char 1)
23141 (if (and (re-search-forward re nil t) (> (outline-level) level))
23142 (progn (goto-char (match-beginning 0)) t)
23143 (goto-char pos) nil))))
23145 (defun org-show-hidden-entry ()
23146 "Show an entry where even the heading is hidden."
23147 (save-excursion
23148 (org-show-entry)))
23150 (defun org-flag-heading (flag &optional entry)
23151 "Flag the current heading. FLAG non-nil means make invisible.
23152 When ENTRY is non-nil, show the entire entry."
23153 (save-excursion
23154 (org-back-to-heading t)
23155 ;; Check if we should show the entire entry
23156 (if entry
23157 (progn
23158 (org-show-entry)
23159 (save-excursion
23160 (and (outline-next-heading)
23161 (org-flag-heading nil))))
23162 (outline-flag-region (max (point-min) (1- (point)))
23163 (save-excursion (outline-end-of-heading) (point))
23164 flag))))
23166 (defun org-get-next-sibling ()
23167 "Move to next heading of the same level, and return point.
23168 If there is no such heading, return nil.
23169 This is like outline-next-sibling, but invisible headings are ok."
23170 (let ((level (funcall outline-level)))
23171 (outline-next-heading)
23172 (while (and (not (eobp)) (> (funcall outline-level) level))
23173 (outline-next-heading))
23174 (if (or (eobp) (< (funcall outline-level) level))
23176 (point))))
23178 (defun org-get-last-sibling ()
23179 "Move to previous heading of the same level, and return point.
23180 If there is no such heading, return nil."
23181 (let ((opoint (point))
23182 (level (funcall outline-level)))
23183 (outline-previous-heading)
23184 (when (and (/= (point) opoint) (outline-on-heading-p t))
23185 (while (and (> (funcall outline-level) level)
23186 (not (bobp)))
23187 (outline-previous-heading))
23188 (if (< (funcall outline-level) level)
23190 (point)))))
23192 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23193 "Goto to the end of a subtree."
23194 ;; This contains an exact copy of the original function, but it uses
23195 ;; `org-back-to-heading', to make it work also in invisible
23196 ;; trees. And is uses an invisible-ok argument.
23197 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23198 ;; Furthermore, when used inside Org, finding the end of a large subtree
23199 ;; with many children and grandchildren etc, this can be much faster
23200 ;; than the outline version.
23201 (org-back-to-heading invisible-ok)
23202 (let ((first t)
23203 (level (funcall outline-level)))
23204 (if (and (derived-mode-p 'org-mode) (< level 1000))
23205 ;; A true heading (not a plain list item), in Org-mode
23206 ;; This means we can easily find the end by looking
23207 ;; only for the right number of stars. Using a regexp to do
23208 ;; this is so much faster than using a Lisp loop.
23209 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23210 (forward-char 1)
23211 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23212 ;; something else, do it the slow way
23213 (while (and (not (eobp))
23214 (or first (> (funcall outline-level) level)))
23215 (setq first nil)
23216 (outline-next-heading)))
23217 (unless to-heading
23218 (if (memq (preceding-char) '(?\n ?\^M))
23219 (progn
23220 ;; Go to end of line before heading
23221 (forward-char -1)
23222 (if (memq (preceding-char) '(?\n ?\^M))
23223 ;; leave blank line before heading
23224 (forward-char -1))))))
23225 (point))
23227 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23228 "Use Org version in org-mode, for dramatic speed-up."
23229 (if (derived-mode-p 'org-mode)
23230 (progn
23231 (org-end-of-subtree nil t)
23232 (unless (eobp) (backward-char 1)))
23233 ad-do-it))
23235 (defun org-end-of-meta-data-and-drawers ()
23236 "Jump to the first text after meta data and drawers in the current entry.
23237 This will move over empty lines, lines with planning time stamps,
23238 clocking lines, and drawers."
23239 (org-back-to-heading t)
23240 (let ((end (save-excursion (outline-next-heading) (point)))
23241 (re (concat "\\(" org-drawer-regexp "\\)"
23242 "\\|" "[ \t]*" org-keyword-time-regexp)))
23243 (forward-line 1)
23244 (while (re-search-forward re end t)
23245 (if (not (match-end 1))
23246 ;; empty or planning line
23247 (forward-line 1)
23248 ;; a drawer, find the end
23249 (re-search-forward "^[ \t]*:END:" end 'move)
23250 (forward-line 1)))
23251 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23252 (point)))
23254 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23255 "Move forward to the ARG'th subheading at same level as this one.
23256 Stop at the first and last subheadings of a superior heading.
23257 Normally this only looks at visible headings, but when INVISIBLE-OK is
23258 non-nil it will also look at invisible ones."
23259 (interactive "p")
23260 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23261 (if (and arg (< arg 0))
23262 (goto-char (point-min))
23263 (outline-next-heading))
23264 (org-at-heading-p)
23265 (let ((level (- (match-end 0) (match-beginning 0) 1))
23266 (f (if (and arg (< arg 0))
23267 're-search-backward
23268 're-search-forward))
23269 (count (if arg (abs arg) 1))
23270 (result (point)))
23271 (while (and (prog1 (> count 0)
23272 (forward-char (if (and arg (< arg 0)) -1 1)))
23273 (funcall f org-outline-regexp-bol nil 'move))
23274 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23275 (cond ((< l level) (setq count 0))
23276 ((and (= l level)
23277 (or invisible-ok
23278 (progn
23279 (goto-char (line-beginning-position))
23280 (not (outline-invisible-p)))))
23281 (setq count (1- count))
23282 (when (eq l level)
23283 (setq result (point)))))))
23284 (goto-char result))
23285 (beginning-of-line 1)))
23287 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23288 "Move backward to the ARG'th subheading at same level as this one.
23289 Stop at the first and last subheadings of a superior heading."
23290 (interactive "p")
23291 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23293 (defun org-next-block (arg &optional backward block-regexp)
23294 "Jump to the next block.
23295 With a prefix argument ARG, jump forward ARG many source blocks.
23296 When BACKWARD is non-nil, jump to the previous block.
23297 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23298 (interactive "p")
23299 (let ((re (or block-regexp org-block-regexp))
23300 (re-search-fn (or (and backward 're-search-backward)
23301 're-search-forward)))
23302 (if (looking-at re) (forward-char 1))
23303 (condition-case nil
23304 (funcall re-search-fn re nil nil arg)
23305 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23306 (goto-char (match-beginning 0)) (org-show-context)))
23308 (defun org-previous-block (arg &optional block-regexp)
23309 "Jump to the previous block.
23310 With a prefix argument ARG, jump backward ARG many source blocks.
23311 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23312 (interactive "p")
23313 (org-next-block arg t block-regexp))
23315 (defun org-forward-paragraph ()
23316 "Move forward to beginning of next paragraph or equivalent.
23318 The function moves point to the beginning of the next visible
23319 structural element, which can be a paragraph, a table, a list
23320 item, etc. It also provides some special moves for convenience:
23322 - On an affiliated keyword, jump to the beginning of the
23323 relative element.
23324 - On an item or a footnote definition, move to the second
23325 element inside, if any.
23326 - On a table or a property drawer, jump after it.
23327 - On a verse or source block, stop after blank lines."
23328 (interactive)
23329 (when (eobp) (user-error "Cannot move further down"))
23330 (let* ((deactivate-mark nil)
23331 (element (org-element-at-point))
23332 (type (org-element-type element))
23333 (post-affiliated (org-element-property :post-affiliated element))
23334 (contents-begin (org-element-property :contents-begin element))
23335 (contents-end (org-element-property :contents-end element))
23336 (end (let ((end (org-element-property :end element)) (parent element))
23337 (while (and (setq parent (org-element-property :parent parent))
23338 (= (org-element-property :contents-end parent) end))
23339 (setq end (org-element-property :end parent)))
23340 end)))
23341 (cond ((not element)
23342 (skip-chars-forward " \r\t\n")
23343 (or (eobp) (beginning-of-line)))
23344 ;; On affiliated keywords, move to element's beginning.
23345 ((and post-affiliated (< (point) post-affiliated))
23346 (goto-char post-affiliated))
23347 ;; At a table row, move to the end of the table. Similarly,
23348 ;; at a node property, move to the end of the property
23349 ;; drawer.
23350 ((memq type '(node-property table-row))
23351 (goto-char (org-element-property
23352 :end (org-element-property :parent element))))
23353 ((memq type '(property-drawer table)) (goto-char end))
23354 ;; Consider blank lines as separators in verse and source
23355 ;; blocks to ease editing.
23356 ((memq type '(src-block verse-block))
23357 (when (eq type 'src-block)
23358 (setq contents-end
23359 (save-excursion (goto-char end)
23360 (skip-chars-backward " \r\t\n")
23361 (line-beginning-position))))
23362 (beginning-of-line)
23363 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23364 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23365 (goto-char end)
23366 (skip-chars-forward " \r\t\n")
23367 (if (= (point) contents-end) (goto-char end)
23368 (beginning-of-line))))
23369 ;; With no contents, just skip element.
23370 ((not contents-begin) (goto-char end))
23371 ;; If contents are invisible, skip the element altogether.
23372 ((outline-invisible-p (line-end-position))
23373 (case type
23374 (headline
23375 (org-with-limited-levels (outline-next-visible-heading 1)))
23376 ;; At a plain list, make sure we move to the next item
23377 ;; instead of skipping the whole list.
23378 (plain-list (forward-char)
23379 (org-forward-paragraph))
23380 (otherwise (goto-char end))))
23381 ((>= (point) contents-end) (goto-char end))
23382 ((>= (point) contents-begin)
23383 ;; This can only happen on paragraphs and plain lists.
23384 (case type
23385 (paragraph (goto-char end))
23386 ;; At a plain list, try to move to second element in
23387 ;; first item, if possible.
23388 (plain-list (end-of-line)
23389 (org-forward-paragraph))))
23390 ;; When contents start on the middle of a line (e.g. in
23391 ;; items and footnote definitions), try to reach first
23392 ;; element starting after current line.
23393 ((> (line-end-position) contents-begin)
23394 (end-of-line)
23395 (org-forward-paragraph))
23396 (t (goto-char contents-begin)))))
23398 (defun org-backward-paragraph ()
23399 "Move backward to start of previous paragraph or equivalent.
23401 The function moves point to the beginning of the current
23402 structural element, which can be a paragraph, a table, a list
23403 item, etc., or to the beginning of the previous visible one if
23404 point is already there. It also provides some special moves for
23405 convenience:
23407 - On an affiliated keyword, jump to the first one.
23408 - On a table or a property drawer, move to its beginning.
23409 - On a verse or source block, stop before blank lines."
23410 (interactive)
23411 (when (bobp) (user-error "Cannot move further up"))
23412 (let* ((deactivate-mark nil)
23413 (element (org-element-at-point))
23414 (type (org-element-type element))
23415 (contents-begin (org-element-property :contents-begin element))
23416 (contents-end (org-element-property :contents-end element))
23417 (post-affiliated (org-element-property :post-affiliated element))
23418 (begin (org-element-property :begin element)))
23419 (cond
23420 ((not element) (goto-char (point-min)))
23421 ((= (point) begin)
23422 (backward-char)
23423 (org-backward-paragraph))
23424 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23425 ((memq type '(node-property table-row))
23426 (goto-char (org-element-property
23427 :post-affiliated (org-element-property :parent element))))
23428 ((memq type '(property-drawer table)) (goto-char begin))
23429 ((memq type '(src-block verse-block))
23430 (when (eq type 'src-block)
23431 (setq contents-begin
23432 (save-excursion (goto-char begin) (forward-line) (point))))
23433 (if (= (point) contents-begin) (goto-char post-affiliated)
23434 ;; Inside a verse block, see blank lines as paragraph
23435 ;; separators.
23436 (let ((origin (point)))
23437 (skip-chars-backward " \r\t\n" contents-begin)
23438 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23439 (skip-chars-forward " \r\t\n" origin)
23440 (if (= (point) origin) (goto-char contents-begin)
23441 (beginning-of-line))))))
23442 ((not contents-begin) (goto-char (or post-affiliated begin)))
23443 ((eq type 'paragraph)
23444 (goto-char contents-begin)
23445 ;; When at first paragraph in an item or a footnote definition,
23446 ;; move directly to beginning of line.
23447 (let ((parent-contents
23448 (org-element-property
23449 :contents-begin (org-element-property :parent element))))
23450 (when (and parent-contents (= parent-contents contents-begin))
23451 (beginning-of-line))))
23452 ;; At the end of a greater element, move to the beginning of the
23453 ;; last element within.
23454 ((>= (point) contents-end)
23455 (goto-char (1- contents-end))
23456 (org-backward-paragraph))
23457 (t (goto-char (or post-affiliated begin))))
23458 ;; Ensure we never leave point invisible.
23459 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23461 (defun org-forward-element ()
23462 "Move forward by one element.
23463 Move to the next element at the same level, when possible."
23464 (interactive)
23465 (cond ((eobp) (user-error "Cannot move further down"))
23466 ((org-with-limited-levels (org-at-heading-p))
23467 (let ((origin (point)))
23468 (goto-char (org-end-of-subtree nil t))
23469 (unless (org-with-limited-levels (org-at-heading-p))
23470 (goto-char origin)
23471 (user-error "Cannot move further down"))))
23473 (let* ((elem (org-element-at-point))
23474 (end (org-element-property :end elem))
23475 (parent (org-element-property :parent elem)))
23476 (cond ((and parent (= (org-element-property :contents-end parent) end))
23477 (goto-char (org-element-property :end parent)))
23478 ((integer-or-marker-p end) (goto-char end))
23479 (t (message "No element at point")))))))
23481 (defun org-backward-element ()
23482 "Move backward by one element.
23483 Move to the previous element at the same level, when possible."
23484 (interactive)
23485 (cond ((bobp) (user-error "Cannot move further up"))
23486 ((org-with-limited-levels (org-at-heading-p))
23487 ;; At a headline, move to the previous one, if any, or stay
23488 ;; here.
23489 (let ((origin (point)))
23490 (org-with-limited-levels (org-backward-heading-same-level 1))
23491 ;; When current headline has no sibling above, move to its
23492 ;; parent.
23493 (when (= (point) origin)
23494 (or (org-with-limited-levels (org-up-heading-safe))
23495 (progn (goto-char origin)
23496 (user-error "Cannot move further up"))))))
23498 (let* ((trail (org-element-at-point 'keep-trail))
23499 (elem (car trail))
23500 (prev-elem (nth 1 trail))
23501 (beg (org-element-property :begin elem)))
23502 (cond
23503 ;; Move to beginning of current element if point isn't
23504 ;; there already.
23505 ((null beg) (message "No element at point"))
23506 ((/= (point) beg) (goto-char beg))
23507 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23508 ((org-before-first-heading-p) (goto-char (point-min)))
23509 (t (org-back-to-heading)))))))
23511 (defun org-up-element ()
23512 "Move to upper element."
23513 (interactive)
23514 (if (org-with-limited-levels (org-at-heading-p))
23515 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23516 (let* ((elem (org-element-at-point))
23517 (parent (org-element-property :parent elem)))
23518 (if parent (goto-char (org-element-property :begin parent))
23519 (if (org-with-limited-levels (org-before-first-heading-p))
23520 (user-error "No surrounding element")
23521 (org-with-limited-levels (org-back-to-heading)))))))
23523 (defvar org-element-greater-elements)
23524 (defun org-down-element ()
23525 "Move to inner element."
23526 (interactive)
23527 (let ((element (org-element-at-point)))
23528 (cond
23529 ((memq (org-element-type element) '(plain-list table))
23530 (goto-char (org-element-property :contents-begin element))
23531 (forward-char))
23532 ((memq (org-element-type element) org-element-greater-elements)
23533 ;; If contents are hidden, first disclose them.
23534 (when (org-element-property :hiddenp element) (org-cycle))
23535 (goto-char (or (org-element-property :contents-begin element)
23536 (user-error "No content for this element"))))
23537 (t (user-error "No inner element")))))
23539 (defun org-drag-element-backward ()
23540 "Move backward element at point."
23541 (interactive)
23542 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23543 (let* ((trail (org-element-at-point 'keep-trail))
23544 (elem (car trail))
23545 (prev-elem (nth 1 trail)))
23546 ;; Error out if no previous element or previous element is
23547 ;; a parent of the current one.
23548 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23549 (user-error "Cannot drag element backward")
23550 (let ((pos (point)))
23551 (org-element-swap-A-B prev-elem elem)
23552 (goto-char (+ (org-element-property :begin prev-elem)
23553 (- pos (org-element-property :begin elem)))))))))
23555 (defun org-drag-element-forward ()
23556 "Move forward element at point."
23557 (interactive)
23558 (let* ((pos (point))
23559 (elem (org-element-at-point)))
23560 (when (= (point-max) (org-element-property :end elem))
23561 (user-error "Cannot drag element forward"))
23562 (goto-char (org-element-property :end elem))
23563 (let ((next-elem (org-element-at-point)))
23564 (when (or (org-element-nested-p elem next-elem)
23565 (and (eq (org-element-type next-elem) 'headline)
23566 (not (eq (org-element-type elem) 'headline))))
23567 (goto-char pos)
23568 (user-error "Cannot drag element forward"))
23569 ;; Compute new position of point: it's shifted by NEXT-ELEM
23570 ;; body's length (without final blanks) and by the length of
23571 ;; blanks between ELEM and NEXT-ELEM.
23572 (let ((size-next (- (save-excursion
23573 (goto-char (org-element-property :end next-elem))
23574 (skip-chars-backward " \r\t\n")
23575 (forward-line)
23576 ;; Small correction if buffer doesn't end
23577 ;; with a newline character.
23578 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23579 (org-element-property :begin next-elem)))
23580 (size-blank (- (org-element-property :end elem)
23581 (save-excursion
23582 (goto-char (org-element-property :end elem))
23583 (skip-chars-backward " \r\t\n")
23584 (forward-line)
23585 (point)))))
23586 (org-element-swap-A-B elem next-elem)
23587 (goto-char (+ pos size-next size-blank))))))
23589 (defun org-drag-line-forward (arg)
23590 "Drag the line at point ARG lines forward."
23591 (interactive "p")
23592 (dotimes (n (abs arg))
23593 (let ((c (current-column)))
23594 (if (< 0 arg)
23595 (progn
23596 (beginning-of-line 2)
23597 (transpose-lines 1)
23598 (beginning-of-line 0))
23599 (transpose-lines 1)
23600 (beginning-of-line -1))
23601 (org-move-to-column c))))
23603 (defun org-drag-line-backward (arg)
23604 "Drag the line at point ARG lines backward."
23605 (interactive "p")
23606 (org-drag-line-forward (- arg)))
23608 (defun org-mark-element ()
23609 "Put point at beginning of this element, mark at end.
23611 Interactively, if this command is repeated or (in Transient Mark
23612 mode) if the mark is active, it marks the next element after the
23613 ones already marked."
23614 (interactive)
23615 (let (deactivate-mark)
23616 (if (and (org-called-interactively-p 'any)
23617 (or (and (eq last-command this-command) (mark t))
23618 (and transient-mark-mode mark-active)))
23619 (set-mark
23620 (save-excursion
23621 (goto-char (mark))
23622 (goto-char (org-element-property :end (org-element-at-point)))))
23623 (let ((element (org-element-at-point)))
23624 (end-of-line)
23625 (push-mark (org-element-property :end element) t t)
23626 (goto-char (org-element-property :begin element))))))
23628 (defun org-narrow-to-element ()
23629 "Narrow buffer to current element."
23630 (interactive)
23631 (let ((elem (org-element-at-point)))
23632 (cond
23633 ((eq (car elem) 'headline)
23634 (narrow-to-region
23635 (org-element-property :begin elem)
23636 (org-element-property :end elem)))
23637 ((memq (car elem) org-element-greater-elements)
23638 (narrow-to-region
23639 (org-element-property :contents-begin elem)
23640 (org-element-property :contents-end elem)))
23642 (narrow-to-region
23643 (org-element-property :begin elem)
23644 (org-element-property :end elem))))))
23646 (defun org-transpose-element ()
23647 "Transpose current and previous elements, keeping blank lines between.
23648 Point is moved after both elements."
23649 (interactive)
23650 (org-skip-whitespace)
23651 (let ((end (org-element-property :end (org-element-at-point))))
23652 (org-drag-element-backward)
23653 (goto-char end)))
23655 (defun org-unindent-buffer ()
23656 "Un-indent the visible part of the buffer.
23657 Relative indentation (between items, inside blocks, etc.) isn't
23658 modified."
23659 (interactive)
23660 (unless (eq major-mode 'org-mode)
23661 (user-error "Cannot un-indent a buffer not in Org mode"))
23662 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23663 unindent-tree ; For byte-compiler.
23664 (unindent-tree
23665 (function
23666 (lambda (contents)
23667 (mapc
23668 (lambda (element)
23669 (if (memq (org-element-type element) '(headline section))
23670 (funcall unindent-tree (org-element-contents element))
23671 (save-excursion
23672 (save-restriction
23673 (narrow-to-region
23674 (org-element-property :begin element)
23675 (org-element-property :end element))
23676 (org-do-remove-indentation)))))
23677 (reverse contents))))))
23678 (funcall unindent-tree (org-element-contents parse-tree))))
23680 (defun org-show-subtree ()
23681 "Show everything after this heading at deeper levels."
23682 (interactive)
23683 (outline-flag-region
23684 (point)
23685 (save-excursion
23686 (org-end-of-subtree t t))
23687 nil))
23689 (defun org-show-entry ()
23690 "Show the body directly following this heading.
23691 Show the heading too, if it is currently invisible."
23692 (interactive)
23693 (save-excursion
23694 (condition-case nil
23695 (progn
23696 (org-back-to-heading t)
23697 (outline-flag-region
23698 (max (point-min) (1- (point)))
23699 (save-excursion
23700 (if (re-search-forward
23701 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23702 (match-beginning 1)
23703 (point-max)))
23704 nil)
23705 (org-cycle-hide-drawers 'children))
23706 (error nil))))
23708 (defun org-make-options-regexp (kwds &optional extra)
23709 "Make a regular expression for keyword lines."
23710 (concat
23711 "^#\\+\\("
23712 (mapconcat 'regexp-quote kwds "\\|")
23713 (if extra (concat "\\|" extra))
23714 "\\):[ \t]*\\(.*\\)"))
23716 ;; Make isearch reveal the necessary context
23717 (defun org-isearch-end ()
23718 "Reveal context after isearch exits."
23719 (when isearch-success ; only if search was successful
23720 (if (featurep 'xemacs)
23721 ;; Under XEmacs, the hook is run in the correct place,
23722 ;; we directly show the context.
23723 (org-show-context 'isearch)
23724 ;; In Emacs the hook runs *before* restoring the overlays.
23725 ;; So we have to use a one-time post-command-hook to do this.
23726 ;; (Emacs 22 has a special variable, see function `org-mode')
23727 (unless (and (boundp 'isearch-mode-end-hook-quit)
23728 isearch-mode-end-hook-quit)
23729 ;; Only when the isearch was not quitted.
23730 (org-add-hook 'post-command-hook 'org-isearch-post-command
23731 'append 'local)))
23732 (org-fix-ellipsis-at-bol)))
23734 (defun org-isearch-post-command ()
23735 "Remove self from hook, and show context."
23736 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23737 (org-show-context 'isearch))
23740 ;;;; Integration with and fixes for other packages
23742 ;;; Imenu support
23744 (defvar org-imenu-markers nil
23745 "All markers currently used by Imenu.")
23746 (make-variable-buffer-local 'org-imenu-markers)
23748 (defun org-imenu-new-marker (&optional pos)
23749 "Return a new marker for use by Imenu, and remember the marker."
23750 (let ((m (make-marker)))
23751 (move-marker m (or pos (point)))
23752 (push m org-imenu-markers)
23755 (defun org-imenu-get-tree ()
23756 "Produce the index for Imenu."
23757 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23758 (setq org-imenu-markers nil)
23759 (let* ((n org-imenu-depth)
23760 (re (concat "^" (org-get-limited-outline-regexp)))
23761 (subs (make-vector (1+ n) nil))
23762 (last-level 0)
23763 m level head0 head)
23764 (save-excursion
23765 (save-restriction
23766 (widen)
23767 (goto-char (point-max))
23768 (while (re-search-backward re nil t)
23769 (setq level (org-reduced-level (funcall outline-level)))
23770 (when (and (<= level n)
23771 (looking-at org-complex-heading-regexp)
23772 (setq head0 (org-match-string-no-properties 4)))
23773 (setq head (org-link-display-format head0)
23774 m (org-imenu-new-marker))
23775 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23776 (if (>= level last-level)
23777 (push (cons head m) (aref subs level))
23778 (push (cons head (aref subs (1+ level))) (aref subs level))
23779 (loop for i from (1+ level) to n do (aset subs i nil)))
23780 (setq last-level level)))))
23781 (aref subs 1)))
23783 (eval-after-load "imenu"
23784 '(progn
23785 (add-hook 'imenu-after-jump-hook
23786 (lambda ()
23787 (if (derived-mode-p 'org-mode)
23788 (org-show-context 'org-goto))))))
23790 (defun org-link-display-format (link)
23791 "Replace a link with its the description.
23792 If there is no description, use the link target."
23793 (save-match-data
23794 (if (string-match org-bracket-link-analytic-regexp link)
23795 (replace-match (if (match-end 5)
23796 (match-string 5 link)
23797 (concat (match-string 1 link)
23798 (match-string 3 link)))
23799 nil t link)
23800 link)))
23802 (defun org-toggle-link-display ()
23803 "Toggle the literal or descriptive display of links."
23804 (interactive)
23805 (if org-descriptive-links
23806 (progn (org-remove-from-invisibility-spec '(org-link))
23807 (org-restart-font-lock)
23808 (setq org-descriptive-links nil))
23809 (progn (add-to-invisibility-spec '(org-link))
23810 (org-restart-font-lock)
23811 (setq org-descriptive-links t))))
23813 ;; Speedbar support
23815 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23816 "Overlay marking the agenda restriction line in speedbar.")
23817 (overlay-put org-speedbar-restriction-lock-overlay
23818 'face 'org-agenda-restriction-lock)
23819 (overlay-put org-speedbar-restriction-lock-overlay
23820 'help-echo "Agendas are currently limited to this item.")
23821 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23823 (defun org-speedbar-set-agenda-restriction ()
23824 "Restrict future agenda commands to the location at point in speedbar.
23825 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23826 (interactive)
23827 (require 'org-agenda)
23828 (let (p m tp np dir txt)
23829 (cond
23830 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23831 'org-imenu t))
23832 (setq m (get-text-property p 'org-imenu-marker))
23833 (with-current-buffer (marker-buffer m)
23834 (goto-char m)
23835 (org-agenda-set-restriction-lock 'subtree)))
23836 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23837 'speedbar-function 'speedbar-find-file))
23838 (setq tp (previous-single-property-change
23839 (1+ p) 'speedbar-function)
23840 np (next-single-property-change
23841 tp 'speedbar-function)
23842 dir (speedbar-line-directory)
23843 txt (buffer-substring-no-properties (or tp (point-min))
23844 (or np (point-max))))
23845 (with-current-buffer (find-file-noselect
23846 (let ((default-directory dir))
23847 (expand-file-name txt)))
23848 (unless (derived-mode-p 'org-mode)
23849 (user-error "Cannot restrict to non-Org-mode file"))
23850 (org-agenda-set-restriction-lock 'file)))
23851 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23852 (move-overlay org-speedbar-restriction-lock-overlay
23853 (point-at-bol) (point-at-eol))
23854 (setq current-prefix-arg nil)
23855 (org-agenda-maybe-redo)))
23857 (defvar speedbar-file-key-map)
23858 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23859 (eval-after-load "speedbar"
23860 '(progn
23861 (speedbar-add-supported-extension ".org")
23862 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23863 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23864 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23865 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23866 (add-hook 'speedbar-visiting-tag-hook
23867 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23869 ;;; Fixes and Hacks for problems with other packages
23871 ;; Make flyspell not check words in links, to not mess up our keymap
23872 (defvar org-element-affiliated-keywords) ; From org-element.el
23873 (defvar org-element-block-name-alist) ; From org-element.el
23874 (defun org-mode-flyspell-verify ()
23875 "Don't let flyspell put overlays at active buttons, or on
23876 {todo,all-time,additional-option-like}-keywords."
23877 (require 'org-element) ; For `org-element-affiliated-keywords'
23878 (let ((pos (max (1- (point)) (point-min)))
23879 (word (thing-at-point 'word)))
23880 (and (not (get-text-property pos 'keymap))
23881 (not (get-text-property pos 'org-no-flyspell))
23882 (not (member word org-todo-keywords-1))
23883 (not (member word org-all-time-keywords))
23884 (not (member word org-options-keywords))
23885 (not (member word (mapcar 'car org-startup-options)))
23886 (not (member-ignore-case word org-element-affiliated-keywords))
23887 (not (member-ignore-case word (org-get-export-keywords)))
23888 (not (member-ignore-case
23889 word (mapcar 'car org-element-block-name-alist)))
23890 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23891 (not (org-in-src-block-p)))))
23893 (defun org-remove-flyspell-overlays-in (beg end)
23894 "Remove flyspell overlays in region."
23895 (and (org-bound-and-true-p flyspell-mode)
23896 (fboundp 'flyspell-delete-region-overlays)
23897 (flyspell-delete-region-overlays beg end))
23898 (add-text-properties beg end '(org-no-flyspell t)))
23900 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23901 (eval-after-load "bookmark"
23902 '(if (boundp 'bookmark-after-jump-hook)
23903 ;; We can use the hook
23904 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23905 ;; Hook not available, use advice
23906 (defadvice bookmark-jump (after org-make-visible activate)
23907 "Make the position visible."
23908 (org-bookmark-jump-unhide))))
23910 ;; Make sure saveplace shows the location if it was hidden
23911 (eval-after-load "saveplace"
23912 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23913 "Make the position visible."
23914 (org-bookmark-jump-unhide)))
23916 ;; Make sure ecb shows the location if it was hidden
23917 (eval-after-load "ecb"
23918 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23919 "Make hierarchy visible when jumping into location from ECB tree buffer."
23920 (if (derived-mode-p 'org-mode)
23921 (org-show-context))))
23923 (defun org-bookmark-jump-unhide ()
23924 "Unhide the current position, to show the bookmark location."
23925 (and (derived-mode-p 'org-mode)
23926 (or (outline-invisible-p)
23927 (save-excursion (goto-char (max (point-min) (1- (point))))
23928 (outline-invisible-p)))
23929 (org-show-context 'bookmark-jump)))
23931 ;; Make session.el ignore our circular variable
23932 (defvar session-globals-exclude)
23933 (eval-after-load "session"
23934 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23936 ;;;; Finish up
23938 (provide 'org)
23940 (run-hooks 'org-load-hook)
23942 ;;; org.el ends here