Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob7cbad9741234a08a4679089c34347099b6fa9fa0
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (org-babel-tangle-file file exported-file "emacs-lisp"))
202 (message "%s %s"
203 (if compile
204 (progn (byte-compile-file exported-file 'load)
205 "Compiled and loaded")
206 (progn (load-file exported-file) "Loaded"))
207 exported-file)))
209 (defcustom org-babel-load-languages '((emacs-lisp . t))
210 "Languages which can be evaluated in Org-mode buffers.
211 This list can be used to load support for any of the languages
212 below, note that each language will depend on a different set of
213 system executables and/or Emacs modes. When a language is
214 \"loaded\", then code blocks in that language can be evaluated
215 with `org-babel-execute-src-block' bound by default to C-c
216 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
217 be set to remove code block evaluation from the C-c C-c
218 keybinding. By default only Emacs Lisp (which has no
219 requirements) is loaded."
220 :group 'org-babel
221 :set 'org-babel-do-load-languages
222 :version "24.1"
223 :type '(alist :tag "Babel Languages"
224 :key-type
225 (choice
226 (const :tag "Awk" awk)
227 (const :tag "C" C)
228 (const :tag "R" R)
229 (const :tag "Asymptote" asymptote)
230 (const :tag "Calc" calc)
231 (const :tag "Clojure" clojure)
232 (const :tag "CSS" css)
233 (const :tag "Ditaa" ditaa)
234 (const :tag "Dot" dot)
235 (const :tag "Emacs Lisp" emacs-lisp)
236 (const :tag "Fortran" fortran)
237 (const :tag "Gnuplot" gnuplot)
238 (const :tag "Haskell" haskell)
239 (const :tag "IO" io)
240 (const :tag "Java" java)
241 (const :tag "Javascript" js)
242 (const :tag "LaTeX" latex)
243 (const :tag "Ledger" ledger)
244 (const :tag "Lilypond" lilypond)
245 (const :tag "Lisp" lisp)
246 (const :tag "Makefile" makefile)
247 (const :tag "Maxima" maxima)
248 (const :tag "Matlab" matlab)
249 (const :tag "Mscgen" mscgen)
250 (const :tag "Ocaml" ocaml)
251 (const :tag "Octave" octave)
252 (const :tag "Org" org)
253 (const :tag "Perl" perl)
254 (const :tag "Pico Lisp" picolisp)
255 (const :tag "PlantUML" plantuml)
256 (const :tag "Python" python)
257 (const :tag "Ruby" ruby)
258 (const :tag "Sass" sass)
259 (const :tag "Scala" scala)
260 (const :tag "Scheme" scheme)
261 (const :tag "Screen" screen)
262 (const :tag "Shell Script" sh)
263 (const :tag "Shen" shen)
264 (const :tag "Sql" sql)
265 (const :tag "Sqlite" sqlite))
266 :value-type (boolean :tag "Activate" :value t)))
268 ;;;; Customization variables
269 (defcustom org-clone-delete-id nil
270 "Remove ID property of clones of a subtree.
271 When non-nil, clones of a subtree don't inherit the ID property.
272 Otherwise they inherit the ID property with a new unique
273 identifier."
274 :type 'boolean
275 :version "24.1"
276 :group 'org-id)
278 ;;; Version
279 (org-check-version)
281 ;;;###autoload
282 (defun org-version (&optional here full message)
283 "Show the org-mode version in the echo area.
284 With prefix argument HERE, insert it at point.
285 When FULL is non-nil, use a verbose version string.
286 When MESSAGE is non-nil, display a message with the version."
287 (interactive "P")
288 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
289 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
290 (load-suffixes (list ".el"))
291 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
292 (org-trash (or
293 (and (fboundp 'org-release) (fboundp 'org-git-version))
294 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
295 (load-suffixes save-load-suffixes)
296 (org-version (org-release))
297 (git-version (org-git-version))
298 (version (format "Org-mode version %s (%s @ %s)"
299 org-version
300 git-version
301 (if org-install-dir
302 (if (string= org-dir org-install-dir)
303 org-install-dir
304 (concat "mixed installation! " org-install-dir " and " org-dir))
305 "org-loaddefs.el can not be found!")))
306 (_version (if full version org-version)))
307 (if (org-called-interactively-p 'interactive)
308 (if here
309 (insert version)
310 (message version))
311 (if message (message _version))
312 _version)))
314 (defconst org-version (org-version))
316 ;;; Compatibility constants
318 ;;; The custom variables
320 (defgroup org nil
321 "Outline-based notes management and organizer."
322 :tag "Org"
323 :group 'outlines
324 :group 'calendar)
326 (defcustom org-mode-hook nil
327 "Mode hook for Org-mode, run after the mode was turned on."
328 :group 'org
329 :type 'hook)
331 (defcustom org-load-hook nil
332 "Hook that is run after org.el has been loaded."
333 :group 'org
334 :type 'hook)
336 (defcustom org-log-buffer-setup-hook nil
337 "Hook that is run after an Org log buffer is created."
338 :group 'org
339 :version "24.1"
340 :type 'hook)
342 (defvar org-modules) ; defined below
343 (defvar org-modules-loaded nil
344 "Have the modules been loaded already?")
346 (defun org-load-modules-maybe (&optional force)
347 "Load all extensions listed in `org-modules'."
348 (when (or force (not org-modules-loaded))
349 (mapc (lambda (ext)
350 (condition-case nil (require ext)
351 (error (message "Problems while trying to load feature `%s'" ext))))
352 org-modules)
353 (setq org-modules-loaded t)))
355 (defun org-set-modules (var value)
356 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
357 (set var value)
358 (when (featurep 'org)
359 (org-load-modules-maybe 'force)))
361 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
362 "Modules that should always be loaded together with org.el.
364 If a description starts with <C>, the file is not part of Emacs
365 and loading it will require that you have downloaded and properly
366 installed the Org mode distribution.
368 You can also use this system to load external packages (i.e. neither Org
369 core modules, nor modules from the CONTRIB directory). Just add symbols
370 to the end of the list. If the package is called org-xyz.el, then you need
371 to add the symbol `xyz', and the package must have a call to:
373 \(provide 'org-xyz)
375 For export specific modules, see also `org-export-backends'."
376 :group 'org
377 :set 'org-set-modules
378 :version "24.4"
379 :package-version '(Org . "8.0")
380 :type
381 '(set :greedy t
382 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
383 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
384 (const :tag " crypt: Encryption of subtrees" org-crypt)
385 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
386 (const :tag " docview: Links to doc-view buffers" org-docview)
387 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
388 (const :tag " habit: Track your consistency with habits" org-habit)
389 (const :tag " id: Global IDs for identifying entries" org-id)
390 (const :tag " info: Links to Info nodes" org-info)
391 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
392 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
393 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
394 (const :tag " mouse: Additional mouse support" org-mouse)
395 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
396 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
397 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
399 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
400 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
401 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
402 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
403 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
404 (const :tag "C collector: Collect properties into tables" org-collector)
405 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
406 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
407 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
408 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
409 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
410 (const :tag "C eval: Include command output as text" org-eval)
411 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
412 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
413 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
414 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
415 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
416 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
417 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
418 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
419 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
420 (const :tag "C mac-message: Links to messages in Apple Mail" org-mac-message)
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 (defgroup org-cycle nil
1036 "Options concerning visibility cycling in Org-mode."
1037 :tag "Org Cycle"
1038 :group 'org-structure)
1040 (defcustom org-cycle-skip-children-state-if-no-children t
1041 "Non-nil means skip CHILDREN state in entries that don't have any."
1042 :group 'org-cycle
1043 :type 'boolean)
1045 (defcustom org-cycle-max-level nil
1046 "Maximum level which should still be subject to visibility cycling.
1047 Levels higher than this will, for cycling, be treated as text, not a headline.
1048 When `org-odd-levels-only' is set, a value of N in this variable actually
1049 means 2N-1 stars as the limiting headline.
1050 When nil, cycle all levels.
1051 Note that the limiting level of cycling is also influenced by
1052 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1053 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1054 than its value."
1055 :group 'org-cycle
1056 :type '(choice
1057 (const :tag "No limit" nil)
1058 (integer :tag "Maximum level")))
1060 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1061 "Names of drawers. Drawers are not opened by cycling on the headline above.
1062 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1063 this:
1064 :DRAWERNAME:
1065 .....
1066 :END:
1067 The drawer \"PROPERTIES\" is special for capturing properties through
1068 the property API.
1070 Drawers can be defined on the per-file basis with a line like:
1072 #+DRAWERS: HIDDEN STATE PROPERTIES"
1073 :group 'org-structure
1074 :group 'org-cycle
1075 :type '(repeat (string :tag "Drawer Name")))
1077 (defcustom org-hide-block-startup nil
1078 "Non-nil means entering Org-mode will fold all blocks.
1079 This can also be set in on a per-file basis with
1081 #+STARTUP: hideblocks
1082 #+STARTUP: showblocks"
1083 :group 'org-startup
1084 :group 'org-cycle
1085 :type 'boolean)
1087 (defcustom org-cycle-global-at-bob nil
1088 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1089 This makes it possible to do global cycling without having to use S-TAB or
1090 \\[universal-argument] TAB. For this special case to work, the first line
1091 of the buffer must not be a headline -- it may be empty or some other text.
1092 When used in this way, `org-cycle-hook' is disabled temporarily to make
1093 sure the cursor stays at the beginning of the buffer. When this option is
1094 nil, don't do anything special at the beginning of the buffer."
1095 :group 'org-cycle
1096 :type 'boolean)
1098 (defcustom org-cycle-level-after-item/entry-creation t
1099 "Non-nil means cycle entry level or item indentation in new empty entries.
1101 When the cursor is at the end of an empty headline, i.e., with only stars
1102 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1103 and then all possible ancestor states, before returning to the original state.
1104 This makes data entry extremely fast: M-RET to create a new headline,
1105 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1107 When the cursor is at the end of an empty plain list item, one TAB will
1108 make it a subitem, two or more tabs will back up to make this an item
1109 higher up in the item hierarchy."
1110 :group 'org-cycle
1111 :type 'boolean)
1113 (defcustom org-cycle-emulate-tab t
1114 "Where should `org-cycle' emulate TAB.
1115 nil Never
1116 white Only in completely white lines
1117 whitestart Only at the beginning of lines, before the first non-white char
1118 t Everywhere except in headlines
1119 exc-hl-bol Everywhere except at the start of a headline
1120 If TAB is used in a place where it does not emulate TAB, the current subtree
1121 visibility is cycled."
1122 :group 'org-cycle
1123 :type '(choice (const :tag "Never" nil)
1124 (const :tag "Only in completely white lines" white)
1125 (const :tag "Before first char in a line" whitestart)
1126 (const :tag "Everywhere except in headlines" t)
1127 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1129 (defcustom org-cycle-separator-lines 2
1130 "Number of empty lines needed to keep an empty line between collapsed trees.
1131 If you leave an empty line between the end of a subtree and the following
1132 headline, this empty line is hidden when the subtree is folded.
1133 Org-mode will leave (exactly) one empty line visible if the number of
1134 empty lines is equal or larger to the number given in this variable.
1135 So the default 2 means at least 2 empty lines after the end of a subtree
1136 are needed to produce free space between a collapsed subtree and the
1137 following headline.
1139 If the number is negative, and the number of empty lines is at least -N,
1140 all empty lines are shown.
1142 Special case: when 0, never leave empty lines in collapsed view."
1143 :group 'org-cycle
1144 :type 'integer)
1145 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1147 (defcustom org-pre-cycle-hook nil
1148 "Hook that is run before visibility cycling is happening.
1149 The function(s) in this hook must accept a single argument which indicates
1150 the new state that will be set right after running this hook. The
1151 argument is a symbol. Before a global state change, it can have the values
1152 `overview', `content', or `all'. Before a local state change, it can have
1153 the values `folded', `children', or `subtree'."
1154 :group 'org-cycle
1155 :type 'hook)
1157 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1158 org-cycle-hide-drawers
1159 org-cycle-hide-inline-tasks
1160 org-cycle-show-empty-lines
1161 org-optimize-window-after-visibility-change)
1162 "Hook that is run after `org-cycle' has changed the buffer visibility.
1163 The function(s) in this hook must accept a single argument which indicates
1164 the new state that was set by the most recent `org-cycle' command. The
1165 argument is a symbol. After a global state change, it can have the values
1166 `overview', `contents', or `all'. After a local state change, it can have
1167 the values `folded', `children', or `subtree'."
1168 :group 'org-cycle
1169 :type 'hook)
1171 (defgroup org-edit-structure nil
1172 "Options concerning structure editing in Org-mode."
1173 :tag "Org Edit Structure"
1174 :group 'org-structure)
1176 (defcustom org-odd-levels-only nil
1177 "Non-nil means skip even levels and only use odd levels for the outline.
1178 This has the effect that two stars are being added/taken away in
1179 promotion/demotion commands. It also influences how levels are
1180 handled by the exporters.
1181 Changing it requires restart of `font-lock-mode' to become effective
1182 for fontification also in regions already fontified.
1183 You may also set this on a per-file basis by adding one of the following
1184 lines to the buffer:
1186 #+STARTUP: odd
1187 #+STARTUP: oddeven"
1188 :group 'org-edit-structure
1189 :group 'org-appearance
1190 :type 'boolean)
1192 (defcustom org-adapt-indentation t
1193 "Non-nil means adapt indentation to outline node level.
1195 When this variable is set, Org assumes that you write outlines by
1196 indenting text in each node to align with the headline (after the stars).
1197 The following issues are influenced by this variable:
1199 - When this is set and the *entire* text in an entry is indented, the
1200 indentation is increased by one space in a demotion command, and
1201 decreased by one in a promotion command. If any line in the entry
1202 body starts with text at column 0, indentation is not changed at all.
1204 - Property drawers and planning information is inserted indented when
1205 this variable s set. When nil, they will not be indented.
1207 - TAB indents a line relative to context. The lines below a headline
1208 will be indented when this variable is set.
1210 Note that this is all about true indentation, by adding and removing
1211 space characters. See also `org-indent.el' which does level-dependent
1212 indentation in a virtual way, i.e. at display time in Emacs."
1213 :group 'org-edit-structure
1214 :type 'boolean)
1216 (defcustom org-special-ctrl-a/e nil
1217 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1219 When t, `C-a' will bring back the cursor to the beginning of the
1220 headline text, i.e. after the stars and after a possible TODO
1221 keyword. In an item, this will be the position after bullet and
1222 check-box, if any. When the cursor is already at that position,
1223 another `C-a' will bring it to the beginning of the line.
1225 `C-e' will jump to the end of the headline, ignoring the presence
1226 of tags in the headline. A second `C-e' will then jump to the
1227 true end of the line, after any tags. This also means that, when
1228 this variable is non-nil, `C-e' also will never jump beyond the
1229 end of the heading of a folded section, i.e. not after the
1230 ellipses.
1232 When set to the symbol `reversed', the first `C-a' or `C-e' works
1233 normally, going to the true line boundary first. Only a directly
1234 following, identical keypress will bring the cursor to the
1235 special positions.
1237 This may also be a cons cell where the behavior for `C-a' and
1238 `C-e' is set separately."
1239 :group 'org-edit-structure
1240 :type '(choice
1241 (const :tag "off" nil)
1242 (const :tag "on: after stars/bullet and before tags first" t)
1243 (const :tag "reversed: true line boundary first" reversed)
1244 (cons :tag "Set C-a and C-e separately"
1245 (choice :tag "Special C-a"
1246 (const :tag "off" nil)
1247 (const :tag "on: after stars/bullet first" t)
1248 (const :tag "reversed: before stars/bullet first" reversed))
1249 (choice :tag "Special C-e"
1250 (const :tag "off" nil)
1251 (const :tag "on: before tags first" t)
1252 (const :tag "reversed: after tags first" reversed)))))
1253 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1255 (defcustom org-special-ctrl-k nil
1256 "Non-nil means `C-k' will behave specially in headlines.
1257 When nil, `C-k' will call the default `kill-line' command.
1258 When t, the following will happen while the cursor is in the headline:
1260 - When the cursor is at the beginning of a headline, kill the entire
1261 line and possible the folded subtree below the line.
1262 - When in the middle of the headline text, kill the headline up to the tags.
1263 - When after the headline text, kill the tags."
1264 :group 'org-edit-structure
1265 :type 'boolean)
1267 (defcustom org-ctrl-k-protect-subtree nil
1268 "Non-nil means, do not delete a hidden subtree with C-k.
1269 When set to the symbol `error', simply throw an error when C-k is
1270 used to kill (part-of) a headline that has hidden text behind it.
1271 Any other non-nil value will result in a query to the user, if it is
1272 OK to kill that hidden subtree. When nil, kill without remorse."
1273 :group 'org-edit-structure
1274 :version "24.1"
1275 :type '(choice
1276 (const :tag "Do not protect hidden subtrees" nil)
1277 (const :tag "Protect hidden subtrees with a security query" t)
1278 (const :tag "Never kill a hidden subtree with C-k" error)))
1280 (defcustom org-catch-invisible-edits nil
1281 "Check if in invisible region before inserting or deleting a character.
1282 Valid values are:
1284 nil Do not check, so just do invisible edits.
1285 error Throw an error and do nothing.
1286 show Make point visible, and do the requested edit.
1287 show-and-error Make point visible, then throw an error and abort the edit.
1288 smart Make point visible, and do insertion/deletion if it is
1289 adjacent to visible text and the change feels predictable.
1290 Never delete a previously invisible character or add in the
1291 middle or right after an invisible region. Basically, this
1292 allows insertion and backward-delete right before ellipses.
1293 FIXME: maybe in this case we should not even show?"
1294 :group 'org-edit-structure
1295 :version "24.1"
1296 :type '(choice
1297 (const :tag "Do not check" nil)
1298 (const :tag "Throw error when trying to edit" error)
1299 (const :tag "Unhide, but do not do the edit" show-and-error)
1300 (const :tag "Show invisible part and do the edit" show)
1301 (const :tag "Be smart and do the right thing" smart)))
1303 (defcustom org-yank-folded-subtrees t
1304 "Non-nil means when yanking subtrees, fold them.
1305 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1306 it starts with a heading and all other headings in it are either children
1307 or siblings, then fold all the subtrees. However, do this only if no
1308 text after the yank would be swallowed into a folded tree by this action."
1309 :group 'org-edit-structure
1310 :type 'boolean)
1312 (defcustom org-yank-adjusted-subtrees nil
1313 "Non-nil means when yanking subtrees, adjust the level.
1314 With this setting, `org-paste-subtree' is used to insert the subtree, see
1315 this function for details."
1316 :group 'org-edit-structure
1317 :type 'boolean)
1319 (defcustom org-M-RET-may-split-line '((default . t))
1320 "Non-nil means M-RET will split the line at the cursor position.
1321 When nil, it will go to the end of the line before making a
1322 new line.
1323 You may also set this option in a different way for different
1324 contexts. Valid contexts are:
1326 headline when creating a new headline
1327 item when creating a new item
1328 table in a table field
1329 default the value to be used for all contexts not explicitly
1330 customized"
1331 :group 'org-structure
1332 :group 'org-table
1333 :type '(choice
1334 (const :tag "Always" t)
1335 (const :tag "Never" nil)
1336 (repeat :greedy t :tag "Individual contexts"
1337 (cons
1338 (choice :tag "Context"
1339 (const headline)
1340 (const item)
1341 (const table)
1342 (const default))
1343 (boolean)))))
1346 (defcustom org-insert-heading-respect-content nil
1347 "Non-nil means insert new headings after the current subtree.
1348 When nil, the new heading is created directly after the current line.
1349 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1350 this variable on for the duration of the command."
1351 :group 'org-structure
1352 :type 'boolean)
1354 (defcustom org-blank-before-new-entry '((heading . auto)
1355 (plain-list-item . auto))
1356 "Should `org-insert-heading' leave a blank line before new heading/item?
1357 The value is an alist, with `heading' and `plain-list-item' as CAR,
1358 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1359 which case Org will look at the surrounding headings/items and try to
1360 make an intelligent decision whether to insert a blank line or not.
1362 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1363 the setting here is ignored and no empty line is inserted to avoid breaking
1364 the list structure."
1365 :group 'org-edit-structure
1366 :type '(list
1367 (cons (const heading)
1368 (choice (const :tag "Never" nil)
1369 (const :tag "Always" t)
1370 (const :tag "Auto" auto)))
1371 (cons (const plain-list-item)
1372 (choice (const :tag "Never" nil)
1373 (const :tag "Always" t)
1374 (const :tag "Auto" auto)))))
1376 (defcustom org-insert-heading-hook nil
1377 "Hook being run after inserting a new heading."
1378 :group 'org-edit-structure
1379 :type 'hook)
1381 (defcustom org-enable-fixed-width-editor t
1382 "Non-nil means lines starting with \":\" are treated as fixed-width.
1383 This currently only means they are never auto-wrapped.
1384 When nil, such lines will be treated like ordinary lines.
1385 See also the QUOTE keyword."
1386 :group 'org-edit-structure
1387 :type 'boolean)
1389 (defcustom org-goto-auto-isearch t
1390 "Non-nil means typing characters in `org-goto' starts incremental search.
1391 When nil, you can use these keybindings to navigate the buffer:
1393 q Quit the org-goto interface
1394 n Go to the next visible heading
1395 p Go to the previous visible heading
1396 f Go one heading forward on same level
1397 b Go one heading backward on same level
1398 u Go one heading up"
1399 :group 'org-edit-structure
1400 :type 'boolean)
1402 (defgroup org-sparse-trees nil
1403 "Options concerning sparse trees in Org-mode."
1404 :tag "Org Sparse Trees"
1405 :group 'org-structure)
1407 (defcustom org-highlight-sparse-tree-matches t
1408 "Non-nil means highlight all matches that define a sparse tree.
1409 The highlights will automatically disappear the next time the buffer is
1410 changed by an edit command."
1411 :group 'org-sparse-trees
1412 :type 'boolean)
1414 (defcustom org-remove-highlights-with-change t
1415 "Non-nil means any change to the buffer will remove temporary highlights.
1416 Such highlights are created by `org-occur' and `org-clock-display'.
1417 When nil, `C-c C-c needs to be used to get rid of the highlights.
1418 The highlights created by `org-preview-latex-fragment' always need
1419 `C-c C-c' to be removed."
1420 :group 'org-sparse-trees
1421 :group 'org-time
1422 :type 'boolean)
1425 (defcustom org-occur-hook '(org-first-headline-recenter)
1426 "Hook that is run after `org-occur' has constructed a sparse tree.
1427 This can be used to recenter the window to show as much of the structure
1428 as possible."
1429 :group 'org-sparse-trees
1430 :type 'hook)
1432 (defgroup org-imenu-and-speedbar nil
1433 "Options concerning imenu and speedbar in Org-mode."
1434 :tag "Org Imenu and Speedbar"
1435 :group 'org-structure)
1437 (defcustom org-imenu-depth 2
1438 "The maximum level for Imenu access to Org-mode headlines.
1439 This also applied for speedbar access."
1440 :group 'org-imenu-and-speedbar
1441 :type 'integer)
1443 (defgroup org-table nil
1444 "Options concerning tables in Org-mode."
1445 :tag "Org Table"
1446 :group 'org)
1448 (defcustom org-enable-table-editor 'optimized
1449 "Non-nil means lines starting with \"|\" are handled by the table editor.
1450 When nil, such lines will be treated like ordinary lines.
1452 When equal to the symbol `optimized', the table editor will be optimized to
1453 do the following:
1454 - Automatic overwrite mode in front of whitespace in table fields.
1455 This makes the structure of the table stay in tact as long as the edited
1456 field does not exceed the column width.
1457 - Minimize the number of realigns. Normally, the table is aligned each time
1458 TAB or RET are pressed to move to another field. With optimization this
1459 happens only if changes to a field might have changed the column width.
1460 Optimization requires replacing the functions `self-insert-command',
1461 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1462 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1463 very good at guessing when a re-align will be necessary, but you can always
1464 force one with \\[org-ctrl-c-ctrl-c].
1466 If you would like to use the optimized version in Org-mode, but the
1467 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1469 This variable can be used to turn on and off the table editor during a session,
1470 but in order to toggle optimization, a restart is required.
1472 See also the variable `org-table-auto-blank-field'."
1473 :group 'org-table
1474 :type '(choice
1475 (const :tag "off" nil)
1476 (const :tag "on" t)
1477 (const :tag "on, optimized" optimized)))
1479 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1480 (version<= emacs-version "24.1"))
1481 "Non-nil means cluster self-insert commands for undo when possible.
1482 If this is set, then, like in the Emacs command loop, 20 consecutive
1483 characters will be undone together.
1484 This is configurable, because there is some impact on typing performance."
1485 :group 'org-table
1486 :type 'boolean)
1488 (defcustom org-table-tab-recognizes-table.el t
1489 "Non-nil means TAB will automatically notice a table.el table.
1490 When it sees such a table, it moves point into it and - if necessary -
1491 calls `table-recognize-table'."
1492 :group 'org-table-editing
1493 :type 'boolean)
1495 (defgroup org-link nil
1496 "Options concerning links in Org-mode."
1497 :tag "Org Link"
1498 :group 'org)
1500 (defvar org-link-abbrev-alist-local nil
1501 "Buffer-local version of `org-link-abbrev-alist', which see.
1502 The value of this is taken from the #+LINK lines.")
1503 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1505 (defcustom org-link-abbrev-alist nil
1506 "Alist of link abbreviations.
1507 The car of each element is a string, to be replaced at the start of a link.
1508 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1509 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1511 [[linkkey:tag][description]]
1513 The 'linkkey' must be a word word, starting with a letter, followed
1514 by letters, numbers, '-' or '_'.
1516 If REPLACE is a string, the tag will simply be appended to create the link.
1517 If the string contains \"%s\", the tag will be inserted there. If the string
1518 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1519 at that point (see the function `url-hexify-string'). If the string contains
1520 the specifier \"%(my-function)\", then the custom function `my-function' will
1521 be invoked: this function takes the tag as its only argument and must return
1522 a string.
1524 REPLACE may also be a function that will be called with the tag as the
1525 only argument to create the link, which should be returned as a string.
1527 See the manual for examples."
1528 :group 'org-link
1529 :type '(repeat
1530 (cons
1531 (string :tag "Protocol")
1532 (choice
1533 (string :tag "Format")
1534 (function)))))
1536 (defcustom org-descriptive-links t
1537 "Non-nil means Org will display descriptive links.
1538 E.g. [[http://orgmode.org][Org website]] will be displayed as
1539 \"Org Website\", hiding the link itself and just displaying its
1540 description. When set to `nil', Org will display the full links
1541 literally.
1543 You can interactively set the value of this variable by calling
1544 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1545 :group 'org-link
1546 :type 'boolean)
1548 (defcustom org-link-file-path-type 'adaptive
1549 "How the path name in file links should be stored.
1550 Valid values are:
1552 relative Relative to the current directory, i.e. the directory of the file
1553 into which the link is being inserted.
1554 absolute Absolute path, if possible with ~ for home directory.
1555 noabbrev Absolute path, no abbreviation of home directory.
1556 adaptive Use relative path for files in the current directory and sub-
1557 directories of it. For other files, use an absolute path."
1558 :group 'org-link
1559 :type '(choice
1560 (const relative)
1561 (const absolute)
1562 (const noabbrev)
1563 (const adaptive)))
1565 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1566 "Types of links that should be activated in Org-mode files.
1567 This is a list of symbols, each leading to the activation of a certain link
1568 type. In principle, it does not hurt to turn on most link types - there may
1569 be a small gain when turning off unused link types. The types are:
1571 bracket The recommended [[link][description]] or [[link]] links with hiding.
1572 angle Links in angular brackets that may contain whitespace like
1573 <bbdb:Carsten Dominik>.
1574 plain Plain links in normal text, no whitespace, like http://google.com.
1575 radio Text that is matched by a radio target, see manual for details.
1576 tag Tag settings in a headline (link to tag search).
1577 date Time stamps (link to calendar).
1578 footnote Footnote labels.
1580 Changing this variable requires a restart of Emacs to become effective."
1581 :group 'org-link
1582 :type '(set :greedy t
1583 (const :tag "Double bracket links" bracket)
1584 (const :tag "Angular bracket links" angle)
1585 (const :tag "Plain text links" plain)
1586 (const :tag "Radio target matches" radio)
1587 (const :tag "Tags" tag)
1588 (const :tag "Timestamps" date)
1589 (const :tag "Footnotes" footnote)))
1591 (defcustom org-make-link-description-function nil
1592 "Function to use for generating link descriptions from links.
1593 When nil, the link location will be used. This function must take
1594 two parameters: the first one is the link, the second one is the
1595 description generated by `org-insert-link'. The function should
1596 return the description to use."
1597 :group 'org-link
1598 :type '(choice (const nil) (function)))
1600 (defgroup org-link-store nil
1601 "Options concerning storing links in Org-mode."
1602 :tag "Org Store Link"
1603 :group 'org-link)
1605 (defcustom org-url-hexify-p t
1606 "When non-nil, hexify URL when creating a link."
1607 :type 'boolean
1608 :version "24.3"
1609 :group 'org-link-store)
1611 (defcustom org-email-link-description-format "Email %c: %.30s"
1612 "Format of the description part of a link to an email or usenet message.
1613 The following %-escapes will be replaced by corresponding information:
1615 %F full \"From\" field
1616 %f name, taken from \"From\" field, address if no name
1617 %T full \"To\" field
1618 %t first name in \"To\" field, address if no name
1619 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1620 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1621 %s subject
1622 %d date
1623 %m message-id.
1625 You may use normal field width specification between the % and the letter.
1626 This is for example useful to limit the length of the subject.
1628 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1629 :group 'org-link-store
1630 :type 'string)
1632 (defcustom org-from-is-user-regexp
1633 (let (r1 r2)
1634 (when (and user-mail-address (not (string= user-mail-address "")))
1635 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1636 (when (and user-full-name (not (string= user-full-name "")))
1637 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1638 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1639 "Regexp matched against the \"From:\" header of an email or usenet message.
1640 It should match if the message is from the user him/herself."
1641 :group 'org-link-store
1642 :type 'regexp)
1644 (defcustom org-context-in-file-links t
1645 "Non-nil means file links from `org-store-link' contain context.
1646 A search string will be added to the file name with :: as separator and
1647 used to find the context when the link is activated by the command
1648 `org-open-at-point'. When this option is t, the entire active region
1649 will be placed in the search string of the file link. If set to a
1650 positive integer, only the first n lines of context will be stored.
1652 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1653 negates this setting for the duration of the command."
1654 :group 'org-link-store
1655 :type '(choice boolean integer))
1657 (defcustom org-keep-stored-link-after-insertion nil
1658 "Non-nil means keep link in list for entire session.
1660 The command `org-store-link' adds a link pointing to the current
1661 location to an internal list. These links accumulate during a session.
1662 The command `org-insert-link' can be used to insert links into any
1663 Org-mode file (offering completion for all stored links). When this
1664 option is nil, every link which has been inserted once using \\[org-insert-link]
1665 will be removed from the list, to make completing the unused links
1666 more efficient."
1667 :group 'org-link-store
1668 :type 'boolean)
1670 (defgroup org-link-follow nil
1671 "Options concerning following links in Org-mode."
1672 :tag "Org Follow Link"
1673 :group 'org-link)
1675 (defcustom org-link-translation-function nil
1676 "Function to translate links with different syntax to Org syntax.
1677 This can be used to translate links created for example by the Planner
1678 or emacs-wiki packages to Org syntax.
1679 The function must accept two parameters, a TYPE containing the link
1680 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1681 which is everything after the link protocol. It should return a cons
1682 with possibly modified values of type and path.
1683 Org contains a function for this, so if you set this variable to
1684 `org-translate-link-from-planner', you should be able follow many
1685 links created by planner."
1686 :group 'org-link-follow
1687 :type '(choice (const nil) (function)))
1689 (defcustom org-follow-link-hook nil
1690 "Hook that is run after a link has been followed."
1691 :group 'org-link-follow
1692 :type 'hook)
1694 (defcustom org-tab-follows-link nil
1695 "Non-nil means on links TAB will follow the link.
1696 Needs to be set before org.el is loaded.
1697 This really should not be used, it does not make sense, and the
1698 implementation is bad."
1699 :group 'org-link-follow
1700 :type 'boolean)
1702 (defcustom org-return-follows-link nil
1703 "Non-nil means on links RET will follow the link.
1704 In tables, the special behavior of RET has precedence."
1705 :group 'org-link-follow
1706 :type 'boolean)
1708 (defcustom org-mouse-1-follows-link
1709 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1710 "Non-nil means mouse-1 on a link will follow the link.
1711 A longer mouse click will still set point. Does not work on XEmacs.
1712 Needs to be set before org.el is loaded."
1713 :group 'org-link-follow
1714 :type 'boolean)
1716 (defcustom org-mark-ring-length 4
1717 "Number of different positions to be recorded in the ring.
1718 Changing this requires a restart of Emacs to work correctly."
1719 :group 'org-link-follow
1720 :type 'integer)
1722 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1723 "Non-nil means internal links in Org files must exactly match a headline.
1724 When nil, the link search tries to match a phrase with all words
1725 in the search text."
1726 :group 'org-link-follow
1727 :version "24.1"
1728 :type '(choice
1729 (const :tag "Use fuzzy text search" nil)
1730 (const :tag "Match only exact headline" t)
1731 (const :tag "Match exact headline or query to create it"
1732 query-to-create)))
1734 (defcustom org-link-frame-setup
1735 '((vm . vm-visit-folder-other-frame)
1736 (vm-imap . vm-visit-imap-folder-other-frame)
1737 (gnus . org-gnus-no-new-news)
1738 (file . find-file-other-window)
1739 (wl . wl-other-frame))
1740 "Setup the frame configuration for following links.
1741 When following a link with Emacs, it may often be useful to display
1742 this link in another window or frame. This variable can be used to
1743 set this up for the different types of links.
1744 For VM, use any of
1745 `vm-visit-folder'
1746 `vm-visit-folder-other-window'
1747 `vm-visit-folder-other-frame'
1748 For Gnus, use any of
1749 `gnus'
1750 `gnus-other-frame'
1751 `org-gnus-no-new-news'
1752 For FILE, use any of
1753 `find-file'
1754 `find-file-other-window'
1755 `find-file-other-frame'
1756 For Wanderlust use any of
1757 `wl'
1758 `wl-other-frame'
1759 For the calendar, use the variable `calendar-setup'.
1760 For BBDB, it is currently only possible to display the matches in
1761 another window."
1762 :group 'org-link-follow
1763 :type '(list
1764 (cons (const vm)
1765 (choice
1766 (const vm-visit-folder)
1767 (const vm-visit-folder-other-window)
1768 (const vm-visit-folder-other-frame)))
1769 (cons (const vm-imap)
1770 (choice
1771 (const vm-visit-imap-folder)
1772 (const vm-visit-imap-folder-other-window)
1773 (const vm-visit-imap-folder-other-frame)))
1774 (cons (const gnus)
1775 (choice
1776 (const gnus)
1777 (const gnus-other-frame)
1778 (const org-gnus-no-new-news)))
1779 (cons (const file)
1780 (choice
1781 (const find-file)
1782 (const find-file-other-window)
1783 (const find-file-other-frame)))
1784 (cons (const wl)
1785 (choice
1786 (const wl)
1787 (const wl-other-frame)))))
1789 (defcustom org-display-internal-link-with-indirect-buffer nil
1790 "Non-nil means use indirect buffer to display infile links.
1791 Activating internal links (from one location in a file to another location
1792 in the same file) normally just jumps to the location. When the link is
1793 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1794 is displayed in
1795 another window. When this option is set, the other window actually displays
1796 an indirect buffer clone of the current buffer, to avoid any visibility
1797 changes to the current buffer."
1798 :group 'org-link-follow
1799 :type 'boolean)
1801 (defcustom org-open-non-existing-files nil
1802 "Non-nil means `org-open-file' will open non-existing files.
1803 When nil, an error will be generated.
1804 This variable applies only to external applications because they
1805 might choke on non-existing files. If the link is to a file that
1806 will be opened in Emacs, the variable is ignored."
1807 :group 'org-link-follow
1808 :type 'boolean)
1810 (defcustom org-open-directory-means-index-dot-org nil
1811 "Non-nil means a link to a directory really means to index.org.
1812 When nil, following a directory link will run dired or open a finder/explorer
1813 window on that directory."
1814 :group 'org-link-follow
1815 :type 'boolean)
1817 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1818 "Function and arguments to call for following mailto links.
1819 This is a list with the first element being a Lisp function, and the
1820 remaining elements being arguments to the function. In string arguments,
1821 %a will be replaced by the address, and %s will be replaced by the subject
1822 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1823 :group 'org-link-follow
1824 :type '(choice
1825 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1826 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1827 (const :tag "message-mail" (message-mail "%a" "%s"))
1828 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1830 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1831 "Non-nil means ask for confirmation before executing shell links.
1832 Shell links can be dangerous: just think about a link
1834 [[shell:rm -rf ~/*][Google Search]]
1836 This link would show up in your Org-mode document as \"Google Search\",
1837 but really it would remove your entire home directory.
1838 Therefore we advise against setting this variable to nil.
1839 Just change it to `y-or-n-p' if you want to confirm with a
1840 single keystroke rather than having to type \"yes\"."
1841 :group 'org-link-follow
1842 :type '(choice
1843 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1844 (const :tag "with y-or-n (faster)" y-or-n-p)
1845 (const :tag "no confirmation (dangerous)" nil)))
1846 (put 'org-confirm-shell-link-function
1847 'safe-local-variable
1848 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1850 (defcustom org-confirm-shell-link-not-regexp ""
1851 "A regexp to skip confirmation for shell links."
1852 :group 'org-link-follow
1853 :version "24.1"
1854 :type 'regexp)
1856 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1857 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1858 Elisp links can be dangerous: just think about a link
1860 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1862 This link would show up in your Org-mode document as \"Google Search\",
1863 but really it would remove your entire home directory.
1864 Therefore we advise against setting this variable to nil.
1865 Just change it to `y-or-n-p' if you want to confirm with a
1866 single keystroke rather than having to type \"yes\"."
1867 :group 'org-link-follow
1868 :type '(choice
1869 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1870 (const :tag "with y-or-n (faster)" y-or-n-p)
1871 (const :tag "no confirmation (dangerous)" nil)))
1872 (put 'org-confirm-shell-link-function
1873 'safe-local-variable
1874 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1876 (defcustom org-confirm-elisp-link-not-regexp ""
1877 "A regexp to skip confirmation for Elisp links."
1878 :group 'org-link-follow
1879 :version "24.1"
1880 :type 'regexp)
1882 (defconst org-file-apps-defaults-gnu
1883 '((remote . emacs)
1884 (system . mailcap)
1885 (t . mailcap))
1886 "Default file applications on a UNIX or GNU/Linux system.
1887 See `org-file-apps'.")
1889 (defconst org-file-apps-defaults-macosx
1890 '((remote . emacs)
1891 (t . "open %s")
1892 (system . "open %s")
1893 ("ps.gz" . "gv %s")
1894 ("eps.gz" . "gv %s")
1895 ("dvi" . "xdvi %s")
1896 ("fig" . "xfig %s"))
1897 "Default file applications on a MacOS X system.
1898 The system \"open\" is known as a default, but we use X11 applications
1899 for some files for which the OS does not have a good default.
1900 See `org-file-apps'.")
1902 (defconst org-file-apps-defaults-windowsnt
1903 (list
1904 '(remote . emacs)
1905 (cons t
1906 (list (if (featurep 'xemacs)
1907 'mswindows-shell-execute
1908 'w32-shell-execute)
1909 "open" 'file))
1910 (cons 'system
1911 (list (if (featurep 'xemacs)
1912 'mswindows-shell-execute
1913 'w32-shell-execute)
1914 "open" 'file)))
1915 "Default file applications on a Windows NT system.
1916 The system \"open\" is used for most files.
1917 See `org-file-apps'.")
1919 (defcustom org-file-apps
1920 '((auto-mode . emacs)
1921 ("\\.mm\\'" . default)
1922 ("\\.x?html?\\'" . default)
1923 ("\\.pdf\\'" . default))
1924 "External applications for opening `file:path' items in a document.
1925 Org-mode uses system defaults for different file types, but
1926 you can use this variable to set the application for a given file
1927 extension. The entries in this list are cons cells where the car identifies
1928 files and the cdr the corresponding command. Possible values for the
1929 file identifier are
1930 \"string\" A string as a file identifier can be interpreted in different
1931 ways, depending on its contents:
1933 - Alphanumeric characters only:
1934 Match links with this file extension.
1935 Example: (\"pdf\" . \"evince %s\")
1936 to open PDFs with evince.
1938 - Regular expression: Match links where the
1939 filename matches the regexp. If you want to
1940 use groups here, use shy groups.
1942 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1943 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1944 to open *.html and *.xhtml with firefox.
1946 - Regular expression which contains (non-shy) groups:
1947 Match links where the whole link, including \"::\", and
1948 anything after that, matches the regexp.
1949 In a custom command string, %1, %2, etc. are replaced with
1950 the parts of the link that were matched by the groups.
1951 For backwards compatibility, if a command string is given
1952 that does not use any of the group matches, this case is
1953 handled identically to the second one (i.e. match against
1954 file name only).
1955 In a custom lisp form, you can access the group matches with
1956 (match-string n link).
1958 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1959 to open [[file:document.pdf::5]] with evince at page 5.
1961 `directory' Matches a directory
1962 `remote' Matches a remote file, accessible through tramp or efs.
1963 Remote files most likely should be visited through Emacs
1964 because external applications cannot handle such paths.
1965 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1966 so all files Emacs knows how to handle. Using this with
1967 command `emacs' will open most files in Emacs. Beware that this
1968 will also open html files inside Emacs, unless you add
1969 (\"html\" . default) to the list as well.
1970 t Default for files not matched by any of the other options.
1971 `system' The system command to open files, like `open' on Windows
1972 and Mac OS X, and mailcap under GNU/Linux. This is the command
1973 that will be selected if you call `C-c C-o' with a double
1974 \\[universal-argument] \\[universal-argument] prefix.
1976 Possible values for the command are:
1977 `emacs' The file will be visited by the current Emacs process.
1978 `default' Use the default application for this file type, which is the
1979 association for t in the list, most likely in the system-specific
1980 part.
1981 This can be used to overrule an unwanted setting in the
1982 system-specific variable.
1983 `system' Use the system command for opening files, like \"open\".
1984 This command is specified by the entry whose car is `system'.
1985 Most likely, the system-specific version of this variable
1986 does define this command, but you can overrule/replace it
1987 here.
1988 string A command to be executed by a shell; %s will be replaced
1989 by the path to the file.
1990 sexp A Lisp form which will be evaluated. The file path will
1991 be available in the Lisp variable `file'.
1992 For more examples, see the system specific constants
1993 `org-file-apps-defaults-macosx'
1994 `org-file-apps-defaults-windowsnt'
1995 `org-file-apps-defaults-gnu'."
1996 :group 'org-link-follow
1997 :type '(repeat
1998 (cons (choice :value ""
1999 (string :tag "Extension")
2000 (const :tag "System command to open files" system)
2001 (const :tag "Default for unrecognized files" t)
2002 (const :tag "Remote file" remote)
2003 (const :tag "Links to a directory" directory)
2004 (const :tag "Any files that have Emacs modes"
2005 auto-mode))
2006 (choice :value ""
2007 (const :tag "Visit with Emacs" emacs)
2008 (const :tag "Use default" default)
2009 (const :tag "Use the system command" system)
2010 (string :tag "Command")
2011 (sexp :tag "Lisp form")))))
2013 (defcustom org-doi-server-url "http://dx.doi.org/"
2014 "The URL of the DOI server."
2015 :type 'string
2016 :version "24.3"
2017 :group 'org-link-follow)
2019 (defgroup org-refile nil
2020 "Options concerning refiling entries in Org-mode."
2021 :tag "Org Refile"
2022 :group 'org)
2024 (defcustom org-directory "~/org"
2025 "Directory with org files.
2026 This is just a default location to look for Org files. There is no need
2027 at all to put your files into this directory. It is only used in the
2028 following situations:
2030 1. When a capture template specifies a target file that is not an
2031 absolute path. The path will then be interpreted relative to
2032 `org-directory'
2033 2. When a capture note is filed away in an interactive way (when exiting the
2034 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2035 with `org-directory' as the default path."
2036 :group 'org-refile
2037 :group 'org-remember
2038 :group 'org-capture
2039 :type 'directory)
2041 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2042 "Default target for storing notes.
2043 Used as a fall back file for org-remember.el and org-capture.el, for
2044 templates that do not specify a target file."
2045 :group 'org-refile
2046 :group 'org-remember
2047 :group 'org-capture
2048 :type '(choice
2049 (const :tag "Default from remember-data-file" nil)
2050 file))
2052 (defcustom org-goto-interface 'outline
2053 "The default interface to be used for `org-goto'.
2054 Allowed values are:
2055 outline The interface shows an outline of the relevant file
2056 and the correct heading is found by moving through
2057 the outline or by searching with incremental search.
2058 outline-path-completion Headlines in the current buffer are offered via
2059 completion. This is the interface also used by
2060 the refile command."
2061 :group 'org-refile
2062 :type '(choice
2063 (const :tag "Outline" outline)
2064 (const :tag "Outline-path-completion" outline-path-completion)))
2066 (defcustom org-goto-max-level 5
2067 "Maximum target level when running `org-goto' with refile interface."
2068 :group 'org-refile
2069 :type 'integer)
2071 (defcustom org-reverse-note-order nil
2072 "Non-nil means store new notes at the beginning of a file or entry.
2073 When nil, new notes will be filed to the end of a file or entry.
2074 This can also be a list with cons cells of regular expressions that
2075 are matched against file names, and values."
2076 :group 'org-remember
2077 :group 'org-capture
2078 :group 'org-refile
2079 :type '(choice
2080 (const :tag "Reverse always" t)
2081 (const :tag "Reverse never" nil)
2082 (repeat :tag "By file name regexp"
2083 (cons regexp boolean))))
2085 (defcustom org-log-refile nil
2086 "Information to record when a task is refiled.
2088 Possible values are:
2090 nil Don't add anything
2091 time Add a time stamp to the task
2092 note Prompt for a note and add it with template `org-log-note-headings'
2094 This option can also be set with on a per-file-basis with
2096 #+STARTUP: nologrefile
2097 #+STARTUP: logrefile
2098 #+STARTUP: lognoterefile
2100 You can have local logging settings for a subtree by setting the LOGGING
2101 property to one or more of these keywords.
2103 When bulk-refiling from the agenda, the value `note' is forbidden and
2104 will temporarily be changed to `time'."
2105 :group 'org-refile
2106 :group 'org-progress
2107 :version "24.1"
2108 :type '(choice
2109 (const :tag "No logging" nil)
2110 (const :tag "Record timestamp" time)
2111 (const :tag "Record timestamp with note." note)))
2113 (defcustom org-refile-targets nil
2114 "Targets for refiling entries with \\[org-refile].
2115 This is a list of cons cells. Each cell contains:
2116 - a specification of the files to be considered, either a list of files,
2117 or a symbol whose function or variable value will be used to retrieve
2118 a file name or a list of file names. If you use `org-agenda-files' for
2119 that, all agenda files will be scanned for targets. Nil means consider
2120 headings in the current buffer.
2121 - A specification of how to find candidate refile targets. This may be
2122 any of:
2123 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2124 This tag has to be present in all target headlines, inheritance will
2125 not be considered.
2126 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2127 todo keyword.
2128 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2129 headlines that are refiling targets.
2130 - a cons cell (:level . N). Any headline of level N is considered a target.
2131 Note that, when `org-odd-levels-only' is set, level corresponds to
2132 order in hierarchy, not to the number of stars.
2133 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2134 Note that, when `org-odd-levels-only' is set, level corresponds to
2135 order in hierarchy, not to the number of stars.
2137 Each element of this list generates a set of possible targets.
2138 The union of these sets is presented (with completion) to
2139 the user by `org-refile'.
2141 You can set the variable `org-refile-target-verify-function' to a function
2142 to verify each headline found by the simple criteria above.
2144 When this variable is nil, all top-level headlines in the current buffer
2145 are used, equivalent to the value `((nil . (:level . 1))'."
2146 :group 'org-refile
2147 :type '(repeat
2148 (cons
2149 (choice :value org-agenda-files
2150 (const :tag "All agenda files" org-agenda-files)
2151 (const :tag "Current buffer" nil)
2152 (function) (variable) (file))
2153 (choice :tag "Identify target headline by"
2154 (cons :tag "Specific tag" (const :value :tag) (string))
2155 (cons :tag "TODO keyword" (const :value :todo) (string))
2156 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2157 (cons :tag "Level number" (const :value :level) (integer))
2158 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2160 (defcustom org-refile-target-verify-function nil
2161 "Function to verify if the headline at point should be a refile target.
2162 The function will be called without arguments, with point at the
2163 beginning of the headline. It should return t and leave point
2164 where it is if the headline is a valid target for refiling.
2166 If the target should not be selected, the function must return nil.
2167 In addition to this, it may move point to a place from where the search
2168 should be continued. For example, the function may decide that the entire
2169 subtree of the current entry should be excluded and move point to the end
2170 of the subtree."
2171 :group 'org-refile
2172 :type '(choice
2173 (const nil)
2174 (function)))
2176 (defcustom org-refile-use-cache nil
2177 "Non-nil means cache refile targets to speed up the process.
2178 The cache for a particular file will be updated automatically when
2179 the buffer has been killed, or when any of the marker used for flagging
2180 refile targets no longer points at a live buffer.
2181 If you have added new entries to a buffer that might themselves be targets,
2182 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2183 find that easier, `C-u C-u C-u C-c C-w'."
2184 :group 'org-refile
2185 :version "24.1"
2186 :type 'boolean)
2188 (defcustom org-refile-use-outline-path nil
2189 "Non-nil means provide refile targets as paths.
2190 So a level 3 headline will be available as level1/level2/level3.
2192 When the value is `file', also include the file name (without directory)
2193 into the path. In this case, you can also stop the completion after
2194 the file name, to get entries inserted as top level in the file.
2196 When `full-file-path', include the full file path."
2197 :group 'org-refile
2198 :type '(choice
2199 (const :tag "Not" nil)
2200 (const :tag "Yes" t)
2201 (const :tag "Start with file name" file)
2202 (const :tag "Start with full file path" full-file-path)))
2204 (defcustom org-outline-path-complete-in-steps t
2205 "Non-nil means complete the outline path in hierarchical steps.
2206 When Org-mode uses the refile interface to select an outline path
2207 \(see variable `org-refile-use-outline-path'), the completion of
2208 the path can be done is a single go, or if can be done in steps down
2209 the headline hierarchy. Going in steps is probably the best if you
2210 do not use a special completion package like `ido' or `icicles'.
2211 However, when using these packages, going in one step can be very
2212 fast, while still showing the whole path to the entry."
2213 :group 'org-refile
2214 :type 'boolean)
2216 (defcustom org-refile-allow-creating-parent-nodes nil
2217 "Non-nil means allow to create new nodes as refile targets.
2218 New nodes are then created by adding \"/new node name\" to the completion
2219 of an existing node. When the value of this variable is `confirm',
2220 new node creation must be confirmed by the user (recommended)
2221 When nil, the completion must match an existing entry.
2223 Note that, if the new heading is not seen by the criteria
2224 listed in `org-refile-targets', multiple instances of the same
2225 heading would be created by trying again to file under the new
2226 heading."
2227 :group 'org-refile
2228 :type '(choice
2229 (const :tag "Never" nil)
2230 (const :tag "Always" t)
2231 (const :tag "Prompt for confirmation" confirm)))
2233 (defcustom org-refile-active-region-within-subtree nil
2234 "Non-nil means also refile active region within a subtree.
2236 By default `org-refile' doesn't allow refiling regions if they
2237 don't contain a set of subtrees, but it might be convenient to
2238 do so sometimes: in that case, the first line of the region is
2239 converted to a headline before refiling."
2240 :group 'org-refile
2241 :version "24.1"
2242 :type 'boolean)
2244 (defgroup org-todo nil
2245 "Options concerning TODO items in Org-mode."
2246 :tag "Org TODO"
2247 :group 'org)
2249 (defgroup org-progress nil
2250 "Options concerning Progress logging in Org-mode."
2251 :tag "Org Progress"
2252 :group 'org-time)
2254 (defvar org-todo-interpretation-widgets
2255 '((:tag "Sequence (cycling hits every state)" sequence)
2256 (:tag "Type (cycling directly to DONE)" type))
2257 "The available interpretation symbols for customizing `org-todo-keywords'.
2258 Interested libraries should add to this list.")
2260 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2261 "List of TODO entry keyword sequences and their interpretation.
2262 \\<org-mode-map>This is a list of sequences.
2264 Each sequence starts with a symbol, either `sequence' or `type',
2265 indicating if the keywords should be interpreted as a sequence of
2266 action steps, or as different types of TODO items. The first
2267 keywords are states requiring action - these states will select a headline
2268 for inclusion into the global TODO list Org-mode produces. If one of
2269 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2270 signify that no further action is necessary. If \"|\" is not found,
2271 the last keyword is treated as the only DONE state of the sequence.
2273 The command \\[org-todo] cycles an entry through these states, and one
2274 additional state where no keyword is present. For details about this
2275 cycling, see the manual.
2277 TODO keywords and interpretation can also be set on a per-file basis with
2278 the special #+SEQ_TODO and #+TYP_TODO lines.
2280 Each keyword can optionally specify a character for fast state selection
2281 \(in combination with the variable `org-use-fast-todo-selection')
2282 and specifiers for state change logging, using the same syntax that
2283 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2284 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2285 indicates to record a time stamp each time this state is selected.
2287 Each keyword may also specify if a timestamp or a note should be
2288 recorded when entering or leaving the state, by adding additional
2289 characters in the parenthesis after the keyword. This looks like this:
2290 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2291 record only the time of the state change. With X and Y being either
2292 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2293 Y when leaving the state if and only if the *target* state does not
2294 define X. You may omit any of the fast-selection key or X or /Y,
2295 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2297 For backward compatibility, this variable may also be just a list
2298 of keywords. In this case the interpretation (sequence or type) will be
2299 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2300 :group 'org-todo
2301 :group 'org-keywords
2302 :type '(choice
2303 (repeat :tag "Old syntax, just keywords"
2304 (string :tag "Keyword"))
2305 (repeat :tag "New syntax"
2306 (cons
2307 (choice
2308 :tag "Interpretation"
2309 ;;Quick and dirty way to see
2310 ;;`org-todo-interpretations'. This takes the
2311 ;;place of item arguments
2312 :convert-widget
2313 (lambda (widget)
2314 (widget-put widget
2315 :args (mapcar
2316 #'(lambda (x)
2317 (widget-convert
2318 (cons 'const x)))
2319 org-todo-interpretation-widgets))
2320 widget))
2321 (repeat
2322 (string :tag "Keyword"))))))
2324 (defvar org-todo-keywords-1 nil
2325 "All TODO and DONE keywords active in a buffer.")
2326 (make-variable-buffer-local 'org-todo-keywords-1)
2327 (defvar org-todo-keywords-for-agenda nil)
2328 (defvar org-done-keywords-for-agenda nil)
2329 (defvar org-drawers-for-agenda nil)
2330 (defvar org-todo-keyword-alist-for-agenda nil)
2331 (defvar org-tag-alist-for-agenda nil
2332 "Alist of all tags from all agenda files.")
2333 (defvar org-tag-groups-alist-for-agenda nil
2334 "Alist of all groups tags from all current agenda files.")
2335 (defvar org-tag-groups-alist nil)
2336 (make-variable-buffer-local 'org-tag-groups-alist)
2337 (defvar org-agenda-contributing-files nil)
2338 (defvar org-not-done-keywords nil)
2339 (make-variable-buffer-local 'org-not-done-keywords)
2340 (defvar org-done-keywords nil)
2341 (make-variable-buffer-local 'org-done-keywords)
2342 (defvar org-todo-heads nil)
2343 (make-variable-buffer-local 'org-todo-heads)
2344 (defvar org-todo-sets nil)
2345 (make-variable-buffer-local 'org-todo-sets)
2346 (defvar org-todo-log-states nil)
2347 (make-variable-buffer-local 'org-todo-log-states)
2348 (defvar org-todo-kwd-alist nil)
2349 (make-variable-buffer-local 'org-todo-kwd-alist)
2350 (defvar org-todo-key-alist nil)
2351 (make-variable-buffer-local 'org-todo-key-alist)
2352 (defvar org-todo-key-trigger nil)
2353 (make-variable-buffer-local 'org-todo-key-trigger)
2355 (defcustom org-todo-interpretation 'sequence
2356 "Controls how TODO keywords are interpreted.
2357 This variable is in principle obsolete and is only used for
2358 backward compatibility, if the interpretation of todo keywords is
2359 not given already in `org-todo-keywords'. See that variable for
2360 more information."
2361 :group 'org-todo
2362 :group 'org-keywords
2363 :type '(choice (const sequence)
2364 (const type)))
2366 (defcustom org-use-fast-todo-selection t
2367 "Non-nil means use the fast todo selection scheme with C-c C-t.
2368 This variable describes if and under what circumstances the cycling
2369 mechanism for TODO keywords will be replaced by a single-key, direct
2370 selection scheme.
2372 When nil, fast selection is never used.
2374 When the symbol `prefix', it will be used when `org-todo' is called
2375 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2376 `C-u t' in an agenda buffer.
2378 When t, fast selection is used by default. In this case, the prefix
2379 argument forces cycling instead.
2381 In all cases, the special interface is only used if access keys have
2382 actually been assigned by the user, i.e. if keywords in the configuration
2383 are followed by a letter in parenthesis, like TODO(t)."
2384 :group 'org-todo
2385 :type '(choice
2386 (const :tag "Never" nil)
2387 (const :tag "By default" t)
2388 (const :tag "Only with C-u C-c C-t" prefix)))
2390 (defcustom org-provide-todo-statistics t
2391 "Non-nil means update todo statistics after insert and toggle.
2392 ALL-HEADLINES means update todo statistics by including headlines
2393 with no TODO keyword as well, counting them as not done.
2394 A list of TODO keywords means the same, but skip keywords that are
2395 not in this list.
2397 When this is set, todo statistics is updated in the parent of the
2398 current entry each time a todo state is changed."
2399 :group 'org-todo
2400 :type '(choice
2401 (const :tag "Yes, only for TODO entries" t)
2402 (const :tag "Yes, including all entries" 'all-headlines)
2403 (repeat :tag "Yes, for TODOs in this list"
2404 (string :tag "TODO keyword"))
2405 (other :tag "No TODO statistics" nil)))
2407 (defcustom org-hierarchical-todo-statistics t
2408 "Non-nil means TODO statistics covers just direct children.
2409 When nil, all entries in the subtree are considered.
2410 This has only an effect if `org-provide-todo-statistics' is set.
2411 To set this to nil for only a single subtree, use a COOKIE_DATA
2412 property and include the word \"recursive\" into the value."
2413 :group 'org-todo
2414 :type 'boolean)
2416 (defcustom org-after-todo-state-change-hook nil
2417 "Hook which is run after the state of a TODO item was changed.
2418 The new state (a string with a TODO keyword, or nil) is available in the
2419 Lisp variable `org-state'."
2420 :group 'org-todo
2421 :type 'hook)
2423 (defvar org-blocker-hook nil
2424 "Hook for functions that are allowed to block a state change.
2426 Functions in this hook should not modify the buffer.
2427 Each function gets as its single argument a property list,
2428 see `org-trigger-hook' for more information about this list.
2430 If any of the functions in this hook returns nil, the state change
2431 is blocked.")
2433 (defvar org-trigger-hook nil
2434 "Hook for functions that are triggered by a state change.
2436 Each function gets as its single argument a property list with at
2437 least the following elements:
2439 (:type type-of-change :position pos-at-entry-start
2440 :from old-state :to new-state)
2442 Depending on the type, more properties may be present.
2444 This mechanism is currently implemented for:
2446 TODO state changes
2447 ------------------
2448 :type todo-state-change
2449 :from previous state (keyword as a string), or nil, or a symbol
2450 'todo' or 'done', to indicate the general type of state.
2451 :to new state, like in :from")
2453 (defcustom org-enforce-todo-dependencies nil
2454 "Non-nil means undone TODO entries will block switching the parent to DONE.
2455 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2456 be blocked if any prior sibling is not yet done.
2457 Finally, if the parent is blocked because of ordered siblings of its own,
2458 the child will also be blocked."
2459 :set (lambda (var val)
2460 (set var val)
2461 (if val
2462 (add-hook 'org-blocker-hook
2463 'org-block-todo-from-children-or-siblings-or-parent)
2464 (remove-hook 'org-blocker-hook
2465 'org-block-todo-from-children-or-siblings-or-parent)))
2466 :group 'org-todo
2467 :type 'boolean)
2469 (defcustom org-enforce-todo-checkbox-dependencies nil
2470 "Non-nil means unchecked boxes will block switching the parent to DONE.
2471 When this is nil, checkboxes have no influence on switching TODO states.
2472 When non-nil, you first need to check off all check boxes before the TODO
2473 entry can be switched to DONE.
2474 This variable needs to be set before org.el is loaded, and you need to
2475 restart Emacs after a change to make the change effective. The only way
2476 to change is while Emacs is running is through the customize interface."
2477 :set (lambda (var val)
2478 (set var val)
2479 (if val
2480 (add-hook 'org-blocker-hook
2481 'org-block-todo-from-checkboxes)
2482 (remove-hook 'org-blocker-hook
2483 'org-block-todo-from-checkboxes)))
2484 :group 'org-todo
2485 :type 'boolean)
2487 (defcustom org-treat-insert-todo-heading-as-state-change nil
2488 "Non-nil means inserting a TODO heading is treated as state change.
2489 So when the command \\[org-insert-todo-heading] is used, state change
2490 logging will apply if appropriate. When nil, the new TODO item will
2491 be inserted directly, and no logging will take place."
2492 :group 'org-todo
2493 :type 'boolean)
2495 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2496 "Non-nil means switching TODO states with S-cursor counts as state change.
2497 This is the default behavior. However, setting this to nil allows a
2498 convenient way to select a TODO state and bypass any logging associated
2499 with that."
2500 :group 'org-todo
2501 :type 'boolean)
2503 (defcustom org-todo-state-tags-triggers nil
2504 "Tag changes that should be triggered by TODO state changes.
2505 This is a list. Each entry is
2507 (state-change (tag . flag) .......)
2509 State-change can be a string with a state, and empty string to indicate the
2510 state that has no TODO keyword, or it can be one of the symbols `todo'
2511 or `done', meaning any not-done or done state, respectively."
2512 :group 'org-todo
2513 :group 'org-tags
2514 :type '(repeat
2515 (cons (choice :tag "When changing to"
2516 (const :tag "Not-done state" todo)
2517 (const :tag "Done state" done)
2518 (string :tag "State"))
2519 (repeat
2520 (cons :tag "Tag action"
2521 (string :tag "Tag")
2522 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2524 (defcustom org-log-done nil
2525 "Information to record when a task moves to the DONE state.
2527 Possible values are:
2529 nil Don't add anything, just change the keyword
2530 time Add a time stamp to the task
2531 note Prompt for a note and add it with template `org-log-note-headings'
2533 This option can also be set with on a per-file-basis with
2535 #+STARTUP: nologdone
2536 #+STARTUP: logdone
2537 #+STARTUP: lognotedone
2539 You can have local logging settings for a subtree by setting the LOGGING
2540 property to one or more of these keywords."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type '(choice
2544 (const :tag "No logging" nil)
2545 (const :tag "Record CLOSED timestamp" time)
2546 (const :tag "Record CLOSED timestamp with note." note)))
2548 ;; Normalize old uses of org-log-done.
2549 (cond
2550 ((eq org-log-done t) (setq org-log-done 'time))
2551 ((and (listp org-log-done) (memq 'done org-log-done))
2552 (setq org-log-done 'note)))
2554 (defcustom org-log-reschedule nil
2555 "Information to record when the scheduling date of a tasks is modified.
2557 Possible values are:
2559 nil Don't add anything, just change the date
2560 time Add a time stamp to the task
2561 note Prompt for a note and add it with template `org-log-note-headings'
2563 This option can also be set with on a per-file-basis with
2565 #+STARTUP: nologreschedule
2566 #+STARTUP: logreschedule
2567 #+STARTUP: lognotereschedule"
2568 :group 'org-todo
2569 :group 'org-progress
2570 :type '(choice
2571 (const :tag "No logging" nil)
2572 (const :tag "Record timestamp" time)
2573 (const :tag "Record timestamp with note." note)))
2575 (defcustom org-log-redeadline nil
2576 "Information to record when the deadline date of a tasks is modified.
2578 Possible values are:
2580 nil Don't add anything, just change the date
2581 time Add a time stamp to the task
2582 note Prompt for a note and add it with template `org-log-note-headings'
2584 This option can also be set with on a per-file-basis with
2586 #+STARTUP: nologredeadline
2587 #+STARTUP: logredeadline
2588 #+STARTUP: lognoteredeadline
2590 You can have local logging settings for a subtree by setting the LOGGING
2591 property to one or more of these keywords."
2592 :group 'org-todo
2593 :group 'org-progress
2594 :type '(choice
2595 (const :tag "No logging" nil)
2596 (const :tag "Record timestamp" time)
2597 (const :tag "Record timestamp with note." note)))
2599 (defcustom org-log-note-clock-out nil
2600 "Non-nil means record a note when clocking out of an item.
2601 This can also be configured on a per-file basis by adding one of
2602 the following lines anywhere in the buffer:
2604 #+STARTUP: lognoteclock-out
2605 #+STARTUP: nolognoteclock-out"
2606 :group 'org-todo
2607 :group 'org-progress
2608 :type 'boolean)
2610 (defcustom org-log-done-with-time t
2611 "Non-nil means the CLOSED time stamp will contain date and time.
2612 When nil, only the date will be recorded."
2613 :group 'org-progress
2614 :type 'boolean)
2616 (defcustom org-log-note-headings
2617 '((done . "CLOSING NOTE %t")
2618 (state . "State %-12s from %-12S %t")
2619 (note . "Note taken on %t")
2620 (reschedule . "Rescheduled from %S on %t")
2621 (delschedule . "Not scheduled, was %S on %t")
2622 (redeadline . "New deadline from %S on %t")
2623 (deldeadline . "Removed deadline, was %S on %t")
2624 (refile . "Refiled on %t")
2625 (clock-out . ""))
2626 "Headings for notes added to entries.
2627 The value is an alist, with the car being a symbol indicating the note
2628 context, and the cdr is the heading to be used. The heading may also be the
2629 empty string.
2630 %t in the heading will be replaced by a time stamp.
2631 %T will be an active time stamp instead the default inactive one
2632 %d will be replaced by a short-format time stamp.
2633 %D will be replaced by an active short-format time stamp.
2634 %s will be replaced by the new TODO state, in double quotes.
2635 %S will be replaced by the old TODO state, in double quotes.
2636 %u will be replaced by the user name.
2637 %U will be replaced by the full user name.
2639 In fact, it is not a good idea to change the `state' entry, because
2640 agenda log mode depends on the format of these entries."
2641 :group 'org-todo
2642 :group 'org-progress
2643 :type '(list :greedy t
2644 (cons (const :tag "Heading when closing an item" done) string)
2645 (cons (const :tag
2646 "Heading when changing todo state (todo sequence only)"
2647 state) string)
2648 (cons (const :tag "Heading when just taking a note" note) string)
2649 (cons (const :tag "Heading when clocking out" clock-out) string)
2650 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2651 (cons (const :tag "Heading when rescheduling" reschedule) string)
2652 (cons (const :tag "Heading when changing deadline" redeadline) string)
2653 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2654 (cons (const :tag "Heading when refiling" refile) string)))
2656 (unless (assq 'note org-log-note-headings)
2657 (push '(note . "%t") org-log-note-headings))
2659 (defcustom org-log-into-drawer nil
2660 "Non-nil means insert state change notes and time stamps into a drawer.
2661 When nil, state changes notes will be inserted after the headline and
2662 any scheduling and clock lines, but not inside a drawer.
2664 The value of this variable should be the name of the drawer to use.
2665 LOGBOOK is proposed as the default drawer for this purpose, you can
2666 also set this to a string to define the drawer of your choice.
2668 A value of t is also allowed, representing \"LOGBOOK\".
2670 A value of t or nil can also be set with on a per-file-basis with
2672 #+STARTUP: logdrawer
2673 #+STARTUP: nologdrawer
2675 If this variable is set, `org-log-state-notes-insert-after-drawers'
2676 will be ignored.
2678 You can set the property LOG_INTO_DRAWER to overrule this setting for
2679 a subtree."
2680 :group 'org-todo
2681 :group 'org-progress
2682 :type '(choice
2683 (const :tag "Not into a drawer" nil)
2684 (const :tag "LOGBOOK" t)
2685 (string :tag "Other")))
2687 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2689 (defun org-log-into-drawer ()
2690 "Return the value of `org-log-into-drawer', but let properties overrule.
2691 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2692 used instead of the default value."
2693 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2694 (cond
2695 ((not p) org-log-into-drawer)
2696 ((equal p "nil") nil)
2697 ((equal p "t") "LOGBOOK")
2698 (t p))))
2700 (defcustom org-log-state-notes-insert-after-drawers nil
2701 "Non-nil means insert state change notes after any drawers in entry.
2702 Only the drawers that *immediately* follow the headline and the
2703 deadline/scheduled line are skipped.
2704 When nil, insert notes right after the heading and perhaps the line
2705 with deadline/scheduling if present.
2707 This variable will have no effect if `org-log-into-drawer' is
2708 set."
2709 :group 'org-todo
2710 :group 'org-progress
2711 :type 'boolean)
2713 (defcustom org-log-states-order-reversed t
2714 "Non-nil means the latest state note will be directly after heading.
2715 When nil, the state change notes will be ordered according to time.
2717 This option can also be set with on a per-file-basis with
2719 #+STARTUP: logstatesreversed
2720 #+STARTUP: nologstatesreversed"
2721 :group 'org-todo
2722 :group 'org-progress
2723 :type 'boolean)
2725 (defcustom org-todo-repeat-to-state nil
2726 "The TODO state to which a repeater should return the repeating task.
2727 By default this is the first task in a TODO sequence, or the previous state
2728 in a TODO_TYP set. But you can specify another task here.
2729 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2730 :group 'org-todo
2731 :version "24.1"
2732 :type '(choice (const :tag "Head of sequence" nil)
2733 (string :tag "Specific state")))
2735 (defcustom org-log-repeat 'time
2736 "Non-nil means record moving through the DONE state when triggering repeat.
2737 An auto-repeating task is immediately switched back to TODO when
2738 marked DONE. If you are not logging state changes (by adding \"@\"
2739 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2740 record a closing note, there will be no record of the task moving
2741 through DONE. This variable forces taking a note anyway.
2743 nil Don't force a record
2744 time Record a time stamp
2745 note Prompt for a note and add it with template `org-log-note-headings'
2747 This option can also be set with on a per-file-basis with
2749 #+STARTUP: nologrepeat
2750 #+STARTUP: logrepeat
2751 #+STARTUP: lognoterepeat
2753 You can have local logging settings for a subtree by setting the LOGGING
2754 property to one or more of these keywords."
2755 :group 'org-todo
2756 :group 'org-progress
2757 :type '(choice
2758 (const :tag "Don't force a record" nil)
2759 (const :tag "Force recording the DONE state" time)
2760 (const :tag "Force recording a note with the DONE state" note)))
2763 (defgroup org-priorities nil
2764 "Priorities in Org-mode."
2765 :tag "Org Priorities"
2766 :group 'org-todo)
2768 (defcustom org-enable-priority-commands t
2769 "Non-nil means priority commands are active.
2770 When nil, these commands will be disabled, so that you never accidentally
2771 set a priority."
2772 :group 'org-priorities
2773 :type 'boolean)
2775 (defcustom org-highest-priority ?A
2776 "The highest priority of TODO items. A character like ?A, ?B etc.
2777 Must have a smaller ASCII number than `org-lowest-priority'."
2778 :group 'org-priorities
2779 :type 'character)
2781 (defcustom org-lowest-priority ?C
2782 "The lowest priority of TODO items. A character like ?A, ?B etc.
2783 Must have a larger ASCII number than `org-highest-priority'."
2784 :group 'org-priorities
2785 :type 'character)
2787 (defcustom org-default-priority ?B
2788 "The default priority of TODO items.
2789 This is the priority an item gets if no explicit priority is given.
2790 When starting to cycle on an empty priority the first step in the cycle
2791 depends on `org-priority-start-cycle-with-default'. The resulting first
2792 step priority must not exceed the range from `org-highest-priority' to
2793 `org-lowest-priority' which means that `org-default-priority' has to be
2794 in this range exclusive or inclusive the range boundaries. Else the
2795 first step refuses to set the default and the second will fall back
2796 to (depending on the command used) the highest or lowest priority."
2797 :group 'org-priorities
2798 :type 'character)
2800 (defcustom org-priority-start-cycle-with-default t
2801 "Non-nil means start with default priority when starting to cycle.
2802 When this is nil, the first step in the cycle will be (depending on the
2803 command used) one higher or lower than the default priority.
2804 See also `org-default-priority'."
2805 :group 'org-priorities
2806 :type 'boolean)
2808 (defcustom org-get-priority-function nil
2809 "Function to extract the priority from a string.
2810 The string is normally the headline. If this is nil Org computes the
2811 priority from the priority cookie like [#A] in the headline. It returns
2812 an integer, increasing by 1000 for each priority level.
2813 The user can set a different function here, which should take a string
2814 as an argument and return the numeric priority."
2815 :group 'org-priorities
2816 :version "24.1"
2817 :type '(choice
2818 (const nil)
2819 (function)))
2821 (defgroup org-time nil
2822 "Options concerning time stamps and deadlines in Org-mode."
2823 :tag "Org Time"
2824 :group 'org)
2826 (defcustom org-insert-labeled-timestamps-at-point nil
2827 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2828 When nil, these labeled time stamps are forces into the second line of an
2829 entry, just after the headline. When scheduling from the global TODO list,
2830 the time stamp will always be forced into the second line."
2831 :group 'org-time
2832 :type 'boolean)
2834 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2835 "Formats for `format-time-string' which are used for time stamps.
2836 It is not recommended to change this constant.")
2838 (defcustom org-time-stamp-rounding-minutes '(0 5)
2839 "Number of minutes to round time stamps to.
2840 These are two values, the first applies when first creating a time stamp.
2841 The second applies when changing it with the commands `S-up' and `S-down'.
2842 When changing the time stamp, this means that it will change in steps
2843 of N minutes, as given by the second value.
2845 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2846 numbers should be factors of 60, so for example 5, 10, 15.
2848 When this is larger than 1, you can still force an exact time stamp by using
2849 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2850 and by using a prefix arg to `S-up/down' to specify the exact number
2851 of minutes to shift."
2852 :group 'org-time
2853 :get #'(lambda (var) ; Make sure both elements are there
2854 (if (integerp (default-value var))
2855 (list (default-value var) 5)
2856 (default-value var)))
2857 :type '(list
2858 (integer :tag "when inserting times")
2859 (integer :tag "when modifying times")))
2861 ;; Normalize old customizations of this variable.
2862 (when (integerp org-time-stamp-rounding-minutes)
2863 (setq org-time-stamp-rounding-minutes
2864 (list org-time-stamp-rounding-minutes
2865 org-time-stamp-rounding-minutes)))
2867 (defcustom org-display-custom-times nil
2868 "Non-nil means overlay custom formats over all time stamps.
2869 The formats are defined through the variable `org-time-stamp-custom-formats'.
2870 To turn this on on a per-file basis, insert anywhere in the file:
2871 #+STARTUP: customtime"
2872 :group 'org-time
2873 :set 'set-default
2874 :type 'sexp)
2875 (make-variable-buffer-local 'org-display-custom-times)
2877 (defcustom org-time-stamp-custom-formats
2878 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2879 "Custom formats for time stamps. See `format-time-string' for the syntax.
2880 These are overlaid over the default ISO format if the variable
2881 `org-display-custom-times' is set. Time like %H:%M should be at the
2882 end of the second format. The custom formats are also honored by export
2883 commands, if custom time display is turned on at the time of export."
2884 :group 'org-time
2885 :type 'sexp)
2887 (defun org-time-stamp-format (&optional long inactive)
2888 "Get the right format for a time string."
2889 (let ((f (if long (cdr org-time-stamp-formats)
2890 (car org-time-stamp-formats))))
2891 (if inactive
2892 (concat "[" (substring f 1 -1) "]")
2893 f)))
2895 (defcustom org-time-clocksum-format
2896 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2897 "The format string used when creating CLOCKSUM lines.
2898 This is also used when Org mode generates a time duration.
2900 The value can be a single format string containing two
2901 %-sequences, which will be filled with the number of hours and
2902 minutes in that order.
2904 Alternatively, the value can be a plist associating any of the
2905 keys :years, :months, :weeks, :days, :hours or :minutes with
2906 format strings. The time duration is formatted using only the
2907 time components that are needed and concatenating the results.
2908 If a time unit in absent, it falls back to the next smallest
2909 unit.
2911 The keys :require-years, :require-months, :require-days,
2912 :require-weeks, :require-hours, :require-minutes are also
2913 meaningful. A non-nil value for these keys indicates that the
2914 corresponding time component should always be included, even if
2915 its value is 0.
2918 For example,
2920 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2921 :require-minutes t)
2923 means durations longer than a day will be expressed in days,
2924 hours and minutes, and durations less than a day will always be
2925 expressed in hours and minutes (even for durations less than an
2926 hour).
2928 The value
2930 \(:days \"%dd\" :minutes \"%dm\")
2932 means durations longer than a day will be expressed in days and
2933 minutes, and durations less than a day will be expressed entirely
2934 in minutes (even for durations longer than an hour)."
2935 :group 'org-time
2936 :group 'org-clock
2937 :version "24.4"
2938 :package-version '(Org . "8.0")
2939 :type '(choice (string :tag "Format string")
2940 (set :tag "Plist"
2941 (group :inline t (const :tag "Years" :years)
2942 (string :tag "Format string"))
2943 (group :inline t
2944 (const :tag "Always show years" :require-years)
2945 (const t))
2946 (group :inline t (const :tag "Months" :months)
2947 (string :tag "Format string"))
2948 (group :inline t
2949 (const :tag "Always show months" :require-months)
2950 (const t))
2951 (group :inline t (const :tag "Weeks" :weeks)
2952 (string :tag "Format string"))
2953 (group :inline t
2954 (const :tag "Always show weeks" :require-weeks)
2955 (const t))
2956 (group :inline t (const :tag "Days" :days)
2957 (string :tag "Format string"))
2958 (group :inline t
2959 (const :tag "Always show days" :require-days)
2960 (const t))
2961 (group :inline t (const :tag "Hours" :hours)
2962 (string :tag "Format string"))
2963 (group :inline t
2964 (const :tag "Always show hours" :require-hours)
2965 (const t))
2966 (group :inline t (const :tag "Minutes" :minutes)
2967 (string :tag "Format string"))
2968 (group :inline t
2969 (const :tag "Always show minutes" :require-minutes)
2970 (const t)))))
2972 (defcustom org-time-clocksum-use-fractional nil
2973 "When non-nil, \\[org-clock-display] uses fractional times.
2974 See `org-time-clocksum-format' for more on time clock formats."
2975 :group 'org-time
2976 :group 'org-clock
2977 :version "24.3"
2978 :type 'boolean)
2980 (defcustom org-time-clocksum-use-effort-durations nil
2981 "When non-nil, \\[org-clock-display] uses effort durations.
2982 E.g. by default, one day is considered to be a 8 hours effort,
2983 so a task that has been clocked for 16 hours will be displayed
2984 as during 2 days in the clock display or in the clocktable.
2986 See `org-effort-durations' on how to set effort durations
2987 and `org-time-clocksum-format' for more on time clock formats."
2988 :group 'org-time
2989 :group 'org-clock
2990 :version "24.4"
2991 :package-version '(Org . "8.0")
2992 :type 'boolean)
2994 (defcustom org-time-clocksum-fractional-format "%.2f"
2995 "The format string used when creating CLOCKSUM lines,
2996 or when Org mode generates a time duration, if
2997 `org-time-clocksum-use-fractional' is enabled.
2999 The value can be a single format string containing one
3000 %-sequence, which will be filled with the number of hours as
3001 a float.
3003 Alternatively, the value can be a plist associating any of the
3004 keys :years, :months, :weeks, :days, :hours or :minutes with
3005 a format string. The time duration is formatted using the
3006 largest time unit which gives a non-zero integer part. If all
3007 specified formats have zero integer part, the smallest time unit
3008 is used."
3009 :group 'org-time
3010 :type '(choice (string :tag "Format string")
3011 (set (group :inline t (const :tag "Years" :years)
3012 (string :tag "Format string"))
3013 (group :inline t (const :tag "Months" :months)
3014 (string :tag "Format string"))
3015 (group :inline t (const :tag "Weeks" :weeks)
3016 (string :tag "Format string"))
3017 (group :inline t (const :tag "Days" :days)
3018 (string :tag "Format string"))
3019 (group :inline t (const :tag "Hours" :hours)
3020 (string :tag "Format string"))
3021 (group :inline t (const :tag "Minutes" :minutes)
3022 (string :tag "Format string")))))
3024 (defcustom org-deadline-warning-days 14
3025 "Number of days before expiration during which a deadline becomes active.
3026 This variable governs the display in sparse trees and in the agenda.
3027 When 0 or negative, it means use this number (the absolute value of it)
3028 even if a deadline has a different individual lead time specified.
3030 Custom commands can set this variable in the options section."
3031 :group 'org-time
3032 :group 'org-agenda-daily/weekly
3033 :type 'integer)
3035 (defcustom org-scheduled-delay-days 0
3036 "Number of days before a scheduled item becomes active.
3037 This variable governs the display in sparse trees and in the agenda.
3038 The default value (i.e. 0) means: don't delay scheduled item.
3039 When negative, it means use this number (the absolute value of it)
3040 even if a scheduled item has a different individual delay time
3041 specified.
3043 Custom commands can set this variable in the options section."
3044 :group 'org-time
3045 :group 'org-agenda-daily/weekly
3046 :version "24.4"
3047 :package-version '(Org . "8.0")
3048 :type 'integer)
3050 (defcustom org-read-date-prefer-future t
3051 "Non-nil means assume future for incomplete date input from user.
3052 This affects the following situations:
3053 1. The user gives a month but not a year.
3054 For example, if it is April and you enter \"feb 2\", this will be read
3055 as Feb 2, *next* year. \"May 5\", however, will be this year.
3056 2. The user gives a day, but no month.
3057 For example, if today is the 15th, and you enter \"3\", Org-mode will
3058 read this as the third of *next* month. However, if you enter \"17\",
3059 it will be considered as *this* month.
3061 If you set this variable to the symbol `time', then also the following
3062 will work:
3064 3. If the user gives a time.
3065 If the time is before now, it will be interpreted as tomorrow.
3067 Currently none of this works for ISO week specifications.
3069 When this option is nil, the current day, month and year will always be
3070 used as defaults.
3072 See also `org-agenda-jump-prefer-future'."
3073 :group 'org-time
3074 :type '(choice
3075 (const :tag "Never" nil)
3076 (const :tag "Check month and day" t)
3077 (const :tag "Check month, day, and time" time)))
3079 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3080 "Should the agenda jump command prefer the future for incomplete dates?
3081 The default is to do the same as configured in `org-read-date-prefer-future'.
3082 But you can also set a deviating value here.
3083 This may t or nil, or the symbol `org-read-date-prefer-future'."
3084 :group 'org-agenda
3085 :group 'org-time
3086 :version "24.1"
3087 :type '(choice
3088 (const :tag "Use org-read-date-prefer-future"
3089 org-read-date-prefer-future)
3090 (const :tag "Never" nil)
3091 (const :tag "Always" t)))
3093 (defcustom org-read-date-force-compatible-dates t
3094 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3096 Depending on the system Emacs is running on, certain dates cannot
3097 be represented with the type used internally to represent time.
3098 Dates between 1970-1-1 and 2038-1-1 can always be represented
3099 correctly. Some systems allow for earlier dates, some for later,
3100 some for both. One way to find out it to insert any date into an
3101 Org buffer, putting the cursor on the year and hitting S-up and
3102 S-down to test the range.
3104 When this variable is set to t, the date/time prompt will not let
3105 you specify dates outside the 1970-2037 range, so it is certain that
3106 these dates will work in whatever version of Emacs you are
3107 running, and also that you can move a file from one Emacs implementation
3108 to another. WHenever Org is forcing the year for you, it will display
3109 a message and beep.
3111 When this variable is nil, Org will check if the date is
3112 representable in the specific Emacs implementation you are using.
3113 If not, it will force a year, usually the current year, and beep
3114 to remind you. Currently this setting is not recommended because
3115 the likelihood that you will open your Org files in an Emacs that
3116 has limited date range is not negligible.
3118 A workaround for this problem is to use diary sexp dates for time
3119 stamps outside of this range."
3120 :group 'org-time
3121 :version "24.1"
3122 :type 'boolean)
3124 (defcustom org-read-date-display-live t
3125 "Non-nil means display current interpretation of date prompt live.
3126 This display will be in an overlay, in the minibuffer."
3127 :group 'org-time
3128 :type 'boolean)
3130 (defcustom org-read-date-popup-calendar t
3131 "Non-nil means pop up a calendar when prompting for a date.
3132 In the calendar, the date can be selected with mouse-1. However, the
3133 minibuffer will also be active, and you can simply enter the date as well.
3134 When nil, only the minibuffer will be available."
3135 :group 'org-time
3136 :type 'boolean)
3137 (org-defvaralias 'org-popup-calendar-for-date-prompt
3138 'org-read-date-popup-calendar)
3140 (make-obsolete-variable
3141 'org-read-date-minibuffer-setup-hook
3142 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3143 (defcustom org-read-date-minibuffer-setup-hook nil
3144 "Hook to be used to set up keys for the date/time interface.
3145 Add key definitions to `minibuffer-local-map', which will be a
3146 temporary copy.
3148 WARNING: This option is obsolete, you should use
3149 `org-read-date-minibuffer-local-map' to set up keys."
3150 :group 'org-time
3151 :type 'hook)
3153 (defcustom org-extend-today-until 0
3154 "The hour when your day really ends. Must be an integer.
3155 This has influence for the following applications:
3156 - When switching the agenda to \"today\". It it is still earlier than
3157 the time given here, the day recognized as TODAY is actually yesterday.
3158 - When a date is read from the user and it is still before the time given
3159 here, the current date and time will be assumed to be yesterday, 23:59.
3160 Also, timestamps inserted in capture templates follow this rule.
3162 IMPORTANT: This is a feature whose implementation is and likely will
3163 remain incomplete. Really, it is only here because past midnight seems to
3164 be the favorite working time of John Wiegley :-)"
3165 :group 'org-time
3166 :type 'integer)
3168 (defcustom org-use-effective-time nil
3169 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3170 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3171 \"effective time\" of any timestamps between midnight and 8am will be
3172 23:59 of the previous day."
3173 :group 'org-time
3174 :version "24.1"
3175 :type 'boolean)
3177 (defcustom org-use-last-clock-out-time-as-effective-time nil
3178 "When non-nil, use the last clock out time for `org-todo'.
3179 Note that this option has precedence over the combined use of
3180 `org-use-effective-time' and `org-extend-today-until'."
3181 :group 'org-time
3182 :version "24.4"
3183 :package-version '(Org . "8.0")
3184 :type 'boolean)
3186 (defcustom org-edit-timestamp-down-means-later nil
3187 "Non-nil means S-down will increase the time in a time stamp.
3188 When nil, S-up will increase."
3189 :group 'org-time
3190 :type 'boolean)
3192 (defcustom org-calendar-follow-timestamp-change t
3193 "Non-nil means make the calendar window follow timestamp changes.
3194 When a timestamp is modified and the calendar window is visible, it will be
3195 moved to the new date."
3196 :group 'org-time
3197 :type 'boolean)
3199 (defgroup org-tags nil
3200 "Options concerning tags in Org-mode."
3201 :tag "Org Tags"
3202 :group 'org)
3204 (defcustom org-tag-alist nil
3205 "List of tags allowed in Org-mode files.
3206 When this list is nil, Org-mode will base TAG input on what is already in the
3207 buffer.
3208 The value of this variable is an alist, the car of each entry must be a
3209 keyword as a string, the cdr may be a character that is used to select
3210 that tag through the fast-tag-selection interface.
3211 See the manual for details."
3212 :group 'org-tags
3213 :type '(repeat
3214 (choice
3215 (cons (string :tag "Tag name")
3216 (character :tag "Access char"))
3217 (list :tag "Start radio group"
3218 (const :startgroup)
3219 (option (string :tag "Group description")))
3220 (list :tag "Group tags delimiter"
3221 (const :grouptags))
3222 (list :tag "End radio group"
3223 (const :endgroup)
3224 (option (string :tag "Group description")))
3225 (const :tag "New line" (:newline)))))
3227 (defcustom org-tag-persistent-alist nil
3228 "List of tags that will always appear in all Org-mode files.
3229 This is in addition to any in buffer settings or customizations
3230 of `org-tag-alist'.
3231 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3232 The value of this variable is an alist, the car of each entry must be a
3233 keyword as a string, the cdr may be a character that is used to select
3234 that tag through the fast-tag-selection interface.
3235 See the manual for details.
3236 To disable these tags on a per-file basis, insert anywhere in the file:
3237 #+STARTUP: noptag"
3238 :group 'org-tags
3239 :type '(repeat
3240 (choice
3241 (cons (string :tag "Tag name")
3242 (character :tag "Access char"))
3243 (const :tag "Start radio group" (:startgroup))
3244 (const :tag "Group tags delimiter" (:grouptags))
3245 (const :tag "End radio group" (:endgroup))
3246 (const :tag "New line" (:newline)))))
3248 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3249 "If non-nil, always offer completion for all tags of all agenda files.
3250 Instead of customizing this variable directly, you might want to
3251 set it locally for capture buffers, because there no list of
3252 tags in that file can be created dynamically (there are none).
3254 (add-hook 'org-capture-mode-hook
3255 (lambda ()
3256 (set (make-local-variable
3257 'org-complete-tags-always-offer-all-agenda-tags)
3258 t)))"
3259 :group 'org-tags
3260 :version "24.1"
3261 :type 'boolean)
3263 (defvar org-file-tags nil
3264 "List of tags that can be inherited by all entries in the file.
3265 The tags will be inherited if the variable `org-use-tag-inheritance'
3266 says they should be.
3267 This variable is populated from #+FILETAGS lines.")
3269 (defcustom org-use-fast-tag-selection 'auto
3270 "Non-nil means use fast tag selection scheme.
3271 This is a special interface to select and deselect tags with single keys.
3272 When nil, fast selection is never used.
3273 When the symbol `auto', fast selection is used if and only if selection
3274 characters for tags have been configured, either through the variable
3275 `org-tag-alist' or through a #+TAGS line in the buffer.
3276 When t, fast selection is always used and selection keys are assigned
3277 automatically if necessary."
3278 :group 'org-tags
3279 :type '(choice
3280 (const :tag "Always" t)
3281 (const :tag "Never" nil)
3282 (const :tag "When selection characters are configured" auto)))
3284 (defcustom org-fast-tag-selection-single-key nil
3285 "Non-nil means fast tag selection exits after first change.
3286 When nil, you have to press RET to exit it.
3287 During fast tag selection, you can toggle this flag with `C-c'.
3288 This variable can also have the value `expert'. In this case, the window
3289 displaying the tags menu is not even shown, until you press C-c again."
3290 :group 'org-tags
3291 :type '(choice
3292 (const :tag "No" nil)
3293 (const :tag "Yes" t)
3294 (const :tag "Expert" expert)))
3296 (defvar org-fast-tag-selection-include-todo nil
3297 "Non-nil means fast tags selection interface will also offer TODO states.
3298 This is an undocumented feature, you should not rely on it.")
3300 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3301 "The column to which tags should be indented in a headline.
3302 If this number is positive, it specifies the column. If it is negative,
3303 it means that the tags should be flushright to that column. For example,
3304 -80 works well for a normal 80 character screen.
3305 When 0, place tags directly after headline text, with only one space in
3306 between."
3307 :group 'org-tags
3308 :type 'integer)
3310 (defcustom org-auto-align-tags t
3311 "Non-nil keeps tags aligned when modifying headlines.
3312 Some operations (i.e. demoting) change the length of a headline and
3313 therefore shift the tags around. With this option turned on, after
3314 each such operation the tags are again aligned to `org-tags-column'."
3315 :group 'org-tags
3316 :type 'boolean)
3318 (defcustom org-use-tag-inheritance t
3319 "Non-nil means tags in levels apply also for sublevels.
3320 When nil, only the tags directly given in a specific line apply there.
3321 This may also be a list of tags that should be inherited, or a regexp that
3322 matches tags that should be inherited. Additional control is possible
3323 with the variable `org-tags-exclude-from-inheritance' which gives an
3324 explicit list of tags to be excluded from inheritance, even if the value of
3325 `org-use-tag-inheritance' would select it for inheritance.
3327 If this option is t, a match early-on in a tree can lead to a large
3328 number of matches in the subtree when constructing the agenda or creating
3329 a sparse tree. If you only want to see the first match in a tree during
3330 a search, check out the variable `org-tags-match-list-sublevels'."
3331 :group 'org-tags
3332 :type '(choice
3333 (const :tag "Not" nil)
3334 (const :tag "Always" t)
3335 (repeat :tag "Specific tags" (string :tag "Tag"))
3336 (regexp :tag "Tags matched by regexp")))
3338 (defcustom org-tags-exclude-from-inheritance nil
3339 "List of tags that should never be inherited.
3340 This is a way to exclude a few tags from inheritance. For way to do
3341 the opposite, to actively allow inheritance for selected tags,
3342 see the variable `org-use-tag-inheritance'."
3343 :group 'org-tags
3344 :type '(repeat (string :tag "Tag")))
3346 (defun org-tag-inherit-p (tag)
3347 "Check if TAG is one that should be inherited."
3348 (cond
3349 ((member tag org-tags-exclude-from-inheritance) nil)
3350 ((eq org-use-tag-inheritance t) t)
3351 ((not org-use-tag-inheritance) nil)
3352 ((stringp org-use-tag-inheritance)
3353 (string-match org-use-tag-inheritance tag))
3354 ((listp org-use-tag-inheritance)
3355 (member tag org-use-tag-inheritance))
3356 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3358 (defcustom org-tags-match-list-sublevels t
3359 "Non-nil means list also sublevels of headlines matching a search.
3360 This variable applies to tags/property searches, and also to stuck
3361 projects because this search is based on a tags match as well.
3363 When set to the symbol `indented', sublevels are indented with
3364 leading dots.
3366 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3367 the sublevels of a headline matching a tag search often also match
3368 the same search. Listing all of them can create very long lists.
3369 Setting this variable to nil causes subtrees of a match to be skipped.
3371 This variable is semi-obsolete and probably should always be true. It
3372 is better to limit inheritance to certain tags using the variables
3373 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3374 :group 'org-tags
3375 :type '(choice
3376 (const :tag "No, don't list them" nil)
3377 (const :tag "Yes, do list them" t)
3378 (const :tag "List them, indented with leading dots" indented)))
3380 (defcustom org-tags-sort-function nil
3381 "When set, tags are sorted using this function as a comparator."
3382 :group 'org-tags
3383 :type '(choice
3384 (const :tag "No sorting" nil)
3385 (const :tag "Alphabetical" string<)
3386 (const :tag "Reverse alphabetical" string>)
3387 (function :tag "Custom function" nil)))
3389 (defvar org-tags-history nil
3390 "History of minibuffer reads for tags.")
3391 (defvar org-last-tags-completion-table nil
3392 "The last used completion table for tags.")
3393 (defvar org-after-tags-change-hook nil
3394 "Hook that is run after the tags in a line have changed.")
3396 (defgroup org-properties nil
3397 "Options concerning properties in Org-mode."
3398 :tag "Org Properties"
3399 :group 'org)
3401 (defcustom org-property-format "%-10s %s"
3402 "How property key/value pairs should be formatted by `indent-line'.
3403 When `indent-line' hits a property definition, it will format the line
3404 according to this format, mainly to make sure that the values are
3405 lined-up with respect to each other."
3406 :group 'org-properties
3407 :type 'string)
3409 (defcustom org-properties-postprocess-alist nil
3410 "Alist of properties and functions to adjust inserted values.
3411 Elements of this alist must be of the form
3413 ([string] [function])
3415 where [string] must be a property name and [function] must be a
3416 lambda expression: this lambda expression must take one argument,
3417 the value to adjust, and return the new value as a string.
3419 For example, this element will allow the property \"Remaining\"
3420 to be updated wrt the relation between the \"Effort\" property
3421 and the clock summary:
3423 ((\"Remaining\" (lambda(value)
3424 (let ((clocksum (org-clock-sum-current-item))
3425 (effort (org-duration-string-to-minutes
3426 (org-entry-get (point) \"Effort\"))))
3427 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3428 :group 'org-properties
3429 :version "24.1"
3430 :type '(alist :key-type (string :tag "Property")
3431 :value-type (function :tag "Function")))
3433 (defcustom org-use-property-inheritance nil
3434 "Non-nil means properties apply also for sublevels.
3436 This setting is chiefly used during property searches. Turning it on can
3437 cause significant overhead when doing a search, which is why it is not
3438 on by default.
3440 When nil, only the properties directly given in the current entry count.
3441 When t, every property is inherited. The value may also be a list of
3442 properties that should have inheritance, or a regular expression matching
3443 properties that should be inherited.
3445 However, note that some special properties use inheritance under special
3446 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3447 and the properties ending in \"_ALL\" when they are used as descriptor
3448 for valid values of a property.
3450 Note for programmers:
3451 When querying an entry with `org-entry-get', you can control if inheritance
3452 should be used. By default, `org-entry-get' looks only at the local
3453 properties. You can request inheritance by setting the inherit argument
3454 to t (to force inheritance) or to `selective' (to respect the setting
3455 in this variable)."
3456 :group 'org-properties
3457 :type '(choice
3458 (const :tag "Not" nil)
3459 (const :tag "Always" t)
3460 (repeat :tag "Specific properties" (string :tag "Property"))
3461 (regexp :tag "Properties matched by regexp")))
3463 (defun org-property-inherit-p (property)
3464 "Check if PROPERTY is one that should be inherited."
3465 (cond
3466 ((eq org-use-property-inheritance t) t)
3467 ((not org-use-property-inheritance) nil)
3468 ((stringp org-use-property-inheritance)
3469 (string-match org-use-property-inheritance property))
3470 ((listp org-use-property-inheritance)
3471 (member property org-use-property-inheritance))
3472 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3474 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3475 "The default column format, if no other format has been defined.
3476 This variable can be set on the per-file basis by inserting a line
3478 #+COLUMNS: %25ITEM ....."
3479 :group 'org-properties
3480 :type 'string)
3482 (defcustom org-columns-ellipses ".."
3483 "The ellipses to be used when a field in column view is truncated.
3484 When this is the empty string, as many characters as possible are shown,
3485 but then there will be no visual indication that the field has been truncated.
3486 When this is a string of length N, the last N characters of a truncated
3487 field are replaced by this string. If the column is narrower than the
3488 ellipses string, only part of the ellipses string will be shown."
3489 :group 'org-properties
3490 :type 'string)
3492 (defcustom org-columns-modify-value-for-display-function nil
3493 "Function that modifies values for display in column view.
3494 For example, it can be used to cut out a certain part from a time stamp.
3495 The function must take 2 arguments:
3497 column-title The title of the column (*not* the property name)
3498 value The value that should be modified.
3500 The function should return the value that should be displayed,
3501 or nil if the normal value should be used."
3502 :group 'org-properties
3503 :type '(choice (const nil) (function)))
3505 (defcustom org-effort-property "Effort"
3506 "The property that is being used to keep track of effort estimates.
3507 Effort estimates given in this property need to have the format H:MM."
3508 :group 'org-properties
3509 :group 'org-progress
3510 :type '(string :tag "Property"))
3512 (defconst org-global-properties-fixed
3513 '(("VISIBILITY_ALL" . "folded children content all")
3514 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3515 "List of property/value pairs that can be inherited by any entry.
3517 These are fixed values, for the preset properties. The user variable
3518 that can be used to add to this list is `org-global-properties'.
3520 The entries in this list are cons cells where the car is a property
3521 name and cdr is a string with the value. If the value represents
3522 multiple items like an \"_ALL\" property, separate the items by
3523 spaces.")
3525 (defcustom org-global-properties nil
3526 "List of property/value pairs that can be inherited by any entry.
3528 This list will be combined with the constant `org-global-properties-fixed'.
3530 The entries in this list are cons cells where the car is a property
3531 name and cdr is a string with the value.
3533 You can set buffer-local values for the same purpose in the variable
3534 `org-file-properties' this by adding lines like
3536 #+PROPERTY: NAME VALUE"
3537 :group 'org-properties
3538 :type '(repeat
3539 (cons (string :tag "Property")
3540 (string :tag "Value"))))
3542 (defvar org-file-properties nil
3543 "List of property/value pairs that can be inherited by any entry.
3544 Valid for the current buffer.
3545 This variable is populated from #+PROPERTY lines.")
3546 (make-variable-buffer-local 'org-file-properties)
3548 (defgroup org-agenda nil
3549 "Options concerning agenda views in Org-mode."
3550 :tag "Org Agenda"
3551 :group 'org)
3553 (defvar org-category nil
3554 "Variable used by org files to set a category for agenda display.
3555 Such files should use a file variable to set it, for example
3557 # -*- mode: org; org-category: \"ELisp\"
3559 or contain a special line
3561 #+CATEGORY: ELisp
3563 If the file does not specify a category, then file's base name
3564 is used instead.")
3565 (make-variable-buffer-local 'org-category)
3566 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3568 (defcustom org-agenda-files nil
3569 "The files to be used for agenda display.
3570 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3571 \\[org-remove-file]. You can also use customize to edit the list.
3573 If an entry is a directory, all files in that directory that are matched by
3574 `org-agenda-file-regexp' will be part of the file list.
3576 If the value of the variable is not a list but a single file name, then
3577 the list of agenda files is actually stored and maintained in that file, one
3578 agenda file per line. In this file paths can be given relative to
3579 `org-directory'. Tilde expansion and environment variable substitution
3580 are also made."
3581 :group 'org-agenda
3582 :type '(choice
3583 (repeat :tag "List of files and directories" file)
3584 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3586 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3587 "Regular expression to match files for `org-agenda-files'.
3588 If any element in the list in that variable contains a directory instead
3589 of a normal file, all files in that directory that are matched by this
3590 regular expression will be included."
3591 :group 'org-agenda
3592 :type 'regexp)
3594 (defcustom org-agenda-text-search-extra-files nil
3595 "List of extra files to be searched by text search commands.
3596 These files will be searched in addition to the agenda files by the
3597 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3598 Note that these files will only be searched for text search commands,
3599 not for the other agenda views like todo lists, tag searches or the weekly
3600 agenda. This variable is intended to list notes and possibly archive files
3601 that should also be searched by these two commands.
3602 In fact, if the first element in the list is the symbol `agenda-archives',
3603 then all archive files of all agenda files will be added to the search
3604 scope."
3605 :group 'org-agenda
3606 :type '(set :greedy t
3607 (const :tag "Agenda Archives" agenda-archives)
3608 (repeat :inline t (file))))
3610 (org-defvaralias 'org-agenda-multi-occur-extra-files
3611 'org-agenda-text-search-extra-files)
3613 (defcustom org-agenda-skip-unavailable-files nil
3614 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3615 A nil value means to remove them, after a query, from the list."
3616 :group 'org-agenda
3617 :type 'boolean)
3619 (defcustom org-calendar-to-agenda-key [?c]
3620 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3621 The command `org-calendar-goto-agenda' will be bound to this key. The
3622 default is the character `c' because then `c' can be used to switch back and
3623 forth between agenda and calendar."
3624 :group 'org-agenda
3625 :type 'sexp)
3627 (defcustom org-calendar-insert-diary-entry-key [?i]
3628 "The key to be installed in `calendar-mode-map' for adding diary entries.
3629 This option is irrelevant until `org-agenda-diary-file' has been configured
3630 to point to an Org-mode file. When that is the case, the command
3631 `org-agenda-diary-entry' will be bound to the key given here, by default
3632 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3633 if you want to continue doing this, you need to change this to a different
3634 key."
3635 :group 'org-agenda
3636 :type 'sexp)
3638 (defcustom org-agenda-diary-file 'diary-file
3639 "File to which to add new entries with the `i' key in agenda and calendar.
3640 When this is the symbol `diary-file', the functionality in the Emacs
3641 calendar will be used to add entries to the `diary-file'. But when this
3642 points to a file, `org-agenda-diary-entry' will be used instead."
3643 :group 'org-agenda
3644 :type '(choice
3645 (const :tag "The standard Emacs diary file" diary-file)
3646 (file :tag "Special Org file diary entries")))
3648 (eval-after-load "calendar"
3649 '(progn
3650 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3651 'org-calendar-goto-agenda)
3652 (add-hook 'calendar-mode-hook
3653 (lambda ()
3654 (unless (eq org-agenda-diary-file 'diary-file)
3655 (define-key calendar-mode-map
3656 org-calendar-insert-diary-entry-key
3657 'org-agenda-diary-entry))))))
3659 (defgroup org-latex nil
3660 "Options for embedding LaTeX code into Org-mode."
3661 :tag "Org LaTeX"
3662 :group 'org)
3664 (defcustom org-format-latex-options
3665 '(:foreground default :background default :scale 1.0
3666 :html-foreground "Black" :html-background "Transparent"
3667 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3668 "Options for creating images from LaTeX fragments.
3669 This is a property list with the following properties:
3670 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3671 `default' means use the foreground of the default face.
3672 `auto' means use the foreground from the text face.
3673 :background the background color, or \"Transparent\".
3674 `default' means use the background of the default face.
3675 `auto' means use the background from the text face.
3676 :scale a scaling factor for the size of the images, to get more pixels
3677 :html-foreground, :html-background, :html-scale
3678 the same numbers for HTML export.
3679 :matchers a list indicating which matchers should be used to
3680 find LaTeX fragments. Valid members of this list are:
3681 \"begin\" find environments
3682 \"$1\" find single characters surrounded by $.$
3683 \"$\" find math expressions surrounded by $...$
3684 \"$$\" find math expressions surrounded by $$....$$
3685 \"\\(\" find math expressions surrounded by \\(...\\)
3686 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3687 :group 'org-latex
3688 :type 'plist)
3690 (defcustom org-format-latex-signal-error t
3691 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3692 When nil, just push out a message."
3693 :group 'org-latex
3694 :version "24.1"
3695 :type 'boolean)
3697 (defcustom org-latex-to-mathml-jar-file nil
3698 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3699 Use this to specify additional executable file say a jar file.
3701 When using MathToWeb as the converter, specify the full-path to
3702 your mathtoweb.jar file."
3703 :group 'org-latex
3704 :version "24.1"
3705 :type '(choice
3706 (const :tag "None" nil)
3707 (file :tag "JAR file" :must-match t)))
3709 (defcustom org-latex-to-mathml-convert-command nil
3710 "Command to convert LaTeX fragments to MathML.
3711 Replace format-specifiers in the command as noted below and use
3712 `shell-command' to convert LaTeX to MathML.
3713 %j: Executable file in fully expanded form as specified by
3714 `org-latex-to-mathml-jar-file'.
3715 %I: Input LaTeX file in fully expanded form
3716 %o: Output MathML file
3717 This command is used by `org-create-math-formula'.
3719 When using MathToWeb as the converter, set this to
3720 \"java -jar %j -unicode -force -df %o %I\"."
3721 :group 'org-latex
3722 :version "24.1"
3723 :type '(choice
3724 (const :tag "None" nil)
3725 (string :tag "\nShell command")))
3727 (defcustom org-latex-create-formula-image-program 'dvipng
3728 "Program to convert LaTeX fragments with.
3730 dvipng Process the LaTeX fragments to dvi file, then convert
3731 dvi files to png files using dvipng.
3732 This will also include processing of non-math environments.
3733 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3734 to convert pdf files to png files"
3735 :group 'org-latex
3736 :version "24.1"
3737 :type '(choice
3738 (const :tag "dvipng" dvipng)
3739 (const :tag "imagemagick" imagemagick)))
3741 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3742 "Path to store latex preview images.
3743 A relative path here creates many directories relative to the
3744 processed org files paths. An absolute path puts all preview
3745 images at the same place."
3746 :group 'org-latex
3747 :version "24.3"
3748 :type 'string)
3750 (defun org-format-latex-mathml-available-p ()
3751 "Return t if `org-latex-to-mathml-convert-command' is usable."
3752 (save-match-data
3753 (when (and (boundp 'org-latex-to-mathml-convert-command)
3754 org-latex-to-mathml-convert-command)
3755 (let ((executable (car (split-string
3756 org-latex-to-mathml-convert-command))))
3757 (when (executable-find executable)
3758 (if (string-match
3759 "%j" org-latex-to-mathml-convert-command)
3760 (file-readable-p org-latex-to-mathml-jar-file)
3761 t))))))
3763 (defcustom org-format-latex-header "\\documentclass{article}
3764 \\usepackage[usenames]{color}
3765 \\usepackage{amsmath}
3766 \\usepackage[mathscr]{eucal}
3767 \\pagestyle{empty} % do not remove
3768 \[PACKAGES]
3769 \[DEFAULT-PACKAGES]
3770 % The settings below are copied from fullpage.sty
3771 \\setlength{\\textwidth}{\\paperwidth}
3772 \\addtolength{\\textwidth}{-3cm}
3773 \\setlength{\\oddsidemargin}{1.5cm}
3774 \\addtolength{\\oddsidemargin}{-2.54cm}
3775 \\setlength{\\evensidemargin}{\\oddsidemargin}
3776 \\setlength{\\textheight}{\\paperheight}
3777 \\addtolength{\\textheight}{-\\headheight}
3778 \\addtolength{\\textheight}{-\\headsep}
3779 \\addtolength{\\textheight}{-\\footskip}
3780 \\addtolength{\\textheight}{-3cm}
3781 \\setlength{\\topmargin}{1.5cm}
3782 \\addtolength{\\topmargin}{-2.54cm}"
3783 "The document header used for processing LaTeX fragments.
3784 It is imperative that this header make sure that no page number
3785 appears on the page. The package defined in the variables
3786 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3787 will either replace the placeholder \"[PACKAGES]\" in this
3788 header, or they will be appended."
3789 :group 'org-latex
3790 :type 'string)
3792 (defun org-set-packages-alist (var val)
3793 "Set the packages alist and make sure it has 3 elements per entry."
3794 (set var (mapcar (lambda (x)
3795 (if (and (consp x) (= (length x) 2))
3796 (list (car x) (nth 1 x) t)
3798 val)))
3800 (defun org-get-packages-alist (var)
3801 "Get the packages alist and make sure it has 3 elements per entry."
3802 (mapcar (lambda (x)
3803 (if (and (consp x) (= (length x) 2))
3804 (list (car x) (nth 1 x) t)
3806 (default-value var)))
3808 (defcustom org-latex-default-packages-alist
3809 '(("AUTO" "inputenc" t)
3810 ("T1" "fontenc" t)
3811 ("" "fixltx2e" nil)
3812 ("" "graphicx" t)
3813 ("" "longtable" nil)
3814 ("" "float" nil)
3815 ("" "wrapfig" nil)
3816 ("normalem" "ulem" t)
3817 ("" "textcomp" t)
3818 ("" "marvosym" t)
3819 ("" "wasysym" t)
3820 ("" "latexsym" t)
3821 ("" "amssymb" t)
3822 ("" "amstext" nil)
3823 ("" "hyperref" nil)
3824 "\\tolerance=1000")
3825 "Alist of default packages to be inserted in the header.
3827 Change this only if one of the packages here causes an
3828 incompatibility with another package you are using.
3830 The packages in this list are needed by one part or another of
3831 Org mode to function properly:
3833 - inputenc, fontenc: for basic font and character selection
3834 - amstext: for subscript and superscript
3835 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3836 symbols used for interpreting the entities in `org-entities'.
3837 You can skip some of these packages if you don't use any of the
3838 symbols in it.
3839 - ulem: for underline and strike-through
3840 - graphicx: for including images
3841 - float, wrapfig: for figure placement
3842 - longtable: for long tables
3843 - hyperref: for cross references
3845 Therefore you should not modify this variable unless you know
3846 what you are doing. The one reason to change it anyway is that
3847 you might be loading some other package that conflicts with one
3848 of the default packages. Each cell is of the format
3849 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3850 the package also needs to be included when compiling LaTeX
3851 snippets into images for inclusion into non-LaTeX output."
3852 :group 'org-latex
3853 :group 'org-export-latex
3854 :set 'org-set-packages-alist
3855 :get 'org-get-packages-alist
3856 :version "24.1"
3857 :type '(repeat
3858 (choice
3859 (list :tag "options/package pair"
3860 (string :tag "options")
3861 (string :tag "package")
3862 (boolean :tag "Snippet"))
3863 (string :tag "A line of LaTeX"))))
3865 (defcustom org-latex-packages-alist nil
3866 "Alist of packages to be inserted in every LaTeX header.
3868 These will be inserted after `org-latex-default-packages-alist'.
3869 Each cell is of the format:
3871 \(\"options\" \"package\" snippet-flag)
3873 SNIPPET-FLAG, when t, indicates that this package is also needed
3874 when turning LaTeX snippets into images for inclusion into
3875 non-LaTeX output.
3877 Make sure that you only list packages here which:
3879 - you want in every file
3880 - do not conflict with the setup in `org-format-latex-header'.
3881 - do not conflict with the default packages in
3882 `org-latex-default-packages-alist'."
3883 :group 'org-latex
3884 :group 'org-export-latex
3885 :set 'org-set-packages-alist
3886 :get 'org-get-packages-alist
3887 :type '(repeat
3888 (choice
3889 (list :tag "options/package pair"
3890 (string :tag "options")
3891 (string :tag "package")
3892 (boolean :tag "Snippet"))
3893 (string :tag "A line of LaTeX"))))
3895 (defgroup org-appearance nil
3896 "Settings for Org-mode appearance."
3897 :tag "Org Appearance"
3898 :group 'org)
3900 (defcustom org-level-color-stars-only nil
3901 "Non-nil means fontify only the stars in each headline.
3902 When nil, the entire headline is fontified.
3903 Changing it requires restart of `font-lock-mode' to become effective
3904 also in regions already fontified."
3905 :group 'org-appearance
3906 :type 'boolean)
3908 (defcustom org-hide-leading-stars nil
3909 "Non-nil means hide the first N-1 stars in a headline.
3910 This works by using the face `org-hide' for these stars. This
3911 face is white for a light background, and black for a dark
3912 background. You may have to customize the face `org-hide' to
3913 make this work.
3914 Changing it requires restart of `font-lock-mode' to become effective
3915 also in regions already fontified.
3916 You may also set this on a per-file basis by adding one of the following
3917 lines to the buffer:
3919 #+STARTUP: hidestars
3920 #+STARTUP: showstars"
3921 :group 'org-appearance
3922 :type 'boolean)
3924 (defcustom org-hidden-keywords nil
3925 "List of symbols corresponding to keywords to be hidden the org buffer.
3926 For example, a value '(title) for this list will make the document's title
3927 appear in the buffer without the initial #+TITLE: keyword."
3928 :group 'org-appearance
3929 :version "24.1"
3930 :type '(set (const :tag "#+AUTHOR" author)
3931 (const :tag "#+DATE" date)
3932 (const :tag "#+EMAIL" email)
3933 (const :tag "#+TITLE" title)))
3935 (defcustom org-custom-properties nil
3936 "List of properties (as strings) with a special meaning.
3937 The default use of these custom properties is to let the user
3938 hide them with `org-toggle-custom-properties-visibility'."
3939 :group 'org-properties
3940 :group 'org-appearance
3941 :version "24.3"
3942 :type '(repeat (string :tag "Property Name")))
3944 (defcustom org-fontify-done-headline nil
3945 "Non-nil means change the face of a headline if it is marked DONE.
3946 Normally, only the TODO/DONE keyword indicates the state of a headline.
3947 When this is non-nil, the headline after the keyword is set to the
3948 `org-headline-done' as an additional indication."
3949 :group 'org-appearance
3950 :type 'boolean)
3952 (defcustom org-fontify-emphasized-text t
3953 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3954 Changing this variable requires a restart of Emacs to take effect."
3955 :group 'org-appearance
3956 :type 'boolean)
3958 (defcustom org-fontify-whole-heading-line nil
3959 "Non-nil means fontify the whole line for headings.
3960 This is useful when setting a background color for the
3961 org-level-* faces."
3962 :group 'org-appearance
3963 :type 'boolean)
3965 (defcustom org-highlight-latex-and-related nil
3966 "Non-nil means highlight LaTeX related syntax in the buffer.
3967 When non nil, the value should be a list containing any of the
3968 following symbols:
3969 `latex' Highlight LaTeX snippets and environments.
3970 `script' Highlight subscript and superscript.
3971 `entities' Highlight entities."
3972 :group 'org-appearance
3973 :version "24.4"
3974 :package-version '(Org . "8.0")
3975 :type '(choice
3976 (const :tag "No highlighting" nil)
3977 (set :greedy t :tag "Highlight"
3978 (const :tag "LaTeX snippets and environments" latex)
3979 (const :tag "Subscript and superscript" script)
3980 (const :tag "Entities" entities))))
3982 (defcustom org-hide-emphasis-markers nil
3983 "Non-nil mean font-lock should hide the emphasis marker characters."
3984 :group 'org-appearance
3985 :type 'boolean)
3987 (defcustom org-pretty-entities nil
3988 "Non-nil means show entities as UTF8 characters.
3989 When nil, the \\name form remains in the buffer."
3990 :group 'org-appearance
3991 :version "24.1"
3992 :type 'boolean)
3994 (defcustom org-pretty-entities-include-sub-superscripts t
3995 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3996 :group 'org-appearance
3997 :version "24.1"
3998 :type 'boolean)
4000 (defvar org-emph-re nil
4001 "Regular expression for matching emphasis.
4002 After a match, the match groups contain these elements:
4003 0 The match of the full regular expression, including the characters
4004 before and after the proper match
4005 1 The character before the proper match, or empty at beginning of line
4006 2 The proper match, including the leading and trailing markers
4007 3 The leading marker like * or /, indicating the type of highlighting
4008 4 The text between the emphasis markers, not including the markers
4009 5 The character after the match, empty at the end of a line")
4010 (defvar org-verbatim-re nil
4011 "Regular expression for matching verbatim text.")
4012 (defvar org-emphasis-regexp-components) ; defined just below
4013 (defvar org-emphasis-alist) ; defined just below
4014 (defun org-set-emph-re (var val)
4015 "Set variable and compute the emphasis regular expression."
4016 (set var val)
4017 (when (and (boundp 'org-emphasis-alist)
4018 (boundp 'org-emphasis-regexp-components)
4019 org-emphasis-alist org-emphasis-regexp-components)
4020 (let* ((e org-emphasis-regexp-components)
4021 (pre (car e))
4022 (post (nth 1 e))
4023 (border (nth 2 e))
4024 (body (nth 3 e))
4025 (nl (nth 4 e))
4026 (body1 (concat body "*?"))
4027 (markers (mapconcat 'car org-emphasis-alist ""))
4028 (vmarkers (mapconcat
4029 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4030 org-emphasis-alist "")))
4031 ;; make sure special characters appear at the right position in the class
4032 (if (string-match "\\^" markers)
4033 (setq markers (concat (replace-match "" t t markers) "^")))
4034 (if (string-match "-" markers)
4035 (setq markers (concat (replace-match "" t t markers) "-")))
4036 (if (string-match "\\^" vmarkers)
4037 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4038 (if (string-match "-" vmarkers)
4039 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4040 (if (> nl 0)
4041 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4042 (int-to-string nl) "\\}")))
4043 ;; Make the regexp
4044 (setq org-emph-re
4045 (concat "\\([" pre "]\\|^\\)"
4046 "\\("
4047 "\\([" markers "]\\)"
4048 "\\("
4049 "[^" border "]\\|"
4050 "[^" border "]"
4051 body1
4052 "[^" border "]"
4053 "\\)"
4054 "\\3\\)"
4055 "\\([" post "]\\|$\\)"))
4056 (setq org-verbatim-re
4057 (concat "\\([" pre "]\\|^\\)"
4058 "\\("
4059 "\\([" vmarkers "]\\)"
4060 "\\("
4061 "[^" border "]\\|"
4062 "[^" border "]"
4063 body1
4064 "[^" border "]"
4065 "\\)"
4066 "\\3\\)"
4067 "\\([" post "]\\|$\\)")))))
4069 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4070 ;; set this option proved cumbersome. See this message/thread:
4071 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4072 (defvar org-emphasis-regexp-components
4073 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4074 "Components used to build the regular expression for emphasis.
4075 This is a list with five entries. Terminology: In an emphasis string
4076 like \" *strong word* \", we call the initial space PREMATCH, the final
4077 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4078 and \"trong wor\" is the body. The different components in this variable
4079 specify what is allowed/forbidden in each part:
4081 pre Chars allowed as prematch. Beginning of line will be allowed too.
4082 post Chars allowed as postmatch. End of line will be allowed too.
4083 border The chars *forbidden* as border characters.
4084 body-regexp A regexp like \".\" to match a body character. Don't use
4085 non-shy groups here, and don't allow newline here.
4086 newline The maximum number of newlines allowed in an emphasis exp.
4088 You need to reload Org or to restart Emacs after customizing this.")
4090 (defcustom org-emphasis-alist
4091 `(("*" bold)
4092 ("/" italic)
4093 ("_" underline)
4094 ("=" org-code verbatim)
4095 ("~" org-verbatim verbatim)
4096 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4097 "Alist of characters and faces to emphasize text.
4098 Text starting and ending with a special character will be emphasized,
4099 for example *bold*, _underlined_ and /italic/. This variable sets the
4100 marker characters and the face to be used by font-lock for highlighting
4101 in Org-mode Emacs buffers.
4103 You need to reload Org or to restart Emacs after customizing this."
4104 :group 'org-appearance
4105 :set 'org-set-emph-re
4106 :version "24.4"
4107 :package-version '(Org . "8.0")
4108 :type '(repeat
4109 (list
4110 (string :tag "Marker character")
4111 (choice
4112 (face :tag "Font-lock-face")
4113 (plist :tag "Face property list"))
4114 (option (const verbatim)))))
4116 (defvar org-protecting-blocks
4117 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4118 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4119 This is needed for font-lock setup.")
4121 ;;; Miscellaneous options
4123 (defgroup org-completion nil
4124 "Completion in Org-mode."
4125 :tag "Org Completion"
4126 :group 'org)
4128 (defcustom org-completion-use-ido nil
4129 "Non-nil means use ido completion wherever possible.
4130 Note that `ido-mode' must be active for this variable to be relevant.
4131 If you decide to turn this variable on, you might well want to turn off
4132 `org-outline-path-complete-in-steps'.
4133 See also `org-completion-use-iswitchb'."
4134 :group 'org-completion
4135 :type 'boolean)
4137 (defcustom org-completion-use-iswitchb nil
4138 "Non-nil means use iswitchb completion wherever possible.
4139 Note that `iswitchb-mode' must be active for this variable to be relevant.
4140 If you decide to turn this variable on, you might well want to turn off
4141 `org-outline-path-complete-in-steps'.
4142 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4143 :group 'org-completion
4144 :type 'boolean)
4146 (defcustom org-completion-fallback-command 'hippie-expand
4147 "The expansion command called by \\[pcomplete] in normal context.
4148 Normal means, no org-mode-specific context."
4149 :group 'org-completion
4150 :type 'function)
4152 ;;; Functions and variables from their packages
4153 ;; Declared here to avoid compiler warnings
4155 ;; XEmacs only
4156 (defvar outline-mode-menu-heading)
4157 (defvar outline-mode-menu-show)
4158 (defvar outline-mode-menu-hide)
4159 (defvar zmacs-regions) ; XEmacs regions
4161 ;; Emacs only
4162 (defvar mark-active)
4164 ;; Various packages
4165 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4166 (declare-function calendar-forward-day "cal-move" (arg))
4167 (declare-function calendar-goto-date "cal-move" (date))
4168 (declare-function calendar-goto-today "cal-move" ())
4169 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4170 (defvar calc-embedded-close-formula)
4171 (defvar calc-embedded-open-formula)
4172 (declare-function cdlatex-tab "ext:cdlatex" ())
4173 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4174 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4175 (defvar font-lock-unfontify-region-function)
4176 (declare-function iswitchb-read-buffer "iswitchb"
4177 (prompt &optional default require-match start matches-set))
4178 (defvar iswitchb-temp-buflist)
4179 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4180 (defvar org-agenda-tags-todo-honor-ignore-options)
4181 (declare-function org-agenda-skip "org-agenda" ())
4182 (declare-function
4183 org-agenda-format-item "org-agenda"
4184 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4185 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4186 (declare-function org-agenda-change-all-lines "org-agenda"
4187 (newhead hdmarker &optional fixface just-this))
4188 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4189 (declare-function org-agenda-maybe-redo "org-agenda" ())
4190 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4191 (beg end))
4192 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4193 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4194 "org-agenda" (&optional end))
4195 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4196 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4197 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4198 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4199 (declare-function org-indent-mode "org-indent" (&optional arg))
4200 (declare-function parse-time-string "parse-time" (string))
4201 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4202 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4203 (defvar remember-data-file)
4204 (defvar texmathp-why)
4205 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4206 (declare-function table--at-cell-p "table" (position &optional object at-column))
4208 (defvar org-latex-regexps)
4210 ;;; Autoload and prepare some org modules
4212 ;; Some table stuff that needs to be defined here, because it is used
4213 ;; by the functions setting up org-mode or checking for table context.
4215 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4216 "Detect an org-type or table-type table.")
4217 (defconst org-table-line-regexp "^[ \t]*|"
4218 "Detect an org-type table line.")
4219 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4220 "Detect an org-type table line.")
4221 (defconst org-table-hline-regexp "^[ \t]*|-"
4222 "Detect an org-type table hline.")
4223 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4224 "Detect a table-type table hline.")
4225 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4226 "Detect the first line outside a table when searching from within it.
4227 This works for both table types.")
4229 ;; Autoload the functions in org-table.el that are needed by functions here.
4231 (eval-and-compile
4232 (org-autoload "org-table"
4233 '(org-table-begin org-table-blank-field org-table-end)))
4235 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4236 "Detect a #+TBLFM line.")
4238 ;;;###autoload
4239 (defun turn-on-orgtbl ()
4240 "Unconditionally turn on `orgtbl-mode'."
4241 (require 'org-table)
4242 (orgtbl-mode 1))
4244 (defun org-at-table-p (&optional table-type)
4245 "Return t if the cursor is inside an org-type table.
4246 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4247 (if org-enable-table-editor
4248 (save-excursion
4249 (beginning-of-line 1)
4250 (looking-at (if table-type org-table-any-line-regexp
4251 org-table-line-regexp)))
4252 nil))
4253 (defsubst org-table-p () (org-at-table-p))
4255 (defun org-at-table.el-p ()
4256 "Return t if and only if we are at a table.el table."
4257 (and (org-at-table-p 'any)
4258 (save-excursion
4259 (goto-char (org-table-begin 'any))
4260 (looking-at org-table1-hline-regexp))))
4262 (defun org-table-recognize-table.el ()
4263 "If there is a table.el table nearby, recognize it and move into it."
4264 (if org-table-tab-recognizes-table.el
4265 (if (org-at-table.el-p)
4266 (progn
4267 (beginning-of-line 1)
4268 (if (looking-at org-table-dataline-regexp)
4270 (if (looking-at org-table1-hline-regexp)
4271 (progn
4272 (beginning-of-line 2)
4273 (if (looking-at org-table-any-border-regexp)
4274 (beginning-of-line -1)))))
4275 (if (re-search-forward "|" (org-table-end t) t)
4276 (progn
4277 (require 'table)
4278 (if (table--at-cell-p (point))
4280 (message "recognizing table.el table...")
4281 (table-recognize-table)
4282 (message "recognizing table.el table...done")))
4283 (error "This should not happen"))
4285 nil)
4286 nil))
4288 (defun org-at-table-hline-p ()
4289 "Return t if the cursor is inside a hline in a table."
4290 (if org-enable-table-editor
4291 (save-excursion
4292 (beginning-of-line 1)
4293 (looking-at org-table-hline-regexp))
4294 nil))
4296 (defun org-table-map-tables (function &optional quietly)
4297 "Apply FUNCTION to the start of all tables in the buffer."
4298 (save-excursion
4299 (save-restriction
4300 (widen)
4301 (goto-char (point-min))
4302 (while (re-search-forward org-table-any-line-regexp nil t)
4303 (unless quietly
4304 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4305 (beginning-of-line 1)
4306 (when (and (looking-at org-table-line-regexp)
4307 ;; Exclude tables in src/example/verbatim/clocktable blocks
4308 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4309 (save-excursion (funcall function))
4310 (or (looking-at org-table-line-regexp)
4311 (forward-char 1)))
4312 (re-search-forward org-table-any-border-regexp nil 1))))
4313 (unless quietly (message "Mapping tables: done")))
4315 ;; Declare and autoload functions from org-agenda.el
4317 (eval-and-compile
4318 (org-autoload "org-agenda"
4319 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4321 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4322 (declare-function org-clock-update-mode-line "org-clock" ())
4323 (declare-function org-resolve-clocks "org-clock"
4324 (&optional also-non-dangling-p prompt last-valid))
4326 (defun org-at-TBLFM-p (&optional pos)
4327 "Return t when point (or POS) is in #+TBLFM line."
4328 (save-excursion
4329 (let ((pos pos)))
4330 (goto-char (or pos (point)))
4331 (beginning-of-line 1)
4332 (looking-at org-TBLFM-regexp)))
4334 (defvar org-clock-start-time)
4335 (defvar org-clock-marker (make-marker)
4336 "Marker recording the last clock-in.")
4337 (defvar org-clock-hd-marker (make-marker)
4338 "Marker recording the last clock-in, but the headline position.")
4339 (defvar org-clock-heading ""
4340 "The heading of the current clock entry.")
4341 (defun org-clock-is-active ()
4342 "Return the buffer where the clock is currently running.
4343 Return nil if no clock is running."
4344 (marker-buffer org-clock-marker))
4346 (eval-and-compile
4347 (org-autoload "org-clock" '(org-clock-remove-overlays
4348 org-clock-update-time-maybe
4349 org-clocktable-shift)))
4351 (defun org-check-running-clock ()
4352 "Check if the current buffer contains the running clock.
4353 If yes, offer to stop it and to save the buffer with the changes."
4354 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4355 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4356 (buffer-name))))
4357 (org-clock-out)
4358 (when (y-or-n-p "Save changed buffer?")
4359 (save-buffer))))
4361 (defun org-clocktable-try-shift (dir n)
4362 "Check if this line starts a clock table, if yes, shift the time block."
4363 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4364 (org-clocktable-shift dir n)))
4366 ;;;###autoload
4367 (defun org-clock-persistence-insinuate ()
4368 "Set up hooks for clock persistence."
4369 (require 'org-clock)
4370 (add-hook 'org-mode-hook 'org-clock-load)
4371 (add-hook 'kill-emacs-hook 'org-clock-save))
4373 ;; Define the variable already here, to make sure we have it.
4374 (defvar org-indent-mode nil
4375 "Non-nil if Org-Indent mode is enabled.
4376 Use the command `org-indent-mode' to change this variable.")
4378 ;; Autoload archiving code
4379 ;; The stuff that is needed for cycling and tags has to be defined here.
4381 (defgroup org-archive nil
4382 "Options concerning archiving in Org-mode."
4383 :tag "Org Archive"
4384 :group 'org-structure)
4386 (defcustom org-archive-location "%s_archive::"
4387 "The location where subtrees should be archived.
4389 The value of this variable is a string, consisting of two parts,
4390 separated by a double-colon. The first part is a filename and
4391 the second part is a headline.
4393 When the filename is omitted, archiving happens in the same file.
4394 %s in the filename will be replaced by the current file
4395 name (without the directory part). Archiving to a different file
4396 is useful to keep archived entries from contributing to the
4397 Org-mode Agenda.
4399 The archived entries will be filed as subtrees of the specified
4400 headline. When the headline is omitted, the subtrees are simply
4401 filed away at the end of the file, as top-level entries. Also in
4402 the heading you can use %s to represent the file name, this can be
4403 useful when using the same archive for a number of different files.
4405 Here are a few examples:
4406 \"%s_archive::\"
4407 If the current file is Projects.org, archive in file
4408 Projects.org_archive, as top-level trees. This is the default.
4410 \"::* Archived Tasks\"
4411 Archive in the current file, under the top-level headline
4412 \"* Archived Tasks\".
4414 \"~/org/archive.org::\"
4415 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4417 \"~/org/archive.org::* From %s\"
4418 Archive in file ~/org/archive.org (absolute path), under headlines
4419 \"From FILENAME\" where file name is the current file name.
4421 \"~/org/datetree.org::datetree/* Finished Tasks\"
4422 The \"datetree/\" string is special, signifying to archive
4423 items to the datetree. Items are placed in either the CLOSED
4424 date of the item, or the current date if there is no CLOSED date.
4425 The heading will be a subentry to the current date. There doesn't
4426 need to be a heading, but there always needs to be a slash after
4427 datetree. For example, to store archived items directly in the
4428 datetree, use \"~/org/datetree.org::datetree/\".
4430 \"basement::** Finished Tasks\"
4431 Archive in file ./basement (relative path), as level 3 trees
4432 below the level 2 heading \"** Finished Tasks\".
4434 You may set this option on a per-file basis by adding to the buffer a
4435 line like
4437 #+ARCHIVE: basement::** Finished Tasks
4439 You may also define it locally for a subtree by setting an ARCHIVE property
4440 in the entry. If such a property is found in an entry, or anywhere up
4441 the hierarchy, it will be used."
4442 :group 'org-archive
4443 :type 'string)
4445 (defcustom org-archive-tag "ARCHIVE"
4446 "The tag that marks a subtree as archived.
4447 An archived subtree does not open during visibility cycling, and does
4448 not contribute to the agenda listings.
4449 After changing this, font-lock must be restarted in the relevant buffers to
4450 get the proper fontification."
4451 :group 'org-archive
4452 :group 'org-keywords
4453 :type 'string)
4455 (defcustom org-agenda-skip-archived-trees t
4456 "Non-nil means the agenda will skip any items located in archived trees.
4457 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4458 variable is no longer recommended, you should leave it at the value t.
4459 Instead, use the key `v' to cycle the archives-mode in the agenda."
4460 :group 'org-archive
4461 :group 'org-agenda-skip
4462 :type 'boolean)
4464 (defcustom org-columns-skip-archived-trees t
4465 "Non-nil means ignore archived trees when creating column view."
4466 :group 'org-archive
4467 :group 'org-properties
4468 :type 'boolean)
4470 (defcustom org-cycle-open-archived-trees nil
4471 "Non-nil means `org-cycle' will open archived trees.
4472 An archived tree is a tree marked with the tag ARCHIVE.
4473 When nil, archived trees will stay folded. You can still open them with
4474 normal outline commands like `show-all', but not with the cycling commands."
4475 :group 'org-archive
4476 :group 'org-cycle
4477 :type 'boolean)
4479 (defcustom org-sparse-tree-open-archived-trees nil
4480 "Non-nil means sparse tree construction shows matches in archived trees.
4481 When nil, matches in these trees are highlighted, but the trees are kept in
4482 collapsed state."
4483 :group 'org-archive
4484 :group 'org-sparse-trees
4485 :type 'boolean)
4487 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4488 "The default date type when building a sparse tree.
4489 When this is nil, a date is a scheduled or a deadline timestamp.
4490 Otherwise, these types are allowed:
4492 all: all timestamps
4493 active: only active timestamps (<...>)
4494 inactive: only inactive timestamps (<...)
4495 scheduled: only scheduled timestamps
4496 deadline: only deadline timestamps"
4497 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4498 (const :tag "All timestamps" all)
4499 (const :tag "Only active timestamps" active)
4500 (const :tag "Only inactive timestamps" inactive)
4501 (const :tag "Only scheduled timestamps" scheduled)
4502 (const :tag "Only deadline timestamps" deadline)
4503 (const :tag "Only closed timestamps" closed))
4504 :version "24.3"
4505 :group 'org-sparse-trees)
4507 (defun org-cycle-hide-archived-subtrees (state)
4508 "Re-hide all archived subtrees after a visibility state change."
4509 (when (and (not org-cycle-open-archived-trees)
4510 (not (memq state '(overview folded))))
4511 (save-excursion
4512 (let* ((globalp (memq state '(contents all)))
4513 (beg (if globalp (point-min) (point)))
4514 (end (if globalp (point-max) (org-end-of-subtree t))))
4515 (org-hide-archived-subtrees beg end)
4516 (goto-char beg)
4517 (if (looking-at (concat ".*:" org-archive-tag ":"))
4518 (message "%s" (substitute-command-keys
4519 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4521 (defun org-force-cycle-archived ()
4522 "Cycle subtree even if it is archived."
4523 (interactive)
4524 (setq this-command 'org-cycle)
4525 (let ((org-cycle-open-archived-trees t))
4526 (call-interactively 'org-cycle)))
4528 (defun org-hide-archived-subtrees (beg end)
4529 "Re-hide all archived subtrees after a visibility state change."
4530 (save-excursion
4531 (let* ((re (concat ":" org-archive-tag ":")))
4532 (goto-char beg)
4533 (while (re-search-forward re end t)
4534 (when (org-at-heading-p)
4535 (org-flag-subtree t)
4536 (org-end-of-subtree t))))))
4538 (declare-function outline-end-of-heading "outline" ())
4539 (declare-function outline-flag-region "outline" (from to flag))
4540 (defun org-flag-subtree (flag)
4541 (save-excursion
4542 (org-back-to-heading t)
4543 (outline-end-of-heading)
4544 (outline-flag-region (point)
4545 (progn (org-end-of-subtree t) (point))
4546 flag)))
4548 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4550 (eval-and-compile
4551 (org-autoload "org-archive"
4552 '(org-add-archive-files)))
4554 ;; Autoload Column View Code
4556 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4557 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4558 (declare-function org-columns-compute "org-colview" (property))
4560 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4561 '(org-columns-number-to-string
4562 org-columns-get-format-and-top-level
4563 org-columns-compute
4564 org-columns-remove-overlays))
4566 ;; Autoload ID code
4568 (declare-function org-id-store-link "org-id")
4569 (declare-function org-id-locations-load "org-id")
4570 (declare-function org-id-locations-save "org-id")
4571 (defvar org-id-track-globally)
4572 (org-autoload "org-id"
4573 '(org-id-new
4574 org-id-copy
4575 org-id-get-with-outline-path-completion
4576 org-id-get-with-outline-drilling))
4578 ;;; Variables for pre-computed regular expressions, all buffer local
4580 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4581 "Matches first line of a hidden block.")
4582 (make-variable-buffer-local 'org-drawer-regexp)
4583 (defvar org-todo-regexp nil
4584 "Matches any of the TODO state keywords.")
4585 (make-variable-buffer-local 'org-todo-regexp)
4586 (defvar org-not-done-regexp nil
4587 "Matches any of the TODO state keywords except the last one.")
4588 (make-variable-buffer-local 'org-not-done-regexp)
4589 (defvar org-not-done-heading-regexp nil
4590 "Matches a TODO headline that is not done.")
4591 (make-variable-buffer-local 'org-not-done-regexp)
4592 (defvar org-todo-line-regexp nil
4593 "Matches a headline and puts TODO state into group 2 if present.")
4594 (make-variable-buffer-local 'org-todo-line-regexp)
4595 (defvar org-complex-heading-regexp nil
4596 "Matches a headline and puts everything into groups:
4597 group 1: the stars
4598 group 2: The todo keyword, maybe
4599 group 3: Priority cookie
4600 group 4: True headline
4601 group 5: Tags")
4602 (make-variable-buffer-local 'org-complex-heading-regexp)
4603 (defvar org-complex-heading-regexp-format nil
4604 "Printf format to make regexp to match an exact headline.
4605 This regexp will match the headline of any node which has the
4606 exact headline text that is put into the format, but may have any
4607 TODO state, priority and tags.")
4608 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4609 (defvar org-todo-line-tags-regexp nil
4610 "Matches a headline and puts TODO state into group 2 if present.
4611 Also put tags into group 4 if tags are present.")
4612 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4613 (defvar org-ds-keyword-length 12
4614 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4615 (make-variable-buffer-local 'org-ds-keyword-length)
4616 (defvar org-deadline-regexp nil
4617 "Matches the DEADLINE keyword.")
4618 (make-variable-buffer-local 'org-deadline-regexp)
4619 (defvar org-deadline-time-regexp nil
4620 "Matches the DEADLINE keyword together with a time stamp.")
4621 (make-variable-buffer-local 'org-deadline-time-regexp)
4622 (defvar org-deadline-time-hour-regexp nil
4623 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4624 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4625 (defvar org-deadline-line-regexp nil
4626 "Matches the DEADLINE keyword and the rest of the line.")
4627 (make-variable-buffer-local 'org-deadline-line-regexp)
4628 (defvar org-scheduled-regexp nil
4629 "Matches the SCHEDULED keyword.")
4630 (make-variable-buffer-local 'org-scheduled-regexp)
4631 (defvar org-scheduled-time-regexp nil
4632 "Matches the SCHEDULED keyword together with a time stamp.")
4633 (make-variable-buffer-local 'org-scheduled-time-regexp)
4634 (defvar org-scheduled-time-hour-regexp nil
4635 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4636 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4637 (defvar org-closed-time-regexp nil
4638 "Matches the CLOSED keyword together with a time stamp.")
4639 (make-variable-buffer-local 'org-closed-time-regexp)
4641 (defvar org-keyword-time-regexp nil
4642 "Matches any of the 4 keywords, together with the time stamp.")
4643 (make-variable-buffer-local 'org-keyword-time-regexp)
4644 (defvar org-keyword-time-not-clock-regexp nil
4645 "Matches any of the 3 keywords, together with the time stamp.")
4646 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4647 (defvar org-maybe-keyword-time-regexp nil
4648 "Matches a timestamp, possibly preceded by a keyword.")
4649 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4650 (defvar org-all-time-keywords nil
4651 "List of time keywords.")
4652 (make-variable-buffer-local 'org-all-time-keywords)
4654 (defconst org-plain-time-of-day-regexp
4655 (concat
4656 "\\(\\<[012]?[0-9]"
4657 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4658 "\\(--?"
4659 "\\(\\<[012]?[0-9]"
4660 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4661 "\\)?")
4662 "Regular expression to match a plain time or time range.
4663 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4664 groups carry important information:
4665 0 the full match
4666 1 the first time, range or not
4667 8 the second time, if it is a range.")
4669 (defconst org-plain-time-extension-regexp
4670 (concat
4671 "\\(\\<[012]?[0-9]"
4672 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4673 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4674 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4675 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4676 groups carry important information:
4677 0 the full match
4678 7 hours of duration
4679 9 minutes of duration")
4681 (defconst org-stamp-time-of-day-regexp
4682 (concat
4683 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4684 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4685 "\\(--?"
4686 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4687 "Regular expression to match a timestamp time or time range.
4688 After a match, the following groups carry important information:
4689 0 the full match
4690 1 date plus weekday, for back referencing to make sure both times are on the same day
4691 2 the first time, range or not
4692 4 the second time, if it is a range.")
4694 (defconst org-startup-options
4695 '(("fold" org-startup-folded t)
4696 ("overview" org-startup-folded t)
4697 ("nofold" org-startup-folded nil)
4698 ("showall" org-startup-folded nil)
4699 ("showeverything" org-startup-folded showeverything)
4700 ("content" org-startup-folded content)
4701 ("indent" org-startup-indented t)
4702 ("noindent" org-startup-indented nil)
4703 ("hidestars" org-hide-leading-stars t)
4704 ("showstars" org-hide-leading-stars nil)
4705 ("odd" org-odd-levels-only t)
4706 ("oddeven" org-odd-levels-only nil)
4707 ("align" org-startup-align-all-tables t)
4708 ("noalign" org-startup-align-all-tables nil)
4709 ("inlineimages" org-startup-with-inline-images t)
4710 ("noinlineimages" org-startup-with-inline-images nil)
4711 ("latexpreview" org-startup-with-latex-preview t)
4712 ("nolatexpreview" org-startup-with-latex-preview nil)
4713 ("customtime" org-display-custom-times t)
4714 ("logdone" org-log-done time)
4715 ("lognotedone" org-log-done note)
4716 ("nologdone" org-log-done nil)
4717 ("lognoteclock-out" org-log-note-clock-out t)
4718 ("nolognoteclock-out" org-log-note-clock-out nil)
4719 ("logrepeat" org-log-repeat state)
4720 ("lognoterepeat" org-log-repeat note)
4721 ("logdrawer" org-log-into-drawer t)
4722 ("nologdrawer" org-log-into-drawer nil)
4723 ("logstatesreversed" org-log-states-order-reversed t)
4724 ("nologstatesreversed" org-log-states-order-reversed nil)
4725 ("nologrepeat" org-log-repeat nil)
4726 ("logreschedule" org-log-reschedule time)
4727 ("lognotereschedule" org-log-reschedule note)
4728 ("nologreschedule" org-log-reschedule nil)
4729 ("logredeadline" org-log-redeadline time)
4730 ("lognoteredeadline" org-log-redeadline note)
4731 ("nologredeadline" org-log-redeadline nil)
4732 ("logrefile" org-log-refile time)
4733 ("lognoterefile" org-log-refile note)
4734 ("nologrefile" org-log-refile nil)
4735 ("fninline" org-footnote-define-inline t)
4736 ("nofninline" org-footnote-define-inline nil)
4737 ("fnlocal" org-footnote-section nil)
4738 ("fnauto" org-footnote-auto-label t)
4739 ("fnprompt" org-footnote-auto-label nil)
4740 ("fnconfirm" org-footnote-auto-label confirm)
4741 ("fnplain" org-footnote-auto-label plain)
4742 ("fnadjust" org-footnote-auto-adjust t)
4743 ("nofnadjust" org-footnote-auto-adjust nil)
4744 ("constcgs" constants-unit-system cgs)
4745 ("constSI" constants-unit-system SI)
4746 ("noptag" org-tag-persistent-alist nil)
4747 ("hideblocks" org-hide-block-startup t)
4748 ("nohideblocks" org-hide-block-startup nil)
4749 ("beamer" org-startup-with-beamer-mode t)
4750 ("entitiespretty" org-pretty-entities t)
4751 ("entitiesplain" org-pretty-entities nil))
4752 "Variable associated with STARTUP options for org-mode.
4753 Each element is a list of three items: the startup options (as written
4754 in the #+STARTUP line), the corresponding variable, and the value to set
4755 this variable to if the option is found. An optional forth element PUSH
4756 means to push this value onto the list in the variable.")
4758 (defun org-update-property-plist (key val props)
4759 "Update PROPS with KEY and VAL."
4760 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4761 (key (if appending (substring key 0 (- (length key) 1)) key))
4762 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4763 (previous (cdr (assoc key props))))
4764 (if appending
4765 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4766 (cons (cons key val) remainder))))
4768 (defconst org-block-regexp
4769 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4770 "Regular expression for hiding blocks.")
4771 (defconst org-heading-keyword-regexp-format
4772 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4773 "Printf format for a regexp matching a headline with some keyword.
4774 This regexp will match the headline of any node which has the
4775 exact keyword that is put into the format. The keyword isn't in
4776 any group by default, but the stars and the body are.")
4777 (defconst org-heading-keyword-maybe-regexp-format
4778 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4779 "Printf format for a regexp matching a headline, possibly with some keyword.
4780 This regexp can match any headline with the specified keyword, or
4781 without a keyword. The keyword isn't in any group by default,
4782 but the stars and the body are.")
4784 (defcustom org-group-tags t
4785 "When non-nil (the default), use group tags.
4786 This can be turned on/off through `org-toggle-tags-groups'."
4787 :group 'org-tags
4788 :group 'org-startup
4789 :type 'boolean)
4791 (defun org-toggle-tags-groups ()
4792 "Toggle support for group tags.
4793 Support for group tags is controlled by the option
4794 `org-group-tags', which is non-nil by default."
4795 (interactive)
4796 (setq org-group-tags (not org-group-tags))
4797 (cond ((and (derived-mode-p 'org-agenda-mode)
4798 org-group-tags)
4799 (org-agenda-redo))
4800 ((derived-mode-p 'org-mode)
4801 (let ((org-inhibit-startup t)) (org-mode))))
4802 (message "Groups tags support has been turned %s"
4803 (if org-group-tags "on" "off")))
4805 (defun org-set-regexps-and-options-for-tags ()
4806 "Precompute variables used for tags."
4807 (when (derived-mode-p 'org-mode)
4808 (org-set-local 'org-file-tags nil)
4809 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4810 (splitre "[ \t]+")
4811 (start 0)
4812 tags ftags key value)
4813 (save-excursion
4814 (save-restriction
4815 (widen)
4816 (goto-char (point-min))
4817 (while (re-search-forward re nil t)
4818 (setq key (upcase (org-match-string-no-properties 1))
4819 value (org-match-string-no-properties 2))
4820 (if (stringp value) (setq value (org-trim value)))
4821 (cond
4822 ((equal key "TAGS")
4823 (setq tags (append tags (if tags '("\\n") nil)
4824 (org-split-string value splitre))))
4825 ((equal key "FILETAGS")
4826 (when (string-match "\\S-" value)
4827 (setq ftags
4828 (append
4829 ftags
4830 (apply 'append
4831 (mapcar (lambda (x) (org-split-string x ":"))
4832 (org-split-string value)))))))))))
4833 ;; Process the file tags.
4834 (and ftags (org-set-local 'org-file-tags
4835 (mapcar 'org-add-prop-inherited ftags)))
4836 (org-set-local 'org-tag-groups-alist nil)
4837 ;; Process the tags.
4838 (when (and (not tags) org-tag-alist)
4839 (setq tags
4840 (mapcar
4841 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4842 ((eq (car tg) :endgroup) "}")
4843 ((eq (car tg) :grouptags) ":")
4844 (t (concat (car tg)
4845 (if (characterp (cdr tg))
4846 (format "(%s)" (char-to-string (cdr tg))) "")))))
4847 org-tag-alist)))
4848 (let (e tgs g)
4849 (while (setq e (pop tags))
4850 (cond
4851 ((equal e "{")
4852 (progn (push '(:startgroup) tgs)
4853 (when (equal (nth 1 tags) ":")
4854 (push (list (replace-regexp-in-string
4855 "(.+)$" "" (nth 0 tags)))
4856 org-tag-groups-alist)
4857 (setq g 0))))
4858 ((equal e ":") (push '(:grouptags) tgs))
4859 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4860 ((equal e "\\n") (push '(:newline) tgs))
4861 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4862 (push (cons (match-string 1 e)
4863 (string-to-char (match-string 2 e))) tgs)
4864 (if (and g (> g 0))
4865 (setcar org-tag-groups-alist
4866 (append (car org-tag-groups-alist)
4867 (list (match-string 1 e)))))
4868 (if g (setq g (1+ g))))
4869 (t (push (list e) tgs)
4870 (if (and g (> g 0))
4871 (setcar org-tag-groups-alist
4872 (append (car org-tag-groups-alist) (list e))))
4873 (if g (setq g (1+ g))))))
4874 (org-set-local 'org-tag-alist nil)
4875 (while (setq e (pop tgs))
4876 (or (and (stringp (car e))
4877 (assoc (car e) org-tag-alist))
4878 (push e org-tag-alist)))
4879 ;; Return a list with tag variables
4880 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4882 (defvar org-ota nil)
4883 (defun org-set-regexps-and-options ()
4884 "Precompute regular expressions used in the current buffer."
4885 (when (derived-mode-p 'org-mode)
4886 (org-set-local 'org-todo-kwd-alist nil)
4887 (org-set-local 'org-todo-key-alist nil)
4888 (org-set-local 'org-todo-key-trigger nil)
4889 (org-set-local 'org-todo-keywords-1 nil)
4890 (org-set-local 'org-done-keywords nil)
4891 (org-set-local 'org-todo-heads nil)
4892 (org-set-local 'org-todo-sets nil)
4893 (org-set-local 'org-todo-log-states nil)
4894 (org-set-local 'org-file-properties nil)
4895 (let ((re (org-make-options-regexp
4896 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4897 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4898 "SETUPFILE" "OPTIONS")
4899 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4900 (splitre "[ \t]+")
4901 (scripts org-use-sub-superscripts)
4902 kwds kws0 kwsa key log value cat arch const links hw dws
4903 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4904 (start 0))
4905 (save-excursion
4906 (save-restriction
4907 (widen)
4908 (goto-char (point-min))
4909 (while
4910 (or (and
4911 ext-setup-or-nil
4912 (not org-ota)
4913 (let (ret)
4914 (with-temp-buffer
4915 (insert ext-setup-or-nil)
4916 (let ((major-mode 'org-mode) org-ota)
4917 (setq ret (save-match-data
4918 (org-set-regexps-and-options-for-tags)))))
4919 ;; Append setupfile tags to existing tags
4920 (setq org-ota t)
4921 (setq org-file-tags
4922 (delq nil (append org-file-tags (nth 0 ret)))
4923 org-tag-alist
4924 (delq nil (append org-tag-alist (nth 1 ret)))
4925 org-tag-groups-alist
4926 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4927 (and ext-setup-or-nil
4928 (string-match re ext-setup-or-nil start)
4929 (setq start (match-end 0)))
4930 (and (setq ext-setup-or-nil nil start 0)
4931 (re-search-forward re nil t)))
4932 (setq key (upcase (match-string 1 ext-setup-or-nil))
4933 value (org-match-string-no-properties 2 ext-setup-or-nil))
4934 (if (stringp value) (setq value (org-trim value)))
4935 (cond
4936 ((equal key "CATEGORY")
4937 (setq cat value))
4938 ((member key '("SEQ_TODO" "TODO"))
4939 (push (cons 'sequence (org-split-string value splitre)) kwds))
4940 ((equal key "TYP_TODO")
4941 (push (cons 'type (org-split-string value splitre)) kwds))
4942 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4943 ;; general TODO-like setup
4944 (push (cons (intern (downcase (match-string 1 key)))
4945 (org-split-string value splitre)) kwds))
4946 ((equal key "COLUMNS")
4947 (org-set-local 'org-columns-default-format value))
4948 ((equal key "LINK")
4949 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4950 (push (cons (match-string 1 value)
4951 (org-trim (match-string 2 value)))
4952 links)))
4953 ((equal key "PRIORITIES")
4954 (setq prio (org-split-string value " +")))
4955 ((equal key "PROPERTY")
4956 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4957 (setq props (org-update-property-plist (match-string 1 value)
4958 (match-string 2 value)
4959 props))))
4960 ((equal key "DRAWERS")
4961 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4962 ((equal key "CONSTANTS")
4963 (org-table-set-constants))
4964 ((equal key "STARTUP")
4965 (let ((opts (org-split-string value splitre))
4966 l var val)
4967 (while (setq l (pop opts))
4968 (when (setq l (assoc l org-startup-options))
4969 (setq var (nth 1 l) val (nth 2 l))
4970 (if (not (nth 3 l))
4971 (set (make-local-variable var) val)
4972 (if (not (listp (symbol-value var)))
4973 (set (make-local-variable var) nil))
4974 (set (make-local-variable var) (symbol-value var))
4975 (add-to-list var val))))))
4976 ((equal key "ARCHIVE")
4977 (setq arch value)
4978 (remove-text-properties 0 (length arch)
4979 '(face t fontified t) arch))
4980 ((equal key "OPTIONS")
4981 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4982 (setq scripts (read (match-string 2 value)))))
4983 ((and (equal key "SETUPFILE")
4984 ;; Prevent checking in Gnus messages
4985 (not buffer-read-only))
4986 (setq setup-contents (org-file-contents
4987 (expand-file-name
4988 (org-remove-double-quotes value))
4989 'noerror))
4990 (if (not ext-setup-or-nil)
4991 (setq ext-setup-or-nil setup-contents start 0)
4992 (setq ext-setup-or-nil
4993 (concat (substring ext-setup-or-nil 0 start)
4994 "\n" setup-contents "\n"
4995 (substring ext-setup-or-nil start)))))))
4996 ;; search for property blocks
4997 (goto-char (point-min))
4998 (while (re-search-forward org-block-regexp nil t)
4999 (when (equal "PROPERTY" (upcase (match-string 1)))
5000 (setq value (replace-regexp-in-string
5001 "[\n\r]" " " (match-string 4)))
5002 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5003 (setq props (org-update-property-plist (match-string 1 value)
5004 (match-string 2 value)
5005 props)))))))
5006 (org-set-local 'org-use-sub-superscripts scripts)
5007 (when cat
5008 (org-set-local 'org-category (intern cat))
5009 (push (cons "CATEGORY" cat) props))
5010 (when prio
5011 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5012 (setq prio (mapcar 'string-to-char prio))
5013 (org-set-local 'org-highest-priority (nth 0 prio))
5014 (org-set-local 'org-lowest-priority (nth 1 prio))
5015 (org-set-local 'org-default-priority (nth 2 prio)))
5016 (and props (org-set-local 'org-file-properties (nreverse props)))
5017 (and drawers (org-set-local 'org-drawers drawers))
5018 (and arch (org-set-local 'org-archive-location arch))
5019 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5020 ;; Process the TODO keywords
5021 (unless kwds
5022 ;; Use the global values as if they had been given locally.
5023 (setq kwds (default-value 'org-todo-keywords))
5024 (if (stringp (car kwds))
5025 (setq kwds (list (cons org-todo-interpretation
5026 (default-value 'org-todo-keywords)))))
5027 (setq kwds (reverse kwds)))
5028 (setq kwds (nreverse kwds))
5029 (let (inter kws kw)
5030 (while (setq kws (pop kwds))
5031 (let ((kws (or
5032 (run-hook-with-args-until-success
5033 'org-todo-setup-filter-hook kws)
5034 kws)))
5035 (setq inter (pop kws) sep (member "|" kws)
5036 kws0 (delete "|" (copy-sequence kws))
5037 kwsa nil
5038 kws1 (mapcar
5039 (lambda (x)
5040 ;; 1 2
5041 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5042 (progn
5043 (setq kw (match-string 1 x)
5044 key (and (match-end 2) (match-string 2 x))
5045 log (org-extract-log-state-settings x))
5046 (push (cons kw (and key (string-to-char key))) kwsa)
5047 (and log (push log org-todo-log-states))
5049 (error "Invalid TODO keyword %s" x)))
5050 kws0)
5051 kwsa (if kwsa (append '((:startgroup))
5052 (nreverse kwsa)
5053 '((:endgroup))))
5054 hw (car kws1)
5055 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5056 tail (list inter hw (car dws) (org-last dws))))
5057 (add-to-list 'org-todo-heads hw 'append)
5058 (push kws1 org-todo-sets)
5059 (setq org-done-keywords (append org-done-keywords dws nil))
5060 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5061 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5062 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5063 (setq org-todo-sets (nreverse org-todo-sets)
5064 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5065 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5066 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5067 ;; Compute the regular expressions and other local variables.
5068 ;; Using `org-outline-regexp-bol' would complicate them much,
5069 ;; because of the fixed white space at the end of that string.
5070 (if (not org-done-keywords)
5071 (setq org-done-keywords (and org-todo-keywords-1
5072 (list (org-last org-todo-keywords-1)))))
5073 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5074 (length org-scheduled-string)
5075 (length org-clock-string)
5076 (length org-closed-string)))
5077 org-drawer-regexp
5078 (concat "^[ \t]*:\\("
5079 (mapconcat 'regexp-quote org-drawers "\\|")
5080 "\\):[ \t]*$")
5081 org-not-done-keywords
5082 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5083 org-todo-regexp
5084 (concat "\\("
5085 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5086 "\\)")
5087 org-not-done-regexp
5088 (concat "\\("
5089 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5090 "\\)")
5091 org-not-done-heading-regexp
5092 (format org-heading-keyword-regexp-format org-not-done-regexp)
5093 org-todo-line-regexp
5094 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5095 org-complex-heading-regexp
5096 (concat "^\\(\\*+\\)"
5097 "\\(?: +" org-todo-regexp "\\)?"
5098 "\\(?: +\\(\\[#.\\]\\)\\)?"
5099 "\\(?: +\\(.*?\\)\\)??"
5100 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5101 "[ \t]*$")
5102 org-complex-heading-regexp-format
5103 (concat "^\\(\\*+\\)"
5104 "\\(?: +" org-todo-regexp "\\)?"
5105 "\\(?: +\\(\\[#.\\]\\)\\)?"
5106 "\\(?: +"
5107 ;; Stats cookies can be stuck to body.
5108 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5109 "\\(%s\\)"
5110 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5111 "\\)"
5112 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5113 "[ \t]*$")
5114 org-todo-line-tags-regexp
5115 (concat "^\\(\\*+\\)"
5116 "\\(?: +" org-todo-regexp "\\)?"
5117 "\\(?: +\\(.*?\\)\\)??"
5118 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5119 "[ \t]*$")
5120 org-deadline-regexp (concat "\\<" org-deadline-string)
5121 org-deadline-time-regexp
5122 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5123 org-deadline-time-hour-regexp
5124 (concat "\\<" org-deadline-string
5125 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5126 org-deadline-line-regexp
5127 (concat "\\<\\(" org-deadline-string "\\).*")
5128 org-scheduled-regexp
5129 (concat "\\<" org-scheduled-string)
5130 org-scheduled-time-regexp
5131 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5132 org-scheduled-time-hour-regexp
5133 (concat "\\<" org-scheduled-string
5134 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5135 org-closed-time-regexp
5136 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5137 org-keyword-time-regexp
5138 (concat "\\<\\(" org-scheduled-string
5139 "\\|" org-deadline-string
5140 "\\|" org-closed-string
5141 "\\|" org-clock-string "\\)"
5142 " *[[<]\\([^]>]+\\)[]>]")
5143 org-keyword-time-not-clock-regexp
5144 (concat "\\<\\(" org-scheduled-string
5145 "\\|" org-deadline-string
5146 "\\|" org-closed-string
5147 "\\)"
5148 " *[[<]\\([^]>]+\\)[]>]")
5149 org-maybe-keyword-time-regexp
5150 (concat "\\(\\<\\(" org-scheduled-string
5151 "\\|" org-deadline-string
5152 "\\|" org-closed-string
5153 "\\|" org-clock-string "\\)\\)?"
5154 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5155 org-all-time-keywords
5156 (mapcar (lambda (w) (substring w 0 -1))
5157 (list org-scheduled-string org-deadline-string
5158 org-clock-string org-closed-string)))
5159 (setq org-ota nil)
5160 (org-compute-latex-and-related-regexp))))
5162 (defun org-file-contents (file &optional noerror)
5163 "Return the contents of FILE, as a string."
5164 (if (or (not file)
5165 (not (file-readable-p file)))
5166 (if noerror
5167 (message "Cannot read file \"%s\"" file)
5168 (error "Cannot read file \"%s\"" file))
5169 (with-temp-buffer
5170 (insert-file-contents file)
5171 (buffer-string))))
5173 (defun org-extract-log-state-settings (x)
5174 "Extract the log state setting from a TODO keyword string.
5175 This will extract info from a string like \"WAIT(w@/!)\"."
5176 (let (kw key log1 log2)
5177 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5178 (setq kw (match-string 1 x)
5179 key (and (match-end 2) (match-string 2 x))
5180 log1 (and (match-end 3) (match-string 3 x))
5181 log2 (and (match-end 4) (match-string 4 x)))
5182 (and (or log1 log2)
5183 (list kw
5184 (and log1 (if (equal log1 "!") 'time 'note))
5185 (and log2 (if (equal log2 "!") 'time 'note)))))))
5187 (defun org-remove-keyword-keys (list)
5188 "Remove a pair of parenthesis at the end of each string in LIST."
5189 (mapcar (lambda (x)
5190 (if (string-match "(.*)$" x)
5191 (substring x 0 (match-beginning 0))
5193 list))
5195 (defun org-assign-fast-keys (alist)
5196 "Assign fast keys to a keyword-key alist.
5197 Respect keys that are already there."
5198 (let (new e (alt ?0))
5199 (while (setq e (pop alist))
5200 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5201 (cdr e)) ;; Key already assigned.
5202 (push e new)
5203 (let ((clist (string-to-list (downcase (car e))))
5204 (used (append new alist)))
5205 (when (= (car clist) ?@)
5206 (pop clist))
5207 (while (and clist (rassoc (car clist) used))
5208 (pop clist))
5209 (unless clist
5210 (while (rassoc alt used)
5211 (incf alt)))
5212 (push (cons (car e) (or (car clist) alt)) new))))
5213 (nreverse new)))
5215 ;;; Some variables used in various places
5217 (defvar org-window-configuration nil
5218 "Used in various places to store a window configuration.")
5219 (defvar org-selected-window nil
5220 "Used in various places to store a window configuration.")
5221 (defvar org-finish-function nil
5222 "Function to be called when `C-c C-c' is used.
5223 This is for getting out of special buffers like capture.")
5226 ;; FIXME: Occasionally check by commenting these, to make sure
5227 ;; no other functions uses these, forgetting to let-bind them.
5228 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5229 (defvar org-last-state)
5230 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5232 ;; Defined somewhere in this file, but used before definition.
5233 (defvar org-entities) ;; defined in org-entities.el
5234 (defvar org-struct-menu)
5235 (defvar org-org-menu)
5236 (defvar org-tbl-menu)
5238 ;;;; Define the Org-mode
5240 ;; We use a before-change function to check if a table might need
5241 ;; an update.
5242 (defvar org-table-may-need-update t
5243 "Indicates that a table might need an update.
5244 This variable is set by `org-before-change-function'.
5245 `org-table-align' sets it back to nil.")
5246 (defun org-before-change-function (beg end)
5247 "Every change indicates that a table might need an update."
5248 (setq org-table-may-need-update t))
5249 (defvar org-mode-map)
5250 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5251 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5252 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5253 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5254 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5255 (defvar org-table-buffer-is-an nil)
5257 (defvar bidi-paragraph-direction)
5258 (defvar buffer-face-mode-face)
5260 (require 'outline)
5261 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5262 (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"))
5263 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5265 ;; Other stuff we need.
5266 (require 'time-date)
5267 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5268 (require 'easymenu)
5269 (require 'overlay)
5271 ;; (require 'org-macs) moved higher up in the file before it is first used
5272 (require 'org-entities)
5273 ;; (require 'org-compat) moved higher up in the file before it is first used
5274 (require 'org-faces)
5275 (require 'org-list)
5276 (require 'org-pcomplete)
5277 (require 'org-src)
5278 (require 'org-footnote)
5279 (require 'org-macro)
5281 ;; babel
5282 (require 'ob)
5284 ;;;###autoload
5285 (define-derived-mode org-mode outline-mode "Org"
5286 "Outline-based notes management and organizer, alias
5287 \"Carsten's outline-mode for keeping track of everything.\"
5289 Org-mode develops organizational tasks around a NOTES file which
5290 contains information about projects as plain text. Org-mode is
5291 implemented on top of outline-mode, which is ideal to keep the content
5292 of large files well structured. It supports ToDo items, deadlines and
5293 time stamps, which magically appear in the diary listing of the Emacs
5294 calendar. Tables are easily created with a built-in table editor.
5295 Plain text URL-like links connect to websites, emails (VM), Usenet
5296 messages (Gnus), BBDB entries, and any files related to the project.
5297 For printing and sharing of notes, an Org-mode file (or a part of it)
5298 can be exported as a structured ASCII or HTML file.
5300 The following commands are available:
5302 \\{org-mode-map}"
5304 ;; Get rid of Outline menus, they are not needed
5305 ;; Need to do this here because define-derived-mode sets up
5306 ;; the keymap so late. Still, it is a waste to call this each time
5307 ;; we switch another buffer into org-mode.
5308 (if (featurep 'xemacs)
5309 (when (boundp 'outline-mode-menu-heading)
5310 ;; Assume this is Greg's port, it uses easymenu
5311 (easy-menu-remove outline-mode-menu-heading)
5312 (easy-menu-remove outline-mode-menu-show)
5313 (easy-menu-remove outline-mode-menu-hide))
5314 (define-key org-mode-map [menu-bar headings] 'undefined)
5315 (define-key org-mode-map [menu-bar hide] 'undefined)
5316 (define-key org-mode-map [menu-bar show] 'undefined))
5318 (org-load-modules-maybe)
5319 (easy-menu-add org-org-menu)
5320 (easy-menu-add org-tbl-menu)
5321 (org-install-agenda-files-menu)
5322 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5323 (add-to-invisibility-spec '(org-cwidth))
5324 (add-to-invisibility-spec '(org-hide-block . t))
5325 (when (featurep 'xemacs)
5326 (org-set-local 'line-move-ignore-invisible t))
5327 (org-set-local 'outline-regexp org-outline-regexp)
5328 (org-set-local 'outline-level 'org-outline-level)
5329 (setq bidi-paragraph-direction 'left-to-right)
5330 (when (and org-ellipsis
5331 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5332 (fboundp 'make-glyph-code))
5333 (unless org-display-table
5334 (setq org-display-table (make-display-table)))
5335 (set-display-table-slot
5336 org-display-table 4
5337 (vconcat (mapcar
5338 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5339 org-ellipsis)))
5340 (if (stringp org-ellipsis) org-ellipsis "..."))))
5341 (setq buffer-display-table org-display-table))
5342 (org-set-regexps-and-options-for-tags)
5343 (org-set-regexps-and-options)
5344 (org-set-font-lock-defaults)
5345 (when (and org-tag-faces (not org-tags-special-faces-re))
5346 ;; tag faces set outside customize.... force initialization.
5347 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5348 ;; Calc embedded
5349 (org-set-local 'calc-embedded-open-mode "# ")
5350 ;; Modify a few syntax entries
5351 (modify-syntax-entry ?@ "w")
5352 (modify-syntax-entry ?\" "\"")
5353 (if org-startup-truncated (setq truncate-lines t))
5354 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5355 (org-set-local 'font-lock-unfontify-region-function
5356 'org-unfontify-region)
5357 ;; Activate before-change-function
5358 (org-set-local 'org-table-may-need-update t)
5359 (org-add-hook 'before-change-functions 'org-before-change-function nil
5360 'local)
5361 ;; Check for running clock before killing a buffer
5362 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5363 ;; Initialize macros templates.
5364 (org-macro-initialize-templates)
5365 ;; Initialize radio targets.
5366 (org-update-radio-target-regexp)
5367 ;; Indentation.
5368 (org-set-local 'indent-line-function 'org-indent-line)
5369 (org-set-local 'indent-region-function 'org-indent-region)
5370 ;; Filling and auto-filling.
5371 (org-setup-filling)
5372 ;; Comments.
5373 (org-setup-comments-handling)
5374 ;; Beginning/end of defun
5375 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5376 (org-set-local 'end-of-defun-function 'org-forward-element)
5377 ;; Next error for sparse trees
5378 (org-set-local 'next-error-function 'org-occur-next-match)
5379 ;; Make sure dependence stuff works reliably, even for users who set it
5380 ;; too late :-(
5381 (if org-enforce-todo-dependencies
5382 (add-hook 'org-blocker-hook
5383 'org-block-todo-from-children-or-siblings-or-parent)
5384 (remove-hook 'org-blocker-hook
5385 'org-block-todo-from-children-or-siblings-or-parent))
5386 (if org-enforce-todo-checkbox-dependencies
5387 (add-hook 'org-blocker-hook
5388 'org-block-todo-from-checkboxes)
5389 (remove-hook 'org-blocker-hook
5390 'org-block-todo-from-checkboxes))
5392 ;; Align options lines
5393 (org-set-local
5394 'align-mode-rules-list
5395 '((org-in-buffer-settings
5396 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5397 (modes . '(org-mode)))))
5399 ;; Imenu
5400 (org-set-local 'imenu-create-index-function
5401 'org-imenu-get-tree)
5403 ;; Make isearch reveal context
5404 (if (or (featurep 'xemacs)
5405 (not (boundp 'outline-isearch-open-invisible-function)))
5406 ;; Emacs 21 and XEmacs make use of the hook
5407 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5408 ;; Emacs 22 deals with this through a special variable
5409 (org-set-local 'outline-isearch-open-invisible-function
5410 (lambda (&rest ignore) (org-show-context 'isearch)))
5411 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5413 ;; Setup the pcomplete hooks
5414 (set (make-local-variable 'pcomplete-command-completion-function)
5415 'org-pcomplete-initial)
5416 (set (make-local-variable 'pcomplete-command-name-function)
5417 'org-command-at-point)
5418 (set (make-local-variable 'pcomplete-default-completion-function)
5419 'ignore)
5420 (set (make-local-variable 'pcomplete-parse-arguments-function)
5421 'org-parse-arguments)
5422 (set (make-local-variable 'pcomplete-termination-string) "")
5423 (when (>= emacs-major-version 23)
5424 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5426 ;; If empty file that did not turn on org-mode automatically, make it to.
5427 (if (and org-insert-mode-line-in-empty-file
5428 (org-called-interactively-p 'any)
5429 (= (point-min) (point-max)))
5430 (insert "# -*- mode: org -*-\n\n"))
5431 (unless org-inhibit-startup
5432 (org-unmodified
5433 (and org-startup-with-beamer-mode (org-beamer-mode))
5434 (when org-startup-align-all-tables
5435 (org-table-map-tables 'org-table-align 'quietly))
5436 (when org-startup-with-inline-images
5437 (org-display-inline-images))
5438 (when org-startup-with-latex-preview
5439 (org-preview-latex-fragment))
5440 (unless org-inhibit-startup-visibility-stuff
5441 (org-set-startup-visibility))))
5442 ;; Try to set org-hide correctly
5443 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5445 ;; Update `customize-package-emacs-version-alist'
5446 (add-to-list 'customize-package-emacs-version-alist
5447 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5448 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5449 ("8.0" . "24.4")))
5451 (defvar org-mode-transpose-word-syntax-table
5452 (let ((st (make-syntax-table)))
5453 (mapc (lambda(c) (modify-syntax-entry
5454 (string-to-char (car c)) "w p" st))
5455 org-emphasis-alist)
5456 st))
5458 (when (fboundp 'abbrev-table-put)
5459 (abbrev-table-put org-mode-abbrev-table
5460 :parents (list text-mode-abbrev-table)))
5462 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5464 (defsubst org-fix-ellipsis-at-bol ()
5465 (save-excursion (goto-char (window-start)) (recenter 0)))
5467 (defun org-find-invisible-foreground ()
5468 (let ((candidates (remove
5469 "unspecified-bg"
5470 (nconc
5471 (list (face-background 'default)
5472 (face-background 'org-default))
5473 (mapcar
5474 (lambda (alist)
5475 (when (boundp alist)
5476 (cdr (assoc 'background-color (symbol-value alist)))))
5477 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5478 (list (face-foreground 'org-hide))))))
5479 (car (remove nil candidates))))
5481 (defun org-current-time (&optional rounding-minutes past)
5482 "Current time, possibly rounded to ROUNDING-MINUTES.
5483 When ROUNDING-MINUTES is not an integer, fall back on the car of
5484 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5485 the rounding returns a past time."
5486 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5487 (car org-time-stamp-rounding-minutes)))
5488 (time (decode-time)) res)
5489 (if (< r 1)
5490 (current-time)
5491 (setq res
5492 (apply 'encode-time
5493 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5494 (nthcdr 2 time))))
5495 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5496 (seconds-to-time (- (org-float-time res) (* r 60)))
5497 res))))
5499 (defun org-today ()
5500 "Return today date, considering `org-extend-today-until'."
5501 (time-to-days
5502 (time-subtract (current-time)
5503 (list 0 (* 3600 org-extend-today-until) 0))))
5505 ;;;; Font-Lock stuff, including the activators
5507 (defvar org-mouse-map (make-sparse-keymap))
5508 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5509 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5510 (when org-mouse-1-follows-link
5511 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5512 (when org-tab-follows-link
5513 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5514 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5516 (require 'font-lock)
5518 (defconst org-non-link-chars "]\t\n\r<>")
5519 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5520 "shell" "elisp" "doi" "message"))
5521 (defvar org-link-types-re nil
5522 "Matches a link that has a url-like prefix like \"http:\"")
5523 (defvar org-link-re-with-space nil
5524 "Matches a link with spaces, optional angular brackets around it.")
5525 (defvar org-link-re-with-space2 nil
5526 "Matches a link with spaces, optional angular brackets around it.")
5527 (defvar org-link-re-with-space3 nil
5528 "Matches a link with spaces, only for internal part in bracket links.")
5529 (defvar org-angle-link-re nil
5530 "Matches link with angular brackets, spaces are allowed.")
5531 (defvar org-plain-link-re nil
5532 "Matches plain link, without spaces.")
5533 (defvar org-bracket-link-regexp nil
5534 "Matches a link in double brackets.")
5535 (defvar org-bracket-link-analytic-regexp nil
5536 "Regular expression used to analyze links.
5537 Here is what the match groups contain after a match:
5538 1: http:
5539 2: http
5540 3: path
5541 4: [desc]
5542 5: desc")
5543 (defvar org-bracket-link-analytic-regexp++ nil
5544 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5545 (defvar org-any-link-re nil
5546 "Regular expression matching any link.")
5548 (defconst org-match-sexp-depth 3
5549 "Number of stacked braces for sub/superscript matching.")
5551 (defun org-create-multibrace-regexp (left right n)
5552 "Create a regular expression which will match a balanced sexp.
5553 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5554 as single character strings.
5555 The regexp returned will match the entire expression including the
5556 delimiters. It will also define a single group which contains the
5557 match except for the outermost delimiters. The maximum depth of
5558 stacked delimiters is N. Escaping delimiters is not possible."
5559 (let* ((nothing (concat "[^" left right "]*?"))
5560 (or "\\|")
5561 (re nothing)
5562 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5563 (while (> n 1)
5564 (setq n (1- n)
5565 re (concat re or next)
5566 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5567 (concat left "\\(" re "\\)" right)))
5569 (defvar org-match-substring-regexp
5570 (concat
5571 "\\(\\S-\\)\\([_^]\\)\\("
5572 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5573 "\\|"
5574 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5575 "\\|"
5576 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5577 "The regular expression matching a sub- or superscript.")
5579 (defvar org-match-substring-with-braces-regexp
5580 (concat
5581 "\\(\\S-\\)\\([_^]\\)\\("
5582 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5583 "\\)")
5584 "The regular expression matching a sub- or superscript, forcing braces.")
5586 (defun org-make-link-regexps ()
5587 "Update the link regular expressions.
5588 This should be called after the variable `org-link-types' has changed."
5589 (setq org-link-types-re
5590 (concat
5591 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5592 org-link-re-with-space
5593 (concat
5594 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5595 "\\([^" org-non-link-chars " ]"
5596 "[^" org-non-link-chars "]*"
5597 "[^" org-non-link-chars " ]\\)>?")
5598 org-link-re-with-space2
5599 (concat
5600 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5601 "\\([^" org-non-link-chars " ]"
5602 "[^\t\n\r]*"
5603 "[^" org-non-link-chars " ]\\)>?")
5604 org-link-re-with-space3
5605 (concat
5606 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5607 "\\([^" org-non-link-chars " ]"
5608 "[^\t\n\r]*\\)")
5609 org-angle-link-re
5610 (concat
5611 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5612 "\\([^" org-non-link-chars " ]"
5613 "[^" org-non-link-chars "]*"
5614 "\\)>")
5615 org-plain-link-re
5616 (concat
5617 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5618 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5619 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5620 org-bracket-link-regexp
5621 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5622 org-bracket-link-analytic-regexp
5623 (concat
5624 "\\[\\["
5625 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5626 "\\([^]]+\\)"
5627 "\\]"
5628 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5629 "\\]")
5630 org-bracket-link-analytic-regexp++
5631 (concat
5632 "\\[\\["
5633 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5634 "\\([^]]+\\)"
5635 "\\]"
5636 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5637 "\\]")
5638 org-any-link-re
5639 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5640 org-angle-link-re "\\)\\|\\("
5641 org-plain-link-re "\\)")))
5643 (org-make-link-regexps)
5645 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5646 "Regular expression for fast time stamp matching.")
5647 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5648 "Regular expression for fast time stamp matching.")
5649 (defconst org-ts-regexp0
5650 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5651 "Regular expression matching time strings for analysis.
5652 This one does not require the space after the date, so it can be used
5653 on a string that terminates immediately after the date.")
5654 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5655 "Regular expression matching time strings for analysis.")
5656 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5657 "Regular expression matching time stamps, with groups.")
5658 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5659 "Regular expression matching time stamps (also [..]), with groups.")
5660 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5661 "Regular expression matching a time stamp range.")
5662 (defconst org-tr-regexp-both
5663 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5664 "Regular expression matching a time stamp range.")
5665 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5666 org-ts-regexp "\\)?")
5667 "Regular expression matching a time stamp or time stamp range.")
5668 (defconst org-tsr-regexp-both
5669 (concat org-ts-regexp-both "\\(--?-?"
5670 org-ts-regexp-both "\\)?")
5671 "Regular expression matching a time stamp or time stamp range.
5672 The time stamps may be either active or inactive.")
5674 (defvar org-emph-face nil)
5676 (defun org-do-emphasis-faces (limit)
5677 "Run through the buffer and add overlays to emphasized strings."
5678 (let (rtn a)
5679 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5680 (if (not (= (char-after (match-beginning 3))
5681 (char-after (match-beginning 4))))
5682 (progn
5683 (setq rtn t)
5684 (setq a (assoc (match-string 3) org-emphasis-alist))
5685 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5686 'face
5687 (nth 1 a))
5688 (and (nth 4 a)
5689 (org-remove-flyspell-overlays-in
5690 (match-beginning 0) (match-end 0)))
5691 (add-text-properties (match-beginning 2) (match-end 2)
5692 '(font-lock-multiline t org-emphasis t))
5693 (when org-hide-emphasis-markers
5694 (add-text-properties (match-end 4) (match-beginning 5)
5695 '(invisible org-link))
5696 (add-text-properties (match-beginning 3) (match-end 3)
5697 '(invisible org-link)))))
5698 (backward-char 1))
5699 rtn))
5701 (defun org-emphasize (&optional char)
5702 "Insert or change an emphasis, i.e. a font like bold or italic.
5703 If there is an active region, change that region to a new emphasis.
5704 If there is no region, just insert the marker characters and position
5705 the cursor between them.
5706 CHAR should be the marker character. If it is a space, it means to
5707 remove the emphasis of the selected region.
5708 If CHAR is not given (for example in an interactive call) it will be
5709 prompted for."
5710 (interactive)
5711 (let ((erc org-emphasis-regexp-components)
5712 (prompt "")
5713 (string "") beg end move c s)
5714 (if (org-region-active-p)
5715 (setq beg (region-beginning) end (region-end)
5716 string (buffer-substring beg end))
5717 (setq move t))
5719 (unless char
5720 (message "Emphasis marker or tag: [%s]"
5721 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5722 (setq char (read-char-exclusive)))
5723 (if (equal char ?\ )
5724 (setq s "" move nil)
5725 (unless (assoc (char-to-string char) org-emphasis-alist)
5726 (user-error "No such emphasis marker: \"%c\"" char))
5727 (setq s (char-to-string char)))
5728 (while (and (> (length string) 1)
5729 (equal (substring string 0 1) (substring string -1))
5730 (assoc (substring string 0 1) org-emphasis-alist))
5731 (setq string (substring string 1 -1)))
5732 (setq string (concat s string s))
5733 (if beg (delete-region beg end))
5734 (unless (or (bolp)
5735 (string-match (concat "[" (nth 0 erc) "\n]")
5736 (char-to-string (char-before (point)))))
5737 (insert " "))
5738 (unless (or (eobp)
5739 (string-match (concat "[" (nth 1 erc) "\n]")
5740 (char-to-string (char-after (point)))))
5741 (insert " ") (backward-char 1))
5742 (insert string)
5743 (and move (backward-char 1))))
5745 (defconst org-nonsticky-props
5746 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5748 (defsubst org-rear-nonsticky-at (pos)
5749 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5751 (defun org-activate-plain-links (limit)
5752 "Run through the buffer and add overlays to links."
5753 (let (f hl)
5754 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5755 (not (org-in-src-block-p)))
5756 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5757 (setq f (get-text-property (match-beginning 0) 'face))
5758 (setq hl (org-match-string-no-properties 0))
5759 (if (or (eq f 'org-tag)
5760 (and (listp f) (memq 'org-tag f)))
5762 (add-text-properties (match-beginning 0) (match-end 0)
5763 (list 'mouse-face 'highlight
5764 'face 'org-link
5765 'htmlize-link `(:uri ,hl)
5766 'keymap org-mouse-map))
5767 (org-rear-nonsticky-at (match-end 0)))
5768 t)))
5770 (defun org-activate-code (limit)
5771 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5772 (progn
5773 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5774 (remove-text-properties (match-beginning 0) (match-end 0)
5775 '(display t invisible t intangible t))
5776 t)))
5778 (defcustom org-src-fontify-natively nil
5779 "When non-nil, fontify code in code blocks."
5780 :type 'boolean
5781 :version "24.1"
5782 :group 'org-appearance
5783 :group 'org-babel)
5785 (defcustom org-allow-promoting-top-level-subtree nil
5786 "When non-nil, allow promoting a top level subtree.
5787 The leading star of the top level headline will be replaced
5788 by a #."
5789 :type 'boolean
5790 :version "24.1"
5791 :group 'org-appearance)
5793 (defun org-fontify-meta-lines-and-blocks (limit)
5794 (condition-case nil
5795 (org-fontify-meta-lines-and-blocks-1 limit)
5796 (error (message "org-mode fontification error"))))
5798 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5799 "Fontify #+ lines and blocks."
5800 (let ((case-fold-search t))
5801 (if (re-search-forward
5802 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5803 limit t)
5804 (let ((beg (match-beginning 0))
5805 (block-start (match-end 0))
5806 (block-end nil)
5807 (lang (match-string 7))
5808 (beg1 (line-beginning-position 2))
5809 (dc1 (downcase (match-string 2)))
5810 (dc3 (downcase (match-string 3)))
5811 end end1 quoting block-type ovl)
5812 (cond
5813 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5814 ;; a single line of backend-specific content
5815 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5816 (remove-text-properties (match-beginning 0) (match-end 0)
5817 '(display t invisible t intangible t))
5818 (add-text-properties (match-beginning 1) (match-end 3)
5819 '(font-lock-fontified t face org-meta-line))
5820 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5821 '(font-lock-fontified t face org-block))
5822 ; for backend-specific code
5824 ((and (match-end 4) (equal dc3 "+begin"))
5825 ;; Truly a block
5826 (setq block-type (downcase (match-string 5))
5827 quoting (member block-type org-protecting-blocks))
5828 (when (re-search-forward
5829 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5830 nil t) ;; on purpose, we look further than LIMIT
5831 (setq end (min (point-max) (match-end 0))
5832 end1 (min (point-max) (1- (match-beginning 0))))
5833 (setq block-end (match-beginning 0))
5834 (when quoting
5835 (remove-text-properties beg end
5836 '(display t invisible t intangible t)))
5837 (add-text-properties
5838 beg end
5839 '(font-lock-fontified t font-lock-multiline t))
5840 (add-text-properties beg beg1 '(face org-meta-line))
5841 (add-text-properties end1 (min (point-max) (1+ end))
5842 '(face org-meta-line)) ; for end_src
5843 (cond
5844 ((and lang (not (string= lang "")) org-src-fontify-natively)
5845 (org-src-font-lock-fontify-block lang block-start block-end)
5846 ;; remove old background overlays
5847 (mapc (lambda (ov)
5848 (if (eq (overlay-get ov 'face) 'org-block-background)
5849 (delete-overlay ov)))
5850 (overlays-at (/ (+ beg1 block-end) 2)))
5851 ;; add a background overlay
5852 (setq ovl (make-overlay beg1 block-end))
5853 (overlay-put ovl 'face 'org-block-background)
5854 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5855 (quoting
5856 (add-text-properties beg1 (min (point-max) (1+ end1))
5857 '(face org-block))) ; end of source block
5858 ((not org-fontify-quote-and-verse-blocks))
5859 ((string= block-type "quote")
5860 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5861 ((string= block-type "verse")
5862 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5863 (add-text-properties beg beg1 '(face org-block-begin-line))
5864 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5865 '(face org-block-end-line))
5867 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5868 (add-text-properties
5869 beg (match-end 3)
5870 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5871 '(font-lock-fontified t invisible t)
5872 '(font-lock-fontified t face org-document-info-keyword)))
5873 (add-text-properties
5874 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5875 (if (string-equal dc1 "+title:")
5876 '(font-lock-fontified t face org-document-title)
5877 '(font-lock-fontified t face org-document-info))))
5878 ((or (equal dc1 "+results")
5879 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5880 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5881 "+call:" "+header:" "+headers:" "+name:"))
5882 (and (match-end 4) (equal dc3 "+attr")))
5883 (add-text-properties
5884 beg (match-end 0)
5885 '(font-lock-fontified t face org-meta-line))
5887 ((member dc3 '(" " ""))
5888 (add-text-properties
5889 beg (match-end 0)
5890 '(font-lock-fontified t face font-lock-comment-face)))
5891 ((not (member (char-after beg) '(?\ ?\t)))
5892 ;; just any other in-buffer setting, but not indented
5893 (add-text-properties
5894 beg (match-end 0)
5895 '(font-lock-fontified t face org-meta-line))
5897 (t nil))))))
5899 (defun org-activate-angle-links (limit)
5900 "Run through the buffer and add overlays to links."
5901 (if (and (re-search-forward org-angle-link-re limit t)
5902 (not (org-in-src-block-p)))
5903 (progn
5904 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5905 (add-text-properties (match-beginning 0) (match-end 0)
5906 (list 'mouse-face 'highlight
5907 'keymap org-mouse-map))
5908 (org-rear-nonsticky-at (match-end 0))
5909 t)))
5911 (defun org-activate-footnote-links (limit)
5912 "Run through the buffer and add overlays to footnotes."
5913 (let ((fn (org-footnote-next-reference-or-definition limit)))
5914 (when fn
5915 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5916 (org-remove-flyspell-overlays-in beg end)
5917 (add-text-properties beg end
5918 (list 'mouse-face 'highlight
5919 'keymap org-mouse-map
5920 'help-echo
5921 (if (= (point-at-bol) beg)
5922 "Footnote definition"
5923 "Footnote reference")
5924 'font-lock-fontified t
5925 'font-lock-multiline t
5926 'face 'org-footnote))))))
5928 (defun org-activate-bracket-links (limit)
5929 "Run through the buffer and add overlays to bracketed links."
5930 (if (and (re-search-forward org-bracket-link-regexp limit t)
5931 (not (org-in-src-block-p)))
5932 (let* ((hl (org-match-string-no-properties 1))
5933 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5934 (ip (org-maybe-intangible
5935 (list 'invisible 'org-link
5936 'keymap org-mouse-map 'mouse-face 'highlight
5937 'font-lock-multiline t 'help-echo help
5938 'htmlize-link `(:uri ,hl))))
5939 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5940 'font-lock-multiline t 'help-echo help
5941 'htmlize-link `(:uri ,hl))))
5942 ;; We need to remove the invisible property here. Table narrowing
5943 ;; may have made some of this invisible.
5944 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5945 (remove-text-properties (match-beginning 0) (match-end 0)
5946 '(invisible nil))
5947 (if (match-end 3)
5948 (progn
5949 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5950 (org-rear-nonsticky-at (match-beginning 3))
5951 (add-text-properties (match-beginning 3) (match-end 3) vp)
5952 (org-rear-nonsticky-at (match-end 3))
5953 (add-text-properties (match-end 3) (match-end 0) ip)
5954 (org-rear-nonsticky-at (match-end 0)))
5955 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5956 (org-rear-nonsticky-at (match-beginning 1))
5957 (add-text-properties (match-beginning 1) (match-end 1) vp)
5958 (org-rear-nonsticky-at (match-end 1))
5959 (add-text-properties (match-end 1) (match-end 0) ip)
5960 (org-rear-nonsticky-at (match-end 0)))
5961 t)))
5963 (defun org-activate-dates (limit)
5964 "Run through the buffer and add overlays to dates."
5965 (if (and (re-search-forward org-tsr-regexp-both limit t)
5966 (not (equal (char-before (match-beginning 0)) 91)))
5967 (progn
5968 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5969 (add-text-properties (match-beginning 0) (match-end 0)
5970 (list 'mouse-face 'highlight
5971 'keymap org-mouse-map))
5972 (org-rear-nonsticky-at (match-end 0))
5973 (when org-display-custom-times
5974 (if (match-end 3)
5975 (org-display-custom-time (match-beginning 3) (match-end 3)))
5976 (org-display-custom-time (match-beginning 1) (match-end 1)))
5977 t)))
5979 (defvar org-target-link-regexp nil
5980 "Regular expression matching radio targets in plain text.")
5981 (make-variable-buffer-local 'org-target-link-regexp)
5982 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5983 "Regular expression matching a link target.")
5984 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5985 "Regular expression matching a radio target.")
5986 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5987 "Regular expression matching any target.")
5989 (defun org-activate-target-links (limit)
5990 "Run through the buffer and add overlays to target matches."
5991 (when org-target-link-regexp
5992 (let ((case-fold-search t))
5993 (if (re-search-forward org-target-link-regexp limit t)
5994 (progn
5995 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5996 (add-text-properties (match-beginning 0) (match-end 0)
5997 (list 'mouse-face 'highlight
5998 'keymap org-mouse-map
5999 'help-echo "Radio target link"
6000 'org-linked-text t))
6001 (org-rear-nonsticky-at (match-end 0))
6002 t)))))
6004 (defun org-update-radio-target-regexp ()
6005 "Find all radio targets in this file and update the regular expression."
6006 (interactive)
6007 (when (memq 'radio org-activate-links)
6008 (setq org-target-link-regexp
6009 (org-make-target-link-regexp (org-all-targets 'radio)))
6010 (org-restart-font-lock)))
6012 (defun org-hide-wide-columns (limit)
6013 (let (s e)
6014 (setq s (text-property-any (point) (or limit (point-max))
6015 'org-cwidth t))
6016 (when s
6017 (setq e (next-single-property-change s 'org-cwidth))
6018 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6019 (goto-char e)
6020 t)))
6022 (defvar org-latex-and-related-regexp nil
6023 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6024 (defvar org-match-substring-regexp)
6025 (defvar org-match-substring-with-braces-regexp)
6027 (defun org-compute-latex-and-related-regexp ()
6028 "Compute regular expression for LaTeX, entities and sub/superscript.
6029 Result depends on variable `org-highlight-latex-and-related'."
6030 (org-set-local
6031 'org-latex-and-related-regexp
6032 (let* ((re-sub
6033 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6034 ((eq org-use-sub-superscripts '{})
6035 (list org-match-substring-with-braces-regexp))
6036 (org-use-sub-superscripts (list org-match-substring-regexp))))
6037 (re-latex
6038 (when (memq 'latex org-highlight-latex-and-related)
6039 (let ((matchers (plist-get org-format-latex-options :matchers)))
6040 (delq nil
6041 (mapcar (lambda (x)
6042 (and (member (car x) matchers) (nth 1 x)))
6043 org-latex-regexps)))))
6044 (re-entities
6045 (when (memq 'entities org-highlight-latex-and-related)
6046 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6047 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6049 (defun org-do-latex-and-related (limit)
6050 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6051 LIMIT bounds the search for syntax to highlight. Stop at first
6052 highlighted object, if any. Return t if some highlighting was
6053 done, nil otherwise."
6054 (when (org-string-nw-p org-latex-and-related-regexp)
6055 (catch 'found
6056 (while (re-search-forward org-latex-and-related-regexp limit t)
6057 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6058 'face))
6059 '(org-code org-verbatim underline))
6060 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6061 '(?_ ?^))
6063 0)))
6064 (font-lock-prepend-text-property
6065 (+ offset (match-beginning 0)) (match-end 0)
6066 'face 'org-latex-and-related)
6067 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6068 '(font-lock-multiline t)))
6069 (throw 'found t)))
6070 nil)))
6072 (defun org-restart-font-lock ()
6073 "Restart `font-lock-mode', to force refontification."
6074 (when (and (boundp 'font-lock-mode) font-lock-mode)
6075 (font-lock-mode -1)
6076 (font-lock-mode 1)))
6078 (defun org-all-targets (&optional radio)
6079 "Return a list of all targets in this file.
6080 When optional argument RADIO is non-nil, only find radio
6081 targets."
6082 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6083 (save-excursion
6084 (goto-char (point-min))
6085 (while (re-search-forward re nil t)
6086 ;; Make sure point is really within the object.
6087 (backward-char)
6088 (let ((obj (org-element-context)))
6089 (when (memq (org-element-type obj) '(radio-target target))
6090 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6091 rtn)))
6093 (defun org-make-target-link-regexp (targets)
6094 "Make regular expression matching all strings in TARGETS.
6095 The regular expression finds the targets also if there is a line break
6096 between words."
6097 (and targets
6098 (concat
6099 "\\<\\("
6100 (mapconcat
6101 (lambda (x)
6102 (setq x (regexp-quote x))
6103 (while (string-match " +" x)
6104 (setq x (replace-match "\\s-+" t t x)))
6106 targets
6107 "\\|")
6108 "\\)\\>")))
6110 (defun org-activate-tags (limit)
6111 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6112 (progn
6113 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6114 (add-text-properties (match-beginning 1) (match-end 1)
6115 (list 'mouse-face 'highlight
6116 'keymap org-mouse-map))
6117 (org-rear-nonsticky-at (match-end 1))
6118 t)))
6120 (defun org-outline-level ()
6121 "Compute the outline level of the heading at point.
6122 If this is called at a normal headline, the level is the number of stars.
6123 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6124 (save-excursion
6125 (if (not (condition-case nil
6126 (org-back-to-heading t)
6127 (error nil)))
6129 (looking-at org-outline-regexp)
6130 (1- (- (match-end 0) (match-beginning 0))))))
6132 (defvar org-font-lock-keywords nil)
6134 (defsubst org-re-property (property &optional literal)
6135 "Return a regexp matching a PROPERTY line.
6136 Match group 3 will be set to the value if it exists."
6137 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6138 (if literal property (regexp-quote property))
6139 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6141 (defconst org-property-re
6142 (org-re-property ".*?" 'literal)
6143 "Regular expression matching a property line.
6144 There are four matching groups:
6145 1: :PROPKEY: including the leading and trailing colon,
6146 2: PROPKEY without the leading and trailing colon,
6147 3: PROPVAL without leading or trailing spaces,
6148 4: the indentation of the current line,
6149 5: trailing whitespace.")
6151 (defvar org-font-lock-hook nil
6152 "Functions to be called for special font lock stuff.")
6154 (defvar org-font-lock-set-keywords-hook nil
6155 "Functions that can manipulate `org-font-lock-extra-keywords'.
6156 This is called after `org-font-lock-extra-keywords' is defined, but before
6157 it is installed to be used by font lock. This can be useful if something
6158 needs to be inserted at a specific position in the font-lock sequence.")
6160 (defun org-font-lock-hook (limit)
6161 "Run `org-font-lock-hook' within LIMIT."
6162 (run-hook-with-args 'org-font-lock-hook limit))
6164 (defun org-set-font-lock-defaults ()
6165 "Set font lock defaults for the current buffer."
6166 (let* ((em org-fontify-emphasized-text)
6167 (lk org-activate-links)
6168 (org-font-lock-extra-keywords
6169 (list
6170 ;; Call the hook
6171 '(org-font-lock-hook)
6172 ;; Headlines
6173 `(,(if org-fontify-whole-heading-line
6174 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6175 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6176 (1 (org-get-level-face 1))
6177 (2 (org-get-level-face 2))
6178 (3 (org-get-level-face 3)))
6179 ;; Table lines
6180 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6181 (1 'org-table t))
6182 ;; Table internals
6183 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6184 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6185 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6186 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6187 ;; Drawers
6188 (list org-drawer-regexp '(0 'org-special-keyword t))
6189 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6190 ;; Properties
6191 (list org-property-re
6192 '(1 'org-special-keyword t)
6193 '(3 'org-property-value t))
6194 ;; Links
6195 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6196 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6197 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6198 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6199 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6200 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6201 (if (memq 'footnote lk) '(org-activate-footnote-links))
6202 ;; Targets.
6203 (list org-any-target-regexp '(0 'org-target t))
6204 ;; Diary sexps.
6205 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6206 ;; Macro
6207 '("{{{.+}}}" (0 'org-macro t))
6208 '(org-hide-wide-columns (0 nil append))
6209 ;; TODO keyword
6210 (list (format org-heading-keyword-regexp-format
6211 org-todo-regexp)
6212 '(2 (org-get-todo-face 2) t))
6213 ;; DONE
6214 (if org-fontify-done-headline
6215 (list (format org-heading-keyword-regexp-format
6216 (concat
6217 "\\(?:"
6218 (mapconcat 'regexp-quote org-done-keywords "\\|")
6219 "\\)"))
6220 '(2 'org-headline-done t))
6221 nil)
6222 ;; Priorities
6223 '(org-font-lock-add-priority-faces)
6224 ;; Tags
6225 '(org-font-lock-add-tag-faces)
6226 ;; Tags groups
6227 (if (and org-group-tags org-tag-groups-alist)
6228 (list (concat org-outline-regexp-bol ".+\\(:"
6229 (regexp-opt (mapcar 'car org-tag-groups-alist))
6230 ":\\).*$")
6231 '(1 'org-tag-group prepend)))
6232 ;; Special keywords
6233 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6234 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6235 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6236 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6237 ;; Emphasis
6238 (if em
6239 (if (featurep 'xemacs)
6240 '(org-do-emphasis-faces (0 nil append))
6241 '(org-do-emphasis-faces)))
6242 ;; Checkboxes
6243 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6244 1 'org-checkbox prepend)
6245 (if (cdr (assq 'checkbox org-list-automatic-rules))
6246 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6247 (0 (org-get-checkbox-statistics-face) t)))
6248 ;; Description list items
6249 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6250 1 'org-list-dt prepend)
6251 ;; ARCHIVEd headings
6252 (list (concat
6253 org-outline-regexp-bol
6254 "\\(.*:" org-archive-tag ":.*\\)")
6255 '(1 'org-archived prepend))
6256 ;; Specials
6257 '(org-do-latex-and-related)
6258 '(org-fontify-entities)
6259 '(org-raise-scripts)
6260 ;; Code
6261 '(org-activate-code (1 'org-code t))
6262 ;; COMMENT
6263 (list (format org-heading-keyword-regexp-format
6264 (concat "\\("
6265 org-comment-string "\\|" org-quote-string
6266 "\\)"))
6267 '(2 'org-special-keyword t))
6268 ;; Blocks and meta lines
6269 '(org-fontify-meta-lines-and-blocks))))
6270 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6271 (run-hooks 'org-font-lock-set-keywords-hook)
6272 ;; Now set the full font-lock-keywords
6273 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6274 (org-set-local 'font-lock-defaults
6275 '(org-font-lock-keywords t nil nil backward-paragraph))
6276 (kill-local-variable 'font-lock-keywords) nil))
6278 (defun org-toggle-pretty-entities ()
6279 "Toggle the composition display of entities as UTF8 characters."
6280 (interactive)
6281 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6282 (org-restart-font-lock)
6283 (if org-pretty-entities
6284 (message "Entities are now displayed as UTF8 characters")
6285 (save-restriction
6286 (widen)
6287 (org-decompose-region (point-min) (point-max))
6288 (message "Entities are now displayed as plain text"))))
6290 (defvar org-custom-properties-overlays nil
6291 "List of overlays used for custom properties.")
6292 (make-variable-buffer-local 'org-custom-properties-overlays)
6294 (defun org-toggle-custom-properties-visibility ()
6295 "Display or hide properties in `org-custom-properties'."
6296 (interactive)
6297 (if org-custom-properties-overlays
6298 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6299 (setq org-custom-properties-overlays nil))
6300 (unless (not org-custom-properties)
6301 (save-excursion
6302 (save-restriction
6303 (widen)
6304 (goto-char (point-min))
6305 (while (re-search-forward org-property-re nil t)
6306 (mapc (lambda(p)
6307 (when (equal p (substring (match-string 1) 1 -1))
6308 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6309 (overlay-put o 'invisible t)
6310 (overlay-put o 'org-custom-property t)
6311 (push o org-custom-properties-overlays))))
6312 org-custom-properties)))))))
6314 (defun org-fontify-entities (limit)
6315 "Find an entity to fontify."
6316 (let (ee)
6317 (when org-pretty-entities
6318 (catch 'match
6319 (while (re-search-forward
6320 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6321 limit t)
6322 (if (and (not (org-in-indented-comment-line))
6323 (setq ee (org-entity-get (match-string 1)))
6324 (= (length (nth 6 ee)) 1))
6325 (let*
6326 ((end (if (equal (match-string 2) "{}")
6327 (match-end 2)
6328 (match-end 1))))
6329 (add-text-properties
6330 (match-beginning 0) end
6331 (list 'font-lock-fontified t))
6332 (compose-region (match-beginning 0) end
6333 (nth 6 ee) nil)
6334 (backward-char 1)
6335 (throw 'match t))))
6336 nil))))
6338 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6339 "Fontify string S like in Org-mode."
6340 (with-temp-buffer
6341 (insert s)
6342 (let ((org-odd-levels-only odd-levels))
6343 (org-mode)
6344 (font-lock-fontify-buffer)
6345 (buffer-string))))
6347 (defvar org-m nil)
6348 (defvar org-l nil)
6349 (defvar org-f nil)
6350 (defun org-get-level-face (n)
6351 "Get the right face for match N in font-lock matching of headlines."
6352 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6353 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6354 (if org-cycle-level-faces
6355 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6356 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6357 (cond
6358 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6359 ((eq n 2) org-f)
6360 (t (if org-level-color-stars-only nil org-f))))
6363 (defun org-get-todo-face (kwd)
6364 "Get the right face for a TODO keyword KWD.
6365 If KWD is a number, get the corresponding match group."
6366 (if (numberp kwd) (setq kwd (match-string kwd)))
6367 (or (org-face-from-face-or-color
6368 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6369 (and (member kwd org-done-keywords) 'org-done)
6370 'org-todo))
6372 (defun org-face-from-face-or-color (context inherit face-or-color)
6373 "Create a face list that inherits INHERIT, but sets the foreground color.
6374 When FACE-OR-COLOR is not a string, just return it."
6375 (if (stringp face-or-color)
6376 (list :inherit inherit
6377 (cdr (assoc context org-faces-easy-properties))
6378 face-or-color)
6379 face-or-color))
6381 (defun org-font-lock-add-tag-faces (limit)
6382 "Add the special tag faces."
6383 (when (and org-tag-faces org-tags-special-faces-re)
6384 (while (re-search-forward org-tags-special-faces-re limit t)
6385 (add-text-properties (match-beginning 1) (match-end 1)
6386 (list 'face (org-get-tag-face 1)
6387 'font-lock-fontified t))
6388 (backward-char 1))))
6390 (defun org-font-lock-add-priority-faces (limit)
6391 "Add the special priority faces."
6392 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6393 (when (save-match-data (org-at-heading-p))
6394 (add-text-properties
6395 (match-beginning 0) (match-end 0)
6396 (list 'face (or (org-face-from-face-or-color
6397 'priority 'org-priority
6398 (cdr (assoc (char-after (match-beginning 1))
6399 org-priority-faces)))
6400 'org-priority)
6401 'font-lock-fontified t)))))
6403 (defun org-get-tag-face (kwd)
6404 "Get the right face for a TODO keyword KWD.
6405 If KWD is a number, get the corresponding match group."
6406 (if (numberp kwd) (setq kwd (match-string kwd)))
6407 (or (org-face-from-face-or-color
6408 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6409 'org-tag))
6411 (defun org-unfontify-region (beg end &optional maybe_loudly)
6412 "Remove fontification and activation overlays from links."
6413 (font-lock-default-unfontify-region beg end)
6414 (let* ((buffer-undo-list t)
6415 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6416 (inhibit-modification-hooks t)
6417 deactivate-mark buffer-file-name buffer-file-truename)
6418 (org-decompose-region beg end)
6419 (remove-text-properties beg end
6420 '(mouse-face t keymap t org-linked-text t
6421 invisible t intangible t
6422 org-no-flyspell t org-emphasis t))
6423 (org-remove-font-lock-display-properties beg end)))
6425 (defconst org-script-display '(((raise -0.3) (height 0.7))
6426 ((raise 0.3) (height 0.7))
6427 ((raise -0.5))
6428 ((raise 0.5)))
6429 "Display properties for showing superscripts and subscripts.")
6431 (defun org-remove-font-lock-display-properties (beg end)
6432 "Remove specific display properties that have been added by font lock.
6433 The will remove the raise properties that are used to show superscripts
6434 and subscripts."
6435 (let (next prop)
6436 (while (< beg end)
6437 (setq next (next-single-property-change beg 'display nil end)
6438 prop (get-text-property beg 'display))
6439 (if (member prop org-script-display)
6440 (put-text-property beg next 'display nil))
6441 (setq beg next))))
6443 (defun org-raise-scripts (limit)
6444 "Add raise properties to sub/superscripts."
6445 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6446 (if (re-search-forward
6447 (if (eq org-use-sub-superscripts t)
6448 org-match-substring-regexp
6449 org-match-substring-with-braces-regexp)
6450 limit t)
6451 (let* ((pos (point)) table-p comment-p
6452 (mpos (match-beginning 3))
6453 (emph-p (get-text-property mpos 'org-emphasis))
6454 (link-p (get-text-property mpos 'mouse-face))
6455 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6456 (goto-char (point-at-bol))
6457 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6458 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6459 (goto-char pos)
6460 ;; Handle a_b^c
6461 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6462 (if (or comment-p emph-p link-p keyw-p)
6464 (put-text-property (match-beginning 3) (match-end 0)
6465 'display
6466 (if (equal (char-after (match-beginning 2)) ?^)
6467 (nth (if table-p 3 1) org-script-display)
6468 (nth (if table-p 2 0) org-script-display)))
6469 (add-text-properties (match-beginning 2) (match-end 2)
6470 (list 'invisible t
6471 'org-dwidth t 'org-dwidth-n 1))
6472 (if (and (eq (char-after (match-beginning 3)) ?{)
6473 (eq (char-before (match-end 3)) ?}))
6474 (progn
6475 (add-text-properties
6476 (match-beginning 3) (1+ (match-beginning 3))
6477 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6478 (add-text-properties
6479 (1- (match-end 3)) (match-end 3)
6480 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6481 t)))))
6483 ;;;; Visibility cycling, including org-goto and indirect buffer
6485 ;;; Cycling
6487 (defvar org-cycle-global-status nil)
6488 (make-variable-buffer-local 'org-cycle-global-status)
6489 (put 'org-cycle-global-status 'org-state t)
6490 (defvar org-cycle-subtree-status nil)
6491 (make-variable-buffer-local 'org-cycle-subtree-status)
6492 (put 'org-cycle-subtree-status 'org-state t)
6494 (defvar org-inlinetask-min-level)
6496 ;;;###autoload
6497 (defun org-cycle (&optional arg)
6498 "TAB-action and visibility cycling for Org-mode.
6500 This is the command invoked in Org-mode by the TAB key. Its main purpose
6501 is outline visibility cycling, but it also invokes other actions
6502 in special contexts.
6504 - When this function is called with a prefix argument, rotate the entire
6505 buffer through 3 states (global cycling)
6506 1. OVERVIEW: Show only top-level headlines.
6507 2. CONTENTS: Show all headlines of all levels, but no body text.
6508 3. SHOW ALL: Show everything.
6509 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6510 determined by the variable `org-startup-folded', and by any VISIBILITY
6511 properties in the buffer.
6512 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6513 including any drawers.
6515 - When inside a table, re-align the table and move to the next field.
6517 - When point is at the beginning of a headline, rotate the subtree started
6518 by this line through 3 different states (local cycling)
6519 1. FOLDED: Only the main headline is shown.
6520 2. CHILDREN: The main headline and the direct children are shown.
6521 From this state, you can move to one of the children
6522 and zoom in further.
6523 3. SUBTREE: Show the entire subtree, including body text.
6524 If there is no subtree, switch directly from CHILDREN to FOLDED.
6526 - When point is at the beginning of an empty headline and the variable
6527 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6528 of the headline by demoting and promoting it to likely levels. This
6529 speeds up creation document structure by pressing TAB once or several
6530 times right after creating a new headline.
6532 - When there is a numeric prefix, go up to a heading with level ARG, do
6533 a `show-subtree' and return to the previous cursor position. If ARG
6534 is negative, go up that many levels.
6536 - When point is not at the beginning of a headline, execute the global
6537 binding for TAB, which is re-indenting the line. See the option
6538 `org-cycle-emulate-tab' for details.
6540 - Special case: if point is at the beginning of the buffer and there is
6541 no headline in line 1, this function will act as if called with prefix arg
6542 (C-u TAB, same as S-TAB) also when called without prefix arg.
6543 But only if also the variable `org-cycle-global-at-bob' is t."
6544 (interactive "P")
6545 (org-load-modules-maybe)
6546 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6547 (and org-cycle-level-after-item/entry-creation
6548 (or (org-cycle-level)
6549 (org-cycle-item-indentation))))
6550 (let* (message-log-max ; Don't populate the *Messages* buffer
6551 (limit-level
6552 (or org-cycle-max-level
6553 (and (boundp 'org-inlinetask-min-level)
6554 org-inlinetask-min-level
6555 (1- org-inlinetask-min-level))))
6556 (nstars (and limit-level
6557 (if org-odd-levels-only
6558 (and limit-level (1- (* limit-level 2)))
6559 limit-level)))
6560 (org-outline-regexp
6561 (if (not (derived-mode-p 'org-mode))
6562 outline-regexp
6563 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6564 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6565 (not (looking-at org-outline-regexp))))
6566 (org-cycle-hook
6567 (if bob-special
6568 (delq 'org-optimize-window-after-visibility-change
6569 (copy-sequence org-cycle-hook))
6570 org-cycle-hook))
6571 (pos (point)))
6573 (if (or bob-special (equal arg '(4)))
6574 ;; special case: use global cycling
6575 (setq arg t))
6577 (cond
6579 ((equal arg '(16))
6580 (setq last-command 'dummy)
6581 (org-set-startup-visibility)
6582 (message "Startup visibility, plus VISIBILITY properties"))
6584 ((equal arg '(64))
6585 (show-all)
6586 (message "Entire buffer visible, including drawers"))
6588 ;; Table: enter it or move to the next field.
6589 ((org-at-table-p 'any)
6590 (if (org-at-table.el-p)
6591 (message "Use C-c ' to edit table.el tables")
6592 (if arg (org-table-edit-field t)
6593 (org-table-justify-field-maybe)
6594 (call-interactively 'org-table-next-field))))
6596 ((run-hook-with-args-until-success
6597 'org-tab-after-check-for-table-hook))
6599 ;; Global cycling: delegate to `org-cycle-internal-global'.
6600 ((eq arg t) (org-cycle-internal-global))
6602 ;; Drawers: delegate to `org-flag-drawer'.
6603 ((and org-drawers org-drawer-regexp
6604 (save-excursion
6605 (beginning-of-line 1)
6606 (looking-at org-drawer-regexp)))
6607 (org-flag-drawer ; toggle block visibility
6608 (not (get-char-property (match-end 0) 'invisible))))
6610 ;; Show-subtree, ARG levels up from here.
6611 ((integerp arg)
6612 (save-excursion
6613 (org-back-to-heading)
6614 (outline-up-heading (if (< arg 0) (- arg)
6615 (- (funcall outline-level) arg)))
6616 (org-show-subtree)))
6618 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6619 ((and (featurep 'org-inlinetask)
6620 (org-inlinetask-at-task-p)
6621 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6622 (org-inlinetask-toggle-visibility))
6624 ((org-try-cdlatex-tab))
6626 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6627 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6628 (save-excursion (beginning-of-line 1)
6629 (looking-at org-outline-regexp)))
6630 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6631 (org-cycle-internal-local))
6633 ;; From there: TAB emulation and template completion.
6634 (buffer-read-only (org-back-to-heading))
6636 ((run-hook-with-args-until-success
6637 'org-tab-after-check-for-cycling-hook))
6639 ((org-try-structure-completion))
6641 ((run-hook-with-args-until-success
6642 'org-tab-before-tab-emulation-hook))
6644 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6645 (or (not (bolp))
6646 (not (looking-at org-outline-regexp))))
6647 (call-interactively (global-key-binding "\t")))
6649 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6650 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6651 (or (and (eq org-cycle-emulate-tab 'white)
6652 (= (match-end 0) (point-at-eol)))
6653 (and (eq org-cycle-emulate-tab 'whitestart)
6654 (>= (match-end 0) pos))))
6656 (eq org-cycle-emulate-tab t))
6657 (call-interactively (global-key-binding "\t")))
6659 (t (save-excursion
6660 (org-back-to-heading)
6661 (org-cycle)))))))
6663 (defun org-cycle-internal-global ()
6664 "Do the global cycling action."
6665 ;; Hack to avoid display of messages for .org attachments in Gnus
6666 (let (message-log-max ; Don't populate the *Messages* buffer
6667 (ga (string-match "\\*fontification" (buffer-name))))
6668 (cond
6669 ((and (eq last-command this-command)
6670 (eq org-cycle-global-status 'overview))
6671 ;; We just created the overview - now do table of contents
6672 ;; This can be slow in very large buffers, so indicate action
6673 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6674 (unless ga (message "CONTENTS..."))
6675 (org-content)
6676 (unless ga (message "CONTENTS...done"))
6677 (setq org-cycle-global-status 'contents)
6678 (run-hook-with-args 'org-cycle-hook 'contents))
6680 ((and (eq last-command this-command)
6681 (eq org-cycle-global-status 'contents))
6682 ;; We just showed the table of contents - now show everything
6683 (run-hook-with-args 'org-pre-cycle-hook 'all)
6684 (show-all)
6685 (unless ga (message "SHOW ALL"))
6686 (setq org-cycle-global-status 'all)
6687 (run-hook-with-args 'org-cycle-hook 'all))
6690 ;; Default action: go to overview
6691 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6692 (org-overview)
6693 (unless ga (message "OVERVIEW"))
6694 (setq org-cycle-global-status 'overview)
6695 (run-hook-with-args 'org-cycle-hook 'overview)))))
6697 (defun org-cycle-internal-local ()
6698 "Do the local cycling action."
6699 (let (message-log-max ; Don't populate the *Messages* buffer
6700 (goal-column 0) eoh eol eos has-children children-skipped struct)
6701 ;; First, determine end of headline (EOH), end of subtree or item
6702 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6703 (save-excursion
6704 (if (org-at-item-p)
6705 (progn
6706 (beginning-of-line)
6707 (setq struct (org-list-struct))
6708 (setq eoh (point-at-eol))
6709 (setq eos (org-list-get-item-end-before-blank (point) struct))
6710 (setq has-children (org-list-has-child-p (point) struct)))
6711 (org-back-to-heading)
6712 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6713 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6714 (setq has-children
6715 (or (save-excursion
6716 (let ((level (funcall outline-level)))
6717 (outline-next-heading)
6718 (and (org-at-heading-p t)
6719 (> (funcall outline-level) level))))
6720 (save-excursion
6721 (org-list-search-forward (org-item-beginning-re) eos t)))))
6722 ;; Determine end invisible part of buffer (EOL)
6723 (beginning-of-line 2)
6724 ;; XEmacs doesn't have `next-single-char-property-change'
6725 (if (featurep 'xemacs)
6726 (while (and (not (eobp)) ;; this is like `next-line'
6727 (get-char-property (1- (point)) 'invisible))
6728 (beginning-of-line 2))
6729 (while (and (not (eobp)) ;; this is like `next-line'
6730 (get-char-property (1- (point)) 'invisible))
6731 (goto-char (next-single-char-property-change (point) 'invisible))
6732 (and (eolp) (beginning-of-line 2))))
6733 (setq eol (point)))
6734 ;; Find out what to do next and set `this-command'
6735 (cond
6736 ((= eos eoh)
6737 ;; Nothing is hidden behind this heading
6738 (unless (org-before-first-heading-p)
6739 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6740 (message "EMPTY ENTRY")
6741 (setq org-cycle-subtree-status nil)
6742 (save-excursion
6743 (goto-char eos)
6744 (outline-next-heading)
6745 (if (outline-invisible-p) (org-flag-heading nil))))
6746 ((and (or (>= eol eos)
6747 (not (string-match "\\S-" (buffer-substring eol eos))))
6748 (or has-children
6749 (not (setq children-skipped
6750 org-cycle-skip-children-state-if-no-children))))
6751 ;; Entire subtree is hidden in one line: children view
6752 (unless (org-before-first-heading-p)
6753 (run-hook-with-args 'org-pre-cycle-hook 'children))
6754 (if (org-at-item-p)
6755 (org-list-set-item-visibility (point-at-bol) struct 'children)
6756 (org-show-entry)
6757 (org-with-limited-levels (show-children))
6758 ;; FIXME: This slows down the func way too much.
6759 ;; How keep drawers hidden in subtree anyway?
6760 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6761 ;; (org-cycle-hide-drawers 'subtree))
6763 ;; Fold every list in subtree to top-level items.
6764 (when (eq org-cycle-include-plain-lists 'integrate)
6765 (save-excursion
6766 (org-back-to-heading)
6767 (while (org-list-search-forward (org-item-beginning-re) eos t)
6768 (beginning-of-line 1)
6769 (let* ((struct (org-list-struct))
6770 (prevs (org-list-prevs-alist struct))
6771 (end (org-list-get-bottom-point struct)))
6772 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6773 (org-list-get-all-items (point) struct prevs))
6774 (goto-char (if (< end eos) end eos)))))))
6775 (message "CHILDREN")
6776 (save-excursion
6777 (goto-char eos)
6778 (outline-next-heading)
6779 (if (outline-invisible-p) (org-flag-heading nil)))
6780 (setq org-cycle-subtree-status 'children)
6781 (unless (org-before-first-heading-p)
6782 (run-hook-with-args 'org-cycle-hook 'children)))
6783 ((or children-skipped
6784 (and (eq last-command this-command)
6785 (eq org-cycle-subtree-status 'children)))
6786 ;; We just showed the children, or no children are there,
6787 ;; now show everything.
6788 (unless (org-before-first-heading-p)
6789 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6790 (outline-flag-region eoh eos nil)
6791 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6792 (setq org-cycle-subtree-status 'subtree)
6793 (unless (org-before-first-heading-p)
6794 (run-hook-with-args 'org-cycle-hook 'subtree)))
6796 ;; Default action: hide the subtree.
6797 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6798 (outline-flag-region eoh eos t)
6799 (message "FOLDED")
6800 (setq org-cycle-subtree-status 'folded)
6801 (unless (org-before-first-heading-p)
6802 (run-hook-with-args 'org-cycle-hook 'folded))))))
6804 ;;;###autoload
6805 (defun org-global-cycle (&optional arg)
6806 "Cycle the global visibility. For details see `org-cycle'.
6807 With \\[universal-argument] prefix arg, switch to startup visibility.
6808 With a numeric prefix, show all headlines up to that level."
6809 (interactive "P")
6810 (let ((org-cycle-include-plain-lists
6811 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6812 (cond
6813 ((integerp arg)
6814 (show-all)
6815 (hide-sublevels arg)
6816 (setq org-cycle-global-status 'contents))
6817 ((equal arg '(4))
6818 (org-set-startup-visibility)
6819 (message "Startup visibility, plus VISIBILITY properties."))
6821 (org-cycle '(4))))))
6823 (defun org-set-startup-visibility ()
6824 "Set the visibility required by startup options and properties."
6825 (cond
6826 ((eq org-startup-folded t)
6827 (org-cycle '(4)))
6828 ((eq org-startup-folded 'content)
6829 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6830 (org-cycle '(4)) (org-cycle '(4)))))
6831 (unless (eq org-startup-folded 'showeverything)
6832 (if org-hide-block-startup (org-hide-block-all))
6833 (org-set-visibility-according-to-property 'no-cleanup)
6834 (org-cycle-hide-archived-subtrees 'all)
6835 (org-cycle-hide-drawers 'all)
6836 (org-cycle-show-empty-lines t)))
6838 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6839 "Switch subtree visibilities according to :VISIBILITY: property."
6840 (interactive)
6841 (let (org-show-entry-below state)
6842 (save-excursion
6843 (goto-char (point-min))
6844 (while (re-search-forward
6845 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6846 nil t)
6847 (setq state (match-string 1))
6848 (save-excursion
6849 (org-back-to-heading t)
6850 (hide-subtree)
6851 (org-reveal)
6852 (cond
6853 ((equal state '("fold" "folded"))
6854 (hide-subtree))
6855 ((equal state "children")
6856 (org-show-hidden-entry)
6857 (show-children))
6858 ((equal state "content")
6859 (save-excursion
6860 (save-restriction
6861 (org-narrow-to-subtree)
6862 (org-content))))
6863 ((member state '("all" "showall"))
6864 (show-subtree)))))
6865 (unless no-cleanup
6866 (org-cycle-hide-archived-subtrees 'all)
6867 (org-cycle-hide-drawers 'all)
6868 (org-cycle-show-empty-lines 'all)))))
6870 ;; This function uses outline-regexp instead of the more fundamental
6871 ;; org-outline-regexp so that org-cycle-global works outside of Org
6872 ;; buffers, where outline-regexp is needed.
6873 (defun org-overview ()
6874 "Switch to overview mode, showing only top-level headlines.
6875 Really, this shows all headlines with level equal or greater than the level
6876 of the first headline in the buffer. This is important, because if the
6877 first headline is not level one, then (hide-sublevels 1) gives confusing
6878 results."
6879 (interactive)
6880 (let ((l (org-current-line))
6881 (level (save-excursion
6882 (goto-char (point-min))
6883 (if (re-search-forward (concat "^" outline-regexp) nil t)
6884 (progn
6885 (goto-char (match-beginning 0))
6886 (funcall outline-level))))))
6887 (and level (hide-sublevels level))
6888 (recenter '(4))
6889 (org-goto-line l)))
6891 (defun org-content (&optional arg)
6892 "Show all headlines in the buffer, like a table of contents.
6893 With numerical argument N, show content up to level N."
6894 (interactive "P")
6895 (save-excursion
6896 ;; Visit all headings and show their offspring
6897 (and (integerp arg) (org-overview))
6898 (goto-char (point-max))
6899 (catch 'exit
6900 (while (and (progn (condition-case nil
6901 (outline-previous-visible-heading 1)
6902 (error (goto-char (point-min))))
6904 (looking-at org-outline-regexp))
6905 (if (integerp arg)
6906 (show-children (1- arg))
6907 (show-branches))
6908 (if (bobp) (throw 'exit nil))))))
6911 (defun org-optimize-window-after-visibility-change (state)
6912 "Adjust the window after a change in outline visibility.
6913 This function is the default value of the hook `org-cycle-hook'."
6914 (when (get-buffer-window (current-buffer))
6915 (cond
6916 ((eq state 'content) nil)
6917 ((eq state 'all) nil)
6918 ((eq state 'folded) nil)
6919 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6920 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6922 (defun org-remove-empty-overlays-at (pos)
6923 "Remove outline overlays that do not contain non-white stuff."
6924 (mapc
6925 (lambda (o)
6926 (and (eq 'outline (overlay-get o 'invisible))
6927 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6928 (overlay-end o))))
6929 (delete-overlay o)))
6930 (overlays-at pos)))
6932 (defun org-clean-visibility-after-subtree-move ()
6933 "Fix visibility issues after moving a subtree."
6934 ;; First, find a reasonable region to look at:
6935 ;; Start two siblings above, end three below
6936 (let* ((beg (save-excursion
6937 (and (org-get-last-sibling)
6938 (org-get-last-sibling))
6939 (point)))
6940 (end (save-excursion
6941 (and (org-get-next-sibling)
6942 (org-get-next-sibling)
6943 (org-get-next-sibling))
6944 (if (org-at-heading-p)
6945 (point-at-eol)
6946 (point))))
6947 (level (looking-at "\\*+"))
6948 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6949 (save-excursion
6950 (save-restriction
6951 (narrow-to-region beg end)
6952 (when re
6953 ;; Properly fold already folded siblings
6954 (goto-char (point-min))
6955 (while (re-search-forward re nil t)
6956 (if (and (not (outline-invisible-p))
6957 (save-excursion
6958 (goto-char (point-at-eol)) (outline-invisible-p)))
6959 (hide-entry))))
6960 (org-cycle-show-empty-lines 'overview)
6961 (org-cycle-hide-drawers 'overview)))))
6963 (defun org-cycle-show-empty-lines (state)
6964 "Show empty lines above all visible headlines.
6965 The region to be covered depends on STATE when called through
6966 `org-cycle-hook'. Lisp program can use t for STATE to get the
6967 entire buffer covered. Note that an empty line is only shown if there
6968 are at least `org-cycle-separator-lines' empty lines before the headline."
6969 (when (not (= org-cycle-separator-lines 0))
6970 (save-excursion
6971 (let* ((n (abs org-cycle-separator-lines))
6972 (re (cond
6973 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6974 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6975 (t (let ((ns (number-to-string (- n 2))))
6976 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6977 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6978 beg end b e)
6979 (cond
6980 ((memq state '(overview contents t))
6981 (setq beg (point-min) end (point-max)))
6982 ((memq state '(children folded))
6983 (setq beg (point) end (progn (org-end-of-subtree t t)
6984 (beginning-of-line 2)
6985 (point)))))
6986 (when beg
6987 (goto-char beg)
6988 (while (re-search-forward re end t)
6989 (unless (get-char-property (match-end 1) 'invisible)
6990 (setq e (match-end 1))
6991 (if (< org-cycle-separator-lines 0)
6992 (setq b (save-excursion
6993 (goto-char (match-beginning 0))
6994 (org-back-over-empty-lines)
6995 (if (save-excursion
6996 (goto-char (max (point-min) (1- (point))))
6997 (org-at-heading-p))
6998 (1- (point))
6999 (point))))
7000 (setq b (match-beginning 1)))
7001 (outline-flag-region b e nil)))))))
7002 ;; Never hide empty lines at the end of the file.
7003 (save-excursion
7004 (goto-char (point-max))
7005 (outline-previous-heading)
7006 (outline-end-of-heading)
7007 (if (and (looking-at "[ \t\n]+")
7008 (= (match-end 0) (point-max)))
7009 (outline-flag-region (point) (match-end 0) nil))))
7011 (defun org-show-empty-lines-in-parent ()
7012 "Move to the parent and re-show empty lines before visible headlines."
7013 (save-excursion
7014 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7015 (org-cycle-show-empty-lines context))))
7017 (defun org-files-list ()
7018 "Return `org-agenda-files' list, plus all open org-mode files.
7019 This is useful for operations that need to scan all of a user's
7020 open and agenda-wise Org files."
7021 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7022 (dolist (buf (buffer-list))
7023 (with-current-buffer buf
7024 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7025 (let ((file (expand-file-name (buffer-file-name))))
7026 (unless (member file files)
7027 (push file files))))))
7028 files))
7030 (defsubst org-entry-beginning-position ()
7031 "Return the beginning position of the current entry."
7032 (save-excursion (outline-back-to-heading t) (point)))
7034 (defsubst org-entry-end-position ()
7035 "Return the end position of the current entry."
7036 (save-excursion (outline-next-heading) (point)))
7038 (defun org-cycle-hide-drawers (state)
7039 "Re-hide all drawers after a visibility state change."
7040 (when (and (derived-mode-p 'org-mode)
7041 (not (memq state '(overview folded contents))))
7042 (save-excursion
7043 (let* ((globalp (memq state '(contents all)))
7044 (beg (if globalp (point-min) (point)))
7045 (end (if globalp (point-max)
7046 (if (eq state 'children)
7047 (save-excursion (outline-next-heading) (point))
7048 (org-end-of-subtree t)))))
7049 (goto-char beg)
7050 (while (re-search-forward org-drawer-regexp end t)
7051 (org-flag-drawer t))))))
7053 (defun org-cycle-hide-inline-tasks (state)
7054 "Re-hide inline task when switching to 'contents visibility state."
7055 (when (and (eq state 'contents)
7056 (boundp 'org-inlinetask-min-level)
7057 org-inlinetask-min-level)
7058 (hide-sublevels (1- org-inlinetask-min-level))))
7060 (defun org-flag-drawer (flag)
7061 "When FLAG is non-nil, hide the drawer we are within.
7062 Otherwise make it visible."
7063 (save-excursion
7064 (beginning-of-line 1)
7065 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7066 (let ((b (match-end 0)))
7067 (if (re-search-forward
7068 "^[ \t]*:END:"
7069 (save-excursion (outline-next-heading) (point)) t)
7070 (outline-flag-region b (point-at-eol) flag)
7071 (user-error ":END: line missing at position %s" b))))))
7073 (defun org-subtree-end-visible-p ()
7074 "Is the end of the current subtree visible?"
7075 (pos-visible-in-window-p
7076 (save-excursion (org-end-of-subtree t) (point))))
7078 (defun org-first-headline-recenter (&optional N)
7079 "Move cursor to the first headline and recenter the headline.
7080 Optional argument N means put the headline into the Nth line of the window."
7081 (goto-char (point-min))
7082 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7083 (beginning-of-line)
7084 (recenter (prefix-numeric-value N))))
7086 ;;; Saving and restoring visibility
7088 (defun org-outline-overlay-data (&optional use-markers)
7089 "Return a list of the locations of all outline overlays.
7090 These are overlays with the `invisible' property value `outline'.
7091 The return value is a list of cons cells, with start and stop
7092 positions for each overlay.
7093 If USE-MARKERS is set, return the positions as markers."
7094 (let (beg end)
7095 (save-excursion
7096 (save-restriction
7097 (widen)
7098 (delq nil
7099 (mapcar (lambda (o)
7100 (when (eq (overlay-get o 'invisible) 'outline)
7101 (setq beg (overlay-start o)
7102 end (overlay-end o))
7103 (and beg end (> end beg)
7104 (if use-markers
7105 (cons (move-marker (make-marker) beg)
7106 (move-marker (make-marker) end))
7107 (cons beg end)))))
7108 (overlays-in (point-min) (point-max))))))))
7110 (defun org-set-outline-overlay-data (data)
7111 "Create visibility overlays for all positions in DATA.
7112 DATA should have been made by `org-outline-overlay-data'."
7113 (let (o)
7114 (save-excursion
7115 (save-restriction
7116 (widen)
7117 (show-all)
7118 (mapc (lambda (c)
7119 (outline-flag-region (car c) (cdr c) t))
7120 data)))))
7122 ;;; Folding of blocks
7124 (defvar org-hide-block-overlays nil
7125 "Overlays hiding blocks.")
7126 (make-variable-buffer-local 'org-hide-block-overlays)
7128 (defun org-block-map (function &optional start end)
7129 "Call FUNCTION at the head of all source blocks in the current buffer.
7130 Optional arguments START and END can be used to limit the range."
7131 (let ((start (or start (point-min)))
7132 (end (or end (point-max))))
7133 (save-excursion
7134 (goto-char start)
7135 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7136 (save-excursion
7137 (save-match-data
7138 (goto-char (match-beginning 0))
7139 (funcall function)))))))
7141 (defun org-hide-block-toggle-all ()
7142 "Toggle the visibility of all blocks in the current buffer."
7143 (org-block-map #'org-hide-block-toggle))
7145 (defun org-hide-block-all ()
7146 "Fold all blocks in the current buffer."
7147 (interactive)
7148 (org-show-block-all)
7149 (org-block-map #'org-hide-block-toggle-maybe))
7151 (defun org-show-block-all ()
7152 "Unfold all blocks in the current buffer."
7153 (interactive)
7154 (mapc 'delete-overlay org-hide-block-overlays)
7155 (setq org-hide-block-overlays nil))
7157 (defun org-hide-block-toggle-maybe ()
7158 "Toggle visibility of block at point."
7159 (interactive)
7160 (let ((case-fold-search t))
7161 (if (save-excursion
7162 (beginning-of-line 1)
7163 (looking-at org-block-regexp))
7164 (progn (org-hide-block-toggle)
7165 t) ;; to signal that we took action
7166 nil))) ;; to signal that we did not
7168 (defun org-hide-block-toggle (&optional force)
7169 "Toggle the visibility of the current block."
7170 (interactive)
7171 (save-excursion
7172 (beginning-of-line)
7173 (if (re-search-forward org-block-regexp nil t)
7174 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7175 (end (match-end 0)) ;; end of entire body
7177 (if (memq t (mapcar (lambda (overlay)
7178 (eq (overlay-get overlay 'invisible)
7179 'org-hide-block))
7180 (overlays-at start)))
7181 (if (or (not force) (eq force 'off))
7182 (mapc (lambda (ov)
7183 (when (member ov org-hide-block-overlays)
7184 (setq org-hide-block-overlays
7185 (delq ov org-hide-block-overlays)))
7186 (when (eq (overlay-get ov 'invisible)
7187 'org-hide-block)
7188 (delete-overlay ov)))
7189 (overlays-at start)))
7190 (setq ov (make-overlay start end))
7191 (overlay-put ov 'invisible 'org-hide-block)
7192 ;; make the block accessible to isearch
7193 (overlay-put
7194 ov 'isearch-open-invisible
7195 (lambda (ov)
7196 (when (member ov org-hide-block-overlays)
7197 (setq org-hide-block-overlays
7198 (delq ov org-hide-block-overlays)))
7199 (when (eq (overlay-get ov 'invisible)
7200 'org-hide-block)
7201 (delete-overlay ov))))
7202 (push ov org-hide-block-overlays)))
7203 (user-error "Not looking at a source block"))))
7205 ;; org-tab-after-check-for-cycling-hook
7206 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7207 ;; Remove overlays when changing major mode
7208 (add-hook 'org-mode-hook
7209 (lambda () (org-add-hook 'change-major-mode-hook
7210 'org-show-block-all 'append 'local)))
7212 ;;; Org-goto
7214 (defvar org-goto-window-configuration nil)
7215 (defvar org-goto-marker nil)
7216 (defvar org-goto-map)
7217 (defun org-goto-map ()
7218 "Set the keymap `org-goto'."
7219 (setq org-goto-map
7220 (let ((map (make-sparse-keymap)))
7221 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7222 mouse-drag-region universal-argument org-occur))
7223 cmd)
7224 (while (setq cmd (pop cmds))
7225 (substitute-key-definition cmd cmd map global-map)))
7226 (suppress-keymap map)
7227 (org-defkey map "\C-m" 'org-goto-ret)
7228 (org-defkey map [(return)] 'org-goto-ret)
7229 (org-defkey map [(left)] 'org-goto-left)
7230 (org-defkey map [(right)] 'org-goto-right)
7231 (org-defkey map [(control ?g)] 'org-goto-quit)
7232 (org-defkey map "\C-i" 'org-cycle)
7233 (org-defkey map [(tab)] 'org-cycle)
7234 (org-defkey map [(down)] 'outline-next-visible-heading)
7235 (org-defkey map [(up)] 'outline-previous-visible-heading)
7236 (if org-goto-auto-isearch
7237 (if (fboundp 'define-key-after)
7238 (define-key-after map [t] 'org-goto-local-auto-isearch)
7239 nil)
7240 (org-defkey map "q" 'org-goto-quit)
7241 (org-defkey map "n" 'outline-next-visible-heading)
7242 (org-defkey map "p" 'outline-previous-visible-heading)
7243 (org-defkey map "f" 'outline-forward-same-level)
7244 (org-defkey map "b" 'outline-backward-same-level)
7245 (org-defkey map "u" 'outline-up-heading))
7246 (org-defkey map "/" 'org-occur)
7247 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7248 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7249 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7250 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7251 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7252 map)))
7254 (defconst org-goto-help
7255 "Browse buffer copy, to find location or copy text.%s
7256 RET=jump to location C-g=quit and return to previous location
7257 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7259 (defvar org-goto-start-pos) ; dynamically scoped parameter
7261 (defun org-goto (&optional alternative-interface)
7262 "Look up a different location in the current file, keeping current visibility.
7264 When you want look-up or go to a different location in a
7265 document, the fastest way is often to fold the entire buffer and
7266 then dive into the tree. This method has the disadvantage, that
7267 the previous location will be folded, which may not be what you
7268 want.
7270 This command works around this by showing a copy of the current
7271 buffer in an indirect buffer, in overview mode. You can dive
7272 into the tree in that copy, use org-occur and incremental search
7273 to find a location. When pressing RET or `Q', the command
7274 returns to the original buffer in which the visibility is still
7275 unchanged. After RET it will also jump to the location selected
7276 in the indirect buffer and expose the headline hierarchy above.
7278 With a prefix argument, use the alternative interface: e.g. if
7279 `org-goto-interface' is 'outline use 'outline-path-completion."
7280 (interactive "P")
7281 (org-goto-map)
7282 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7283 (org-refile-use-outline-path t)
7284 (org-refile-target-verify-function nil)
7285 (interface
7286 (if (not alternative-interface)
7287 org-goto-interface
7288 (if (eq org-goto-interface 'outline)
7289 'outline-path-completion
7290 'outline)))
7291 (org-goto-start-pos (point))
7292 (selected-point
7293 (if (eq interface 'outline)
7294 (car (org-get-location (current-buffer) org-goto-help))
7295 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7296 (org-refile-check-position pa)
7297 (nth 3 pa)))))
7298 (if selected-point
7299 (progn
7300 (org-mark-ring-push org-goto-start-pos)
7301 (goto-char selected-point)
7302 (if (or (outline-invisible-p) (org-invisible-p2))
7303 (org-show-context 'org-goto)))
7304 (message "Quit"))))
7306 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7307 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7308 (defvar org-goto-local-auto-isearch-map) ; defined below
7310 (defun org-get-location (buf help)
7311 "Let the user select a location in the Org-mode buffer BUF.
7312 This function uses a recursive edit. It returns the selected position
7313 or nil."
7314 (org-no-popups
7315 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7316 (isearch-hide-immediately nil)
7317 (isearch-search-fun-function
7318 (lambda () 'org-goto-local-search-headings))
7319 (org-goto-selected-point org-goto-exit-command))
7320 (save-excursion
7321 (save-window-excursion
7322 (delete-other-windows)
7323 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7324 (org-pop-to-buffer-same-window
7325 (condition-case nil
7326 (make-indirect-buffer (current-buffer) "*org-goto*")
7327 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7328 (with-output-to-temp-buffer "*Org Help*"
7329 (princ (format help (if org-goto-auto-isearch
7330 " Just type for auto-isearch."
7331 " n/p/f/b/u to navigate, q to quit."))))
7332 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7333 (setq buffer-read-only nil)
7334 (let ((org-startup-truncated t)
7335 (org-startup-folded nil)
7336 (org-startup-align-all-tables nil))
7337 (org-mode)
7338 (org-overview))
7339 (setq buffer-read-only t)
7340 (if (and (boundp 'org-goto-start-pos)
7341 (integer-or-marker-p org-goto-start-pos))
7342 (let ((org-show-hierarchy-above t)
7343 (org-show-siblings t)
7344 (org-show-following-heading t))
7345 (goto-char org-goto-start-pos)
7346 (and (outline-invisible-p) (org-show-context)))
7347 (goto-char (point-min)))
7348 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7349 (message "Select location and press RET")
7350 (use-local-map org-goto-map)
7351 (recursive-edit)))
7352 (kill-buffer "*org-goto*")
7353 (cons org-goto-selected-point org-goto-exit-command))))
7355 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7356 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7357 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7358 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7360 (defun org-goto-local-search-headings (string bound noerror)
7361 "Search and make sure that any matches are in headlines."
7362 (catch 'return
7363 (while (if isearch-forward
7364 (search-forward string bound noerror)
7365 (search-backward string bound noerror))
7366 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7367 (and (member :headline context)
7368 (not (member :tags context))))
7369 (throw 'return (point))))))
7371 (defun org-goto-local-auto-isearch ()
7372 "Start isearch."
7373 (interactive)
7374 (goto-char (point-min))
7375 (let ((keys (this-command-keys)))
7376 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7377 (isearch-mode t)
7378 (isearch-process-search-char (string-to-char keys)))))
7380 (defun org-goto-ret (&optional arg)
7381 "Finish `org-goto' by going to the new location."
7382 (interactive "P")
7383 (setq org-goto-selected-point (point)
7384 org-goto-exit-command 'return)
7385 (throw 'exit nil))
7387 (defun org-goto-left ()
7388 "Finish `org-goto' by going to the new location."
7389 (interactive)
7390 (if (org-at-heading-p)
7391 (progn
7392 (beginning-of-line 1)
7393 (setq org-goto-selected-point (point)
7394 org-goto-exit-command 'left)
7395 (throw 'exit nil))
7396 (user-error "Not on a heading")))
7398 (defun org-goto-right ()
7399 "Finish `org-goto' by going to the new location."
7400 (interactive)
7401 (if (org-at-heading-p)
7402 (progn
7403 (setq org-goto-selected-point (point)
7404 org-goto-exit-command 'right)
7405 (throw 'exit nil))
7406 (user-error "Not on a heading")))
7408 (defun org-goto-quit ()
7409 "Finish `org-goto' without cursor motion."
7410 (interactive)
7411 (setq org-goto-selected-point nil)
7412 (setq org-goto-exit-command 'quit)
7413 (throw 'exit nil))
7415 ;;; Indirect buffer display of subtrees
7417 (defvar org-indirect-dedicated-frame nil
7418 "This is the frame being used for indirect tree display.")
7419 (defvar org-last-indirect-buffer nil)
7421 (defun org-tree-to-indirect-buffer (&optional arg)
7422 "Create indirect buffer and narrow it to current subtree.
7423 With a numerical prefix ARG, go up to this level and then take that tree.
7424 If ARG is negative, go up that many levels.
7426 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7427 indirect buffer previously made with this command, to avoid proliferation of
7428 indirect buffers. However, when you call the command with a \
7429 \\[universal-argument] prefix, or
7430 when `org-indirect-buffer-display' is `new-frame', the last buffer
7431 is kept so that you can work with several indirect buffers at the same time.
7432 If `org-indirect-buffer-display' is `dedicated-frame', the \
7433 \\[universal-argument] prefix also
7434 requests that a new frame be made for the new buffer, so that the dedicated
7435 frame is not changed."
7436 (interactive "P")
7437 (let ((cbuf (current-buffer))
7438 (cwin (selected-window))
7439 (pos (point))
7440 beg end level heading ibuf)
7441 (save-excursion
7442 (org-back-to-heading t)
7443 (when (numberp arg)
7444 (setq level (org-outline-level))
7445 (if (< arg 0) (setq arg (+ level arg)))
7446 (while (> (setq level (org-outline-level)) arg)
7447 (org-up-heading-safe)))
7448 (setq beg (point)
7449 heading (org-get-heading))
7450 (org-end-of-subtree t t)
7451 (if (org-at-heading-p) (backward-char 1))
7452 (setq end (point)))
7453 (if (and (buffer-live-p org-last-indirect-buffer)
7454 (not (eq org-indirect-buffer-display 'new-frame))
7455 (not arg))
7456 (kill-buffer org-last-indirect-buffer))
7457 (setq ibuf (org-get-indirect-buffer cbuf)
7458 org-last-indirect-buffer ibuf)
7459 (cond
7460 ((or (eq org-indirect-buffer-display 'new-frame)
7461 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7462 (select-frame (make-frame))
7463 (delete-other-windows)
7464 (org-pop-to-buffer-same-window ibuf)
7465 (org-set-frame-title heading))
7466 ((eq org-indirect-buffer-display 'dedicated-frame)
7467 (raise-frame
7468 (select-frame (or (and org-indirect-dedicated-frame
7469 (frame-live-p org-indirect-dedicated-frame)
7470 org-indirect-dedicated-frame)
7471 (setq org-indirect-dedicated-frame (make-frame)))))
7472 (delete-other-windows)
7473 (org-pop-to-buffer-same-window ibuf)
7474 (org-set-frame-title (concat "Indirect: " heading)))
7475 ((eq org-indirect-buffer-display 'current-window)
7476 (org-pop-to-buffer-same-window ibuf))
7477 ((eq org-indirect-buffer-display 'other-window)
7478 (pop-to-buffer ibuf))
7479 (t (error "Invalid value")))
7480 (if (featurep 'xemacs)
7481 (save-excursion (org-mode) (turn-on-font-lock)))
7482 (narrow-to-region beg end)
7483 (show-all)
7484 (goto-char pos)
7485 (run-hook-with-args 'org-cycle-hook 'all)
7486 (and (window-live-p cwin) (select-window cwin))))
7488 (defun org-get-indirect-buffer (&optional buffer)
7489 (setq buffer (or buffer (current-buffer)))
7490 (let ((n 1) (base (buffer-name buffer)) bname)
7491 (while (buffer-live-p
7492 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7493 (setq n (1+ n)))
7494 (condition-case nil
7495 (make-indirect-buffer buffer bname 'clone)
7496 (error (make-indirect-buffer buffer bname)))))
7498 (defun org-set-frame-title (title)
7499 "Set the title of the current frame to the string TITLE."
7500 ;; FIXME: how to name a single frame in XEmacs???
7501 (unless (featurep 'xemacs)
7502 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7504 ;;;; Structure editing
7506 ;;; Inserting headlines
7508 (defun org-previous-line-empty-p (&optional next)
7509 "Is the previous line a blank line?
7510 When NEXT is non-nil, check the next line instead."
7511 (save-excursion
7512 (and (not (bobp))
7513 (or (beginning-of-line (if next 2 0)) t)
7514 (save-match-data
7515 (looking-at "[ \t]*$")))))
7517 (defun org-insert-heading (&optional arg invisible-ok)
7518 "Insert a new heading or item with same depth at point.
7519 If point is in a plain list and ARG is nil, create a new list item.
7520 With one universal prefix argument, insert a heading even in lists.
7521 With two universal prefix arguments, insert the heading at the end
7522 of the parent subtree.
7524 If point is at the beginning of a headline, insert a sibling before
7525 the current headline. If point is not at the beginning, split the line
7526 and create a new headline with the text in the current line after point
7527 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7529 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7530 This is important for non-interactive uses of the command."
7531 (interactive "P")
7532 (if (org-called-interactively-p 'any) (org-reveal))
7533 (let ((itemp (org-in-item-p)))
7534 (cond
7535 ((or (= (buffer-size) 0)
7536 (and (not (save-excursion
7537 (and (ignore-errors (org-back-to-heading invisible-ok))
7538 (org-at-heading-p))))
7539 (or arg (not itemp))))
7540 (insert
7541 (if (org-previous-line-empty-p) "" "\n")
7542 (if (org-in-src-block-p) ",* " "* "))
7543 (run-hooks 'org-insert-heading-hook))
7544 ((or arg
7545 (and (not itemp) org-insert-heading-respect-content)
7546 (not (org-insert-item
7547 (save-excursion
7548 (and itemp
7549 (goto-char itemp)
7550 (looking-at org-list-full-item-re)
7551 (match-string 3))))))
7552 (let (begn endn)
7553 (when (org-buffer-narrowed-p)
7554 (setq begn (point-min) endn (point-max))
7555 (widen))
7556 (let* ((empty-line-p nil)
7557 (eops (equal arg '(16))) ; insert at end of parent subtree
7558 (org-insert-heading-respect-content
7559 (or (not (null arg)) org-insert-heading-respect-content))
7560 (level nil)
7561 (on-heading (org-at-heading-p))
7562 ;; Get a level to fall back on
7563 (fix-level
7564 (save-excursion
7565 (org-back-to-heading t)
7566 (looking-at org-outline-regexp)
7567 (make-string (1- (length (match-string 0))) ?*)))
7568 (on-empty-line
7569 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7570 (head (save-excursion
7571 (condition-case nil
7572 (progn
7573 (org-back-to-heading invisible-ok)
7574 (when (and (not on-heading)
7575 (featurep 'org-inlinetask)
7576 (integerp org-inlinetask-min-level)
7577 (>= (length (match-string 0))
7578 org-inlinetask-min-level))
7579 ;; Find a heading level before the inline task
7580 (while (and (setq level (org-up-heading-safe))
7581 (>= level org-inlinetask-min-level)))
7582 (if (org-at-heading-p)
7583 (org-back-to-heading invisible-ok)
7584 (error "This should not happen")))
7585 (unless (and (save-excursion
7586 (save-match-data
7587 (org-backward-heading-same-level 1 invisible-ok))
7588 (= (point) (match-beginning 0)))
7589 (not (org-previous-line-empty-p t)))
7590 (setq empty-line-p (org-previous-line-empty-p)))
7591 (match-string 0))
7592 (error (or fix-level "* ")))))
7593 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7594 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7595 pos hide-previous previous-pos)
7596 (if ;; At the beginning of a heading, open a new line for insertion
7597 (and (bolp) (org-at-heading-p)
7598 (not eops)
7599 (or (bobp)
7600 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7601 (open-line (if blank 2 1))
7602 (save-excursion
7603 (setq previous-pos (point-at-bol))
7604 (end-of-line)
7605 (setq hide-previous (outline-invisible-p)))
7606 (and org-insert-heading-respect-content
7607 (save-excursion
7608 (while (outline-invisible-p)
7609 (org-show-subtree)
7610 (org-up-heading-safe))))
7611 (let ((split
7612 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7613 (save-excursion
7614 (let ((p (point)))
7615 (goto-char (point-at-bol))
7616 (and (looking-at org-complex-heading-regexp)
7617 (match-beginning 4)
7618 (> p (match-beginning 4)))))))
7619 tags pos)
7620 (cond
7621 ;; Insert a new line, possibly at end of parent subtree
7622 ((and (not arg) (not on-heading) (not on-empty-line)
7623 (not (save-excursion
7624 (beginning-of-line 1)
7625 (or (looking-at org-list-full-item-re)
7626 ;; Don't convert :end: lines to headline
7627 (looking-at "^\\s-*:end:")
7628 (looking-at "^\\s-*#\\+end_?")))))
7629 (beginning-of-line 1))
7630 (org-insert-heading-respect-content
7631 (if (not eops)
7632 (progn
7633 (org-end-of-subtree nil t)
7634 (and (looking-at "^\\*") (backward-char 1))
7635 (while (and (not (bobp))
7636 ;; Don't delete spaces in empty headlines
7637 (not (looking-back org-outline-regexp))
7638 (member (char-before) '(?\ ?\t ?\n)))
7639 (backward-delete-char 1)))
7640 (let ((p (point)))
7641 (org-up-heading-safe)
7642 (if (= p (point))
7643 (goto-char (point-max))
7644 (org-end-of-subtree nil t))))
7645 (when (featurep 'org-inlinetask)
7646 (while (and (not (eobp))
7647 (looking-at "\\(\\*+\\)[ \t]+")
7648 (>= (length (match-string 1))
7649 org-inlinetask-min-level))
7650 (org-end-of-subtree nil t)))
7651 (or (bolp) (newline))
7652 (or (org-previous-line-empty-p)
7653 (and blank (newline)))
7654 (if (or empty-line-p eops) (open-line 1)))
7655 ;; Insert a headling containing text after point
7656 ((org-at-heading-p)
7657 (when hide-previous
7658 (show-children)
7659 (org-show-entry))
7660 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7661 (setq tags (and (match-end 2) (match-string 2)))
7662 (and (match-end 1)
7663 (delete-region (match-beginning 1) (match-end 1)))
7664 (setq pos (point-at-bol))
7665 (or split (end-of-line 1))
7666 (delete-horizontal-space)
7667 (if (string-match "\\`\\*+\\'"
7668 (buffer-substring (point-at-bol) (point)))
7669 (insert " "))
7670 (newline (if blank 2 1))
7671 (when tags
7672 (save-excursion
7673 (goto-char pos)
7674 (end-of-line 1)
7675 (insert " " tags)
7676 (org-set-tags nil 'align))))
7678 (or split (end-of-line 1))
7679 (newline (cond ((and blank (not on-empty-line)) 2)
7680 (blank 1)
7681 (on-empty-line 0) (t 1)))))))
7682 (insert head) (just-one-space)
7683 (setq pos (point))
7684 (end-of-line 1)
7685 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7686 (when (and org-insert-heading-respect-content hide-previous)
7687 (save-excursion
7688 (goto-char previous-pos)
7689 (hide-subtree)))
7690 (when (and begn endn)
7691 (narrow-to-region (min (point) begn) (max (point) endn)))
7692 (run-hooks 'org-insert-heading-hook)))))))
7694 (defun org-get-heading (&optional no-tags no-todo)
7695 "Return the heading of the current entry, without the stars.
7696 When NO-TAGS is non-nil, don't include tags.
7697 When NO-TODO is non-nil, don't include TODO keywords."
7698 (save-excursion
7699 (org-back-to-heading t)
7700 (cond
7701 ((and no-tags no-todo)
7702 (looking-at org-complex-heading-regexp)
7703 (match-string 4))
7704 (no-tags
7705 (looking-at (concat org-outline-regexp
7706 "\\(.*?\\)"
7707 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7708 (match-string 1))
7709 (no-todo
7710 (looking-at org-todo-line-regexp)
7711 (match-string 3))
7712 (t (looking-at org-heading-regexp)
7713 (match-string 2)))))
7715 (defvar orgstruct-mode) ; defined below
7717 (defun org-heading-components ()
7718 "Return the components of the current heading.
7719 This is a list with the following elements:
7720 - the level as an integer
7721 - the reduced level, different if `org-odd-levels-only' is set.
7722 - the TODO keyword, or nil
7723 - the priority character, like ?A, or nil if no priority is given
7724 - the headline text itself, or the tags string if no headline text
7725 - the tags string, or nil."
7726 (save-excursion
7727 (org-back-to-heading t)
7728 (if (let (case-fold-search)
7729 (looking-at
7730 (if orgstruct-mode
7731 org-heading-regexp
7732 org-complex-heading-regexp)))
7733 (if orgstruct-mode
7734 (list (length (match-string 1))
7735 (org-reduced-level (length (match-string 1)))
7738 (match-string 2)
7739 nil)
7740 (list (length (match-string 1))
7741 (org-reduced-level (length (match-string 1)))
7742 (org-match-string-no-properties 2)
7743 (and (match-end 3) (aref (match-string 3) 2))
7744 (org-match-string-no-properties 4)
7745 (org-match-string-no-properties 5))))))
7747 (defun org-get-entry ()
7748 "Get the entry text, after heading, entire subtree."
7749 (save-excursion
7750 (org-back-to-heading t)
7751 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7753 (defun org-insert-heading-after-current ()
7754 "Insert a new heading with same level as current, after current subtree."
7755 (interactive)
7756 (org-back-to-heading)
7757 (org-insert-heading)
7758 (org-move-subtree-down)
7759 (end-of-line 1))
7761 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7762 "Insert heading with `org-insert-heading-respect-content' set to t."
7763 (interactive "P")
7764 (let ((org-insert-heading-respect-content t))
7765 (org-insert-heading arg invisible-ok)))
7767 (defun org-insert-todo-heading-respect-content (&optional force-state)
7768 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7769 (interactive "P")
7770 (let ((org-insert-heading-respect-content t))
7771 (org-insert-todo-heading force-state t)))
7773 (defun org-insert-todo-heading (arg &optional force-heading)
7774 "Insert a new heading with the same level and TODO state as current heading.
7775 If the heading has no TODO state, or if the state is DONE, use the first
7776 state (TODO by default). Also one prefix arg, force first state. With two
7777 prefix args, force inserting at the end of the parent subtree."
7778 (interactive "P")
7779 (when (or force-heading (not (org-insert-item 'checkbox)))
7780 (org-insert-heading (or (and (equal arg '(16)) '(16))
7781 force-heading))
7782 (save-excursion
7783 (org-back-to-heading)
7784 (outline-previous-heading)
7785 (looking-at org-todo-line-regexp))
7786 (let*
7787 ((new-mark-x
7788 (if (or arg
7789 (not (match-beginning 2))
7790 (member (match-string 2) org-done-keywords))
7791 (car org-todo-keywords-1)
7792 (match-string 2)))
7793 (new-mark
7795 (run-hook-with-args-until-success
7796 'org-todo-get-default-hook new-mark-x nil)
7797 new-mark-x)))
7798 (beginning-of-line 1)
7799 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7800 (if org-treat-insert-todo-heading-as-state-change
7801 (org-todo new-mark)
7802 (insert new-mark " "))))
7803 (when org-provide-todo-statistics
7804 (org-update-parent-todo-statistics))))
7806 (defun org-insert-subheading (arg)
7807 "Insert a new subheading and demote it.
7808 Works for outline headings and for plain lists alike."
7809 (interactive "P")
7810 (org-insert-heading arg)
7811 (cond
7812 ((org-at-heading-p) (org-do-demote))
7813 ((org-at-item-p) (org-indent-item))))
7815 (defun org-insert-todo-subheading (arg)
7816 "Insert a new subheading with TODO keyword or checkbox and demote it.
7817 Works for outline headings and for plain lists alike."
7818 (interactive "P")
7819 (org-insert-todo-heading arg)
7820 (cond
7821 ((org-at-heading-p) (org-do-demote))
7822 ((org-at-item-p) (org-indent-item))))
7824 ;;; Promotion and Demotion
7826 (defvar org-after-demote-entry-hook nil
7827 "Hook run after an entry has been demoted.
7828 The cursor will be at the beginning of the entry.
7829 When a subtree is being demoted, the hook will be called for each node.")
7831 (defvar org-after-promote-entry-hook nil
7832 "Hook run after an entry has been promoted.
7833 The cursor will be at the beginning of the entry.
7834 When a subtree is being promoted, the hook will be called for each node.")
7836 (defun org-promote-subtree ()
7837 "Promote the entire subtree.
7838 See also `org-promote'."
7839 (interactive)
7840 (save-excursion
7841 (org-with-limited-levels (org-map-tree 'org-promote)))
7842 (org-fix-position-after-promote))
7844 (defun org-demote-subtree ()
7845 "Demote the entire subtree. See `org-demote'.
7846 See also `org-promote'."
7847 (interactive)
7848 (save-excursion
7849 (org-with-limited-levels (org-map-tree 'org-demote)))
7850 (org-fix-position-after-promote))
7853 (defun org-do-promote ()
7854 "Promote the current heading higher up the tree.
7855 If the region is active in `transient-mark-mode', promote all headings
7856 in the region."
7857 (interactive)
7858 (save-excursion
7859 (if (org-region-active-p)
7860 (org-map-region 'org-promote (region-beginning) (region-end))
7861 (org-promote)))
7862 (org-fix-position-after-promote))
7864 (defun org-do-demote ()
7865 "Demote the current heading lower down the tree.
7866 If the region is active in `transient-mark-mode', demote all headings
7867 in the region."
7868 (interactive)
7869 (save-excursion
7870 (if (org-region-active-p)
7871 (org-map-region 'org-demote (region-beginning) (region-end))
7872 (org-demote)))
7873 (org-fix-position-after-promote))
7875 (defun org-fix-position-after-promote ()
7876 "Make sure that after pro/demotion cursor position is right."
7877 (let ((pos (point)))
7878 (when (save-excursion
7879 (beginning-of-line 1)
7880 (looking-at org-todo-line-regexp)
7881 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7882 (cond ((eobp) (insert " "))
7883 ((eolp) (insert " "))
7884 ((equal (char-after) ?\ ) (forward-char 1))))))
7886 (defun org-current-level ()
7887 "Return the level of the current entry, or nil if before the first headline.
7888 The level is the number of stars at the beginning of the headline."
7889 (save-excursion
7890 (org-with-limited-levels
7891 (if (ignore-errors (org-back-to-heading t))
7892 (funcall outline-level)))))
7894 (defun org-get-previous-line-level ()
7895 "Return the outline depth of the last headline before the current line.
7896 Returns 0 for the first headline in the buffer, and nil if before the
7897 first headline."
7898 (let ((current-level (org-current-level))
7899 (prev-level (when (> (line-number-at-pos) 1)
7900 (save-excursion
7901 (beginning-of-line 0)
7902 (org-current-level)))))
7903 (cond ((null current-level) nil) ; Before first headline
7904 ((null prev-level) 0) ; At first headline
7905 (prev-level))))
7907 (defun org-reduced-level (l)
7908 "Compute the effective level of a heading.
7909 This takes into account the setting of `org-odd-levels-only'."
7910 (cond
7911 ((zerop l) 0)
7912 (org-odd-levels-only (1+ (floor (/ l 2))))
7913 (t l)))
7915 (defun org-level-increment ()
7916 "Return the number of stars that will be added or removed at a
7917 time to headlines when structure editing, based on the value of
7918 `org-odd-levels-only'."
7919 (if org-odd-levels-only 2 1))
7921 (defun org-get-valid-level (level &optional change)
7922 "Rectify a level change under the influence of `org-odd-levels-only'
7923 LEVEL is a current level, CHANGE is by how much the level should be
7924 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7925 even level numbers will become the next higher odd number."
7926 (if org-odd-levels-only
7927 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7928 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7929 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7930 (max 1 (+ level (or change 0)))))
7932 (if (boundp 'define-obsolete-function-alias)
7933 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7934 (define-obsolete-function-alias 'org-get-legal-level
7935 'org-get-valid-level)
7936 (define-obsolete-function-alias 'org-get-legal-level
7937 'org-get-valid-level "23.1")))
7939 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7940 ;; ̀org-with-limited-levels'
7941 (defun org-promote ()
7942 "Promote the current heading higher up the tree.
7943 If the region is active in `transient-mark-mode', promote all headings
7944 in the region."
7945 (org-back-to-heading t)
7946 (let* ((level (save-match-data (funcall outline-level)))
7947 (after-change-functions (remove 'flyspell-after-change-function
7948 after-change-functions))
7949 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7950 (diff (abs (- level (length up-head) -1))))
7951 (cond ((and (= level 1) org-called-with-limited-levels
7952 org-allow-promoting-top-level-subtree)
7953 (replace-match "# " nil t))
7954 ((= level 1)
7955 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7956 (t (replace-match up-head nil t)))
7957 ;; Fixup tag positioning
7958 (unless (= level 1)
7959 (and org-auto-align-tags (org-set-tags nil t))
7960 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7961 (run-hooks 'org-after-promote-entry-hook)))
7963 (defun org-demote ()
7964 "Demote the current heading lower down the tree.
7965 If the region is active in `transient-mark-mode', demote all headings
7966 in the region."
7967 (org-back-to-heading t)
7968 (let* ((level (save-match-data (funcall outline-level)))
7969 (after-change-functions (remove 'flyspell-after-change-function
7970 after-change-functions))
7971 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7972 (diff (abs (- level (length down-head) -1))))
7973 (replace-match down-head nil t)
7974 ;; Fixup tag positioning
7975 (and org-auto-align-tags (org-set-tags nil t))
7976 (if org-adapt-indentation (org-fixup-indentation diff))
7977 (run-hooks 'org-after-demote-entry-hook)))
7979 (defun org-cycle-level ()
7980 "Cycle the level of an empty headline through possible states.
7981 This goes first to child, then to parent, level, then up the hierarchy.
7982 After top level, it switches back to sibling level."
7983 (interactive)
7984 (let ((org-adapt-indentation nil))
7985 (when (org-point-at-end-of-empty-headline)
7986 (setq this-command 'org-cycle-level) ; Only needed for caching
7987 (let ((cur-level (org-current-level))
7988 (prev-level (org-get-previous-line-level)))
7989 (cond
7990 ;; If first headline in file, promote to top-level.
7991 ((= prev-level 0)
7992 (loop repeat (/ (- cur-level 1) (org-level-increment))
7993 do (org-do-promote)))
7994 ;; If same level as prev, demote one.
7995 ((= prev-level cur-level)
7996 (org-do-demote))
7997 ;; If parent is top-level, promote to top level if not already.
7998 ((= prev-level 1)
7999 (loop repeat (/ (- cur-level 1) (org-level-increment))
8000 do (org-do-promote)))
8001 ;; If top-level, return to prev-level.
8002 ((= cur-level 1)
8003 (loop repeat (/ (- prev-level 1) (org-level-increment))
8004 do (org-do-demote)))
8005 ;; If less than prev-level, promote one.
8006 ((< cur-level prev-level)
8007 (org-do-promote))
8008 ;; If deeper than prev-level, promote until higher than
8009 ;; prev-level.
8010 ((> cur-level prev-level)
8011 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8012 do (org-do-promote))))
8013 t))))
8015 (defun org-map-tree (fun)
8016 "Call FUN for every heading underneath the current one."
8017 (org-back-to-heading)
8018 (let ((level (funcall outline-level)))
8019 (save-excursion
8020 (funcall fun)
8021 (while (and (progn
8022 (outline-next-heading)
8023 (> (funcall outline-level) level))
8024 (not (eobp)))
8025 (funcall fun)))))
8027 (defun org-map-region (fun beg end)
8028 "Call FUN for every heading between BEG and END."
8029 (let ((org-ignore-region t))
8030 (save-excursion
8031 (setq end (copy-marker end))
8032 (goto-char beg)
8033 (if (and (re-search-forward org-outline-regexp-bol nil t)
8034 (< (point) end))
8035 (funcall fun))
8036 (while (and (progn
8037 (outline-next-heading)
8038 (< (point) end))
8039 (not (eobp)))
8040 (funcall fun)))))
8042 (defvar org-property-end-re) ; silence byte-compiler
8043 (defun org-fixup-indentation (diff)
8044 "Change the indentation in the current entry by DIFF.
8045 However, if any line in the current entry has no indentation, or if it
8046 would end up with no indentation after the change, nothing at all is done."
8047 (save-excursion
8048 (let ((end (save-excursion (outline-next-heading)
8049 (point-marker)))
8050 (prohibit (if (> diff 0)
8051 "^\\S-"
8052 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8053 col)
8054 (unless (save-excursion (end-of-line 1)
8055 (re-search-forward prohibit end t))
8056 (while (and (< (point) end)
8057 (re-search-forward "^[ \t]+" end t))
8058 (goto-char (match-end 0))
8059 (setq col (current-column))
8060 (if (< diff 0) (replace-match ""))
8061 (org-indent-to-column (+ diff col))))
8062 (move-marker end nil))))
8064 (defun org-convert-to-odd-levels ()
8065 "Convert an org-mode file with all levels allowed to one with odd levels.
8066 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8067 level 5 etc."
8068 (interactive)
8069 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8070 (let ((outline-level 'org-outline-level)
8071 (org-odd-levels-only nil) n)
8072 (save-excursion
8073 (goto-char (point-min))
8074 (while (re-search-forward "^\\*\\*+ " nil t)
8075 (setq n (- (length (match-string 0)) 2))
8076 (while (>= (setq n (1- n)) 0)
8077 (org-demote))
8078 (end-of-line 1))))))
8080 (defun org-convert-to-oddeven-levels ()
8081 "Convert an org-mode file with only odd levels to one with odd/even levels.
8082 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8083 file contains a section with an even level, conversion would
8084 destroy the structure of the file. An error is signaled in this
8085 case."
8086 (interactive)
8087 (goto-char (point-min))
8088 ;; First check if there are no even levels
8089 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8090 (org-show-context t)
8091 (error "Not all levels are odd in this file. Conversion not possible"))
8092 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8093 (let ((outline-regexp org-outline-regexp)
8094 (outline-level 'org-outline-level)
8095 (org-odd-levels-only nil) n)
8096 (save-excursion
8097 (goto-char (point-min))
8098 (while (re-search-forward "^\\*\\*+ " nil t)
8099 (setq n (/ (1- (length (match-string 0))) 2))
8100 (while (>= (setq n (1- n)) 0)
8101 (org-promote))
8102 (end-of-line 1))))))
8104 (defun org-tr-level (n)
8105 "Make N odd if required."
8106 (if org-odd-levels-only (1+ (/ n 2)) n))
8108 ;;; Vertical tree motion, cutting and pasting of subtrees
8110 (defun org-move-subtree-up (&optional arg)
8111 "Move the current subtree up past ARG headlines of the same level."
8112 (interactive "p")
8113 (org-move-subtree-down (- (prefix-numeric-value arg))))
8115 (defun org-move-subtree-down (&optional arg)
8116 "Move the current subtree down past ARG headlines of the same level."
8117 (interactive "p")
8118 (setq arg (prefix-numeric-value arg))
8119 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8120 'org-get-last-sibling))
8121 (ins-point (make-marker))
8122 (cnt (abs arg))
8123 (col (current-column))
8124 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8125 ;; Select the tree
8126 (org-back-to-heading)
8127 (setq beg0 (point))
8128 (save-excursion
8129 (setq ne-beg (org-back-over-empty-lines))
8130 (setq beg (point)))
8131 (save-match-data
8132 (save-excursion (outline-end-of-heading)
8133 (setq folded (outline-invisible-p)))
8134 (outline-end-of-subtree))
8135 (outline-next-heading)
8136 (setq ne-end (org-back-over-empty-lines))
8137 (setq end (point))
8138 (goto-char beg0)
8139 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8140 ;; include less whitespace
8141 (save-excursion
8142 (goto-char beg)
8143 (forward-line (- ne-beg ne-end))
8144 (setq beg (point))))
8145 ;; Find insertion point, with error handling
8146 (while (> cnt 0)
8147 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8148 (progn (goto-char beg0)
8149 (user-error "Cannot move past superior level or buffer limit")))
8150 (setq cnt (1- cnt)))
8151 (if (> arg 0)
8152 ;; Moving forward - still need to move over subtree
8153 (progn (org-end-of-subtree t t)
8154 (save-excursion
8155 (org-back-over-empty-lines)
8156 (or (bolp) (newline)))))
8157 (setq ne-ins (org-back-over-empty-lines))
8158 (move-marker ins-point (point))
8159 (setq txt (buffer-substring beg end))
8160 (org-save-markers-in-region beg end)
8161 (delete-region beg end)
8162 (org-remove-empty-overlays-at beg)
8163 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8164 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8165 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8166 (let ((bbb (point)))
8167 (insert-before-markers txt)
8168 (org-reinstall-markers-in-region bbb)
8169 (move-marker ins-point bbb))
8170 (or (bolp) (insert "\n"))
8171 (setq ins-end (point))
8172 (goto-char ins-point)
8173 (org-skip-whitespace)
8174 (when (and (< arg 0)
8175 (org-first-sibling-p)
8176 (> ne-ins ne-beg))
8177 ;; Move whitespace back to beginning
8178 (save-excursion
8179 (goto-char ins-end)
8180 (let ((kill-whole-line t))
8181 (kill-line (- ne-ins ne-beg)) (point)))
8182 (insert (make-string (- ne-ins ne-beg) ?\n)))
8183 (move-marker ins-point nil)
8184 (if folded
8185 (hide-subtree)
8186 (org-show-entry)
8187 (show-children)
8188 (org-cycle-hide-drawers 'children))
8189 (org-clean-visibility-after-subtree-move)
8190 ;; move back to the initial column we were at
8191 (move-to-column col)))
8193 (defvar org-subtree-clip ""
8194 "Clipboard for cut and paste of subtrees.
8195 This is actually only a copy of the kill, because we use the normal kill
8196 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8198 (defvar org-subtree-clip-folded nil
8199 "Was the last copied subtree folded?
8200 This is used to fold the tree back after pasting.")
8202 (defun org-cut-subtree (&optional n)
8203 "Cut the current subtree into the clipboard.
8204 With prefix arg N, cut this many sequential subtrees.
8205 This is a short-hand for marking the subtree and then cutting it."
8206 (interactive "p")
8207 (org-copy-subtree n 'cut))
8209 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8210 "Copy the current subtree it in the clipboard.
8211 With prefix arg N, copy this many sequential subtrees.
8212 This is a short-hand for marking the subtree and then copying it.
8213 If CUT is non-nil, actually cut the subtree.
8214 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8215 of some markers in the region, even if CUT is non-nil. This is
8216 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8217 (interactive "p")
8218 (let (beg end folded (beg0 (point)))
8219 (if (org-called-interactively-p 'any)
8220 (org-back-to-heading nil) ; take what looks like a subtree
8221 (org-back-to-heading t)) ; take what is really there
8222 (setq beg (point))
8223 (skip-chars-forward " \t\r\n")
8224 (save-match-data
8225 (if nosubtrees
8226 (outline-next-heading)
8227 (save-excursion (outline-end-of-heading)
8228 (setq folded (outline-invisible-p)))
8229 (condition-case nil
8230 (org-forward-heading-same-level (1- n) t)
8231 (error nil))
8232 (org-end-of-subtree t t)))
8233 (setq end (point))
8234 (goto-char beg0)
8235 (when (> end beg)
8236 (setq org-subtree-clip-folded folded)
8237 (when (or cut force-store-markers)
8238 (org-save-markers-in-region beg end))
8239 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8240 (setq org-subtree-clip (current-kill 0))
8241 (message "%s: Subtree(s) with %d characters"
8242 (if cut "Cut" "Copied")
8243 (length org-subtree-clip)))))
8245 (defun org-paste-subtree (&optional level tree for-yank)
8246 "Paste the clipboard as a subtree, with modification of headline level.
8247 The entire subtree is promoted or demoted in order to match a new headline
8248 level.
8250 If the cursor is at the beginning of a headline, the same level as
8251 that headline is used to paste the tree.
8253 If not, the new level is derived from the *visible* headings
8254 before and after the insertion point, and taken to be the inferior headline
8255 level of the two. So if the previous visible heading is level 3 and the
8256 next is level 4 (or vice versa), level 4 will be used for insertion.
8257 This makes sure that the subtree remains an independent subtree and does
8258 not swallow low level entries.
8260 You can also force a different level, either by using a numeric prefix
8261 argument, or by inserting the heading marker by hand. For example, if the
8262 cursor is after \"*****\", then the tree will be shifted to level 5.
8264 If optional TREE is given, use this text instead of the kill ring.
8266 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8267 move back over whitespace before inserting, and move point to the end of
8268 the inserted text when done."
8269 (interactive "P")
8270 (setq tree (or tree (and kill-ring (current-kill 0))))
8271 (unless (org-kill-is-subtree-p tree)
8272 (user-error "%s"
8273 (substitute-command-keys
8274 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8275 (org-with-limited-levels
8276 (let* ((visp (not (outline-invisible-p)))
8277 (txt tree)
8278 (^re_ "\\(\\*+\\)[ \t]*")
8279 (old-level (if (string-match org-outline-regexp-bol txt)
8280 (- (match-end 0) (match-beginning 0) 1)
8281 -1))
8282 (force-level (cond (level (prefix-numeric-value level))
8283 ((and (looking-at "[ \t]*$")
8284 (string-match
8285 "^\\*+$" (buffer-substring
8286 (point-at-bol) (point))))
8287 (- (match-end 1) (match-beginning 1)))
8288 ((and (bolp)
8289 (looking-at org-outline-regexp))
8290 (- (match-end 0) (point) 1))))
8291 (previous-level (save-excursion
8292 (condition-case nil
8293 (progn
8294 (outline-previous-visible-heading 1)
8295 (if (looking-at ^re_)
8296 (- (match-end 0) (match-beginning 0) 1)
8298 (error 1))))
8299 (next-level (save-excursion
8300 (condition-case nil
8301 (progn
8302 (or (looking-at org-outline-regexp)
8303 (outline-next-visible-heading 1))
8304 (if (looking-at ^re_)
8305 (- (match-end 0) (match-beginning 0) 1)
8307 (error 1))))
8308 (new-level (or force-level (max previous-level next-level)))
8309 (shift (if (or (= old-level -1)
8310 (= new-level -1)
8311 (= old-level new-level))
8313 (- new-level old-level)))
8314 (delta (if (> shift 0) -1 1))
8315 (func (if (> shift 0) 'org-demote 'org-promote))
8316 (org-odd-levels-only nil)
8317 beg end newend)
8318 ;; Remove the forced level indicator
8319 (if force-level
8320 (delete-region (point-at-bol) (point)))
8321 ;; Paste
8322 (beginning-of-line (if (bolp) 1 2))
8323 (setq beg (point))
8324 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8325 (insert-before-markers txt)
8326 (unless (string-match "\n\\'" txt) (insert "\n"))
8327 (setq newend (point))
8328 (org-reinstall-markers-in-region beg)
8329 (setq end (point))
8330 (goto-char beg)
8331 (skip-chars-forward " \t\n\r")
8332 (setq beg (point))
8333 (if (and (outline-invisible-p) visp)
8334 (save-excursion (outline-show-heading)))
8335 ;; Shift if necessary
8336 (unless (= shift 0)
8337 (save-restriction
8338 (narrow-to-region beg end)
8339 (while (not (= shift 0))
8340 (org-map-region func (point-min) (point-max))
8341 (setq shift (+ delta shift)))
8342 (goto-char (point-min))
8343 (setq newend (point-max))))
8344 (when (or (org-called-interactively-p 'interactive) for-yank)
8345 (message "Clipboard pasted as level %d subtree" new-level))
8346 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8347 kill-ring
8348 (eq org-subtree-clip (current-kill 0))
8349 org-subtree-clip-folded)
8350 ;; The tree was folded before it was killed/copied
8351 (hide-subtree))
8352 (and for-yank (goto-char newend)))))
8354 (defun org-kill-is-subtree-p (&optional txt)
8355 "Check if the current kill is an outline subtree, or a set of trees.
8356 Returns nil if kill does not start with a headline, or if the first
8357 headline level is not the largest headline level in the tree.
8358 So this will actually accept several entries of equal levels as well,
8359 which is OK for `org-paste-subtree'.
8360 If optional TXT is given, check this string instead of the current kill."
8361 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8362 (re (org-get-limited-outline-regexp))
8363 (^re (concat "^" re))
8364 (start-level (and kill
8365 (string-match
8366 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8367 kill)
8368 (- (match-end 2) (match-beginning 2) 1)))
8369 (start (1+ (or (match-beginning 2) -1))))
8370 (if (not start-level)
8371 (progn
8372 nil) ;; does not even start with a heading
8373 (catch 'exit
8374 (while (setq start (string-match ^re kill (1+ start)))
8375 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8376 (throw 'exit nil)))
8377 t))))
8379 (defvar org-markers-to-move nil
8380 "Markers that should be moved with a cut-and-paste operation.
8381 Those markers are stored together with their positions relative to
8382 the start of the region.")
8384 (defun org-save-markers-in-region (beg end)
8385 "Check markers in region.
8386 If these markers are between BEG and END, record their position relative
8387 to BEG, so that after moving the block of text, we can put the markers back
8388 into place.
8389 This function gets called just before an entry or tree gets cut from the
8390 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8391 called immediately, to move the markers with the entries."
8392 (setq org-markers-to-move nil)
8393 (when (featurep 'org-clock)
8394 (org-clock-save-markers-for-cut-and-paste beg end))
8395 (when (featurep 'org-agenda)
8396 (org-agenda-save-markers-for-cut-and-paste beg end)))
8398 (defun org-check-and-save-marker (marker beg end)
8399 "Check if MARKER is between BEG and END.
8400 If yes, remember the marker and the distance to BEG."
8401 (when (and (marker-buffer marker)
8402 (equal (marker-buffer marker) (current-buffer)))
8403 (if (and (>= marker beg) (< marker end))
8404 (push (cons marker (- marker beg)) org-markers-to-move))))
8406 (defun org-reinstall-markers-in-region (beg)
8407 "Move all remembered markers to their position relative to BEG."
8408 (mapc (lambda (x)
8409 (move-marker (car x) (+ beg (cdr x))))
8410 org-markers-to-move)
8411 (setq org-markers-to-move nil))
8413 (defun org-narrow-to-subtree ()
8414 "Narrow buffer to the current subtree."
8415 (interactive)
8416 (save-excursion
8417 (save-match-data
8418 (org-with-limited-levels
8419 (narrow-to-region
8420 (progn (org-back-to-heading t) (point))
8421 (progn (org-end-of-subtree t t)
8422 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8423 (point)))))))
8425 (defun org-narrow-to-block ()
8426 "Narrow buffer to the current block."
8427 (interactive)
8428 (let* ((case-fold-search t)
8429 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8430 "^[ \t]*#\\+end_.*")))
8431 (if blockp
8432 (narrow-to-region (car blockp) (cdr blockp))
8433 (user-error "Not in a block"))))
8435 (eval-when-compile
8436 (defvar org-property-drawer-re))
8438 (defvar org-property-start-re) ;; defined below
8439 (defun org-clone-subtree-with-time-shift (n &optional shift)
8440 "Clone the task (subtree) at point N times.
8441 The clones will be inserted as siblings.
8443 In interactive use, the user will be prompted for the number of
8444 clones to be produced. If the entry has a timestamp, the user
8445 will also be prompted for a time shift, which may be a repeater
8446 as used in time stamps, for example `+3d'. To disable this,
8447 you can call the function with a universal prefix argument.
8449 When a valid repeater is given and the entry contains any time
8450 stamps, the clones will become a sequence in time, with time
8451 stamps in the subtree shifted for each clone produced. If SHIFT
8452 is nil or the empty string, time stamps will be left alone. The
8453 ID property of the original subtree is removed.
8455 If the original subtree did contain time stamps with a repeater,
8456 the following will happen:
8457 - the repeater will be removed in each clone
8458 - an additional clone will be produced, with the current, unshifted
8459 date(s) in the entry.
8460 - the original entry will be placed *after* all the clones, with
8461 repeater intact.
8462 - the start days in the repeater in the original entry will be shifted
8463 to past the last clone.
8464 In this way you can spell out a number of instances of a repeating task,
8465 and still retain the repeater to cover future instances of the task."
8466 (interactive "nNumber of clones to produce: ")
8467 (let ((shift
8468 (or shift
8469 (if (and (not (equal current-prefix-arg '(4)))
8470 (save-excursion
8471 (re-search-forward org-ts-regexp-both
8472 (save-excursion
8473 (org-end-of-subtree t)
8474 (point)) t)))
8475 (read-from-minibuffer
8476 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8477 ""))) ;; No time shift
8478 (n-no-remove -1)
8479 (drawer-re org-drawer-regexp)
8480 beg end template task idprop
8481 shift-n shift-what doshift nmin nmax)
8482 (if (not (and (integerp n) (> n 0)))
8483 (error "Invalid number of replications %s" n))
8484 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8485 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8486 shift)))
8487 (error "Invalid shift specification %s" shift))
8488 (when doshift
8489 (setq shift-n (string-to-number (match-string 1 shift))
8490 shift-what (cdr (assoc (match-string 2 shift)
8491 '(("d" . day) ("w" . week)
8492 ("m" . month) ("y" . year))))))
8493 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8494 (setq nmin 1 nmax n)
8495 (org-back-to-heading t)
8496 (setq beg (point))
8497 (setq idprop (org-entry-get nil "ID"))
8498 (org-end-of-subtree t t)
8499 (or (bolp) (insert "\n"))
8500 (setq end (point))
8501 (setq template (buffer-substring beg end))
8502 (when (and doshift
8503 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8504 (delete-region beg end)
8505 (setq end beg)
8506 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8507 (goto-char end)
8508 (loop for n from nmin to nmax do
8509 ;; prepare clone
8510 (with-temp-buffer
8511 (insert template)
8512 (org-mode)
8513 (goto-char (point-min))
8514 (org-show-subtree)
8515 (and idprop (if org-clone-delete-id
8516 (org-entry-delete nil "ID")
8517 (org-id-get-create t)))
8518 (unless (= n 0)
8519 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8520 (kill-whole-line))
8521 (goto-char (point-min))
8522 (while (re-search-forward drawer-re nil t)
8523 (mapc (lambda (d)
8524 (org-remove-empty-drawer-at d (point))) org-drawers)))
8525 (goto-char (point-min))
8526 (when doshift
8527 (while (re-search-forward org-ts-regexp-both nil t)
8528 (org-timestamp-change (* n shift-n) shift-what))
8529 (unless (= n n-no-remove)
8530 (goto-char (point-min))
8531 (while (re-search-forward org-ts-regexp nil t)
8532 (save-excursion
8533 (goto-char (match-beginning 0))
8534 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8535 (delete-region (match-beginning 1) (match-end 1)))))))
8536 (setq task (buffer-string)))
8537 (insert task))
8538 (goto-char beg)))
8540 ;;; Outline Sorting
8542 (defun org-sort (with-case)
8543 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8544 Optional argument WITH-CASE means sort case-sensitively."
8545 (interactive "P")
8546 (cond
8547 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8548 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8550 (org-call-with-arg 'org-sort-entries with-case))))
8552 (defun org-sort-remove-invisible (s)
8553 "Remove invisible links from string S."
8554 (remove-text-properties 0 (length s) org-rm-props s)
8555 (while (string-match org-bracket-link-regexp s)
8556 (setq s (replace-match (if (match-end 2)
8557 (match-string 3 s)
8558 (match-string 1 s)) t t s)))
8559 (let ((st (format " %s " s)))
8560 (while (string-match org-emph-re st)
8561 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8562 (setq s (substring st 1 -1)))
8565 (defvar org-priority-regexp) ; defined later in the file
8567 (defvar org-after-sorting-entries-or-items-hook nil
8568 "Hook that is run after a bunch of entries or items have been sorted.
8569 When children are sorted, the cursor is in the parent line when this
8570 hook gets called. When a region or a plain list is sorted, the cursor
8571 will be in the first entry of the sorted region/list.")
8573 (defun org-sort-entries
8574 (&optional with-case sorting-type getkey-func compare-func property)
8575 "Sort entries on a certain level of an outline tree.
8576 If there is an active region, the entries in the region are sorted.
8577 Else, if the cursor is before the first entry, sort the top-level items.
8578 Else, the children of the entry at point are sorted.
8580 Sorting can be alphabetically, numerically, by date/time as given by
8581 a time stamp, by a property, by priority order, or by a custom function.
8583 The command prompts for the sorting type unless it has been given to the
8584 function through the SORTING-TYPE argument, which needs to be a character,
8585 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8586 precise meaning of each character:
8588 n Numerically, by converting the beginning of the entry/item to a number.
8589 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8590 o By order of TODO keywords.
8591 t By date/time, either the first active time stamp in the entry, or, if
8592 none exist, by the first inactive one.
8593 s By the scheduled date/time.
8594 d By deadline date/time.
8595 c By creation time, which is assumed to be the first inactive time stamp
8596 at the beginning of a line.
8597 p By priority according to the cookie.
8598 r By the value of a property.
8600 Capital letters will reverse the sort order.
8602 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8603 called with point at the beginning of the record. It must return either
8604 a string or a number that should serve as the sorting key for that record.
8606 Comparing entries ignores case by default. However, with an optional argument
8607 WITH-CASE, the sorting considers case as well.
8609 Sorting is done against the visible part of the headlines, it ignores hidden
8610 links."
8611 (interactive "P")
8612 (let ((case-func (if with-case 'identity 'downcase))
8613 (cmstr
8614 ;; The clock marker is lost when using `sort-subr', let's
8615 ;; store the clocking string.
8616 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8617 (save-excursion
8618 (goto-char org-clock-marker)
8619 (looking-back "^.*") (match-string-no-properties 0))))
8620 start beg end stars re re2
8621 txt what tmp)
8622 ;; Find beginning and end of region to sort
8623 (cond
8624 ((org-region-active-p)
8625 ;; we will sort the region
8626 (setq end (region-end)
8627 what "region")
8628 (goto-char (region-beginning))
8629 (if (not (org-at-heading-p)) (outline-next-heading))
8630 (setq start (point)))
8631 ((or (org-at-heading-p)
8632 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8633 ;; we will sort the children of the current headline
8634 (org-back-to-heading)
8635 (setq start (point)
8636 end (progn (org-end-of-subtree t t)
8637 (or (bolp) (insert "\n"))
8638 (org-back-over-empty-lines)
8639 (point))
8640 what "children")
8641 (goto-char start)
8642 (show-subtree)
8643 (outline-next-heading))
8645 ;; we will sort the top-level entries in this file
8646 (goto-char (point-min))
8647 (or (org-at-heading-p) (outline-next-heading))
8648 (setq start (point))
8649 (goto-char (point-max))
8650 (beginning-of-line 1)
8651 (when (looking-at ".*?\\S-")
8652 ;; File ends in a non-white line
8653 (end-of-line 1)
8654 (insert "\n"))
8655 (setq end (point-max))
8656 (setq what "top-level")
8657 (goto-char start)
8658 (show-all)))
8660 (setq beg (point))
8661 (if (>= beg end) (user-error "Nothing to sort"))
8663 (looking-at "\\(\\*+\\)")
8664 (setq stars (match-string 1)
8665 re (concat "^" (regexp-quote stars) " +")
8666 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8667 txt (buffer-substring beg end))
8668 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8669 (if (and (not (equal stars "*")) (string-match re2 txt))
8670 (user-error "Region to sort contains a level above the first entry"))
8672 (unless sorting-type
8673 (message
8674 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8675 [t]ime [s]cheduled [d]eadline [c]reated
8676 A/N/P/R/O/F/T/S/D/C means reversed:"
8677 what)
8678 (setq sorting-type (read-char-exclusive))
8680 (unless getkey-func
8681 (and (= (downcase sorting-type) ?f)
8682 (setq getkey-func
8683 (org-icompleting-read "Sort using function: "
8684 obarray 'fboundp t nil nil))
8685 (setq getkey-func (intern getkey-func))))
8687 (and (= (downcase sorting-type) ?r)
8688 (not property)
8689 (setq property
8690 (org-icompleting-read "Property: "
8691 (mapcar 'list (org-buffer-property-keys t))
8692 nil t))))
8694 (message "Sorting entries...")
8696 (save-restriction
8697 (narrow-to-region start end)
8698 (let ((dcst (downcase sorting-type))
8699 (case-fold-search nil)
8700 (now (current-time)))
8701 (sort-subr
8702 (/= dcst sorting-type)
8703 ;; This function moves to the beginning character of the "record" to
8704 ;; be sorted.
8705 (lambda nil
8706 (if (re-search-forward re nil t)
8707 (goto-char (match-beginning 0))
8708 (goto-char (point-max))))
8709 ;; This function moves to the last character of the "record" being
8710 ;; sorted.
8711 (lambda nil
8712 (save-match-data
8713 (condition-case nil
8714 (outline-forward-same-level 1)
8715 (error
8716 (goto-char (point-max))))))
8717 ;; This function returns the value that gets sorted against.
8718 (lambda nil
8719 (cond
8720 ((= dcst ?n)
8721 (if (looking-at org-complex-heading-regexp)
8722 (string-to-number (org-sort-remove-invisible (match-string 4)))
8723 nil))
8724 ((= dcst ?a)
8725 (if (looking-at org-complex-heading-regexp)
8726 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8727 nil))
8728 ((= dcst ?t)
8729 (let ((end (save-excursion (outline-next-heading) (point))))
8730 (if (or (re-search-forward org-ts-regexp end t)
8731 (re-search-forward org-ts-regexp-both end t))
8732 (org-time-string-to-seconds (match-string 0))
8733 (org-float-time now))))
8734 ((= dcst ?c)
8735 (let ((end (save-excursion (outline-next-heading) (point))))
8736 (if (re-search-forward
8737 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8738 end t)
8739 (org-time-string-to-seconds (match-string 0))
8740 (org-float-time now))))
8741 ((= dcst ?s)
8742 (let ((end (save-excursion (outline-next-heading) (point))))
8743 (if (re-search-forward org-scheduled-time-regexp end t)
8744 (org-time-string-to-seconds (match-string 1))
8745 (org-float-time now))))
8746 ((= dcst ?d)
8747 (let ((end (save-excursion (outline-next-heading) (point))))
8748 (if (re-search-forward org-deadline-time-regexp end t)
8749 (org-time-string-to-seconds (match-string 1))
8750 (org-float-time now))))
8751 ((= dcst ?p)
8752 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8753 (string-to-char (match-string 2))
8754 org-default-priority))
8755 ((= dcst ?r)
8756 (or (org-entry-get nil property) ""))
8757 ((= dcst ?o)
8758 (if (looking-at org-complex-heading-regexp)
8759 (- 9999 (length (member (match-string 2)
8760 org-todo-keywords-1)))))
8761 ((= dcst ?f)
8762 (if getkey-func
8763 (progn
8764 (setq tmp (funcall getkey-func))
8765 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8766 tmp)
8767 (error "Invalid key function `%s'" getkey-func)))
8768 (t (error "Invalid sorting type `%c'" sorting-type))))
8770 (cond
8771 ((= dcst ?a) 'string<)
8772 ((= dcst ?f) compare-func)
8773 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8774 (run-hooks 'org-after-sorting-entries-or-items-hook)
8775 ;; Reset the clock marker if needed
8776 (when cmstr
8777 (save-excursion
8778 (goto-char start)
8779 (search-forward cmstr nil t)
8780 (move-marker org-clock-marker (point))))
8781 (message "Sorting entries...done")))
8783 (defun org-do-sort (table what &optional with-case sorting-type)
8784 "Sort TABLE of WHAT according to SORTING-TYPE.
8785 The user will be prompted for the SORTING-TYPE if the call to this
8786 function does not specify it. WHAT is only for the prompt, to indicate
8787 what is being sorted. The sorting key will be extracted from
8788 the car of the elements of the table.
8789 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8790 (unless sorting-type
8791 (message
8792 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8793 what)
8794 (setq sorting-type (read-char-exclusive)))
8795 (let ((dcst (downcase sorting-type))
8796 extractfun comparefun)
8797 ;; Define the appropriate functions
8798 (cond
8799 ((= dcst ?n)
8800 (setq extractfun 'string-to-number
8801 comparefun (if (= dcst sorting-type) '< '>)))
8802 ((= dcst ?a)
8803 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8804 (lambda(x) (downcase (org-sort-remove-invisible x))))
8805 comparefun (if (= dcst sorting-type)
8806 'string<
8807 (lambda (a b) (and (not (string< a b))
8808 (not (string= a b)))))))
8809 ((= dcst ?t)
8810 (setq extractfun
8811 (lambda (x)
8812 (if (or (string-match org-ts-regexp x)
8813 (string-match org-ts-regexp-both x))
8814 (org-float-time
8815 (org-time-string-to-time (match-string 0 x)))
8817 comparefun (if (= dcst sorting-type) '< '>)))
8818 (t (error "Invalid sorting type `%c'" sorting-type)))
8820 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8821 table)
8822 (lambda (a b) (funcall comparefun (car a) (car b))))))
8825 ;;; The orgstruct minor mode
8827 ;; Define a minor mode which can be used in other modes in order to
8828 ;; integrate the org-mode structure editing commands.
8830 ;; This is really a hack, because the org-mode structure commands use
8831 ;; keys which normally belong to the major mode. Here is how it
8832 ;; works: The minor mode defines all the keys necessary to operate the
8833 ;; structure commands, but wraps the commands into a function which
8834 ;; tests if the cursor is currently at a headline or a plain list
8835 ;; item. If that is the case, the structure command is used,
8836 ;; temporarily setting many Org-mode variables like regular
8837 ;; expressions for filling etc. However, when any of those keys is
8838 ;; used at a different location, function uses `key-binding' to look
8839 ;; up if the key has an associated command in another currently active
8840 ;; keymap (minor modes, major mode, global), and executes that
8841 ;; command. There might be problems if any of the keys is otherwise
8842 ;; used as a prefix key.
8844 (defcustom orgstruct-heading-prefix-regexp nil
8845 "Regexp that matches the custom prefix of Org headlines in
8846 orgstruct(++)-mode."
8847 :group 'org
8848 :version "24.4"
8849 :package-version '(Org . "8.0")
8850 :type 'string)
8851 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8853 (defcustom orgstruct-setup-hook nil
8854 "Hook run after orgstruct-mode-map is filled."
8855 :group 'org
8856 :version "24.4"
8857 :package-version '(Org . "8.0")
8858 :type 'hook)
8860 (defvar orgstruct-initialized nil)
8862 (defvar org-local-vars nil
8863 "List of local variables, for use by `orgstruct-mode'.")
8865 ;;;###autoload
8866 (define-minor-mode orgstruct-mode
8867 "Toggle the minor mode `orgstruct-mode'.
8868 This mode is for using Org-mode structure commands in other
8869 modes. The following keys behave as if Org-mode were active, if
8870 the cursor is on a headline, or on a plain list item (both as
8871 defined by Org-mode)."
8872 nil " OrgStruct" (make-sparse-keymap)
8873 (funcall (if orgstruct-mode
8874 'add-to-invisibility-spec
8875 'remove-from-invisibility-spec)
8876 '(outline . t))
8877 (when orgstruct-mode
8878 (org-load-modules-maybe)
8879 (unless orgstruct-initialized
8880 (orgstruct-setup)
8881 (setq orgstruct-initialized t))))
8883 ;;;###autoload
8884 (defun turn-on-orgstruct ()
8885 "Unconditionally turn on `orgstruct-mode'."
8886 (orgstruct-mode 1))
8888 (defvar org-fb-vars nil)
8889 (make-variable-buffer-local 'org-fb-vars)
8890 (defun orgstruct++-mode (&optional arg)
8891 "Toggle `orgstruct-mode', the enhanced version of it.
8892 In addition to setting orgstruct-mode, this also exports all
8893 indentation and autofilling variables from org-mode into the
8894 buffer. It will also recognize item context in multiline items."
8895 (interactive "P")
8896 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8897 (if (< arg 1)
8898 (progn (orgstruct-mode -1)
8899 (mapc (lambda(v)
8900 (org-set-local (car v)
8901 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8902 org-fb-vars))
8903 (orgstruct-mode 1)
8904 (setq org-fb-vars nil)
8905 (unless org-local-vars
8906 (setq org-local-vars (org-get-local-variables)))
8907 (let (var val)
8908 (mapc
8909 (lambda (x)
8910 (when (string-match
8911 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8912 (symbol-name (car x)))
8913 (setq var (car x) val (nth 1 x))
8914 (push (list var `(quote ,(eval var))) org-fb-vars)
8915 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8916 org-local-vars)
8917 (org-set-local 'orgstruct-is-++ t))))
8919 (defvar orgstruct-is-++ nil
8920 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8921 (make-variable-buffer-local 'orgstruct-is-++)
8923 ;;;###autoload
8924 (defun turn-on-orgstruct++ ()
8925 "Unconditionally turn on `orgstruct++-mode'."
8926 (orgstruct++-mode 1))
8928 (defun orgstruct-error ()
8929 "Error when there is no default binding for a structure key."
8930 (interactive)
8931 (funcall (if (fboundp 'user-error)
8932 'user-error
8933 'error)
8934 "This key has no function outside structure elements"))
8936 (defun orgstruct-setup ()
8937 "Setup orgstruct keymap."
8938 (dolist (cell '((org-demote . t)
8939 (org-metaleft . t)
8940 (org-metaright . t)
8941 (org-promote . t)
8942 (org-shiftmetaleft . t)
8943 (org-shiftmetaright . t)
8944 org-backward-element
8945 org-backward-heading-same-level
8946 org-ctrl-c-ret
8947 org-ctrl-c-minus
8948 org-ctrl-c-star
8949 org-cycle
8950 org-forward-heading-same-level
8951 org-insert-heading
8952 org-insert-heading-respect-content
8953 org-kill-note-or-show-branches
8954 org-mark-subtree
8955 org-meta-return
8956 org-metadown
8957 org-metaup
8958 org-narrow-to-subtree
8959 org-promote-subtree
8960 org-reveal
8961 org-shiftdown
8962 org-shiftleft
8963 org-shiftmetadown
8964 org-shiftmetaup
8965 org-shiftright
8966 org-shifttab
8967 org-shifttab
8968 org-shiftup
8969 org-show-subtree
8970 org-sort
8971 org-up-element
8972 outline-demote
8973 outline-next-visible-heading
8974 outline-previous-visible-heading
8975 outline-promote
8976 outline-up-heading
8977 show-children))
8978 (let ((f (or (car-safe cell) cell))
8979 (disable-when-heading-prefix (cdr-safe cell)))
8980 (when (fboundp f)
8981 (let ((new-bindings))
8982 (dolist (binding (nconc (where-is-internal f org-mode-map)
8983 (where-is-internal f outline-mode-map)))
8984 (push binding new-bindings)
8985 ;; TODO use local-function-key-map
8986 (dolist (rep '(("<tab>" . "TAB")
8987 ("<return>" . "RET")
8988 ("<escape>" . "ESC")
8989 ("<delete>" . "DEL")))
8990 (setq binding (read-kbd-macro
8991 (let ((case-fold-search))
8992 (replace-regexp-in-string
8993 (regexp-quote (cdr rep))
8994 (car rep)
8995 (key-description binding)))))
8996 (pushnew binding new-bindings :test 'equal)))
8997 (dolist (binding new-bindings)
8998 (let ((key (lookup-key orgstruct-mode-map binding)))
8999 (when (or (not key) (numberp key))
9000 (condition-case nil
9001 (org-defkey orgstruct-mode-map
9002 binding
9003 (orgstruct-make-binding f binding disable-when-heading-prefix))
9004 (error nil)))))))))
9005 (run-hooks 'orgstruct-setup-hook))
9007 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9008 "Create a function for binding in the structure minor mode.
9009 FUN is the command to call inside a table. KEY is the key that
9010 should be checked in for a command to execute outside of tables.
9011 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
9012 if `orgstruct-heading-prefix-regexp' is non-nil."
9013 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9014 (let ((nname name)
9015 (i 0))
9016 (while (fboundp (intern nname))
9017 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9018 (setq name (intern nname)))
9019 (eval
9020 (let ((bindings '((org-heading-regexp
9021 (concat "^"
9022 orgstruct-heading-prefix-regexp
9023 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9024 (org-outline-regexp
9025 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9026 (org-outline-regexp-bol
9027 (concat "^" org-outline-regexp))
9028 (outline-regexp org-outline-regexp)
9029 (outline-heading-end-regexp "\n")
9030 (outline-level 'org-outline-level)
9031 (outline-heading-alist))))
9032 `(defun ,name (arg)
9033 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9034 "Outside of structure, run the binding of `"
9035 (key-description key) "'."
9036 (when disable-when-heading-prefix
9037 (concat
9038 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9039 "back to the default binding due to limitations of Org's implementation of\n"
9040 "`" (symbol-name fun) "'.")))
9041 (interactive "p")
9042 (let* ((disable
9043 ,(when disable-when-heading-prefix
9044 '(and orgstruct-heading-prefix-regexp
9045 (not (string= orgstruct-heading-prefix-regexp "")))))
9046 (fallback
9047 (or disable
9048 (not
9049 (let* ,bindings
9050 (org-context-p 'headline 'item
9051 ,(when (memq fun
9052 '(org-insert-heading
9053 org-insert-heading-respect-content
9054 org-meta-return))
9055 '(when orgstruct-is-++
9056 'item-body))))))))
9057 (if fallback
9058 (let* ((orgstruct-mode)
9059 (binding
9060 (loop with key = ,key
9061 for rep in
9062 '(nil
9063 ("<\\([^>]*\\)tab>" . "\\1TAB")
9064 ("<\\([^>]*\\)return>" . "\\1RET")
9065 ("<\\([^>]*\\)escape>" . "\\1ESC")
9066 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9068 (when rep
9069 (setq key (read-kbd-macro
9070 (let ((case-fold-search))
9071 (replace-regexp-in-string
9072 (car rep)
9073 (cdr rep)
9074 (key-description key))))))
9075 thereis (key-binding key))))
9076 (if (keymapp binding)
9077 (set-temporary-overlay-map binding)
9078 (let ((func (or binding
9079 (unless disable
9080 'orgstruct-error))))
9081 (when func
9082 (call-interactively func)))))
9083 (org-run-like-in-org-mode
9084 (lambda ()
9085 (interactive)
9086 (let* ,bindings
9087 (call-interactively ',fun)))))))))
9088 name))
9090 (defun org-contextualize-keys (alist contexts)
9091 "Return valid elements in ALIST depending on CONTEXTS.
9093 `org-agenda-custom-commands' or `org-capture-templates' are the
9094 values used for ALIST, and `org-agenda-custom-commands-contexts'
9095 or `org-capture-templates-contexts' are the associated contexts
9096 definitions."
9097 (let ((contexts
9098 ;; normalize contexts
9099 (mapcar
9100 (lambda(c) (cond ((listp (cadr c))
9101 (list (car c) (car c) (cadr c)))
9102 ((string= "" (cadr c))
9103 (list (car c) (car c) (caddr c)))
9104 (t c))) contexts))
9105 (a alist) c r s)
9106 ;; loop over all commands or templates
9107 (while (setq c (pop a))
9108 (let (vrules repl)
9109 (cond
9110 ((not (assoc (car c) contexts))
9111 (push c r))
9112 ((and (assoc (car c) contexts)
9113 (setq vrules (org-contextualize-validate-key
9114 (car c) contexts)))
9115 (mapc (lambda (vr)
9116 (when (not (equal (car vr) (cadr vr)))
9117 (setq repl vr))) vrules)
9118 (if (not repl) (push c r)
9119 (push (cadr repl) s)
9120 (push
9121 (cons (car c)
9122 (cdr (or (assoc (cadr repl) alist)
9123 (error "Undefined key `%s' as contextual replacement for `%s'"
9124 (cadr repl) (car c)))))
9125 r))))))
9126 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9127 (delq
9129 (delete-dups
9130 (mapcar (lambda (x)
9131 (let ((tpl (car x)))
9132 (when (not (delq
9134 (mapcar (lambda(y)
9135 (equal y tpl)) s))) x)))
9136 (reverse r))))))
9138 (defun org-contextualize-validate-key (key contexts)
9139 "Check CONTEXTS for agenda or capture KEY."
9140 (let (r rr res)
9141 (while (setq r (pop contexts))
9142 (mapc
9143 (lambda (rr)
9144 (when
9145 (and (equal key (car r))
9146 (if (functionp rr) (funcall rr)
9147 (or (and (eq (car rr) 'in-file)
9148 (buffer-file-name)
9149 (string-match (cdr rr) (buffer-file-name)))
9150 (and (eq (car rr) 'in-mode)
9151 (string-match (cdr rr) (symbol-name major-mode)))
9152 (and (eq (car rr) 'in-buffer)
9153 (string-match (cdr rr) (buffer-name)))
9154 (when (and (eq (car rr) 'not-in-file)
9155 (buffer-file-name))
9156 (not (string-match (cdr rr) (buffer-file-name))))
9157 (when (eq (car rr) 'not-in-mode)
9158 (not (string-match (cdr rr) (symbol-name major-mode))))
9159 (when (eq (car rr) 'not-in-buffer)
9160 (not (string-match (cdr rr) (buffer-name)))))))
9161 (push r res)))
9162 (car (last r))))
9163 (delete-dups (delq nil res))))
9165 (defun org-context-p (&rest contexts)
9166 "Check if local context is any of CONTEXTS.
9167 Possible values in the list of contexts are `table', `headline', and `item'."
9168 (let ((pos (point)))
9169 (goto-char (point-at-bol))
9170 (prog1 (or (and (memq 'table contexts)
9171 (looking-at "[ \t]*|"))
9172 (and (memq 'headline contexts)
9173 (looking-at org-outline-regexp))
9174 (and (memq 'item contexts)
9175 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9176 (and (memq 'item-body contexts)
9177 (org-in-item-p)))
9178 (goto-char pos))))
9180 (defun org-get-local-variables ()
9181 "Return a list of all local variables in an Org mode buffer."
9182 (let (varlist)
9183 (with-current-buffer (get-buffer-create "*Org tmp*")
9184 (erase-buffer)
9185 (org-mode)
9186 (setq varlist (buffer-local-variables)))
9187 (kill-buffer "*Org tmp*")
9188 (delq nil
9189 (mapcar
9190 (lambda (x)
9191 (setq x
9192 (if (symbolp x)
9193 (list x)
9194 (list (car x) (cdr x))))
9195 (if (and (not (get (car x) 'org-state))
9196 (string-match
9197 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9198 (symbol-name (car x))))
9199 x nil))
9200 varlist))))
9202 (defun org-clone-local-variables (from-buffer &optional regexp)
9203 "Clone local variables from FROM-BUFFER.
9204 Optional argument REGEXP selects variables to clone."
9205 (mapc
9206 (lambda (pair)
9207 (and (symbolp (car pair))
9208 (or (null regexp)
9209 (string-match regexp (symbol-name (car pair))))
9210 (set (make-local-variable (car pair))
9211 (cdr pair))))
9212 (buffer-local-variables from-buffer)))
9214 ;;;###autoload
9215 (defun org-run-like-in-org-mode (cmd)
9216 "Run a command, pretending that the current buffer is in Org-mode.
9217 This will temporarily bind local variables that are typically bound in
9218 Org-mode to the values they have in Org-mode, and then interactively
9219 call CMD."
9220 (org-load-modules-maybe)
9221 (unless org-local-vars
9222 (setq org-local-vars (org-get-local-variables)))
9223 (let (binds)
9224 (dolist (var org-local-vars)
9225 (when (or (not (boundp (car var)))
9226 (eq (symbol-value (car var))
9227 (default-value (car var))))
9228 (push (list (car var) `(quote ,(cadr var))) binds)))
9229 (eval `(let ,binds
9230 (call-interactively (quote ,cmd))))))
9232 ;;;; Archiving
9234 (defun org-get-category (&optional pos force-refresh)
9235 "Get the category applying to position POS."
9236 (save-match-data
9237 (if force-refresh (org-refresh-category-properties))
9238 (let ((pos (or pos (point))))
9239 (or (get-text-property pos 'org-category)
9240 (progn (org-refresh-category-properties)
9241 (get-text-property pos 'org-category))))))
9243 (defun org-refresh-category-properties ()
9244 "Refresh category text properties in the buffer."
9245 (let ((case-fold-search t)
9246 (inhibit-read-only t)
9247 (def-cat (cond
9248 ((null org-category)
9249 (if buffer-file-name
9250 (file-name-sans-extension
9251 (file-name-nondirectory buffer-file-name))
9252 "???"))
9253 ((symbolp org-category) (symbol-name org-category))
9254 (t org-category)))
9255 beg end cat pos optionp)
9256 (org-with-silent-modifications
9257 (save-excursion
9258 (save-restriction
9259 (widen)
9260 (goto-char (point-min))
9261 (put-text-property (point) (point-max) 'org-category def-cat)
9262 (while (re-search-forward
9263 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9264 (setq pos (match-end 0)
9265 optionp (equal (char-after (match-beginning 0)) ?#)
9266 cat (org-trim (match-string 2)))
9267 (if optionp
9268 (setq beg (point-at-bol) end (point-max))
9269 (org-back-to-heading t)
9270 (setq beg (point) end (org-end-of-subtree t t)))
9271 (put-text-property beg end 'org-category cat)
9272 (put-text-property beg end 'org-category-position beg)
9273 (goto-char pos)))))))
9275 (defun org-refresh-properties (dprop tprop)
9276 "Refresh buffer text properties.
9277 DPROP is the drawer property and TPROP is the corresponding text
9278 property to set."
9279 (let ((case-fold-search t)
9280 (inhibit-read-only t) p)
9281 (org-with-silent-modifications
9282 (save-excursion
9283 (save-restriction
9284 (widen)
9285 (goto-char (point-min))
9286 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9287 (setq p (org-match-string-no-properties 1))
9288 (save-excursion
9289 (org-back-to-heading t)
9290 (put-text-property
9291 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9294 ;;;; Link Stuff
9296 ;;; Link abbreviations
9298 (defun org-link-expand-abbrev (link)
9299 "Apply replacements as defined in `org-link-abbrev-alist'."
9300 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9301 (let* ((key (match-string 1 link))
9302 (as (or (assoc key org-link-abbrev-alist-local)
9303 (assoc key org-link-abbrev-alist)))
9304 (tag (and (match-end 2) (match-string 3 link)))
9305 rpl)
9306 (if (not as)
9307 link
9308 (setq rpl (cdr as))
9309 (cond
9310 ((symbolp rpl) (funcall rpl tag))
9311 ((string-match "%(\\([^)]+\\))" rpl)
9312 (replace-match
9313 (save-match-data
9314 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9315 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9316 ((string-match "%h" rpl)
9317 (replace-match (url-hexify-string (or tag "")) t t rpl))
9318 (t (concat rpl tag)))))
9319 link))
9321 ;;; Storing and inserting links
9323 (defvar org-insert-link-history nil
9324 "Minibuffer history for links inserted with `org-insert-link'.")
9326 (defvar org-stored-links nil
9327 "Contains the links stored with `org-store-link'.")
9329 (defvar org-store-link-plist nil
9330 "Plist with info about the most recently link created with `org-store-link'.")
9332 (defvar org-link-protocols nil
9333 "Link protocols added to Org-mode using `org-add-link-type'.")
9335 (defvar org-store-link-functions nil
9336 "List of functions that are called to create and store a link.
9337 Each function will be called in turn until one returns a non-nil
9338 value. Each function should check if it is responsible for creating
9339 this link (for example by looking at the major mode).
9340 If not, it must exit and return nil.
9341 If yes, it should return a non-nil value after a calling
9342 `org-store-link-props' with a list of properties and values.
9343 Special properties are:
9345 :type The link prefix, like \"http\". This must be given.
9346 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9347 This is obligatory as well.
9348 :description Optional default description for the second pair
9349 of brackets in an Org-mode link. The user can still change
9350 this when inserting this link into an Org-mode buffer.
9352 In addition to these, any additional properties can be specified
9353 and then used in capture templates.")
9355 (defun org-add-link-type (type &optional follow export)
9356 "Add TYPE to the list of `org-link-types'.
9357 Re-compute all regular expressions depending on `org-link-types'
9359 FOLLOW and EXPORT are two functions.
9361 FOLLOW should take the link path as the single argument and do whatever
9362 is necessary to follow the link, for example find a file or display
9363 a mail message.
9365 EXPORT should format the link path for export to one of the export formats.
9366 It should be a function accepting three arguments:
9368 path the path of the link, the text after the prefix (like \"http:\")
9369 desc the description of the link, if any, or a description added by
9370 org-export-normalize-links if there is none
9371 format the export format, a symbol like `html' or `latex' or `ascii'..
9373 The function may use the FORMAT information to return different values
9374 depending on the format. The return value will be put literally into
9375 the exported file. If the return value is nil, this means Org should
9376 do what it normally does with links which do not have EXPORT defined.
9378 Org-mode has a built-in default for exporting links. If you are happy with
9379 this default, there is no need to define an export function for the link
9380 type. For a simple example of an export function, see `org-bbdb.el'."
9381 (add-to-list 'org-link-types type t)
9382 (org-make-link-regexps)
9383 (if (assoc type org-link-protocols)
9384 (setcdr (assoc type org-link-protocols) (list follow export))
9385 (push (list type follow export) org-link-protocols)))
9387 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9388 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9390 ;;;###autoload
9391 (defun org-store-link (arg)
9392 "\\<org-mode-map>Store an org-link to the current location.
9393 This link is added to `org-stored-links' and can later be inserted
9394 into an org-buffer with \\[org-insert-link].
9396 For some link types, a prefix arg is interpreted.
9397 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9398 For file links, arg negates `org-context-in-file-links'.
9400 A double prefix arg force skipping storing functions that are not
9401 part of Org's core.
9403 A triple prefix arg force storing a link for each line in the
9404 active region."
9405 (interactive "P")
9406 (org-load-modules-maybe)
9407 (if (and (equal arg '(64)) (org-region-active-p))
9408 (save-excursion
9409 (let ((end (region-end)))
9410 (goto-char (region-beginning))
9411 (set-mark (point))
9412 (while (< (point-at-eol) end)
9413 (move-end-of-line 1) (activate-mark)
9414 (let (current-prefix-arg)
9415 (call-interactively 'org-store-link))
9416 (move-beginning-of-line 2)
9417 (set-mark (point)))))
9418 (org-with-limited-levels
9419 (setq org-store-link-plist nil)
9420 (let (link cpltxt desc description search
9421 txt custom-id agenda-link sfuns sfunsn)
9422 (cond
9424 ;; Store a link using an external link type
9425 ((and (not (equal arg '(16)))
9426 (setq sfuns
9427 (delq
9428 nil (mapcar (lambda (f)
9429 (let (fs) (if (funcall f) (push f fs))))
9430 org-store-link-functions))
9431 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9432 (or (and (cdr sfuns)
9433 (funcall (intern
9434 (completing-read
9435 "Which function for creating the link? "
9436 sfunsn t (car sfunsn)))))
9437 (funcall (caar sfuns)))
9438 (setq link (plist-get org-store-link-plist :link)
9439 desc (or (plist-get org-store-link-plist
9440 :description) link))))
9442 ;; Store a link from a source code buffer
9443 ((org-src-edit-buffer-p)
9444 (let (label gc)
9445 (while (or (not label)
9446 (save-excursion
9447 (save-restriction
9448 (widen)
9449 (goto-char (point-min))
9450 (re-search-forward
9451 (regexp-quote (format org-coderef-label-format label))
9452 nil t))))
9453 (when label (message "Label exists already") (sit-for 2))
9454 (setq label (read-string "Code line label: " label)))
9455 (end-of-line 1)
9456 (setq link (format org-coderef-label-format label))
9457 (setq gc (- 79 (length link)))
9458 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9459 (insert link)
9460 (setq link (concat "(" label ")") desc nil)))
9462 ;; We are in the agenda, link to referenced location
9463 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9464 (let ((m (or (get-text-property (point) 'org-hd-marker)
9465 (get-text-property (point) 'org-marker))))
9466 (when m
9467 (org-with-point-at m
9468 (setq agenda-link
9469 (if (org-called-interactively-p 'any)
9470 (call-interactively 'org-store-link)
9471 (org-store-link nil)))))))
9473 ((eq major-mode 'calendar-mode)
9474 (let ((cd (calendar-cursor-to-date)))
9475 (setq link
9476 (format-time-string
9477 (car org-time-stamp-formats)
9478 (apply 'encode-time
9479 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9480 nil nil nil))))
9481 (org-store-link-props :type "calendar" :date cd)))
9483 ((eq major-mode 'help-mode)
9484 (setq link (concat "help:" (save-excursion
9485 (goto-char (point-min))
9486 (looking-at "^[^ ]+")
9487 (match-string 0))))
9488 (org-store-link-props :type "help"))
9490 ((eq major-mode 'w3-mode)
9491 (setq cpltxt (if (and (buffer-name)
9492 (not (string-match "Untitled" (buffer-name))))
9493 (buffer-name)
9494 (url-view-url t))
9495 link (url-view-url t))
9496 (org-store-link-props :type "w3" :url (url-view-url t)))
9498 ((eq major-mode 'image-mode)
9499 (setq cpltxt (concat "file:"
9500 (abbreviate-file-name buffer-file-name))
9501 link cpltxt)
9502 (org-store-link-props :type "image" :file buffer-file-name))
9504 ;; In dired, store a link to the file of the current line
9505 ((eq major-mode 'dired-mode)
9506 (let ((file (dired-get-filename nil t)))
9507 (setq file (if file
9508 (abbreviate-file-name
9509 (expand-file-name (dired-get-filename nil t)))
9510 ;; otherwise, no file so use current directory.
9511 default-directory))
9512 (setq cpltxt (concat "file:" file)
9513 link cpltxt)))
9515 ((setq search (run-hook-with-args-until-success
9516 'org-create-file-search-functions))
9517 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9518 "::" search))
9519 (setq cpltxt (or description link)))
9521 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9522 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9523 (cond
9524 ;; Store a link using the target at point
9525 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9526 (setq cpltxt
9527 (concat "file:"
9528 (abbreviate-file-name
9529 (buffer-file-name (buffer-base-buffer)))
9530 "::" (match-string 1))
9531 link cpltxt))
9532 ((and (featurep 'org-id)
9533 (or (eq org-id-link-to-org-use-id t)
9534 (and (org-called-interactively-p 'any)
9535 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9536 (and (eq org-id-link-to-org-use-id
9537 'create-if-interactive-and-no-custom-id)
9538 (not custom-id))))
9539 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9540 ;; Store a link using the ID at point
9541 (setq link (condition-case nil
9542 (prog1 (org-id-store-link)
9543 (setq desc (plist-get org-store-link-plist
9544 :description)))
9545 (error
9546 ;; Probably before first headline, link only to file
9547 (concat "file:"
9548 (abbreviate-file-name
9549 (buffer-file-name (buffer-base-buffer))))))))
9551 ;; Just link to current headline
9552 (setq cpltxt (concat "file:"
9553 (abbreviate-file-name
9554 (buffer-file-name (buffer-base-buffer)))))
9555 ;; Add a context search string
9556 (when (org-xor org-context-in-file-links arg)
9557 (let* ((ee (org-element-at-point))
9558 (et (org-element-type ee))
9559 (ev (plist-get (cadr ee) :value))
9560 (ek (plist-get (cadr ee) :key))
9561 (eok (and (stringp ek) (string-match "name" ek))))
9562 (setq txt (cond
9563 ((org-at-heading-p) nil)
9564 ((and (eq et 'keyword) eok) ev)
9565 ((org-region-active-p)
9566 (buffer-substring (region-beginning) (region-end)))))
9567 (when (or (null txt) (string-match "\\S-" txt))
9568 (setq cpltxt
9569 (concat cpltxt "::"
9570 (condition-case nil
9571 (org-make-org-heading-search-string txt)
9572 (error "")))
9573 desc (or (and (eq et 'keyword) eok ev)
9574 (nth 4 (ignore-errors (org-heading-components)))
9575 "NONE")))))
9576 (if (string-match "::\\'" cpltxt)
9577 (setq cpltxt (substring cpltxt 0 -2)))
9578 (setq link cpltxt))))
9580 ((buffer-file-name (buffer-base-buffer))
9581 ;; Just link to this file here.
9582 (setq cpltxt (concat "file:"
9583 (abbreviate-file-name
9584 (buffer-file-name (buffer-base-buffer)))))
9585 ;; Add a context string.
9586 (when (org-xor org-context-in-file-links arg)
9587 (setq txt (if (org-region-active-p)
9588 (buffer-substring (region-beginning) (region-end))
9589 (buffer-substring (point-at-bol) (point-at-eol))))
9590 ;; Only use search option if there is some text.
9591 (when (string-match "\\S-" txt)
9592 (setq cpltxt
9593 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9594 desc "NONE")))
9595 (setq link cpltxt))
9597 ((org-called-interactively-p 'interactive)
9598 (user-error "No method for storing a link from this buffer"))
9600 (t (setq link nil)))
9602 ;; We're done setting link and desc, clean up
9603 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9604 (setq link (or link cpltxt)
9605 desc (or desc cpltxt))
9606 (cond ((equal desc "NONE") (setq desc nil))
9607 ((string-match org-bracket-link-analytic-regexp desc)
9608 (let ((d0 (match-string 3 desc))
9609 (p0 (match-string 5 desc)))
9610 (setq desc
9611 (replace-regexp-in-string
9612 org-bracket-link-regexp
9613 (concat (or p0 d0)
9614 (if (equal (length (match-string 0 desc))
9615 (length desc)) "*" "")) desc)))))
9617 ;; Return the link
9618 (if (not (and (or (org-called-interactively-p 'any)
9619 executing-kbd-macro) link))
9620 (or agenda-link (and link (org-make-link-string link desc)))
9621 (push (list link desc) org-stored-links)
9622 (message "Stored: %s" (or desc link))
9623 (when custom-id
9624 (setq link (concat "file:" (abbreviate-file-name
9625 (buffer-file-name)) "::#" custom-id))
9626 (push (list link desc) org-stored-links)))))))
9628 (defun org-store-link-props (&rest plist)
9629 "Store link properties, extract names and addresses."
9630 (let (x adr)
9631 (when (setq x (plist-get plist :from))
9632 (setq adr (mail-extract-address-components x))
9633 (setq plist (plist-put plist :fromname (car adr)))
9634 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9635 (when (setq x (plist-get plist :to))
9636 (setq adr (mail-extract-address-components x))
9637 (setq plist (plist-put plist :toname (car adr)))
9638 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9639 (let ((from (plist-get plist :from))
9640 (to (plist-get plist :to)))
9641 (when (and from to org-from-is-user-regexp)
9642 (setq plist
9643 (plist-put plist :fromto
9644 (if (string-match org-from-is-user-regexp from)
9645 (concat "to %t")
9646 (concat "from %f"))))))
9647 (setq org-store-link-plist plist))
9649 (defun org-add-link-props (&rest plist)
9650 "Add these properties to the link property list."
9651 (let (key value)
9652 (while plist
9653 (setq key (pop plist) value (pop plist))
9654 (setq org-store-link-plist
9655 (plist-put org-store-link-plist key value)))))
9657 (defun org-email-link-description (&optional fmt)
9658 "Return the description part of an email link.
9659 This takes information from `org-store-link-plist' and formats it
9660 according to FMT (default from `org-email-link-description-format')."
9661 (setq fmt (or fmt org-email-link-description-format))
9662 (let* ((p org-store-link-plist)
9663 (to (plist-get p :toaddress))
9664 (from (plist-get p :fromaddress))
9665 (table
9666 (list
9667 (cons "%c" (plist-get p :fromto))
9668 (cons "%F" (plist-get p :from))
9669 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9670 (cons "%T" (plist-get p :to))
9671 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9672 (cons "%s" (plist-get p :subject))
9673 (cons "%d" (plist-get p :date))
9674 (cons "%m" (plist-get p :message-id)))))
9675 (when (string-match "%c" fmt)
9676 ;; Check if the user wrote this message
9677 (if (and org-from-is-user-regexp from to
9678 (save-match-data (string-match org-from-is-user-regexp from)))
9679 (setq fmt (replace-match "to %t" t t fmt))
9680 (setq fmt (replace-match "from %f" t t fmt))))
9681 (org-replace-escapes fmt table)))
9683 (defun org-make-org-heading-search-string (&optional string)
9684 "Make search string for the current headline or STRING."
9685 (let ((s (or string
9686 (and (derived-mode-p 'org-mode)
9687 (save-excursion
9688 (org-back-to-heading t)
9689 (org-element-property :raw-value (org-element-at-point))))))
9690 (lines org-context-in-file-links))
9691 (or string (setq s (concat "*" s))) ; Add * for headlines
9692 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9693 (when (and string (integerp lines) (> lines 0))
9694 (let ((slines (org-split-string s "\n")))
9695 (when (< lines (length slines))
9696 (setq s (mapconcat
9697 'identity
9698 (reverse (nthcdr (- (length slines) lines)
9699 (reverse slines))) "\n")))))
9700 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9702 (defun org-make-link-string (link &optional description)
9703 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9704 (unless (string-match "\\S-" link)
9705 (error "Empty link"))
9706 (when (and description
9707 (stringp description)
9708 (not (string-match "\\S-" description)))
9709 (setq description nil))
9710 (when (stringp description)
9711 ;; Remove brackets from the description, they are fatal.
9712 (while (string-match "\\[" description)
9713 (setq description (replace-match "{" t t description)))
9714 (while (string-match "\\]" description)
9715 (setq description (replace-match "}" t t description))))
9716 (when (equal link description)
9717 ;; No description needed, it is identical
9718 (setq description nil))
9719 (when (and (not description)
9720 (not (string-match (org-image-file-name-regexp) link))
9721 (not (equal link (org-link-escape link))))
9722 (setq description (org-extract-attributes link)))
9723 (setq link
9724 (cond ((string-match (org-image-file-name-regexp) link) link)
9725 ((string-match org-link-types-re link)
9726 (concat (match-string 1 link)
9727 (org-link-escape (substring link (match-end 1)))))
9728 (t (org-link-escape link))))
9729 (concat "[[" link "]"
9730 (if description (concat "[" description "]") "")
9731 "]"))
9733 (defconst org-link-escape-chars
9734 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9735 "List of characters that should be escaped in link.
9736 This is the list that is used for internal purposes.")
9738 (defconst org-link-escape-chars-browser
9739 '(?\ ?\")
9740 "List of escapes for characters that are problematic in links.
9741 This is the list that is used before handing over to the browser.")
9743 (defun org-link-escape (text &optional table merge)
9744 "Return percent escaped representation of TEXT.
9745 TEXT is a string with the text to escape.
9746 Optional argument TABLE is a list with characters that should be
9747 escaped. When nil, `org-link-escape-chars' is used.
9748 If optional argument MERGE is set, merge TABLE into
9749 `org-link-escape-chars'."
9750 (cond
9751 ((and table merge)
9752 (mapc (lambda (defchr)
9753 (unless (member defchr table)
9754 (setq table (cons defchr table)))) org-link-escape-chars))
9755 ((null table)
9756 (setq table org-link-escape-chars)))
9757 (mapconcat
9758 (lambda (char)
9759 (if (or (member char table)
9760 (and (or (< char 32) (= char 37) (> char 126))
9761 org-url-hexify-p))
9762 (mapconcat (lambda (sequence-element)
9763 (format "%%%.2X" sequence-element))
9764 (or (encode-coding-char char 'utf-8)
9765 (error "Unable to percent escape character: %s"
9766 (char-to-string char))) "")
9767 (char-to-string char))) text ""))
9769 (defun org-link-unescape (str)
9770 "Unhex hexified Unicode strings as returned from the JavaScript function
9771 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9772 (unless (and (null str) (string= "" str))
9773 (let ((pos 0) (case-fold-search t) unhexed)
9774 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9775 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9776 (setq str (replace-match unhexed t t str))
9777 (setq pos (+ pos (length unhexed))))))
9778 str)
9780 (defun org-link-unescape-compound (hex)
9781 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9782 Note: this function also decodes single byte encodings like
9783 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9784 (save-match-data
9785 (let* ((bytes (cdr (split-string hex "%")))
9786 (ret "")
9787 (eat 0)
9788 (sum 0))
9789 (while bytes
9790 (let* ((val (string-to-number (pop bytes) 16))
9791 (shift-xor
9792 (if (= 0 eat)
9793 (cond
9794 ((>= val 252) (cons 6 252))
9795 ((>= val 248) (cons 5 248))
9796 ((>= val 240) (cons 4 240))
9797 ((>= val 224) (cons 3 224))
9798 ((>= val 192) (cons 2 192))
9799 (t (cons 0 0)))
9800 (cons 6 128))))
9801 (if (>= val 192) (setq eat (car shift-xor)))
9802 (setq val (logxor val (cdr shift-xor)))
9803 (setq sum (+ (lsh sum (car shift-xor)) val))
9804 (if (> eat 0) (setq eat (- eat 1)))
9805 (cond
9806 ((= 0 eat) ;multi byte
9807 (setq ret (concat ret (org-char-to-string sum)))
9808 (setq sum 0))
9809 ((not bytes) ; single byte(s)
9810 (setq ret (org-link-unescape-single-byte-sequence hex))))
9811 )) ;; end (while bytes
9812 ret )))
9814 (defun org-link-unescape-single-byte-sequence (hex)
9815 "Unhexify hex-encoded single byte character sequences."
9816 (mapconcat (lambda (byte)
9817 (char-to-string (string-to-number byte 16)))
9818 (cdr (split-string hex "%")) ""))
9820 (defun org-xor (a b)
9821 "Exclusive or."
9822 (if a (not b) b))
9824 (defun org-fixup-message-id-for-http (s)
9825 "Replace special characters in a message id, so it can be used in an http query."
9826 (when (string-match "%" s)
9827 (setq s (mapconcat (lambda (c)
9828 (if (eq c ?%)
9829 "%25"
9830 (char-to-string c)))
9831 s "")))
9832 (while (string-match "<" s)
9833 (setq s (replace-match "%3C" t t s)))
9834 (while (string-match ">" s)
9835 (setq s (replace-match "%3E" t t s)))
9836 (while (string-match "@" s)
9837 (setq s (replace-match "%40" t t s)))
9840 (defun org-link-prettify (link)
9841 "Return a human-readable representation of LINK.
9842 The car of LINK must be a raw link the cdr of LINK must be either
9843 a link description or nil."
9844 (let ((desc (or (cadr link) "<no description>")))
9845 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9846 "<" (car link) ">")))
9848 ;;;###autoload
9849 (defun org-insert-link-global ()
9850 "Insert a link like Org-mode does.
9851 This command can be called in any mode to insert a link in Org-mode syntax."
9852 (interactive)
9853 (org-load-modules-maybe)
9854 (org-run-like-in-org-mode 'org-insert-link))
9856 (defun org-insert-all-links (&optional keep)
9857 "Insert all links in `org-stored-links'."
9858 (interactive "P")
9859 (let ((links (copy-sequence org-stored-links)) l)
9860 (while (setq l (if keep (pop links) (pop org-stored-links)))
9861 (insert "- ")
9862 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9863 (insert "\n"))))
9865 (defun org-link-fontify-links-to-this-file ()
9866 "Fontify links to the current file in `org-stored-links'."
9867 (let ((f (buffer-file-name)) a b)
9868 (setq a (mapcar (lambda(l)
9869 (let ((ll (car l)))
9870 (when (and (string-match "^file:\\(.+\\)::" ll)
9871 (equal f (expand-file-name (match-string 1 ll))))
9872 ll)))
9873 org-stored-links))
9874 (when (featurep 'org-id)
9875 (setq b (mapcar (lambda(l)
9876 (let ((ll (car l)))
9877 (when (and (string-match "^id:\\(.+\\)$" ll)
9878 (equal f (expand-file-name
9879 (or (org-id-find-id-file
9880 (match-string 1 ll)) ""))))
9881 ll)))
9882 org-stored-links)))
9883 (mapcar (lambda(l)
9884 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9885 (delq nil (append a b)))))
9887 (defvar org-link-links-in-this-file nil)
9888 (defun org-insert-link (&optional complete-file link-location default-description)
9889 "Insert a link. At the prompt, enter the link.
9891 Completion can be used to insert any of the link protocol prefixes like
9892 http or ftp in use.
9894 The history can be used to select a link previously stored with
9895 `org-store-link'. When the empty string is entered (i.e. if you just
9896 press RET at the prompt), the link defaults to the most recently
9897 stored link. As SPC triggers completion in the minibuffer, you need to
9898 use M-SPC or C-q SPC to force the insertion of a space character.
9900 You will also be prompted for a description, and if one is given, it will
9901 be displayed in the buffer instead of the link.
9903 If there is already a link at point, this command will allow you to edit link
9904 and description parts.
9906 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9907 be selected using completion. The path to the file will be relative to the
9908 current directory if the file is in the current directory or a subdirectory.
9909 Otherwise, the link will be the absolute path as completed in the minibuffer
9910 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9911 option `org-link-file-path-type'.
9913 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9914 the current directory or below.
9916 With three \\[universal-argument] prefixes, negate the meaning of
9917 `org-keep-stored-link-after-insertion'.
9919 If `org-make-link-description-function' is non-nil, this function will be
9920 called with the link target, and the result will be the default
9921 link description.
9923 If the LINK-LOCATION parameter is non-nil, this value will be
9924 used as the link location instead of reading one interactively.
9926 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9927 be used as the default description."
9928 (interactive "P")
9929 (let* ((wcf (current-window-configuration))
9930 (origbuf (current-buffer))
9931 (region (if (org-region-active-p)
9932 (buffer-substring (region-beginning) (region-end))))
9933 (remove (and region (list (region-beginning) (region-end))))
9934 (desc region)
9935 tmphist ; byte-compile incorrectly complains about this
9936 (link link-location)
9937 (abbrevs org-link-abbrev-alist-local)
9938 entry file all-prefixes auto-desc)
9939 (cond
9940 (link-location) ; specified by arg, just use it.
9941 ((org-in-regexp org-bracket-link-regexp 1)
9942 ;; We do have a link at point, and we are going to edit it.
9943 (setq remove (list (match-beginning 0) (match-end 0)))
9944 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9945 (setq link (read-string "Link: "
9946 (org-link-unescape
9947 (org-match-string-no-properties 1)))))
9948 ((or (org-in-regexp org-angle-link-re)
9949 (org-in-regexp org-plain-link-re))
9950 ;; Convert to bracket link
9951 (setq remove (list (match-beginning 0) (match-end 0))
9952 link (read-string "Link: "
9953 (org-remove-angle-brackets (match-string 0)))))
9954 ((member complete-file '((4) (16)))
9955 ;; Completing read for file names.
9956 (setq link (org-file-complete-link complete-file)))
9958 ;; Read link, with completion for stored links.
9959 (org-link-fontify-links-to-this-file)
9960 (org-switch-to-buffer-other-window "*Org Links*")
9961 (with-current-buffer "*Org Links*"
9962 (erase-buffer)
9963 (insert "Insert a link.
9964 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9965 (when org-stored-links
9966 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9967 (insert (mapconcat 'org-link-prettify
9968 (reverse org-stored-links) "\n")))
9969 (goto-char (point-min)))
9970 (let ((cw (selected-window)))
9971 (select-window (get-buffer-window "*Org Links*" 'visible))
9972 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9973 (unless (pos-visible-in-window-p (point-max))
9974 (org-fit-window-to-buffer))
9975 (and (window-live-p cw) (select-window cw)))
9976 ;; Fake a link history, containing the stored links.
9977 (setq tmphist (append (mapcar 'car org-stored-links)
9978 org-insert-link-history))
9979 (setq all-prefixes (append (mapcar 'car abbrevs)
9980 (mapcar 'car org-link-abbrev-alist)
9981 org-link-types))
9982 (unwind-protect
9983 (progn
9984 (setq link
9985 (org-completing-read
9986 "Link: "
9987 (append
9988 (mapcar (lambda (x) (concat x ":"))
9989 all-prefixes)
9990 (mapcar 'car org-stored-links))
9991 nil nil nil
9992 'tmphist
9993 (caar org-stored-links)))
9994 (if (not (string-match "\\S-" link))
9995 (user-error "No link selected"))
9996 (mapc (lambda(l)
9997 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9998 org-stored-links)
9999 (if (or (member link all-prefixes)
10000 (and (equal ":" (substring link -1))
10001 (member (substring link 0 -1) all-prefixes)
10002 (setq link (substring link 0 -1))))
10003 (setq link (with-current-buffer origbuf
10004 (org-link-try-special-completion link)))))
10005 (set-window-configuration wcf)
10006 (kill-buffer "*Org Links*"))
10007 (setq entry (assoc link org-stored-links))
10008 (or entry (push link org-insert-link-history))
10009 (setq desc (or desc (nth 1 entry)))))
10011 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10012 (not org-keep-stored-link-after-insertion))
10013 (setq org-stored-links (delq (assoc link org-stored-links)
10014 org-stored-links)))
10016 (if (string-match org-plain-link-re link)
10017 ;; URL-like link, normalize the use of angular brackets.
10018 (setq link (org-remove-angle-brackets link)))
10020 ;; Check if we are linking to the current file with a search
10021 ;; option If yes, simplify the link by using only the search
10022 ;; option.
10023 (when (and buffer-file-name
10024 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10025 (let* ((path (match-string 1 link))
10026 (case-fold-search nil)
10027 (search (match-string 2 link)))
10028 (save-match-data
10029 (if (equal (file-truename buffer-file-name) (file-truename path))
10030 ;; We are linking to this same file, with a search option
10031 (setq link search)))))
10033 ;; Check if we can/should use a relative path. If yes, simplify the link
10034 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10035 (let* ((type (match-string 1 link))
10036 (path (match-string 2 link))
10037 (origpath path)
10038 (case-fold-search nil))
10039 (cond
10040 ((or (eq org-link-file-path-type 'absolute)
10041 (equal complete-file '(16)))
10042 (setq path (abbreviate-file-name (expand-file-name path))))
10043 ((eq org-link-file-path-type 'noabbrev)
10044 (setq path (expand-file-name path)))
10045 ((eq org-link-file-path-type 'relative)
10046 (setq path (file-relative-name path)))
10048 (save-match-data
10049 (if (string-match (concat "^" (regexp-quote
10050 (expand-file-name
10051 (file-name-as-directory
10052 default-directory))))
10053 (expand-file-name path))
10054 ;; We are linking a file with relative path name.
10055 (setq path (substring (expand-file-name path)
10056 (match-end 0)))
10057 (setq path (abbreviate-file-name (expand-file-name path)))))))
10058 (setq link (concat type path))
10059 (if (equal desc origpath)
10060 (setq desc path))))
10062 (if org-make-link-description-function
10063 (setq desc
10064 (or (condition-case nil
10065 (funcall org-make-link-description-function link desc)
10066 (error (progn (message "Can't get link description from `%s'"
10067 (symbol-name org-make-link-description-function))
10068 (sit-for 2) nil)))
10069 (read-string "Description: " default-description)))
10070 (if default-description (setq desc default-description)
10071 (setq desc (or (and auto-desc desc)
10072 (read-string "Description: " desc)))))
10074 (unless (string-match "\\S-" desc) (setq desc nil))
10075 (if remove (apply 'delete-region remove))
10076 (insert (org-make-link-string link desc))))
10078 (defun org-link-try-special-completion (type)
10079 "If there is completion support for link type TYPE, offer it."
10080 (let ((fun (intern (concat "org-" type "-complete-link"))))
10081 (if (functionp fun)
10082 (funcall fun)
10083 (read-string "Link (no completion support): " (concat type ":")))))
10085 (defun org-file-complete-link (&optional arg)
10086 "Create a file link using completion."
10087 (let (file link)
10088 (setq file (org-iread-file-name "File: "))
10089 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10090 (pwd1 (file-name-as-directory (abbreviate-file-name
10091 (expand-file-name ".")))))
10092 (cond
10093 ((equal arg '(16))
10094 (setq link (concat
10095 "file:"
10096 (abbreviate-file-name (expand-file-name file)))))
10097 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10098 (setq link (concat "file:" (match-string 1 file))))
10099 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10100 (expand-file-name file))
10101 (setq link (concat
10102 "file:" (match-string 1 (expand-file-name file)))))
10103 (t (setq link (concat "file:" file)))))
10104 link))
10106 (defun org-iread-file-name (&rest args)
10107 "Read-file-name using `ido-mode' speedup if available.
10108 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10109 See `read-file-name' for a description of parameters."
10110 (org-without-partial-completion
10111 (if (and org-completion-use-ido
10112 (fboundp 'ido-read-file-name)
10113 (boundp 'ido-mode) ido-mode
10114 (listp (second args)))
10115 (let ((ido-enter-matching-directory nil))
10116 (apply 'ido-read-file-name args))
10117 (apply 'read-file-name args))))
10119 (defun org-completing-read (&rest args)
10120 "Completing-read with SPACE being a normal character."
10121 (let ((enable-recursive-minibuffers t)
10122 (minibuffer-local-completion-map
10123 (copy-keymap minibuffer-local-completion-map)))
10124 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10125 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10126 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10127 (apply 'org-icompleting-read args)))
10129 (defun org-completing-read-no-i (&rest args)
10130 (let (org-completion-use-ido org-completion-use-iswitchb)
10131 (apply 'org-completing-read args)))
10133 (defun org-iswitchb-completing-read (prompt choices &rest args)
10134 "Use iswitch as a completing-read replacement to choose from choices.
10135 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10136 from."
10137 (let* ((iswitchb-use-virtual-buffers nil)
10138 (iswitchb-make-buflist-hook
10139 (lambda ()
10140 (setq iswitchb-temp-buflist choices))))
10141 (iswitchb-read-buffer prompt)))
10143 (defun org-icompleting-read (&rest args)
10144 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10145 (org-without-partial-completion
10146 (if (and org-completion-use-ido
10147 (fboundp 'ido-completing-read)
10148 (boundp 'ido-mode) ido-mode
10149 (listp (second args)))
10150 (let ((ido-enter-matching-directory nil))
10151 (apply 'ido-completing-read (concat (car args))
10152 (if (consp (car (nth 1 args)))
10153 (mapcar 'car (nth 1 args))
10154 (nth 1 args))
10155 (cddr args)))
10156 (if (and org-completion-use-iswitchb
10157 (boundp 'iswitchb-mode) iswitchb-mode
10158 (listp (second args)))
10159 (apply 'org-iswitchb-completing-read (concat (car args))
10160 (if (consp (car (nth 1 args)))
10161 (mapcar 'car (nth 1 args))
10162 (nth 1 args))
10163 (cddr args))
10164 (apply 'completing-read args)))))
10166 (defun org-extract-attributes (s)
10167 "Extract the attributes cookie from a string and set as text property."
10168 (let (a attr (start 0) key value)
10169 (save-match-data
10170 (when (string-match "{{\\([^}]+\\)}}$" s)
10171 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10172 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10173 (setq key (match-string 1 a) value (match-string 2 a)
10174 start (match-end 0)
10175 attr (plist-put attr (intern key) value))))
10176 (org-add-props s nil 'org-attr attr))
10179 ;;; Opening/following a link
10181 (defvar org-link-search-failed nil)
10183 (defvar org-open-link-functions nil
10184 "Hook for functions finding a plain text link.
10185 These functions must take a single argument, the link content.
10186 They will be called for links that look like [[link text][description]]
10187 when LINK TEXT does not have a protocol like \"http:\" and does not look
10188 like a filename (e.g. \"./blue.png\").
10190 These functions will be called *before* Org attempts to resolve the
10191 link by doing text searches in the current buffer - so if you want a
10192 link \"[[target]]\" to still find \"<<target>>\", your function should
10193 handle this as a special case.
10195 When the function does handle the link, it must return a non-nil value.
10196 If it decides that it is not responsible for this link, it must return
10197 nil to indicate that that Org-mode can continue with other options
10198 like exact and fuzzy text search.")
10200 (defun org-next-link (&optional search-backward)
10201 "Move forward to the next link.
10202 If the link is in hidden text, expose it."
10203 (interactive "P")
10204 (when (and org-link-search-failed (eq this-command last-command))
10205 (goto-char (point-min))
10206 (message "Link search wrapped back to beginning of buffer"))
10207 (setq org-link-search-failed nil)
10208 (let* ((pos (point))
10209 (ct (org-context))
10210 (a (assoc :link ct))
10211 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10212 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10213 ((looking-at org-any-link-re)
10214 ;; Don't stay stuck at link without an org-link face
10215 (forward-char (if search-backward -1 1))))
10216 (if (funcall srch-fun org-any-link-re nil t)
10217 (progn
10218 (goto-char (match-beginning 0))
10219 (if (outline-invisible-p) (org-show-context)))
10220 (goto-char pos)
10221 (setq org-link-search-failed t)
10222 (message "No further link found"))))
10224 (defun org-previous-link ()
10225 "Move backward to the previous link.
10226 If the link is in hidden text, expose it."
10227 (interactive)
10228 (funcall 'org-next-link t))
10230 (defun org-translate-link (s)
10231 "Translate a link string if a translation function has been defined."
10232 (if (and org-link-translation-function
10233 (fboundp org-link-translation-function)
10234 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10235 (progn
10236 (setq s (funcall org-link-translation-function
10237 (match-string 1 s) (match-string 2 s)))
10238 (concat (car s) ":" (cdr s)))
10241 (defun org-translate-link-from-planner (type path)
10242 "Translate a link from Emacs Planner syntax so that Org can follow it.
10243 This is still an experimental function, your mileage may vary."
10244 (cond
10245 ((member type '("http" "https" "news" "ftp"))
10246 ;; standard Internet links are the same.
10247 nil)
10248 ((and (equal type "irc") (string-match "^//" path))
10249 ;; Planner has two / at the beginning of an irc link, we have 1.
10250 ;; We should have zero, actually....
10251 (setq path (substring path 1)))
10252 ((and (equal type "lisp") (string-match "^/" path))
10253 ;; Planner has a slash, we do not.
10254 (setq type "elisp" path (substring path 1)))
10255 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10256 ;; A typical message link. Planner has the id after the final slash,
10257 ;; we separate it with a hash mark
10258 (setq path (concat (match-string 1 path) "#"
10259 (org-remove-angle-brackets (match-string 2 path))))))
10260 (cons type path))
10262 (defun org-find-file-at-mouse (ev)
10263 "Open file link or URL at mouse."
10264 (interactive "e")
10265 (mouse-set-point ev)
10266 (org-open-at-point 'in-emacs))
10268 (defun org-open-at-mouse (ev)
10269 "Open file link or URL at mouse.
10270 See the docstring of `org-open-file' for details."
10271 (interactive "e")
10272 (mouse-set-point ev)
10273 (if (eq major-mode 'org-agenda-mode)
10274 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10275 (org-open-at-point))
10277 (defvar org-window-config-before-follow-link nil
10278 "The window configuration before following a link.
10279 This is saved in case the need arises to restore it.")
10281 (defvar org-open-link-marker (make-marker)
10282 "Marker pointing to the location where `org-open-at-point; was called.")
10284 ;;;###autoload
10285 (defun org-open-at-point-global ()
10286 "Follow a link like Org-mode does.
10287 This command can be called in any mode to follow a link that has
10288 Org-mode syntax."
10289 (interactive)
10290 (org-run-like-in-org-mode 'org-open-at-point))
10292 ;;;###autoload
10293 (defun org-open-link-from-string (s &optional arg reference-buffer)
10294 "Open a link in the string S, as if it was in Org-mode."
10295 (interactive "sLink: \nP")
10296 (let ((reference-buffer (or reference-buffer (current-buffer))))
10297 (with-temp-buffer
10298 (let ((org-inhibit-startup (not reference-buffer)))
10299 (org-mode)
10300 (insert s)
10301 (goto-char (point-min))
10302 (when reference-buffer
10303 (setq org-link-abbrev-alist-local
10304 (with-current-buffer reference-buffer
10305 org-link-abbrev-alist-local)))
10306 (org-open-at-point arg reference-buffer)))))
10308 (defvar org-open-at-point-functions nil
10309 "Hook that is run when following a link at point.
10311 Functions in this hook must return t if they identify and follow
10312 a link at point. If they don't find anything interesting at point,
10313 they must return nil.")
10315 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10316 (defun org-open-at-point (&optional arg reference-buffer)
10317 "Open link at or after point.
10318 If there is no link at point, this function will search forward up to
10319 the end of the current line.
10320 Normally, files will be opened by an appropriate application. If the
10321 optional prefix argument ARG is non-nil, Emacs will visit the file.
10322 With a double prefix argument, try to open outside of Emacs, in the
10323 application the system uses for this file type."
10324 (interactive "P")
10325 ;; if in a code block, then open the block's results
10326 (unless (call-interactively #'org-babel-open-src-block-result)
10327 (org-load-modules-maybe)
10328 (move-marker org-open-link-marker (point))
10329 (setq org-window-config-before-follow-link (current-window-configuration))
10330 (org-remove-occur-highlights nil nil t)
10331 (cond
10332 ((and (org-at-heading-p)
10333 (not (org-at-timestamp-p t))
10334 (not (org-in-regexp
10335 (concat org-plain-link-re "\\|"
10336 org-bracket-link-regexp "\\|"
10337 org-angle-link-re "\\|"
10338 "[ \t]:[^ \t\n]+:[ \t]*$")))
10339 (not (get-text-property (point) 'org-linked-text)))
10340 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10341 (lk0 (car lkall))
10342 (lk (if (stringp lk0) (list lk0) lk0))
10343 (lkend (cdr lkall)))
10344 (mapcar (lambda(l)
10345 (search-forward l nil lkend)
10346 (goto-char (match-beginning 0))
10347 (org-open-at-point))
10348 lk))
10349 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10350 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10351 ((and (org-at-timestamp-p t)
10352 (not (org-in-regexp org-bracket-link-regexp)))
10353 (org-follow-timestamp-link))
10354 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10355 (not (org-in-regexp org-any-link-re)))
10356 (org-footnote-action))
10358 (let (type path link line search (pos (point)))
10359 (catch 'match
10360 (save-excursion
10361 (skip-chars-forward "^]\n\r")
10362 (when (org-in-regexp org-bracket-link-regexp 1)
10363 (setq link (org-extract-attributes
10364 (org-link-unescape (org-match-string-no-properties 1))))
10365 (while (string-match " *\n *" link)
10366 (setq link (replace-match " " t t link)))
10367 (setq link (org-link-expand-abbrev link))
10368 (cond
10369 ((or (file-name-absolute-p link)
10370 (string-match "^\\.\\.?/" link))
10371 (setq type "file" path link))
10372 ((string-match org-link-re-with-space3 link)
10373 (setq type (match-string 1 link) path (match-string 2 link)))
10374 ((string-match "^help:+\\(.+\\)" link)
10375 (setq type "help" path (match-string 1 link)))
10376 (t (setq type "thisfile" path link)))
10377 (throw 'match t)))
10379 (when (get-text-property (point) 'org-linked-text)
10380 (setq type "thisfile"
10381 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10382 (1+ (point)) (point))
10383 path (buffer-substring
10384 (or (previous-single-property-change pos 'org-linked-text)
10385 (point-min))
10386 (or (next-single-property-change pos 'org-linked-text)
10387 (point-max)))
10388 ;; Ensure we will search for a <<<radio>>> link, not
10389 ;; a simple reference like <<ref>>
10390 path (concat "<" path))
10391 (throw 'match t))
10393 (save-excursion
10394 (when (or (org-in-regexp org-angle-link-re)
10395 (let ((match (org-in-regexp org-plain-link-re)))
10396 ;; Check a plain link is not within a bracket link
10397 (and match
10398 (save-excursion
10399 (progn
10400 (goto-char (car match))
10401 (not (org-in-regexp org-bracket-link-regexp))))))
10402 (let ((line_ending (save-excursion (end-of-line) (point))))
10403 ;; We are in a line before a plain or bracket link
10404 (or (re-search-forward org-plain-link-re line_ending t)
10405 (re-search-forward org-bracket-link-regexp line_ending t))))
10406 (setq type (match-string 1)
10407 path (org-link-unescape (match-string 2)))
10408 (throw 'match t)))
10409 (save-excursion
10410 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10411 (setq type "tags"
10412 path (match-string 1))
10413 (while (string-match ":" path)
10414 (setq path (replace-match "+" t t path)))
10415 (throw 'match t)))
10416 (when (org-in-regexp "<\\([^><\n]+\\)>")
10417 (setq type "tree-match"
10418 path (match-string 1))
10419 (throw 'match t)))
10420 (unless path
10421 (user-error "No link found"))
10423 ;; switch back to reference buffer
10424 ;; needed when if called in a temporary buffer through
10425 ;; org-open-link-from-string
10426 (with-current-buffer (or reference-buffer (current-buffer))
10428 ;; Remove any trailing spaces in path
10429 (if (string-match " +\\'" path)
10430 (setq path (replace-match "" t t path)))
10431 (if (and org-link-translation-function
10432 (fboundp org-link-translation-function))
10433 ;; Check if we need to translate the link
10434 (let ((tmp (funcall org-link-translation-function type path)))
10435 (setq type (car tmp) path (cdr tmp))))
10437 (cond
10439 ((assoc type org-link-protocols)
10440 (funcall (nth 1 (assoc type org-link-protocols)) path))
10442 ((equal type "help")
10443 (let ((f-or-v (intern path)))
10444 (cond ((fboundp f-or-v)
10445 (describe-function f-or-v))
10446 ((boundp f-or-v)
10447 (describe-variable f-or-v))
10448 (t (error "Not a known function or variable")))))
10450 ((equal type "mailto")
10451 (let ((cmd (car org-link-mailto-program))
10452 (args (cdr org-link-mailto-program)) args1
10453 (address path) (subject "") a)
10454 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10455 (setq address (match-string 1 path)
10456 subject (org-link-escape (match-string 2 path))))
10457 (while args
10458 (cond
10459 ((not (stringp (car args))) (push (pop args) args1))
10460 (t (setq a (pop args))
10461 (if (string-match "%a" a)
10462 (setq a (replace-match address t t a)))
10463 (if (string-match "%s" a)
10464 (setq a (replace-match subject t t a)))
10465 (push a args1))))
10466 (apply cmd (nreverse args1))))
10468 ((member type '("http" "https" "ftp" "news"))
10469 (browse-url
10470 (concat type ":"
10471 (if (org-string-match-p
10472 (concat "[[:nonascii:]"
10473 org-link-escape-chars-browser "]")
10474 path)
10475 (org-link-escape path org-link-escape-chars-browser)
10476 path))))
10478 ((string= type "doi")
10479 (browse-url
10480 (concat org-doi-server-url
10481 (if (org-string-match-p
10482 (concat "[[:nonascii:]"
10483 org-link-escape-chars-browser "]")
10484 path)
10485 (org-link-escape path org-link-escape-chars-browser)
10486 path))))
10488 ((member type '("message"))
10489 (browse-url (concat type ":" path)))
10491 ((string= type "tags")
10492 (org-tags-view arg path))
10494 ((string= type "tree-match")
10495 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10497 ((string= type "file")
10498 (if (string-match "::\\([0-9]+\\)\\'" path)
10499 (setq line (string-to-number (match-string 1 path))
10500 path (substring path 0 (match-beginning 0)))
10501 (if (string-match "::\\(.+\\)\\'" path)
10502 (setq search (match-string 1 path)
10503 path (substring path 0 (match-beginning 0)))))
10504 (if (string-match "[*?{]" (file-name-nondirectory path))
10505 (dired path)
10506 (org-open-file path arg line search)))
10508 ((string= type "shell")
10509 (let ((buf (generate-new-buffer "*Org Shell Output"))
10510 (cmd path))
10511 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10512 (string-match org-confirm-shell-link-not-regexp cmd))
10513 (not org-confirm-shell-link-function)
10514 (funcall org-confirm-shell-link-function
10515 (format "Execute \"%s\" in shell? "
10516 (org-add-props cmd nil
10517 'face 'org-warning))))
10518 (progn
10519 (message "Executing %s" cmd)
10520 (shell-command cmd buf)
10521 (if (featurep 'midnight)
10522 (setq clean-buffer-list-kill-buffer-names
10523 (cons buf clean-buffer-list-kill-buffer-names))))
10524 (error "Abort"))))
10526 ((string= type "elisp")
10527 (let ((cmd path))
10528 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10529 (string-match org-confirm-elisp-link-not-regexp cmd))
10530 (not org-confirm-elisp-link-function)
10531 (funcall org-confirm-elisp-link-function
10532 (format "Execute \"%s\" as elisp? "
10533 (org-add-props cmd nil
10534 'face 'org-warning))))
10535 (message "%s => %s" cmd
10536 (if (equal (string-to-char cmd) ?\()
10537 (eval (read cmd))
10538 (call-interactively (read cmd))))
10539 (error "Abort"))))
10541 ((and (string= type "thisfile")
10542 (run-hook-with-args-until-success
10543 'org-open-link-functions path)))
10545 ((string= type "thisfile")
10546 (if arg
10547 (switch-to-buffer-other-window
10548 (org-get-buffer-for-internal-link (current-buffer)))
10549 (org-mark-ring-push))
10550 (let ((cmd `(org-link-search
10551 ,path
10552 ,(cond ((equal arg '(4)) ''occur)
10553 ((equal arg '(16)) ''org-occur))
10554 ,pos)))
10555 (condition-case nil (let ((org-link-search-inhibit-query t))
10556 (eval cmd))
10557 (error (progn (widen) (eval cmd))))))
10559 (t (browse-url-at-point)))))))
10560 (move-marker org-open-link-marker nil)
10561 (run-hook-with-args 'org-follow-link-hook)))
10563 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10564 "Offer links in the current entry and return the selected link.
10565 If there is only one link, return it.
10566 If NTH is an integer, return the NTH link found.
10567 If ZERO is a string, check also this string for a link, and if
10568 there is one, return it."
10569 (with-current-buffer buffer
10570 (save-excursion
10571 (save-restriction
10572 (widen)
10573 (goto-char marker)
10574 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10575 "\\(" org-angle-link-re "\\)\\|"
10576 "\\(" org-plain-link-re "\\)"))
10577 (cnt ?0)
10578 (in-emacs (if (integerp nth) nil nth))
10579 have-zero end links link c)
10580 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10581 (push (match-string 0 zero) links)
10582 (setq cnt (1- cnt) have-zero t))
10583 (save-excursion
10584 (org-back-to-heading t)
10585 (setq end (save-excursion (outline-next-heading) (point)))
10586 (while (re-search-forward re end t)
10587 (push (match-string 0) links))
10588 (setq links (org-uniquify (reverse links))))
10589 (cond
10590 ((null links)
10591 (message "No links"))
10592 ((equal (length links) 1)
10593 (setq link (car links)))
10594 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10595 (setq link (nth (if have-zero nth (1- nth)) links)))
10596 (t ; we have to select a link
10597 (save-excursion
10598 (save-window-excursion
10599 (delete-other-windows)
10600 (with-output-to-temp-buffer "*Select Link*"
10601 (mapc (lambda (l)
10602 (if (not (string-match org-bracket-link-regexp l))
10603 (princ (format "[%c] %s\n" (incf cnt)
10604 (org-remove-angle-brackets l)))
10605 (if (match-end 3)
10606 (princ (format "[%c] %s (%s)\n" (incf cnt)
10607 (match-string 3 l) (match-string 1 l)))
10608 (princ (format "[%c] %s\n" (incf cnt)
10609 (match-string 1 l))))))
10610 links))
10611 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10612 (message "Select link to open, RET to open all:")
10613 (setq c (read-char-exclusive))
10614 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10615 (when (equal c ?q) (error "Abort"))
10616 (if (equal c ?\C-m)
10617 (setq link links)
10618 (setq nth (- c ?0))
10619 (if have-zero (setq nth (1+ nth)))
10620 (unless (and (integerp nth) (>= (length links) nth))
10621 (user-error "Invalid link selection"))
10622 (setq link (nth (1- nth) links)))))
10623 (cons link end))))))
10625 ;; Add special file links that specify the way of opening
10627 (org-add-link-type "file+sys" 'org-open-file-with-system)
10628 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10629 (defun org-open-file-with-system (path)
10630 "Open file at PATH using the system way of opening it."
10631 (org-open-file path 'system))
10632 (defun org-open-file-with-emacs (path)
10633 "Open file at PATH in Emacs."
10634 (org-open-file path 'emacs))
10637 ;;; File search
10639 (defvar org-create-file-search-functions nil
10640 "List of functions to construct the right search string for a file link.
10641 These functions are called in turn with point at the location to
10642 which the link should point.
10644 A function in the hook should first test if it would like to
10645 handle this file type, for example by checking the `major-mode'
10646 or the file extension. If it decides not to handle this file, it
10647 should just return nil to give other functions a chance. If it
10648 does handle the file, it must return the search string to be used
10649 when following the link. The search string will be part of the
10650 file link, given after a double colon, and `org-open-at-point'
10651 will automatically search for it. If special measures must be
10652 taken to make the search successful, another function should be
10653 added to the companion hook `org-execute-file-search-functions',
10654 which see.
10656 A function in this hook may also use `setq' to set the variable
10657 `description' to provide a suggestion for the descriptive text to
10658 be used for this link when it gets inserted into an Org-mode
10659 buffer with \\[org-insert-link].")
10661 (defvar org-execute-file-search-functions nil
10662 "List of functions to execute a file search triggered by a link.
10664 Functions added to this hook must accept a single argument, the
10665 search string that was part of the file link, the part after the
10666 double colon. The function must first check if it would like to
10667 handle this search, for example by checking the `major-mode' or
10668 the file extension. If it decides not to handle this search, it
10669 should just return nil to give other functions a chance. If it
10670 does handle the search, it must return a non-nil value to keep
10671 other functions from trying.
10673 Each function can access the current prefix argument through the
10674 variable `current-prefix-arg'. Note that a single prefix is used
10675 to force opening a link in Emacs, so it may be good to only use a
10676 numeric or double prefix to guide the search function.
10678 In case this is needed, a function in this hook can also restore
10679 the window configuration before `org-open-at-point' was called using:
10681 (set-window-configuration org-window-config-before-follow-link)")
10683 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10684 (defun org-link-search (s &optional type avoid-pos stealth)
10685 "Search for a link search option.
10686 If S is surrounded by forward slashes, it is interpreted as a
10687 regular expression. In org-mode files, this will create an `org-occur'
10688 sparse tree. In ordinary files, `occur' will be used to list matches.
10689 If the current buffer is in `dired-mode', grep will be used to search
10690 in all files. If AVOID-POS is given, ignore matches near that position.
10692 When optional argument STEALTH is non-nil, do not modify
10693 visibility around point, thus ignoring
10694 `org-show-hierarchy-above', `org-show-following-heading' and
10695 `org-show-siblings' variables."
10696 (let ((case-fold-search t)
10697 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10698 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10699 (append '(("") (" ") ("\t") ("\n"))
10700 org-emphasis-alist)
10701 "\\|") "\\)"))
10702 (pos (point))
10703 (pre nil) (post nil)
10704 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10705 (cond
10706 ;; First check if there are any special search functions
10707 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10708 ;; Now try the builtin stuff
10709 ((and (equal (string-to-char s0) ?#)
10710 (> (length s0) 1)
10711 (save-excursion
10712 (goto-char (point-min))
10713 (and
10714 (re-search-forward
10715 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10716 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10717 (setq type 'dedicated
10718 pos (match-beginning 0))))
10719 ;; There is an exact target for this
10720 (goto-char pos)
10721 (org-back-to-heading t)))
10722 ((save-excursion
10723 (goto-char (point-min))
10724 (and
10725 (re-search-forward
10726 (concat "<<" (regexp-quote s0) ">>") nil t)
10727 (setq type 'dedicated
10728 pos (match-beginning 0))))
10729 ;; There is an exact target for this
10730 (goto-char pos))
10731 ((save-excursion
10732 (goto-char (point-min))
10733 (and
10734 (re-search-forward
10735 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10736 (setq type 'dedicated pos (match-beginning 0))))
10737 ;; Found an element with a matching #+name affiliated keyword.
10738 (goto-char pos))
10739 ((and (string-match "^(\\(.*\\))$" s0)
10740 (save-excursion
10741 (goto-char (point-min))
10742 (and
10743 (re-search-forward
10744 (concat "[^[]" (regexp-quote
10745 (format org-coderef-label-format
10746 (match-string 1 s0))))
10747 nil t)
10748 (setq type 'dedicated
10749 pos (1+ (match-beginning 0))))))
10750 ;; There is a coderef target for this
10751 (goto-char pos))
10752 ((string-match "^/\\(.*\\)/$" s)
10753 ;; A regular expression
10754 (cond
10755 ((derived-mode-p 'org-mode)
10756 (org-occur (match-string 1 s)))
10757 (t (org-do-occur (match-string 1 s)))))
10758 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10759 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10760 (goto-char (point-min))
10761 (cond
10762 ((let (case-fold-search)
10763 (re-search-forward (format org-complex-heading-regexp-format
10764 (regexp-quote s))
10765 nil t))
10766 ;; OK, found a match
10767 (setq type 'dedicated)
10768 (goto-char (match-beginning 0)))
10769 ((and (not org-link-search-inhibit-query)
10770 (eq org-link-search-must-match-exact-headline 'query-to-create)
10771 (y-or-n-p "No match - create this as a new heading? "))
10772 (goto-char (point-max))
10773 (or (bolp) (newline))
10774 (insert "* " s "\n")
10775 (beginning-of-line 0))
10777 (goto-char pos)
10778 (error "No match"))))
10780 ;; A normal search string
10781 (when (equal (string-to-char s) ?*)
10782 ;; Anchor on headlines, post may include tags.
10783 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10784 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10785 s (substring s 1)))
10786 (remove-text-properties
10787 0 (length s)
10788 '(face nil mouse-face nil keymap nil fontified nil) s)
10789 ;; Make a series of regular expressions to find a match
10790 (setq words (org-split-string s "[ \n\r\t]+")
10792 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10793 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10794 "\\)" markers)
10795 re2a_ (concat "\\(" (mapconcat 'downcase words
10796 "[ \t\r\n]+") "\\)[ \t\r\n]")
10797 re2a (concat "[ \t\r\n]" re2a_)
10798 re4_ (concat "\\(" (mapconcat 'downcase words
10799 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10800 re4 (concat "[^a-zA-Z_]" re4_)
10802 re1 (concat pre re2 post)
10803 re3 (concat pre (if pre re4_ re4) post)
10804 re5 (concat pre ".*" re4)
10805 re2 (concat pre re2)
10806 re2a (concat pre (if pre re2a_ re2a))
10807 re4 (concat pre (if pre re4_ re4))
10808 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10809 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10810 re5 "\\)"))
10811 (cond
10812 ((eq type 'org-occur) (org-occur reall))
10813 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10814 (t (goto-char (point-min))
10815 (setq type 'fuzzy)
10816 (if (or (and (org-search-not-self 1 re0 nil t)
10817 (setq type 'dedicated))
10818 (org-search-not-self 1 re1 nil t)
10819 (org-search-not-self 1 re2 nil t)
10820 (org-search-not-self 1 re2a nil t)
10821 (org-search-not-self 1 re3 nil t)
10822 (org-search-not-self 1 re4 nil t)
10823 (org-search-not-self 1 re5 nil t))
10824 (goto-char (match-beginning 1))
10825 (goto-char pos)
10826 (error "No match"))))))
10827 (and (derived-mode-p 'org-mode)
10828 (not stealth)
10829 (org-show-context 'link-search))
10830 type))
10832 (defun org-search-not-self (group &rest args)
10833 "Execute `re-search-forward', but only accept matches that do not
10834 enclose the position of `org-open-link-marker'."
10835 (let ((m org-open-link-marker))
10836 (catch 'exit
10837 (while (apply 're-search-forward args)
10838 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10839 (goto-char (match-end group))
10840 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10841 (> (match-beginning 0) (marker-position m))
10842 (< (match-end 0) (marker-position m)))
10843 (save-match-data
10844 (or (not (org-in-regexp
10845 org-bracket-link-analytic-regexp 1))
10846 (not (match-end 4)) ; no description
10847 (and (<= (match-beginning 4) (point))
10848 (>= (match-end 4) (point))))))
10849 (throw 'exit (point))))))))
10851 (defun org-get-buffer-for-internal-link (buffer)
10852 "Return a buffer to be used for displaying the link target of internal links."
10853 (cond
10854 ((not org-display-internal-link-with-indirect-buffer)
10855 buffer)
10856 ((string-match "(Clone)$" (buffer-name buffer))
10857 (message "Buffer is already a clone, not making another one")
10858 ;; we also do not modify visibility in this case
10859 buffer)
10860 (t ; make a new indirect buffer for displaying the link
10861 (let* ((bn (buffer-name buffer))
10862 (ibn (concat bn "(Clone)"))
10863 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10864 (with-current-buffer ib (org-overview))
10865 ib))))
10867 (defun org-do-occur (regexp &optional cleanup)
10868 "Call the Emacs command `occur'.
10869 If CLEANUP is non-nil, remove the printout of the regular expression
10870 in the *Occur* buffer. This is useful if the regex is long and not useful
10871 to read."
10872 (occur regexp)
10873 (when cleanup
10874 (let ((cwin (selected-window)) win beg end)
10875 (when (setq win (get-buffer-window "*Occur*"))
10876 (select-window win))
10877 (goto-char (point-min))
10878 (when (re-search-forward "match[a-z]+" nil t)
10879 (setq beg (match-end 0))
10880 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10881 (setq end (1- (match-beginning 0)))))
10882 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10883 (goto-char (point-min))
10884 (select-window cwin))))
10886 ;;; The mark ring for links jumps
10888 (defvar org-mark-ring nil
10889 "Mark ring for positions before jumps in Org-mode.")
10890 (defvar org-mark-ring-last-goto nil
10891 "Last position in the mark ring used to go back.")
10892 ;; Fill and close the ring
10893 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10894 (loop for i from 1 to org-mark-ring-length do
10895 (push (make-marker) org-mark-ring))
10896 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10897 org-mark-ring)
10899 (defun org-mark-ring-push (&optional pos buffer)
10900 "Put the current position or POS into the mark ring and rotate it."
10901 (interactive)
10902 (setq pos (or pos (point)))
10903 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10904 (move-marker (car org-mark-ring)
10905 (or pos (point))
10906 (or buffer (current-buffer)))
10907 (message "%s"
10908 (substitute-command-keys
10909 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10911 (defun org-mark-ring-goto (&optional n)
10912 "Jump to the previous position in the mark ring.
10913 With prefix arg N, jump back that many stored positions. When
10914 called several times in succession, walk through the entire ring.
10915 Org-mode commands jumping to a different position in the current file,
10916 or to another Org-mode file, automatically push the old position
10917 onto the ring."
10918 (interactive "p")
10919 (let (p m)
10920 (if (eq last-command this-command)
10921 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10922 (setq p org-mark-ring))
10923 (setq org-mark-ring-last-goto p)
10924 (setq m (car p))
10925 (org-pop-to-buffer-same-window (marker-buffer m))
10926 (goto-char m)
10927 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10929 (defun org-remove-angle-brackets (s)
10930 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10931 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10933 (defun org-add-angle-brackets (s)
10934 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10935 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10937 (defun org-remove-double-quotes (s)
10938 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10939 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10942 ;;; Following specific links
10944 (defun org-follow-timestamp-link ()
10945 "Open an agenda view for the time-stamp date/range at point."
10946 (cond
10947 ((org-at-date-range-p t)
10948 (let ((org-agenda-start-on-weekday)
10949 (t1 (match-string 1))
10950 (t2 (match-string 2)) tt1 tt2)
10951 (setq tt1 (time-to-days (org-time-string-to-time t1))
10952 tt2 (time-to-days (org-time-string-to-time t2)))
10953 (let ((org-agenda-buffer-tmp-name
10954 (format "*Org Agenda(a:%s)"
10955 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10956 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10957 ((org-at-timestamp-p t)
10958 (let ((org-agenda-buffer-tmp-name
10959 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10960 (org-agenda-list nil (time-to-days (org-time-string-to-time
10961 (substring (match-string 1) 0 10)))
10962 1)))
10963 (t (error "This should not happen"))))
10966 ;;; Following file links
10967 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10968 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10969 (declare-function mailcap-mime-info
10970 "mailcap" (string &optional request no-decode))
10971 (defvar org-wait nil)
10972 (defun org-open-file (path &optional in-emacs line search)
10973 "Open the file at PATH.
10974 First, this expands any special file name abbreviations. Then the
10975 configuration variable `org-file-apps' is checked if it contains an
10976 entry for this file type, and if yes, the corresponding command is launched.
10978 If no application is found, Emacs simply visits the file.
10980 With optional prefix argument IN-EMACS, Emacs will visit the file.
10981 With a double \\[universal-argument] \\[universal-argument] \
10982 prefix arg, Org tries to avoid opening in Emacs
10983 and to use an external application to visit the file.
10985 Optional LINE specifies a line to go to, optional SEARCH a string
10986 to search for. If LINE or SEARCH is given, the file will be
10987 opened in Emacs, unless an entry from org-file-apps that makes
10988 use of groups in a regexp matches.
10990 If you want to change the way frames are used when following a
10991 link, please customize `org-link-frame-setup'.
10993 If the file does not exist, an error is thrown."
10994 (let* ((file (if (equal path "")
10995 buffer-file-name
10996 (substitute-in-file-name (expand-file-name path))))
10997 (file-apps (append org-file-apps (org-default-apps)))
10998 (apps (org-remove-if
10999 'org-file-apps-entry-match-against-dlink-p file-apps))
11000 (apps-dlink (org-remove-if-not
11001 'org-file-apps-entry-match-against-dlink-p file-apps))
11002 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11003 (dirp (if remp nil (file-directory-p file)))
11004 (file (if (and dirp org-open-directory-means-index-dot-org)
11005 (concat (file-name-as-directory file) "index.org")
11006 file))
11007 (a-m-a-p (assq 'auto-mode apps))
11008 (dfile (downcase file))
11009 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11010 (link (cond ((and (eq line nil)
11011 (eq search nil))
11012 file)
11013 (line
11014 (concat file "::" (number-to-string line)))
11015 (search
11016 (concat file "::" search))))
11017 (dlink (downcase link))
11018 (old-buffer (current-buffer))
11019 (old-pos (point))
11020 (old-mode major-mode)
11021 ext cmd link-match-data)
11022 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11023 (setq ext (match-string 1 dfile))
11024 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11025 (setq ext (match-string 1 dfile))))
11026 (cond
11027 ((member in-emacs '((16) system))
11028 (setq cmd (cdr (assoc 'system apps))))
11029 (in-emacs (setq cmd 'emacs))
11031 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11032 (and dirp (cdr (assoc 'directory apps)))
11033 ; first, try matching against apps-dlink
11034 ; if we get a match here, store the match data for later
11035 (let ((match (assoc-default dlink apps-dlink
11036 'string-match)))
11037 (if match
11038 (progn (setq link-match-data (match-data))
11039 match)
11040 (progn (setq in-emacs (or in-emacs line search))
11041 nil))) ; if we have no match in apps-dlink,
11042 ; always open the file in emacs if line or search
11043 ; is given (for backwards compatibility)
11044 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11045 'string-match)
11046 (cdr (assoc ext apps))
11047 (cdr (assoc t apps))))))
11048 (when (eq cmd 'system)
11049 (setq cmd (cdr (assoc 'system apps))))
11050 (when (eq cmd 'default)
11051 (setq cmd (cdr (assoc t apps))))
11052 (when (eq cmd 'mailcap)
11053 (require 'mailcap)
11054 (mailcap-parse-mailcaps)
11055 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11056 (command (mailcap-mime-info mime-type)))
11057 (if (stringp command)
11058 (setq cmd command)
11059 (setq cmd 'emacs))))
11060 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11061 (not (file-exists-p file))
11062 (not org-open-non-existing-files))
11063 (user-error "No such file: %s" file))
11064 (cond
11065 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11066 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11067 (while (string-match "['\"]%s['\"]" cmd)
11068 (setq cmd (replace-match "%s" t t cmd)))
11069 (while (string-match "%s" cmd)
11070 (setq cmd (replace-match
11071 (save-match-data
11072 (shell-quote-argument
11073 (convert-standard-filename file)))
11074 t t cmd)))
11076 ;; Replace "%1", "%2" etc. in command with group matches from regex
11077 (save-match-data
11078 (let ((match-index 1)
11079 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11080 (set-match-data link-match-data)
11081 (while (<= match-index number-of-groups)
11082 (let ((regex (concat "%" (number-to-string match-index)))
11083 (replace-with (match-string match-index dlink)))
11084 (while (string-match regex cmd)
11085 (setq cmd (replace-match replace-with t t cmd))))
11086 (setq match-index (+ match-index 1)))))
11088 (save-window-excursion
11089 (message "Running %s...done" cmd)
11090 (start-process-shell-command cmd nil cmd)
11091 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11092 ((or (stringp cmd)
11093 (eq cmd 'emacs))
11094 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11095 (widen)
11096 (if line (org-goto-line line)
11097 (if search (org-link-search search))))
11098 ((consp cmd)
11099 (let ((file (convert-standard-filename file)))
11100 (save-match-data
11101 (set-match-data link-match-data)
11102 (eval cmd))))
11103 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11104 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11105 (or (not (equal old-buffer (current-buffer)))
11106 (not (equal old-pos (point))))
11107 (org-mark-ring-push old-pos old-buffer))))
11109 (defun org-file-apps-entry-match-against-dlink-p (entry)
11110 "This function returns non-nil if `entry' uses a regular
11111 expression which should be matched against the whole link by
11112 org-open-file.
11114 It assumes that is the case when the entry uses a regular
11115 expression which has at least one grouping construct and the
11116 action is either a lisp form or a command string containing
11117 '%1', i.e. using at least one subexpression match as a
11118 parameter."
11119 (let ((selector (car entry))
11120 (action (cdr entry)))
11121 (if (stringp selector)
11122 (and (> (regexp-opt-depth selector) 0)
11123 (or (and (stringp action)
11124 (string-match "%[0-9]" action))
11125 (consp action)))
11126 nil)))
11128 (defun org-default-apps ()
11129 "Return the default applications for this operating system."
11130 (cond
11131 ((eq system-type 'darwin)
11132 org-file-apps-defaults-macosx)
11133 ((eq system-type 'windows-nt)
11134 org-file-apps-defaults-windowsnt)
11135 (t org-file-apps-defaults-gnu)))
11137 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11138 "Convert extensions to regular expressions in the cars of LIST.
11139 Also, weed out any non-string entries, because the return value is used
11140 only for regexp matching.
11141 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11142 point to the symbol `emacs', indicating that the file should
11143 be opened in Emacs."
11144 (append
11145 (delq nil
11146 (mapcar (lambda (x)
11147 (if (not (stringp (car x)))
11149 (if (string-match "\\W" (car x))
11151 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11152 list))
11153 (if add-auto-mode
11154 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11156 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11157 (defun org-file-remote-p (file)
11158 "Test whether FILE specifies a location on a remote system.
11159 Return non-nil if the location is indeed remote.
11161 For example, the filename \"/user@host:/foo\" specifies a location
11162 on the system \"/user@host:\"."
11163 (cond ((fboundp 'file-remote-p)
11164 (file-remote-p file))
11165 ((fboundp 'tramp-handle-file-remote-p)
11166 (tramp-handle-file-remote-p file))
11167 ((and (boundp 'ange-ftp-name-format)
11168 (string-match (car ange-ftp-name-format) file))
11169 t)))
11172 ;;;; Refiling
11174 (defun org-get-org-file ()
11175 "Read a filename, with default directory `org-directory'."
11176 (let ((default (or org-default-notes-file remember-data-file)))
11177 (read-file-name (format "File name [%s]: " default)
11178 (file-name-as-directory org-directory)
11179 default)))
11181 (defun org-notes-order-reversed-p ()
11182 "Check if the current file should receive notes in reversed order."
11183 (cond
11184 ((not org-reverse-note-order) nil)
11185 ((eq t org-reverse-note-order) t)
11186 ((not (listp org-reverse-note-order)) nil)
11187 (t (catch 'exit
11188 (let ((all org-reverse-note-order)
11189 entry)
11190 (while (setq entry (pop all))
11191 (if (string-match (car entry) buffer-file-name)
11192 (throw 'exit (cdr entry))))
11193 nil)))))
11195 (defvar org-refile-target-table nil
11196 "The list of refile targets, created by `org-refile'.")
11198 (defvar org-agenda-new-buffers nil
11199 "Buffers created to visit agenda files.")
11201 (defvar org-refile-cache nil
11202 "Cache for refile targets.")
11204 (defvar org-refile-markers nil
11205 "All the markers used for caching refile locations.")
11207 (defun org-refile-marker (pos)
11208 "Get a new refile marker, but only if caching is in use."
11209 (if (not org-refile-use-cache)
11211 (let ((m (make-marker)))
11212 (move-marker m pos)
11213 (push m org-refile-markers)
11214 m)))
11216 (defun org-refile-cache-clear ()
11217 "Clear the refile cache and disable all the markers."
11218 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11219 (setq org-refile-markers nil)
11220 (setq org-refile-cache nil)
11221 (message "Refile cache has been cleared"))
11223 (defun org-refile-cache-check-set (set)
11224 "Check if all the markers in the cache still have live buffers."
11225 (let (marker)
11226 (catch 'exit
11227 (while (and set (setq marker (nth 3 (pop set))))
11228 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11229 (when (and marker (null (marker-buffer marker)))
11230 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11231 (sit-for 3)
11232 (throw 'exit nil)))
11233 t)))
11235 (defun org-refile-cache-put (set &rest identifiers)
11236 "Push the refile targets SET into the cache, under IDENTIFIERS."
11237 (let* ((key (sha1 (prin1-to-string identifiers)))
11238 (entry (assoc key org-refile-cache)))
11239 (if entry
11240 (setcdr entry set)
11241 (push (cons key set) org-refile-cache))))
11243 (defun org-refile-cache-get (&rest identifiers)
11244 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11245 (cond
11246 ((not org-refile-cache) nil)
11247 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11249 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11250 org-refile-cache))))
11251 (and set (org-refile-cache-check-set set) set)))))
11253 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11254 "Produce a table with refile targets."
11255 (let ((case-fold-search nil)
11256 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11257 (entries (or org-refile-targets '((nil . (:level . 1)))))
11258 targets tgs txt re files f desc descre fast-path-p level pos0)
11259 (message "Getting targets...")
11260 (with-current-buffer (or default-buffer (current-buffer))
11261 (while (setq entry (pop entries))
11262 (setq files (car entry) desc (cdr entry))
11263 (setq fast-path-p nil)
11264 (cond
11265 ((null files) (setq files (list (current-buffer))))
11266 ((eq files 'org-agenda-files)
11267 (setq files (org-agenda-files 'unrestricted)))
11268 ((and (symbolp files) (fboundp files))
11269 (setq files (funcall files)))
11270 ((and (symbolp files) (boundp files))
11271 (setq files (symbol-value files))))
11272 (if (stringp files) (setq files (list files)))
11273 (cond
11274 ((eq (car desc) :tag)
11275 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11276 ((eq (car desc) :todo)
11277 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11278 ((eq (car desc) :regexp)
11279 (setq descre (cdr desc)))
11280 ((eq (car desc) :level)
11281 (setq descre (concat "^\\*\\{" (number-to-string
11282 (if org-odd-levels-only
11283 (1- (* 2 (cdr desc)))
11284 (cdr desc)))
11285 "\\}[ \t]")))
11286 ((eq (car desc) :maxlevel)
11287 (setq fast-path-p t)
11288 (setq descre (concat "^\\*\\{1," (number-to-string
11289 (if org-odd-levels-only
11290 (1- (* 2 (cdr desc)))
11291 (cdr desc)))
11292 "\\}[ \t]")))
11293 (t (error "Bad refiling target description %s" desc)))
11294 (while (setq f (pop files))
11295 (with-current-buffer
11296 (if (bufferp f) f (org-get-agenda-file-buffer f))
11298 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11299 (progn
11300 (if (bufferp f) (setq f (buffer-file-name
11301 (buffer-base-buffer f))))
11302 (setq f (and f (expand-file-name f)))
11303 (if (eq org-refile-use-outline-path 'file)
11304 (push (list (file-name-nondirectory f) f nil nil) tgs))
11305 (save-excursion
11306 (save-restriction
11307 (widen)
11308 (goto-char (point-min))
11309 (while (re-search-forward descre nil t)
11310 (goto-char (setq pos0 (point-at-bol)))
11311 (catch 'next
11312 (when org-refile-target-verify-function
11313 (save-match-data
11314 (or (funcall org-refile-target-verify-function)
11315 (throw 'next t))))
11316 (when (and (looking-at org-complex-heading-regexp)
11317 (not (member (match-string 4) excluded-entries))
11318 (match-string 4))
11319 (setq level (org-reduced-level
11320 (- (match-end 1) (match-beginning 1)))
11321 txt (org-link-display-format (match-string 4))
11322 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11323 re (format org-complex-heading-regexp-format
11324 (regexp-quote (match-string 4))))
11325 (when org-refile-use-outline-path
11326 (setq txt (mapconcat
11327 'org-protect-slash
11328 (append
11329 (if (eq org-refile-use-outline-path
11330 'file)
11331 (list (file-name-nondirectory
11332 (buffer-file-name
11333 (buffer-base-buffer))))
11334 (if (eq org-refile-use-outline-path
11335 'full-file-path)
11336 (list (buffer-file-name
11337 (buffer-base-buffer)))))
11338 (org-get-outline-path fast-path-p
11339 level txt)
11340 (list txt))
11341 "/")))
11342 (push (list txt f re (org-refile-marker (point)))
11343 tgs)))
11344 (when (= (point) pos0)
11345 ;; verification function has not moved point
11346 (goto-char (point-at-eol))))))))
11347 (when org-refile-use-cache
11348 (org-refile-cache-put tgs (buffer-file-name) descre))
11349 (setq targets (append tgs targets))))))
11350 (message "Getting targets...done")
11351 (nreverse targets)))
11353 (defun org-protect-slash (s)
11354 (while (string-match "/" s)
11355 (setq s (replace-match "\\" t t s)))
11358 (defvar org-olpa (make-vector 20 nil))
11360 (defun org-get-outline-path (&optional fastp level heading)
11361 "Return the outline path to the current entry, as a list.
11363 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11364 routine which makes outline path derivations for an entire file,
11365 avoiding backtracing. Refile target collection makes use of that."
11366 (if fastp
11367 (progn
11368 (if (> level 19)
11369 (error "Outline path failure, more than 19 levels"))
11370 (loop for i from level upto 19 do
11371 (aset org-olpa i nil))
11372 (prog1
11373 (delq nil (append org-olpa nil))
11374 (aset org-olpa level heading)))
11375 (let (rtn case-fold-search)
11376 (save-excursion
11377 (save-restriction
11378 (widen)
11379 (while (org-up-heading-safe)
11380 (when (looking-at org-complex-heading-regexp)
11381 (push (org-trim
11382 (replace-regexp-in-string
11383 ;; Remove statistical/checkboxes cookies
11384 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11385 (org-match-string-no-properties 4)))
11386 rtn)))
11387 rtn)))))
11389 (defun org-format-outline-path (path &optional width prefix separator)
11390 "Format the outline path PATH for display.
11391 WIDTH is the maximum number of characters that is available.
11392 PREFIX is a prefix to be included in the returned string,
11393 such as the file name.
11394 SEPARATOR is inserted between the different parts of the path,
11395 the default is \"/\"."
11396 (setq width (or width 79))
11397 (if prefix (setq width (- width (length prefix))))
11398 (if (not path)
11399 (or prefix "")
11400 (let* ((nsteps (length path))
11401 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11402 (maxwidth (if (<= total-width width)
11403 10000 ;; everything fits
11404 ;; we need to shorten the level headings
11405 (/ (- width nsteps) nsteps)))
11406 (org-odd-levels-only nil)
11407 (n 0)
11408 (total (1+ (length prefix))))
11409 (setq maxwidth (max maxwidth 10))
11410 (concat prefix
11411 (if prefix (or separator "/"))
11412 (mapconcat
11413 (lambda (h)
11414 (setq n (1+ n))
11415 (if (and (= n nsteps) (< maxwidth 10000))
11416 (setq maxwidth (- total-width total)))
11417 (if (< (length h) maxwidth)
11418 (progn (setq total (+ total (length h) 1)) h)
11419 (setq h (substring h 0 (- maxwidth 2))
11420 total (+ total maxwidth 1))
11421 (if (string-match "[ \t]+\\'" h)
11422 (setq h (substring h 0 (match-beginning 0))))
11423 (setq h (concat h "..")))
11424 (org-add-props h nil 'face
11425 (nth (% (1- n) org-n-level-faces)
11426 org-level-faces))
11428 path (or separator "/"))))))
11430 (defun org-display-outline-path (&optional file current separator just-return-string)
11431 "Display the current outline path in the echo area.
11433 If FILE is non-nil, prepend the output with the file name.
11434 If CURRENT is non-nil, append the current heading to the output.
11435 SEPARATOR is passed through to `org-format-outline-path'. It separates
11436 the different parts of the path and defaults to \"/\".
11437 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11438 (interactive "P")
11439 (let* (case-fold-search
11440 message-log-max ; Don't populate the *Messages* buffer
11441 (bfn (buffer-file-name (buffer-base-buffer)))
11442 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11443 res)
11444 (if current (setq path (append path
11445 (save-excursion
11446 (org-back-to-heading t)
11447 (if (looking-at org-complex-heading-regexp)
11448 (list (match-string 4)))))))
11449 (setq res
11450 (org-format-outline-path
11451 path
11452 (1- (frame-width))
11453 (and file bfn (concat (file-name-nondirectory bfn) separator))
11454 separator))
11455 (if just-return-string
11456 (org-no-properties res)
11457 (message "%s" res))))
11459 (defvar org-refile-history nil
11460 "History for refiling operations.")
11462 (defvar org-after-refile-insert-hook nil
11463 "Hook run after `org-refile' has inserted its stuff at the new location.
11464 Note that this is still *before* the stuff will be removed from
11465 the *old* location.")
11467 (defvar org-capture-last-stored-marker)
11468 (defvar org-refile-keep nil
11469 "Non-nil means `org-refile' will copy instead of refile.")
11471 (defun org-copy ()
11472 "Like `org-refile', but copy."
11473 (interactive)
11474 (let ((org-refile-keep t))
11475 (funcall 'org-refile nil nil nil "Copy")))
11477 (defun org-refile (&optional goto default-buffer rfloc msg)
11478 "Move the entry or entries at point to another heading.
11479 The list of target headings is compiled using the information in
11480 `org-refile-targets', which see.
11482 At the target location, the entry is filed as a subitem of the target
11483 heading. Depending on `org-reverse-note-order', the new subitem will
11484 either be the first or the last subitem.
11486 If there is an active region, all entries in that region will be moved.
11487 However, the region must fulfill the requirement that the first heading
11488 is the first one sets the top-level of the moved text - at most siblings
11489 below it are allowed.
11491 With prefix arg GOTO, the command will only visit the target location
11492 and not actually move anything.
11494 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11495 go to the location where the last refiling operation has put the subtree.
11497 With a numeric prefix argument of `2', refile to the running clock.
11499 With a numeric prefix argument of `3', emulate `org-refile-keep'
11500 being set to `t' and copy to the target location, don't move it.
11501 Beware that keeping refiled entries may result in duplicated ID
11502 properties.
11504 RFLOC can be a refile location obtained in a different way.
11506 MSG is a string to replace \"Refile\" in the default prompt with
11507 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11509 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11511 If you are using target caching (see `org-refile-use-cache'),
11512 you have to clear the target cache in order to find new targets.
11513 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11514 prefix argument (`C-u C-u C-u C-c C-w')."
11516 (interactive "P")
11517 (if (member goto '(0 (64)))
11518 (org-refile-cache-clear)
11519 (let* ((actionmsg (or msg "Refile"))
11520 (cbuf (current-buffer))
11521 (regionp (org-region-active-p))
11522 (region-start (and regionp (region-beginning)))
11523 (region-end (and regionp (region-end)))
11524 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11525 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11526 pos it nbuf file re level reversed)
11527 (setq last-command nil)
11528 (when regionp
11529 (goto-char region-start)
11530 (or (bolp) (goto-char (point-at-bol)))
11531 (setq region-start (point))
11532 (unless (or (org-kill-is-subtree-p
11533 (buffer-substring region-start region-end))
11534 (prog1 org-refile-active-region-within-subtree
11535 (let ((s (point-at-eol)))
11536 (org-toggle-heading)
11537 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11538 (user-error "The region is not a (sequence of) subtree(s)")))
11539 (if (equal goto '(16))
11540 (org-refile-goto-last-stored)
11541 (when (or
11542 (and (equal goto 2)
11543 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11544 (prog1
11545 (setq it (list (or org-clock-heading "running clock")
11546 (buffer-file-name
11547 (marker-buffer org-clock-hd-marker))
11549 (marker-position org-clock-hd-marker)))
11550 (setq goto nil)))
11551 (setq it (or rfloc
11552 (let (heading-text)
11553 (save-excursion
11554 (unless goto
11555 (org-back-to-heading t)
11556 (setq heading-text
11557 (nth 4 (org-heading-components))))
11559 (org-refile-get-location
11560 (cond (goto "Goto")
11561 (regionp (concat actionmsg " region to"))
11562 (t (concat actionmsg " subtree \""
11563 heading-text "\" to")))
11564 default-buffer
11565 (and (not (equal '(4) goto))
11566 org-refile-allow-creating-parent-nodes)
11567 goto))))))
11568 (setq file (nth 1 it)
11569 re (nth 2 it)
11570 pos (nth 3 it))
11571 (if (and (not goto)
11573 (equal (buffer-file-name) file)
11574 (if regionp
11575 (and (>= pos region-start)
11576 (<= pos region-end))
11577 (and (>= pos (point))
11578 (< pos (save-excursion
11579 (org-end-of-subtree t t))))))
11580 (error "Cannot refile to position inside the tree or region"))
11582 (setq nbuf (or (find-buffer-visiting file)
11583 (find-file-noselect file)))
11584 (if (and goto (not (equal goto 3)))
11585 (progn
11586 (org-pop-to-buffer-same-window nbuf)
11587 (goto-char pos)
11588 (org-show-context 'org-goto))
11589 (if regionp
11590 (progn
11591 (org-kill-new (buffer-substring region-start region-end))
11592 (org-save-markers-in-region region-start region-end))
11593 (org-copy-subtree 1 nil t))
11594 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11595 (find-file-noselect file)))
11596 (setq reversed (org-notes-order-reversed-p))
11597 (save-excursion
11598 (save-restriction
11599 (widen)
11600 (if pos
11601 (progn
11602 (goto-char pos)
11603 (looking-at org-outline-regexp)
11604 (setq level (org-get-valid-level (funcall outline-level) 1))
11605 (goto-char
11606 (if reversed
11607 (or (outline-next-heading) (point-max))
11608 (or (save-excursion (org-get-next-sibling))
11609 (org-end-of-subtree t t)
11610 (point-max)))))
11611 (setq level 1)
11612 (if (not reversed)
11613 (goto-char (point-max))
11614 (goto-char (point-min))
11615 (or (outline-next-heading) (goto-char (point-max)))))
11616 (if (not (bolp)) (newline))
11617 (org-paste-subtree level)
11618 (when org-log-refile
11619 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11620 (unless (eq org-log-refile 'note)
11621 (save-excursion (org-add-log-note))))
11622 (and org-auto-align-tags
11623 (let ((org-loop-over-headlines-in-active-region nil))
11624 (org-set-tags nil t)))
11625 (with-demoted-errors
11626 (bookmark-set "org-refile-last-stored"))
11627 ;; If we are refiling for capture, make sure that the
11628 ;; last-capture pointers point here
11629 (when (org-bound-and-true-p org-refile-for-capture)
11630 (with-demoted-errors
11631 (bookmark-set "org-capture-last-stored-marker"))
11632 (move-marker org-capture-last-stored-marker (point)))
11633 (if (fboundp 'deactivate-mark) (deactivate-mark))
11634 (run-hooks 'org-after-refile-insert-hook))))
11635 (unless org-refile-keep
11636 (if regionp
11637 (delete-region (point) (+ (point) (- region-end region-start)))
11638 (delete-region
11639 (and (org-back-to-heading t) (point))
11640 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11641 (when (featurep 'org-inlinetask)
11642 (org-inlinetask-remove-END-maybe))
11643 (setq org-markers-to-move nil)
11644 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11646 (defun org-refile-goto-last-stored ()
11647 "Go to the location where the last refile was stored."
11648 (interactive)
11649 (bookmark-jump "org-refile-last-stored")
11650 (message "This is the location of the last refile"))
11652 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11653 no-exclude)
11654 "Prompt the user for a refile location, using PROMPT.
11655 PROMPT should not be suffixed with a colon and a space, because
11656 this function appends the default value from
11657 `org-refile-history' automatically, if that is not empty.
11658 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11659 this is used for the GOTO interface."
11660 (let ((org-refile-targets org-refile-targets)
11661 (org-refile-use-outline-path org-refile-use-outline-path)
11662 excluded-entries)
11663 (when (and (derived-mode-p 'org-mode)
11664 (not org-refile-use-cache)
11665 (not no-exclude))
11666 (org-map-tree
11667 (lambda()
11668 (setq excluded-entries
11669 (append excluded-entries (list (org-get-heading t t)))))))
11670 (setq org-refile-target-table
11671 (org-refile-get-targets default-buffer excluded-entries)))
11672 (unless org-refile-target-table
11673 (user-error "No refile targets"))
11674 (let* ((cbuf (current-buffer))
11675 (partial-completion-mode nil)
11676 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11677 (cfunc (if (and org-refile-use-outline-path
11678 org-outline-path-complete-in-steps)
11679 'org-olpath-completing-read
11680 'org-icompleting-read))
11681 (extra (if org-refile-use-outline-path "/" ""))
11682 (cbnex (concat (buffer-name) extra))
11683 (filename (and cfn (expand-file-name cfn)))
11684 (tbl (mapcar
11685 (lambda (x)
11686 (if (and (not (member org-refile-use-outline-path
11687 '(file full-file-path)))
11688 (not (equal filename (nth 1 x))))
11689 (cons (concat (car x) extra " ("
11690 (file-name-nondirectory (nth 1 x)) ")")
11691 (cdr x))
11692 (cons (concat (car x) extra) (cdr x))))
11693 org-refile-target-table))
11694 (completion-ignore-case t)
11695 cdef
11696 (prompt (concat prompt
11697 (or (and (car org-refile-history)
11698 (concat " (default " (car org-refile-history) ")"))
11699 (and (assoc cbnex tbl) (setq cdef cbnex)
11700 (concat " (default " cbnex ")"))) ": "))
11701 pa answ parent-target child parent old-hist)
11702 (setq old-hist org-refile-history)
11703 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11704 nil 'org-refile-history (or cdef (car org-refile-history))))
11705 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11706 (org-refile-check-position pa)
11707 (if pa
11708 (progn
11709 (when (or (not org-refile-history)
11710 (not (eq old-hist org-refile-history))
11711 (not (equal (car pa) (car org-refile-history))))
11712 (setq org-refile-history
11713 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11714 org-refile-history
11715 (cdr org-refile-history))))
11716 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11717 (pop org-refile-history)))
11719 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11720 (progn
11721 (setq parent (match-string 1 answ)
11722 child (match-string 2 answ))
11723 (setq parent-target (or (assoc parent tbl)
11724 (assoc (concat parent "/") tbl)))
11725 (when (and parent-target
11726 (or (eq new-nodes t)
11727 (and (eq new-nodes 'confirm)
11728 (y-or-n-p (format "Create new node \"%s\"? "
11729 child)))))
11730 (org-refile-new-child parent-target child)))
11731 (user-error "Invalid target location")))))
11733 (declare-function org-string-nw-p "org-macs" (s))
11734 (defun org-refile-check-position (refile-pointer)
11735 "Check if the refile pointer matches the headline to which it points."
11736 (let* ((file (nth 1 refile-pointer))
11737 (re (nth 2 refile-pointer))
11738 (pos (nth 3 refile-pointer))
11739 buffer)
11740 (if (and (not (markerp pos)) (not file))
11741 (user-error "Please save the buffer to a file before refiling")
11742 (when (org-string-nw-p re)
11743 (setq buffer (if (markerp pos)
11744 (marker-buffer pos)
11745 (or (find-buffer-visiting file)
11746 (find-file-noselect file))))
11747 (with-current-buffer buffer
11748 (save-excursion
11749 (save-restriction
11750 (widen)
11751 (goto-char pos)
11752 (beginning-of-line 1)
11753 (unless (org-looking-at-p re)
11754 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11756 (defun org-refile-new-child (parent-target child)
11757 "Use refile target PARENT-TARGET to add new CHILD below it."
11758 (unless parent-target
11759 (error "Cannot find parent for new node"))
11760 (let ((file (nth 1 parent-target))
11761 (pos (nth 3 parent-target))
11762 level)
11763 (with-current-buffer (or (find-buffer-visiting file)
11764 (find-file-noselect file))
11765 (save-excursion
11766 (save-restriction
11767 (widen)
11768 (if pos
11769 (goto-char pos)
11770 (goto-char (point-max))
11771 (if (not (bolp)) (newline)))
11772 (when (looking-at org-outline-regexp)
11773 (setq level (funcall outline-level))
11774 (org-end-of-subtree t t))
11775 (org-back-over-empty-lines)
11776 (insert "\n" (make-string
11777 (if pos (org-get-valid-level level 1) 1) ?*)
11778 " " child "\n")
11779 (beginning-of-line 0)
11780 (list (concat (car parent-target) "/" child) file "" (point)))))))
11782 (defun org-olpath-completing-read (prompt collection &rest args)
11783 "Read an outline path like a file name."
11784 (let ((thetable collection)
11785 (org-completion-use-ido nil) ; does not work with ido.
11786 (org-completion-use-iswitchb nil)) ; or iswitchb
11787 (apply
11788 'org-icompleting-read prompt
11789 (lambda (string predicate &optional flag)
11790 (let (rtn r f (l (length string)))
11791 (cond
11792 ((eq flag nil)
11793 ;; try completion
11794 (try-completion string thetable))
11795 ((eq flag t)
11796 ;; all-completions
11797 (setq rtn (all-completions string thetable predicate))
11798 (mapcar
11799 (lambda (x)
11800 (setq r (substring x l))
11801 (if (string-match " ([^)]*)$" x)
11802 (setq f (match-string 0 x))
11803 (setq f ""))
11804 (if (string-match "/" r)
11805 (concat string (substring r 0 (match-end 0)) f)
11807 rtn))
11808 ((eq flag 'lambda)
11809 ;; exact match?
11810 (assoc string thetable)))))
11811 args)))
11813 ;;;; Dynamic blocks
11815 (defun org-find-dblock (name)
11816 "Find the first dynamic block with name NAME in the buffer.
11817 If not found, stay at current position and return nil."
11818 (let ((case-fold-search t) pos)
11819 (save-excursion
11820 (goto-char (point-min))
11821 (setq pos (and (re-search-forward
11822 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11823 (match-beginning 0))))
11824 (if pos (goto-char pos))
11825 pos))
11827 (defconst org-dblock-start-re
11828 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11829 "Matches the start line of a dynamic block, with parameters.")
11831 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11832 "Matches the end of a dynamic block.")
11834 (defun org-create-dblock (plist)
11835 "Create a dynamic block section, with parameters taken from PLIST.
11836 PLIST must contain a :name entry which is used as name of the block."
11837 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11838 (end-of-line 1)
11839 (newline))
11840 (let ((col (current-column))
11841 (name (plist-get plist :name)))
11842 (insert "#+BEGIN: " name)
11843 (while plist
11844 (if (eq (car plist) :name)
11845 (setq plist (cddr plist))
11846 (insert " " (prin1-to-string (pop plist)))))
11847 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11848 (beginning-of-line -2)))
11850 (defun org-prepare-dblock ()
11851 "Prepare dynamic block for refresh.
11852 This empties the block, puts the cursor at the insert position and returns
11853 the property list including an extra property :name with the block name."
11854 (unless (looking-at org-dblock-start-re)
11855 (user-error "Not at a dynamic block"))
11856 (let* ((begdel (1+ (match-end 0)))
11857 (name (org-no-properties (match-string 1)))
11858 (params (append (list :name name)
11859 (read (concat "(" (match-string 3) ")")))))
11860 (save-excursion
11861 (beginning-of-line 1)
11862 (skip-chars-forward " \t")
11863 (setq params (plist-put params :indentation-column (current-column))))
11864 (unless (re-search-forward org-dblock-end-re nil t)
11865 (error "Dynamic block not terminated"))
11866 (setq params
11867 (append params
11868 (list :content (buffer-substring
11869 begdel (match-beginning 0)))))
11870 (delete-region begdel (match-beginning 0))
11871 (goto-char begdel)
11872 (open-line 1)
11873 params))
11875 (defun org-map-dblocks (&optional command)
11876 "Apply COMMAND to all dynamic blocks in the current buffer.
11877 If COMMAND is not given, use `org-update-dblock'."
11878 (let ((cmd (or command 'org-update-dblock)))
11879 (save-excursion
11880 (goto-char (point-min))
11881 (while (re-search-forward org-dblock-start-re nil t)
11882 (goto-char (match-beginning 0))
11883 (save-excursion
11884 (condition-case nil
11885 (funcall cmd)
11886 (error (message "Error during update of dynamic block"))))
11887 (unless (re-search-forward org-dblock-end-re nil t)
11888 (error "Dynamic block not terminated"))))))
11890 (defun org-dblock-update (&optional arg)
11891 "User command for updating dynamic blocks.
11892 Update the dynamic block at point. With prefix ARG, update all dynamic
11893 blocks in the buffer."
11894 (interactive "P")
11895 (if arg
11896 (org-update-all-dblocks)
11897 (or (looking-at org-dblock-start-re)
11898 (org-beginning-of-dblock))
11899 (org-update-dblock)))
11901 (defun org-update-dblock ()
11902 "Update the dynamic block at point.
11903 This means to empty the block, parse for parameters and then call
11904 the correct writing function."
11905 (interactive)
11906 (save-window-excursion
11907 (let* ((pos (point))
11908 (line (org-current-line))
11909 (params (org-prepare-dblock))
11910 (name (plist-get params :name))
11911 (indent (plist-get params :indentation-column))
11912 (cmd (intern (concat "org-dblock-write:" name))))
11913 (message "Updating dynamic block `%s' at line %d..." name line)
11914 (funcall cmd params)
11915 (message "Updating dynamic block `%s' at line %d...done" name line)
11916 (goto-char pos)
11917 (when (and indent (> indent 0))
11918 (setq indent (make-string indent ?\ ))
11919 (save-excursion
11920 (org-beginning-of-dblock)
11921 (forward-line 1)
11922 (while (not (looking-at org-dblock-end-re))
11923 (insert indent)
11924 (beginning-of-line 2))
11925 (when (looking-at org-dblock-end-re)
11926 (and (looking-at "[ \t]+")
11927 (replace-match ""))
11928 (insert indent)))))))
11930 (defun org-beginning-of-dblock ()
11931 "Find the beginning of the dynamic block at point.
11932 Error if there is no such block at point."
11933 (let ((pos (point))
11934 beg)
11935 (end-of-line 1)
11936 (if (and (re-search-backward org-dblock-start-re nil t)
11937 (setq beg (match-beginning 0))
11938 (re-search-forward org-dblock-end-re nil t)
11939 (> (match-end 0) pos))
11940 (goto-char beg)
11941 (goto-char pos)
11942 (error "Not in a dynamic block"))))
11944 (defun org-update-all-dblocks ()
11945 "Update all dynamic blocks in the buffer.
11946 This function can be used in a hook."
11947 (interactive)
11948 (when (derived-mode-p 'org-mode)
11949 (org-map-dblocks 'org-update-dblock)))
11952 ;;;; Completion
11954 (declare-function org-export-backend-name "org-export" (cl-x))
11955 (declare-function org-export-backend-options "org-export" (cl-x))
11956 (defun org-get-export-keywords ()
11957 "Return a list of all currently understood export keywords.
11958 Export keywords include options, block names, attributes and
11959 keywords relative to each registered export back-end."
11960 (let (keywords)
11961 (dolist (backend
11962 (org-bound-and-true-p org-export--registered-backends)
11963 (delq nil keywords))
11964 ;; Back-end name (for keywords, like #+LATEX:)
11965 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11966 (dolist (option-entry (org-export-backend-options backend))
11967 ;; Back-end options.
11968 (push (nth 1 option-entry) keywords)))))
11970 (defconst org-options-keywords
11971 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11972 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11973 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11974 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11975 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11977 (defcustom org-structure-template-alist
11978 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11979 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11980 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11981 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11982 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11983 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11984 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11985 "<literal style=\"latex\">\n?\n</literal>")
11986 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11987 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11988 "<literal style=\"html\">\n?\n</literal>")
11989 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11990 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11991 ("A" "#+ASCII: " "")
11992 ("i" "#+INDEX: ?" "#+INDEX: ?")
11993 ("I" "#+INCLUDE: %file ?"
11994 "<include file=%file markup=\"?\">"))
11995 "Structure completion elements.
11996 This is a list of abbreviation keys and values. The value gets inserted
11997 if you type `<' followed by the key and then press the completion key,
11998 usually `M-TAB'. %file will be replaced by a file name after prompting
11999 for the file using completion. The cursor will be placed at the position
12000 of the `?` in the template.
12001 There are two templates for each key, the first uses the original Org syntax,
12002 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12003 the default when the /org-mtags.el/ module has been loaded. See also the
12004 variable `org-mtags-prefer-muse-templates'."
12005 :group 'org-completion
12006 :type '(repeat
12007 (list
12008 (string :tag "Key")
12009 (string :tag "Template")
12010 (string :tag "Muse Template"))))
12012 (defun org-try-structure-completion ()
12013 "Try to complete a structure template before point.
12014 This looks for strings like \"<e\" on an otherwise empty line and
12015 expands them."
12016 (let ((l (buffer-substring (point-at-bol) (point)))
12018 (when (and (looking-at "[ \t]*$")
12019 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12020 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12021 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12022 (match-beginning 1)) a)
12023 t)))
12025 (defun org-complete-expand-structure-template (start cell)
12026 "Expand a structure template."
12027 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12028 (rpl (nth (if musep 2 1) cell))
12029 (ind ""))
12030 (delete-region start (point))
12031 (when (string-match "\\`#\\+" rpl)
12032 (cond
12033 ((bolp))
12034 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12035 (setq ind (buffer-substring (point-at-bol) (point))))
12036 (t (newline))))
12037 (setq start (point))
12038 (if (string-match "%file" rpl)
12039 (setq rpl (replace-match
12040 (concat
12041 "\""
12042 (save-match-data
12043 (abbreviate-file-name (read-file-name "Include file: ")))
12044 "\"")
12045 t t rpl)))
12046 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12047 (concat "\n" ind)))
12048 (insert rpl)
12049 (if (re-search-backward "\\?" start t) (delete-char 1))))
12051 ;;;; TODO, DEADLINE, Comments
12053 (defun org-toggle-comment ()
12054 "Change the COMMENT state of an entry."
12055 (interactive)
12056 (save-excursion
12057 (org-back-to-heading)
12058 (let (case-fold-search)
12059 (cond
12060 ((looking-at (format org-heading-keyword-regexp-format
12061 org-comment-string))
12062 (goto-char (match-end 1))
12063 (looking-at (concat " +" org-comment-string))
12064 (replace-match "" t t)
12065 (when (eolp) (insert " ")))
12066 ((looking-at org-outline-regexp)
12067 (goto-char (match-end 0))
12068 (insert org-comment-string " "))))))
12070 (defvar org-last-todo-state-is-todo nil
12071 "This is non-nil when the last TODO state change led to a TODO state.
12072 If the last change removed the TODO tag or switched to DONE, then
12073 this is nil.")
12075 (defvar org-setting-tags nil) ; dynamically skipped
12077 (defvar org-todo-setup-filter-hook nil
12078 "Hook for functions that pre-filter todo specs.
12079 Each function takes a todo spec and returns either nil or the spec
12080 transformed into canonical form." )
12082 (defvar org-todo-get-default-hook nil
12083 "Hook for functions that get a default item for todo.
12084 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12085 nil or a string to be used for the todo mark." )
12087 (defvar org-agenda-headline-snapshot-before-repeat)
12089 (defun org-current-effective-time ()
12090 "Return current time adjusted for `org-extend-today-until' variable."
12091 (let* ((ct (org-current-time))
12092 (dct (decode-time ct))
12093 (ct1
12094 (cond
12095 (org-use-last-clock-out-time-as-effective-time
12096 (or (org-clock-get-last-clock-out-time) ct))
12097 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12098 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12099 (t ct))))
12100 ct1))
12102 (defun org-todo-yesterday (&optional arg)
12103 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12104 (interactive "P")
12105 (if (eq major-mode 'org-agenda-mode)
12106 (apply 'org-agenda-todo-yesterday arg)
12107 (let* ((hour (third (decode-time
12108 (org-current-time))))
12109 (org-extend-today-until (1+ hour)))
12110 (org-todo arg))))
12112 (defvar org-block-entry-blocking ""
12113 "First entry preventing the TODO state change.")
12115 (defun org-todo (&optional arg)
12116 "Change the TODO state of an item.
12117 The state of an item is given by a keyword at the start of the heading,
12118 like
12119 *** TODO Write paper
12120 *** DONE Call mom
12122 The different keywords are specified in the variable `org-todo-keywords'.
12123 By default the available states are \"TODO\" and \"DONE\".
12124 So for this example: when the item starts with TODO, it is changed to DONE.
12125 When it starts with DONE, the DONE is removed. And when neither TODO nor
12126 DONE are present, add TODO at the beginning of the heading.
12128 With \\[universal-argument] prefix arg, use completion to determine the new \
12129 state.
12130 With numeric prefix arg, switch to that state.
12131 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12132 keywords (nextset).
12133 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12134 With a numeric prefix arg of 0, inhibit note taking for the change.
12136 For calling through lisp, arg is also interpreted in the following way:
12137 'none -> empty state
12138 \"\"(empty string) -> switch to empty state
12139 'done -> switch to DONE
12140 'nextset -> switch to the next set of keywords
12141 'previousset -> switch to the previous set of keywords
12142 \"WAITING\" -> switch to the specified keyword, but only if it
12143 really is a member of `org-todo-keywords'."
12144 (interactive "P")
12145 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12146 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12147 'region-start-level 'region))
12148 org-loop-over-headlines-in-active-region)
12149 (org-map-entries
12150 `(org-todo ,arg)
12151 org-loop-over-headlines-in-active-region
12152 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12153 (if (equal arg '(16)) (setq arg 'nextset))
12154 (let ((org-blocker-hook org-blocker-hook)
12155 commentp
12156 case-fold-search)
12157 (when (equal arg '(64))
12158 (setq arg nil org-blocker-hook nil))
12159 (when (and org-blocker-hook
12160 (or org-inhibit-blocking
12161 (org-entry-get nil "NOBLOCKING")))
12162 (setq org-blocker-hook nil))
12163 (save-excursion
12164 (catch 'exit
12165 (org-back-to-heading t)
12166 (when (looking-at (concat "^\\*+ " org-comment-string))
12167 (org-toggle-comment)
12168 (setq commentp t))
12169 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12170 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12171 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12172 (let* ((match-data (match-data))
12173 (startpos (point-at-bol))
12174 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12175 (org-log-done org-log-done)
12176 (org-log-repeat org-log-repeat)
12177 (org-todo-log-states org-todo-log-states)
12178 (org-inhibit-logging
12179 (if (equal arg 0)
12180 (progn (setq arg nil) 'note) org-inhibit-logging))
12181 (this (match-string 1))
12182 (hl-pos (match-beginning 0))
12183 (head (org-get-todo-sequence-head this))
12184 (ass (assoc head org-todo-kwd-alist))
12185 (interpret (nth 1 ass))
12186 (done-word (nth 3 ass))
12187 (final-done-word (nth 4 ass))
12188 (org-last-state (or this ""))
12189 (completion-ignore-case t)
12190 (member (member this org-todo-keywords-1))
12191 (tail (cdr member))
12192 (org-state (cond
12193 ((and org-todo-key-trigger
12194 (or (and (equal arg '(4))
12195 (eq org-use-fast-todo-selection 'prefix))
12196 (and (not arg) org-use-fast-todo-selection
12197 (not (eq org-use-fast-todo-selection
12198 'prefix)))))
12199 ;; Use fast selection
12200 (org-fast-todo-selection))
12201 ((and (equal arg '(4))
12202 (or (not org-use-fast-todo-selection)
12203 (not org-todo-key-trigger)))
12204 ;; Read a state with completion
12205 (org-icompleting-read
12206 "State: " (mapcar 'list org-todo-keywords-1)
12207 nil t))
12208 ((eq arg 'right)
12209 (if this
12210 (if tail (car tail) nil)
12211 (car org-todo-keywords-1)))
12212 ((eq arg 'left)
12213 (if (equal member org-todo-keywords-1)
12215 (if this
12216 (nth (- (length org-todo-keywords-1)
12217 (length tail) 2)
12218 org-todo-keywords-1)
12219 (org-last org-todo-keywords-1))))
12220 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12221 (setq arg nil))) ; hack to fall back to cycling
12222 (arg
12223 ;; user or caller requests a specific state
12224 (cond
12225 ((equal arg "") nil)
12226 ((eq arg 'none) nil)
12227 ((eq arg 'done) (or done-word (car org-done-keywords)))
12228 ((eq arg 'nextset)
12229 (or (car (cdr (member head org-todo-heads)))
12230 (car org-todo-heads)))
12231 ((eq arg 'previousset)
12232 (let ((org-todo-heads (reverse org-todo-heads)))
12233 (or (car (cdr (member head org-todo-heads)))
12234 (car org-todo-heads))))
12235 ((car (member arg org-todo-keywords-1)))
12236 ((stringp arg)
12237 (user-error "State `%s' not valid in this file" arg))
12238 ((nth (1- (prefix-numeric-value arg))
12239 org-todo-keywords-1))))
12240 ((null member) (or head (car org-todo-keywords-1)))
12241 ((equal this final-done-word) nil) ;; -> make empty
12242 ((null tail) nil) ;; -> first entry
12243 ((memq interpret '(type priority))
12244 (if (eq this-command last-command)
12245 (car tail)
12246 (if (> (length tail) 0)
12247 (or done-word (car org-done-keywords))
12248 nil)))
12250 (car tail))))
12251 (org-state (or
12252 (run-hook-with-args-until-success
12253 'org-todo-get-default-hook org-state org-last-state)
12254 org-state))
12255 (next (if org-state (concat " " org-state " ") " "))
12256 (change-plist (list :type 'todo-state-change :from this :to org-state
12257 :position startpos))
12258 dolog now-done-p)
12259 (when org-blocker-hook
12260 (setq org-last-todo-state-is-todo
12261 (not (member this org-done-keywords)))
12262 (unless (save-excursion
12263 (save-match-data
12264 (org-with-wide-buffer
12265 (run-hook-with-args-until-failure
12266 'org-blocker-hook change-plist))))
12267 (if (org-called-interactively-p 'interactive)
12268 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12269 this org-state org-block-entry-blocking)
12270 ;; fail silently
12271 (message "TODO state change from %s to %s blocked (by \"%s\")"
12272 this org-state org-block-entry-blocking)
12273 (throw 'exit nil))))
12274 (store-match-data match-data)
12275 (replace-match next t t)
12276 (unless (pos-visible-in-window-p hl-pos)
12277 (message "TODO state changed to %s" (org-trim next)))
12278 (unless head
12279 (setq head (org-get-todo-sequence-head org-state)
12280 ass (assoc head org-todo-kwd-alist)
12281 interpret (nth 1 ass)
12282 done-word (nth 3 ass)
12283 final-done-word (nth 4 ass)))
12284 (when (memq arg '(nextset previousset))
12285 (message "Keyword-Set %d/%d: %s"
12286 (- (length org-todo-sets) -1
12287 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12288 (length org-todo-sets)
12289 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12290 (setq org-last-todo-state-is-todo
12291 (not (member org-state org-done-keywords)))
12292 (setq now-done-p (and (member org-state org-done-keywords)
12293 (not (member this org-done-keywords))))
12294 (and logging (org-local-logging logging))
12295 (when (and (or org-todo-log-states org-log-done)
12296 (not (eq org-inhibit-logging t))
12297 (not (memq arg '(nextset previousset))))
12298 ;; we need to look at recording a time and note
12299 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12300 (nth 2 (assoc this org-todo-log-states))))
12301 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12302 (setq dolog 'time))
12303 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12304 (and org-state
12305 (member org-state org-not-done-keywords)
12306 (not (member this org-not-done-keywords))))
12307 ;; This is now a todo state and was not one before
12308 ;; If there was a CLOSED time stamp, get rid of it.
12309 (org-add-planning-info nil nil 'closed))
12310 (when (and now-done-p org-log-done)
12311 ;; It is now done, and it was not done before
12312 (org-add-planning-info 'closed (org-current-effective-time))
12313 (if (and (not dolog) (eq 'note org-log-done))
12314 (org-add-log-setup 'done org-state this 'findpos 'note)))
12315 (when (and org-state dolog)
12316 ;; This is a non-nil state, and we need to log it
12317 (org-add-log-setup 'state org-state this 'findpos dolog)))
12318 ;; Fixup tag positioning
12319 (org-todo-trigger-tag-changes org-state)
12320 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12321 (when org-provide-todo-statistics
12322 (org-update-parent-todo-statistics))
12323 (run-hooks 'org-after-todo-state-change-hook)
12324 (if (and arg (not (member org-state org-done-keywords)))
12325 (setq head (org-get-todo-sequence-head org-state)))
12326 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12327 ;; Do we need to trigger a repeat?
12328 (when now-done-p
12329 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12330 ;; This is for the agenda, take a snapshot of the headline.
12331 (save-match-data
12332 (setq org-agenda-headline-snapshot-before-repeat
12333 (org-get-heading))))
12334 (org-auto-repeat-maybe org-state))
12335 ;; Fixup cursor location if close to the keyword
12336 (if (and (outline-on-heading-p)
12337 (not (bolp))
12338 (save-excursion (beginning-of-line 1)
12339 (looking-at org-todo-line-regexp))
12340 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12341 (progn
12342 (goto-char (or (match-end 2) (match-end 1)))
12343 (and (looking-at " ") (just-one-space))))
12344 (when org-trigger-hook
12345 (save-excursion
12346 (run-hook-with-args 'org-trigger-hook change-plist)))
12347 (when commentp (org-toggle-comment))))))))
12349 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12350 "Block turning an entry into a TODO, using the hierarchy.
12351 This checks whether the current task should be blocked from state
12352 changes. Such blocking occurs when:
12354 1. The task has children which are not all in a completed state.
12356 2. A task has a parent with the property :ORDERED:, and there
12357 are siblings prior to the current task with incomplete
12358 status.
12360 3. The parent of the task is blocked because it has siblings that should
12361 be done first, or is child of a block grandparent TODO entry."
12363 (if (not org-enforce-todo-dependencies)
12364 t ; if locally turned off don't block
12365 (catch 'dont-block
12366 ;; If this is not a todo state change, or if this entry is already DONE,
12367 ;; do not block
12368 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12369 (member (plist-get change-plist :from)
12370 (cons 'done org-done-keywords))
12371 (member (plist-get change-plist :to)
12372 (cons 'todo org-not-done-keywords))
12373 (not (plist-get change-plist :to)))
12374 (throw 'dont-block t))
12375 ;; If this task has children, and any are undone, it's blocked
12376 (save-excursion
12377 (org-back-to-heading t)
12378 (let ((this-level (funcall outline-level)))
12379 (outline-next-heading)
12380 (let ((child-level (funcall outline-level)))
12381 (while (and (not (eobp))
12382 (> child-level this-level))
12383 ;; this todo has children, check whether they are all
12384 ;; completed
12385 (if (and (not (org-entry-is-done-p))
12386 (org-entry-is-todo-p))
12387 (progn (setq org-block-entry-blocking (org-get-heading))
12388 (throw 'dont-block nil)))
12389 (outline-next-heading)
12390 (setq child-level (funcall outline-level))))))
12391 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12392 ;; any previous siblings are undone, it's blocked
12393 (save-excursion
12394 (org-back-to-heading t)
12395 (let* ((pos (point))
12396 (parent-pos (and (org-up-heading-safe) (point))))
12397 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12398 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12399 (forward-line 1)
12400 (re-search-forward org-not-done-heading-regexp pos t))
12401 (setq org-block-entry-blocking (match-string 0))
12402 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12403 ;; Search further up the hierarchy, to see if an ancestor is blocked
12404 (while t
12405 (goto-char parent-pos)
12406 (if (not (looking-at org-not-done-heading-regexp))
12407 (throw 'dont-block t)) ; do not block, parent is not a TODO
12408 (setq pos (point))
12409 (setq parent-pos (and (org-up-heading-safe) (point)))
12410 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12411 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12412 (forward-line 1)
12413 (re-search-forward org-not-done-heading-regexp pos t)
12414 (setq org-block-entry-blocking (org-get-heading)))
12415 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12417 (defcustom org-track-ordered-property-with-tag nil
12418 "Should the ORDERED property also be shown as a tag?
12419 The ORDERED property decides if an entry should require subtasks to be
12420 completed in sequence. Since a property is not very visible, setting
12421 this option means that toggling the ORDERED property with the command
12422 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12423 not relevant for the behavior, but it makes things more visible.
12425 Note that toggling the tag with tags commands will not change the property
12426 and therefore not influence behavior!
12428 This can be t, meaning the tag ORDERED should be used, It can also be a
12429 string to select a different tag for this task."
12430 :group 'org-todo
12431 :type '(choice
12432 (const :tag "No tracking" nil)
12433 (const :tag "Track with ORDERED tag" t)
12434 (string :tag "Use other tag")))
12436 (defun org-toggle-ordered-property ()
12437 "Toggle the ORDERED property of the current entry.
12438 For better visibility, you can track the value of this property with a tag.
12439 See variable `org-track-ordered-property-with-tag'."
12440 (interactive)
12441 (let* ((t1 org-track-ordered-property-with-tag)
12442 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12443 (save-excursion
12444 (org-back-to-heading)
12445 (if (org-entry-get nil "ORDERED")
12446 (progn
12447 (org-delete-property "ORDERED" "PROPERTIES")
12448 (and tag (org-toggle-tag tag 'off))
12449 (message "Subtasks can be completed in arbitrary order"))
12450 (org-entry-put nil "ORDERED" "t")
12451 (and tag (org-toggle-tag tag 'on))
12452 (message "Subtasks must be completed in sequence")))))
12454 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12455 (defun org-block-todo-from-checkboxes (change-plist)
12456 "Block turning an entry into a TODO, using checkboxes.
12457 This checks whether the current task should be blocked from state
12458 changes because there are unchecked boxes in this entry."
12459 (if (not org-enforce-todo-checkbox-dependencies)
12460 t ; if locally turned off don't block
12461 (catch 'dont-block
12462 ;; If this is not a todo state change, or if this entry is already DONE,
12463 ;; do not block
12464 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12465 (member (plist-get change-plist :from)
12466 (cons 'done org-done-keywords))
12467 (member (plist-get change-plist :to)
12468 (cons 'todo org-not-done-keywords))
12469 (not (plist-get change-plist :to)))
12470 (throw 'dont-block t))
12471 ;; If this task has checkboxes that are not checked, it's blocked
12472 (save-excursion
12473 (org-back-to-heading t)
12474 (let ((beg (point)) end)
12475 (outline-next-heading)
12476 (setq end (point))
12477 (goto-char beg)
12478 (if (org-list-search-forward
12479 (concat (org-item-beginning-re)
12480 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12481 "\\[[- ]\\]")
12482 end t)
12483 (progn
12484 (if (boundp 'org-blocked-by-checkboxes)
12485 (setq org-blocked-by-checkboxes t))
12486 (throw 'dont-block nil)))))
12487 t))) ; do not block
12489 (defun org-entry-blocked-p ()
12490 "Is the current entry blocked?"
12491 (org-with-silent-modifications
12492 (if (org-entry-get nil "NOBLOCKING")
12493 nil ;; Never block this entry
12494 (not (run-hook-with-args-until-failure
12495 'org-blocker-hook
12496 (list :type 'todo-state-change
12497 :position (point)
12498 :from 'todo
12499 :to 'done))))))
12501 (defun org-update-statistics-cookies (all)
12502 "Update the statistics cookie, either from TODO or from checkboxes.
12503 This should be called with the cursor in a line with a statistics cookie."
12504 (interactive "P")
12505 (if all
12506 (progn
12507 (org-update-checkbox-count 'all)
12508 (org-map-entries 'org-update-parent-todo-statistics))
12509 (if (not (org-at-heading-p))
12510 (org-update-checkbox-count)
12511 (let ((pos (point-marker))
12512 end l1 l2)
12513 (ignore-errors (org-back-to-heading t))
12514 (if (not (org-at-heading-p))
12515 (org-update-checkbox-count)
12516 (setq l1 (org-outline-level))
12517 (setq end (save-excursion
12518 (outline-next-heading)
12519 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12520 (point)))
12521 (if (and (save-excursion
12522 (re-search-forward
12523 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12524 (not (save-excursion (re-search-forward
12525 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12526 (org-update-checkbox-count)
12527 (if (and l2 (> l2 l1))
12528 (progn
12529 (goto-char end)
12530 (org-update-parent-todo-statistics))
12531 (goto-char pos)
12532 (beginning-of-line 1)
12533 (while (re-search-forward
12534 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12535 (point-at-eol) t)
12536 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12537 (goto-char pos)
12538 (move-marker pos nil)))))
12540 (defvar org-entry-property-inherited-from) ;; defined below
12541 (defun org-update-parent-todo-statistics ()
12542 "Update any statistics cookie in the parent of the current headline.
12543 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12544 the entire subtree and this will travel up the hierarchy and update
12545 statistics everywhere."
12546 (let* ((prop (save-excursion (org-up-heading-safe)
12547 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12548 (recursive (or (not org-hierarchical-todo-statistics)
12549 (and prop (string-match "\\<recursive\\>" prop))))
12550 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12552 (first t)
12553 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12554 level ltoggle l1 new ndel
12555 (cnt-all 0) (cnt-done 0) is-percent kwd
12556 checkbox-beg ov ovs ove cookie-present)
12557 (catch 'exit
12558 (save-excursion
12559 (beginning-of-line 1)
12560 (setq ltoggle (funcall outline-level))
12561 ;; Three situations are to consider:
12563 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12564 ;; to the top-level ancestor on the headline;
12566 ;; 2. If parent has "recursive" property, repeat up to the
12567 ;; headline setting that property, taking inheritance into
12568 ;; account;
12570 ;; 3. Else, move up to direct parent and proceed only once.
12571 (while (and (setq level (org-up-heading-safe))
12572 (or recursive first)
12573 (>= (point) lim))
12574 (setq first nil cookie-present nil)
12575 (unless (and level
12576 (not (string-match
12577 "\\<checkbox\\>"
12578 (downcase (or (org-entry-get nil "COOKIE_DATA")
12579 "")))))
12580 (throw 'exit nil))
12581 (while (re-search-forward box-re (point-at-eol) t)
12582 (setq cnt-all 0 cnt-done 0 cookie-present t)
12583 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12584 (save-match-data
12585 (unless (outline-next-heading) (throw 'exit nil))
12586 (while (and (looking-at org-complex-heading-regexp)
12587 (> (setq l1 (length (match-string 1))) level))
12588 (setq kwd (and (or recursive (= l1 ltoggle))
12589 (match-string 2)))
12590 (if (or (eq org-provide-todo-statistics 'all-headlines)
12591 (and (listp org-provide-todo-statistics)
12592 (or (member kwd org-provide-todo-statistics)
12593 (member kwd org-done-keywords))))
12594 (setq cnt-all (1+ cnt-all))
12595 (if (eq org-provide-todo-statistics t)
12596 (and kwd (setq cnt-all (1+ cnt-all)))))
12597 (and (member kwd org-done-keywords)
12598 (setq cnt-done (1+ cnt-done)))
12599 (outline-next-heading)))
12600 (setq new
12601 (if is-percent
12602 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12603 (format "[%d/%d]" cnt-done cnt-all))
12604 ndel (- (match-end 0) checkbox-beg))
12605 ;; handle overlays when updating cookie from column view
12606 (when (setq ov (car (overlays-at checkbox-beg)))
12607 (setq ovs (overlay-start ov) ove (overlay-end ov))
12608 (delete-overlay ov))
12609 (goto-char checkbox-beg)
12610 (insert new)
12611 (delete-region (point) (+ (point) ndel))
12612 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12613 (when ov (move-overlay ov ovs ove)))
12614 (when cookie-present
12615 (run-hook-with-args 'org-after-todo-statistics-hook
12616 cnt-done (- cnt-all cnt-done))))))
12617 (run-hooks 'org-todo-statistics-hook)))
12619 (defvar org-after-todo-statistics-hook nil
12620 "Hook that is called after a TODO statistics cookie has been updated.
12621 Each function is called with two arguments: the number of not-done entries
12622 and the number of done entries.
12624 For example, the following function, when added to this hook, will switch
12625 an entry to DONE when all children are done, and back to TODO when new
12626 entries are set to a TODO status. Note that this hook is only called
12627 when there is a statistics cookie in the headline!
12629 (defun org-summary-todo (n-done n-not-done)
12630 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12631 (let (org-log-done org-log-states) ; turn off logging
12632 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12635 (defvar org-todo-statistics-hook nil
12636 "Hook that is run whenever Org thinks TODO statistics should be updated.
12637 This hook runs even if there is no statistics cookie present, in which case
12638 `org-after-todo-statistics-hook' would not run.")
12640 (defun org-todo-trigger-tag-changes (state)
12641 "Apply the changes defined in `org-todo-state-tags-triggers'."
12642 (let ((l org-todo-state-tags-triggers)
12643 changes)
12644 (when (or (not state) (equal state ""))
12645 (setq changes (append changes (cdr (assoc "" l)))))
12646 (when (and (stringp state) (> (length state) 0))
12647 (setq changes (append changes (cdr (assoc state l)))))
12648 (when (member state org-not-done-keywords)
12649 (setq changes (append changes (cdr (assoc 'todo l)))))
12650 (when (member state org-done-keywords)
12651 (setq changes (append changes (cdr (assoc 'done l)))))
12652 (dolist (c changes)
12653 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12655 (defun org-local-logging (value)
12656 "Get logging settings from a property VALUE."
12657 (let* (words w a)
12658 ;; directly set the variables, they are already local.
12659 (setq org-log-done nil
12660 org-log-repeat nil
12661 org-todo-log-states nil)
12662 (setq words (org-split-string value))
12663 (while (setq w (pop words))
12664 (cond
12665 ((setq a (assoc w org-startup-options))
12666 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12667 (set (nth 1 a) (nth 2 a))))
12668 ((setq a (org-extract-log-state-settings w))
12669 (and (member (car a) org-todo-keywords-1)
12670 (push a org-todo-log-states)))))))
12672 (defun org-get-todo-sequence-head (kwd)
12673 "Return the head of the TODO sequence to which KWD belongs.
12674 If KWD is not set, check if there is a text property remembering the
12675 right sequence."
12676 (let (p)
12677 (cond
12678 ((not kwd)
12679 (or (get-text-property (point-at-bol) 'org-todo-head)
12680 (progn
12681 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12682 nil (point-at-eol)))
12683 (get-text-property p 'org-todo-head))))
12684 ((not (member kwd org-todo-keywords-1))
12685 (car org-todo-keywords-1))
12686 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12688 (defun org-fast-todo-selection ()
12689 "Fast TODO keyword selection with single keys.
12690 Returns the new TODO keyword, or nil if no state change should occur."
12691 (let* ((fulltable org-todo-key-alist)
12692 (done-keywords org-done-keywords) ;; needed for the faces.
12693 (maxlen (apply 'max (mapcar
12694 (lambda (x)
12695 (if (stringp (car x)) (string-width (car x)) 0))
12696 fulltable)))
12697 (expert nil)
12698 (fwidth (+ maxlen 3 1 3))
12699 (ncol (/ (- (window-width) 4) fwidth))
12700 tg cnt e c tbl
12701 groups ingroup)
12702 (save-excursion
12703 (save-window-excursion
12704 (if expert
12705 (set-buffer (get-buffer-create " *Org todo*"))
12706 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12707 (erase-buffer)
12708 (org-set-local 'org-done-keywords done-keywords)
12709 (setq tbl fulltable cnt 0)
12710 (while (setq e (pop tbl))
12711 (cond
12712 ((equal e '(:startgroup))
12713 (push '() groups) (setq ingroup t)
12714 (when (not (= cnt 0))
12715 (setq cnt 0)
12716 (insert "\n"))
12717 (insert "{ "))
12718 ((equal e '(:endgroup))
12719 (setq ingroup nil cnt 0)
12720 (insert "}\n"))
12721 ((equal e '(:newline))
12722 (when (not (= cnt 0))
12723 (setq cnt 0)
12724 (insert "\n")
12725 (setq e (car tbl))
12726 (while (equal (car tbl) '(:newline))
12727 (insert "\n")
12728 (setq tbl (cdr tbl)))))
12730 (setq tg (car e) c (cdr e))
12731 (if ingroup (push tg (car groups)))
12732 (setq tg (org-add-props tg nil 'face
12733 (org-get-todo-face tg)))
12734 (if (and (= cnt 0) (not ingroup)) (insert " "))
12735 (insert "[" c "] " tg (make-string
12736 (- fwidth 4 (length tg)) ?\ ))
12737 (when (= (setq cnt (1+ cnt)) ncol)
12738 (insert "\n")
12739 (if ingroup (insert " "))
12740 (setq cnt 0)))))
12741 (insert "\n")
12742 (goto-char (point-min))
12743 (if (not expert) (org-fit-window-to-buffer))
12744 (message "[a-z..]:Set [SPC]:clear")
12745 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12746 (cond
12747 ((or (= c ?\C-g)
12748 (and (= c ?q) (not (rassoc c fulltable))))
12749 (setq quit-flag t))
12750 ((= c ?\ ) nil)
12751 ((setq e (rassoc c fulltable) tg (car e))
12753 (t (setq quit-flag t)))))))
12755 (defun org-entry-is-todo-p ()
12756 (member (org-get-todo-state) org-not-done-keywords))
12758 (defun org-entry-is-done-p ()
12759 (member (org-get-todo-state) org-done-keywords))
12761 (defun org-get-todo-state ()
12762 "Return the TODO keyword of the current subtree."
12763 (save-excursion
12764 (org-back-to-heading t)
12765 (and (looking-at org-todo-line-regexp)
12766 (match-end 2)
12767 (match-string 2))))
12769 (defun org-at-date-range-p (&optional inactive-ok)
12770 "Is the cursor inside a date range?"
12771 (interactive)
12772 (save-excursion
12773 (catch 'exit
12774 (let ((pos (point)))
12775 (skip-chars-backward "^[<\r\n")
12776 (skip-chars-backward "<[")
12777 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12778 (>= (match-end 0) pos)
12779 (throw 'exit t))
12780 (skip-chars-backward "^<[\r\n")
12781 (skip-chars-backward "<[")
12782 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12783 (>= (match-end 0) pos)
12784 (throw 'exit t)))
12785 nil)))
12787 (defun org-get-repeat (&optional tagline)
12788 "Check if there is a deadline/schedule with repeater in this entry."
12789 (save-match-data
12790 (save-excursion
12791 (org-back-to-heading t)
12792 (and (re-search-forward (if tagline
12793 (concat tagline "\\s-*" org-repeat-re)
12794 org-repeat-re)
12795 (org-entry-end-position) t)
12796 (match-string-no-properties 1)))))
12798 (defvar org-last-changed-timestamp)
12799 (defvar org-last-inserted-timestamp)
12800 (defvar org-log-post-message)
12801 (defvar org-log-note-purpose)
12802 (defvar org-log-note-how)
12803 (defvar org-log-note-extra)
12804 (defun org-auto-repeat-maybe (done-word)
12805 "Check if the current headline contains a repeated deadline/schedule.
12806 If yes, set TODO state back to what it was and change the base date
12807 of repeating deadline/scheduled time stamps to new date.
12808 This function is run automatically after each state change to a DONE state."
12809 ;; last-state is dynamically scoped into this function
12810 (let* ((repeat (org-get-repeat))
12811 (aa (assoc org-last-state org-todo-kwd-alist))
12812 (interpret (nth 1 aa))
12813 (head (nth 2 aa))
12814 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12815 (msg "Entry repeats: ")
12816 (org-log-done nil)
12817 (org-todo-log-states nil)
12818 re type n what ts time to-state)
12819 (when repeat
12820 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12821 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12822 org-todo-repeat-to-state))
12823 (unless (and to-state (member to-state org-todo-keywords-1))
12824 (setq to-state (if (eq interpret 'type) org-last-state head)))
12825 (org-todo to-state)
12826 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12827 (org-entry-put nil "LAST_REPEAT" (format-time-string
12828 (org-time-stamp-format t t))))
12829 (when org-log-repeat
12830 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12831 (memq 'org-add-log-note post-command-hook))
12832 ;; OK, we are already setup for some record
12833 (if (eq org-log-repeat 'note)
12834 ;; make sure we take a note, not only a time stamp
12835 (setq org-log-note-how 'note))
12836 ;; Set up for taking a record
12837 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12838 org-last-state
12839 'findpos org-log-repeat)))
12840 (org-back-to-heading t)
12841 (org-add-planning-info nil nil 'closed)
12842 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12843 org-deadline-time-regexp "\\)\\|\\("
12844 org-ts-regexp "\\)"))
12845 (while (re-search-forward
12846 re (save-excursion (outline-next-heading) (point)) t)
12847 (setq type (if (match-end 1) org-scheduled-string
12848 (if (match-end 3) org-deadline-string "Plain:"))
12849 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12850 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12851 (setq n (string-to-number (match-string 2 ts))
12852 what (match-string 3 ts))
12853 (if (equal what "w") (setq n (* n 7) what "d"))
12854 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12855 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12856 ;; Preparation, see if we need to modify the start date for the change
12857 (when (match-end 1)
12858 (setq time (save-match-data (org-time-string-to-time ts)))
12859 (cond
12860 ((equal (match-string 1 ts) ".")
12861 ;; Shift starting date to today
12862 (org-timestamp-change
12863 (- (org-today) (time-to-days time))
12864 'day))
12865 ((equal (match-string 1 ts) "+")
12866 (let ((nshiftmax 10) (nshift 0))
12867 (while (or (= nshift 0)
12868 (<= (time-to-days time)
12869 (time-to-days (current-time))))
12870 (when (= (incf nshift) nshiftmax)
12871 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12872 (error "Abort")))
12873 (org-timestamp-change n (cdr (assoc what whata)))
12874 (org-at-timestamp-p t)
12875 (setq ts (match-string 1))
12876 (setq time (save-match-data (org-time-string-to-time ts)))))
12877 (org-timestamp-change (- n) (cdr (assoc what whata)))
12878 ;; rematch, so that we have everything in place for the real shift
12879 (org-at-timestamp-p t)
12880 (setq ts (match-string 1))
12881 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12882 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12883 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12884 (setq org-log-post-message msg)
12885 (message "%s" msg))))
12887 (defun org-show-todo-tree (arg)
12888 "Make a compact tree which shows all headlines marked with TODO.
12889 The tree will show the lines where the regexp matches, and all higher
12890 headlines above the match.
12891 With a \\[universal-argument] prefix, prompt for a regexp to match.
12892 With a numeric prefix N, construct a sparse tree for the Nth element
12893 of `org-todo-keywords-1'."
12894 (interactive "P")
12895 (let ((case-fold-search nil)
12896 (kwd-re
12897 (cond ((null arg) org-not-done-regexp)
12898 ((equal arg '(4))
12899 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12900 (mapcar 'list org-todo-keywords-1))))
12901 (concat "\\("
12902 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12903 "\\)\\>")))
12904 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12905 (regexp-quote (nth (1- (prefix-numeric-value arg))
12906 org-todo-keywords-1)))
12907 (t (user-error "Invalid prefix argument: %s" arg)))))
12908 (message "%d TODO entries found"
12909 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12911 (defun org-deadline (arg &optional time)
12912 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12913 With one universal prefix argument, remove any deadline from the item.
12914 With two universal prefix arguments, prompt for a warning delay.
12915 With argument TIME, set the deadline at the corresponding date. TIME
12916 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12917 (interactive "P")
12918 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12919 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12920 'region-start-level 'region))
12921 org-loop-over-headlines-in-active-region)
12922 (org-map-entries
12923 `(org-deadline ',arg ,time)
12924 org-loop-over-headlines-in-active-region
12925 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12926 (let* ((old-date (org-entry-get nil "DEADLINE"))
12927 (old-date-time (if old-date (org-time-string-to-time old-date)))
12928 (repeater (and old-date
12929 (string-match
12930 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12931 old-date)
12932 (match-string 1 old-date))))
12933 (cond
12934 ((equal arg '(4))
12935 (when (and old-date org-log-redeadline)
12936 (org-add-log-setup 'deldeadline nil old-date 'findpos
12937 org-log-redeadline))
12938 (org-remove-timestamp-with-keyword org-deadline-string)
12939 (message "Item no longer has a deadline."))
12940 ((equal arg '(16))
12941 (save-excursion
12942 (if (re-search-forward
12943 org-deadline-time-regexp
12944 (save-excursion (outline-next-heading) (point)) t)
12945 (let* ((rpl0 (match-string 1))
12946 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12947 (replace-match
12948 (concat org-deadline-string
12949 " <" rpl
12950 (format " -%dd"
12951 (abs
12952 (- (time-to-days
12953 (save-match-data
12954 (org-read-date nil t nil "Warn starting from" old-date-time)))
12955 (time-to-days old-date-time))))
12956 ">") t t))
12957 (user-error "No deadline information to update"))))
12959 (org-add-planning-info 'deadline time 'closed)
12960 (when (and old-date org-log-redeadline
12961 (not (equal old-date
12962 (substring org-last-inserted-timestamp 1 -1))))
12963 (org-add-log-setup 'redeadline nil old-date 'findpos
12964 org-log-redeadline))
12965 (when repeater
12966 (save-excursion
12967 (org-back-to-heading t)
12968 (when (re-search-forward (concat org-deadline-string " "
12969 org-last-inserted-timestamp)
12970 (save-excursion
12971 (outline-next-heading) (point)) t)
12972 (goto-char (1- (match-end 0)))
12973 (insert " " repeater)
12974 (setq org-last-inserted-timestamp
12975 (concat (substring org-last-inserted-timestamp 0 -1)
12976 " " repeater
12977 (substring org-last-inserted-timestamp -1))))))
12978 (message "Deadline on %s" org-last-inserted-timestamp))))))
12980 (defun org-schedule (arg &optional time)
12981 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12982 With one universal prefix argument, remove any scheduling date from the item.
12983 With two universal prefix arguments, prompt for a delay cookie.
12984 With argument TIME, scheduled at the corresponding date. TIME can
12985 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12986 (interactive "P")
12987 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12988 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12989 'region-start-level 'region))
12990 org-loop-over-headlines-in-active-region)
12991 (org-map-entries
12992 `(org-schedule ',arg ,time)
12993 org-loop-over-headlines-in-active-region
12994 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12995 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12996 (old-date-time (if old-date (org-time-string-to-time old-date)))
12997 (repeater (and old-date
12998 (string-match
12999 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13000 old-date)
13001 (match-string 1 old-date))))
13002 (cond
13003 ((equal arg '(4))
13004 (progn
13005 (when (and old-date org-log-reschedule)
13006 (org-add-log-setup 'delschedule nil old-date 'findpos
13007 org-log-reschedule))
13008 (org-remove-timestamp-with-keyword org-scheduled-string)
13009 (message "Item is no longer scheduled.")))
13010 ((equal arg '(16))
13011 (save-excursion
13012 (if (re-search-forward
13013 org-scheduled-time-regexp
13014 (save-excursion (outline-next-heading) (point)) t)
13015 (let* ((rpl0 (match-string 1))
13016 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13017 (replace-match
13018 (concat org-scheduled-string
13019 " <" rpl
13020 (format " -%dd"
13021 (abs
13022 (- (time-to-days
13023 (save-match-data
13024 (org-read-date nil t nil "Delay until" old-date-time)))
13025 (time-to-days old-date-time))))
13026 ">") t t))
13027 (user-error "No scheduled information to update"))))
13029 (org-add-planning-info 'scheduled time 'closed)
13030 (when (and old-date org-log-reschedule
13031 (not (equal old-date
13032 (substring org-last-inserted-timestamp 1 -1))))
13033 (org-add-log-setup 'reschedule nil old-date 'findpos
13034 org-log-reschedule))
13035 (when repeater
13036 (save-excursion
13037 (org-back-to-heading t)
13038 (when (re-search-forward (concat org-scheduled-string " "
13039 org-last-inserted-timestamp)
13040 (save-excursion
13041 (outline-next-heading) (point)) t)
13042 (goto-char (1- (match-end 0)))
13043 (insert " " repeater)
13044 (setq org-last-inserted-timestamp
13045 (concat (substring org-last-inserted-timestamp 0 -1)
13046 " " repeater
13047 (substring org-last-inserted-timestamp -1))))))
13048 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13050 (defun org-get-scheduled-time (pom &optional inherit)
13051 "Get the scheduled time as a time tuple, of a format suitable
13052 for calling org-schedule with, or if there is no scheduling,
13053 returns nil."
13054 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13055 (when time
13056 (apply 'encode-time (org-parse-time-string time)))))
13058 (defun org-get-deadline-time (pom &optional inherit)
13059 "Get the deadline as a time tuple, of a format suitable for
13060 calling org-deadline with, or if there is no scheduling, returns
13061 nil."
13062 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13063 (when time
13064 (apply 'encode-time (org-parse-time-string time)))))
13066 (defun org-remove-timestamp-with-keyword (keyword)
13067 "Remove all time stamps with KEYWORD in the current entry."
13068 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13069 beg)
13070 (save-excursion
13071 (org-back-to-heading t)
13072 (setq beg (point))
13073 (outline-next-heading)
13074 (while (re-search-backward re beg t)
13075 (replace-match "")
13076 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13077 (equal (char-before) ?\ ))
13078 (backward-delete-char 1)
13079 (if (string-match "^[ \t]*$" (buffer-substring
13080 (point-at-bol) (point-at-eol)))
13081 (delete-region (point-at-bol)
13082 (min (point-max) (1+ (point-at-eol))))))))))
13084 (defun org-add-planning-info (what &optional time &rest remove)
13085 "Insert new timestamp with keyword in the line directly after the headline.
13086 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13087 If non is given, the user is prompted for a date.
13088 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13089 be removed."
13090 (interactive)
13091 (let (org-time-was-given org-end-time-was-given ts
13092 end default-time default-input)
13094 (catch 'exit
13095 (when (and (memq what '(scheduled deadline))
13096 (or (not time)
13097 (and (stringp time)
13098 (string-match "^[-+]+[0-9]" time))))
13099 ;; Try to get a default date/time from existing timestamp
13100 (save-excursion
13101 (org-back-to-heading t)
13102 (setq end (save-excursion (outline-next-heading) (point)))
13103 (when (re-search-forward (if (eq what 'scheduled)
13104 org-scheduled-time-regexp
13105 org-deadline-time-regexp)
13106 end t)
13107 (setq ts (match-string 1)
13108 default-time
13109 (apply 'encode-time (org-parse-time-string ts))
13110 default-input (and ts (org-get-compact-tod ts))))))
13111 (when what
13112 (setq time
13113 (if (stringp time)
13114 ;; This is a string (relative or absolute), set proper date
13115 (apply 'encode-time
13116 (org-read-date-analyze
13117 time default-time (decode-time default-time)))
13118 ;; If necessary, get the time from the user
13119 (or time (org-read-date nil 'to-time nil nil
13120 default-time default-input)))))
13122 (when (and org-insert-labeled-timestamps-at-point
13123 (member what '(scheduled deadline)))
13124 (insert
13125 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13126 (org-insert-time-stamp time org-time-was-given
13127 nil nil nil (list org-end-time-was-given))
13128 (setq what nil))
13129 (save-excursion
13130 (save-restriction
13131 (let (col list elt ts buffer-invisibility-spec)
13132 (org-back-to-heading t)
13133 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13134 (goto-char (match-end 1))
13135 (setq col (current-column))
13136 (goto-char (match-end 0))
13137 (if (eobp) (insert "\n") (forward-char 1))
13138 (when (and (not what)
13139 (not (looking-at
13140 (concat "[ \t]*"
13141 org-keyword-time-not-clock-regexp))))
13142 ;; Nothing to add, nothing to remove...... :-)
13143 (throw 'exit nil))
13144 (if (and (not (looking-at org-outline-regexp))
13145 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13146 "[^\r\n]*"))
13147 (not (equal (match-string 1) org-clock-string)))
13148 (narrow-to-region (match-beginning 0) (match-end 0))
13149 (insert-before-markers "\n")
13150 (backward-char 1)
13151 (narrow-to-region (point) (point))
13152 (and org-adapt-indentation (org-indent-to-column col)))
13153 ;; Check if we have to remove something.
13154 (setq list (cons what remove))
13155 (while list
13156 (setq elt (pop list))
13157 (when (or (and (eq elt 'scheduled)
13158 (re-search-forward org-scheduled-time-regexp nil t))
13159 (and (eq elt 'deadline)
13160 (re-search-forward org-deadline-time-regexp nil t))
13161 (and (eq elt 'closed)
13162 (re-search-forward org-closed-time-regexp nil t)))
13163 (replace-match "")
13164 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13165 (and (looking-at "[ \t]+") (replace-match ""))
13166 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13167 (when what
13168 (insert
13169 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13170 (cond ((eq what 'scheduled) org-scheduled-string)
13171 ((eq what 'deadline) org-deadline-string)
13172 ((eq what 'closed) org-closed-string))
13173 " ")
13174 (setq ts (org-insert-time-stamp
13175 time
13176 (or org-time-was-given
13177 (and (eq what 'closed) org-log-done-with-time))
13178 (eq what 'closed)
13179 nil nil (list org-end-time-was-given)))
13180 (insert
13181 (if (not (or (bolp) (eq (char-before) ?\ )
13182 (memq (char-after) '(32 10))
13183 (eobp))) " " ""))
13184 (end-of-line 1))
13185 (goto-char (point-min))
13186 (widen)
13187 (if (and (looking-at "[ \t]*\n")
13188 (equal (char-before) ?\n))
13189 (delete-region (1- (point)) (point-at-eol)))
13190 ts))))))
13192 (defvar org-log-note-marker (make-marker))
13193 (defvar org-log-note-purpose nil)
13194 (defvar org-log-note-state nil)
13195 (defvar org-log-note-previous-state nil)
13196 (defvar org-log-note-how nil)
13197 (defvar org-log-note-extra nil)
13198 (defvar org-log-note-window-configuration nil)
13199 (defvar org-log-note-return-to (make-marker))
13200 (defvar org-log-note-effective-time nil
13201 "Remembered current time so that dynamically scoped
13202 `org-extend-today-until' affects tha timestamps in state change
13203 log")
13205 (defvar org-log-post-message nil
13206 "Message to be displayed after a log note has been stored.
13207 The auto-repeater uses this.")
13209 (defun org-add-note ()
13210 "Add a note to the current entry.
13211 This is done in the same way as adding a state change note."
13212 (interactive)
13213 (org-add-log-setup 'note nil nil 'findpos nil))
13215 (defvar org-property-end-re)
13216 (defun org-add-log-setup (&optional purpose state prev-state
13217 findpos how extra)
13218 "Set up the post command hook to take a note.
13219 If this is about to TODO state change, the new state is expected in STATE.
13220 When FINDPOS is non-nil, find the correct position for the note in
13221 the current entry. If not, assume that it can be inserted at point.
13222 HOW is an indicator what kind of note should be created.
13223 EXTRA is additional text that will be inserted into the notes buffer."
13224 (let* ((org-log-into-drawer (org-log-into-drawer))
13225 (drawer (cond ((stringp org-log-into-drawer)
13226 org-log-into-drawer)
13227 (org-log-into-drawer "LOGBOOK"))))
13228 (save-restriction
13229 (save-excursion
13230 (when findpos
13231 (org-back-to-heading t)
13232 (narrow-to-region (point) (save-excursion
13233 (outline-next-heading) (point)))
13234 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13235 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13236 "[^\r\n]*\\)?"))
13237 (goto-char (match-end 0))
13238 (cond
13239 (drawer
13240 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13241 nil t)
13242 (progn
13243 (goto-char (match-end 0))
13244 (or org-log-states-order-reversed
13245 (and (re-search-forward org-property-end-re nil t)
13246 (goto-char (1- (match-beginning 0))))))
13247 (insert "\n:" drawer ":\n:END:")
13248 (beginning-of-line 0)
13249 (org-indent-line)
13250 (beginning-of-line 2)
13251 (org-indent-line)
13252 (end-of-line 0)))
13253 ((and org-log-state-notes-insert-after-drawers
13254 (save-excursion
13255 (forward-line) (looking-at org-drawer-regexp)))
13256 (forward-line)
13257 (while (looking-at org-drawer-regexp)
13258 (goto-char (match-end 0))
13259 (re-search-forward org-property-end-re (point-max) t)
13260 (forward-line))
13261 (forward-line -1)))
13262 (unless org-log-states-order-reversed
13263 (and (= (char-after) ?\n) (forward-char 1))
13264 (org-skip-over-state-notes)
13265 (skip-chars-backward " \t\n\r")))
13266 (move-marker org-log-note-marker (point))
13267 (setq org-log-note-purpose purpose
13268 org-log-note-state state
13269 org-log-note-previous-state prev-state
13270 org-log-note-how how
13271 org-log-note-extra extra
13272 org-log-note-effective-time (org-current-effective-time))
13273 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13275 (defun org-skip-over-state-notes ()
13276 "Skip past the list of State notes in an entry."
13277 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13278 (when (ignore-errors (goto-char (org-in-item-p)))
13279 (let* ((struct (org-list-struct))
13280 (prevs (org-list-prevs-alist struct)))
13281 (while (looking-at "[ \t]*- State")
13282 (goto-char (or (org-list-get-next-item (point) struct prevs)
13283 (org-list-get-item-end (point) struct)))))))
13285 (defun org-add-log-note (&optional purpose)
13286 "Pop up a window for taking a note, and add this note later at point."
13287 (remove-hook 'post-command-hook 'org-add-log-note)
13288 (setq org-log-note-window-configuration (current-window-configuration))
13289 (delete-other-windows)
13290 (move-marker org-log-note-return-to (point))
13291 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13292 (goto-char org-log-note-marker)
13293 (org-switch-to-buffer-other-window "*Org Note*")
13294 (erase-buffer)
13295 (if (memq org-log-note-how '(time state))
13296 (let (current-prefix-arg) (org-store-log-note))
13297 (let ((org-inhibit-startup t)) (org-mode))
13298 (insert (format "# Insert note for %s.
13299 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13300 (cond
13301 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13302 ((eq org-log-note-purpose 'done) "closed todo item")
13303 ((eq org-log-note-purpose 'state)
13304 (format "state change from \"%s\" to \"%s\""
13305 (or org-log-note-previous-state "")
13306 (or org-log-note-state "")))
13307 ((eq org-log-note-purpose 'reschedule)
13308 "rescheduling")
13309 ((eq org-log-note-purpose 'delschedule)
13310 "no longer scheduled")
13311 ((eq org-log-note-purpose 'redeadline)
13312 "changing deadline")
13313 ((eq org-log-note-purpose 'deldeadline)
13314 "removing deadline")
13315 ((eq org-log-note-purpose 'refile)
13316 "refiling")
13317 ((eq org-log-note-purpose 'note)
13318 "this entry")
13319 (t (error "This should not happen")))))
13320 (if org-log-note-extra (insert org-log-note-extra))
13321 (org-set-local 'org-finish-function 'org-store-log-note)
13322 (run-hooks 'org-log-buffer-setup-hook)))
13324 (defvar org-note-abort nil) ; dynamically scoped
13325 (defun org-store-log-note ()
13326 "Finish taking a log note, and insert it to where it belongs."
13327 (let ((txt (buffer-string)))
13328 (kill-buffer (current-buffer))
13329 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13330 lines ind bul)
13331 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13332 (setq txt (replace-match "" t t txt)))
13333 (if (string-match "\\s-+\\'" txt)
13334 (setq txt (replace-match "" t t txt)))
13335 (setq lines (org-split-string txt "\n"))
13336 (when (and note (string-match "\\S-" note))
13337 (setq note
13338 (org-replace-escapes
13339 note
13340 (list (cons "%u" (user-login-name))
13341 (cons "%U" user-full-name)
13342 (cons "%t" (format-time-string
13343 (org-time-stamp-format 'long 'inactive)
13344 org-log-note-effective-time))
13345 (cons "%T" (format-time-string
13346 (org-time-stamp-format 'long nil)
13347 org-log-note-effective-time))
13348 (cons "%d" (format-time-string
13349 (org-time-stamp-format nil 'inactive)
13350 org-log-note-effective-time))
13351 (cons "%D" (format-time-string
13352 (org-time-stamp-format nil nil)
13353 org-log-note-effective-time))
13354 (cons "%s" (if org-log-note-state
13355 (concat "\"" org-log-note-state "\"")
13356 ""))
13357 (cons "%S" (if org-log-note-previous-state
13358 (concat "\"" org-log-note-previous-state "\"")
13359 "\"\"")))))
13360 (if lines (setq note (concat note " \\\\")))
13361 (push note lines))
13362 (when (or current-prefix-arg org-note-abort)
13363 (when org-log-into-drawer
13364 (org-remove-empty-drawer-at
13365 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13366 org-log-note-marker))
13367 (setq lines nil))
13368 (when lines
13369 (with-current-buffer (marker-buffer org-log-note-marker)
13370 (save-excursion
13371 (goto-char org-log-note-marker)
13372 (move-marker org-log-note-marker nil)
13373 (end-of-line 1)
13374 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13375 (setq ind (save-excursion
13376 (if (ignore-errors (goto-char (org-in-item-p)))
13377 (let ((struct (org-list-struct)))
13378 (org-list-get-ind
13379 (org-list-get-top-point struct) struct))
13380 (skip-chars-backward " \r\t\n")
13381 (cond
13382 ((and (org-at-heading-p)
13383 org-adapt-indentation)
13384 (1+ (org-current-level)))
13385 ((org-at-heading-p) 0)
13386 (t (org-get-indentation))))))
13387 (setq bul (org-list-bullet-string "-"))
13388 (org-indent-line-to ind)
13389 (insert bul (pop lines))
13390 (let ((ind-body (+ (length bul) ind)))
13391 (while lines
13392 (insert "\n")
13393 (org-indent-line-to ind-body)
13394 (insert (pop lines))))
13395 (message "Note stored")
13396 (org-back-to-heading t)
13397 (org-cycle-hide-drawers 'children))
13398 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13399 ;; from within `org-add-log-note' because `buffer-undo-list'
13400 ;; is then modified outside of `org-with-remote-undo'.
13401 (when (eq this-command 'org-agenda-todo)
13402 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13403 ;; Don't add undo information when called from `org-agenda-todo'
13404 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13405 (set-window-configuration org-log-note-window-configuration)
13406 (with-current-buffer (marker-buffer org-log-note-return-to)
13407 (goto-char org-log-note-return-to))
13408 (move-marker org-log-note-return-to nil)
13409 (and org-log-post-message (message "%s" org-log-post-message))))
13411 (defun org-remove-empty-drawer-at (drawer pos)
13412 "Remove an empty drawer DRAWER at position POS.
13413 POS may also be a marker."
13414 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13415 (save-excursion
13416 (save-restriction
13417 (widen)
13418 (goto-char pos)
13419 (if (org-in-regexp
13420 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13421 (replace-match ""))))))
13423 (defvar org-ts-type nil)
13424 (defun org-sparse-tree (&optional arg type)
13425 "Create a sparse tree, prompt for the details.
13426 This command can create sparse trees. You first need to select the type
13427 of match used to create the tree:
13429 t Show all TODO entries.
13430 T Show entries with a specific TODO keyword.
13431 m Show entries selected by a tags/property match.
13432 p Enter a property name and its value (both with completion on existing
13433 names/values) and show entries with that property.
13434 r Show entries matching a regular expression (`/' can be used as well).
13435 b Show deadlines and scheduled items before a date.
13436 a Show deadlines and scheduled items after a date.
13437 d Show deadlines due within `org-deadline-warning-days'.
13438 D Show deadlines and scheduled items between a date range."
13439 (interactive "P")
13440 (let (ans kwd value ts-type)
13441 (setq type (or type org-sparse-tree-default-date-type))
13442 (setq org-ts-type type)
13443 (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"
13444 (cond ((eq type 'all) "all timestamps")
13445 ((eq type 'scheduled) "only scheduled")
13446 ((eq type 'deadline) "only deadline")
13447 ((eq type 'active) "only active timestamps")
13448 ((eq type 'inactive) "only inactive timestamps")
13449 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13450 ((eq type 'closed) "with a closed time-stamp")
13451 (t "scheduled/deadline")))
13452 (setq ans (read-char-exclusive))
13453 (cond
13454 ((equal ans ?c)
13455 (org-sparse-tree
13456 arg (cadr (member type '(scheduled-or-deadline
13457 all scheduled deadline active inactive closed)))))
13458 ((equal ans ?d)
13459 (call-interactively 'org-check-deadlines))
13460 ((equal ans ?b)
13461 (call-interactively 'org-check-before-date))
13462 ((equal ans ?a)
13463 (call-interactively 'org-check-after-date))
13464 ((equal ans ?D)
13465 (call-interactively 'org-check-dates-range))
13466 ((equal ans ?t)
13467 (call-interactively 'org-show-todo-tree))
13468 ((equal ans ?T)
13469 (org-show-todo-tree '(4)))
13470 ((member ans '(?T ?m))
13471 (call-interactively 'org-match-sparse-tree))
13472 ((member ans '(?p ?P))
13473 (setq kwd (org-icompleting-read "Property: "
13474 (mapcar 'list (org-buffer-property-keys))))
13475 (setq value (org-icompleting-read "Value: "
13476 (mapcar 'list (org-property-values kwd))))
13477 (unless (string-match "\\`{.*}\\'" value)
13478 (setq value (concat "\"" value "\"")))
13479 (org-match-sparse-tree arg (concat kwd "=" value)))
13480 ((member ans '(?r ?R ?/))
13481 (call-interactively 'org-occur))
13482 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13484 (defvar org-occur-highlights nil
13485 "List of overlays used for occur matches.")
13486 (make-variable-buffer-local 'org-occur-highlights)
13487 (defvar org-occur-parameters nil
13488 "Parameters of the active org-occur calls.
13489 This is a list, each call to org-occur pushes as cons cell,
13490 containing the regular expression and the callback, onto the list.
13491 The list can contain several entries if `org-occur' has been called
13492 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13493 will only contain one set of parameters. When the highlights are
13494 removed (for example with `C-c C-c', or with the next edit (depending
13495 on `org-remove-highlights-with-change'), this variable is emptied
13496 as well.")
13497 (make-variable-buffer-local 'org-occur-parameters)
13499 (defun org-occur (regexp &optional keep-previous callback)
13500 "Make a compact tree which shows all matches of REGEXP.
13501 The tree will show the lines where the regexp matches, and all higher
13502 headlines above the match. It will also show the heading after the match,
13503 to make sure editing the matching entry is easy.
13504 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13505 call to `org-occur' will be kept, to allow stacking of calls to this
13506 command.
13507 If CALLBACK is non-nil, it is a function which is called to confirm
13508 that the match should indeed be shown."
13509 (interactive "sRegexp: \nP")
13510 (when (equal regexp "")
13511 (user-error "Regexp cannot be empty"))
13512 (unless keep-previous
13513 (org-remove-occur-highlights nil nil t))
13514 (push (cons regexp callback) org-occur-parameters)
13515 (let ((cnt 0))
13516 (save-excursion
13517 (goto-char (point-min))
13518 (if (or (not keep-previous) ; do not want to keep
13519 (not org-occur-highlights)) ; no previous matches
13520 ;; hide everything
13521 (org-overview))
13522 (while (re-search-forward regexp nil t)
13523 (when (or (not callback)
13524 (save-match-data (funcall callback)))
13525 (setq cnt (1+ cnt))
13526 (when org-highlight-sparse-tree-matches
13527 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13528 (org-show-context 'occur-tree))))
13529 (when org-remove-highlights-with-change
13530 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13531 nil 'local))
13532 (unless org-sparse-tree-open-archived-trees
13533 (org-hide-archived-subtrees (point-min) (point-max)))
13534 (run-hooks 'org-occur-hook)
13535 (if (org-called-interactively-p 'interactive)
13536 (message "%d match(es) for regexp %s" cnt regexp))
13537 cnt))
13539 (defun org-occur-next-match (&optional n reset)
13540 "Function for `next-error-function' to find sparse tree matches.
13541 N is the number of matches to move, when negative move backwards.
13542 RESET is entirely ignored - this function always goes back to the
13543 starting point when no match is found."
13544 (let* ((limit (if (< n 0) (point-min) (point-max)))
13545 (search-func (if (< n 0)
13546 'previous-single-char-property-change
13547 'next-single-char-property-change))
13548 (n (abs n))
13549 (pos (point))
13551 (catch 'exit
13552 (while (setq p1 (funcall search-func (point) 'org-type))
13553 (when (equal p1 limit)
13554 (goto-char pos)
13555 (error "No more matches"))
13556 (when (equal (get-char-property p1 'org-type) 'org-occur)
13557 (setq n (1- n))
13558 (when (= n 0)
13559 (goto-char p1)
13560 (throw 'exit (point))))
13561 (goto-char p1))
13562 (goto-char p1)
13563 (error "No more matches"))))
13565 (defun org-show-context (&optional key)
13566 "Make sure point and context are visible.
13567 How much context is shown depends upon the variables
13568 `org-show-hierarchy-above', `org-show-following-heading',
13569 `org-show-entry-below' and `org-show-siblings'."
13570 (let ((heading-p (org-at-heading-p t))
13571 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13572 (following-p (org-get-alist-option org-show-following-heading key))
13573 (entry-p (org-get-alist-option org-show-entry-below key))
13574 (siblings-p (org-get-alist-option org-show-siblings key)))
13575 ;; Show heading or entry text
13576 (if (and heading-p (not entry-p))
13577 (org-flag-heading nil) ; only show the heading
13578 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13579 (org-show-hidden-entry))) ; show entire entry
13580 (when following-p
13581 ;; Show next sibling, or heading below text
13582 (save-excursion
13583 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13584 (org-flag-heading nil))))
13585 (when siblings-p (org-show-siblings))
13586 (when hierarchy-p
13587 ;; show all higher headings, possibly with siblings
13588 (save-excursion
13589 (while (and (condition-case nil
13590 (progn (org-up-heading-all 1) t)
13591 (error nil))
13592 (not (bobp)))
13593 (org-flag-heading nil)
13594 (when siblings-p (org-show-siblings)))))
13595 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13597 (defvar org-reveal-start-hook nil
13598 "Hook run before revealing a location.")
13600 (defun org-reveal (&optional siblings)
13601 "Show current entry, hierarchy above it, and the following headline.
13602 This can be used to show a consistent set of context around locations
13603 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13604 not t for the search context.
13606 With optional argument SIBLINGS, on each level of the hierarchy all
13607 siblings are shown. This repairs the tree structure to what it would
13608 look like when opened with hierarchical calls to `org-cycle'.
13609 With double optional argument \\[universal-argument] \\[universal-argument], \
13610 go to the parent and show the
13611 entire tree."
13612 (interactive "P")
13613 (run-hooks 'org-reveal-start-hook)
13614 (let ((org-show-hierarchy-above t)
13615 (org-show-following-heading t)
13616 (org-show-siblings (if siblings t org-show-siblings)))
13617 (org-show-context nil))
13618 (when (equal siblings '(16))
13619 (save-excursion
13620 (when (org-up-heading-safe)
13621 (org-show-subtree)
13622 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13624 (defun org-highlight-new-match (beg end)
13625 "Highlight from BEG to END and mark the highlight is an occur headline."
13626 (let ((ov (make-overlay beg end)))
13627 (overlay-put ov 'face 'secondary-selection)
13628 (overlay-put ov 'org-type 'org-occur)
13629 (push ov org-occur-highlights)))
13631 (defun org-remove-occur-highlights (&optional beg end noremove)
13632 "Remove the occur highlights from the buffer.
13633 BEG and END are ignored. If NOREMOVE is nil, remove this function
13634 from the `before-change-functions' in the current buffer."
13635 (interactive)
13636 (unless org-inhibit-highlight-removal
13637 (mapc 'delete-overlay org-occur-highlights)
13638 (setq org-occur-highlights nil)
13639 (setq org-occur-parameters nil)
13640 (unless noremove
13641 (remove-hook 'before-change-functions
13642 'org-remove-occur-highlights 'local))))
13644 ;;;; Priorities
13646 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13647 "Regular expression matching the priority indicator.")
13649 (defvar org-remove-priority-next-time nil)
13651 (defun org-priority-up ()
13652 "Increase the priority of the current item."
13653 (interactive)
13654 (org-priority 'up))
13656 (defun org-priority-down ()
13657 "Decrease the priority of the current item."
13658 (interactive)
13659 (org-priority 'down))
13661 (defun org-priority (&optional action show)
13662 "Change the priority of an item.
13663 ACTION can be `set', `up', `down', or a character."
13664 (interactive "P")
13665 (if (equal action '(4))
13666 (org-show-priority)
13667 (unless org-enable-priority-commands
13668 (user-error "Priority commands are disabled"))
13669 (setq action (or action 'set))
13670 (let (current new news have remove)
13671 (save-excursion
13672 (org-back-to-heading t)
13673 (if (looking-at org-priority-regexp)
13674 (setq current (string-to-char (match-string 2))
13675 have t))
13676 (cond
13677 ((eq action 'remove)
13678 (setq remove t new ?\ ))
13679 ((or (eq action 'set)
13680 (if (featurep 'xemacs) (characterp action) (integerp action)))
13681 (if (not (eq action 'set))
13682 (setq new action)
13683 (message "Priority %c-%c, SPC to remove: "
13684 org-highest-priority org-lowest-priority)
13685 (save-match-data
13686 (setq new (read-char-exclusive))))
13687 (if (and (= (upcase org-highest-priority) org-highest-priority)
13688 (= (upcase org-lowest-priority) org-lowest-priority))
13689 (setq new (upcase new)))
13690 (cond ((equal new ?\ ) (setq remove t))
13691 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13692 (user-error "Priority must be between `%c' and `%c'"
13693 org-highest-priority org-lowest-priority))))
13694 ((eq action 'up)
13695 (setq new (if have
13696 (1- current) ; normal cycling
13697 ;; last priority was empty
13698 (if (eq last-command this-command)
13699 org-lowest-priority ; wrap around empty to lowest
13700 ;; default
13701 (if org-priority-start-cycle-with-default
13702 org-default-priority
13703 (1- org-default-priority))))))
13704 ((eq action 'down)
13705 (setq new (if have
13706 (1+ current) ; normal cycling
13707 ;; last priority was empty
13708 (if (eq last-command this-command)
13709 org-highest-priority ; wrap around empty to highest
13710 ;; default
13711 (if org-priority-start-cycle-with-default
13712 org-default-priority
13713 (1+ org-default-priority))))))
13714 (t (user-error "Invalid action")))
13715 (if (or (< (upcase new) org-highest-priority)
13716 (> (upcase new) org-lowest-priority))
13717 (if (and (memq action '(up down))
13718 (not have) (not (eq last-command this-command)))
13719 ;; `new' is from default priority
13720 (error
13721 "The default can not be set, see `org-default-priority' why")
13722 ;; normal cycling: `new' is beyond highest/lowest priority
13723 ;; and is wrapped around to the empty priority
13724 (setq remove t)))
13725 (setq news (format "%c" new))
13726 (if have
13727 (if remove
13728 (replace-match "" t t nil 1)
13729 (replace-match news t t nil 2))
13730 (if remove
13731 (user-error "No priority cookie found in line")
13732 (let ((case-fold-search nil))
13733 (looking-at org-todo-line-regexp))
13734 (if (match-end 2)
13735 (progn
13736 (goto-char (match-end 2))
13737 (insert " [#" news "]"))
13738 (goto-char (match-beginning 3))
13739 (insert "[#" news "] "))))
13740 (org-preserve-lc (org-set-tags nil 'align)))
13741 (if remove
13742 (message "Priority removed")
13743 (message "Priority of current item set to %s" news)))))
13745 (defun org-show-priority ()
13746 "Show the priority of the current item.
13747 This priority is composed of the main priority given with the [#A] cookies,
13748 and by additional input from the age of a schedules or deadline entry."
13749 (interactive)
13750 (let ((pri (if (eq major-mode 'org-agenda-mode)
13751 (org-get-at-bol 'priority)
13752 (save-excursion
13753 (save-match-data
13754 (beginning-of-line)
13755 (and (looking-at org-heading-regexp)
13756 (org-get-priority (match-string 0))))))))
13757 (message "Priority is %d" (if pri pri -1000))))
13759 (defun org-get-priority (s)
13760 "Find priority cookie and return priority."
13761 (save-match-data
13762 (if (functionp org-get-priority-function)
13763 (funcall org-get-priority-function)
13764 (if (not (string-match org-priority-regexp s))
13765 (* 1000 (- org-lowest-priority org-default-priority))
13766 (* 1000 (- org-lowest-priority
13767 (string-to-char (match-string 2 s))))))))
13769 ;;;; Tags
13771 (defvar org-agenda-archives-mode)
13772 (defvar org-map-continue-from nil
13773 "Position from where mapping should continue.
13774 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13776 (defvar org-scanner-tags nil
13777 "The current tag list while the tags scanner is running.")
13778 (defvar org-trust-scanner-tags nil
13779 "Should `org-get-tags-at' use the tags for the scanner.
13780 This is for internal dynamical scoping only.
13781 When this is non-nil, the function `org-get-tags-at' will return the value
13782 of `org-scanner-tags' instead of building the list by itself. This
13783 can lead to large speed-ups when the tags scanner is used in a file with
13784 many entries, and when the list of tags is retrieved, for example to
13785 obtain a list of properties. Building the tags list for each entry in such
13786 a file becomes an N^2 operation - but with this variable set, it scales
13787 as N.")
13789 (defun org-scan-tags (action matcher todo-only &optional start-level)
13790 "Sca headline tags with inheritance and produce output ACTION.
13792 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13793 or `agenda' to produce an entry list for an agenda view. It can also be
13794 a Lisp form or a function that should be called at each matched headline, in
13795 this case the return value is a list of all return values from these calls.
13797 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13798 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13799 only lines with a not-done TODO keyword are included in the output.
13800 This should be the same variable that was scoped into
13801 and set by `org-make-tags-matcher' when it constructed MATCHER.
13803 START-LEVEL can be a string with asterisks, reducing the scope to
13804 headlines matching this string."
13805 (require 'org-agenda)
13806 (let* ((re (concat "^"
13807 (if start-level
13808 ;; Get the correct level to match
13809 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13810 org-outline-regexp)
13811 " *\\(\\<\\("
13812 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13813 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13814 (props (list 'face 'default
13815 'done-face 'org-agenda-done
13816 'undone-face 'default
13817 'mouse-face 'highlight
13818 'org-not-done-regexp org-not-done-regexp
13819 'org-todo-regexp org-todo-regexp
13820 'org-complex-heading-regexp org-complex-heading-regexp
13821 'help-echo
13822 (format "mouse-2 or RET jump to org file %s"
13823 (abbreviate-file-name
13824 (or (buffer-file-name (buffer-base-buffer))
13825 (buffer-name (buffer-base-buffer)))))))
13826 (org-map-continue-from nil)
13827 lspos tags tags-list
13828 (tags-alist (list (cons 0 org-file-tags)))
13829 (llast 0) rtn rtn1 level category i txt
13830 todo marker entry priority)
13831 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13832 (setq action (list 'lambda nil action)))
13833 (save-excursion
13834 (goto-char (point-min))
13835 (when (eq action 'sparse-tree)
13836 (org-overview)
13837 (org-remove-occur-highlights))
13838 (while (let (case-fold-search)
13839 (re-search-forward re nil t))
13840 (setq org-map-continue-from nil)
13841 (catch :skip
13842 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13843 tags (if (match-end 4) (org-match-string-no-properties 4)))
13844 (goto-char (setq lspos (match-beginning 0)))
13845 (setq level (org-reduced-level (org-outline-level))
13846 category (org-get-category))
13847 (setq i llast llast level)
13848 ;; remove tag lists from same and sublevels
13849 (while (>= i level)
13850 (when (setq entry (assoc i tags-alist))
13851 (setq tags-alist (delete entry tags-alist)))
13852 (setq i (1- i)))
13853 ;; add the next tags
13854 (when tags
13855 (setq tags (org-split-string tags ":")
13856 tags-alist
13857 (cons (cons level tags) tags-alist)))
13858 ;; compile tags for current headline
13859 (setq tags-list
13860 (if org-use-tag-inheritance
13861 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13862 tags)
13863 org-scanner-tags tags-list)
13864 (when org-use-tag-inheritance
13865 (setcdr (car tags-alist)
13866 (mapcar (lambda (x)
13867 (setq x (copy-sequence x))
13868 (org-add-prop-inherited x))
13869 (cdar tags-alist))))
13870 (when (and tags org-use-tag-inheritance
13871 (or (not (eq t org-use-tag-inheritance))
13872 org-tags-exclude-from-inheritance))
13873 ;; selective inheritance, remove uninherited ones
13874 (setcdr (car tags-alist)
13875 (org-remove-uninherited-tags (cdar tags-alist))))
13876 (when (and
13878 ;; eval matcher only when the todo condition is OK
13879 (and (or (not todo-only) (member todo org-not-done-keywords))
13880 (let ((case-fold-search t) (org-trust-scanner-tags t))
13881 (eval matcher)))
13883 ;; Call the skipper, but return t if it does not skip,
13884 ;; so that the `and' form continues evaluating
13885 (progn
13886 (unless (eq action 'sparse-tree) (org-agenda-skip))
13889 ;; Check if timestamps are deselecting this entry
13890 (or (not todo-only)
13891 (and (member todo org-not-done-keywords)
13892 (or (not org-agenda-tags-todo-honor-ignore-options)
13893 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13895 ;; select this headline
13896 (cond
13897 ((eq action 'sparse-tree)
13898 (and org-highlight-sparse-tree-matches
13899 (org-get-heading) (match-end 0)
13900 (org-highlight-new-match
13901 (match-beginning 1) (match-end 1)))
13902 (org-show-context 'tags-tree))
13903 ((eq action 'agenda)
13904 (setq txt (org-agenda-format-item
13906 (concat
13907 (if (eq org-tags-match-list-sublevels 'indented)
13908 (make-string (1- level) ?.) "")
13909 (org-get-heading))
13910 level category
13911 tags-list)
13912 priority (org-get-priority txt))
13913 (goto-char lspos)
13914 (setq marker (org-agenda-new-marker))
13915 (org-add-props txt props
13916 'org-marker marker 'org-hd-marker marker 'org-category category
13917 'todo-state todo
13918 'priority priority 'type "tagsmatch")
13919 (push txt rtn))
13920 ((functionp action)
13921 (setq org-map-continue-from nil)
13922 (save-excursion
13923 (setq rtn1 (funcall action))
13924 (push rtn1 rtn)))
13925 (t (user-error "Invalid action")))
13927 ;; if we are to skip sublevels, jump to end of subtree
13928 (unless org-tags-match-list-sublevels
13929 (org-end-of-subtree t)
13930 (backward-char 1))))
13931 ;; Get the correct position from where to continue
13932 (if org-map-continue-from
13933 (goto-char org-map-continue-from)
13934 (and (= (point) lspos) (end-of-line 1)))))
13935 (when (and (eq action 'sparse-tree)
13936 (not org-sparse-tree-open-archived-trees))
13937 (org-hide-archived-subtrees (point-min) (point-max)))
13938 (nreverse rtn)))
13940 (defun org-remove-uninherited-tags (tags)
13941 "Remove all tags that are not inherited from the list TAGS."
13942 (cond
13943 ((eq org-use-tag-inheritance t)
13944 (if org-tags-exclude-from-inheritance
13945 (org-delete-all org-tags-exclude-from-inheritance tags)
13946 tags))
13947 ((not org-use-tag-inheritance) nil)
13948 ((stringp org-use-tag-inheritance)
13949 (delq nil (mapcar
13950 (lambda (x)
13951 (if (and (string-match org-use-tag-inheritance x)
13952 (not (member x org-tags-exclude-from-inheritance)))
13953 x nil))
13954 tags)))
13955 ((listp org-use-tag-inheritance)
13956 (delq nil (mapcar
13957 (lambda (x)
13958 (if (member x org-use-tag-inheritance) x nil))
13959 tags)))))
13961 (defun org-match-sparse-tree (&optional todo-only match)
13962 "Create a sparse tree according to tags string MATCH.
13963 MATCH can contain positive and negative selection of tags, like
13964 \"+WORK+URGENT-WITHBOSS\".
13965 If optional argument TODO-ONLY is non-nil, only select lines that are
13966 also TODO lines."
13967 (interactive "P")
13968 (org-agenda-prepare-buffers (list (current-buffer)))
13969 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13971 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13973 (defvar org-cached-props nil)
13974 (defun org-cached-entry-get (pom property)
13975 (if (or (eq t org-use-property-inheritance)
13976 (and (stringp org-use-property-inheritance)
13977 (string-match org-use-property-inheritance property))
13978 (and (listp org-use-property-inheritance)
13979 (member property org-use-property-inheritance)))
13980 ;; Caching is not possible, check it directly
13981 (org-entry-get pom property 'inherit)
13982 ;; Get all properties, so that we can do complicated checks easily
13983 (cdr (assoc property (or org-cached-props
13984 (setq org-cached-props
13985 (org-entry-properties pom)))))))
13987 (defun org-global-tags-completion-table (&optional files)
13988 "Return the list of all tags in all agenda buffer/files.
13989 Optional FILES argument is a list of files which can be used
13990 instead of the agenda files."
13991 (save-excursion
13992 (org-uniquify
13993 (delq nil
13994 (apply 'append
13995 (mapcar
13996 (lambda (file)
13997 (set-buffer (find-file-noselect file))
13998 (append (org-get-buffer-tags)
13999 (mapcar (lambda (x) (if (stringp (car-safe x))
14000 (list (car-safe x)) nil))
14001 org-tag-alist)))
14002 (if (and files (car files))
14003 files
14004 (org-agenda-files))))))))
14006 (defun org-make-tags-matcher (match)
14007 "Create the TAGS/TODO matcher form for the selection string MATCH.
14009 The variable `todo-only' is scoped dynamically into this function.
14010 It will be set to t if the matcher restricts matching to TODO entries,
14011 otherwise will not be touched.
14013 Returns a cons of the selection string MATCH and the constructed
14014 lisp form implementing the matcher. The matcher is to be evaluated
14015 at an Org entry, with point on the headline, and returns t if the
14016 entry matches the selection string MATCH. The returned lisp form
14017 references two variables with information about the entry, which
14018 must be bound around the form's evaluation: todo, the TODO keyword
14019 at the entry (or nil of none); and tags-list, the list of all tags
14020 at the entry including inherited ones. Additionally, the category
14021 of the entry (if any) must be specified as the text property
14022 'org-category on the headline.
14024 See also `org-scan-tags'.
14026 (declare (special todo-only))
14027 (unless (boundp 'todo-only)
14028 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14029 (unless match
14030 ;; Get a new match request, with completion against the global
14031 ;; tags table and the local tags in current buffer
14032 (let ((org-last-tags-completion-table
14033 (org-uniquify
14034 (delq nil (append (org-get-buffer-tags)
14035 (org-global-tags-completion-table))))))
14036 (setq match (org-completing-read-no-i
14037 "Match: " 'org-tags-completion-function nil nil nil
14038 'org-tags-history))))
14040 ;; Parse the string and create a lisp form
14041 (let ((match0 match)
14042 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14043 minus tag mm
14044 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14045 orterms term orlist re-p str-p level-p level-op time-p
14046 prop-p pn pv po gv rest)
14047 ;; Expand group tags
14048 (setq match (org-tags-expand match))
14049 (if (string-match "/+" match)
14050 ;; match contains also a todo-matching request
14051 (progn
14052 (setq tagsmatch (substring match 0 (match-beginning 0))
14053 todomatch (substring match (match-end 0)))
14054 (if (string-match "^!" todomatch)
14055 (setq todo-only t todomatch (substring todomatch 1)))
14056 (if (string-match "^\\s-*$" todomatch)
14057 (setq todomatch nil)))
14058 ;; only matching tags
14059 (setq tagsmatch match todomatch nil))
14061 ;; Make the tags matcher
14062 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14063 (setq tagsmatcher t)
14064 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14065 (while (setq term (pop orterms))
14066 (while (and (equal (substring term -1) "\\") orterms)
14067 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14068 (while (string-match re term)
14069 (setq rest (substring term (match-end 0))
14070 minus (and (match-end 1)
14071 (equal (match-string 1 term) "-"))
14072 tag (save-match-data (replace-regexp-in-string
14073 "\\\\-" "-"
14074 (match-string 2 term)))
14075 re-p (equal (string-to-char tag) ?{)
14076 level-p (match-end 4)
14077 prop-p (match-end 5)
14078 mm (cond
14079 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14080 (level-p
14081 (setq level-op (org-op-to-function (match-string 3 term)))
14082 `(,level-op level ,(string-to-number
14083 (match-string 4 term))))
14084 (prop-p
14085 (setq pn (match-string 5 term)
14086 po (match-string 6 term)
14087 pv (match-string 7 term)
14088 re-p (equal (string-to-char pv) ?{)
14089 str-p (equal (string-to-char pv) ?\")
14090 time-p (save-match-data
14091 (string-match "^\"[[<].*[]>]\"$" pv))
14092 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14093 (if time-p (setq pv (org-matcher-time pv)))
14094 (setq po (org-op-to-function po (if time-p 'time str-p)))
14095 (cond
14096 ((equal pn "CATEGORY")
14097 (setq gv '(get-text-property (point) 'org-category)))
14098 ((equal pn "TODO")
14099 (setq gv 'todo))
14101 (setq gv `(org-cached-entry-get nil ,pn))))
14102 (if re-p
14103 (if (eq po 'org<>)
14104 `(not (string-match ,pv (or ,gv "")))
14105 `(string-match ,pv (or ,gv "")))
14106 (if str-p
14107 `(,po (or ,gv "") ,pv)
14108 `(,po (string-to-number (or ,gv ""))
14109 ,(string-to-number pv) ))))
14110 (t `(member ,tag tags-list)))
14111 mm (if minus (list 'not mm) mm)
14112 term rest)
14113 (push mm tagsmatcher))
14114 (push (if (> (length tagsmatcher) 1)
14115 (cons 'and tagsmatcher)
14116 (car tagsmatcher))
14117 orlist)
14118 (setq tagsmatcher nil))
14119 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14120 (setq tagsmatcher
14121 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14122 ;; Make the todo matcher
14123 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14124 (setq todomatcher t)
14125 (setq orterms (org-split-string todomatch "|") orlist nil)
14126 (while (setq term (pop orterms))
14127 (while (string-match re term)
14128 (setq minus (and (match-end 1)
14129 (equal (match-string 1 term) "-"))
14130 kwd (match-string 2 term)
14131 re-p (equal (string-to-char kwd) ?{)
14132 term (substring term (match-end 0))
14133 mm (if re-p
14134 `(string-match ,(substring kwd 1 -1) todo)
14135 (list 'equal 'todo kwd))
14136 mm (if minus (list 'not mm) mm))
14137 (push mm todomatcher))
14138 (push (if (> (length todomatcher) 1)
14139 (cons 'and todomatcher)
14140 (car todomatcher))
14141 orlist)
14142 (setq todomatcher nil))
14143 (setq todomatcher (if (> (length orlist) 1)
14144 (cons 'or orlist) (car orlist))))
14146 ;; Return the string and lisp forms of the matcher
14147 (setq matcher (if todomatcher
14148 (list 'and tagsmatcher todomatcher)
14149 tagsmatcher))
14150 (when todo-only
14151 (setq matcher (list 'and '(member todo org-not-done-keywords)
14152 matcher)))
14153 (cons match0 matcher)))
14155 (defun org-tags-expand (match &optional single-as-list downcased)
14156 "Expand group tags in MATCH.
14158 This replaces every group tag in MATCH with a regexp tag search.
14159 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14160 will be replaced like this:
14162 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14163 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14164 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14166 Replacing by a regexp preserves the structure of the match.
14167 E.g., this expansion
14169 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14171 will match anything tagged with \"Lab\" and \"Home\", or tagged
14172 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14174 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14175 assumed to be a single group tag, and the function will return
14176 the list of tags in this group.
14178 When DOWNCASE is non-nil, expand downcased TAGS."
14179 (if org-group-tags
14180 (let* ((case-fold-search t)
14181 (stable org-mode-syntax-table)
14182 (tal (or org-tag-groups-alist-for-agenda
14183 org-tag-groups-alist))
14184 (tal (if downcased
14185 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14186 (tml (mapcar 'car tal))
14187 (rtnmatch match) rpl)
14188 ;; @ and _ are allowed as word-components in tags
14189 (modify-syntax-entry ?@ "w" stable)
14190 (modify-syntax-entry ?_ "w" stable)
14191 (while (and tml
14192 (with-syntax-table stable
14193 (string-match
14194 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14195 (regexp-opt tml) "\\>\\)") rtnmatch)))
14196 (let* ((dir (match-string 1 rtnmatch))
14197 (tag (match-string 2 rtnmatch))
14198 (tag (if downcased (downcase tag) tag)))
14199 (setq tml (delete tag tml))
14200 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14201 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14202 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14203 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14204 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14205 (if single-as-list
14206 (or (reverse rpl) (list rtnmatch))
14207 rtnmatch))
14208 (if single-as-list (list (if downcased (downcase match) match))
14209 match)))
14211 (defun org-op-to-function (op &optional stringp)
14212 "Turn an operator into the appropriate function."
14213 (setq op
14214 (cond
14215 ((equal op "<" ) '(< string< org-time<))
14216 ((equal op ">" ) '(> org-string> org-time>))
14217 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14218 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14219 ((member op '("=" "==")) '(= string= org-time=))
14220 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14221 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14223 (defun org<> (a b) (not (= a b)))
14224 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14225 (defun org-string>= (a b) (not (string< a b)))
14226 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14227 (defun org-string<> (a b) (not (string= a b)))
14228 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14229 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14230 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14231 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14232 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14233 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14234 (defun org-2ft (s)
14235 "Convert S to a floating point time.
14236 If S is already a number, just return it. If it is a string, parse
14237 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14238 (cond
14239 ((numberp s) s)
14240 ((stringp s)
14241 (condition-case nil
14242 (float-time (apply 'encode-time (org-parse-time-string s)))
14243 (error 0.)))
14244 (t 0.)))
14246 (defun org-time-today ()
14247 "Time in seconds today at 0:00.
14248 Returns the float number of seconds since the beginning of the
14249 epoch to the beginning of today (00:00)."
14250 (float-time (apply 'encode-time
14251 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14253 (defun org-matcher-time (s)
14254 "Interpret a time comparison value."
14255 (save-match-data
14256 (cond
14257 ((string= s "<now>") (float-time))
14258 ((string= s "<today>") (org-time-today))
14259 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14260 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14261 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14262 (+ (org-time-today)
14263 (* (string-to-number (match-string 1 s))
14264 (cdr (assoc (match-string 2 s)
14265 '(("d" . 86400.0) ("w" . 604800.0)
14266 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14267 (t (org-2ft s)))))
14269 (defun org-match-any-p (re list)
14270 "Does re match any element of list?"
14271 (setq list (mapcar (lambda (x) (string-match re x)) list))
14272 (delq nil list))
14274 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14275 (defvar org-tags-overlay (make-overlay 1 1))
14276 (org-detach-overlay org-tags-overlay)
14278 (defun org-get-local-tags-at (&optional pos)
14279 "Get a list of tags defined in the current headline."
14280 (org-get-tags-at pos 'local))
14282 (defun org-get-local-tags ()
14283 "Get a list of tags defined in the current headline."
14284 (org-get-tags-at nil 'local))
14286 (defun org-get-tags-at (&optional pos local)
14287 "Get a list of all headline tags applicable at POS.
14288 POS defaults to point. If tags are inherited, the list contains
14289 the targets in the same sequence as the headlines appear, i.e.
14290 the tags of the current headline come last.
14291 When LOCAL is non-nil, only return tags from the current headline,
14292 ignore inherited ones."
14293 (interactive)
14294 (if (and org-trust-scanner-tags
14295 (or (not pos) (equal pos (point)))
14296 (not local))
14297 org-scanner-tags
14298 (let (tags ltags lastpos parent)
14299 (save-excursion
14300 (save-restriction
14301 (widen)
14302 (goto-char (or pos (point)))
14303 (save-match-data
14304 (catch 'done
14305 (condition-case nil
14306 (progn
14307 (org-back-to-heading t)
14308 (while (not (equal lastpos (point)))
14309 (setq lastpos (point))
14310 (when (looking-at
14311 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14312 (setq ltags (org-split-string
14313 (org-match-string-no-properties 1) ":"))
14314 (when parent
14315 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14316 (setq tags (append
14317 (if parent
14318 (org-remove-uninherited-tags ltags)
14319 ltags)
14320 tags)))
14321 (or org-use-tag-inheritance (throw 'done t))
14322 (if local (throw 'done t))
14323 (or (org-up-heading-safe) (error nil))
14324 (setq parent t)))
14325 (error nil)))))
14326 (if local
14327 tags
14328 (reverse (delete-dups
14329 (reverse (append
14330 (org-remove-uninherited-tags
14331 org-file-tags) tags)))))))))
14333 (defun org-add-prop-inherited (s)
14334 (add-text-properties 0 (length s) '(inherited t) s)
14337 (defun org-toggle-tag (tag &optional onoff)
14338 "Toggle the tag TAG for the current line.
14339 If ONOFF is `on' or `off', don't toggle but set to this state."
14340 (let (res current)
14341 (save-excursion
14342 (org-back-to-heading t)
14343 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14344 (point-at-eol) t)
14345 (progn
14346 (setq current (match-string 1))
14347 (replace-match ""))
14348 (setq current ""))
14349 (setq current (nreverse (org-split-string current ":")))
14350 (cond
14351 ((eq onoff 'on)
14352 (setq res t)
14353 (or (member tag current) (push tag current)))
14354 ((eq onoff 'off)
14355 (or (not (member tag current)) (setq current (delete tag current))))
14356 (t (if (member tag current)
14357 (setq current (delete tag current))
14358 (setq res t)
14359 (push tag current))))
14360 (end-of-line 1)
14361 (if current
14362 (progn
14363 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14364 (org-set-tags nil t))
14365 (delete-horizontal-space))
14366 (run-hooks 'org-after-tags-change-hook))
14367 res))
14369 (defun org-align-tags-here (to-col)
14370 ;; Assumes that this is a headline
14371 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14372 (beginning-of-line 1)
14373 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14374 (< pos (match-beginning 2)))
14375 (progn
14376 (setq tags-l (- (match-end 2) (match-beginning 2)))
14377 (goto-char (match-beginning 1))
14378 (insert " ")
14379 (delete-region (point) (1+ (match-beginning 2)))
14380 (setq ncol (max (current-column)
14381 (1+ col)
14382 (if (> to-col 0)
14383 to-col
14384 (- (abs to-col) tags-l))))
14385 (setq p (point))
14386 (insert (make-string (- ncol (current-column)) ?\ ))
14387 (setq ncol (current-column))
14388 (when indent-tabs-mode (tabify p (point-at-eol)))
14389 (org-move-to-column (min ncol col) t))
14390 (goto-char pos))))
14392 (defun org-set-tags-command (&optional arg just-align)
14393 "Call the set-tags command for the current entry."
14394 (interactive "P")
14395 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14396 (org-set-tags arg just-align)
14397 (save-excursion
14398 (unless (and (org-region-active-p)
14399 org-loop-over-headlines-in-active-region)
14400 (org-back-to-heading t))
14401 (org-set-tags arg just-align))))
14403 (defun org-set-tags-to (data)
14404 "Set the tags of the current entry to DATA, replacing the current tags.
14405 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14406 If DATA is nil or the empty string, any tags will be removed."
14407 (interactive "sTags: ")
14408 (setq data
14409 (cond
14410 ((eq data nil) "")
14411 ((equal data "") "")
14412 ((stringp data)
14413 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14414 ":"))
14415 ((listp data)
14416 (concat ":" (mapconcat 'identity data ":") ":"))))
14417 (when data
14418 (save-excursion
14419 (org-back-to-heading t)
14420 (when (looking-at org-complex-heading-regexp)
14421 (if (match-end 5)
14422 (progn
14423 (goto-char (match-beginning 5))
14424 (insert data)
14425 (delete-region (point) (point-at-eol))
14426 (org-set-tags nil 'align))
14427 (goto-char (point-at-eol))
14428 (insert " " data)
14429 (org-set-tags nil 'align)))
14430 (beginning-of-line 1)
14431 (if (looking-at ".*?\\([ \t]+\\)$")
14432 (delete-region (match-beginning 1) (match-end 1))))))
14434 (defun org-align-all-tags ()
14435 "Align the tags i all headings."
14436 (interactive)
14437 (save-excursion
14438 (or (ignore-errors (org-back-to-heading t))
14439 (outline-next-heading))
14440 (if (org-at-heading-p)
14441 (org-set-tags t)
14442 (message "No headings"))))
14444 (defvar org-indent-indentation-per-level)
14445 (defun org-set-tags (&optional arg just-align)
14446 "Set the tags for the current headline.
14447 With prefix ARG, realign all tags in headings in the current buffer."
14448 (interactive "P")
14449 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14450 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14451 'region-start-level 'region))
14452 org-loop-over-headlines-in-active-region)
14453 (org-map-entries
14454 ;; We don't use ARG and JUST-ALIGN here these args are not
14455 ;; useful when looping over headlines
14456 `(org-set-tags)
14457 org-loop-over-headlines-in-active-region
14458 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14459 (let* ((re org-outline-regexp-bol)
14460 (current (unless arg (org-get-tags-string)))
14461 (col (current-column))
14462 (org-setting-tags t)
14463 table current-tags inherited-tags ; computed below when needed
14464 tags p0 c0 c1 rpl di tc level)
14465 (if arg
14466 (save-excursion
14467 (goto-char (point-min))
14468 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14469 (while (re-search-forward re nil t)
14470 (org-set-tags nil t)
14471 (end-of-line 1)))
14472 (message "All tags realigned to column %d" org-tags-column))
14473 (if just-align
14474 (setq tags current)
14475 ;; Get a new set of tags from the user
14476 (save-excursion
14477 (setq table (append org-tag-persistent-alist
14478 (or org-tag-alist (org-get-buffer-tags))
14479 (and
14480 org-complete-tags-always-offer-all-agenda-tags
14481 (org-global-tags-completion-table
14482 (org-agenda-files))))
14483 org-last-tags-completion-table table
14484 current-tags (org-split-string current ":")
14485 inherited-tags (nreverse
14486 (nthcdr (length current-tags)
14487 (nreverse (org-get-tags-at))))
14488 tags
14489 (if (or (eq t org-use-fast-tag-selection)
14490 (and org-use-fast-tag-selection
14491 (delq nil (mapcar 'cdr table))))
14492 (org-fast-tag-selection
14493 current-tags inherited-tags table
14494 (if org-fast-tag-selection-include-todo
14495 org-todo-key-alist))
14496 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14497 (org-trim
14498 (org-icompleting-read "Tags: "
14499 'org-tags-completion-function
14500 nil nil current 'org-tags-history))))))
14501 (while (string-match "[-+&]+" tags)
14502 ;; No boolean logic, just a list
14503 (setq tags (replace-match ":" t t tags))))
14505 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14507 (if org-tags-sort-function
14508 (setq tags (mapconcat 'identity
14509 (sort (org-split-string
14510 tags (org-re "[^[:alnum:]_@#%]+"))
14511 org-tags-sort-function) ":")))
14513 (if (string-match "\\`[\t ]*\\'" tags)
14514 (setq tags "")
14515 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14516 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14518 ;; Insert new tags at the correct column
14519 (beginning-of-line 1)
14520 (setq level (or (and (looking-at org-outline-regexp)
14521 (- (match-end 0) (point) 1))
14523 (cond
14524 ((and (equal current "") (equal tags "")))
14525 ((re-search-forward
14526 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14527 (point-at-eol) t)
14528 (if (equal tags "")
14529 (setq rpl "")
14530 (goto-char (match-beginning 0))
14531 (setq c0 (current-column)
14532 ;; compute offset for the case of org-indent-mode active
14533 di (if org-indent-mode
14534 (* (1- org-indent-indentation-per-level) (1- level))
14536 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14537 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14538 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14539 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14540 (replace-match rpl t t)
14541 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14542 tags)
14543 (t (error "Tags alignment failed")))
14544 (org-move-to-column col)
14545 (unless just-align
14546 (run-hooks 'org-after-tags-change-hook))))))
14548 (defun org-change-tag-in-region (beg end tag off)
14549 "Add or remove TAG for each entry in the region.
14550 This works in the agenda, and also in an org-mode buffer."
14551 (interactive
14552 (list (region-beginning) (region-end)
14553 (let ((org-last-tags-completion-table
14554 (if (derived-mode-p 'org-mode)
14555 (org-uniquify
14556 (delq nil (append (org-get-buffer-tags)
14557 (org-global-tags-completion-table))))
14558 (org-global-tags-completion-table))))
14559 (org-icompleting-read
14560 "Tag: " 'org-tags-completion-function nil nil nil
14561 'org-tags-history))
14562 (progn
14563 (message "[s]et or [r]emove? ")
14564 (equal (read-char-exclusive) ?r))))
14565 (if (fboundp 'deactivate-mark) (deactivate-mark))
14566 (let ((agendap (equal major-mode 'org-agenda-mode))
14567 l1 l2 m buf pos newhead (cnt 0))
14568 (goto-char end)
14569 (setq l2 (1- (org-current-line)))
14570 (goto-char beg)
14571 (setq l1 (org-current-line))
14572 (loop for l from l1 to l2 do
14573 (org-goto-line l)
14574 (setq m (get-text-property (point) 'org-hd-marker))
14575 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14576 (and agendap m))
14577 (setq buf (if agendap (marker-buffer m) (current-buffer))
14578 pos (if agendap m (point)))
14579 (with-current-buffer buf
14580 (save-excursion
14581 (save-restriction
14582 (goto-char pos)
14583 (setq cnt (1+ cnt))
14584 (org-toggle-tag tag (if off 'off 'on))
14585 (setq newhead (org-get-heading)))))
14586 (and agendap (org-agenda-change-all-lines newhead m))))
14587 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14589 (defun org-tags-completion-function (string predicate &optional flag)
14590 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14591 (confirm (lambda (x) (stringp (car x)))))
14592 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14593 (setq s1 (match-string 1 string)
14594 s2 (match-string 2 string))
14595 (setq s1 "" s2 string))
14596 (cond
14597 ((eq flag nil)
14598 ;; try completion
14599 (setq rtn (try-completion s2 ctable confirm))
14600 (if (stringp rtn)
14601 (setq rtn
14602 (concat s1 s2 (substring rtn (length s2))
14603 (if (and org-add-colon-after-tag-completion
14604 (assoc rtn ctable))
14605 ":" ""))))
14606 rtn)
14607 ((eq flag t)
14608 ;; all-completions
14609 (all-completions s2 ctable confirm))
14610 ((eq flag 'lambda)
14611 ;; exact match?
14612 (assoc s2 ctable)))))
14614 (defun org-fast-tag-insert (kwd tags face &optional end)
14615 "Insert KDW, and the TAGS, the latter with face FACE.
14616 Also insert END."
14617 (insert (format "%-12s" (concat kwd ":"))
14618 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14619 (or end "")))
14621 (defun org-fast-tag-show-exit (flag)
14622 (save-excursion
14623 (org-goto-line 3)
14624 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14625 (replace-match ""))
14626 (when flag
14627 (end-of-line 1)
14628 (org-move-to-column (- (window-width) 19) t)
14629 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14631 (defun org-set-current-tags-overlay (current prefix)
14632 "Add an overlay to CURRENT tag with PREFIX."
14633 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14634 (if (featurep 'xemacs)
14635 (org-overlay-display org-tags-overlay (concat prefix s)
14636 'secondary-selection)
14637 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14638 (org-overlay-display org-tags-overlay (concat prefix s)))))
14640 (defvar org-last-tag-selection-key nil)
14641 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14642 "Fast tag selection with single keys.
14643 CURRENT is the current list of tags in the headline, INHERITED is the
14644 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14645 possibly with grouping information. TODO-TABLE is a similar table with
14646 TODO keywords, should these have keys assigned to them.
14647 If the keys are nil, a-z are automatically assigned.
14648 Returns the new tags string, or nil to not change the current settings."
14649 (let* ((fulltable (append table todo-table))
14650 (maxlen (apply 'max (mapcar
14651 (lambda (x)
14652 (if (stringp (car x)) (string-width (car x)) 0))
14653 fulltable)))
14654 (buf (current-buffer))
14655 (expert (eq org-fast-tag-selection-single-key 'expert))
14656 (buffer-tags nil)
14657 (fwidth (+ maxlen 3 1 3))
14658 (ncol (/ (- (window-width) 4) fwidth))
14659 (i-face 'org-done)
14660 (c-face 'org-todo)
14661 tg cnt e c char c1 c2 ntable tbl rtn
14662 ov-start ov-end ov-prefix
14663 (exit-after-next org-fast-tag-selection-single-key)
14664 (done-keywords org-done-keywords)
14665 groups ingroup)
14666 (save-excursion
14667 (beginning-of-line 1)
14668 (if (looking-at
14669 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14670 (setq ov-start (match-beginning 1)
14671 ov-end (match-end 1)
14672 ov-prefix "")
14673 (setq ov-start (1- (point-at-eol))
14674 ov-end (1+ ov-start))
14675 (skip-chars-forward "^\n\r")
14676 (setq ov-prefix
14677 (concat
14678 (buffer-substring (1- (point)) (point))
14679 (if (> (current-column) org-tags-column)
14681 (make-string (- org-tags-column (current-column)) ?\ ))))))
14682 (move-overlay org-tags-overlay ov-start ov-end)
14683 (save-window-excursion
14684 (if expert
14685 (set-buffer (get-buffer-create " *Org tags*"))
14686 (delete-other-windows)
14687 (split-window-vertically)
14688 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14689 (erase-buffer)
14690 (org-set-local 'org-done-keywords done-keywords)
14691 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14692 (org-fast-tag-insert "Current" current c-face "\n\n")
14693 (org-fast-tag-show-exit exit-after-next)
14694 (org-set-current-tags-overlay current ov-prefix)
14695 (setq tbl fulltable char ?a cnt 0)
14696 (while (setq e (pop tbl))
14697 (cond
14698 ((equal (car e) :startgroup)
14699 (push '() groups) (setq ingroup t)
14700 (when (not (= cnt 0))
14701 (setq cnt 0)
14702 (insert "\n"))
14703 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14704 ((equal (car e) :endgroup)
14705 (setq ingroup nil cnt 0)
14706 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14707 ((equal e '(:newline))
14708 (when (not (= cnt 0))
14709 (setq cnt 0)
14710 (insert "\n")
14711 (setq e (car tbl))
14712 (while (equal (car tbl) '(:newline))
14713 (insert "\n")
14714 (setq tbl (cdr tbl)))))
14715 ((equal e '(:grouptags)) nil)
14717 (setq tg (copy-sequence (car e)) c2 nil)
14718 (if (cdr e)
14719 (setq c (cdr e))
14720 ;; automatically assign a character.
14721 (setq c1 (string-to-char
14722 (downcase (substring
14723 tg (if (= (string-to-char tg) ?@) 1 0)))))
14724 (if (or (rassoc c1 ntable) (rassoc c1 table))
14725 (while (or (rassoc char ntable) (rassoc char table))
14726 (setq char (1+ char)))
14727 (setq c2 c1))
14728 (setq c (or c2 char)))
14729 (if ingroup (push tg (car groups)))
14730 (setq tg (org-add-props tg nil 'face
14731 (cond
14732 ((not (assoc tg table))
14733 (org-get-todo-face tg))
14734 ((member tg current) c-face)
14735 ((member tg inherited) i-face))))
14736 (if (equal (caar tbl) :grouptags)
14737 (org-add-props tg nil 'face 'org-tag-group))
14738 (if (and (= cnt 0) (not ingroup)) (insert " "))
14739 (insert "[" c "] " tg (make-string
14740 (- fwidth 4 (length tg)) ?\ ))
14741 (push (cons tg c) ntable)
14742 (when (= (setq cnt (1+ cnt)) ncol)
14743 (insert "\n")
14744 (if ingroup (insert " "))
14745 (setq cnt 0)))))
14746 (setq ntable (nreverse ntable))
14747 (insert "\n")
14748 (goto-char (point-min))
14749 (if (not expert) (org-fit-window-to-buffer))
14750 (setq rtn
14751 (catch 'exit
14752 (while t
14753 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14754 (if (not groups) "no " "")
14755 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14756 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14757 (setq org-last-tag-selection-key c)
14758 (cond
14759 ((= c ?\r) (throw 'exit t))
14760 ((= c ?!)
14761 (setq groups (not groups))
14762 (goto-char (point-min))
14763 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14764 ((= c ?\C-c)
14765 (if (not expert)
14766 (org-fast-tag-show-exit
14767 (setq exit-after-next (not exit-after-next)))
14768 (setq expert nil)
14769 (delete-other-windows)
14770 (set-window-buffer (split-window-vertically) " *Org tags*")
14771 (org-switch-to-buffer-other-window " *Org tags*")
14772 (org-fit-window-to-buffer)))
14773 ((or (= c ?\C-g)
14774 (and (= c ?q) (not (rassoc c ntable))))
14775 (org-detach-overlay org-tags-overlay)
14776 (setq quit-flag t))
14777 ((= c ?\ )
14778 (setq current nil)
14779 (if exit-after-next (setq exit-after-next 'now)))
14780 ((= c ?\t)
14781 (condition-case nil
14782 (setq tg (org-icompleting-read
14783 "Tag: "
14784 (or buffer-tags
14785 (with-current-buffer buf
14786 (org-get-buffer-tags)))))
14787 (quit (setq tg "")))
14788 (when (string-match "\\S-" tg)
14789 (add-to-list 'buffer-tags (list tg))
14790 (if (member tg current)
14791 (setq current (delete tg current))
14792 (push tg current)))
14793 (if exit-after-next (setq exit-after-next 'now)))
14794 ((setq e (rassoc c todo-table) tg (car e))
14795 (with-current-buffer buf
14796 (save-excursion (org-todo tg)))
14797 (if exit-after-next (setq exit-after-next 'now)))
14798 ((setq e (rassoc c ntable) tg (car e))
14799 (if (member tg current)
14800 (setq current (delete tg current))
14801 (loop for g in groups do
14802 (if (member tg g)
14803 (mapc (lambda (x)
14804 (setq current (delete x current)))
14805 g)))
14806 (push tg current))
14807 (if exit-after-next (setq exit-after-next 'now))))
14809 ;; Create a sorted list
14810 (setq current
14811 (sort current
14812 (lambda (a b)
14813 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14814 (if (eq exit-after-next 'now) (throw 'exit t))
14815 (goto-char (point-min))
14816 (beginning-of-line 2)
14817 (delete-region (point) (point-at-eol))
14818 (org-fast-tag-insert "Current" current c-face)
14819 (org-set-current-tags-overlay current ov-prefix)
14820 (while (re-search-forward
14821 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14822 (setq tg (match-string 1))
14823 (add-text-properties
14824 (match-beginning 1) (match-end 1)
14825 (list 'face
14826 (cond
14827 ((member tg current) c-face)
14828 ((member tg inherited) i-face)
14829 (t (get-text-property (match-beginning 1) 'face))))))
14830 (goto-char (point-min)))))
14831 (org-detach-overlay org-tags-overlay)
14832 (if rtn
14833 (mapconcat 'identity current ":")
14834 nil))))
14836 (defun org-get-tags-string ()
14837 "Get the TAGS string in the current headline."
14838 (unless (org-at-heading-p t)
14839 (user-error "Not on a heading"))
14840 (save-excursion
14841 (beginning-of-line 1)
14842 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14843 (org-match-string-no-properties 1)
14844 "")))
14846 (defun org-get-tags ()
14847 "Get the list of tags specified in the current headline."
14848 (org-split-string (org-get-tags-string) ":"))
14850 (defun org-get-buffer-tags ()
14851 "Get a table of all tags used in the buffer, for completion."
14852 (let (tags)
14853 (save-excursion
14854 (goto-char (point-min))
14855 (while (re-search-forward
14856 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14857 (when (equal (char-after (point-at-bol 0)) ?*)
14858 (mapc (lambda (x) (add-to-list 'tags x))
14859 (org-split-string (org-match-string-no-properties 1) ":")))))
14860 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14861 (mapcar 'list tags)))
14863 ;;;; The mapping API
14865 (defun org-map-entries (func &optional match scope &rest skip)
14866 "Call FUNC at each headline selected by MATCH in SCOPE.
14868 FUNC is a function or a lisp form. The function will be called without
14869 arguments, with the cursor positioned at the beginning of the headline.
14870 The return values of all calls to the function will be collected and
14871 returned as a list.
14873 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14874 does not need to preserve point. After evaluation, the cursor will be
14875 moved to the end of the line (presumably of the headline of the
14876 processed entry) and search continues from there. Under some
14877 circumstances, this may not produce the wanted results. For example,
14878 if you have removed (e.g. archived) the current (sub)tree it could
14879 mean that the next entry will be skipped entirely. In such cases, you
14880 can specify the position from where search should continue by making
14881 FUNC set the variable `org-map-continue-from' to the desired buffer
14882 position.
14884 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14885 Only headlines that are matched by this query will be considered during
14886 the iteration. When MATCH is nil or t, all headlines will be
14887 visited by the iteration.
14889 SCOPE determines the scope of this command. It can be any of:
14891 nil The current buffer, respecting the restriction if any
14892 tree The subtree started with the entry at point
14893 region The entries within the active region, if any
14894 region-start-level
14895 The entries within the active region, but only those at
14896 the same level than the first one.
14897 file The current buffer, without restriction
14898 file-with-archives
14899 The current buffer, and any archives associated with it
14900 agenda All agenda files
14901 agenda-with-archives
14902 All agenda files with any archive files associated with them
14903 \(file1 file2 ...)
14904 If this is a list, all files in the list will be scanned
14906 The remaining args are treated as settings for the skipping facilities of
14907 the scanner. The following items can be given here:
14909 archive skip trees with the archive tag
14910 comment skip trees with the COMMENT keyword
14911 function or Emacs Lisp form:
14912 will be used as value for `org-agenda-skip-function', so
14913 whenever the function returns a position, FUNC will not be
14914 called for that entry and search will continue from the
14915 position returned
14917 If your function needs to retrieve the tags including inherited tags
14918 at the *current* entry, you can use the value of the variable
14919 `org-scanner-tags' which will be much faster than getting the value
14920 with `org-get-tags-at'. If your function gets properties with
14921 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14922 to t around the call to `org-entry-properties' to get the same speedup.
14923 Note that if your function moves around to retrieve tags and properties at
14924 a *different* entry, you cannot use these techniques."
14925 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14926 (not (org-region-active-p)))
14927 (let* ((org-agenda-archives-mode nil) ; just to make sure
14928 (org-agenda-skip-archived-trees (memq 'archive skip))
14929 (org-agenda-skip-comment-trees (memq 'comment skip))
14930 (org-agenda-skip-function
14931 (car (org-delete-all '(comment archive) skip)))
14932 (org-tags-match-list-sublevels t)
14933 (start-level (eq scope 'region-start-level))
14934 matcher file res
14935 org-todo-keywords-for-agenda
14936 org-done-keywords-for-agenda
14937 org-todo-keyword-alist-for-agenda
14938 org-drawers-for-agenda
14939 org-tag-alist-for-agenda
14940 todo-only)
14942 (cond
14943 ((eq match t) (setq matcher t))
14944 ((eq match nil) (setq matcher t))
14945 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14947 (save-window-excursion
14948 (save-restriction
14949 (cond ((eq scope 'tree)
14950 (org-back-to-heading t)
14951 (org-narrow-to-subtree)
14952 (setq scope nil))
14953 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14954 (org-region-active-p))
14955 ;; If needed, set start-level to a string like "2"
14956 (when start-level
14957 (save-excursion
14958 (goto-char (region-beginning))
14959 (unless (org-at-heading-p) (outline-next-heading))
14960 (setq start-level (org-current-level))))
14961 (narrow-to-region (region-beginning)
14962 (save-excursion
14963 (goto-char (region-end))
14964 (unless (and (bolp) (org-at-heading-p))
14965 (outline-next-heading))
14966 (point)))
14967 (setq scope nil)))
14969 (if (not scope)
14970 (progn
14971 (org-agenda-prepare-buffers
14972 (list (buffer-file-name (current-buffer))))
14973 (setq res (org-scan-tags func matcher todo-only start-level)))
14974 ;; Get the right scope
14975 (cond
14976 ((and scope (listp scope) (symbolp (car scope)))
14977 (setq scope (eval scope)))
14978 ((eq scope 'agenda)
14979 (setq scope (org-agenda-files t)))
14980 ((eq scope 'agenda-with-archives)
14981 (setq scope (org-agenda-files t))
14982 (setq scope (org-add-archive-files scope)))
14983 ((eq scope 'file)
14984 (setq scope (list (buffer-file-name))))
14985 ((eq scope 'file-with-archives)
14986 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14987 (org-agenda-prepare-buffers scope)
14988 (while (setq file (pop scope))
14989 (with-current-buffer (org-find-base-buffer-visiting file)
14990 (save-excursion
14991 (save-restriction
14992 (widen)
14993 (goto-char (point-min))
14994 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14995 res)))
14997 ;;;; Properties
14999 ;;; Setting and retrieving properties
15001 (defconst org-special-properties
15002 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15003 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15004 "The special properties valid in Org-mode.
15006 These are properties that are not defined in the property drawer,
15007 but in some other way.")
15009 (defconst org-default-properties
15010 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15011 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15012 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15013 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15014 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15015 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15016 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15017 "Some properties that are used by Org-mode for various purposes.
15018 Being in this list makes sure that they are offered for completion.")
15020 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15021 "Regular expression matching the first line of a property drawer.")
15023 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15024 "Regular expression matching the last line of a property drawer.")
15026 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15027 "Regular expression matching the first line of a property drawer.")
15029 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15030 "Regular expression matching the first line of a property drawer.")
15032 (defconst org-property-drawer-re
15033 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15034 org-property-end-re "\\)\n?")
15035 "Matches an entire property drawer.")
15037 (defconst org-clock-drawer-re
15038 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15039 org-property-end-re "\\)\n?")
15040 "Matches an entire clock drawer.")
15042 (defun org-property-action ()
15043 "Do an action on properties."
15044 (interactive)
15045 (let (c)
15046 (org-at-property-p)
15047 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15048 (setq c (read-char-exclusive))
15049 (cond
15050 ((equal c ?s)
15051 (call-interactively 'org-set-property))
15052 ((equal c ?d)
15053 (call-interactively 'org-delete-property))
15054 ((equal c ?D)
15055 (call-interactively 'org-delete-property-globally))
15056 ((equal c ?c)
15057 (call-interactively 'org-compute-property-at-point))
15058 (t (user-error "No such property action %c" c)))))
15060 (defun org-inc-effort ()
15061 "Increment the value of the effort property in the current entry."
15062 (interactive)
15063 (org-set-effort nil t))
15065 (defvar org-clock-effort) ;; Defined in org-clock.el
15066 (defvar org-clock-current-task) ;; Defined in org-clock.el
15067 (defun org-set-effort (&optional value increment)
15068 "Set the effort property of the current entry.
15069 With numerical prefix arg, use the nth allowed value, 0 stands for the
15070 10th allowed value.
15072 When INCREMENT is non-nil, set the property to the next allowed value."
15073 (interactive "P")
15074 (if (equal value 0) (setq value 10))
15075 (let* ((completion-ignore-case t)
15076 (prop org-effort-property)
15077 (cur (org-entry-get nil prop))
15078 (allowed (org-property-get-allowed-values nil prop 'table))
15079 (existing (mapcar 'list (org-property-values prop)))
15080 (heading (nth 4 (org-heading-components)))
15082 (val (cond
15083 ((stringp value) value)
15084 ((and allowed (integerp value))
15085 (or (car (nth (1- value) allowed))
15086 (car (org-last allowed))))
15087 ((and allowed increment)
15088 (or (caadr (member (list cur) allowed))
15089 (user-error "Allowed effort values are not set")))
15090 (allowed
15091 (message "Select 1-9,0, [RET%s]: %s"
15092 (if cur (concat "=" cur) "")
15093 (mapconcat 'car allowed " "))
15094 (setq rpl (read-char-exclusive))
15095 (if (equal rpl ?\r)
15097 (setq rpl (- rpl ?0))
15098 (if (equal rpl 0) (setq rpl 10))
15099 (if (and (> rpl 0) (<= rpl (length allowed)))
15100 (car (nth (1- rpl) allowed))
15101 (org-completing-read "Effort: " allowed nil))))
15103 (let (org-completion-use-ido org-completion-use-iswitchb)
15104 (org-completing-read
15105 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15106 (concat "[" cur "]") "")
15107 ": ")
15108 existing nil nil "" nil cur))))))
15109 (unless (equal (org-entry-get nil prop) val)
15110 (org-entry-put nil prop val))
15111 (save-excursion
15112 (org-back-to-heading t)
15113 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15114 (when (string= heading org-clock-current-task)
15115 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15116 (org-clock-update-mode-line))
15117 (message "%s is now %s" prop val)))
15119 (defun org-at-property-p ()
15120 "Is cursor inside a property drawer?"
15121 (save-excursion
15122 (when (equal 'node-property (car (org-element-at-point)))
15123 (beginning-of-line 1)
15124 (looking-at org-property-re))))
15126 (defun org-get-property-block (&optional beg end force)
15127 "Return the (beg . end) range of the body of the property drawer.
15128 BEG and END are the beginning and end of the current subtree, or of
15129 the part before the first headline. If they are not given, they will
15130 be found. If the drawer does not exist and FORCE is non-nil, create
15131 the drawer."
15132 (catch 'exit
15133 (save-excursion
15134 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15135 (progn (org-back-to-heading t) (point))))
15136 (end (or end (and (not (outline-next-heading)) (point-max))
15137 (point))))
15138 (goto-char beg)
15139 (if (re-search-forward org-property-start-re end t)
15140 (setq beg (1+ (match-end 0)))
15141 (if force
15142 (save-excursion
15143 (org-insert-property-drawer)
15144 (setq end (progn (outline-next-heading) (point))))
15145 (throw 'exit nil))
15146 (goto-char beg)
15147 (if (re-search-forward org-property-start-re end t)
15148 (setq beg (1+ (match-end 0)))))
15149 (if (re-search-forward org-property-end-re end t)
15150 (setq end (match-beginning 0))
15151 (or force (throw 'exit nil))
15152 (goto-char beg)
15153 (setq end beg)
15154 (org-indent-line)
15155 (insert ":END:\n"))
15156 (cons beg end)))))
15158 (defun org-entry-properties (&optional pom which specific)
15159 "Get all properties of the entry at point-or-marker POM.
15160 This includes the TODO keyword, the tags, time strings for deadline,
15161 scheduled, and clocking, and any additional properties defined in the
15162 entry. The return value is an alist, keys may occur multiple times
15163 if the property key was used several times.
15164 POM may also be nil, in which case the current entry is used.
15165 If WHICH is nil or `all', get all properties. If WHICH is
15166 `special' or `standard', only get that subclass. If WHICH
15167 is a string only get exactly this property. SPECIFIC can be a string, the
15168 specific property we are interested in. Specifying it can speed
15169 things up because then unnecessary parsing is avoided."
15170 (setq which (or which 'all))
15171 (org-with-point-at pom
15172 (let ((clockstr (substring org-clock-string 0 -1))
15173 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15174 (case-fold-search nil)
15175 beg end range props sum-props key key1 value string clocksum clocksumt)
15176 (save-excursion
15177 (when (condition-case nil
15178 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15179 (error nil))
15180 (setq beg (point))
15181 (setq sum-props (get-text-property (point) 'org-summaries))
15182 (setq clocksum (get-text-property (point) :org-clock-minutes)
15183 clocksumt (get-text-property (point) :org-clock-minutes-today))
15184 (outline-next-heading)
15185 (setq end (point))
15186 (when (memq which '(all special))
15187 ;; Get the special properties, like TODO and tags
15188 (goto-char beg)
15189 (when (and (or (not specific) (string= specific "TODO"))
15190 (looking-at org-todo-line-regexp) (match-end 2))
15191 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15192 (when (and (or (not specific) (string= specific "PRIORITY"))
15193 (looking-at org-priority-regexp))
15194 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15195 (when (or (not specific) (string= specific "FILE"))
15196 (push (cons "FILE" buffer-file-name) props))
15197 (when (and (or (not specific) (string= specific "TAGS"))
15198 (setq value (org-get-tags-string))
15199 (string-match "\\S-" value))
15200 (push (cons "TAGS" value) props))
15201 (when (and (or (not specific) (string= specific "ALLTAGS"))
15202 (setq value (org-get-tags-at)))
15203 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15204 ":"))
15205 props))
15206 (when (or (not specific) (string= specific "BLOCKED"))
15207 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15208 (when (or (not specific)
15209 (member specific
15210 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15211 "TIMESTAMP" "TIMESTAMP_IA")))
15212 (catch 'match
15213 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15214 (setq key (if (match-end 1)
15215 (substring (org-match-string-no-properties 1)
15216 0 -1))
15217 string (if (equal key clockstr)
15218 (org-trim
15219 (buffer-substring-no-properties
15220 (match-beginning 3) (goto-char
15221 (point-at-eol))))
15222 (substring (org-match-string-no-properties 3)
15223 1 -1)))
15224 ;; Get the correct property name from the key. This is
15225 ;; necessary if the user has configured time keywords.
15226 (setq key1 (concat key ":"))
15227 (cond
15228 ((not key)
15229 (setq key
15230 (if (= (char-after (match-beginning 3)) ?\[)
15231 "TIMESTAMP_IA" "TIMESTAMP")))
15232 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15233 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15234 ((equal key1 org-closed-string) (setq key "CLOSED"))
15235 ((equal key1 org-clock-string) (setq key "CLOCK")))
15236 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15237 (progn
15238 (push (cons key string) props)
15239 ;; no need to search further if match is found
15240 (throw 'match t))
15241 (when (or (equal key "CLOCK") (not (assoc key props)))
15242 (push (cons key string) props)))))))
15244 (when (memq which '(all standard))
15245 ;; Get the standard properties, like :PROP: ...
15246 (setq range (org-get-property-block beg end))
15247 (when range
15248 (goto-char (car range))
15249 (while (re-search-forward org-property-re
15250 (cdr range) t)
15251 (setq key (org-match-string-no-properties 2)
15252 value (org-trim (or (org-match-string-no-properties 3) "")))
15253 (unless (member key excluded)
15254 (push (cons key (or value "")) props)))))
15255 (if clocksum
15256 (push (cons "CLOCKSUM"
15257 (org-columns-number-to-string (/ (float clocksum) 60.)
15258 'add_times))
15259 props))
15260 (if clocksumt
15261 (push (cons "CLOCKSUM_T"
15262 (org-columns-number-to-string (/ (float clocksumt) 60.)
15263 'add_times))
15264 props))
15265 (unless (assoc "CATEGORY" props)
15266 (push (cons "CATEGORY" (org-get-category)) props))
15267 (append sum-props (nreverse props)))))))
15269 (defun org-entry-get (pom property &optional inherit literal-nil)
15270 "Get value of PROPERTY for entry or content at point-or-marker POM.
15271 If INHERIT is non-nil and the entry does not have the property,
15272 then also check higher levels of the hierarchy.
15273 If INHERIT is the symbol `selective', use inheritance only if the setting
15274 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15275 If the property is present but empty, the return value is the empty string.
15276 If the property is not present at all, nil is returned.
15278 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15279 do not interpret it as the list atom nil. This is used for inheritance
15280 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15281 (org-with-point-at pom
15282 (if (and inherit (if (eq inherit 'selective)
15283 (org-property-inherit-p property)
15285 (org-entry-get-with-inheritance property literal-nil)
15286 (if (member property org-special-properties)
15287 ;; We need a special property. Use `org-entry-properties' to
15288 ;; retrieve it, but specify the wanted property
15289 (cdr (assoc property (org-entry-properties nil 'special property)))
15290 (let ((range (org-get-property-block)))
15291 (when (and range (not (eq (car range) (cdr range))))
15292 (let* ((props (list (or (assoc property org-file-properties)
15293 (assoc property org-global-properties)
15294 (assoc property org-global-properties-fixed))))
15295 (ap (lambda (key)
15296 (when (re-search-forward
15297 (org-re-property key) (cdr range) t)
15298 (setq props
15299 (org-update-property-plist
15301 (if (match-end 3)
15302 (org-match-string-no-properties 3) "")
15303 props)))))
15304 val)
15305 (goto-char (car range))
15306 (funcall ap property)
15307 (goto-char (car range))
15308 (while (funcall ap (concat property "+")))
15309 (setq val (cdr (assoc property props)))
15310 (when val (if literal-nil val (org-not-nil val))))))))))
15312 (defun org-property-or-variable-value (var &optional inherit)
15313 "Check if there is a property fixing the value of VAR.
15314 If yes, return this value. If not, return the current value of the variable."
15315 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15316 (if (and prop (stringp prop) (string-match "\\S-" prop))
15317 (read prop)
15318 (symbol-value var))))
15320 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15321 "Delete the property PROPERTY from entry at point-or-marker POM.
15322 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15323 an empty drawer to delete."
15324 (org-with-point-at pom
15325 (if (member property org-special-properties)
15326 nil ; cannot delete these properties.
15327 (let ((range (org-get-property-block)))
15328 (if (and range
15329 (goto-char (car range))
15330 (re-search-forward
15331 (org-re-property property)
15332 (cdr range) t))
15333 (progn
15334 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15335 (and delete-empty-drawer
15336 (org-remove-empty-drawer-at
15337 delete-empty-drawer (car range)))
15339 nil)))))
15341 ;; Multi-values properties are properties that contain multiple values
15342 ;; These values are assumed to be single words, separated by whitespace.
15343 (defun org-entry-add-to-multivalued-property (pom property value)
15344 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15345 (let* ((old (org-entry-get pom property))
15346 (values (and old (org-split-string old "[ \t]"))))
15347 (setq value (org-entry-protect-space value))
15348 (unless (member value values)
15349 (setq values (append values (list value)))
15350 (org-entry-put pom property
15351 (mapconcat 'identity values " ")))))
15353 (defun org-entry-remove-from-multivalued-property (pom property value)
15354 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15355 (let* ((old (org-entry-get pom property))
15356 (values (and old (org-split-string old "[ \t]"))))
15357 (setq value (org-entry-protect-space value))
15358 (when (member value values)
15359 (setq values (delete value values))
15360 (org-entry-put pom property
15361 (mapconcat 'identity values " ")))))
15363 (defun org-entry-member-in-multivalued-property (pom property value)
15364 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15365 (let* ((old (org-entry-get pom property))
15366 (values (and old (org-split-string old "[ \t]"))))
15367 (setq value (org-entry-protect-space value))
15368 (member value values)))
15370 (defun org-entry-get-multivalued-property (pom property)
15371 "Return a list of values in a multivalued property."
15372 (let* ((value (org-entry-get pom property))
15373 (values (and value (org-split-string value "[ \t]"))))
15374 (mapcar 'org-entry-restore-space values)))
15376 (defun org-entry-put-multivalued-property (pom property &rest values)
15377 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15378 VALUES should be a list of strings. Spaces will be protected."
15379 (org-entry-put pom property
15380 (mapconcat 'org-entry-protect-space values " "))
15381 (let* ((value (org-entry-get pom property))
15382 (values (and value (org-split-string value "[ \t]"))))
15383 (mapcar 'org-entry-restore-space values)))
15385 (defun org-entry-protect-space (s)
15386 "Protect spaces and newline in string S."
15387 (while (string-match " " s)
15388 (setq s (replace-match "%20" t t s)))
15389 (while (string-match "\n" s)
15390 (setq s (replace-match "%0A" t t s)))
15393 (defun org-entry-restore-space (s)
15394 "Restore spaces and newline in string S."
15395 (while (string-match "%20" s)
15396 (setq s (replace-match " " t t s)))
15397 (while (string-match "%0A" s)
15398 (setq s (replace-match "\n" t t s)))
15401 (defvar org-entry-property-inherited-from (make-marker)
15402 "Marker pointing to the entry from where a property was inherited.
15403 Each call to `org-entry-get-with-inheritance' will set this marker to the
15404 location of the entry where the inheritance search matched. If there was
15405 no match, the marker will point nowhere.
15406 Note that also `org-entry-get' calls this function, if the INHERIT flag
15407 is set.")
15409 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15410 "Get PROPERTY of entry or content at point, search higher levels if needed.
15411 The search will stop at the first ancestor which has the property defined.
15412 If the value found is \"nil\", return nil to show that the property
15413 should be considered as undefined (this is the meaning of nil here).
15414 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15415 (move-marker org-entry-property-inherited-from nil)
15416 (let (tmp)
15417 (save-excursion
15418 (save-restriction
15419 (widen)
15420 (catch 'ex
15421 (while t
15422 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15423 (or (ignore-errors (org-back-to-heading t))
15424 (goto-char (point-min)))
15425 (move-marker org-entry-property-inherited-from (point))
15426 (throw 'ex tmp))
15427 (or (ignore-errors (org-up-heading-safe))
15428 (throw 'ex nil))))))
15429 (setq tmp (or tmp
15430 (cdr (assoc property org-file-properties))
15431 (cdr (assoc property org-global-properties))
15432 (cdr (assoc property org-global-properties-fixed))))
15433 (if literal-nil tmp (org-not-nil tmp))))
15435 (defvar org-property-changed-functions nil
15436 "Hook called when the value of a property has changed.
15437 Each hook function should accept two arguments, the name of the property
15438 and the new value.")
15440 (defun org-entry-put (pom property value)
15441 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15442 (org-with-point-at pom
15443 (org-back-to-heading t)
15444 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15445 range)
15446 (cond
15447 ((equal property "TODO")
15448 (when (and (stringp value) (string-match "\\S-" value)
15449 (not (member value org-todo-keywords-1)))
15450 (user-error "\"%s\" is not a valid TODO state" value))
15451 (if (or (not value)
15452 (not (string-match "\\S-" value)))
15453 (setq value 'none))
15454 (org-todo value)
15455 (org-set-tags nil 'align))
15456 ((equal property "PRIORITY")
15457 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15458 (string-to-char value) ?\ ))
15459 (org-set-tags nil 'align))
15460 ((equal property "CLOCKSUM")
15461 (if (not (re-search-forward
15462 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15463 (error "Cannot find a clock log")
15464 (goto-char (- (match-end 1) 2))
15465 (cond
15466 ((eq value 'earlier) (org-timestamp-down))
15467 ((eq value 'later) (org-timestamp-up)))
15468 (org-clock-sum-current-item)))
15469 ((equal property "SCHEDULED")
15470 (if (re-search-forward org-scheduled-time-regexp end t)
15471 (cond
15472 ((eq value 'earlier) (org-timestamp-change -1 'day))
15473 ((eq value 'later) (org-timestamp-change 1 'day))
15474 (t (call-interactively 'org-schedule)))
15475 (call-interactively 'org-schedule)))
15476 ((equal property "DEADLINE")
15477 (if (re-search-forward org-deadline-time-regexp end t)
15478 (cond
15479 ((eq value 'earlier) (org-timestamp-change -1 'day))
15480 ((eq value 'later) (org-timestamp-change 1 'day))
15481 (t (call-interactively 'org-deadline)))
15482 (call-interactively 'org-deadline)))
15483 ((member property org-special-properties)
15484 (error "The %s property can not yet be set with `org-entry-put'"
15485 property))
15486 (t ; a non-special property
15487 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15488 (setq range (org-get-property-block beg end 'force))
15489 (goto-char (car range))
15490 (if (re-search-forward
15491 (org-re-property property) (cdr range) t)
15492 (progn
15493 (delete-region (match-beginning 0) (match-end 0))
15494 (goto-char (match-beginning 0)))
15495 (goto-char (cdr range))
15496 (insert "\n")
15497 (backward-char 1)
15498 (org-indent-line))
15499 (insert ":" property ":")
15500 (and value (insert " " value))
15501 (org-indent-line)))))
15502 (run-hook-with-args 'org-property-changed-functions property value)))
15504 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15505 "Get all property keys in the current buffer.
15506 With INCLUDE-SPECIALS, also list the special properties that reflect things
15507 like tags and TODO state.
15508 With INCLUDE-DEFAULTS, also include properties that has special meaning
15509 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15510 and others.
15511 With INCLUDE-COLUMNS, also include property names given in COLUMN
15512 formats in the current buffer."
15513 (let (rtn range cfmt s p)
15514 (save-excursion
15515 (save-restriction
15516 (widen)
15517 (goto-char (point-min))
15518 (while (re-search-forward org-property-start-re nil t)
15519 (setq range (org-get-property-block))
15520 (goto-char (car range))
15521 (while (re-search-forward org-property-re
15522 (cdr range) t)
15523 (add-to-list 'rtn (org-match-string-no-properties 2)))
15524 (outline-next-heading))))
15526 (when include-specials
15527 (setq rtn (append org-special-properties rtn)))
15529 (when include-defaults
15530 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15531 (add-to-list 'rtn org-effort-property))
15533 (when include-columns
15534 (save-excursion
15535 (save-restriction
15536 (widen)
15537 (goto-char (point-min))
15538 (while (re-search-forward
15539 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15540 nil t)
15541 (setq cfmt (match-string 2) s 0)
15542 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15543 cfmt s)
15544 (setq s (match-end 0)
15545 p (match-string 1 cfmt))
15546 (unless (or (equal p "ITEM")
15547 (member p org-special-properties))
15548 (add-to-list 'rtn (match-string 1 cfmt))))))))
15550 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15552 (defun org-property-values (key)
15553 "Return a list of all values of property KEY in the current buffer."
15554 (save-excursion
15555 (save-restriction
15556 (widen)
15557 (goto-char (point-min))
15558 (let ((re (org-re-property key))
15559 values)
15560 (while (re-search-forward re nil t)
15561 (add-to-list 'values (org-trim (match-string 3))))
15562 (delete "" values)))))
15564 (defun org-insert-property-drawer ()
15565 "Insert a property drawer into the current entry."
15566 (org-back-to-heading t)
15567 (looking-at org-outline-regexp)
15568 (let ((indent (if org-adapt-indentation
15569 (- (match-end 0) (match-beginning 0))
15571 (beg (point))
15572 (re (concat "^[ \t]*" org-keyword-time-regexp))
15573 end hiddenp)
15574 (outline-next-heading)
15575 (setq end (point))
15576 (goto-char beg)
15577 (while (re-search-forward re end t))
15578 (setq hiddenp (outline-invisible-p))
15579 (end-of-line 1)
15580 (and (equal (char-after) ?\n) (forward-char 1))
15581 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15582 (if (member (match-string 1) '("CLOCK:" ":END:"))
15583 ;; just skip this line
15584 (beginning-of-line 2)
15585 ;; Drawer start, find the end
15586 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15587 (beginning-of-line 1)))
15588 (org-skip-over-state-notes)
15589 (skip-chars-backward " \t\n\r")
15590 (if (eq (char-before) ?*) (forward-char 1))
15591 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15592 (beginning-of-line 0)
15593 (org-indent-to-column indent)
15594 (beginning-of-line 2)
15595 (org-indent-to-column indent)
15596 (beginning-of-line 0)
15597 (if hiddenp
15598 (save-excursion
15599 (org-back-to-heading t)
15600 (hide-entry))
15601 (org-flag-drawer t))))
15603 (defun org-insert-drawer (&optional arg drawer)
15604 "Insert a drawer at point.
15606 Optional argument DRAWER, when non-nil, is a string representing
15607 drawer's name. Otherwise, the user is prompted for a name.
15609 If a region is active, insert the drawer around that region
15610 instead.
15612 Point is left between drawer's boundaries."
15613 (interactive "P")
15614 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15615 "LOGBOOK"))
15616 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15617 ;; internally by Org. They are meant to be inserted
15618 ;; automatically.
15619 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15620 ;; Remove system drawers from list. Note: For some reason,
15621 ;; `org-completing-read' ignores the predicate while
15622 ;; `completing-read' handles it fine.
15623 (drawer (if arg "PROPERTIES"
15624 (or drawer
15625 (completing-read
15626 "Drawer: " org-drawers
15627 (lambda (d) (not (member d system-drawers))))))))
15628 (cond
15629 ;; With C-u, fall back on `org-insert-property-drawer'
15630 (arg (org-insert-property-drawer))
15631 ;; With an active region, insert a drawer at point.
15632 ((not (org-region-active-p))
15633 (progn
15634 (unless (bolp) (insert "\n"))
15635 (insert (format ":%s:\n\n:END:\n" drawer))
15636 (forward-line -2)))
15637 ;; Otherwise, insert the drawer at point
15639 (let ((rbeg (region-beginning))
15640 (rend (copy-marker (region-end))))
15641 (unwind-protect
15642 (progn
15643 (goto-char rbeg)
15644 (beginning-of-line)
15645 (when (save-excursion
15646 (re-search-forward org-outline-regexp-bol rend t))
15647 (user-error "Drawers cannot contain headlines"))
15648 ;; Position point at the beginning of the first
15649 ;; non-blank line in region. Insert drawer's opening
15650 ;; there, then indent it.
15651 (org-skip-whitespace)
15652 (beginning-of-line)
15653 (insert ":" drawer ":\n")
15654 (forward-line -1)
15655 (indent-for-tab-command)
15656 ;; Move point to the beginning of the first blank line
15657 ;; after the last non-blank line in region. Insert
15658 ;; drawer's closing, then indent it.
15659 (goto-char rend)
15660 (skip-chars-backward " \r\t\n")
15661 (insert "\n:END:")
15662 (deactivate-mark t)
15663 (indent-for-tab-command)
15664 (unless (eolp) (insert "\n")))
15665 ;; Clear marker, whatever the outcome of insertion is.
15666 (set-marker rend nil)))))))
15668 (defvar org-property-set-functions-alist nil
15669 "Property set function alist.
15670 Each entry should have the following format:
15672 (PROPERTY . READ-FUNCTION)
15674 The read function will be called with the same argument as
15675 `org-completing-read'.")
15677 (defun org-set-property-function (property)
15678 "Get the function that should be used to set PROPERTY.
15679 This is computed according to `org-property-set-functions-alist'."
15680 (or (cdr (assoc property org-property-set-functions-alist))
15681 'org-completing-read))
15683 (defun org-read-property-value (property)
15684 "Read PROPERTY value from user."
15685 (let* ((completion-ignore-case t)
15686 (allowed (org-property-get-allowed-values nil property 'table))
15687 (cur (org-entry-get nil property))
15688 (prompt (concat property " value"
15689 (if (and cur (string-match "\\S-" cur))
15690 (concat " [" cur "]") "") ": "))
15691 (set-function (org-set-property-function property))
15692 (val (if allowed
15693 (funcall set-function prompt allowed nil
15694 (not (get-text-property 0 'org-unrestricted
15695 (caar allowed))))
15696 (let (org-completion-use-ido org-completion-use-iswitchb)
15697 (funcall set-function prompt
15698 (mapcar 'list (org-property-values property))
15699 nil nil "" nil cur)))))
15700 (if (equal val "")
15702 val)))
15704 (defvar org-last-set-property nil)
15705 (defvar org-last-set-property-value nil)
15706 (defun org-read-property-name ()
15707 "Read a property name."
15708 (let* ((completion-ignore-case t)
15709 (keys (org-buffer-property-keys nil t t))
15710 (default-prop (or (save-excursion
15711 (save-match-data
15712 (beginning-of-line)
15713 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15714 (null (string= (match-string 1) "END"))
15715 (match-string 1))))
15716 org-last-set-property))
15717 (property (org-icompleting-read
15718 (concat "Property"
15719 (if default-prop (concat " [" default-prop "]") "")
15720 ": ")
15721 (mapcar 'list keys)
15722 nil nil nil nil
15723 default-prop)))
15724 (if (member property keys)
15725 property
15726 (or (cdr (assoc (downcase property)
15727 (mapcar (lambda (x) (cons (downcase x) x))
15728 keys)))
15729 property))))
15731 (defun org-set-property-and-value (use-last)
15732 "Allow to set [PROPERTY]: [value] direction from prompt.
15733 When use-default, don't even ask, just use the last
15734 \"[PROPERTY]: [value]\" string from the history."
15735 (interactive "P")
15736 (let* ((completion-ignore-case t)
15737 (pv (or (and use-last org-last-set-property-value)
15738 (org-completing-read
15739 "Enter a \"[Property]: [value]\" pair: "
15740 nil nil nil nil nil
15741 org-last-set-property-value)))
15742 prop val)
15743 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15744 (setq prop (match-string 1 pv)
15745 val (match-string 2 pv))
15746 (org-set-property prop val))))
15748 (defun org-set-property (property value)
15749 "In the current entry, set PROPERTY to VALUE.
15750 When called interactively, this will prompt for a property name, offering
15751 completion on existing and default properties. And then it will prompt
15752 for a value, offering completion either on allowed values (via an inherited
15753 xxx_ALL property) or on existing values in other instances of this property
15754 in the current file."
15755 (interactive (list nil nil))
15756 (let* ((property (or property (org-read-property-name)))
15757 (value (or value (org-read-property-value property)))
15758 (fn (cdr (assoc property org-properties-postprocess-alist))))
15759 (setq org-last-set-property property)
15760 (setq org-last-set-property-value (concat property ": " value))
15761 ;; Possibly postprocess the inserted value:
15762 (when fn (setq value (funcall fn value)))
15763 (unless (equal (org-entry-get nil property) value)
15764 (org-entry-put nil property value))))
15766 (defun org-delete-property (property &optional delete-empty-drawer)
15767 "In the current entry, delete PROPERTY.
15768 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15769 an empty drawer to delete."
15770 (interactive
15771 (let* ((completion-ignore-case t)
15772 (prop (org-icompleting-read "Property: "
15773 (org-entry-properties nil 'standard))))
15774 (list prop)))
15775 (message "Property %s %s" property
15776 (if (org-entry-delete nil property delete-empty-drawer)
15777 "deleted"
15778 "was not present in the entry")))
15780 (defun org-delete-property-globally (property)
15781 "Remove PROPERTY globally, from all entries."
15782 (interactive
15783 (let* ((completion-ignore-case t)
15784 (prop (org-icompleting-read
15785 "Globally remove property: "
15786 (mapcar 'list (org-buffer-property-keys)))))
15787 (list prop)))
15788 (save-excursion
15789 (save-restriction
15790 (widen)
15791 (goto-char (point-min))
15792 (let ((cnt 0))
15793 (while (re-search-forward
15794 (org-re-property property)
15795 nil t)
15796 (setq cnt (1+ cnt))
15797 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15798 (message "Property \"%s\" removed from %d entries" property cnt)))))
15800 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15802 (defun org-compute-property-at-point ()
15803 "Compute the property at point.
15804 This looks for an enclosing column format, extracts the operator and
15805 then applies it to the property in the column format's scope."
15806 (interactive)
15807 (unless (org-at-property-p)
15808 (user-error "Not at a property"))
15809 (let ((prop (org-match-string-no-properties 2)))
15810 (org-columns-get-format-and-top-level)
15811 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15812 (user-error "No operator defined for property %s" prop))
15813 (org-columns-compute prop)))
15815 (defvar org-property-allowed-value-functions nil
15816 "Hook for functions supplying allowed values for a specific property.
15817 The functions must take a single argument, the name of the property, and
15818 return a flat list of allowed values. If \":ETC\" is one of
15819 the values, this means that these values are intended as defaults for
15820 completion, but that other values should be allowed too.
15821 The functions must return nil if they are not responsible for this
15822 property.")
15824 (defun org-property-get-allowed-values (pom property &optional table)
15825 "Get allowed values for the property PROPERTY.
15826 When TABLE is non-nil, return an alist that can directly be used for
15827 completion."
15828 (let (vals)
15829 (cond
15830 ((equal property "TODO")
15831 (setq vals (org-with-point-at pom
15832 (append org-todo-keywords-1 '("")))))
15833 ((equal property "PRIORITY")
15834 (let ((n org-lowest-priority))
15835 (while (>= n org-highest-priority)
15836 (push (char-to-string n) vals)
15837 (setq n (1- n)))))
15838 ((member property org-special-properties))
15839 ((setq vals (run-hook-with-args-until-success
15840 'org-property-allowed-value-functions property)))
15842 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15843 (when (and vals (string-match "\\S-" vals))
15844 (setq vals (car (read-from-string (concat "(" vals ")"))))
15845 (setq vals (mapcar (lambda (x)
15846 (cond ((stringp x) x)
15847 ((numberp x) (number-to-string x))
15848 ((symbolp x) (symbol-name x))
15849 (t "???")))
15850 vals)))))
15851 (when (member ":ETC" vals)
15852 (setq vals (remove ":ETC" vals))
15853 (org-add-props (car vals) '(org-unrestricted t)))
15854 (if table (mapcar 'list vals) vals)))
15856 (defun org-property-previous-allowed-value (&optional previous)
15857 "Switch to the next allowed value for this property."
15858 (interactive)
15859 (org-property-next-allowed-value t))
15861 (defun org-property-next-allowed-value (&optional previous)
15862 "Switch to the next allowed value for this property."
15863 (interactive)
15864 (unless (org-at-property-p)
15865 (user-error "Not at a property"))
15866 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15867 (key (match-string 2))
15868 (value (match-string 3))
15869 (allowed (or (org-property-get-allowed-values (point) key)
15870 (and (member value '("[ ]" "[-]" "[X]"))
15871 '("[ ]" "[X]"))))
15872 (heading (save-match-data (nth 4 (org-heading-components))))
15873 nval)
15874 (unless allowed
15875 (user-error "Allowed values for this property have not been defined"))
15876 (if previous (setq allowed (reverse allowed)))
15877 (if (member value allowed)
15878 (setq nval (car (cdr (member value allowed)))))
15879 (setq nval (or nval (car allowed)))
15880 (if (equal nval value)
15881 (user-error "Only one allowed value for this property"))
15882 (org-at-property-p)
15883 (replace-match (concat " :" key ": " nval) t t)
15884 (org-indent-line)
15885 (beginning-of-line 1)
15886 (skip-chars-forward " \t")
15887 (when (equal prop org-effort-property)
15888 (save-excursion
15889 (org-back-to-heading t)
15890 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15891 (when (string= org-clock-current-task heading)
15892 (setq org-clock-effort nval)
15893 (org-clock-update-mode-line)))
15894 (run-hook-with-args 'org-property-changed-functions key nval)))
15896 (defun org-find-olp (path &optional this-buffer)
15897 "Return a marker pointing to the entry at outline path OLP.
15898 If anything goes wrong, throw an error.
15899 You can wrap this call to catch the error like this:
15901 (condition-case msg
15902 (org-mobile-locate-entry (match-string 4))
15903 (error (nth 1 msg)))
15905 The return value will then be either a string with the error message,
15906 or a marker if everything is OK.
15908 If THIS-BUFFER is set, the outline path does not contain a file,
15909 only headings."
15910 (let* ((file (if this-buffer buffer-file-name (pop path)))
15911 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15912 (level 1)
15913 (lmin 1)
15914 (lmax 1)
15915 limit re end found pos heading cnt flevel)
15916 (unless buffer (error "File not found :%s" file))
15917 (with-current-buffer buffer
15918 (save-excursion
15919 (save-restriction
15920 (widen)
15921 (setq limit (point-max))
15922 (goto-char (point-min))
15923 (while (setq heading (pop path))
15924 (setq re (format org-complex-heading-regexp-format
15925 (regexp-quote heading)))
15926 (setq cnt 0 pos (point))
15927 (while (re-search-forward re end t)
15928 (setq level (- (match-end 1) (match-beginning 1)))
15929 (if (and (>= level lmin) (<= level lmax))
15930 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15931 (when (= cnt 0) (error "Heading not found on level %d: %s"
15932 lmax heading))
15933 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15934 lmax heading))
15935 (goto-char found)
15936 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15937 (setq end (save-excursion (org-end-of-subtree t t))))
15938 (when (org-at-heading-p)
15939 (point-marker)))))))
15941 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15942 "Find node HEADING in BUFFER.
15943 Return a marker to the heading if it was found, or nil if not.
15944 If POS-ONLY is set, return just the position instead of a marker.
15946 The heading text must match exact, but it may have a TODO keyword,
15947 a priority cookie and tags in the standard locations."
15948 (with-current-buffer (or buffer (current-buffer))
15949 (save-excursion
15950 (save-restriction
15951 (widen)
15952 (goto-char (point-min))
15953 (let (case-fold-search)
15954 (if (re-search-forward
15955 (format org-complex-heading-regexp-format
15956 (regexp-quote heading)) nil t)
15957 (if pos-only
15958 (match-beginning 0)
15959 (move-marker (make-marker) (match-beginning 0)))))))))
15961 (defun org-find-exact-heading-in-directory (heading &optional dir)
15962 "Find Org node headline HEADING in all .org files in directory DIR.
15963 When the target headline is found, return a marker to this location."
15964 (let ((files (directory-files (or dir default-directory)
15965 nil "\\`[^.#].*\\.org\\'"))
15966 file visiting m buffer)
15967 (catch 'found
15968 (while (setq file (pop files))
15969 (message "trying %s" file)
15970 (setq visiting (org-find-base-buffer-visiting file))
15971 (setq buffer (or visiting (find-file-noselect file)))
15972 (setq m (org-find-exact-headline-in-buffer
15973 heading buffer))
15974 (when (and (not m) (not visiting)) (kill-buffer buffer))
15975 (and m (throw 'found m))))))
15977 (defun org-find-entry-with-id (ident)
15978 "Locate the entry that contains the ID property with exact value IDENT.
15979 IDENT can be a string, a symbol or a number, this function will search for
15980 the string representation of it.
15981 Return the position where this entry starts, or nil if there is no such entry."
15982 (interactive "sID: ")
15983 (let ((id (cond
15984 ((stringp ident) ident)
15985 ((symbol-name ident) (symbol-name ident))
15986 ((numberp ident) (number-to-string ident))
15987 (t (error "IDENT %s must be a string, symbol or number" ident))))
15988 (case-fold-search nil))
15989 (save-excursion
15990 (save-restriction
15991 (widen)
15992 (goto-char (point-min))
15993 (when (re-search-forward
15994 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15995 nil t)
15996 (org-back-to-heading t)
15997 (point))))))
15999 ;;;; Timestamps
16001 (defvar org-last-changed-timestamp nil)
16002 (defvar org-last-inserted-timestamp nil
16003 "The last time stamp inserted with `org-insert-time-stamp'.")
16004 (defvar org-time-was-given) ; dynamically scoped parameter
16005 (defvar org-end-time-was-given) ; dynamically scoped parameter
16006 (defvar org-ts-what) ; dynamically scoped parameter
16008 (defun org-time-stamp (arg &optional inactive)
16009 "Prompt for a date/time and insert a time stamp.
16010 If the user specifies a time like HH:MM or if this command is
16011 called with at least one prefix argument, the time stamp contains
16012 the date and the time. Otherwise, only the date is be included.
16014 All parts of a date not specified by the user is filled in from
16015 the current date/time. So if you just press return without
16016 typing anything, the time stamp will represent the current
16017 date/time.
16019 If there is already a timestamp at the cursor, it will be
16020 modified.
16022 With two universal prefix arguments, insert an active timestamp
16023 with the current time without prompting the user."
16024 (interactive "P")
16025 (let* ((ts nil)
16026 (default-time
16027 ;; Default time is either today, or, when entering a range,
16028 ;; the range start.
16029 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16030 (save-excursion
16031 (re-search-backward
16032 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16033 (- (point) 20) t)))
16034 (apply 'encode-time (org-parse-time-string (match-string 1)))
16035 (current-time)))
16036 (default-input (and ts (org-get-compact-tod ts)))
16037 (repeater (save-excursion
16038 (save-match-data
16039 (beginning-of-line)
16040 (when (re-search-forward
16041 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16042 (save-excursion (progn (end-of-line) (point))) t)
16043 (match-string 0)))))
16044 org-time-was-given org-end-time-was-given time)
16045 (cond
16046 ((and (org-at-timestamp-p t)
16047 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16048 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16049 (insert "--")
16050 (setq time (let ((this-command this-command))
16051 (org-read-date arg 'totime nil nil
16052 default-time default-input inactive)))
16053 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16054 ((org-at-timestamp-p t)
16055 (setq time (let ((this-command this-command))
16056 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16057 (when (org-at-timestamp-p t) ; just to get the match data
16058 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16059 (replace-match "")
16060 (setq org-last-changed-timestamp
16061 (org-insert-time-stamp
16062 time (or org-time-was-given arg)
16063 inactive nil nil (list org-end-time-was-given)))
16064 (when repeater (goto-char (1- (point))) (insert " " repeater)
16065 (setq org-last-changed-timestamp
16066 (concat (substring org-last-inserted-timestamp 0 -1)
16067 " " repeater ">"))))
16068 (message "Timestamp updated"))
16069 ((equal arg '(16))
16070 (org-insert-time-stamp (current-time) t))
16072 (setq time (let ((this-command this-command))
16073 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16074 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16075 nil nil (list org-end-time-was-given))))))
16077 ;; FIXME: can we use this for something else, like computing time differences?
16078 (defun org-get-compact-tod (s)
16079 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16080 (let* ((t1 (match-string 1 s))
16081 (h1 (string-to-number (match-string 2 s)))
16082 (m1 (string-to-number (match-string 3 s)))
16083 (t2 (and (match-end 4) (match-string 5 s)))
16084 (h2 (and t2 (string-to-number (match-string 6 s))))
16085 (m2 (and t2 (string-to-number (match-string 7 s))))
16086 dh dm)
16087 (if (not t2)
16089 (setq dh (- h2 h1) dm (- m2 m1))
16090 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16091 (concat t1 "+" (number-to-string dh)
16092 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16094 (defun org-time-stamp-inactive (&optional arg)
16095 "Insert an inactive time stamp.
16096 An inactive time stamp is enclosed in square brackets instead of angle
16097 brackets. It is inactive in the sense that it does not trigger agenda entries,
16098 does not link to the calendar and cannot be changed with the S-cursor keys.
16099 So these are more for recording a certain time/date."
16100 (interactive "P")
16101 (org-time-stamp arg 'inactive))
16103 (defvar org-date-ovl (make-overlay 1 1))
16104 (overlay-put org-date-ovl 'face 'org-date-selected)
16105 (org-detach-overlay org-date-ovl)
16107 (defvar org-ans1) ; dynamically scoped parameter
16108 (defvar org-ans2) ; dynamically scoped parameter
16110 (defvar org-plain-time-of-day-regexp) ; defined below
16112 (defvar org-overriding-default-time nil) ; dynamically scoped
16113 (defvar org-read-date-overlay nil)
16114 (defvar org-dcst nil) ; dynamically scoped
16115 (defvar org-read-date-history nil)
16116 (defvar org-read-date-final-answer nil)
16117 (defvar org-read-date-analyze-futurep nil)
16118 (defvar org-read-date-analyze-forced-year nil)
16119 (defvar org-read-date-inactive)
16121 (defvar org-read-date-minibuffer-local-map
16122 (let ((map (make-sparse-keymap)))
16123 (set-keymap-parent map minibuffer-local-map)
16124 (org-defkey map (kbd ".")
16125 (lambda () (interactive)
16126 ;; Are we at the beginning of the prompt?
16127 (if (looking-back "^[^:]+: ")
16128 (org-eval-in-calendar '(calendar-goto-today))
16129 (insert "."))))
16130 (org-defkey map (kbd "C-.")
16131 (lambda () (interactive)
16132 (org-eval-in-calendar '(calendar-goto-today))))
16133 (org-defkey map [(meta shift left)]
16134 (lambda () (interactive)
16135 (org-eval-in-calendar '(calendar-backward-month 1))))
16136 (org-defkey map [(meta shift right)]
16137 (lambda () (interactive)
16138 (org-eval-in-calendar '(calendar-forward-month 1))))
16139 (org-defkey map [(meta shift up)]
16140 (lambda () (interactive)
16141 (org-eval-in-calendar '(calendar-backward-year 1))))
16142 (org-defkey map [(meta shift down)]
16143 (lambda () (interactive)
16144 (org-eval-in-calendar '(calendar-forward-year 1))))
16145 (org-defkey map [?\e (shift left)]
16146 (lambda () (interactive)
16147 (org-eval-in-calendar '(calendar-backward-month 1))))
16148 (org-defkey map [?\e (shift right)]
16149 (lambda () (interactive)
16150 (org-eval-in-calendar '(calendar-forward-month 1))))
16151 (org-defkey map [?\e (shift up)]
16152 (lambda () (interactive)
16153 (org-eval-in-calendar '(calendar-backward-year 1))))
16154 (org-defkey map [?\e (shift down)]
16155 (lambda () (interactive)
16156 (org-eval-in-calendar '(calendar-forward-year 1))))
16157 (org-defkey map [(shift up)]
16158 (lambda () (interactive)
16159 (org-eval-in-calendar '(calendar-backward-week 1))))
16160 (org-defkey map [(shift down)]
16161 (lambda () (interactive)
16162 (org-eval-in-calendar '(calendar-forward-week 1))))
16163 (org-defkey map [(shift left)]
16164 (lambda () (interactive)
16165 (org-eval-in-calendar '(calendar-backward-day 1))))
16166 (org-defkey map [(shift right)]
16167 (lambda () (interactive)
16168 (org-eval-in-calendar '(calendar-forward-day 1))))
16169 (org-defkey map "!"
16170 (lambda () (interactive)
16171 (org-eval-in-calendar '(diary-view-entries))
16172 (message "")))
16173 (org-defkey map ">"
16174 (lambda () (interactive)
16175 (org-eval-in-calendar '(scroll-calendar-left 1))))
16176 (org-defkey map "<"
16177 (lambda () (interactive)
16178 (org-eval-in-calendar '(scroll-calendar-right 1))))
16179 (org-defkey map "\C-v"
16180 (lambda () (interactive)
16181 (org-eval-in-calendar
16182 '(calendar-scroll-left-three-months 1))))
16183 (org-defkey map "\M-v"
16184 (lambda () (interactive)
16185 (org-eval-in-calendar
16186 '(calendar-scroll-right-three-months 1))))
16187 map)
16188 "Keymap for minibuffer commands when using `org-read-date'.")
16190 (defun org-read-date (&optional org-with-time to-time from-string prompt
16191 default-time default-input inactive)
16192 "Read a date, possibly a time, and make things smooth for the user.
16193 The prompt will suggest to enter an ISO date, but you can also enter anything
16194 which will at least partially be understood by `parse-time-string'.
16195 Unrecognized parts of the date will default to the current day, month, year,
16196 hour and minute. If this command is called to replace a timestamp at point,
16197 or to enter the second timestamp of a range, the default time is taken
16198 from the existing stamp. Furthermore, the command prefers the future,
16199 so if you are giving a date where the year is not given, and the day-month
16200 combination is already past in the current year, it will assume you
16201 mean next year. For details, see the manual. A few examples:
16203 3-2-5 --> 2003-02-05
16204 feb 15 --> currentyear-02-15
16205 2/15 --> currentyear-02-15
16206 sep 12 9 --> 2009-09-12
16207 12:45 --> today 12:45
16208 22 sept 0:34 --> currentyear-09-22 0:34
16209 12 --> currentyear-currentmonth-12
16210 Fri --> nearest Friday after today
16211 -Tue --> last Tuesday
16212 etc.
16214 Furthermore you can specify a relative date by giving, as the *first* thing
16215 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16216 change in days weeks, months, years.
16217 With a single plus or minus, the date is relative to today. With a double
16218 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16219 +4d --> four days from today
16220 +4 --> same as above
16221 +2w --> two weeks from today
16222 ++5 --> five days from default date
16224 The function understands only English month and weekday abbreviations.
16226 While prompting, a calendar is popped up - you can also select the
16227 date with the mouse (button 1). The calendar shows a period of three
16228 months. To scroll it to other months, use the keys `>' and `<'.
16229 If you don't like the calendar, turn it off with
16230 \(setq org-read-date-popup-calendar nil)
16232 With optional argument TO-TIME, the date will immediately be converted
16233 to an internal time.
16234 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16235 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16236 still enter a time, and this function will inform the calling routine
16237 about this change. The calling routine may then choose to change the
16238 format used to insert the time stamp into the buffer to include the time.
16239 With optional argument FROM-STRING, read from this string instead from
16240 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16241 the time/date that is used for everything that is not specified by the
16242 user."
16243 (require 'parse-time)
16244 (let* ((org-time-stamp-rounding-minutes
16245 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16246 (org-dcst org-display-custom-times)
16247 (ct (org-current-time))
16248 (org-def (or org-overriding-default-time default-time ct))
16249 (org-defdecode (decode-time org-def))
16250 (dummy (progn
16251 (when (< (nth 2 org-defdecode) org-extend-today-until)
16252 (setcar (nthcdr 2 org-defdecode) -1)
16253 (setcar (nthcdr 1 org-defdecode) 59)
16254 (setq org-def (apply 'encode-time org-defdecode)
16255 org-defdecode (decode-time org-def)))))
16256 (mouse-autoselect-window nil) ; Don't let the mouse jump
16257 (calendar-frame-setup nil)
16258 (calendar-setup nil)
16259 (calendar-move-hook nil)
16260 (calendar-view-diary-initially-flag nil)
16261 (calendar-view-holidays-initially-flag nil)
16262 (timestr (format-time-string
16263 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16264 (prompt (concat (if prompt (concat prompt " ") "")
16265 (format "Date+time [%s]: " timestr)))
16266 ans (org-ans0 "") org-ans1 org-ans2 final)
16268 (cond
16269 (from-string (setq ans from-string))
16270 (org-read-date-popup-calendar
16271 (save-excursion
16272 (save-window-excursion
16273 (calendar)
16274 (org-eval-in-calendar '(setq cursor-type nil) t)
16275 (unwind-protect
16276 (progn
16277 (calendar-forward-day (- (time-to-days org-def)
16278 (calendar-absolute-from-gregorian
16279 (calendar-current-date))))
16280 (org-eval-in-calendar nil t)
16281 (let* ((old-map (current-local-map))
16282 (map (copy-keymap calendar-mode-map))
16283 (minibuffer-local-map
16284 (copy-keymap org-read-date-minibuffer-local-map)))
16285 (org-defkey map (kbd "RET") 'org-calendar-select)
16286 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16287 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16288 (unwind-protect
16289 (progn
16290 (use-local-map map)
16291 (setq org-read-date-inactive inactive)
16292 (add-hook 'post-command-hook 'org-read-date-display)
16293 (setq org-ans0 (read-string prompt default-input
16294 'org-read-date-history nil))
16295 ;; org-ans0: from prompt
16296 ;; org-ans1: from mouse click
16297 ;; org-ans2: from calendar motion
16298 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16299 (remove-hook 'post-command-hook 'org-read-date-display)
16300 (use-local-map old-map)
16301 (when org-read-date-overlay
16302 (delete-overlay org-read-date-overlay)
16303 (setq org-read-date-overlay nil)))))
16304 (bury-buffer "*Calendar*")))))
16306 (t ; Naked prompt only
16307 (unwind-protect
16308 (setq ans (read-string prompt default-input
16309 'org-read-date-history timestr))
16310 (when org-read-date-overlay
16311 (delete-overlay org-read-date-overlay)
16312 (setq org-read-date-overlay nil)))))
16314 (setq final (org-read-date-analyze ans org-def org-defdecode))
16316 (when org-read-date-analyze-forced-year
16317 (message "Year was forced into %s"
16318 (if org-read-date-force-compatible-dates
16319 "compatible range (1970-2037)"
16320 "range representable on this machine"))
16321 (ding))
16323 ;; One round trip to get rid of 34th of August and stuff like that....
16324 (setq final (decode-time (apply 'encode-time final)))
16326 (setq org-read-date-final-answer ans)
16328 (if to-time
16329 (apply 'encode-time final)
16330 (if (and (boundp 'org-time-was-given) org-time-was-given)
16331 (format "%04d-%02d-%02d %02d:%02d"
16332 (nth 5 final) (nth 4 final) (nth 3 final)
16333 (nth 2 final) (nth 1 final))
16334 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16336 (defvar org-def)
16337 (defvar org-defdecode)
16338 (defvar org-with-time)
16339 (defun org-read-date-display ()
16340 "Display the current date prompt interpretation in the minibuffer."
16341 (when org-read-date-display-live
16342 (when org-read-date-overlay
16343 (delete-overlay org-read-date-overlay))
16344 (when (minibufferp (current-buffer))
16345 (save-excursion
16346 (end-of-line 1)
16347 (while (not (equal (buffer-substring
16348 (max (point-min) (- (point) 4)) (point))
16349 " "))
16350 (insert " ")))
16351 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16352 " " (or org-ans1 org-ans2)))
16353 (org-end-time-was-given nil)
16354 (f (org-read-date-analyze ans org-def org-defdecode))
16355 (fmts (if org-dcst
16356 org-time-stamp-custom-formats
16357 org-time-stamp-formats))
16358 (fmt (if (or org-with-time
16359 (and (boundp 'org-time-was-given) org-time-was-given))
16360 (cdr fmts)
16361 (car fmts)))
16362 (txt (format-time-string fmt (apply 'encode-time f)))
16363 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16364 (txt (concat "=> " txt)))
16365 (when (and org-end-time-was-given
16366 (string-match org-plain-time-of-day-regexp txt))
16367 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16368 org-end-time-was-given
16369 (substring txt (match-end 0)))))
16370 (when org-read-date-analyze-futurep
16371 (setq txt (concat txt " (=>F)")))
16372 (setq org-read-date-overlay
16373 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16374 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16376 (defun org-read-date-analyze (ans org-def org-defdecode)
16377 "Analyze the combined answer of the date prompt."
16378 ;; FIXME: cleanup and comment
16379 (let ((nowdecode (decode-time (current-time)))
16380 delta deltan deltaw deltadef year month day
16381 hour minute second wday pm h2 m2 tl wday1
16382 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16383 (setq org-read-date-analyze-futurep nil
16384 org-read-date-analyze-forced-year nil)
16385 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16386 (setq ans "+0"))
16388 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16389 (setq ans (replace-match "" t t ans)
16390 deltan (car delta)
16391 deltaw (nth 1 delta)
16392 deltadef (nth 2 delta)))
16394 ;; Check if there is an iso week date in there. If yes, store the
16395 ;; info and postpone interpreting it until the rest of the parsing
16396 ;; is done.
16397 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16398 (setq iso-year (if (match-end 1)
16399 (org-small-year-to-year
16400 (string-to-number (match-string 1 ans))))
16401 iso-weekday (if (match-end 3)
16402 (string-to-number (match-string 3 ans)))
16403 iso-week (string-to-number (match-string 2 ans)))
16404 (setq ans (replace-match "" t t ans)))
16406 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16407 (when (string-match
16408 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16409 (setq year (if (match-end 2)
16410 (string-to-number (match-string 2 ans))
16411 (progn (setq kill-year t)
16412 (string-to-number (format-time-string "%Y"))))
16413 month (string-to-number (match-string 3 ans))
16414 day (string-to-number (match-string 4 ans)))
16415 (if (< year 100) (setq year (+ 2000 year)))
16416 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16417 t nil ans)))
16419 ;; Help matching dotted european dates
16420 (when (string-match
16421 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16422 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16423 (setq kill-year t)
16424 (string-to-number (format-time-string "%Y")))
16425 day (string-to-number (match-string 1 ans))
16426 month (string-to-number (match-string 2 ans))
16427 ans (replace-match (format "%04d-%02d-%02d" year month day)
16428 t nil ans)))
16430 ;; Help matching american dates, like 5/30 or 5/30/7
16431 (when (string-match
16432 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16433 (setq year (if (match-end 4)
16434 (string-to-number (match-string 4 ans))
16435 (progn (setq kill-year t)
16436 (string-to-number (format-time-string "%Y"))))
16437 month (string-to-number (match-string 1 ans))
16438 day (string-to-number (match-string 2 ans)))
16439 (if (< year 100) (setq year (+ 2000 year)))
16440 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16441 t nil ans)))
16442 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16443 ;; If there is a time with am/pm, and *no* time without it, we convert
16444 ;; so that matching will be successful.
16445 (loop for i from 1 to 2 do ; twice, for end time as well
16446 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16447 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16448 (setq hour (string-to-number (match-string 1 ans))
16449 minute (if (match-end 3)
16450 (string-to-number (match-string 3 ans))
16452 pm (equal ?p
16453 (string-to-char (downcase (match-string 4 ans)))))
16454 (if (and (= hour 12) (not pm))
16455 (setq hour 0)
16456 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16457 (setq ans (replace-match (format "%02d:%02d" hour minute)
16458 t t ans))))
16460 ;; Check if a time range is given as a duration
16461 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16462 (setq hour (string-to-number (match-string 1 ans))
16463 h2 (+ hour (string-to-number (match-string 3 ans)))
16464 minute (string-to-number (match-string 2 ans))
16465 m2 (+ minute (if (match-end 5) (string-to-number
16466 (match-string 5 ans))0)))
16467 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16468 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16469 t t ans)))
16471 ;; Check if there is a time range
16472 (when (boundp 'org-end-time-was-given)
16473 (setq org-time-was-given nil)
16474 (when (and (string-match org-plain-time-of-day-regexp ans)
16475 (match-end 8))
16476 (setq org-end-time-was-given (match-string 8 ans))
16477 (setq ans (concat (substring ans 0 (match-beginning 7))
16478 (substring ans (match-end 7))))))
16480 (setq tl (parse-time-string ans)
16481 day (or (nth 3 tl) (nth 3 org-defdecode))
16482 month (or (nth 4 tl)
16483 (if (and org-read-date-prefer-future
16484 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16485 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16486 (nth 4 org-defdecode)))
16487 year (or (and (not kill-year) (nth 5 tl))
16488 (if (and org-read-date-prefer-future
16489 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16490 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16491 (nth 5 org-defdecode)))
16492 hour (or (nth 2 tl) (nth 2 org-defdecode))
16493 minute (or (nth 1 tl) (nth 1 org-defdecode))
16494 second (or (nth 0 tl) 0)
16495 wday (nth 6 tl))
16497 (when (and (eq org-read-date-prefer-future 'time)
16498 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16499 (equal day (nth 3 nowdecode))
16500 (equal month (nth 4 nowdecode))
16501 (equal year (nth 5 nowdecode))
16502 (nth 2 tl)
16503 (or (< (nth 2 tl) (nth 2 nowdecode))
16504 (and (= (nth 2 tl) (nth 2 nowdecode))
16505 (nth 1 tl)
16506 (< (nth 1 tl) (nth 1 nowdecode)))))
16507 (setq day (1+ day)
16508 futurep t))
16510 ;; Special date definitions below
16511 (cond
16512 (iso-week
16513 ;; There was an iso week
16514 (require 'cal-iso)
16515 (setq futurep nil)
16516 (setq year (or iso-year year)
16517 day (or iso-weekday wday 1)
16518 wday nil ; to make sure that the trigger below does not match
16519 iso-date (calendar-gregorian-from-absolute
16520 (calendar-absolute-from-iso
16521 (list iso-week day year))))
16522 ; FIXME: Should we also push ISO weeks into the future?
16523 ; (when (and org-read-date-prefer-future
16524 ; (not iso-year)
16525 ; (< (calendar-absolute-from-gregorian iso-date)
16526 ; (time-to-days (current-time))))
16527 ; (setq year (1+ year)
16528 ; iso-date (calendar-gregorian-from-absolute
16529 ; (calendar-absolute-from-iso
16530 ; (list iso-week day year)))))
16531 (setq month (car iso-date)
16532 year (nth 2 iso-date)
16533 day (nth 1 iso-date)))
16534 (deltan
16535 (setq futurep nil)
16536 (unless deltadef
16537 (let ((now (decode-time (current-time))))
16538 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16539 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16540 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16541 ((equal deltaw "m") (setq month (+ month deltan)))
16542 ((equal deltaw "y") (setq year (+ year deltan)))))
16543 ((and wday (not (nth 3 tl)))
16544 ;; Weekday was given, but no day, so pick that day in the week
16545 ;; on or after the derived date.
16546 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16547 (unless (equal wday wday1)
16548 (setq day (+ day (% (- wday wday1 -7) 7))))))
16549 (if (and (boundp 'org-time-was-given)
16550 (nth 2 tl))
16551 (setq org-time-was-given t))
16552 (if (< year 100) (setq year (+ 2000 year)))
16553 ;; Check of the date is representable
16554 (if org-read-date-force-compatible-dates
16555 (progn
16556 (if (< year 1970)
16557 (setq year 1970 org-read-date-analyze-forced-year t))
16558 (if (> year 2037)
16559 (setq year 2037 org-read-date-analyze-forced-year t)))
16560 (condition-case nil
16561 (ignore (encode-time second minute hour day month year))
16562 (error
16563 (setq year (nth 5 org-defdecode))
16564 (setq org-read-date-analyze-forced-year t))))
16565 (setq org-read-date-analyze-futurep futurep)
16566 (list second minute hour day month year)))
16568 (defvar parse-time-weekdays)
16569 (defun org-read-date-get-relative (s today default)
16570 "Check string S for special relative date string.
16571 TODAY and DEFAULT are internal times, for today and for a default.
16572 Return shift list (N what def-flag)
16573 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16574 N is the number of WHATs to shift.
16575 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16576 the DEFAULT date rather than TODAY."
16577 (require 'parse-time)
16578 (when (and
16579 (string-match
16580 (concat
16581 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16582 "\\([0-9]+\\)?"
16583 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16584 "\\([ \t]\\|$\\)") s)
16585 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16586 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16587 (string-to-char (substring (match-string 1 s) -1))
16588 ?+))
16589 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16590 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16591 (what (if (match-end 3) (match-string 3 s) "d"))
16592 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16593 (date (if rel default today))
16594 (wday (nth 6 (decode-time date)))
16595 delta)
16596 (if wday1
16597 (progn
16598 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16599 (if (= delta 0) (setq delta 7))
16600 (if (= dir ?-)
16601 (progn
16602 (setq delta (- delta 7))
16603 (if (= delta 0) (setq delta -7))))
16604 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16605 (list delta "d" rel))
16606 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16608 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16609 "Turn a user-specified date into the internal representation.
16610 The internal representation needed by the calendar is (month day year).
16611 This is a wrapper to handle the brain-dead convention in calendar that
16612 user function argument order change dependent on argument order."
16613 (if (boundp 'calendar-date-style)
16614 (cond
16615 ((eq calendar-date-style 'american)
16616 (list arg1 arg2 arg3))
16617 ((eq calendar-date-style 'european)
16618 (list arg2 arg1 arg3))
16619 ((eq calendar-date-style 'iso)
16620 (list arg2 arg3 arg1)))
16621 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16622 (if (org-bound-and-true-p european-calendar-style)
16623 (list arg2 arg1 arg3)
16624 (list arg1 arg2 arg3)))))
16626 (defun org-eval-in-calendar (form &optional keepdate)
16627 "Eval FORM in the calendar window and return to current window.
16628 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16629 otherwise stick to the current value of `org-ans2'."
16630 (let ((sf (selected-frame))
16631 (sw (selected-window)))
16632 (select-window (get-buffer-window "*Calendar*" t))
16633 (eval form)
16634 (when (and (not keepdate) (calendar-cursor-to-date))
16635 (let* ((date (calendar-cursor-to-date))
16636 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16637 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16638 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16639 (select-window sw)
16640 (org-select-frame-set-input-focus sf)))
16642 (defun org-calendar-select ()
16643 "Return to `org-read-date' with the date currently selected.
16644 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16645 (interactive)
16646 (when (calendar-cursor-to-date)
16647 (let* ((date (calendar-cursor-to-date))
16648 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16649 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16650 (if (active-minibuffer-window) (exit-minibuffer))))
16652 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16653 "Insert a date stamp for the date given by the internal TIME.
16654 WITH-HM means use the stamp format that includes the time of the day.
16655 INACTIVE means use square brackets instead of angular ones, so that the
16656 stamp will not contribute to the agenda.
16657 PRE and POST are optional strings to be inserted before and after the
16658 stamp.
16659 The command returns the inserted time stamp."
16660 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16661 stamp)
16662 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16663 (insert-before-markers (or pre ""))
16664 (when (listp extra)
16665 (setq extra (car extra))
16666 (if (and (stringp extra)
16667 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16668 (setq extra (format "-%02d:%02d"
16669 (string-to-number (match-string 1 extra))
16670 (string-to-number (match-string 2 extra))))
16671 (setq extra nil)))
16672 (when extra
16673 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16674 (insert-before-markers (setq stamp (format-time-string fmt time)))
16675 (insert-before-markers (or post ""))
16676 (setq org-last-inserted-timestamp stamp)))
16678 (defun org-toggle-time-stamp-overlays ()
16679 "Toggle the use of custom time stamp formats."
16680 (interactive)
16681 (setq org-display-custom-times (not org-display-custom-times))
16682 (unless org-display-custom-times
16683 (let ((p (point-min)) (bmp (buffer-modified-p)))
16684 (while (setq p (next-single-property-change p 'display))
16685 (if (and (get-text-property p 'display)
16686 (eq (get-text-property p 'face) 'org-date))
16687 (remove-text-properties
16688 p (setq p (next-single-property-change p 'display))
16689 '(display t))))
16690 (set-buffer-modified-p bmp)))
16691 (if (featurep 'xemacs)
16692 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16693 (org-restart-font-lock)
16694 (setq org-table-may-need-update t)
16695 (if org-display-custom-times
16696 (message "Time stamps are overlaid with custom format")
16697 (message "Time stamp overlays removed")))
16699 (defun org-display-custom-time (beg end)
16700 "Overlay modified time stamp format over timestamp between BEG and END."
16701 (let* ((ts (buffer-substring beg end))
16702 t1 w1 with-hm tf time str w2 (off 0))
16703 (save-match-data
16704 (setq t1 (org-parse-time-string ts t))
16705 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16706 (setq off (- (match-end 0) (match-beginning 0)))))
16707 (setq end (- end off))
16708 (setq w1 (- end beg)
16709 with-hm (and (nth 1 t1) (nth 2 t1))
16710 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16711 time (org-fix-decoded-time t1)
16712 str (org-add-props
16713 (format-time-string
16714 (substring tf 1 -1) (apply 'encode-time time))
16715 nil 'mouse-face 'highlight)
16716 w2 (length str))
16717 (if (not (= w2 w1))
16718 (add-text-properties (1+ beg) (+ 2 beg)
16719 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16720 (if (featurep 'xemacs)
16721 (progn
16722 (put-text-property beg end 'invisible t)
16723 (put-text-property beg end 'end-glyph (make-glyph str)))
16724 (put-text-property beg end 'display str))))
16726 (defun org-translate-time (string)
16727 "Translate all timestamps in STRING to custom format.
16728 But do this only if the variable `org-display-custom-times' is set."
16729 (when org-display-custom-times
16730 (save-match-data
16731 (let* ((start 0)
16732 (re org-ts-regexp-both)
16733 t1 with-hm inactive tf time str beg end)
16734 (while (setq start (string-match re string start))
16735 (setq beg (match-beginning 0)
16736 end (match-end 0)
16737 t1 (save-match-data
16738 (org-parse-time-string (substring string beg end) t))
16739 with-hm (and (nth 1 t1) (nth 2 t1))
16740 inactive (equal (substring string beg (1+ beg)) "[")
16741 tf (funcall (if with-hm 'cdr 'car)
16742 org-time-stamp-custom-formats)
16743 time (org-fix-decoded-time t1)
16744 str (format-time-string
16745 (concat
16746 (if inactive "[" "<") (substring tf 1 -1)
16747 (if inactive "]" ">"))
16748 (apply 'encode-time time))
16749 string (replace-match str t t string)
16750 start (+ start (length str)))))))
16751 string)
16753 (defun org-fix-decoded-time (time)
16754 "Set 0 instead of nil for the first 6 elements of time.
16755 Don't touch the rest."
16756 (let ((n 0))
16757 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16759 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16761 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16762 "Difference between TIMESTAMP-STRING and now in days.
16763 If SECONDS is non-nil, return the difference in seconds."
16764 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16765 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16766 (funcall fdiff (current-time)))))
16768 (defun org-deadline-close (timestamp-string &optional ndays)
16769 "Is the time in TIMESTAMP-STRING close to the current date?"
16770 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16771 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16772 (not (org-entry-is-done-p))))
16774 (defun org-get-wdays (ts &optional delay zero-delay)
16775 "Get the deadline lead time appropriate for timestring TS.
16776 When DELAY is non-nil, get the delay time for scheduled items
16777 instead of the deadline lead time. When ZERO-DELAY is non-nil
16778 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16779 don't try to find the delay cookie in the scheduled timestamp."
16780 (let ((tv (if delay org-scheduled-delay-days
16781 org-deadline-warning-days)))
16782 (cond
16783 ((or (and delay (< tv 0))
16784 (and delay zero-delay (<= tv 0))
16785 (and (not delay) (<= tv 0)))
16786 ;; Enforce this value no matter what
16787 (- tv))
16788 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16789 ;; lead time is specified.
16790 (floor (* (string-to-number (match-string 1 ts))
16791 (cdr (assoc (match-string 2 ts)
16792 '(("d" . 1) ("w" . 7)
16793 ("m" . 30.4) ("y" . 365.25)
16794 ("h" . 0.041667)))))))
16795 ;; go for the default.
16796 (t tv))))
16798 (defun org-calendar-select-mouse (ev)
16799 "Return to `org-read-date' with the date currently selected.
16800 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16801 (interactive "e")
16802 (mouse-set-point ev)
16803 (when (calendar-cursor-to-date)
16804 (let* ((date (calendar-cursor-to-date))
16805 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16806 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16807 (if (active-minibuffer-window) (exit-minibuffer))))
16809 (defun org-check-deadlines (ndays)
16810 "Check if there are any deadlines due or past due.
16811 A deadline is considered due if it happens within `org-deadline-warning-days'
16812 days from today's date. If the deadline appears in an entry marked DONE,
16813 it is not shown. The prefix arg NDAYS can be used to test that many
16814 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16815 (interactive "P")
16816 (let* ((org-warn-days
16817 (cond
16818 ((equal ndays '(4)) 100000)
16819 (ndays (prefix-numeric-value ndays))
16820 (t (abs org-deadline-warning-days))))
16821 (case-fold-search nil)
16822 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16823 (callback
16824 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16826 (message "%d deadlines past-due or due within %d days"
16827 (org-occur regexp nil callback)
16828 org-warn-days)))
16830 (defsubst org-re-timestamp (type)
16831 "Return a regexp for timestamp TYPE.
16832 Allowed values for TYPE are:
16834 all: all timestamps
16835 active: only active timestamps (<...>)
16836 inactive: only inactive timestamps ([...])
16837 scheduled: only scheduled timestamps
16838 deadline: only deadline timestamps
16839 closed: only closed time-stamps
16841 When TYPE is nil, fall back on returning a regexp that matches
16842 both scheduled and deadline timestamps."
16843 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16844 ((eq type 'active) org-ts-regexp)
16845 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16846 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16847 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16848 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16849 ((eq type 'scheduled-or-deadline)
16850 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16852 (defun org-check-before-date (date)
16853 "Check if there are deadlines or scheduled entries before DATE."
16854 (interactive (list (org-read-date)))
16855 (let ((case-fold-search nil)
16856 (regexp (org-re-timestamp org-ts-type))
16857 (callback
16858 (lambda () (time-less-p
16859 (org-time-string-to-time (match-string 1))
16860 (org-time-string-to-time date)))))
16861 (message "%d entries before %s"
16862 (org-occur regexp nil callback) date)))
16864 (defun org-check-after-date (date)
16865 "Check if there are deadlines or scheduled entries after DATE."
16866 (interactive (list (org-read-date)))
16867 (let ((case-fold-search nil)
16868 (regexp (org-re-timestamp org-ts-type))
16869 (callback
16870 (lambda () (not
16871 (time-less-p
16872 (org-time-string-to-time (match-string 1))
16873 (org-time-string-to-time date))))))
16874 (message "%d entries after %s"
16875 (org-occur regexp nil callback) date)))
16877 (defun org-check-dates-range (start-date end-date)
16878 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16879 (interactive (list (org-read-date nil nil nil "Range starts")
16880 (org-read-date nil nil nil "Range end")))
16881 (let ((case-fold-search nil)
16882 (regexp (org-re-timestamp org-ts-type))
16883 (callback
16884 (lambda ()
16885 (let ((match (match-string 1)))
16886 (and
16887 (not (time-less-p
16888 (org-time-string-to-time match)
16889 (org-time-string-to-time start-date)))
16890 (time-less-p
16891 (org-time-string-to-time match)
16892 (org-time-string-to-time end-date)))))))
16893 (message "%d entries between %s and %s"
16894 (org-occur regexp nil callback) start-date end-date)))
16896 (defun org-evaluate-time-range (&optional to-buffer)
16897 "Evaluate a time range by computing the difference between start and end.
16898 Normally the result is just printed in the echo area, but with prefix arg
16899 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16900 If the time range is actually in a table, the result is inserted into the
16901 next column.
16902 For time difference computation, a year is assumed to be exactly 365
16903 days in order to avoid rounding problems."
16904 (interactive "P")
16906 (org-clock-update-time-maybe)
16907 (save-excursion
16908 (unless (org-at-date-range-p t)
16909 (goto-char (point-at-bol))
16910 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16911 (if (not (org-at-date-range-p t))
16912 (user-error "Not at a time-stamp range, and none found in current line")))
16913 (let* ((ts1 (match-string 1))
16914 (ts2 (match-string 2))
16915 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16916 (match-end (match-end 0))
16917 (time1 (org-time-string-to-time ts1))
16918 (time2 (org-time-string-to-time ts2))
16919 (t1 (org-float-time time1))
16920 (t2 (org-float-time time2))
16921 (diff (abs (- t2 t1)))
16922 (negative (< (- t2 t1) 0))
16923 ;; (ys (floor (* 365 24 60 60)))
16924 (ds (* 24 60 60))
16925 (hs (* 60 60))
16926 (fy "%dy %dd %02d:%02d")
16927 (fy1 "%dy %dd")
16928 (fd "%dd %02d:%02d")
16929 (fd1 "%dd")
16930 (fh "%02d:%02d")
16931 y d h m align)
16932 (if havetime
16933 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16935 d (floor (/ diff ds)) diff (mod diff ds)
16936 h (floor (/ diff hs)) diff (mod diff hs)
16937 m (floor (/ diff 60)))
16938 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16940 d (floor (+ (/ diff ds) 0.5))
16941 h 0 m 0))
16942 (if (not to-buffer)
16943 (message "%s" (org-make-tdiff-string y d h m))
16944 (if (org-at-table-p)
16945 (progn
16946 (goto-char match-end)
16947 (setq align t)
16948 (and (looking-at " *|") (goto-char (match-end 0))))
16949 (goto-char match-end))
16950 (if (looking-at
16951 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16952 (replace-match ""))
16953 (if negative (insert " -"))
16954 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16955 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16956 (insert " " (format fh h m))))
16957 (if align (org-table-align))
16958 (message "Time difference inserted")))))
16960 (defun org-make-tdiff-string (y d h m)
16961 (let ((fmt "")
16962 (l nil))
16963 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16964 l (push y l)))
16965 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16966 l (push d l)))
16967 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16968 l (push h l)))
16969 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16970 l (push m l)))
16971 (apply 'format fmt (nreverse l))))
16973 (defun org-time-string-to-time (s &optional buffer pos)
16974 "Convert a timestamp string into internal time."
16975 (condition-case errdata
16976 (apply 'encode-time (org-parse-time-string s))
16977 (error (error "Bad timestamp `%s'%s\nError was: %s"
16978 s (if (not (and buffer pos))
16980 (format " at %d in buffer `%s'" pos buffer))
16981 (cdr errdata)))))
16983 (defun org-time-string-to-seconds (s)
16984 "Convert a timestamp string to a number of seconds."
16985 (org-float-time (org-time-string-to-time s)))
16987 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16988 "Convert a time stamp to an absolute day number.
16989 If there is a specifier for a cyclic time stamp, get the closest
16990 date to DAYNR.
16991 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16992 The variable `date' is bound by the calendar when this is called."
16993 (cond
16994 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16995 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16996 daynr
16997 (+ daynr 1000)))
16998 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16999 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17000 (time-to-days (current-time))) (match-string 0 s)
17001 prefer show-all))
17002 (t (time-to-days
17003 (condition-case errdata
17004 (apply 'encode-time (org-parse-time-string s))
17005 (error (error "Bad timestamp `%s'%s\nError was: %s"
17006 s (if (not (and buffer pos))
17008 (format " at %d in buffer `%s'" pos buffer))
17009 (cdr errdata))))))))
17011 (defun org-days-to-iso-week (days)
17012 "Return the iso week number."
17013 (require 'cal-iso)
17014 (car (calendar-iso-from-absolute days)))
17016 (defun org-small-year-to-year (year)
17017 "Convert 2-digit years into 4-digit years.
17018 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17019 The year 2000 cannot be abbreviated. Any year larger than 99
17020 is returned unchanged."
17021 (if (< year 38)
17022 (setq year (+ 2000 year))
17023 (if (< year 100)
17024 (setq year (+ 1900 year))))
17025 year)
17027 (defun org-time-from-absolute (d)
17028 "Return the time corresponding to date D.
17029 D may be an absolute day number, or a calendar-type list (month day year)."
17030 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17031 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17033 (defun org-calendar-holiday ()
17034 "List of holidays, for Diary display in Org-mode."
17035 (require 'holidays)
17036 (let ((hl (funcall
17037 (if (fboundp 'calendar-check-holidays)
17038 'calendar-check-holidays 'check-calendar-holidays) date)))
17039 (if hl (mapconcat 'identity hl "; "))))
17041 (defun org-diary-sexp-entry (sexp entry date)
17042 "Process a SEXP diary ENTRY for DATE."
17043 (require 'diary-lib)
17044 (let ((result (if calendar-debug-sexp
17045 (let ((stack-trace-on-error t))
17046 (eval (car (read-from-string sexp))))
17047 (condition-case nil
17048 (eval (car (read-from-string sexp)))
17049 (error
17050 (beep)
17051 (message "Bad sexp at line %d in %s: %s"
17052 (org-current-line)
17053 (buffer-file-name) sexp)
17054 (sleep-for 2))))))
17055 (cond ((stringp result) (split-string result "; "))
17056 ((and (consp result)
17057 (not (consp (cdr result)))
17058 (stringp (cdr result))) (cdr result))
17059 ((and (consp result)
17060 (stringp (car result))) result)
17061 (result entry))))
17063 (defun org-diary-to-ical-string (frombuf)
17064 "Get iCalendar entries from diary entries in buffer FROMBUF.
17065 This uses the icalendar.el library."
17066 (let* ((tmpdir (if (featurep 'xemacs)
17067 (temp-directory)
17068 temporary-file-directory))
17069 (tmpfile (make-temp-name
17070 (expand-file-name "orgics" tmpdir)))
17071 buf rtn b e)
17072 (with-current-buffer frombuf
17073 (icalendar-export-region (point-min) (point-max) tmpfile)
17074 (setq buf (find-buffer-visiting tmpfile))
17075 (set-buffer buf)
17076 (goto-char (point-min))
17077 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17078 (setq b (match-beginning 0)))
17079 (goto-char (point-max))
17080 (if (re-search-backward "^END:VEVENT" nil t)
17081 (setq e (match-end 0)))
17082 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17083 (kill-buffer buf)
17084 (delete-file tmpfile)
17085 rtn))
17087 (defun org-closest-date (start current change prefer show-all)
17088 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17089 When PREFER is `past', return a date that is either CURRENT or past.
17090 When PREFER is `future', return a date that is either CURRENT or future.
17091 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17092 ;; Make the proper lists from the dates
17093 (catch 'exit
17094 (let ((a1 '(("h" . hour)
17095 ("d" . day)
17096 ("w" . week)
17097 ("m" . month)
17098 ("y" . year)))
17099 (shour (nth 2 (org-parse-time-string start)))
17100 dn dw sday cday n1 n2 n0
17101 d m y y1 y2 date1 date2 nmonths nm ny m2)
17103 (setq start (org-date-to-gregorian start)
17104 current (org-date-to-gregorian
17105 (if show-all
17106 current
17107 (time-to-days (current-time))))
17108 sday (calendar-absolute-from-gregorian start)
17109 cday (calendar-absolute-from-gregorian current))
17111 (if (<= cday sday) (throw 'exit sday))
17113 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17114 (setq dn (string-to-number (match-string 1 change))
17115 dw (cdr (assoc (match-string 2 change) a1)))
17116 (user-error "Invalid change specifier: %s" change))
17117 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17118 (cond
17119 ((eq dw 'hour)
17120 (let ((missing-hours
17121 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17122 dn)))
17123 (setq n1 (if (zerop missing-hours) cday
17124 (- cday (1+ (floor (/ missing-hours 24)))))
17125 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17126 ((eq dw 'day)
17127 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17128 n2 (+ n1 dn)))
17129 ((eq dw 'year)
17130 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17131 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17132 (setq date1 (list m d y1)
17133 n1 (calendar-absolute-from-gregorian date1)
17134 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17135 n2 (calendar-absolute-from-gregorian date2)))
17136 ((eq dw 'month)
17137 ;; approx number of month between the two dates
17138 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17139 ;; How often does dn fit in there?
17140 (setq d (nth 1 start) m (car start) y (nth 2 start)
17141 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17142 m (+ m nm)
17143 ny (floor (/ m 12))
17144 y (+ y ny)
17145 m (- m (* ny 12)))
17146 (while (> m 12) (setq m (- m 12) y (1+ y)))
17147 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17148 (setq m2 (+ m dn) y2 y)
17149 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17150 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17151 (while (<= n2 cday)
17152 (setq n1 n2 m m2 y y2)
17153 (setq m2 (+ m dn) y2 y)
17154 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17155 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17156 ;; Make sure n1 is the earlier date
17157 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17158 (if show-all
17159 (cond
17160 ((eq prefer 'past) (if (= cday n2) n2 n1))
17161 ((eq prefer 'future) (if (= cday n1) n1 n2))
17162 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17163 (cond
17164 ((eq prefer 'past) (if (= cday n2) n2 n1))
17165 ((eq prefer 'future) (if (= cday n1) n1 n2))
17166 (t (if (= cday n1) n1 n2)))))))
17168 (defun org-date-to-gregorian (date)
17169 "Turn any specification of DATE into a Gregorian date for the calendar."
17170 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17171 ((and (listp date) (= (length date) 3)) date)
17172 ((stringp date)
17173 (setq date (org-parse-time-string date))
17174 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17175 ((listp date)
17176 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17178 (defun org-parse-time-string (s &optional nodefault)
17179 "Parse the standard Org-mode time string.
17180 This should be a lot faster than the normal `parse-time-string'.
17181 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17182 hour and minute fields will be nil if not given."
17183 (cond ((string-match org-ts-regexp0 s)
17184 (list 0
17185 (if (or (match-beginning 8) (not nodefault))
17186 (string-to-number (or (match-string 8 s) "0")))
17187 (if (or (match-beginning 7) (not nodefault))
17188 (string-to-number (or (match-string 7 s) "0")))
17189 (string-to-number (match-string 4 s))
17190 (string-to-number (match-string 3 s))
17191 (string-to-number (match-string 2 s))
17192 nil nil nil))
17193 ((string-match "^<[^>]+>$" s)
17194 (decode-time (seconds-to-time (org-matcher-time s))))
17195 (t (error "Not a standard Org-mode time string: %s" s))))
17197 (defun org-timestamp-up (&optional arg)
17198 "Increase the date item at the cursor by one.
17199 If the cursor is on the year, change the year. If it is on the month,
17200 the day or the time, change that.
17201 With prefix ARG, change by that many units."
17202 (interactive "p")
17203 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17205 (defun org-timestamp-down (&optional arg)
17206 "Decrease the date item at the cursor by one.
17207 If the cursor is on the year, change the year. If it is on the month,
17208 the day or the time, change that.
17209 With prefix ARG, change by that many units."
17210 (interactive "p")
17211 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17213 (defun org-timestamp-up-day (&optional arg)
17214 "Increase the date in the time stamp by one day.
17215 With prefix ARG, change that many days."
17216 (interactive "p")
17217 (if (and (not (org-at-timestamp-p t))
17218 (org-at-heading-p))
17219 (org-todo 'up)
17220 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17222 (defun org-timestamp-down-day (&optional arg)
17223 "Decrease the date in the time stamp by one day.
17224 With prefix ARG, change that many days."
17225 (interactive "p")
17226 (if (and (not (org-at-timestamp-p t))
17227 (org-at-heading-p))
17228 (org-todo 'down)
17229 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17231 (defun org-at-timestamp-p (&optional inactive-ok)
17232 "Determine if the cursor is in or at a timestamp."
17233 (interactive)
17234 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17235 (pos (point))
17236 (ans (or (looking-at tsr)
17237 (save-excursion
17238 (skip-chars-backward "^[<\n\r\t")
17239 (if (> (point) (point-min)) (backward-char 1))
17240 (and (looking-at tsr)
17241 (> (- (match-end 0) pos) -1))))))
17242 (and ans
17243 (boundp 'org-ts-what)
17244 (setq org-ts-what
17245 (cond
17246 ((= pos (match-beginning 0)) 'bracket)
17247 ;; Point is considered to be "on the bracket" whether
17248 ;; it's really on it or right after it.
17249 ((= pos (1- (match-end 0))) 'bracket)
17250 ((= pos (match-end 0)) 'after)
17251 ((org-pos-in-match-range pos 2) 'year)
17252 ((org-pos-in-match-range pos 3) 'month)
17253 ((org-pos-in-match-range pos 7) 'hour)
17254 ((org-pos-in-match-range pos 8) 'minute)
17255 ((or (org-pos-in-match-range pos 4)
17256 (org-pos-in-match-range pos 5)) 'day)
17257 ((and (> pos (or (match-end 8) (match-end 5)))
17258 (< pos (match-end 0)))
17259 (- pos (or (match-end 8) (match-end 5))))
17260 (t 'day))))
17261 ans))
17263 (defun org-toggle-timestamp-type ()
17264 "Toggle the type (<active> or [inactive]) of a time stamp."
17265 (interactive)
17266 (when (org-at-timestamp-p t)
17267 (let ((beg (match-beginning 0)) (end (match-end 0))
17268 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17269 (save-excursion
17270 (goto-char beg)
17271 (while (re-search-forward "[][<>]" end t)
17272 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17273 t t)))
17274 (message "Timestamp is now %sactive"
17275 (if (equal (char-after beg) ?<) "" "in")))))
17277 (defun org-at-clock-log-p nil
17278 "Is the cursor on the clock log line?"
17279 (save-excursion
17280 (move-beginning-of-line 1)
17281 (looking-at "^[ \t]*CLOCK:")))
17283 (defvar org-clock-history) ; defined in org-clock.el
17284 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17285 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17286 "Change the date in the time stamp at point.
17287 The date will be changed by N times WHAT. WHAT can be `day', `month',
17288 `year', `minute', `second'. If WHAT is not given, the cursor position
17289 in the timestamp determines what will be changed.
17290 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17291 (let ((origin (point)) origin-cat
17292 with-hm inactive
17293 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17294 org-ts-what
17295 extra rem
17296 ts time time0 fixnext clrgx)
17297 (if (not (org-at-timestamp-p t))
17298 (user-error "Not at a timestamp"))
17299 (if (and (not what) (eq org-ts-what 'bracket))
17300 (org-toggle-timestamp-type)
17301 ;; Point isn't on brackets. Remember the part of the time-stamp
17302 ;; the point was in. Indeed, size of time-stamps may change,
17303 ;; but point must be kept in the same category nonetheless.
17304 (setq origin-cat org-ts-what)
17305 (if (and (not what) (not (eq org-ts-what 'day))
17306 org-display-custom-times
17307 (get-text-property (point) 'display)
17308 (not (get-text-property (1- (point)) 'display)))
17309 (setq org-ts-what 'day))
17310 (setq org-ts-what (or what org-ts-what)
17311 inactive (= (char-after (match-beginning 0)) ?\[)
17312 ts (match-string 0))
17313 (replace-match "")
17314 (when (string-match
17315 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17317 (setq extra (match-string 1 ts))
17318 (if suppress-tmp-delay
17319 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17320 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17321 (setq with-hm t))
17322 (setq time0 (org-parse-time-string ts))
17323 (when (and updown
17324 (eq org-ts-what 'minute)
17325 (not current-prefix-arg))
17326 ;; This looks like s-up and s-down. Change by one rounding step.
17327 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17328 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17329 (setcar (cdr time0) (+ (nth 1 time0)
17330 (if (> n 0) (- rem) (- dm rem))))))
17331 (setq time
17332 (encode-time (or (car time0) 0)
17333 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17334 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17335 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17336 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17337 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17338 (nthcdr 6 time0)))
17339 (when (and (member org-ts-what '(hour minute))
17340 extra
17341 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17342 (setq extra (org-modify-ts-extra
17343 extra
17344 (if (eq org-ts-what 'hour) 2 5)
17345 n dm)))
17346 (when (integerp org-ts-what)
17347 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17348 (if (eq what 'calendar)
17349 (let ((cal-date (org-get-date-from-calendar)))
17350 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17351 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17352 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17353 (setcar time0 (or (car time0) 0))
17354 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17355 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17356 (setq time (apply 'encode-time time0))))
17357 ;; Insert the new time-stamp, and ensure point stays in the same
17358 ;; category as before (i.e. not after the last position in that
17359 ;; category).
17360 (let ((pos (point)))
17361 ;; Stay before inserted string. `save-excursion' is of no use.
17362 (setq org-last-changed-timestamp
17363 (org-insert-time-stamp time with-hm inactive nil nil extra))
17364 (goto-char pos))
17365 (save-match-data
17366 (looking-at org-ts-regexp3)
17367 (goto-char (cond
17368 ;; `day' category ends before `hour' if any, or at
17369 ;; the end of the day name.
17370 ((eq origin-cat 'day)
17371 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17372 ((eq origin-cat 'hour) (min (match-end 7) origin))
17373 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17374 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17375 ;; `year' and `month' have both fixed size: point
17376 ;; couldn't have moved into another part.
17377 (t origin))))
17378 ;; Update clock if on a CLOCK line.
17379 (org-clock-update-time-maybe)
17380 ;; Maybe adjust the closest clock in `org-clock-history'
17381 (when org-clock-adjust-closest
17382 (if (not (and (org-at-clock-log-p)
17383 (< 1 (length (delq nil (mapcar 'marker-position
17384 org-clock-history))))))
17385 (message "No clock to adjust")
17386 (cond ((save-excursion ; fix previous clock?
17387 (re-search-backward org-ts-regexp0 nil t)
17388 (org-looking-back (concat org-clock-string " \\[")))
17389 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17390 ((save-excursion ; fix next clock?
17391 (re-search-backward org-ts-regexp0 nil t)
17392 (looking-at (concat org-ts-regexp0 "\\] =>")))
17393 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17394 (save-window-excursion
17395 ;; Find closest clock to point, adjust the previous/next one in history
17396 (let* ((p (save-excursion (org-back-to-heading t)))
17397 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17398 (clfixnth
17399 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17400 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17401 (if (not clfixpos)
17402 (message "No clock to adjust")
17403 (save-excursion
17404 (org-goto-marker-or-bmk clfixpos)
17405 (org-show-subtree)
17406 (when (re-search-forward clrgx nil t)
17407 (goto-char (match-beginning 1))
17408 (let (org-clock-adjust-closest)
17409 (org-timestamp-change n org-ts-what updown))
17410 (message "Clock adjusted in %s for heading: %s"
17411 (file-name-nondirectory (buffer-file-name))
17412 (org-get-heading t t)))))))))
17413 ;; Try to recenter the calendar window, if any.
17414 (if (and org-calendar-follow-timestamp-change
17415 (get-buffer-window "*Calendar*" t)
17416 (memq org-ts-what '(day month year)))
17417 (org-recenter-calendar (time-to-days time))))))
17419 (defun org-modify-ts-extra (s pos n dm)
17420 "Change the different parts of the lead-time and repeat fields in timestamp."
17421 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17422 ng h m new rem)
17423 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17424 (cond
17425 ((or (org-pos-in-match-range pos 2)
17426 (org-pos-in-match-range pos 3))
17427 (setq m (string-to-number (match-string 3 s))
17428 h (string-to-number (match-string 2 s)))
17429 (if (org-pos-in-match-range pos 2)
17430 (setq h (+ h n))
17431 (setq n (* dm (org-no-warnings (signum n))))
17432 (when (not (= 0 (setq rem (% m dm))))
17433 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17434 (setq m (+ m n)))
17435 (if (< m 0) (setq m (+ m 60) h (1- h)))
17436 (if (> m 59) (setq m (- m 60) h (1+ h)))
17437 (setq h (min 24 (max 0 h)))
17438 (setq ng 1 new (format "-%02d:%02d" h m)))
17439 ((org-pos-in-match-range pos 6)
17440 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17441 ((org-pos-in-match-range pos 5)
17442 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17444 ((org-pos-in-match-range pos 9)
17445 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17446 ((org-pos-in-match-range pos 8)
17447 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17449 (when ng
17450 (setq s (concat
17451 (substring s 0 (match-beginning ng))
17453 (substring s (match-end ng))))))
17456 (defun org-recenter-calendar (date)
17457 "If the calendar is visible, recenter it to DATE."
17458 (let ((cwin (get-buffer-window "*Calendar*" t)))
17459 (when cwin
17460 (let ((calendar-move-hook nil))
17461 (with-selected-window cwin
17462 (calendar-goto-date (if (listp date) date
17463 (calendar-gregorian-from-absolute date))))))))
17465 (defun org-goto-calendar (&optional arg)
17466 "Go to the Emacs calendar at the current date.
17467 If there is a time stamp in the current line, go to that date.
17468 A prefix ARG can be used to force the current date."
17469 (interactive "P")
17470 (let ((tsr org-ts-regexp) diff
17471 (calendar-move-hook nil)
17472 (calendar-view-holidays-initially-flag nil)
17473 (calendar-view-diary-initially-flag nil))
17474 (if (or (org-at-timestamp-p)
17475 (save-excursion
17476 (beginning-of-line 1)
17477 (looking-at (concat ".*" tsr))))
17478 (let ((d1 (time-to-days (current-time)))
17479 (d2 (time-to-days
17480 (org-time-string-to-time (match-string 1)))))
17481 (setq diff (- d2 d1))))
17482 (calendar)
17483 (calendar-goto-today)
17484 (if (and diff (not arg)) (calendar-forward-day diff))))
17486 (defun org-get-date-from-calendar ()
17487 "Return a list (month day year) of date at point in calendar."
17488 (with-current-buffer "*Calendar*"
17489 (save-match-data
17490 (calendar-cursor-to-date))))
17492 (defun org-date-from-calendar ()
17493 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17494 If there is already a time stamp at the cursor position, update it."
17495 (interactive)
17496 (if (org-at-timestamp-p t)
17497 (org-timestamp-change 0 'calendar)
17498 (let ((cal-date (org-get-date-from-calendar)))
17499 (org-insert-time-stamp
17500 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17502 (defcustom org-effort-durations
17503 `(("h" . 60)
17504 ("d" . ,(* 60 8))
17505 ("w" . ,(* 60 8 5))
17506 ("m" . ,(* 60 8 5 4))
17507 ("y" . ,(* 60 8 5 40)))
17508 "Conversion factor to minutes for an effort modifier.
17510 Each entry has the form (MODIFIER . MINUTES).
17512 In an effort string, a number followed by MODIFIER is multiplied
17513 by the specified number of MINUTES to obtain an effort in
17514 minutes.
17516 For example, if the value of this variable is ((\"hours\" . 60)), then an
17517 effort string \"2hours\" is equivalent to 120 minutes."
17518 :group 'org-agenda
17519 :version "24.1"
17520 :type '(alist :key-type (string :tag "Modifier")
17521 :value-type (number :tag "Minutes")))
17523 (defun org-minutes-to-clocksum-string (m)
17524 "Format number of minutes as a clocksum string.
17525 The format is determined by `org-time-clocksum-format',
17526 `org-time-clocksum-use-fractional' and
17527 `org-time-clocksum-fractional-format' and
17528 `org-time-clocksum-use-effort-durations'."
17529 (let ((clocksum "")
17530 (m (round m)) ; Don't allow fractions of minutes
17531 h d w mo y fmt n)
17532 (setq h (if org-time-clocksum-use-effort-durations
17533 (cdr (assoc "h" org-effort-durations)) 60)
17534 d (if org-time-clocksum-use-effort-durations
17535 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17536 w (if org-time-clocksum-use-effort-durations
17537 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17538 mo (if org-time-clocksum-use-effort-durations
17539 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17540 y (if org-time-clocksum-use-effort-durations
17541 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17542 ;; fractional format
17543 (if org-time-clocksum-use-fractional
17544 (cond
17545 ;; single format string
17546 ((stringp org-time-clocksum-fractional-format)
17547 (format org-time-clocksum-fractional-format (/ m (float h))))
17548 ;; choice of fractional formats for different time units
17549 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17550 (> (/ (truncate m) (* y d h)) 0))
17551 (format fmt (/ m (* y d (float h)))))
17552 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17553 (> (/ (truncate m) (* mo d h)) 0))
17554 (format fmt (/ m (* mo d (float h)))))
17555 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17556 (> (/ (truncate m) (* w d h)) 0))
17557 (format fmt (/ m (* w d (float h)))))
17558 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17559 (> (/ (truncate m) (* d h)) 0))
17560 (format fmt (/ m (* d (float h)))))
17561 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17562 (> (/ (truncate m) h) 0))
17563 (format fmt (/ m (float h))))
17564 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17565 (format fmt m))
17566 ;; fall back to smallest time unit with a format
17567 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17568 (format fmt (/ m (float h))))
17569 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17570 (format fmt (/ m (* d (float h)))))
17571 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17572 (format fmt (/ m (* w d (float h)))))
17573 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17574 (format fmt (/ m (* mo d (float h)))))
17575 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17576 (format fmt (/ m (* y d (float h))))))
17577 ;; standard (non-fractional) format, with single format string
17578 (if (stringp org-time-clocksum-format)
17579 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17580 ;; separate formats components
17581 (and (setq fmt (plist-get org-time-clocksum-format :years))
17582 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17583 (plist-get org-time-clocksum-format :require-years))
17584 (setq clocksum (concat clocksum (format fmt n))
17585 m (- m (* n y d h))))
17586 (and (setq fmt (plist-get org-time-clocksum-format :months))
17587 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17588 (plist-get org-time-clocksum-format :require-months))
17589 (setq clocksum (concat clocksum (format fmt n))
17590 m (- m (* n mo d h))))
17591 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17592 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17593 (plist-get org-time-clocksum-format :require-weeks))
17594 (setq clocksum (concat clocksum (format fmt n))
17595 m (- m (* n w d h))))
17596 (and (setq fmt (plist-get org-time-clocksum-format :days))
17597 (or (> (setq n (/ (truncate m) (* d h))) 0)
17598 (plist-get org-time-clocksum-format :require-days))
17599 (setq clocksum (concat clocksum (format fmt n))
17600 m (- m (* n d h))))
17601 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17602 (or (> (setq n (/ (truncate m) h)) 0)
17603 (plist-get org-time-clocksum-format :require-hours))
17604 (setq clocksum (concat clocksum (format fmt n))
17605 m (- m (* n h))))
17606 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17607 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17608 (setq clocksum (concat clocksum (format fmt m))))
17609 ;; return formatted time duration
17610 clocksum))))
17612 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17613 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17614 "Org mode version 8.0")
17616 (defun org-hours-to-clocksum-string (n)
17617 (org-minutes-to-clocksum-string (* n 60)))
17619 (defun org-hh:mm-string-to-minutes (s)
17620 "Convert a string H:MM to a number of minutes.
17621 If the string is just a number, interpret it as minutes.
17622 In fact, the first hh:mm or number in the string will be taken,
17623 there can be extra stuff in the string.
17624 If no number is found, the return value is 0."
17625 (cond
17626 ((integerp s) s)
17627 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17628 (+ (* (string-to-number (match-string 1 s)) 60)
17629 (string-to-number (match-string 2 s))))
17630 ((string-match "\\([0-9]+\\)" s)
17631 (string-to-number (match-string 1 s)))
17632 (t 0)))
17634 (defcustom org-image-actual-width t
17635 "Should we use the actual width of images when inlining them?
17637 When set to `t', always use the image width.
17639 When set to a number, use imagemagick (when available) to set
17640 the image's width to this value.
17642 When set to a number in a list, try to get the width from any
17643 #+ATTR.* keyword if it matches a width specification like
17645 #+ATTR_HTML: :width 300px
17647 and fall back on that number if none is found.
17649 When set to nil, try to get the width from an #+ATTR.* keyword
17650 and fall back on the original width if none is found.
17652 This requires Emacs >= 24.1, build with imagemagick support."
17653 :group 'org-appearance
17654 :version "24.4"
17655 :package-version '(Org . "8.0")
17656 :type '(choice
17657 (const :tag "Use the image width" t)
17658 (integer :tag "Use a number of pixels")
17659 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17660 (const :tag "Use #+ATTR* or don't resize" nil)))
17662 (defcustom org-agenda-inhibit-startup nil
17663 "Inhibit startup when preparing agenda buffers.
17664 When this variable is `t' (the default), the initialization of
17665 the Org agenda buffers is inhibited: e.g. the visibility state
17666 is not set, the tables are not re-aligned, etc."
17667 :type 'boolean
17668 :version "24.3"
17669 :group 'org-agenda)
17671 (defun org-duration-string-to-minutes (s &optional output-to-string)
17672 "Convert a duration string S to minutes.
17674 A bare number is interpreted as minutes, modifiers can be set by
17675 customizing `org-effort-durations' (which see).
17677 Entries containing a colon are interpreted as H:MM by
17678 `org-hh:mm-string-to-minutes'."
17679 (let ((result 0)
17680 (re (concat "\\([0-9.]+\\) *\\("
17681 (regexp-opt (mapcar 'car org-effort-durations))
17682 "\\)")))
17683 (while (string-match re s)
17684 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17685 (string-to-number (match-string 1 s))))
17686 (setq s (replace-match "" nil t s)))
17687 (setq result (floor result))
17688 (incf result (org-hh:mm-string-to-minutes s))
17689 (if output-to-string (number-to-string result) result)))
17691 ;;;; Files
17693 (defun org-save-all-org-buffers ()
17694 "Save all Org-mode buffers without user confirmation."
17695 (interactive)
17696 (message "Saving all Org-mode buffers...")
17697 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17698 (when (featurep 'org-id) (org-id-locations-save))
17699 (message "Saving all Org-mode buffers... done"))
17701 (defun org-revert-all-org-buffers ()
17702 "Revert all Org-mode buffers.
17703 Prompt for confirmation when there are unsaved changes.
17704 Be sure you know what you are doing before letting this function
17705 overwrite your changes.
17707 This function is useful in a setup where one tracks org files
17708 with a version control system, to revert on one machine after pulling
17709 changes from another. I believe the procedure must be like this:
17711 1. M-x org-save-all-org-buffers
17712 2. Pull changes from the other machine, resolve conflicts
17713 3. M-x org-revert-all-org-buffers"
17714 (interactive)
17715 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17716 (user-error "Abort"))
17717 (save-excursion
17718 (save-window-excursion
17719 (mapc
17720 (lambda (b)
17721 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17722 (with-current-buffer b buffer-file-name))
17723 (org-pop-to-buffer-same-window b)
17724 (revert-buffer t 'no-confirm)))
17725 (buffer-list))
17726 (when (and (featurep 'org-id) org-id-track-globally)
17727 (org-id-locations-load)))))
17729 ;;;; Agenda files
17731 ;;;###autoload
17732 (defun org-switchb (&optional arg)
17733 "Switch between Org buffers.
17734 With one prefix argument, restrict available buffers to files.
17735 With two prefix arguments, restrict available buffers to agenda files.
17737 Defaults to `iswitchb' for buffer name completion.
17738 Set `org-completion-use-ido' to make it use ido instead."
17739 (interactive "P")
17740 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17741 ((equal arg '(16)) (org-buffer-list 'agenda))
17742 (t (org-buffer-list))))
17743 (org-completion-use-iswitchb org-completion-use-iswitchb)
17744 (org-completion-use-ido org-completion-use-ido))
17745 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17746 (setq org-completion-use-iswitchb t))
17747 (org-pop-to-buffer-same-window
17748 (org-icompleting-read "Org buffer: "
17749 (mapcar 'list (mapcar 'buffer-name blist))
17750 nil t))))
17752 ;;; Define some older names previously used for this functionality
17753 ;;;###autoload
17754 (defalias 'org-ido-switchb 'org-switchb)
17755 ;;;###autoload
17756 (defalias 'org-iswitchb 'org-switchb)
17758 (defun org-buffer-list (&optional predicate exclude-tmp)
17759 "Return a list of Org buffers.
17760 PREDICATE can be `export', `files' or `agenda'.
17762 export restrict the list to Export buffers.
17763 files restrict the list to buffers visiting Org files.
17764 agenda restrict the list to buffers visiting agenda files.
17766 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17767 (let* ((bfn nil)
17768 (agenda-files (and (eq predicate 'agenda)
17769 (mapcar 'file-truename (org-agenda-files t))))
17770 (filter
17771 (cond
17772 ((eq predicate 'files)
17773 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17774 ((eq predicate 'export)
17775 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17776 ((eq predicate 'agenda)
17777 (lambda (b)
17778 (with-current-buffer b
17779 (and (derived-mode-p 'org-mode)
17780 (setq bfn (buffer-file-name b))
17781 (member (file-truename bfn) agenda-files)))))
17782 (t (lambda (b) (with-current-buffer b
17783 (or (derived-mode-p 'org-mode)
17784 (string-match "\*Org .*Export"
17785 (buffer-name b)))))))))
17786 (delq nil
17787 (mapcar
17788 (lambda(b)
17789 (if (and (funcall filter b)
17790 (or (not exclude-tmp)
17791 (not (string-match "tmp" (buffer-name b)))))
17793 nil))
17794 (buffer-list)))))
17796 (defun org-agenda-files (&optional unrestricted archives)
17797 "Get the list of agenda files.
17798 Optional UNRESTRICTED means return the full list even if a restriction
17799 is currently in place.
17800 When ARCHIVES is t, include all archive files that are really being
17801 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17802 `org-agenda-archives-mode' is t."
17803 (let ((files
17804 (cond
17805 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17806 ((stringp org-agenda-files) (org-read-agenda-file-list))
17807 ((listp org-agenda-files) org-agenda-files)
17808 (t (error "Invalid value of `org-agenda-files'")))))
17809 (setq files (apply 'append
17810 (mapcar (lambda (f)
17811 (if (file-directory-p f)
17812 (directory-files
17813 f t org-agenda-file-regexp)
17814 (list f)))
17815 files)))
17816 (when org-agenda-skip-unavailable-files
17817 (setq files (delq nil
17818 (mapcar (function
17819 (lambda (file)
17820 (and (file-readable-p file) file)))
17821 files))))
17822 (when (or (eq archives t)
17823 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17824 (setq files (org-add-archive-files files)))
17825 files))
17827 (defun org-agenda-file-p (&optional file)
17828 "Return non-nil, if FILE is an agenda file.
17829 If FILE is omitted, use the file associated with the current
17830 buffer."
17831 (member (or file (buffer-file-name))
17832 (org-agenda-files t)))
17834 (defun org-edit-agenda-file-list ()
17835 "Edit the list of agenda files.
17836 Depending on setup, this either uses customize to edit the variable
17837 `org-agenda-files', or it visits the file that is holding the list. In the
17838 latter case, the buffer is set up in a way that saving it automatically kills
17839 the buffer and restores the previous window configuration."
17840 (interactive)
17841 (if (stringp org-agenda-files)
17842 (let ((cw (current-window-configuration)))
17843 (find-file org-agenda-files)
17844 (org-set-local 'org-window-configuration cw)
17845 (org-add-hook 'after-save-hook
17846 (lambda ()
17847 (set-window-configuration
17848 (prog1 org-window-configuration
17849 (kill-buffer (current-buffer))))
17850 (org-install-agenda-files-menu)
17851 (message "New agenda file list installed"))
17852 nil 'local)
17853 (message "%s" (substitute-command-keys
17854 "Edit list and finish with \\[save-buffer]")))
17855 (customize-variable 'org-agenda-files)))
17857 (defun org-store-new-agenda-file-list (list)
17858 "Set new value for the agenda file list and save it correctly."
17859 (if (stringp org-agenda-files)
17860 (let ((fe (org-read-agenda-file-list t)) b u)
17861 (while (setq b (find-buffer-visiting org-agenda-files))
17862 (kill-buffer b))
17863 (with-temp-file org-agenda-files
17864 (insert
17865 (mapconcat
17866 (lambda (f) ;; Keep un-expanded entries.
17867 (if (setq u (assoc f fe))
17868 (cdr u)
17870 list "\n")
17871 "\n")))
17872 (let ((org-mode-hook nil) (org-inhibit-startup t)
17873 (org-insert-mode-line-in-empty-file nil))
17874 (setq org-agenda-files list)
17875 (customize-save-variable 'org-agenda-files org-agenda-files))))
17877 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17878 "Read the list of agenda files from a file.
17879 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17880 filenames, used by `org-store-new-agenda-file-list' to write back
17881 un-expanded file names."
17882 (when (file-directory-p org-agenda-files)
17883 (error "`org-agenda-files' cannot be a single directory"))
17884 (when (stringp org-agenda-files)
17885 (with-temp-buffer
17886 (insert-file-contents org-agenda-files)
17887 (mapcar
17888 (lambda (f)
17889 (let ((e (expand-file-name (substitute-in-file-name f)
17890 org-directory)))
17891 (if pair-with-expansion
17892 (cons e f)
17893 e)))
17894 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17896 ;;;###autoload
17897 (defun org-cycle-agenda-files ()
17898 "Cycle through the files in `org-agenda-files'.
17899 If the current buffer visits an agenda file, find the next one in the list.
17900 If the current buffer does not, find the first agenda file."
17901 (interactive)
17902 (let* ((fs (org-agenda-files t))
17903 (files (append fs (list (car fs))))
17904 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17905 file)
17906 (unless files (user-error "No agenda files"))
17907 (catch 'exit
17908 (while (setq file (pop files))
17909 (if (equal (file-truename file) tcf)
17910 (when (car files)
17911 (find-file (car files))
17912 (throw 'exit t))))
17913 (find-file (car fs)))
17914 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17916 (defun org-agenda-file-to-front (&optional to-end)
17917 "Move/add the current file to the top of the agenda file list.
17918 If the file is not present in the list, it is added to the front. If it is
17919 present, it is moved there. With optional argument TO-END, add/move to the
17920 end of the list."
17921 (interactive "P")
17922 (let ((org-agenda-skip-unavailable-files nil)
17923 (file-alist (mapcar (lambda (x)
17924 (cons (file-truename x) x))
17925 (org-agenda-files t)))
17926 (ctf (file-truename
17927 (or buffer-file-name
17928 (user-error "Please save the current buffer to a file"))))
17929 x had)
17930 (setq x (assoc ctf file-alist) had x)
17932 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17933 (if to-end
17934 (setq file-alist (append (delq x file-alist) (list x)))
17935 (setq file-alist (cons x (delq x file-alist))))
17936 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17937 (org-install-agenda-files-menu)
17938 (message "File %s to %s of agenda file list"
17939 (if had "moved" "added") (if to-end "end" "front"))))
17941 (defun org-remove-file (&optional file)
17942 "Remove current file from the list of files in variable `org-agenda-files'.
17943 These are the files which are being checked for agenda entries.
17944 Optional argument FILE means use this file instead of the current."
17945 (interactive)
17946 (let* ((org-agenda-skip-unavailable-files nil)
17947 (file (or file buffer-file-name
17948 (user-error "Current buffer does not visit a file")))
17949 (true-file (file-truename file))
17950 (afile (abbreviate-file-name file))
17951 (files (delq nil (mapcar
17952 (lambda (x)
17953 (if (equal true-file
17954 (file-truename x))
17955 nil x))
17956 (org-agenda-files t)))))
17957 (if (not (= (length files) (length (org-agenda-files t))))
17958 (progn
17959 (org-store-new-agenda-file-list files)
17960 (org-install-agenda-files-menu)
17961 (message "Removed file: %s" afile))
17962 (message "File was not in list: %s (not removed)" afile))))
17964 (defun org-file-menu-entry (file)
17965 (vector file (list 'find-file file) t))
17967 (defun org-check-agenda-file (file)
17968 "Make sure FILE exists. If not, ask user what to do."
17969 (when (not (file-exists-p file))
17970 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17971 (abbreviate-file-name file))
17972 (let ((r (downcase (read-char-exclusive))))
17973 (cond
17974 ((equal r ?r)
17975 (org-remove-file file)
17976 (throw 'nextfile t))
17977 (t (error "Abort"))))))
17979 (defun org-get-agenda-file-buffer (file)
17980 "Get a buffer visiting FILE. If the buffer needs to be created, add
17981 it to the list of buffers which might be released later."
17982 (let ((buf (org-find-base-buffer-visiting file)))
17983 (if buf
17984 buf ; just return it
17985 ;; Make a new buffer and remember it
17986 (setq buf (find-file-noselect file))
17987 (if buf (push buf org-agenda-new-buffers))
17988 buf)))
17990 (defun org-release-buffers (blist)
17991 "Release all buffers in list, asking the user for confirmation when needed.
17992 When a buffer is unmodified, it is just killed. When modified, it is saved
17993 \(if the user agrees) and then killed."
17994 (let (buf file)
17995 (while (setq buf (pop blist))
17996 (setq file (buffer-file-name buf))
17997 (when (and (buffer-modified-p buf)
17998 file
17999 (y-or-n-p (format "Save file %s? " file)))
18000 (with-current-buffer buf (save-buffer)))
18001 (kill-buffer buf))))
18003 (defun org-agenda-prepare-buffers (files)
18004 "Create buffers for all agenda files, protect archived trees and comments."
18005 (interactive)
18006 (let ((pa '(:org-archived t))
18007 (pc '(:org-comment t))
18008 (pall '(:org-archived t :org-comment t))
18009 (inhibit-read-only t)
18010 (org-inhibit-startup org-agenda-inhibit-startup)
18011 (rea (concat ":" org-archive-tag ":"))
18012 file re)
18013 (setq org-tag-alist-for-agenda nil
18014 org-tag-groups-alist-for-agenda nil)
18015 (save-excursion
18016 (save-restriction
18017 (while (setq file (pop files))
18018 (catch 'nextfile
18019 (if (bufferp file)
18020 (set-buffer file)
18021 (org-check-agenda-file file)
18022 (set-buffer (org-get-agenda-file-buffer file)))
18023 (widen)
18024 (org-set-regexps-and-options-for-tags)
18025 (goto-char (point-min))
18026 (let ((case-fold-search t))
18027 (when (search-forward "#+setupfile" nil t)
18028 ;; Don't set all regexps and options systematically as
18029 ;; this is only run for setting agenda tags from setup
18030 ;; file
18031 (org-set-regexps-and-options)))
18032 (org-refresh-category-properties)
18033 (org-refresh-properties org-effort-property 'org-effort)
18034 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18035 (setq org-todo-keywords-for-agenda
18036 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18037 (setq org-done-keywords-for-agenda
18038 (append org-done-keywords-for-agenda org-done-keywords))
18039 (setq org-todo-keyword-alist-for-agenda
18040 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18041 (setq org-drawers-for-agenda
18042 (append org-drawers-for-agenda org-drawers))
18043 (setq org-tag-alist-for-agenda
18044 (org-uniquify
18045 (append org-tag-alist-for-agenda
18046 org-tag-alist
18047 org-tag-persistent-alist)))
18048 (if org-group-tags
18049 (setq org-tag-groups-alist-for-agenda
18050 (org-uniquify-alist
18051 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18052 (org-with-silent-modifications
18053 (save-excursion
18054 (remove-text-properties (point-min) (point-max) pall)
18055 (when org-agenda-skip-archived-trees
18056 (goto-char (point-min))
18057 (while (re-search-forward rea nil t)
18058 (if (org-at-heading-p t)
18059 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18060 (goto-char (point-min))
18061 (setq re (format org-heading-keyword-regexp-format
18062 org-comment-string))
18063 (while (re-search-forward re nil t)
18064 (add-text-properties
18065 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18066 (setq org-todo-keywords-for-agenda
18067 (org-uniquify org-todo-keywords-for-agenda))
18068 (setq org-todo-keyword-alist-for-agenda
18069 (org-uniquify org-todo-keyword-alist-for-agenda))))
18072 ;;;; CDLaTeX minor mode
18074 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18075 "Keymap for the minor `org-cdlatex-mode'.")
18077 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18078 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18079 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18080 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18081 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18083 (defvar org-cdlatex-texmathp-advice-is-done nil
18084 "Flag remembering if we have applied the advice to texmathp already.")
18086 (define-minor-mode org-cdlatex-mode
18087 "Toggle the minor `org-cdlatex-mode'.
18088 This mode supports entering LaTeX environment and math in LaTeX fragments
18089 in Org-mode.
18090 \\{org-cdlatex-mode-map}"
18091 nil " OCDL" nil
18092 (when org-cdlatex-mode
18093 (require 'cdlatex)
18094 (run-hooks 'cdlatex-mode-hook)
18095 (cdlatex-compute-tables))
18096 (unless org-cdlatex-texmathp-advice-is-done
18097 (setq org-cdlatex-texmathp-advice-is-done t)
18098 (defadvice texmathp (around org-math-always-on activate)
18099 "Always return t in org-mode buffers.
18100 This is because we want to insert math symbols without dollars even outside
18101 the LaTeX math segments. If Orgmode thinks that point is actually inside
18102 an embedded LaTeX fragment, let texmathp do its job.
18103 \\[org-cdlatex-mode-map]"
18104 (interactive)
18105 (let (p)
18106 (cond
18107 ((not (derived-mode-p 'org-mode)) ad-do-it)
18108 ((eq this-command 'cdlatex-math-symbol)
18109 (setq ad-return-value t
18110 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18112 (let ((p (org-inside-LaTeX-fragment-p)))
18113 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18114 (setq ad-return-value t
18115 texmathp-why '("Org-mode embedded math" . 0))
18116 (if p ad-do-it)))))))))
18118 (defun turn-on-org-cdlatex ()
18119 "Unconditionally turn on `org-cdlatex-mode'."
18120 (org-cdlatex-mode 1))
18122 (defun org-try-cdlatex-tab ()
18123 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18124 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18125 - inside a LaTeX fragment, or
18126 - after the first word in a line, where an abbreviation expansion could
18127 insert a LaTeX environment."
18128 (when org-cdlatex-mode
18129 (cond
18130 ;; Before any word on the line: No expansion possible.
18131 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18132 ;; Just after first word on the line: Expand it. Make sure it
18133 ;; cannot happen on headlines, though.
18134 ((save-excursion
18135 (skip-chars-backward "a-zA-Z0-9*")
18136 (skip-chars-backward " \t")
18137 (and (bolp) (not (org-at-heading-p))))
18138 (cdlatex-tab) t)
18139 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18141 (defun org-cdlatex-underscore-caret (&optional arg)
18142 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18143 Revert to the normal definition outside of these fragments."
18144 (interactive "P")
18145 (if (org-inside-LaTeX-fragment-p)
18146 (call-interactively 'cdlatex-sub-superscript)
18147 (let (org-cdlatex-mode)
18148 (call-interactively (key-binding (vector last-input-event))))))
18150 (defun org-cdlatex-math-modify (&optional arg)
18151 "Execute `cdlatex-math-modify' in LaTeX fragments.
18152 Revert to the normal definition outside of these fragments."
18153 (interactive "P")
18154 (if (org-inside-LaTeX-fragment-p)
18155 (call-interactively 'cdlatex-math-modify)
18156 (let (org-cdlatex-mode)
18157 (call-interactively (key-binding (vector last-input-event))))))
18161 ;;;; LaTeX fragments
18163 (defvar org-latex-regexps
18164 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18165 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18166 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18167 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18168 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18169 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18170 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18171 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18172 "Regular expressions for matching embedded LaTeX.")
18174 (defun org-inside-LaTeX-fragment-p ()
18175 "Test if point is inside a LaTeX fragment.
18176 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18177 sequence appearing also before point.
18178 Even though the matchers for math are configurable, this function assumes
18179 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18180 delimiters are skipped when they have been removed by customization.
18181 The return value is nil, or a cons cell with the delimiter and the
18182 position of this delimiter.
18184 This function does a reasonably good job, but can locally be fooled by
18185 for example currency specifications. For example it will assume being in
18186 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18187 fragments that are properly closed, but during editing, we have to live
18188 with the uncertainty caused by missing closing delimiters. This function
18189 looks only before point, not after."
18190 (catch 'exit
18191 (let ((pos (point))
18192 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18193 (lim (progn
18194 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18195 (point)))
18196 dd-on str (start 0) m re)
18197 (goto-char pos)
18198 (when dodollar
18199 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18200 re (nth 1 (assoc "$" org-latex-regexps)))
18201 (while (string-match re str start)
18202 (cond
18203 ((= (match-end 0) (length str))
18204 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18205 ((= (match-end 0) (- (length str) 5))
18206 (throw 'exit nil))
18207 (t (setq start (match-end 0))))))
18208 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18209 (goto-char pos)
18210 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18211 (and (match-beginning 2) (throw 'exit nil))
18212 ;; count $$
18213 (while (re-search-backward "\\$\\$" lim t)
18214 (setq dd-on (not dd-on)))
18215 (goto-char pos)
18216 (if dd-on (cons "$$" m))))))
18218 (defun org-inside-latex-macro-p ()
18219 "Is point inside a LaTeX macro or its arguments?"
18220 (save-match-data
18221 (org-in-regexp
18222 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18224 (defvar org-latex-fragment-image-overlays nil
18225 "List of overlays carrying the images of latex fragments.")
18226 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18228 (defun org-remove-latex-fragment-image-overlays ()
18229 "Remove all overlays with LaTeX fragment images in current buffer."
18230 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18231 (setq org-latex-fragment-image-overlays nil))
18233 (defun org-preview-latex-fragment (&optional subtree)
18234 "Preview the LaTeX fragment at point, or all locally or globally.
18235 If the cursor is in a LaTeX fragment, create the image and overlay
18236 it over the source code. If there is no fragment at point, display
18237 all fragments in the current text, from one headline to the next. With
18238 prefix SUBTREE, display all fragments in the current subtree. With a
18239 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18240 the cursor is before the first headline,
18241 display all fragments in the buffer.
18242 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18243 (interactive "P")
18244 (unless buffer-file-name
18245 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18246 (when (display-graphic-p)
18247 (org-remove-latex-fragment-image-overlays)
18248 (save-excursion
18249 (save-restriction
18250 (let (beg end at msg)
18251 (cond
18252 ((or (equal subtree '(16))
18253 (not (save-excursion
18254 (re-search-backward org-outline-regexp-bol nil t))))
18255 (setq beg (point-min) end (point-max)
18256 msg "Creating images for buffer...%s"))
18257 ((equal subtree '(4))
18258 (org-back-to-heading)
18259 (setq beg (point) end (org-end-of-subtree t)
18260 msg "Creating images for subtree...%s"))
18262 (if (setq at (org-inside-LaTeX-fragment-p))
18263 (goto-char (max (point-min) (- (cdr at) 2)))
18264 (org-back-to-heading))
18265 (setq beg (point) end (progn (outline-next-heading) (point))
18266 msg (if at "Creating image...%s"
18267 "Creating images for entry...%s"))))
18268 (message msg "")
18269 (narrow-to-region beg end)
18270 (goto-char beg)
18271 (org-format-latex
18272 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18273 (file-name-nondirectory
18274 buffer-file-name)))
18275 default-directory 'overlays msg at 'forbuffer
18276 org-latex-create-formula-image-program)
18277 (message msg "done. Use `C-c C-c' to remove images."))))))
18279 (defun org-format-latex (prefix &optional dir overlays msg at
18280 forbuffer processing-type)
18281 "Replace LaTeX fragments with links to an image, and produce images.
18282 Some of the options can be changed using the variable
18283 `org-format-latex-options'."
18284 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18285 (let* ((prefixnodir (file-name-nondirectory prefix))
18286 (absprefix (expand-file-name prefix dir))
18287 (todir (file-name-directory absprefix))
18288 (opt org-format-latex-options)
18289 (optnew org-format-latex-options)
18290 (matchers (plist-get opt :matchers))
18291 (re-list org-latex-regexps)
18292 (cnt 0) txt hash link beg end re e checkdir
18293 string
18294 m n block-type block linkfile movefile ov)
18295 ;; Check the different regular expressions
18296 (while (setq e (pop re-list))
18297 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18298 block (if block-type "\n\n" ""))
18299 (when (member m matchers)
18300 (goto-char (point-min))
18301 (while (re-search-forward re nil t)
18302 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18303 (or (not overlays)
18304 (not (eq (get-char-property (match-beginning n)
18305 'org-overlay-type)
18306 'org-latex-overlay))))
18307 (cond
18308 ((eq processing-type 'verbatim))
18309 ((eq processing-type 'mathjax)
18310 ;; Prepare for MathJax processing.
18311 (setq string (match-string n))
18312 (when (member m '("$" "$1"))
18313 (save-excursion
18314 (delete-region (match-beginning n) (match-end n))
18315 (goto-char (match-beginning n))
18316 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18317 ((or (eq processing-type 'dvipng)
18318 (eq processing-type 'imagemagick))
18319 ;; Process to an image.
18320 (setq txt (match-string n)
18321 beg (match-beginning n) end (match-end n)
18322 cnt (1+ cnt))
18323 (let ((face (face-at-point))
18324 (fg (plist-get opt :foreground))
18325 (bg (plist-get opt :background))
18326 ;; Ensure full list is printed.
18327 print-length print-level)
18328 (when forbuffer
18329 ;; Get the colors from the face at point.
18330 (goto-char beg)
18331 (when (eq fg 'auto)
18332 (setq fg (face-attribute face :foreground nil 'default)))
18333 (when (eq bg 'auto)
18334 (setq bg (face-attribute face :background nil 'default)))
18335 (setq optnew (copy-sequence opt))
18336 (plist-put optnew :foreground fg)
18337 (plist-put optnew :background bg))
18338 (setq hash (sha1 (prin1-to-string
18339 (list org-format-latex-header
18340 org-latex-default-packages-alist
18341 org-latex-packages-alist
18342 org-format-latex-options
18343 forbuffer txt fg bg)))
18344 linkfile (format "%s_%s.png" prefix hash)
18345 movefile (format "%s_%s.png" absprefix hash)))
18346 (setq link (concat block "[[file:" linkfile "]]" block))
18347 (if msg (message msg cnt))
18348 (goto-char beg)
18349 (unless checkdir ; Ensure the directory exists.
18350 (setq checkdir t)
18351 (or (file-directory-p todir) (make-directory todir t)))
18352 (unless (file-exists-p movefile)
18353 (org-create-formula-image
18354 txt movefile optnew forbuffer processing-type))
18355 (if overlays
18356 (progn
18357 (mapc (lambda (o)
18358 (if (eq (overlay-get o 'org-overlay-type)
18359 'org-latex-overlay)
18360 (delete-overlay o)))
18361 (overlays-in beg end))
18362 (setq ov (make-overlay beg end))
18363 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18364 (if (featurep 'xemacs)
18365 (progn
18366 (overlay-put ov 'invisible t)
18367 (overlay-put
18368 ov 'end-glyph
18369 (make-glyph (vector 'png :file movefile))))
18370 (overlay-put
18371 ov 'display
18372 (list 'image :type 'png :file movefile :ascent 'center)))
18373 (push ov org-latex-fragment-image-overlays)
18374 (goto-char end))
18375 (delete-region beg end)
18376 (insert (org-add-props link
18377 (list 'org-latex-src
18378 (replace-regexp-in-string
18379 "\"" "" txt)
18380 'org-latex-src-embed-type
18381 (if block-type 'paragraph 'character))))))
18382 ((eq processing-type 'mathml)
18383 ;; Process to MathML
18384 (unless (save-match-data (org-format-latex-mathml-available-p))
18385 (user-error "LaTeX to MathML converter not configured"))
18386 (setq txt (match-string n)
18387 beg (match-beginning n) end (match-end n)
18388 cnt (1+ cnt))
18389 (if msg (message msg cnt))
18390 (goto-char beg)
18391 (delete-region beg end)
18392 (insert (org-format-latex-as-mathml
18393 txt block-type prefix dir)))
18395 (error "Unknown conversion type %s for LaTeX fragments"
18396 processing-type)))))))))
18398 (defun org-create-math-formula (latex-frag &optional mathml-file)
18399 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18400 Use `org-latex-to-mathml-convert-command'. If the conversion is
18401 sucessful, return the portion between \"<math...> </math>\"
18402 elements otherwise return nil. When MATHML-FILE is specified,
18403 write the results in to that file. When invoked as an
18404 interactive command, prompt for LATEX-FRAG, with initial value
18405 set to the current active region and echo the results for user
18406 inspection."
18407 (interactive (list (let ((frag (when (org-region-active-p)
18408 (buffer-substring-no-properties
18409 (region-beginning) (region-end)))))
18410 (read-string "LaTeX Fragment: " frag nil frag))))
18411 (unless latex-frag (error "Invalid LaTeX fragment"))
18412 (let* ((tmp-in-file (file-relative-name
18413 (make-temp-name (expand-file-name "ltxmathml-in"))))
18414 (ignore (write-region latex-frag nil tmp-in-file))
18415 (tmp-out-file (file-relative-name
18416 (make-temp-name (expand-file-name "ltxmathml-out"))))
18417 (cmd (format-spec
18418 org-latex-to-mathml-convert-command
18419 `((?j . ,(shell-quote-argument
18420 (expand-file-name org-latex-to-mathml-jar-file)))
18421 (?I . ,(shell-quote-argument tmp-in-file))
18422 (?o . ,(shell-quote-argument tmp-out-file)))))
18423 mathml shell-command-output)
18424 (when (org-called-interactively-p 'any)
18425 (unless (org-format-latex-mathml-available-p)
18426 (user-error "LaTeX to MathML converter not configured")))
18427 (message "Running %s" cmd)
18428 (setq shell-command-output (shell-command-to-string cmd))
18429 (setq mathml
18430 (when (file-readable-p tmp-out-file)
18431 (with-current-buffer (find-file-noselect tmp-out-file t)
18432 (goto-char (point-min))
18433 (when (re-search-forward
18434 (concat
18435 (regexp-quote
18436 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18437 "\\(.\\|\n\\)*"
18438 (regexp-quote "</math>")) nil t)
18439 (prog1 (match-string 0) (kill-buffer))))))
18440 (cond
18441 (mathml
18442 (setq mathml
18443 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18444 (when mathml-file
18445 (write-region mathml nil mathml-file))
18446 (when (org-called-interactively-p 'any)
18447 (message mathml)))
18448 ((message "LaTeX to MathML conversion failed")
18449 (message shell-command-output)))
18450 (delete-file tmp-in-file)
18451 (when (file-exists-p tmp-out-file)
18452 (delete-file tmp-out-file))
18453 mathml))
18455 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18456 prefix &optional dir)
18457 "Use `org-create-math-formula' but check local cache first."
18458 (let* ((absprefix (expand-file-name prefix dir))
18459 (print-length nil) (print-level nil)
18460 (formula-id (concat
18461 "formula-"
18462 (sha1
18463 (prin1-to-string
18464 (list latex-frag
18465 org-latex-to-mathml-convert-command)))))
18466 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18467 (formula-cache-dir (file-name-directory formula-cache)))
18469 (unless (file-directory-p formula-cache-dir)
18470 (make-directory formula-cache-dir t))
18472 (unless (file-exists-p formula-cache)
18473 (org-create-math-formula latex-frag formula-cache))
18475 (if (file-exists-p formula-cache)
18476 ;; Successful conversion. Return the link to MathML file.
18477 (org-add-props
18478 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18479 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18480 'org-latex-src-embed-type (if latex-frag-type
18481 'paragraph 'character)))
18482 ;; Failed conversion. Return the LaTeX fragment verbatim
18483 latex-frag)))
18485 (defun org-create-formula-image (string tofile options buffer &optional type)
18486 "Create an image from LaTeX source using dvipng or convert.
18487 This function calls either `org-create-formula-image-with-dvipng'
18488 or `org-create-formula-image-with-imagemagick' depending on the
18489 value of `org-latex-create-formula-image-program' or on the value
18490 of the optional TYPE variable.
18492 Note: ultimately these two function should be combined as they
18493 share a good deal of logic."
18494 (org-check-external-command
18495 "latex" "needed to convert LaTeX fragments to images")
18496 (funcall
18497 (case (or type org-latex-create-formula-image-program)
18498 ('dvipng
18499 (org-check-external-command
18500 "dvipng" "needed to convert LaTeX fragments to images")
18501 #'org-create-formula-image-with-dvipng)
18502 ('imagemagick
18503 (org-check-external-command
18504 "convert" "you need to install imagemagick")
18505 #'org-create-formula-image-with-imagemagick)
18506 (t (error
18507 "Invalid value of `org-latex-create-formula-image-program'")))
18508 string tofile options buffer))
18510 (declare-function org-export-get-backend "ox" (name))
18511 (declare-function org-export--get-global-options "ox" (&optional backend))
18512 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18513 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18514 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18515 (defun org-create-formula--latex-header ()
18516 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18517 (let ((info (org-combine-plists (org-export--get-global-options
18518 (org-export-get-backend 'latex))
18519 (org-export--get-inbuffer-options
18520 (org-export-get-backend 'latex)))))
18521 (org-latex-guess-babel-language
18522 (org-latex-guess-inputenc
18523 (org-splice-latex-header
18524 org-format-latex-header
18525 org-latex-default-packages-alist
18526 org-latex-packages-alist t
18527 (plist-get info :latex-header)))
18528 info)))
18530 ;; This function borrows from Ganesh Swami's latex2png.el
18531 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18532 "This calls dvipng."
18533 (require 'ox-latex)
18534 (let* ((tmpdir (if (featurep 'xemacs)
18535 (temp-directory)
18536 temporary-file-directory))
18537 (texfilebase (make-temp-name
18538 (expand-file-name "orgtex" tmpdir)))
18539 (texfile (concat texfilebase ".tex"))
18540 (dvifile (concat texfilebase ".dvi"))
18541 (pngfile (concat texfilebase ".png"))
18542 (fnh (if (featurep 'xemacs)
18543 (font-height (face-font 'default))
18544 (face-attribute 'default :height nil)))
18545 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18546 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18547 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18548 "Black"))
18549 (bg (or (plist-get options (if buffer :background :html-background))
18550 "Transparent")))
18551 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18552 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18553 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18554 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18555 (let ((latex-header (org-create-formula--latex-header)))
18556 (with-temp-file texfile
18557 (insert latex-header)
18558 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18559 (let ((dir default-directory))
18560 (condition-case nil
18561 (progn
18562 (cd tmpdir)
18563 (call-process "latex" nil nil nil texfile))
18564 (error nil))
18565 (cd dir))
18566 (if (not (file-exists-p dvifile))
18567 (progn (message "Failed to create dvi file from %s" texfile) nil)
18568 (condition-case nil
18569 (if (featurep 'xemacs)
18570 (call-process "dvipng" nil nil nil
18571 "-fg" fg "-bg" bg
18572 "-T" "tight"
18573 "-o" pngfile
18574 dvifile)
18575 (call-process "dvipng" nil nil nil
18576 "-fg" fg "-bg" bg
18577 "-D" dpi
18578 ;;"-x" scale "-y" scale
18579 "-T" "tight"
18580 "-o" pngfile
18581 dvifile))
18582 (error nil))
18583 (if (not (file-exists-p pngfile))
18584 (if org-format-latex-signal-error
18585 (error "Failed to create png file from %s" texfile)
18586 (message "Failed to create png file from %s" texfile)
18587 nil)
18588 ;; Use the requested file name and clean up
18589 (copy-file pngfile tofile 'replace)
18590 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18591 (if (file-exists-p (concat texfilebase e))
18592 (delete-file (concat texfilebase e))))
18593 pngfile))))
18595 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18596 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18597 "This calls convert, which is included into imagemagick."
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 (pdffile (concat texfilebase ".pdf"))
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 "white")))
18616 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18617 (setq fg (org-latex-color-format fg)))
18618 (if (eq bg 'default) (setq bg (org-latex-color :background))
18619 (setq bg (org-latex-color-format
18620 (if (string= bg "Transparent") "white" bg))))
18621 (let ((latex-header (org-create-formula--latex-header)))
18622 (with-temp-file texfile
18623 (insert latex-header)
18624 (insert "\n\\begin{document}\n"
18625 "\\definecolor{fg}{rgb}{" fg "}\n"
18626 "\\definecolor{bg}{rgb}{" bg "}\n"
18627 "\n\\pagecolor{bg}\n"
18628 "\n{\\color{fg}\n"
18629 string
18630 "\n}\n"
18631 "\n\\end{document}\n")))
18632 (org-latex-compile texfile t)
18633 (if (not (file-exists-p pdffile))
18634 (progn (message "Failed to create pdf file from %s" texfile) nil)
18635 (condition-case nil
18636 (if (featurep 'xemacs)
18637 (call-process "convert" nil nil nil
18638 "-density" "96"
18639 "-trim"
18640 "-antialias"
18641 pdffile
18642 "-quality" "100"
18643 ;; "-sharpen" "0x1.0"
18644 pngfile)
18645 (call-process "convert" nil nil nil
18646 "-density" dpi
18647 "-trim"
18648 "-antialias"
18649 pdffile
18650 "-quality" "100"
18651 ;; "-sharpen" "0x1.0"
18652 pngfile))
18653 (error nil))
18654 (if (not (file-exists-p pngfile))
18655 (if org-format-latex-signal-error
18656 (error "Failed to create png file from %s" texfile)
18657 (message "Failed to create png file from %s" texfile)
18658 nil)
18659 ;; Use the requested file name and clean up
18660 (copy-file pngfile tofile 'replace)
18661 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18662 (if (file-exists-p (concat texfilebase e))
18663 (delete-file (concat texfilebase e))))
18664 pngfile))))
18666 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18667 "Fill a LaTeX header template TPL.
18668 In the template, the following place holders will be recognized:
18670 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18671 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18672 [PACKAGES] \\usepackage statements for PKG
18673 [NO-PACKAGES] do not include PKG
18674 [EXTRA] the string EXTRA
18675 [NO-EXTRA] do not include EXTRA
18677 For backward compatibility, if both the positive and the negative place
18678 holder is missing, the positive one (without the \"NO-\") will be
18679 assumed to be present at the end of the template.
18680 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18681 EXTRA is a string.
18682 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18683 (let (rpl (end ""))
18684 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18685 (setq rpl (if (or (match-end 1) (not def-pkg))
18686 "" (org-latex-packages-to-string def-pkg snippets-p t))
18687 tpl (replace-match rpl t t tpl))
18688 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18690 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18691 (setq rpl (if (or (match-end 1) (not pkg))
18692 "" (org-latex-packages-to-string pkg snippets-p t))
18693 tpl (replace-match rpl t t tpl))
18694 (if pkg (setq end
18695 (concat end "\n"
18696 (org-latex-packages-to-string pkg snippets-p)))))
18698 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18699 (setq rpl (if (or (match-end 1) (not extra))
18700 "" (concat extra "\n"))
18701 tpl (replace-match rpl t t tpl))
18702 (if (and extra (string-match "\\S-" extra))
18703 (setq end (concat end "\n" extra))))
18705 (if (string-match "\\S-" end)
18706 (concat tpl "\n" end)
18707 tpl)))
18709 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18710 "Turn an alist of packages into a string with the \\usepackage macros."
18711 (setq pkg (mapconcat (lambda(p)
18712 (cond
18713 ((stringp p) p)
18714 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18715 (format "%% Package %s omitted" (cadr p)))
18716 ((equal "" (car p))
18717 (format "\\usepackage{%s}" (cadr p)))
18719 (format "\\usepackage[%s]{%s}"
18720 (car p) (cadr p)))))
18722 "\n"))
18723 (if newline (concat pkg "\n") pkg))
18725 (defun org-dvipng-color (attr)
18726 "Return a RGB color specification for dvipng."
18727 (apply 'format "rgb %s %s %s"
18728 (mapcar 'org-normalize-color
18729 (if (featurep 'xemacs)
18730 (color-rgb-components
18731 (face-property 'default
18732 (cond ((eq attr :foreground) 'foreground)
18733 ((eq attr :background) 'background))))
18734 (color-values (face-attribute 'default attr nil))))))
18736 (defun org-dvipng-color-format (color-name)
18737 "Convert COLOR-NAME to a RGB color value for dvipng."
18738 (apply 'format "rgb %s %s %s"
18739 (mapcar 'org-normalize-color
18740 (color-values color-name))))
18742 (defun org-latex-color (attr)
18743 "Return a RGB color for the LaTeX color package."
18744 (apply 'format "%s,%s,%s"
18745 (mapcar 'org-normalize-color
18746 (if (featurep 'xemacs)
18747 (color-rgb-components
18748 (face-property 'default
18749 (cond ((eq attr :foreground) 'foreground)
18750 ((eq attr :background) 'background))))
18751 (color-values (face-attribute 'default attr nil))))))
18753 (defun org-latex-color-format (color-name)
18754 "Convert COLOR-NAME to a RGB color value."
18755 (apply 'format "%s,%s,%s"
18756 (mapcar 'org-normalize-color
18757 (color-values color-name))))
18759 (defun org-normalize-color (value)
18760 "Return string to be used as color value for an RGB component."
18761 (format "%g" (/ value 65535.0)))
18765 ;; Image display
18767 (defvar org-inline-image-overlays nil)
18768 (make-variable-buffer-local 'org-inline-image-overlays)
18770 (defun org-toggle-inline-images (&optional include-linked)
18771 "Toggle the display of inline images.
18772 INCLUDE-LINKED is passed to `org-display-inline-images'."
18773 (interactive "P")
18774 (if org-inline-image-overlays
18775 (progn
18776 (org-remove-inline-images)
18777 (message "Inline image display turned off"))
18778 (org-display-inline-images include-linked)
18779 (if (and (org-called-interactively-p)
18780 org-inline-image-overlays)
18781 (message "%d images displayed inline"
18782 (length org-inline-image-overlays))
18783 (message "No images to display inline"))))
18785 (defun org-redisplay-inline-images ()
18786 "Refresh the display of inline images."
18787 (interactive)
18788 (if (not org-inline-image-overlays)
18789 (org-toggle-inline-images)
18790 (org-toggle-inline-images)
18791 (org-toggle-inline-images)))
18793 (defun org-display-inline-images (&optional include-linked refresh beg end)
18794 "Display inline images.
18795 Normally only links without a description part are inlined, because this
18796 is how it will work for export. When INCLUDE-LINKED is set, also links
18797 with a description part will be inlined. This can be nice for a quick
18798 look at those images, but it does not reflect what exported files will look
18799 like.
18800 When REFRESH is set, refresh existing images between BEG and END.
18801 This will create new image displays only if necessary.
18802 BEG and END default to the buffer boundaries."
18803 (interactive "P")
18804 (when (display-graphic-p)
18805 (unless refresh
18806 (org-remove-inline-images)
18807 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18808 (save-excursion
18809 (save-restriction
18810 (widen)
18811 (setq beg (or beg (point-min)) end (or end (point-max)))
18812 (goto-char beg)
18813 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18814 (substring (org-image-file-name-regexp) 0 -2)
18815 "\\)\\]" (if include-linked "" "\\]")))
18816 (case-fold-search t)
18817 old file ov img type attrwidth width)
18818 (while (re-search-forward re end t)
18819 (setq old (get-char-property-and-overlay (match-beginning 1)
18820 'org-image-overlay)
18821 file (expand-file-name
18822 (concat (or (match-string 3) "") (match-string 4))))
18823 (when (image-type-available-p 'imagemagick)
18824 (setq attrwidth (if (or (listp org-image-actual-width)
18825 (null org-image-actual-width))
18826 (save-excursion
18827 (save-match-data
18828 (when (re-search-backward
18829 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18830 (save-excursion
18831 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18832 (string-to-number (match-string 1))))))
18833 width (cond ((eq org-image-actual-width t) nil)
18834 ((null org-image-actual-width) attrwidth)
18835 ((numberp org-image-actual-width)
18836 org-image-actual-width)
18837 ((listp org-image-actual-width)
18838 (or attrwidth (car org-image-actual-width))))
18839 type (if width 'imagemagick)))
18840 (when (file-exists-p file)
18841 (if (and (car-safe old) refresh)
18842 (image-refresh (overlay-get (cdr old) 'display))
18843 (setq img (save-match-data (create-image file type nil :width width)))
18844 (when img
18845 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18846 (overlay-put ov 'display img)
18847 (overlay-put ov 'face 'default)
18848 (overlay-put ov 'org-image-overlay t)
18849 (overlay-put ov 'modification-hooks
18850 (list 'org-display-inline-remove-overlay))
18851 (push ov org-inline-image-overlays))))))))))
18853 (define-obsolete-function-alias
18854 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18856 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18857 "Remove inline-display overlay if a corresponding region is modified."
18858 (let ((inhibit-modification-hooks t))
18859 (when (and ov after)
18860 (delete ov org-inline-image-overlays)
18861 (delete-overlay ov))))
18863 (defun org-remove-inline-images ()
18864 "Remove inline display of images."
18865 (interactive)
18866 (mapc 'delete-overlay org-inline-image-overlays)
18867 (setq org-inline-image-overlays nil))
18869 ;;;; Key bindings
18871 ;; Outline functions from `outline-mode-prefix-map'
18872 ;; that can be remapped in Org:
18873 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18874 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18875 (define-key org-mode-map [remap outline-forward-same-level]
18876 'org-forward-heading-same-level)
18877 (define-key org-mode-map [remap outline-backward-same-level]
18878 'org-backward-heading-same-level)
18879 (define-key org-mode-map [remap show-branches]
18880 'org-kill-note-or-show-branches)
18881 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18882 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18883 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18885 ;; Outline functions from `outline-mode-prefix-map' that can not
18886 ;; be remapped in Org:
18888 ;; - the column "key binding" shows whether the Outline function is still
18889 ;; available in Org mode on the same key that it has been bound to in
18890 ;; Outline mode:
18891 ;; - "overridden": key used for a different functionality in Org mode
18892 ;; - else: key still bound to the same Outline function in Org mode
18894 ;; | Outline function | key binding | Org replacement |
18895 ;; |------------------------------------+-------------+-----------------------|
18896 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18897 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18898 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18899 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18900 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18901 ;; | `show-entry' | overridden | no replacement |
18902 ;; | `show-children' | `C-c C-i' | visibility cycling |
18903 ;; | `show-branches' | `C-c C-k' | still same function |
18904 ;; | `show-subtree' | overridden | visibility cycling |
18905 ;; | `show-all' | overridden | no replacement |
18906 ;; | `hide-subtree' | overridden | visibility cycling |
18907 ;; | `hide-body' | overridden | no replacement |
18908 ;; | `hide-entry' | overridden | visibility cycling |
18909 ;; | `hide-leaves' | overridden | no replacement |
18910 ;; | `hide-sublevels' | overridden | no replacement |
18911 ;; | `hide-other' | overridden | no replacement |
18913 ;; Make `C-c C-x' a prefix key
18914 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18916 ;; TAB key with modifiers
18917 (org-defkey org-mode-map "\C-i" 'org-cycle)
18918 (org-defkey org-mode-map [(tab)] 'org-cycle)
18919 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18920 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18921 ;; The following line is necessary under Suse GNU/Linux
18922 (unless (featurep 'xemacs)
18923 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18924 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18925 (define-key org-mode-map [backtab] 'org-shifttab)
18927 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18928 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18929 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18931 ;; Cursor keys with modifiers
18932 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18933 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18934 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18935 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18937 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18938 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18939 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18940 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18942 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18943 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18944 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18945 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18947 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18948 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18949 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18950 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18952 ;; Babel keys
18953 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18954 (mapc (lambda (pair)
18955 (define-key org-babel-map (car pair) (cdr pair)))
18956 org-babel-key-bindings)
18958 ;;; Extra keys for tty access.
18959 ;; We only set them when really needed because otherwise the
18960 ;; menus don't show the simple keys
18962 (when (or org-use-extra-keys
18963 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18964 (not window-system))
18965 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18966 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18967 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18968 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18969 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18970 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18971 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18972 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18973 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18974 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18975 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18976 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18977 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18978 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18979 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18980 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18981 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18982 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18983 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18984 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18985 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18986 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18987 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18988 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18989 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18990 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18991 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18992 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18994 ;; All the other keys
18996 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18997 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18998 (if (boundp 'narrow-map)
18999 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19000 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19001 (if (boundp 'narrow-map)
19002 (org-defkey narrow-map "b" 'org-narrow-to-block)
19003 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19004 (if (boundp 'narrow-map)
19005 (org-defkey narrow-map "e" 'org-narrow-to-element)
19006 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19007 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19008 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19009 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19010 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19011 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19012 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19013 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19014 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19015 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19016 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19017 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19018 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19019 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19020 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19021 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19022 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19023 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19024 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19025 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19026 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19027 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19028 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19029 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19030 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19031 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19032 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19033 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19034 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19035 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19036 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19037 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19038 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19039 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19040 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19041 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19042 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19043 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19044 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19045 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19046 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19047 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19048 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19049 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19050 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19051 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19052 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19053 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19054 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19055 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19056 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19057 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19058 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19059 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19060 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19061 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19062 (org-defkey org-mode-map "\C-c^" 'org-sort)
19063 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19064 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19065 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19066 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19067 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-element)
19068 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-element)
19069 (org-defkey org-mode-map "\C-m" 'org-return)
19070 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19071 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19072 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19073 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19074 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19075 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19076 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19077 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19078 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19079 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19080 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19081 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19082 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19083 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19084 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19085 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19086 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19087 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19088 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19089 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19090 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19091 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19092 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19094 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19095 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19096 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19098 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19099 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19100 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19101 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19102 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19103 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19104 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19105 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19106 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19107 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19108 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19109 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19110 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19111 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19112 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19113 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19114 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19115 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19116 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19117 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19118 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19119 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19120 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19122 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19123 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19124 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19125 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19126 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19128 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19130 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19132 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19133 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19135 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19138 (when (featurep 'xemacs)
19139 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19142 (defconst org-speed-commands-default
19144 ("Outline Navigation")
19145 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19146 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19147 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19148 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19149 ("F" . org-next-block)
19150 ("B" . org-previous-block)
19151 ("u" . (org-speed-move-safe 'outline-up-heading))
19152 ("j" . org-goto)
19153 ("g" . (org-refile t))
19154 ("Outline Visibility")
19155 ("c" . org-cycle)
19156 ("C" . org-shifttab)
19157 (" " . org-display-outline-path)
19158 ("s" . org-narrow-to-subtree)
19159 ("=" . org-columns)
19160 ("Outline Structure Editing")
19161 ("U" . org-shiftmetaup)
19162 ("D" . org-shiftmetadown)
19163 ("r" . org-metaright)
19164 ("l" . org-metaleft)
19165 ("R" . org-shiftmetaright)
19166 ("L" . org-shiftmetaleft)
19167 ("i" . (progn (forward-char 1) (call-interactively
19168 'org-insert-heading-respect-content)))
19169 ("^" . org-sort)
19170 ("w" . org-refile)
19171 ("a" . org-archive-subtree-default-with-confirmation)
19172 ("@" . org-mark-subtree)
19173 ("#" . org-toggle-comment)
19174 ("Clock Commands")
19175 ("I" . org-clock-in)
19176 ("O" . org-clock-out)
19177 ("Meta Data Editing")
19178 ("t" . org-todo)
19179 ("," . (org-priority))
19180 ("0" . (org-priority ?\ ))
19181 ("1" . (org-priority ?A))
19182 ("2" . (org-priority ?B))
19183 ("3" . (org-priority ?C))
19184 (":" . org-set-tags-command)
19185 ("e" . org-set-effort)
19186 ("E" . org-inc-effort)
19187 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19188 (org-entry-put (point) "APPT_WARNTIME" m)))
19189 ("Agenda Views etc")
19190 ("v" . org-agenda)
19191 ("/" . org-sparse-tree)
19192 ("Misc")
19193 ("o" . org-open-at-point)
19194 ("?" . org-speed-command-help)
19195 ("<" . (org-agenda-set-restriction-lock 'subtree))
19196 (">" . (org-agenda-remove-restriction-lock))
19198 "The default speed commands.")
19200 (defun org-print-speed-command (e)
19201 (if (> (length (car e)) 1)
19202 (progn
19203 (princ "\n")
19204 (princ (car e))
19205 (princ "\n")
19206 (princ (make-string (length (car e)) ?-))
19207 (princ "\n"))
19208 (princ (car e))
19209 (princ " ")
19210 (if (symbolp (cdr e))
19211 (princ (symbol-name (cdr e)))
19212 (prin1 (cdr e)))
19213 (princ "\n")))
19215 (defun org-speed-command-help ()
19216 "Show the available speed commands."
19217 (interactive)
19218 (if (not org-use-speed-commands)
19219 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19220 (with-output-to-temp-buffer "*Help*"
19221 (princ "User-defined Speed commands\n===========================\n")
19222 (mapc 'org-print-speed-command org-speed-commands-user)
19223 (princ "\n")
19224 (princ "Built-in Speed commands\n=======================\n")
19225 (mapc 'org-print-speed-command org-speed-commands-default))
19226 (with-current-buffer "*Help*"
19227 (setq truncate-lines t))))
19229 (defun org-speed-move-safe (cmd)
19230 "Execute CMD, but make sure that the cursor always ends up in a headline.
19231 If not, return to the original position and throw an error."
19232 (interactive)
19233 (let ((pos (point)))
19234 (call-interactively cmd)
19235 (unless (and (bolp) (org-at-heading-p))
19236 (goto-char pos)
19237 (error "Boundary reached while executing %s" cmd))))
19239 (defvar org-self-insert-command-undo-counter 0)
19241 (defvar org-table-auto-blank-field) ; defined in org-table.el
19242 (defvar org-speed-command nil)
19244 (define-obsolete-function-alias
19245 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19247 (defun org-speed-command-activate (keys)
19248 "Hook for activating single-letter speed commands.
19249 `org-speed-commands-default' specifies a minimal command set.
19250 Use `org-speed-commands-user' for further customization."
19251 (when (or (and (bolp) (looking-at org-outline-regexp))
19252 (and (functionp org-use-speed-commands)
19253 (funcall org-use-speed-commands)))
19254 (cdr (assoc keys (append org-speed-commands-user
19255 org-speed-commands-default)))))
19257 (define-obsolete-function-alias
19258 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19260 (defun org-babel-speed-command-activate (keys)
19261 "Hook for activating single-letter code block commands."
19262 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19263 (cdr (assoc keys org-babel-key-bindings))))
19265 (defcustom org-speed-command-hook
19266 '(org-speed-command-default-hook org-babel-speed-command-hook)
19267 "Hook for activating speed commands at strategic locations.
19268 Hook functions are called in sequence until a valid handler is
19269 found.
19271 Each hook takes a single argument, a user-pressed command key
19272 which is also a `self-insert-command' from the global map.
19274 Within the hook, examine the cursor position and the command key
19275 and return nil or a valid handler as appropriate. Handler could
19276 be one of an interactive command, a function, or a form.
19278 Set `org-use-speed-commands' to non-nil value to enable this
19279 hook. The default setting is `org-speed-command-activate'."
19280 :group 'org-structure
19281 :version "24.1"
19282 :type 'hook)
19284 (defun org-self-insert-command (N)
19285 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19286 If the cursor is in a table looking at whitespace, the whitespace is
19287 overwritten, and the table is not marked as requiring realignment."
19288 (interactive "p")
19289 (org-check-before-invisible-edit 'insert)
19290 (cond
19291 ((and org-use-speed-commands
19292 (setq org-speed-command
19293 (run-hook-with-args-until-success
19294 'org-speed-command-hook (this-command-keys))))
19295 (cond
19296 ((commandp org-speed-command)
19297 (setq this-command org-speed-command)
19298 (call-interactively org-speed-command))
19299 ((functionp org-speed-command)
19300 (funcall org-speed-command))
19301 ((and org-speed-command (listp org-speed-command))
19302 (eval org-speed-command))
19303 (t (let (org-use-speed-commands)
19304 (call-interactively 'org-self-insert-command)))))
19305 ((and
19306 (org-table-p)
19307 (progn
19308 ;; check if we blank the field, and if that triggers align
19309 (and (featurep 'org-table) org-table-auto-blank-field
19310 (member last-command
19311 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19312 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19313 ;; got extra space, this field does not determine column width
19314 (let (org-table-may-need-update) (org-table-blank-field))
19315 ;; no extra space, this field may determine column width
19316 (org-table-blank-field)))
19318 (eq N 1)
19319 (looking-at "[^|\n]* |"))
19320 (let (org-table-may-need-update)
19321 (goto-char (1- (match-end 0)))
19322 (backward-delete-char 1)
19323 (goto-char (match-beginning 0))
19324 (self-insert-command N)))
19326 (setq org-table-may-need-update t)
19327 (self-insert-command N)
19328 (org-fix-tags-on-the-fly)
19329 (if org-self-insert-cluster-for-undo
19330 (if (not (eq last-command 'org-self-insert-command))
19331 (setq org-self-insert-command-undo-counter 1)
19332 (if (>= org-self-insert-command-undo-counter 20)
19333 (setq org-self-insert-command-undo-counter 1)
19334 (and (> org-self-insert-command-undo-counter 0)
19335 buffer-undo-list (listp buffer-undo-list)
19336 (not (cadr buffer-undo-list)) ; remove nil entry
19337 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19338 (setq org-self-insert-command-undo-counter
19339 (1+ org-self-insert-command-undo-counter))))))))
19341 (defun org-check-before-invisible-edit (kind)
19342 "Check is editing if kind KIND would be dangerous with invisible text around.
19343 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19344 ;; First, try to get out of here as quickly as possible, to reduce overhead
19345 (if (and org-catch-invisible-edits
19346 (or (not (boundp 'visible-mode)) (not visible-mode))
19347 (or (get-char-property (point) 'invisible)
19348 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19349 ;; OK, we need to take a closer look
19350 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19351 (invisible-before-point (if (bobp) nil (get-char-property
19352 (1- (point)) 'invisible)))
19353 (border-and-ok-direction
19355 ;; Check if we are acting predictably before invisible text
19356 (and invisible-at-point (not invisible-before-point)
19357 (memq kind '(insert delete-backward)))
19358 ;; Check if we are acting predictably after invisible text
19359 ;; This works not well, and I have turned it off. It seems
19360 ;; better to always show and stop after invisible text.
19361 ;; (and (not invisible-at-point) invisible-before-point
19362 ;; (memq kind '(insert delete)))
19364 (when (or (memq invisible-at-point '(outline org-hide-block t))
19365 (memq invisible-before-point '(outline org-hide-block t)))
19366 (if (eq org-catch-invisible-edits 'error)
19367 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19368 (if (and org-custom-properties-overlays
19369 (y-or-n-p "Display invisible properties in this buffer? "))
19370 (org-toggle-custom-properties-visibility)
19371 ;; Make the area visible
19372 (save-excursion
19373 (if invisible-before-point
19374 (goto-char (previous-single-char-property-change
19375 (point) 'invisible)))
19376 (org-cycle))
19377 (cond
19378 ((eq org-catch-invisible-edits 'show)
19379 ;; That's it, we do the edit after showing
19380 (message
19381 "Unfolding invisible region around point before editing")
19382 (sit-for 1))
19383 ((and (eq org-catch-invisible-edits 'smart)
19384 border-and-ok-direction)
19385 (message "Unfolding invisible region around point before editing"))
19387 ;; Don't do the edit, make the user repeat it in full visibility
19388 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19390 (defun org-fix-tags-on-the-fly ()
19391 (when (and (equal (char-after (point-at-bol)) ?*)
19392 (org-at-heading-p))
19393 (org-align-tags-here org-tags-column)))
19395 (defun org-delete-backward-char (N)
19396 "Like `delete-backward-char', insert whitespace at field end in tables.
19397 When deleting backwards, in tables this function will insert whitespace in
19398 front of the next \"|\" separator, to keep the table aligned. The table will
19399 still be marked for re-alignment if the field did fill the entire column,
19400 because, in this case the deletion might narrow the column."
19401 (interactive "p")
19402 (save-match-data
19403 (org-check-before-invisible-edit 'delete-backward)
19404 (if (and (org-table-p)
19405 (eq N 1)
19406 (string-match "|" (buffer-substring (point-at-bol) (point)))
19407 (looking-at ".*?|"))
19408 (let ((pos (point))
19409 (noalign (looking-at "[^|\n\r]* |"))
19410 (c org-table-may-need-update))
19411 (backward-delete-char N)
19412 (if (not overwrite-mode)
19413 (progn
19414 (skip-chars-forward "^|")
19415 (insert " ")
19416 (goto-char (1- pos))))
19417 ;; noalign: if there were two spaces at the end, this field
19418 ;; does not determine the width of the column.
19419 (if noalign (setq org-table-may-need-update c)))
19420 (backward-delete-char N)
19421 (org-fix-tags-on-the-fly))))
19423 (defun org-delete-char (N)
19424 "Like `delete-char', but insert whitespace at field end in tables.
19425 When deleting characters, in tables this function will insert whitespace in
19426 front of the next \"|\" separator, to keep the table aligned. The table will
19427 still be marked for re-alignment if the field did fill the entire column,
19428 because, in this case the deletion might narrow the column."
19429 (interactive "p")
19430 (save-match-data
19431 (org-check-before-invisible-edit 'delete)
19432 (if (and (org-table-p)
19433 (not (bolp))
19434 (not (= (char-after) ?|))
19435 (eq N 1))
19436 (if (looking-at ".*?|")
19437 (let ((pos (point))
19438 (noalign (looking-at "[^|\n\r]* |"))
19439 (c org-table-may-need-update))
19440 (replace-match
19441 (concat (substring (match-string 0) 1 -1) " |") nil t)
19442 (goto-char pos)
19443 ;; noalign: if there were two spaces at the end, this field
19444 ;; does not determine the width of the column.
19445 (if noalign (setq org-table-may-need-update c)))
19446 (delete-char N))
19447 (delete-char N)
19448 (org-fix-tags-on-the-fly))))
19450 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19451 (put 'org-self-insert-command 'delete-selection t)
19452 (put 'orgtbl-self-insert-command 'delete-selection t)
19453 (put 'org-delete-char 'delete-selection 'supersede)
19454 (put 'org-delete-backward-char 'delete-selection 'supersede)
19455 (put 'org-yank 'delete-selection 'yank)
19457 ;; Make `flyspell-mode' delay after some commands
19458 (put 'org-self-insert-command 'flyspell-delayed t)
19459 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19460 (put 'org-delete-char 'flyspell-delayed t)
19461 (put 'org-delete-backward-char 'flyspell-delayed t)
19463 ;; Make pabbrev-mode expand after org-mode commands
19464 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19465 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19467 ;; How to do this: Measure non-white length of current string
19468 ;; If equal to column width, we should realign.
19470 (defun org-remap (map &rest commands)
19471 "In MAP, remap the functions given in COMMANDS.
19472 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19473 (let (new old)
19474 (while commands
19475 (setq old (pop commands) new (pop commands))
19476 (if (fboundp 'command-remapping)
19477 (org-defkey map (vector 'remap old) new)
19478 (substitute-key-definition old new map global-map)))))
19480 (defun org-transpose-words ()
19481 "Transpose words for Org.
19482 This uses the `org-mode-transpose-word-syntax-table' syntax
19483 table, which interprets characters in `org-emphasis-alist' as
19484 word constituants."
19485 (interactive)
19486 (with-syntax-table org-mode-transpose-word-syntax-table
19487 (call-interactively 'transpose-words)))
19488 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19490 (when (eq org-enable-table-editor 'optimized)
19491 ;; If the user wants maximum table support, we need to hijack
19492 ;; some standard editing functions
19493 (org-remap org-mode-map
19494 'self-insert-command 'org-self-insert-command
19495 'delete-char 'org-delete-char
19496 'delete-backward-char 'org-delete-backward-char)
19497 (org-defkey org-mode-map "|" 'org-force-self-insert))
19499 (defvar org-ctrl-c-ctrl-c-hook nil
19500 "Hook for functions attaching themselves to `C-c C-c'.
19502 This can be used to add additional functionality to the C-c C-c
19503 key which executes context-dependent commands. This hook is run
19504 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19505 run after the last test.
19507 Each function will be called with no arguments. The function
19508 must check if the context is appropriate for it to act. If yes,
19509 it should do its thing and then return a non-nil value. If the
19510 context is wrong, just do nothing and return nil.")
19512 (defvar org-ctrl-c-ctrl-c-final-hook nil
19513 "Hook for functions attaching themselves to `C-c C-c'.
19515 This can be used to add additional functionality to the C-c C-c
19516 key which executes context-dependent commands. This hook is run
19517 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19518 before the first test.
19520 Each function will be called with no arguments. The function
19521 must check if the context is appropriate for it to act. If yes,
19522 it should do its thing and then return a non-nil value. If the
19523 context is wrong, just do nothing and return nil.")
19525 (defvar org-tab-first-hook nil
19526 "Hook for functions to attach themselves to TAB.
19527 See `org-ctrl-c-ctrl-c-hook' for more information.
19528 This hook runs as the first action when TAB is pressed, even before
19529 `org-cycle' messes around with the `outline-regexp' to cater for
19530 inline tasks and plain list item folding.
19531 If any function in this hook returns t, any other actions that
19532 would have been caused by TAB (such as table field motion or visibility
19533 cycling) will not occur.")
19535 (defvar org-tab-after-check-for-table-hook nil
19536 "Hook for functions to attach themselves to TAB.
19537 See `org-ctrl-c-ctrl-c-hook' for more information.
19538 This hook runs after it has been established that the cursor is not in a
19539 table, but before checking if the cursor is in a headline or if global cycling
19540 should be done.
19541 If any function in this hook returns t, not other actions like visibility
19542 cycling will be done.")
19544 (defvar org-tab-after-check-for-cycling-hook nil
19545 "Hook for functions to attach themselves to TAB.
19546 See `org-ctrl-c-ctrl-c-hook' for more information.
19547 This hook runs after it has been established that not table field motion and
19548 not visibility should be done because of current context. This is probably
19549 the place where a package like yasnippets can hook in.")
19551 (defvar org-tab-before-tab-emulation-hook nil
19552 "Hook for functions to attach themselves to TAB.
19553 See `org-ctrl-c-ctrl-c-hook' for more information.
19554 This hook runs after every other options for TAB have been exhausted, but
19555 before indentation and \t insertion takes place.")
19557 (defvar org-metaleft-hook nil
19558 "Hook for functions attaching themselves to `M-left'.
19559 See `org-ctrl-c-ctrl-c-hook' for more information.")
19560 (defvar org-metaright-hook nil
19561 "Hook for functions attaching themselves to `M-right'.
19562 See `org-ctrl-c-ctrl-c-hook' for more information.")
19563 (defvar org-metaup-hook nil
19564 "Hook for functions attaching themselves to `M-up'.
19565 See `org-ctrl-c-ctrl-c-hook' for more information.")
19566 (defvar org-metadown-hook nil
19567 "Hook for functions attaching themselves to `M-down'.
19568 See `org-ctrl-c-ctrl-c-hook' for more information.")
19569 (defvar org-shiftmetaleft-hook nil
19570 "Hook for functions attaching themselves to `M-S-left'.
19571 See `org-ctrl-c-ctrl-c-hook' for more information.")
19572 (defvar org-shiftmetaright-hook nil
19573 "Hook for functions attaching themselves to `M-S-right'.
19574 See `org-ctrl-c-ctrl-c-hook' for more information.")
19575 (defvar org-shiftmetaup-hook nil
19576 "Hook for functions attaching themselves to `M-S-up'.
19577 See `org-ctrl-c-ctrl-c-hook' for more information.")
19578 (defvar org-shiftmetadown-hook nil
19579 "Hook for functions attaching themselves to `M-S-down'.
19580 See `org-ctrl-c-ctrl-c-hook' for more information.")
19581 (defvar org-metareturn-hook nil
19582 "Hook for functions attaching themselves to `M-RET'.
19583 See `org-ctrl-c-ctrl-c-hook' for more information.")
19584 (defvar org-shiftup-hook nil
19585 "Hook for functions attaching themselves to `S-up'.
19586 See `org-ctrl-c-ctrl-c-hook' for more information.")
19587 (defvar org-shiftup-final-hook nil
19588 "Hook for functions attaching themselves to `S-up'.
19589 This one runs after all other options except shift-select have been excluded.
19590 See `org-ctrl-c-ctrl-c-hook' for more information.")
19591 (defvar org-shiftdown-hook nil
19592 "Hook for functions attaching themselves to `S-down'.
19593 See `org-ctrl-c-ctrl-c-hook' for more information.")
19594 (defvar org-shiftdown-final-hook nil
19595 "Hook for functions attaching themselves to `S-down'.
19596 This one runs after all other options except shift-select have been excluded.
19597 See `org-ctrl-c-ctrl-c-hook' for more information.")
19598 (defvar org-shiftleft-hook nil
19599 "Hook for functions attaching themselves to `S-left'.
19600 See `org-ctrl-c-ctrl-c-hook' for more information.")
19601 (defvar org-shiftleft-final-hook nil
19602 "Hook for functions attaching themselves to `S-left'.
19603 This one runs after all other options except shift-select have been excluded.
19604 See `org-ctrl-c-ctrl-c-hook' for more information.")
19605 (defvar org-shiftright-hook nil
19606 "Hook for functions attaching themselves to `S-right'.
19607 See `org-ctrl-c-ctrl-c-hook' for more information.")
19608 (defvar org-shiftright-final-hook nil
19609 "Hook for functions attaching themselves to `S-right'.
19610 This one runs after all other options except shift-select have been excluded.
19611 See `org-ctrl-c-ctrl-c-hook' for more information.")
19613 (defun org-modifier-cursor-error ()
19614 "Throw an error, a modified cursor command was applied in wrong context."
19615 (user-error "This command is active in special context like tables, headlines or items"))
19617 (defun org-shiftselect-error ()
19618 "Throw an error because Shift-Cursor command was applied in wrong context."
19619 (if (and (boundp 'shift-select-mode) shift-select-mode)
19620 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19621 (user-error "This command works only in special context like headlines or timestamps")))
19623 (defun org-call-for-shift-select (cmd)
19624 (let ((this-command-keys-shift-translated t))
19625 (call-interactively cmd)))
19627 (defun org-shifttab (&optional arg)
19628 "Global visibility cycling or move to previous table field.
19629 Call `org-table-previous-field' within a table.
19630 When ARG is nil, cycle globally through visibility states.
19631 When ARG is a numeric prefix, show contents of this level."
19632 (interactive "P")
19633 (cond
19634 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19635 ((integerp arg)
19636 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19637 (message "Content view to level: %d" arg)
19638 (org-content (prefix-numeric-value arg2))
19639 (org-cycle-show-empty-lines t)
19640 (setq org-cycle-global-status 'overview)))
19641 (t (call-interactively 'org-global-cycle))))
19643 (defun org-shiftmetaleft ()
19644 "Promote subtree or delete table column.
19645 Calls `org-promote-subtree', `org-outdent-item-tree', or
19646 `org-table-delete-column', depending on context. See the
19647 individual commands for more information."
19648 (interactive)
19649 (cond
19650 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19651 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19652 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19653 ((if (not (org-region-active-p)) (org-at-item-p)
19654 (save-excursion (goto-char (region-beginning))
19655 (org-at-item-p)))
19656 (call-interactively 'org-outdent-item-tree))
19657 (t (org-modifier-cursor-error))))
19659 (defun org-shiftmetaright ()
19660 "Demote subtree or insert table column.
19661 Calls `org-demote-subtree', `org-indent-item-tree', or
19662 `org-table-insert-column', depending on context. See the
19663 individual commands for more information."
19664 (interactive)
19665 (cond
19666 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19667 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19668 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19669 ((if (not (org-region-active-p)) (org-at-item-p)
19670 (save-excursion (goto-char (region-beginning))
19671 (org-at-item-p)))
19672 (call-interactively 'org-indent-item-tree))
19673 (t (org-modifier-cursor-error))))
19675 (defun org-shiftmetaup (&optional arg)
19676 "Move subtree up or kill table row.
19677 Calls `org-move-subtree-up' or `org-table-kill-row' or
19678 `org-move-item-up' or `org-timestamp-up', depending on context.
19679 See the individual commands for more information."
19680 (interactive "P")
19681 (cond
19682 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19683 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19684 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19685 ((org-at-item-p) (call-interactively 'org-move-item-up))
19686 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19687 (call-interactively 'org-timestamp-up)))
19688 (t (call-interactively 'org-drag-line-backward))))
19690 (defun org-shiftmetadown (&optional arg)
19691 "Move subtree down or insert table row.
19692 Calls `org-move-subtree-down' or `org-table-insert-row' or
19693 `org-move-item-down' or `org-timestamp-up', depending on context.
19694 See the individual commands for more information."
19695 (interactive "P")
19696 (cond
19697 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19698 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19699 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19700 ((org-at-item-p) (call-interactively 'org-move-item-down))
19701 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19702 (call-interactively 'org-timestamp-down)))
19703 (t (call-interactively 'org-drag-line-forward))))
19705 (defsubst org-hidden-tree-error ()
19706 (user-error
19707 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19709 (defun org-metaleft (&optional arg)
19710 "Promote heading or move table column to left.
19711 Calls `org-do-promote' or `org-table-move-column', depending on context.
19712 With no specific context, calls the Emacs default `backward-word'.
19713 See the individual commands for more information."
19714 (interactive "P")
19715 (cond
19716 ((run-hook-with-args-until-success 'org-metaleft-hook))
19717 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19718 ((org-with-limited-levels
19719 (or (org-at-heading-p)
19720 (and (org-region-active-p)
19721 (save-excursion
19722 (goto-char (region-beginning))
19723 (org-at-heading-p)))))
19724 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19725 (call-interactively 'org-do-promote))
19726 ;; At an inline task.
19727 ((org-at-heading-p)
19728 (call-interactively 'org-inlinetask-promote))
19729 ((or (org-at-item-p)
19730 (and (org-region-active-p)
19731 (save-excursion
19732 (goto-char (region-beginning))
19733 (org-at-item-p))))
19734 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19735 (call-interactively 'org-outdent-item))
19736 (t (call-interactively 'backward-word))))
19738 (defun org-metaright (&optional arg)
19739 "Demote a subtree, a list item or move table column to right.
19740 In front of a drawer or a block keyword, indent it correctly.
19741 With no specific context, calls the Emacs default `forward-word'.
19742 See the individual commands for more information."
19743 (interactive "P")
19744 (cond
19745 ((run-hook-with-args-until-success 'org-metaright-hook))
19746 ((org-at-table-p) (call-interactively 'org-table-move-column))
19747 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19748 ((org-at-block-p) (call-interactively 'org-indent-block))
19749 ((org-with-limited-levels
19750 (or (org-at-heading-p)
19751 (and (org-region-active-p)
19752 (save-excursion
19753 (goto-char (region-beginning))
19754 (org-at-heading-p)))))
19755 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19756 (call-interactively 'org-do-demote))
19757 ;; At an inline task.
19758 ((org-at-heading-p)
19759 (call-interactively 'org-inlinetask-demote))
19760 ((or (org-at-item-p)
19761 (and (org-region-active-p)
19762 (save-excursion
19763 (goto-char (region-beginning))
19764 (org-at-item-p))))
19765 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19766 (call-interactively 'org-indent-item))
19767 (t (call-interactively 'forward-word))))
19769 (defun org-check-for-hidden (what)
19770 "Check if there are hidden headlines/items in the current visual line.
19771 WHAT can be either `headlines' or `items'. If the current line is
19772 an outline or item heading and it has a folded subtree below it,
19773 this function returns t, nil otherwise."
19774 (let ((re (cond
19775 ((eq what 'headlines) org-outline-regexp-bol)
19776 ((eq what 'items) (org-item-beginning-re))
19777 (t (error "This should not happen"))))
19778 beg end)
19779 (save-excursion
19780 (catch 'exit
19781 (unless (org-region-active-p)
19782 (setq beg (point-at-bol))
19783 (beginning-of-line 2)
19784 (while (and (not (eobp)) ;; this is like `next-line'
19785 (get-char-property (1- (point)) 'invisible))
19786 (beginning-of-line 2))
19787 (setq end (point))
19788 (goto-char beg)
19789 (goto-char (point-at-eol))
19790 (setq end (max end (point)))
19791 (while (re-search-forward re end t)
19792 (if (get-char-property (match-beginning 0) 'invisible)
19793 (throw 'exit t))))
19794 nil))))
19796 (defun org-metaup (&optional arg)
19797 "Move subtree up or move table row up.
19798 Calls `org-move-subtree-up' or `org-table-move-row' or
19799 `org-move-item-up', depending on context. See the individual commands
19800 for more information."
19801 (interactive "P")
19802 (cond
19803 ((run-hook-with-args-until-success 'org-metaup-hook))
19804 ((org-region-active-p)
19805 (let* ((a (min (region-beginning) (region-end)))
19806 (b (1- (max (region-beginning) (region-end))))
19807 (c (save-excursion (goto-char a)
19808 (move-beginning-of-line 0)))
19809 (d (save-excursion (goto-char a)
19810 (move-end-of-line 0) (point))))
19811 (transpose-regions a b c d)
19812 (goto-char c)))
19813 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19814 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19815 ((org-at-item-p) (call-interactively 'org-move-item-up))
19816 (t (org-drag-element-backward))))
19818 (defun org-metadown (&optional arg)
19819 "Move subtree down or move table row down.
19820 Calls `org-move-subtree-down' or `org-table-move-row' or
19821 `org-move-item-down', depending on context. See the individual
19822 commands for more information."
19823 (interactive "P")
19824 (cond
19825 ((run-hook-with-args-until-success 'org-metadown-hook))
19826 ((org-region-active-p)
19827 (let* ((a (min (region-beginning) (region-end)))
19828 (b (max (region-beginning) (region-end)))
19829 (c (save-excursion (goto-char b)
19830 (move-beginning-of-line 1)))
19831 (d (save-excursion (goto-char b)
19832 (move-end-of-line 1) (1+ (point)))))
19833 (transpose-regions a b c d)
19834 (goto-char d)))
19835 ((org-at-table-p) (call-interactively 'org-table-move-row))
19836 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19837 ((org-at-item-p) (call-interactively 'org-move-item-down))
19838 (t (org-drag-element-forward))))
19840 (defun org-shiftup (&optional arg)
19841 "Increase item in timestamp or increase priority of current headline.
19842 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19843 depending on context. See the individual commands for more information."
19844 (interactive "P")
19845 (cond
19846 ((run-hook-with-args-until-success 'org-shiftup-hook))
19847 ((and org-support-shift-select (org-region-active-p))
19848 (org-call-for-shift-select 'previous-line))
19849 ((org-at-timestamp-p t)
19850 (call-interactively (if org-edit-timestamp-down-means-later
19851 'org-timestamp-down 'org-timestamp-up)))
19852 ((and (not (eq org-support-shift-select 'always))
19853 org-enable-priority-commands
19854 (org-at-heading-p))
19855 (call-interactively 'org-priority-up))
19856 ((and (not org-support-shift-select) (org-at-item-p))
19857 (call-interactively 'org-previous-item))
19858 ((org-clocktable-try-shift 'up arg))
19859 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19860 (org-support-shift-select
19861 (org-call-for-shift-select 'previous-line))
19862 (t (org-shiftselect-error))))
19864 (defun org-shiftdown (&optional arg)
19865 "Decrease item in timestamp or decrease priority of current headline.
19866 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19867 depending on context. See the individual commands for more information."
19868 (interactive "P")
19869 (cond
19870 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19871 ((and org-support-shift-select (org-region-active-p))
19872 (org-call-for-shift-select 'next-line))
19873 ((org-at-timestamp-p t)
19874 (call-interactively (if org-edit-timestamp-down-means-later
19875 'org-timestamp-up 'org-timestamp-down)))
19876 ((and (not (eq org-support-shift-select 'always))
19877 org-enable-priority-commands
19878 (org-at-heading-p))
19879 (call-interactively 'org-priority-down))
19880 ((and (not org-support-shift-select) (org-at-item-p))
19881 (call-interactively 'org-next-item))
19882 ((org-clocktable-try-shift 'down arg))
19883 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19884 (org-support-shift-select
19885 (org-call-for-shift-select 'next-line))
19886 (t (org-shiftselect-error))))
19888 (defun org-shiftright (&optional arg)
19889 "Cycle the thing at point or in the current line, depending on context.
19890 Depending on context, this does one of the following:
19892 - switch a timestamp at point one day into the future
19893 - on a headline, switch to the next TODO keyword.
19894 - on an item, switch entire list to the next bullet type
19895 - on a property line, switch to the next allowed value
19896 - on a clocktable definition line, move time block into the future"
19897 (interactive "P")
19898 (cond
19899 ((run-hook-with-args-until-success 'org-shiftright-hook))
19900 ((and org-support-shift-select (org-region-active-p))
19901 (org-call-for-shift-select 'forward-char))
19902 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19903 ((and (not (eq org-support-shift-select 'always))
19904 (org-at-heading-p))
19905 (let ((org-inhibit-logging
19906 (not org-treat-S-cursor-todo-selection-as-state-change))
19907 (org-inhibit-blocking
19908 (not org-treat-S-cursor-todo-selection-as-state-change)))
19909 (org-call-with-arg 'org-todo 'right)))
19910 ((or (and org-support-shift-select
19911 (not (eq org-support-shift-select 'always))
19912 (org-at-item-bullet-p))
19913 (and (not org-support-shift-select) (org-at-item-p)))
19914 (org-call-with-arg 'org-cycle-list-bullet nil))
19915 ((and (not (eq org-support-shift-select 'always))
19916 (org-at-property-p))
19917 (call-interactively 'org-property-next-allowed-value))
19918 ((org-clocktable-try-shift 'right arg))
19919 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19920 (org-support-shift-select
19921 (org-call-for-shift-select 'forward-char))
19922 (t (org-shiftselect-error))))
19924 (defun org-shiftleft (&optional arg)
19925 "Cycle the thing at point or in the current line, depending on context.
19926 Depending on context, this does one of the following:
19928 - switch a timestamp at point one day into the past
19929 - on a headline, switch to the previous TODO keyword.
19930 - on an item, switch entire list to the previous bullet type
19931 - on a property line, switch to the previous allowed value
19932 - on a clocktable definition line, move time block into the past"
19933 (interactive "P")
19934 (cond
19935 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19936 ((and org-support-shift-select (org-region-active-p))
19937 (org-call-for-shift-select 'backward-char))
19938 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19939 ((and (not (eq org-support-shift-select 'always))
19940 (org-at-heading-p))
19941 (let ((org-inhibit-logging
19942 (not org-treat-S-cursor-todo-selection-as-state-change))
19943 (org-inhibit-blocking
19944 (not org-treat-S-cursor-todo-selection-as-state-change)))
19945 (org-call-with-arg 'org-todo 'left)))
19946 ((or (and org-support-shift-select
19947 (not (eq org-support-shift-select 'always))
19948 (org-at-item-bullet-p))
19949 (and (not org-support-shift-select) (org-at-item-p)))
19950 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19951 ((and (not (eq org-support-shift-select 'always))
19952 (org-at-property-p))
19953 (call-interactively 'org-property-previous-allowed-value))
19954 ((org-clocktable-try-shift 'left arg))
19955 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19956 (org-support-shift-select
19957 (org-call-for-shift-select 'backward-char))
19958 (t (org-shiftselect-error))))
19960 (defun org-shiftcontrolright ()
19961 "Switch to next TODO set."
19962 (interactive)
19963 (cond
19964 ((and org-support-shift-select (org-region-active-p))
19965 (org-call-for-shift-select 'forward-word))
19966 ((and (not (eq org-support-shift-select 'always))
19967 (org-at-heading-p))
19968 (org-call-with-arg 'org-todo 'nextset))
19969 (org-support-shift-select
19970 (org-call-for-shift-select 'forward-word))
19971 (t (org-shiftselect-error))))
19973 (defun org-shiftcontrolleft ()
19974 "Switch to previous TODO set."
19975 (interactive)
19976 (cond
19977 ((and org-support-shift-select (org-region-active-p))
19978 (org-call-for-shift-select 'backward-word))
19979 ((and (not (eq org-support-shift-select 'always))
19980 (org-at-heading-p))
19981 (org-call-with-arg 'org-todo 'previousset))
19982 (org-support-shift-select
19983 (org-call-for-shift-select 'backward-word))
19984 (t (org-shiftselect-error))))
19986 (defun org-shiftcontrolup (&optional n)
19987 "Change timestamps synchronously up in CLOCK log lines.
19988 Optional argument N tells to change by that many units."
19989 (interactive "P")
19990 (cond ((and (not org-support-shift-select)
19991 (org-at-clock-log-p)
19992 (org-at-timestamp-p t))
19993 (org-clock-timestamps-up n))
19994 (t (org-shiftselect-error))))
19996 (defun org-shiftcontroldown (&optional n)
19997 "Change timestamps synchronously down in CLOCK log lines.
19998 Optional argument N tells to change by that many units."
19999 (interactive "P")
20000 (cond ((and (not org-support-shift-select)
20001 (org-at-clock-log-p)
20002 (org-at-timestamp-p t))
20003 (org-clock-timestamps-down n))
20004 (t (org-shiftselect-error))))
20006 (defun org-ctrl-c-ret ()
20007 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20008 (interactive)
20009 (cond
20010 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20011 (t (call-interactively 'org-insert-heading))))
20013 (defun org-find-visible ()
20014 (let ((s (point)))
20015 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20016 (get-char-property s 'invisible)))
20018 (defun org-find-invisible ()
20019 (let ((s (point)))
20020 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20021 (not (get-char-property s 'invisible))))
20024 (defun org-copy-visible (beg end)
20025 "Copy the visible parts of the region."
20026 (interactive "r")
20027 (let (snippets s)
20028 (save-excursion
20029 (save-restriction
20030 (narrow-to-region beg end)
20031 (setq s (goto-char (point-min)))
20032 (while (not (= (point) (point-max)))
20033 (goto-char (org-find-invisible))
20034 (push (buffer-substring s (point)) snippets)
20035 (setq s (goto-char (org-find-visible))))))
20036 (kill-new (apply 'concat (nreverse snippets)))))
20038 (defun org-copy-special ()
20039 "Copy region in table or copy current subtree.
20040 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20041 See the individual commands for more information."
20042 (interactive)
20043 (call-interactively
20044 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20046 (defun org-cut-special ()
20047 "Cut region in table or cut current subtree.
20048 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20049 See the individual commands for more information."
20050 (interactive)
20051 (call-interactively
20052 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20054 (defun org-paste-special (arg)
20055 "Paste rectangular region into table, or past subtree relative to level.
20056 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20057 See the individual commands for more information."
20058 (interactive "P")
20059 (if (org-at-table-p)
20060 (org-table-paste-rectangle)
20061 (org-paste-subtree arg)))
20063 (defsubst org-in-fixed-width-region-p ()
20064 "Is point in a fixed-width region?"
20065 (save-match-data
20066 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20068 (defun org-edit-special (&optional arg)
20069 "Call a special editor for the element at point.
20070 When at a table, call the formula editor with `org-table-edit-formulas'.
20071 When in a source code block, call `org-edit-src-code'.
20072 When in a fixed-width region, call `org-edit-fixed-width-region'.
20073 When at an #+INCLUDE keyword, visit the included file.
20074 On a link, call `ffap' to visit the link at point.
20075 Otherwise, return a user error."
20076 (interactive "P")
20077 (let ((element (org-element-at-point)))
20078 (assert (not buffer-read-only) nil
20079 "Buffer is read-only: %s" (buffer-name))
20080 (case (org-element-type element)
20081 (src-block
20082 (if (not arg) (org-edit-src-code)
20083 (let* ((info (org-babel-get-src-block-info))
20084 (lang (nth 0 info))
20085 (params (nth 2 info))
20086 (session (cdr (assq :session params))))
20087 (if (not session) (org-edit-src-code)
20088 ;; At a src-block with a session and function called with
20089 ;; an ARG: switch to the buffer related to the inferior
20090 ;; process.
20091 (switch-to-buffer
20092 (funcall (intern (concat "org-babel-prep-session:" lang))
20093 session params))))))
20094 (keyword
20095 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20096 (find-file
20097 (org-remove-double-quotes
20098 (car (org-split-string (org-element-property :value element)))))
20099 (user-error "No special environment to edit here")))
20100 (table
20101 (if (eq (org-element-property :type element) 'table.el)
20102 (org-edit-src-code)
20103 (call-interactively 'org-table-edit-formulas)))
20104 ;; Only Org tables contain `table-row' type elements.
20105 (table-row (call-interactively 'org-table-edit-formulas))
20106 ((example-block export-block) (org-edit-src-code))
20107 (fixed-width (org-edit-fixed-width-region))
20108 (otherwise
20109 ;; No notable element at point. Though, we may be at a link,
20110 ;; which is an object. Thus, scan deeper.
20111 (if (eq (org-element-type (org-element-context element)) 'link)
20112 (call-interactively 'ffap)
20113 (user-error "No special environment to edit here"))))))
20115 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20116 (defun org-ctrl-c-ctrl-c (&optional arg)
20117 "Set tags in headline, or update according to changed information at point.
20119 This command does many different things, depending on context:
20121 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20122 this is what we do.
20124 - If the cursor is on a statistics cookie, update it.
20126 - If the cursor is in a headline, prompt for tags and insert them
20127 into the current line, aligned to `org-tags-column'. When called
20128 with prefix arg, realign all tags in the current buffer.
20130 - If the cursor is in one of the special #+KEYWORD lines, this
20131 triggers scanning the buffer for these lines and updating the
20132 information.
20134 - If the cursor is inside a table, realign the table. This command
20135 works even if the automatic table editor has been turned off.
20137 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20138 the entire table.
20140 - If the cursor is at a footnote reference or definition, jump to
20141 the corresponding definition or references, respectively.
20143 - If the cursor is a the beginning of a dynamic block, update it.
20145 - If the current buffer is a capture buffer, close note and file it.
20147 - If the cursor is on a <<<target>>>, update radio targets and
20148 corresponding links in this buffer.
20150 - If the cursor is on a numbered item in a plain list, renumber the
20151 ordered list.
20153 - If the cursor is on a checkbox, toggle it.
20155 - If the cursor is on a code block, evaluate it. The variable
20156 `org-confirm-babel-evaluate' can be used to control prompting
20157 before code block evaluation, by default every code block
20158 evaluation requires confirmation. Code block evaluation can be
20159 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20160 (interactive "P")
20161 (cond
20162 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20163 org-occur-highlights
20164 org-latex-fragment-image-overlays)
20165 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20166 (org-remove-occur-highlights)
20167 (org-remove-latex-fragment-image-overlays)
20168 (message "Temporary highlights/overlays removed from current buffer"))
20169 ((and (local-variable-p 'org-finish-function (current-buffer))
20170 (fboundp org-finish-function))
20171 (funcall org-finish-function))
20172 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20174 (let* ((context (org-element-context)) (type (org-element-type context)))
20175 ;; Test if point is within a blank line.
20176 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20177 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20178 (user-error "C-c C-c can do nothing useful at this location"))
20179 ;; For convenience: at the first line of a paragraph on the
20180 ;; same line as an item, apply function on that item instead.
20181 (when (eq type 'paragraph)
20182 (let ((parent (org-element-property :parent context)))
20183 (when (and (eq (org-element-type parent) 'item)
20184 (= (point-at-bol) (org-element-property :begin parent)))
20185 (setq context parent type 'item))))
20186 ;; Act according to type of element or object at point.
20187 (case type
20188 (clock (org-clock-update-time-maybe))
20189 (dynamic-block
20190 (save-excursion
20191 (goto-char (org-element-property :post-affiliated context))
20192 (org-update-dblock)))
20193 (footnote-definition
20194 (goto-char (org-element-property :post-affiliated context))
20195 (call-interactively 'org-footnote-action))
20196 (footnote-reference (call-interactively 'org-footnote-action))
20197 ((headline inlinetask)
20198 (save-excursion (goto-char (org-element-property :begin context))
20199 (call-interactively 'org-set-tags)))
20200 (item
20201 ;; At an item: a double C-u set checkbox to "[-]"
20202 ;; unconditionally, whereas a single one will toggle its
20203 ;; presence. Without an universal argument, if the item
20204 ;; has a checkbox, toggle it. Otherwise repair the list.
20205 (let* ((box (org-element-property :checkbox context))
20206 (struct (org-element-property :structure context))
20207 (old-struct (copy-tree struct))
20208 (parents (org-list-parents-alist struct))
20209 (prevs (org-list-prevs-alist struct))
20210 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20211 (org-list-set-checkbox
20212 (org-element-property :begin context) struct
20213 (cond ((equal arg '(16)) "[-]")
20214 ((and (not box) (equal arg '(4))) "[ ]")
20215 ((or (not box) (equal arg '(4))) nil)
20216 ((eq box 'on) "[ ]")
20217 (t "[X]")))
20218 ;; Mimic `org-list-write-struct' but with grabbing
20219 ;; a return value from `org-list-struct-fix-box'.
20220 (org-list-struct-fix-ind struct parents 2)
20221 (org-list-struct-fix-item-end struct)
20222 (org-list-struct-fix-bul struct prevs)
20223 (org-list-struct-fix-ind struct parents)
20224 (let ((block-item
20225 (org-list-struct-fix-box struct parents prevs orderedp)))
20226 (if (and box (equal struct old-struct))
20227 (if (equal arg '(16))
20228 (message "Checkboxes already reset")
20229 (user-error "Cannot toggle this checkbox: %s"
20230 (if (eq box 'on)
20231 "all subitems checked"
20232 "unchecked subitems")))
20233 (org-list-struct-apply-struct struct old-struct)
20234 (org-update-checkbox-count-maybe))
20235 (when block-item
20236 (message "Checkboxes were removed due to empty box at line %d"
20237 (org-current-line block-item))))))
20238 (keyword
20239 (let ((org-inhibit-startup-visibility-stuff t)
20240 (org-startup-align-all-tables nil))
20241 (when (boundp 'org-table-coordinate-overlays)
20242 (mapc 'delete-overlay org-table-coordinate-overlays)
20243 (setq org-table-coordinate-overlays nil))
20244 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20245 (message "Local setup has been refreshed"))
20246 (plain-list
20247 ;; At a plain list, with a double C-u argument, set
20248 ;; checkboxes of each item to "[-]", whereas a single one
20249 ;; will toggle their presence according to the state of the
20250 ;; first item in the list. Without an argument, repair the
20251 ;; list.
20252 (let* ((begin (org-element-property :contents-begin context))
20253 (beginm (move-marker (make-marker) begin))
20254 (struct (org-element-property :structure context))
20255 (old-struct (copy-tree struct))
20256 (first-box (save-excursion
20257 (goto-char begin)
20258 (looking-at org-list-full-item-re)
20259 (match-string-no-properties 3)))
20260 (new-box (cond ((equal arg '(16)) "[-]")
20261 ((equal arg '(4)) (unless first-box "[ ]"))
20262 ((equal first-box "[X]") "[ ]")
20263 (t "[X]"))))
20264 (cond
20265 (arg
20266 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20267 (org-list-get-all-items
20268 begin struct (org-list-prevs-alist struct))))
20269 ((and first-box (eq (point) begin))
20270 ;; For convenience, when point is at bol on the first
20271 ;; item of the list and no argument is provided, simply
20272 ;; toggle checkbox of that item, if any.
20273 (org-list-set-checkbox begin struct new-box)))
20274 (org-list-write-struct
20275 struct (org-list-parents-alist struct) old-struct)
20276 (org-update-checkbox-count-maybe)
20277 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20278 ((property-drawer node-property)
20279 (call-interactively 'org-property-action))
20280 ((radio-target target)
20281 (call-interactively 'org-update-radio-target-regexp))
20282 (statistics-cookie
20283 (call-interactively 'org-update-statistics-cookies))
20284 ((table table-cell table-row)
20285 ;; At a table, recalculate every field and align it. Also
20286 ;; send the table if necessary. If the table has
20287 ;; a `table.el' type, just give up. At a table row or
20288 ;; cell, maybe recalculate line but always align table.
20289 (if (eq (org-element-property :type context) 'table.el)
20290 (message "Use C-c ' to edit table.el tables")
20291 (let ((org-enable-table-editor t))
20292 (if (or (eq type 'table)
20293 ;; Check if point is at a TBLFM line.
20294 (and (eq type 'table-row)
20295 (= (point) (org-element-property :end context))))
20296 (save-excursion
20297 (if (org-at-TBLFM-p)
20298 (progn (require 'org-table)
20299 (org-table-calc-current-TBLFM))
20300 (goto-char (org-element-property :contents-begin context))
20301 (org-call-with-arg 'org-table-recalculate (or arg t))
20302 (orgtbl-send-table 'maybe)))
20303 (org-table-maybe-eval-formula)
20304 (cond (arg (call-interactively 'org-table-recalculate))
20305 ((org-table-maybe-recalculate-line))
20306 (t (org-table-align)))))))
20307 (timestamp (org-timestamp-change 0 'day))
20308 (otherwise
20309 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20310 (user-error
20311 "C-c C-c can do nothing useful at this location")))))))))
20313 (defun org-mode-restart ()
20314 "Restart Org-mode, to scan again for special lines.
20315 Also updates the keyword regular expressions."
20316 (interactive)
20317 (org-mode)
20318 (message "Org-mode restarted"))
20320 (defun org-kill-note-or-show-branches ()
20321 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20322 (interactive)
20323 (if (not org-finish-function)
20324 (progn
20325 (hide-subtree)
20326 (call-interactively 'show-branches))
20327 (let ((org-note-abort t))
20328 (funcall org-finish-function))))
20330 (defun org-open-line (n)
20331 "Insert a new row in tables, call `open-line' elsewhere."
20332 (interactive "*p")
20333 (if (org-at-table-p)
20334 (org-table-insert-row)
20335 (open-line n)))
20337 (defun org-return (&optional indent)
20338 "Goto next table row or insert a newline.
20339 Calls `org-table-next-row' or `newline', depending on context.
20340 See the individual commands for more information."
20341 (interactive)
20342 (let (org-ts-what)
20343 (cond
20344 ((or (bobp) (org-in-src-block-p))
20345 (if indent (newline-and-indent) (newline)))
20346 ((org-at-table-p)
20347 (org-table-justify-field-maybe)
20348 (call-interactively 'org-table-next-row))
20349 ;; when `newline-and-indent' is called within a list, make sure
20350 ;; text moved stays inside the item.
20351 ((and (org-in-item-p) indent)
20352 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20353 (progn
20354 (save-match-data (newline))
20355 (org-indent-line-to (length (match-string 0))))
20356 (let ((ind (org-get-indentation)))
20357 (newline)
20358 (if (org-looking-back org-list-end-re)
20359 (org-indent-line)
20360 (org-indent-line-to ind)))))
20361 ((and org-return-follows-link
20362 (org-at-timestamp-p t)
20363 (not (eq org-ts-what 'after)))
20364 (org-follow-timestamp-link))
20365 ((and org-return-follows-link
20366 (let ((tprop (get-text-property (point) 'face)))
20367 (or (eq tprop 'org-link)
20368 (and (listp tprop) (memq 'org-link tprop)))))
20369 (call-interactively 'org-open-at-point))
20370 ((and (org-at-heading-p)
20371 (looking-at
20372 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20373 (org-show-entry)
20374 (end-of-line 1)
20375 (newline))
20376 (t (if indent (newline-and-indent) (newline))))))
20378 (defun org-return-indent ()
20379 "Goto next table row or insert a newline and indent.
20380 Calls `org-table-next-row' or `newline-and-indent', depending on
20381 context. See the individual commands for more information."
20382 (interactive)
20383 (org-return t))
20385 (defun org-ctrl-c-star ()
20386 "Compute table, or change heading status of lines.
20387 Calls `org-table-recalculate' or `org-toggle-heading',
20388 depending on context."
20389 (interactive)
20390 (cond
20391 ((org-at-table-p)
20392 (call-interactively 'org-table-recalculate))
20394 ;; Convert all lines in region to list items
20395 (call-interactively 'org-toggle-heading))))
20397 (defun org-ctrl-c-minus ()
20398 "Insert separator line in table or modify bullet status of line.
20399 Also turns a plain line or a region of lines into list items.
20400 Calls `org-table-insert-hline', `org-toggle-item', or
20401 `org-cycle-list-bullet', depending on context."
20402 (interactive)
20403 (cond
20404 ((org-at-table-p)
20405 (call-interactively 'org-table-insert-hline))
20406 ((org-region-active-p)
20407 (call-interactively 'org-toggle-item))
20408 ((org-in-item-p)
20409 (call-interactively 'org-cycle-list-bullet))
20411 (call-interactively 'org-toggle-item))))
20413 (defun org-toggle-item (arg)
20414 "Convert headings or normal lines to items, items to normal lines.
20415 If there is no active region, only the current line is considered.
20417 If the first non blank line in the region is a headline, convert
20418 all headlines to items, shifting text accordingly.
20420 If it is an item, convert all items to normal lines.
20422 If it is normal text, change region into a list of items.
20423 With a prefix argument ARG, change the region in a single item."
20424 (interactive "P")
20425 (let ((shift-text
20426 (function
20427 ;; Shift text in current section to IND, from point to END.
20428 ;; The function leaves point to END line.
20429 (lambda (ind end)
20430 (let ((min-i 1000) (end (copy-marker end)))
20431 ;; First determine the minimum indentation (MIN-I) of
20432 ;; the text.
20433 (save-excursion
20434 (catch 'exit
20435 (while (< (point) end)
20436 (let ((i (org-get-indentation)))
20437 (cond
20438 ;; Skip blank lines and inline tasks.
20439 ((looking-at "^[ \t]*$"))
20440 ((looking-at org-outline-regexp-bol))
20441 ;; We can't find less than 0 indentation.
20442 ((zerop i) (throw 'exit (setq min-i 0)))
20443 ((< i min-i) (setq min-i i))))
20444 (forward-line))))
20445 ;; Then indent each line so that a line indented to
20446 ;; MIN-I becomes indented to IND. Ignore blank lines
20447 ;; and inline tasks in the process.
20448 (let ((delta (- ind min-i)))
20449 (while (< (point) end)
20450 (unless (or (looking-at "^[ \t]*$")
20451 (looking-at org-outline-regexp-bol))
20452 (org-indent-line-to (+ (org-get-indentation) delta)))
20453 (forward-line)))))))
20454 (skip-blanks
20455 (function
20456 ;; Return beginning of first non-blank line, starting from
20457 ;; line at POS.
20458 (lambda (pos)
20459 (save-excursion
20460 (goto-char pos)
20461 (skip-chars-forward " \r\t\n")
20462 (point-at-bol)))))
20463 beg end)
20464 ;; Determine boundaries of changes.
20465 (if (org-region-active-p)
20466 (setq beg (funcall skip-blanks (region-beginning))
20467 end (copy-marker (region-end)))
20468 (setq beg (funcall skip-blanks (point-at-bol))
20469 end (copy-marker (point-at-eol))))
20470 ;; Depending on the starting line, choose an action on the text
20471 ;; between BEG and END.
20472 (org-with-limited-levels
20473 (save-excursion
20474 (goto-char beg)
20475 (cond
20476 ;; Case 1. Start at an item: de-itemize. Note that it only
20477 ;; happens when a region is active: `org-ctrl-c-minus'
20478 ;; would call `org-cycle-list-bullet' otherwise.
20479 ((org-at-item-p)
20480 (while (< (point) end)
20481 (when (org-at-item-p)
20482 (skip-chars-forward " \t")
20483 (delete-region (point) (match-end 0)))
20484 (forward-line)))
20485 ;; Case 2. Start at an heading: convert to items.
20486 ((org-at-heading-p)
20487 (let* ((bul (org-list-bullet-string "-"))
20488 (bul-len (length bul))
20489 ;; Indentation of the first heading. It should be
20490 ;; relative to the indentation of its parent, if any.
20491 (start-ind (save-excursion
20492 (cond
20493 ((not org-adapt-indentation) 0)
20494 ((not (outline-previous-heading)) 0)
20495 (t (length (match-string 0))))))
20496 ;; Level of first heading. Further headings will be
20497 ;; compared to it to determine hierarchy in the list.
20498 (ref-level (org-reduced-level (org-outline-level))))
20499 (while (< (point) end)
20500 (let* ((level (org-reduced-level (org-outline-level)))
20501 (delta (max 0 (- level ref-level))))
20502 ;; If current headline is less indented than the first
20503 ;; one, set it as reference, in order to preserve
20504 ;; subtrees.
20505 (when (< level ref-level) (setq ref-level level))
20506 (replace-match bul t t)
20507 (org-indent-line-to (+ start-ind (* delta bul-len)))
20508 ;; Ensure all text down to END (or SECTION-END) belongs
20509 ;; to the newly created item.
20510 (let ((section-end (save-excursion
20511 (or (outline-next-heading) (point)))))
20512 (forward-line)
20513 (funcall shift-text
20514 (+ start-ind (* (1+ delta) bul-len))
20515 (min end section-end)))))))
20516 ;; Case 3. Normal line with ARG: make the first line of region
20517 ;; an item, and shift indentation of others lines to
20518 ;; set them as item's body.
20519 (arg (let* ((bul (org-list-bullet-string "-"))
20520 (bul-len (length bul))
20521 (ref-ind (org-get-indentation)))
20522 (skip-chars-forward " \t")
20523 (insert bul)
20524 (forward-line)
20525 (while (< (point) end)
20526 ;; Ensure that lines less indented than first one
20527 ;; still get included in item body.
20528 (funcall shift-text
20529 (+ ref-ind bul-len)
20530 (min end (save-excursion (or (outline-next-heading)
20531 (point)))))
20532 (forward-line))))
20533 ;; Case 4. Normal line without ARG: turn each non-item line
20534 ;; into an item.
20536 (while (< (point) end)
20537 (unless (or (org-at-heading-p) (org-at-item-p))
20538 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20539 (replace-match
20540 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20541 (forward-line))))))))
20543 (defun org-toggle-heading (&optional nstars)
20544 "Convert headings to normal text, or items or text to headings.
20545 If there is no active region, only convert the current line.
20547 With a \\[universal-argument] prefix, convert the whole list at
20548 point into heading.
20550 In a region:
20552 - If the first non blank line is a headline, remove the stars
20553 from all headlines in the region.
20555 - If it is a normal line, turn each and every normal line (i.e.,
20556 not an heading or an item) in the region into headings. If you
20557 want to convert only the first line of this region, use one
20558 universal prefix argument.
20560 - If it is a plain list item, turn all plain list items into headings.
20562 When converting a line into a heading, the number of stars is chosen
20563 such that the lines become children of the current entry. However,
20564 when a numeric prefix argument is given, its value determines the
20565 number of stars to add."
20566 (interactive "P")
20567 (let ((skip-blanks
20568 (function
20569 ;; Return beginning of first non-blank line, starting from
20570 ;; line at POS.
20571 (lambda (pos)
20572 (save-excursion
20573 (goto-char pos)
20574 (while (org-at-comment-p) (forward-line))
20575 (skip-chars-forward " \r\t\n")
20576 (point-at-bol)))))
20577 beg end toggled)
20578 ;; Determine boundaries of changes. If a universal prefix has
20579 ;; been given, put the list in a region. If region ends at a bol,
20580 ;; do not consider the last line to be in the region.
20582 (when (and current-prefix-arg (org-at-item-p))
20583 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20584 (org-mark-element))
20586 (if (org-region-active-p)
20587 (setq beg (funcall skip-blanks (region-beginning))
20588 end (copy-marker (save-excursion
20589 (goto-char (region-end))
20590 (if (bolp) (point) (point-at-eol)))))
20591 (setq beg (funcall skip-blanks (point-at-bol))
20592 end (copy-marker (point-at-eol))))
20593 ;; Ensure inline tasks don't count as headings.
20594 (org-with-limited-levels
20595 (save-excursion
20596 (goto-char beg)
20597 (cond
20598 ;; Case 1. Started at an heading: de-star headings.
20599 ((org-at-heading-p)
20600 (while (< (point) end)
20601 (when (org-at-heading-p t)
20602 (looking-at org-outline-regexp) (replace-match "")
20603 (setq toggled t))
20604 (forward-line)))
20605 ;; Case 2. Started at an item: change items into headlines.
20606 ;; One star will be added by `org-list-to-subtree'.
20607 ((org-at-item-p)
20608 (let* ((stars (make-string
20609 ;; subtract the star that will be added again by
20610 ;; `org-list-to-subtree'
20611 (if (numberp nstars) (1- nstars)
20612 (or (org-current-level) 0))
20613 ?*))
20614 (add-stars
20615 (cond (nstars "") ; stars from prefix only
20616 ((equal stars "") "") ; before first heading
20617 (org-odd-levels-only "*") ; inside heading, odd
20618 (t "")))) ; inside heading, oddeven
20619 (while (< (point) end)
20620 (when (org-at-item-p)
20621 ;; Pay attention to cases when region ends before list.
20622 (let* ((struct (org-list-struct))
20623 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20624 (save-restriction
20625 (narrow-to-region (point) list-end)
20626 (insert
20627 (org-list-to-subtree
20628 (org-list-parse-list t)
20629 '(:istart (concat stars add-stars (funcall get-stars depth))
20630 :icount (concat stars add-stars (funcall get-stars depth)))))))
20631 (setq toggled t))
20632 (forward-line))))
20633 ;; Case 3. Started at normal text: make every line an heading,
20634 ;; skipping headlines and items.
20635 (t (let* ((stars
20636 (make-string
20637 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20638 (add-stars
20639 (cond (nstars "") ; stars from prefix only
20640 ((equal stars "") "*") ; before first heading
20641 (org-odd-levels-only "**") ; inside heading, odd
20642 (t "*"))) ; inside heading, oddeven
20643 (rpl (concat stars add-stars " "))
20644 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20645 (while (< (point) (if (equal nstars '(4)) lend end))
20646 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20647 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20648 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20649 (forward-line)))))))
20650 (unless toggled (message "Cannot toggle heading from here"))))
20652 (defun org-meta-return (&optional arg)
20653 "Insert a new heading or wrap a region in a table.
20654 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20655 See the individual commands for more information."
20656 (interactive "P")
20657 (org-check-before-invisible-edit 'insert)
20658 (cond
20659 ((run-hook-with-args-until-success 'org-metareturn-hook))
20660 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20661 (newline-and-indent))
20662 ((org-at-table-p)
20663 (call-interactively 'org-table-wrap-region))
20664 (t (call-interactively 'org-insert-heading))))
20666 ;;; Menu entries
20668 (defsubst org-in-subtree-not-table-p ()
20669 "Are we in a subtree and not in a table?"
20670 (and (not (org-before-first-heading-p))
20671 (not (org-at-table-p))))
20673 ;; Define the Org-mode menus
20674 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20675 '("Tbl"
20676 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20677 ["Next Field" org-cycle (org-at-table-p)]
20678 ["Previous Field" org-shifttab (org-at-table-p)]
20679 ["Next Row" org-return (org-at-table-p)]
20680 "--"
20681 ["Blank Field" org-table-blank-field (org-at-table-p)]
20682 ["Edit Field" org-table-edit-field (org-at-table-p)]
20683 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20684 "--"
20685 ("Column"
20686 ["Move Column Left" org-metaleft (org-at-table-p)]
20687 ["Move Column Right" org-metaright (org-at-table-p)]
20688 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20689 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20690 ("Row"
20691 ["Move Row Up" org-metaup (org-at-table-p)]
20692 ["Move Row Down" org-metadown (org-at-table-p)]
20693 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20694 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20695 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20696 "--"
20697 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20698 ("Rectangle"
20699 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20700 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20701 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20702 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20703 "--"
20704 ("Calculate"
20705 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20706 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20707 ["Edit Formulas" org-edit-special (org-at-table-p)]
20708 "--"
20709 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20710 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20711 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20712 "--"
20713 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20714 "--"
20715 ["Sum Column/Rectangle" org-table-sum
20716 (or (org-at-table-p) (org-region-active-p))]
20717 ["Which Column?" org-table-current-column (org-at-table-p)])
20718 ["Debug Formulas"
20719 org-table-toggle-formula-debugger
20720 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20721 ["Show Col/Row Numbers"
20722 org-table-toggle-coordinate-overlays
20723 :style toggle
20724 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20725 "--"
20726 ["Create" org-table-create (and (not (org-at-table-p))
20727 org-enable-table-editor)]
20728 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20729 ["Import from File" org-table-import (not (org-at-table-p))]
20730 ["Export to File" org-table-export (org-at-table-p)]
20731 "--"
20732 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20734 (easy-menu-define org-org-menu org-mode-map "Org menu"
20735 '("Org"
20736 ("Show/Hide"
20737 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20738 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20739 ["Sparse Tree..." org-sparse-tree t]
20740 ["Reveal Context" org-reveal t]
20741 ["Show All" show-all t]
20742 "--"
20743 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20744 "--"
20745 ["New Heading" org-insert-heading t]
20746 ("Navigate Headings"
20747 ["Up" outline-up-heading t]
20748 ["Next" outline-next-visible-heading t]
20749 ["Previous" outline-previous-visible-heading t]
20750 ["Next Same Level" outline-forward-same-level t]
20751 ["Previous Same Level" outline-backward-same-level t]
20752 "--"
20753 ["Jump" org-goto t])
20754 ("Edit Structure"
20755 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20756 "--"
20757 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20758 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20759 "--"
20760 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20761 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20762 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20763 "--"
20764 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20765 "--"
20766 ["Copy visible text" org-copy-visible t]
20767 "--"
20768 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20769 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20770 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20771 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20772 "--"
20773 ["Sort Region/Children" org-sort t]
20774 "--"
20775 ["Convert to odd levels" org-convert-to-odd-levels t]
20776 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20777 ("Editing"
20778 ["Emphasis..." org-emphasize t]
20779 ["Edit Source Example" org-edit-special t]
20780 "--"
20781 ["Footnote new/jump" org-footnote-action t]
20782 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20783 ("Archive"
20784 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20785 "--"
20786 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20787 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20788 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20790 "--"
20791 ("Hyperlinks"
20792 ["Store Link (Global)" org-store-link t]
20793 ["Find existing link to here" org-occur-link-in-agenda-files t]
20794 ["Insert Link" org-insert-link t]
20795 ["Follow Link" org-open-at-point t]
20796 "--"
20797 ["Next link" org-next-link t]
20798 ["Previous link" org-previous-link t]
20799 "--"
20800 ["Descriptive Links"
20801 org-toggle-link-display
20802 :style radio
20803 :selected org-descriptive-links
20805 ["Literal Links"
20806 org-toggle-link-display
20807 :style radio
20808 :selected (not org-descriptive-links)])
20809 "--"
20810 ("TODO Lists"
20811 ["TODO/DONE/-" org-todo t]
20812 ("Select keyword"
20813 ["Next keyword" org-shiftright (org-at-heading-p)]
20814 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20815 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20816 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20817 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20818 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20819 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20820 "--"
20821 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20822 :selected org-enforce-todo-dependencies :style toggle :active t]
20823 "Settings for tree at point"
20824 ["Do Children sequentially" org-toggle-ordered-property :style radio
20825 :selected (org-entry-get nil "ORDERED")
20826 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20827 ["Do Children parallel" org-toggle-ordered-property :style radio
20828 :selected (not (org-entry-get nil "ORDERED"))
20829 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20830 "--"
20831 ["Set Priority" org-priority t]
20832 ["Priority Up" org-shiftup t]
20833 ["Priority Down" org-shiftdown t]
20834 "--"
20835 ["Get news from all feeds" org-feed-update-all t]
20836 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20837 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20838 ("TAGS and Properties"
20839 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20840 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20841 "--"
20842 ["Set property" org-set-property (not (org-before-first-heading-p))]
20843 ["Column view of properties" org-columns t]
20844 ["Insert Column View DBlock" org-insert-columns-dblock t])
20845 ("Dates and Scheduling"
20846 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20847 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20848 ("Change Date"
20849 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20850 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20851 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20852 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20853 ["Compute Time Range" org-evaluate-time-range t]
20854 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20855 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20856 "--"
20857 ["Custom time format" org-toggle-time-stamp-overlays
20858 :style radio :selected org-display-custom-times]
20859 "--"
20860 ["Goto Calendar" org-goto-calendar t]
20861 ["Date from Calendar" org-date-from-calendar t]
20862 "--"
20863 ["Start/Restart Timer" org-timer-start t]
20864 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20865 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20866 ["Insert Timer String" org-timer t]
20867 ["Insert Timer Item" org-timer-item t])
20868 ("Logging work"
20869 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20870 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20871 ["Clock out" org-clock-out t]
20872 ["Clock cancel" org-clock-cancel t]
20873 "--"
20874 ["Mark as default task" org-clock-mark-default-task t]
20875 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20876 ["Goto running clock" org-clock-goto t]
20877 "--"
20878 ["Display times" org-clock-display t]
20879 ["Create clock table" org-clock-report t]
20880 "--"
20881 ["Record DONE time"
20882 (progn (setq org-log-done (not org-log-done))
20883 (message "Switching to %s will %s record a timestamp"
20884 (car org-done-keywords)
20885 (if org-log-done "automatically" "not")))
20886 :style toggle :selected org-log-done])
20887 "--"
20888 ["Agenda Command..." org-agenda t]
20889 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20890 ("File List for Agenda")
20891 ("Special views current file"
20892 ["TODO Tree" org-show-todo-tree t]
20893 ["Check Deadlines" org-check-deadlines t]
20894 ["Timeline" org-timeline t]
20895 ["Tags/Property tree" org-match-sparse-tree t])
20896 "--"
20897 ["Export/Publish..." org-export-dispatch t]
20898 ("LaTeX"
20899 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20900 :selected org-cdlatex-mode]
20901 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20902 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20903 ["Modify math symbol" org-cdlatex-math-modify
20904 (org-inside-LaTeX-fragment-p)]
20905 ["Insert citation" org-reftex-citation t]
20906 "--"
20907 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20908 "--"
20909 ("MobileOrg"
20910 ["Push Files and Views" org-mobile-push t]
20911 ["Get Captured and Flagged" org-mobile-pull t]
20912 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20913 "--"
20914 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20915 "--"
20916 ("Documentation"
20917 ["Show Version" org-version t]
20918 ["Info Documentation" org-info t])
20919 ("Customize"
20920 ["Browse Org Group" org-customize t]
20921 "--"
20922 ["Expand This Menu" org-create-customize-menu
20923 (fboundp 'customize-menu-create)])
20924 ["Send bug report" org-submit-bug-report t]
20925 "--"
20926 ("Refresh/Reload"
20927 ["Refresh setup current buffer" org-mode-restart t]
20928 ["Reload Org (after update)" org-reload t]
20929 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20932 (defun org-info (&optional node)
20933 "Read documentation for Org-mode in the info system.
20934 With optional NODE, go directly to that node."
20935 (interactive)
20936 (info (format "(org)%s" (or node ""))))
20938 ;;;###autoload
20939 (defun org-submit-bug-report ()
20940 "Submit a bug report on Org-mode via mail.
20942 Don't hesitate to report any problems or inaccurate documentation.
20944 If you don't have setup sending mail from (X)Emacs, please copy the
20945 output buffer into your mail program, as it gives us important
20946 information about your Org-mode version and configuration."
20947 (interactive)
20948 (require 'reporter)
20949 (org-load-modules-maybe)
20950 (org-require-autoloaded-modules)
20951 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20952 (reporter-submit-bug-report
20953 "emacs-orgmode@gnu.org"
20954 (org-version nil 'full)
20955 (let (list)
20956 (save-window-excursion
20957 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20958 (delete-other-windows)
20959 (erase-buffer)
20960 (insert "You are about to submit a bug report to the Org-mode mailing list.
20962 We would like to add your full Org-mode and Outline configuration to the
20963 bug report. This greatly simplifies the work of the maintainer and
20964 other experts on the mailing list.
20966 HOWEVER, some variables you have customized may contain private
20967 information. The names of customers, colleagues, or friends, might
20968 appear in the form of file names, tags, todo states, or search strings.
20969 If you answer yes to the prompt, you might want to check and remove
20970 such private information before sending the email.")
20971 (add-text-properties (point-min) (point-max) '(face org-warning))
20972 (when (yes-or-no-p "Include your Org-mode configuration ")
20973 (mapatoms
20974 (lambda (v)
20975 (and (boundp v)
20976 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20977 (or (and (symbol-value v)
20978 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20979 (and
20980 (get v 'custom-type) (get v 'standard-value)
20981 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20982 (push v list)))))
20983 (kill-buffer (get-buffer "*Warn about privacy*"))
20984 list))
20985 nil nil
20986 "Remember to cover the basics, that is, what you expected to happen and
20987 what in fact did happen. You don't know how to make a good report? See
20989 http://orgmode.org/manual/Feedback.html#Feedback
20991 Your bug report will be posted to the Org-mode mailing list.
20992 ------------------------------------------------------------------------")
20993 (save-excursion
20994 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20995 (replace-match "\\1Bug: \\3 [\\2]")))))
20998 (defun org-install-agenda-files-menu ()
20999 (let ((bl (buffer-list)))
21000 (save-excursion
21001 (while bl
21002 (set-buffer (pop bl))
21003 (if (derived-mode-p 'org-mode) (setq bl nil)))
21004 (when (derived-mode-p 'org-mode)
21005 (easy-menu-change
21006 '("Org") "File List for Agenda"
21007 (append
21008 (list
21009 ["Edit File List" (org-edit-agenda-file-list) t]
21010 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21011 ["Remove Current File from List" org-remove-file t]
21012 ["Cycle through agenda files" org-cycle-agenda-files t]
21013 ["Occur in all agenda files" org-occur-in-agenda-files t]
21014 "--")
21015 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21017 ;;;; Documentation
21019 (defun org-require-autoloaded-modules ()
21020 (interactive)
21021 (mapc 'require
21022 '(org-agenda org-archive org-attach org-clock org-colview org-id
21023 org-remember org-table org-timer)))
21025 ;;;###autoload
21026 (defun org-reload (&optional uncompiled)
21027 "Reload all org lisp files.
21028 With prefix arg UNCOMPILED, load the uncompiled versions."
21029 (interactive "P")
21030 (require 'loadhist)
21031 (let* ((org-dir (org-find-library-dir "org"))
21032 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21033 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21034 (remove-re (mapconcat 'identity
21035 (mapcar (lambda (f) (concat "^" f "$"))
21036 (list (if (featurep 'xemacs)
21037 "org-colview"
21038 "org-colview-xemacs")
21039 "org" "org-loaddefs" "org-version"))
21040 "\\|"))
21041 (feats (delete-dups
21042 (mapcar 'file-name-sans-extension
21043 (mapcar 'file-name-nondirectory
21044 (delq nil
21045 (mapcar 'feature-file
21046 features))))))
21047 (lfeat (append
21048 (sort
21049 (setq feats
21050 (delq nil (mapcar
21051 (lambda (f)
21052 (if (and (string-match feature-re f)
21053 (not (string-match remove-re f)))
21054 f nil))
21055 feats)))
21056 'string-lessp)
21057 (list "org-version" "org")))
21058 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21059 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21060 load-uncore load-misses)
21061 (setq load-misses
21062 (delq 't
21063 (mapcar (lambda (f)
21064 (or (org-load-noerror-mustsuffix (concat org-dir f))
21065 (and (string= org-dir contrib-dir)
21066 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21067 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21068 (add-to-list 'load-uncore f 'append)
21071 lfeat)))
21072 (if load-uncore
21073 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21074 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21075 (if load-misses
21076 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21077 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21078 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21080 ;;;###autoload
21081 (defun org-customize ()
21082 "Call the customize function with org as argument."
21083 (interactive)
21084 (org-load-modules-maybe)
21085 (org-require-autoloaded-modules)
21086 (customize-browse 'org))
21088 (defun org-create-customize-menu ()
21089 "Create a full customization menu for Org-mode, insert it into the menu."
21090 (interactive)
21091 (org-load-modules-maybe)
21092 (org-require-autoloaded-modules)
21093 (if (fboundp 'customize-menu-create)
21094 (progn
21095 (easy-menu-change
21096 '("Org") "Customize"
21097 `(["Browse Org group" org-customize t]
21098 "--"
21099 ,(customize-menu-create 'org)
21100 ["Set" Custom-set t]
21101 ["Save" Custom-save t]
21102 ["Reset to Current" Custom-reset-current t]
21103 ["Reset to Saved" Custom-reset-saved t]
21104 ["Reset to Standard Settings" Custom-reset-standard t]))
21105 (message "\"Org\"-menu now contains full customization menu"))
21106 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21108 ;;;; Miscellaneous stuff
21110 ;;; Generally useful functions
21112 (defun org-get-at-bol (property)
21113 "Get text property PROPERTY at beginning of line."
21114 (get-text-property (point-at-bol) property))
21116 (defun org-find-text-property-in-string (prop s)
21117 "Return the first non-nil value of property PROP in string S."
21118 (or (get-text-property 0 prop s)
21119 (get-text-property (or (next-single-property-change 0 prop s) 0)
21120 prop s)))
21122 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21123 "Display the given MESSAGE as a warning."
21124 (if (fboundp 'display-warning)
21125 (display-warning 'org message
21126 (if (featurep 'xemacs) 'warning :warning))
21127 (let ((buf (get-buffer-create "*Org warnings*")))
21128 (with-current-buffer buf
21129 (goto-char (point-max))
21130 (insert "Warning (Org): " message)
21131 (unless (bolp)
21132 (newline)))
21133 (display-buffer buf)
21134 (sit-for 0))))
21136 (defun org-eval (form)
21137 "Eval FORM and return result."
21138 (condition-case error
21139 (eval form)
21140 (error (format "%%![Error: %s]" error))))
21142 (defun org-in-clocktable-p ()
21143 "Check if the cursor is in a clocktable."
21144 (let ((pos (point)) start)
21145 (save-excursion
21146 (end-of-line 1)
21147 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21148 (setq start (match-beginning 0))
21149 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21150 (>= (match-end 0) pos)
21151 start))))
21153 (defun org-in-commented-line ()
21154 "Is point in a line starting with `#'?"
21155 (equal (char-after (point-at-bol)) ?#))
21157 (defun org-in-indented-comment-line ()
21158 "Is point in a line starting with `#' after some white space?"
21159 (save-excursion
21160 (save-match-data
21161 (goto-char (point-at-bol))
21162 (looking-at "[ \t]*#"))))
21164 (defun org-in-verbatim-emphasis ()
21165 (save-match-data
21166 (and (org-in-regexp org-emph-re 2)
21167 (>= (point) (match-beginning 3))
21168 (<= (point) (match-end 4))
21169 (member (match-string 3) '("=" "~")))))
21171 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21172 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21173 (if (and marker (marker-buffer marker)
21174 (buffer-live-p (marker-buffer marker)))
21175 (progn
21176 (org-pop-to-buffer-same-window (marker-buffer marker))
21177 (if (or (> marker (point-max)) (< marker (point-min)))
21178 (widen))
21179 (goto-char marker)
21180 (org-show-context 'org-goto))
21181 (if bookmark
21182 (bookmark-jump bookmark)
21183 (error "Cannot find location"))))
21185 (defun org-quote-csv-field (s)
21186 "Quote field for inclusion in CSV material."
21187 (if (string-match "[\",]" s)
21188 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21191 (defun org-force-self-insert (N)
21192 "Needed to enforce self-insert under remapping."
21193 (interactive "p")
21194 (self-insert-command N))
21196 (defun org-string-width (s)
21197 "Compute width of string, ignoring invisible characters.
21198 This ignores character with invisibility property `org-link', and also
21199 characters with property `org-cwidth', because these will become invisible
21200 upon the next fontification round."
21201 (let (b l)
21202 (when (or (eq t buffer-invisibility-spec)
21203 (assq 'org-link buffer-invisibility-spec))
21204 (while (setq b (text-property-any 0 (length s)
21205 'invisible 'org-link s))
21206 (setq s (concat (substring s 0 b)
21207 (substring s (or (next-single-property-change
21208 b 'invisible s) (length s)))))))
21209 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21210 (setq s (concat (substring s 0 b)
21211 (substring s (or (next-single-property-change
21212 b 'org-cwidth s) (length s))))))
21213 (setq l (string-width s) b -1)
21214 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21215 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21218 (defun org-shorten-string (s maxlength)
21219 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21220 If the string is shorter or has length MAXLENGTH, just return the
21221 original string. If it is longer, the functions finds a space in the
21222 string, breaks this string off at that locations and adds three dots
21223 as ellipsis. Including the ellipsis, the string will not be longer
21224 than MAXLENGTH. If finding a good breaking point in the string does
21225 not work, the string is just chopped off in the middle of a word
21226 if necessary."
21227 (if (<= (length s) maxlength)
21229 (let* ((n (max (- maxlength 4) 1))
21230 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21231 (if (string-match re s)
21232 (concat (match-string 1 s) "...")
21233 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21235 (defun org-get-indentation (&optional line)
21236 "Get the indentation of the current line, interpreting tabs.
21237 When LINE is given, assume it represents a line and compute its indentation."
21238 (if line
21239 (if (string-match "^ *" (org-remove-tabs line))
21240 (match-end 0))
21241 (save-excursion
21242 (beginning-of-line 1)
21243 (skip-chars-forward " \t")
21244 (current-column))))
21246 (defun org-get-string-indentation (s)
21247 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21248 (let ((n -1) (i 0) (w tab-width) c)
21249 (catch 'exit
21250 (while (< (setq n (1+ n)) (length s))
21251 (setq c (aref s n))
21252 (cond ((= c ?\ ) (setq i (1+ i)))
21253 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21254 (t (throw 'exit t)))))
21257 (defun org-remove-tabs (s &optional width)
21258 "Replace tabulators in S with spaces.
21259 Assumes that s is a single line, starting in column 0."
21260 (setq width (or width tab-width))
21261 (while (string-match "\t" s)
21262 (setq s (replace-match
21263 (make-string
21264 (- (* width (/ (+ (match-beginning 0) width) width))
21265 (match-beginning 0)) ?\ )
21266 t t s)))
21269 (defun org-fix-indentation (line ind)
21270 "Fix indentation in LINE.
21271 IND is a cons cell with target and minimum indentation.
21272 If the current indentation in LINE is smaller than the minimum,
21273 leave it alone. If it is larger than ind, set it to the target."
21274 (let* ((l (org-remove-tabs line))
21275 (i (org-get-indentation l))
21276 (i1 (car ind)) (i2 (cdr ind)))
21277 (if (>= i i2) (setq l (substring line i2)))
21278 (if (> i1 0)
21279 (concat (make-string i1 ?\ ) l)
21280 l)))
21282 (defun org-remove-indentation (code &optional n)
21283 "Remove the maximum common indentation from the lines in CODE.
21284 N may optionally be the number of spaces to remove."
21285 (with-temp-buffer
21286 (insert code)
21287 (org-do-remove-indentation n)
21288 (buffer-string)))
21290 (defun org-do-remove-indentation (&optional n)
21291 "Remove the maximum common indentation from the buffer."
21292 (untabify (point-min) (point-max))
21293 (let ((min 10000) re)
21294 (if n
21295 (setq min n)
21296 (goto-char (point-min))
21297 (while (re-search-forward "^ *[^ \n]" nil t)
21298 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21299 (unless (or (= min 0) (= min 10000))
21300 (setq re (format "^ \\{%d\\}" min))
21301 (goto-char (point-min))
21302 (while (re-search-forward re nil t)
21303 (replace-match "")
21304 (end-of-line 1))
21305 min)))
21307 (defun org-fill-template (template alist)
21308 "Find each %key of ALIST in TEMPLATE and replace it."
21309 (let ((case-fold-search nil)
21310 entry key value)
21311 (setq alist (sort (copy-sequence alist)
21312 (lambda (a b) (< (length (car a)) (length (car b))))))
21313 (while (setq entry (pop alist))
21314 (setq template
21315 (replace-regexp-in-string
21316 (concat "%" (regexp-quote (car entry)))
21317 (or (cdr entry) "") template t t)))
21318 template))
21320 (defun org-base-buffer (buffer)
21321 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21322 (if (not buffer)
21323 buffer
21324 (or (buffer-base-buffer buffer)
21325 buffer)))
21327 (defun org-trim (s)
21328 "Remove whitespace at beginning and end of string."
21329 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21330 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21333 (defun org-wrap (string &optional width lines)
21334 "Wrap string to either a number of lines, or a width in characters.
21335 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21336 that costs. If there is a word longer than WIDTH, the text is actually
21337 wrapped to the length of that word.
21338 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21339 many lines, whatever width that takes.
21340 The return value is a list of lines, without newlines at the end."
21341 (let* ((words (org-split-string string "[ \t\n]+"))
21342 (maxword (apply 'max (mapcar 'org-string-width words)))
21343 w ll)
21344 (cond (width
21345 (org-do-wrap words (max maxword width)))
21346 (lines
21347 (setq w maxword)
21348 (setq ll (org-do-wrap words maxword))
21349 (if (<= (length ll) lines)
21351 (setq ll words)
21352 (while (> (length ll) lines)
21353 (setq w (1+ w))
21354 (setq ll (org-do-wrap words w)))
21355 ll))
21356 (t (error "Cannot wrap this")))))
21358 (defun org-do-wrap (words width)
21359 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21360 (let (lines line)
21361 (while words
21362 (setq line (pop words))
21363 (while (and words (< (+ (length line) (length (car words))) width))
21364 (setq line (concat line " " (pop words))))
21365 (setq lines (push line lines)))
21366 (nreverse lines)))
21368 (defun org-split-string (string &optional separators)
21369 "Splits STRING into substrings at SEPARATORS.
21370 No empty strings are returned if there are matches at the beginning
21371 and end of string."
21372 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21373 (start 0)
21374 notfirst
21375 (list nil))
21376 (while (and (string-match rexp string
21377 (if (and notfirst
21378 (= start (match-beginning 0))
21379 (< start (length string)))
21380 (1+ start) start))
21381 (< (match-beginning 0) (length string)))
21382 (setq notfirst t)
21383 (or (eq (match-beginning 0) 0)
21384 (and (eq (match-beginning 0) (match-end 0))
21385 (eq (match-beginning 0) start))
21386 (setq list
21387 (cons (substring string start (match-beginning 0))
21388 list)))
21389 (setq start (match-end 0)))
21390 (or (eq start (length string))
21391 (setq list
21392 (cons (substring string start)
21393 list)))
21394 (nreverse list)))
21396 (defun org-quote-vert (s)
21397 "Replace \"|\" with \"\\vert\"."
21398 (while (string-match "|" s)
21399 (setq s (replace-match "\\vert" t t s)))
21402 (defun org-uuidgen-p (s)
21403 "Is S an ID created by UUIDGEN?"
21404 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21406 (defun org-in-src-block-p (&optional inside)
21407 "Whether point is in a code source block.
21408 When INSIDE is non-nil, don't consider we are within a src block
21409 when point is at #+BEGIN_SRC or #+END_SRC."
21410 (let ((case-fold-search t) ov)
21411 (or (and (setq ov (overlays-at (point)))
21412 (memq 'org-block-background
21413 (overlay-properties (car ov))))
21414 (and (not inside)
21415 (save-match-data
21416 (save-excursion
21417 (beginning-of-line)
21418 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21420 (defun org-context ()
21421 "Return a list of contexts of the current cursor position.
21422 If several contexts apply, all are returned.
21423 Each context entry is a list with a symbol naming the context, and
21424 two positions indicating start and end of the context. Possible
21425 contexts are:
21427 :headline anywhere in a headline
21428 :headline-stars on the leading stars in a headline
21429 :todo-keyword on a TODO keyword (including DONE) in a headline
21430 :tags on the TAGS in a headline
21431 :priority on the priority cookie in a headline
21432 :item on the first line of a plain list item
21433 :item-bullet on the bullet/number of a plain list item
21434 :checkbox on the checkbox in a plain list item
21435 :table in an org-mode table
21436 :table-special on a special filed in a table
21437 :table-table in a table.el table
21438 :clocktable in a clocktable
21439 :src-block in a source block
21440 :link on a hyperlink
21441 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21442 :target on a <<target>>
21443 :radio-target on a <<<radio-target>>>
21444 :latex-fragment on a LaTeX fragment
21445 :latex-preview on a LaTeX fragment with overlaid preview image
21447 This function expects the position to be visible because it uses font-lock
21448 faces as a help to recognize the following contexts: :table-special, :link,
21449 and :keyword."
21450 (let* ((f (get-text-property (point) 'face))
21451 (faces (if (listp f) f (list f)))
21452 (case-fold-search t)
21453 (p (point)) clist o)
21454 ;; First the large context
21455 (cond
21456 ((org-at-heading-p t)
21457 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21458 (when (progn
21459 (beginning-of-line 1)
21460 (looking-at org-todo-line-tags-regexp))
21461 (push (org-point-in-group p 1 :headline-stars) clist)
21462 (push (org-point-in-group p 2 :todo-keyword) clist)
21463 (push (org-point-in-group p 4 :tags) clist))
21464 (goto-char p)
21465 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21466 (if (looking-at "\\[#[A-Z0-9]\\]")
21467 (push (org-point-in-group p 0 :priority) clist)))
21469 ((org-at-item-p)
21470 (push (org-point-in-group p 2 :item-bullet) clist)
21471 (push (list :item (point-at-bol)
21472 (save-excursion (org-end-of-item) (point)))
21473 clist)
21474 (and (org-at-item-checkbox-p)
21475 (push (org-point-in-group p 0 :checkbox) clist)))
21477 ((org-at-table-p)
21478 (push (list :table (org-table-begin) (org-table-end)) clist)
21479 (if (memq 'org-formula faces)
21480 (push (list :table-special
21481 (previous-single-property-change p 'face)
21482 (next-single-property-change p 'face)) clist)))
21483 ((org-at-table-p 'any)
21484 (push (list :table-table) clist)))
21485 (goto-char p)
21487 (let ((case-fold-search t))
21488 ;; New the "medium" contexts: clocktables, source blocks
21489 (cond ((org-in-clocktable-p)
21490 (push (list :clocktable
21491 (and (or (looking-at "#\\+BEGIN: clocktable")
21492 (search-backward "#+BEGIN: clocktable" nil t))
21493 (match-beginning 0))
21494 (and (re-search-forward "#\\+END:?" nil t)
21495 (match-end 0))) clist))
21496 ((org-in-src-block-p)
21497 (push (list :src-block
21498 (and (or (looking-at "#\\+BEGIN_SRC")
21499 (search-backward "#+BEGIN_SRC" nil t))
21500 (match-beginning 0))
21501 (and (search-forward "#+END_SRC" nil t)
21502 (match-beginning 0))) clist))))
21503 (goto-char p)
21505 ;; Now the small context
21506 (cond
21507 ((org-at-timestamp-p)
21508 (push (org-point-in-group p 0 :timestamp) clist))
21509 ((memq 'org-link faces)
21510 (push (list :link
21511 (previous-single-property-change p 'face)
21512 (next-single-property-change p 'face)) clist))
21513 ((memq 'org-special-keyword faces)
21514 (push (list :keyword
21515 (previous-single-property-change p 'face)
21516 (next-single-property-change p 'face)) clist))
21517 ((org-at-target-p)
21518 (push (org-point-in-group p 0 :target) clist)
21519 (goto-char (1- (match-beginning 0)))
21520 (if (looking-at org-radio-target-regexp)
21521 (push (org-point-in-group p 0 :radio-target) clist))
21522 (goto-char p))
21523 ((setq o (car (delq nil
21524 (mapcar
21525 (lambda (x)
21526 (if (memq x org-latex-fragment-image-overlays) x))
21527 (overlays-at (point))))))
21528 (push (list :latex-fragment
21529 (overlay-start o) (overlay-end o)) clist)
21530 (push (list :latex-preview
21531 (overlay-start o) (overlay-end o)) clist))
21532 ((org-inside-LaTeX-fragment-p)
21533 ;; FIXME: positions wrong.
21534 (push (list :latex-fragment (point) (point)) clist)))
21536 (setq clist (nreverse (delq nil clist)))
21537 clist))
21539 ;; FIXME: Compare with at-regexp-p Do we need both?
21540 (defun org-in-regexp (re &optional nlines visually)
21541 "Check if point is inside a match of regexp.
21542 Normally only the current line is checked, but you can include NLINES extra
21543 lines both before and after point into the search.
21544 If VISUALLY is set, require that the cursor is not after the match but
21545 really on, so that the block visually is on the match."
21546 (catch 'exit
21547 (let ((pos (point))
21548 (eol (point-at-eol (+ 1 (or nlines 0))))
21549 (inc (if visually 1 0)))
21550 (save-excursion
21551 (beginning-of-line (- 1 (or nlines 0)))
21552 (while (re-search-forward re eol t)
21553 (if (and (<= (match-beginning 0) pos)
21554 (>= (+ inc (match-end 0)) pos))
21555 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21557 (defun org-at-regexp-p (regexp)
21558 "Is point inside a match of REGEXP in the current line?"
21559 (catch 'exit
21560 (save-excursion
21561 (let ((pos (point)) (end (point-at-eol)))
21562 (beginning-of-line 1)
21563 (while (re-search-forward regexp end t)
21564 (if (and (<= (match-beginning 0) pos)
21565 (>= (match-end 0) pos))
21566 (throw 'exit t)))
21567 nil))))
21569 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21570 "Non-nil when point is between matches of START-RE and END-RE.
21572 Also return a non-nil value when point is on one of the matches.
21574 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21575 buffer positions. Default values are the positions of headlines
21576 surrounding the point.
21578 The functions returns a cons cell whose car (resp. cdr) is the
21579 position before START-RE (resp. after END-RE)."
21580 (save-match-data
21581 (let ((pos (point))
21582 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21583 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21584 beg end)
21585 (save-excursion
21586 ;; Point is on a block when on START-RE or if START-RE can be
21587 ;; found before it...
21588 (and (or (org-at-regexp-p start-re)
21589 (re-search-backward start-re limit-up t))
21590 (setq beg (match-beginning 0))
21591 ;; ... and END-RE after it...
21592 (goto-char (match-end 0))
21593 (re-search-forward end-re limit-down t)
21594 (> (setq end (match-end 0)) pos)
21595 ;; ... without another START-RE in-between.
21596 (goto-char (match-beginning 0))
21597 (not (re-search-backward start-re (1+ beg) t))
21598 ;; Return value.
21599 (cons beg end))))))
21601 (defun org-in-block-p (names)
21602 "Non-nil when point belongs to a block whose name belongs to NAMES.
21604 NAMES is a list of strings containing names of blocks.
21606 Return first block name matched, or nil. Beware that in case of
21607 nested blocks, the returned name may not belong to the closest
21608 block from point."
21609 (save-match-data
21610 (catch 'exit
21611 (let ((case-fold-search t)
21612 (lim-up (save-excursion (outline-previous-heading)))
21613 (lim-down (save-excursion (outline-next-heading))))
21614 (mapc (lambda (name)
21615 (let ((n (regexp-quote name)))
21616 (when (org-between-regexps-p
21617 (concat "^[ \t]*#\\+begin_" n)
21618 (concat "^[ \t]*#\\+end_" n)
21619 lim-up lim-down)
21620 (throw 'exit n))))
21621 names))
21622 nil)))
21624 (defun org-in-drawer-p ()
21625 "Is point within a drawer?"
21626 (save-match-data
21627 (let ((case-fold-search t)
21628 (lim-up (save-excursion (outline-previous-heading)))
21629 (lim-down (save-excursion (outline-next-heading))))
21630 (org-between-regexps-p
21631 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21632 "^[ \t]*:end:.*$"
21633 lim-up lim-down))))
21635 (defun org-occur-in-agenda-files (regexp &optional nlines)
21636 "Call `multi-occur' with buffers for all agenda files."
21637 (interactive "sOrg-files matching: \np")
21638 (let* ((files (org-agenda-files))
21639 (tnames (mapcar 'file-truename files))
21640 (extra org-agenda-text-search-extra-files)
21642 (when (eq (car extra) 'agenda-archives)
21643 (setq extra (cdr extra))
21644 (setq files (org-add-archive-files files)))
21645 (while (setq f (pop extra))
21646 (unless (member (file-truename f) tnames)
21647 (add-to-list 'files f 'append)
21648 (add-to-list 'tnames (file-truename f) 'append)))
21649 (multi-occur
21650 (mapcar (lambda (x)
21651 (with-current-buffer
21652 (or (get-file-buffer x) (find-file-noselect x))
21653 (widen)
21654 (current-buffer)))
21655 files)
21656 regexp)))
21658 (if (boundp 'occur-mode-find-occurrence-hook)
21659 ;; Emacs 23
21660 (add-hook 'occur-mode-find-occurrence-hook
21661 (lambda ()
21662 (when (derived-mode-p 'org-mode)
21663 (org-reveal))))
21664 ;; Emacs 22
21665 (defadvice occur-mode-goto-occurrence
21666 (after org-occur-reveal activate)
21667 (and (derived-mode-p 'org-mode) (org-reveal)))
21668 (defadvice occur-mode-goto-occurrence-other-window
21669 (after org-occur-reveal activate)
21670 (and (derived-mode-p 'org-mode) (org-reveal)))
21671 (defadvice occur-mode-display-occurrence
21672 (after org-occur-reveal activate)
21673 (when (derived-mode-p 'org-mode)
21674 (let ((pos (occur-mode-find-occurrence)))
21675 (with-current-buffer (marker-buffer pos)
21676 (save-excursion
21677 (goto-char pos)
21678 (org-reveal)))))))
21680 (defun org-occur-link-in-agenda-files ()
21681 "Create a link and search for it in the agendas.
21682 The link is not stored in `org-stored-links', it is just created
21683 for the search purpose."
21684 (interactive)
21685 (let ((link (condition-case nil
21686 (org-store-link nil)
21687 (error "Unable to create a link to here"))))
21688 (org-occur-in-agenda-files (regexp-quote link))))
21690 (defun org-reverse-string (string)
21691 "Return the reverse of STRING."
21692 (apply 'string (reverse (string-to-list string))))
21694 (defsubst org-uniquify (list)
21695 "Non-destructively remove duplicate elements from LIST."
21696 (let ((res (copy-sequence list))) (delete-dups res)))
21698 (defun org-uniquify-alist (alist)
21699 "Merge elements of ALIST with the same key.
21701 For example, in this alist:
21703 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21704 => '((a 1 3) (b 2))
21706 merge (a 1) and (a 3) into (a 1 3).
21708 The function returns the new ALIST."
21709 (let (rtn)
21710 (mapc
21711 (lambda (e)
21712 (let (n)
21713 (if (not (assoc (car e) rtn))
21714 (push e rtn)
21715 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21716 (setq rtn (assq-delete-all (car e) rtn))
21717 (push n rtn))))
21718 alist)
21719 rtn))
21721 (defun org-delete-all (elts list)
21722 "Remove all elements in ELTS from LIST."
21723 (while elts
21724 (setq list (delete (pop elts) list)))
21725 list)
21727 (defun org-count (cl-item cl-seq)
21728 "Count the number of occurrences of ITEM in SEQ.
21729 Taken from `count' in cl-seq.el with all keyword arguments removed."
21730 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21731 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21732 (while (< cl-start cl-end)
21733 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21734 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21735 (setq cl-start (1+ cl-start)))
21736 cl-count))
21738 (defun org-remove-if (predicate seq)
21739 "Remove everything from SEQ that fulfills PREDICATE."
21740 (let (res e)
21741 (while seq
21742 (setq e (pop seq))
21743 (if (not (funcall predicate e)) (push e res)))
21744 (nreverse res)))
21746 (defun org-remove-if-not (predicate seq)
21747 "Remove everything from SEQ that does not fulfill PREDICATE."
21748 (let (res e)
21749 (while seq
21750 (setq e (pop seq))
21751 (if (funcall predicate e) (push e res)))
21752 (nreverse res)))
21754 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21755 "Reduce two-argument FUNCTION across SEQ.
21756 Taken from `reduce' in cl-seq.el with all keyword arguments but
21757 \":initial-value\" removed."
21758 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21759 (cadr (memq :initial-value cl-keys)))
21760 (cl-seq (pop cl-seq))
21761 (t (funcall cl-func)))))
21762 (while cl-seq
21763 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21764 cl-accum))
21766 (defun org-every (pred seq)
21767 "Return true if PREDICATE is true of every element of SEQ.
21768 Adapted from `every' in cl.el."
21769 (catch 'org-every
21770 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21773 (defun org-some (pred seq)
21774 "Return true if PREDICATE is true of any element of SEQ.
21775 Adapted from `some' in cl.el."
21776 (catch 'org-some
21777 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21778 nil))
21780 (defun org-back-over-empty-lines ()
21781 "Move backwards over whitespace, to the beginning of the first empty line.
21782 Returns the number of empty lines passed."
21783 (let ((pos (point)))
21784 (if (cdr (assoc 'heading org-blank-before-new-entry))
21785 (skip-chars-backward " \t\n\r")
21786 (unless (eobp)
21787 (forward-line -1)))
21788 (beginning-of-line 2)
21789 (goto-char (min (point) pos))
21790 (count-lines (point) pos)))
21792 (defun org-skip-whitespace ()
21793 (skip-chars-forward " \t\n\r"))
21795 (defun org-point-in-group (point group &optional context)
21796 "Check if POINT is in match-group GROUP.
21797 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21798 match. If the match group does not exist or point is not inside it,
21799 return nil."
21800 (and (match-beginning group)
21801 (>= point (match-beginning group))
21802 (<= point (match-end group))
21803 (if context
21804 (list context (match-beginning group) (match-end group))
21805 t)))
21807 (defun org-switch-to-buffer-other-window (&rest args)
21808 "Switch to buffer in a second window on the current frame.
21809 In particular, do not allow pop-up frames.
21810 Returns the newly created buffer."
21811 (org-no-popups
21812 (apply 'switch-to-buffer-other-window args)))
21814 (defun org-combine-plists (&rest plists)
21815 "Create a single property list from all plists in PLISTS.
21816 The process starts by copying the first list, and then setting properties
21817 from the other lists. Settings in the last list are the most significant
21818 ones and overrule settings in the other lists."
21819 (let ((rtn (copy-sequence (pop plists)))
21820 p v ls)
21821 (while plists
21822 (setq ls (pop plists))
21823 (while ls
21824 (setq p (pop ls) v (pop ls))
21825 (setq rtn (plist-put rtn p v))))
21826 rtn))
21828 (defun org-replace-escapes (string table)
21829 "Replace %-escapes in STRING with values in TABLE.
21830 TABLE is an association list with keys like \"%a\" and string values.
21831 The sequences in STRING may contain normal field width and padding information,
21832 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21833 so values can contain further %-escapes if they are define later in TABLE."
21834 (let ((tbl (copy-alist table))
21835 (case-fold-search nil)
21836 (pchg 0)
21837 e re rpl)
21838 (while (setq e (pop tbl))
21839 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21840 (when (and (cdr e) (string-match re (cdr e)))
21841 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21842 (safe "SREF"))
21843 (add-text-properties 0 3 (list 'sref sref) safe)
21844 (setcdr e (replace-match safe t t (cdr e)))))
21845 (while (string-match re string)
21846 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21847 (cdr e)))
21848 (setq string (replace-match rpl t t string))))
21849 (while (setq pchg (next-property-change pchg string))
21850 (let ((sref (get-text-property pchg 'sref string)))
21851 (when (and sref (string-match "SREF" string pchg))
21852 (setq string (replace-match sref t t string)))))
21853 string))
21855 (defun org-sublist (list start end)
21856 "Return a section of LIST, from START to END.
21857 Counting starts at 1."
21858 (let (rtn (c start))
21859 (setq list (nthcdr (1- start) list))
21860 (while (and list (<= c end))
21861 (push (pop list) rtn)
21862 (setq c (1+ c)))
21863 (nreverse rtn)))
21865 (defun org-find-base-buffer-visiting (file)
21866 "Like `find-buffer-visiting' but always return the base buffer and
21867 not an indirect buffer."
21868 (let ((buf (or (get-file-buffer file)
21869 (find-buffer-visiting file))))
21870 (if buf
21871 (or (buffer-base-buffer buf) buf)
21872 nil)))
21874 (defun org-image-file-name-regexp (&optional extensions)
21875 "Return regexp matching the file names of images.
21876 If EXTENSIONS is given, only match these."
21877 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21878 (image-file-name-regexp)
21879 (let ((image-file-name-extensions
21880 (or extensions
21881 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21882 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21883 (concat "\\."
21884 (regexp-opt (nconc (mapcar 'upcase
21885 image-file-name-extensions)
21886 image-file-name-extensions)
21888 "\\'"))))
21890 (defun org-file-image-p (file &optional extensions)
21891 "Return non-nil if FILE is an image."
21892 (save-match-data
21893 (string-match (org-image-file-name-regexp extensions) file)))
21895 (defun org-get-cursor-date (&optional with-time)
21896 "Return the date at cursor in as a time.
21897 This works in the calendar and in the agenda, anywhere else it just
21898 returns the current time.
21899 If WITH-TIME is non-nil, returns the time of the event at point (in
21900 the agenda) or the current time of the day."
21901 (let (date day defd tp tm hod mod)
21902 (when with-time
21903 (setq tp (get-text-property (point) 'time))
21904 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21905 (setq hod (string-to-number (match-string 1 tp))
21906 mod (string-to-number (match-string 2 tp))))
21907 (or tp (setq hod (nth 2 (decode-time (current-time)))
21908 mod (nth 1 (decode-time (current-time))))))
21909 (cond
21910 ((eq major-mode 'calendar-mode)
21911 (setq date (calendar-cursor-to-date)
21912 defd (encode-time 0 (or mod 0) (or hod 0)
21913 (nth 1 date) (nth 0 date) (nth 2 date))))
21914 ((eq major-mode 'org-agenda-mode)
21915 (setq day (get-text-property (point) 'day))
21916 (if day
21917 (setq date (calendar-gregorian-from-absolute day)
21918 defd (encode-time 0 (or mod 0) (or hod 0)
21919 (nth 1 date) (nth 0 date) (nth 2 date))))))
21920 (or defd (current-time))))
21922 (defun org-mark-subtree (&optional up)
21923 "Mark the current subtree.
21924 This puts point at the start of the current subtree, and mark at
21925 the end. If a numeric prefix UP is given, move up into the
21926 hierarchy of headlines by UP levels before marking the subtree."
21927 (interactive "P")
21928 (org-with-limited-levels
21929 (cond ((org-at-heading-p) (beginning-of-line))
21930 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21931 (t (outline-previous-visible-heading 1))))
21932 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21933 (if (org-called-interactively-p 'any)
21934 (call-interactively 'org-mark-element)
21935 (org-mark-element)))
21938 ;;; Indentation
21940 (defun org-indent-line ()
21941 "Indent line depending on context."
21942 (interactive)
21943 (let* ((pos (point))
21944 (itemp (org-at-item-p))
21945 (case-fold-search t)
21946 (org-drawer-regexp (or org-drawer-regexp "\000"))
21947 (inline-task-p (and (featurep 'org-inlinetask)
21948 (org-inlinetask-in-task-p)))
21949 (inline-re (and inline-task-p
21950 (org-inlinetask-outline-regexp)))
21951 column)
21952 (if (and orgstruct-is-++ (eq pos (point)))
21953 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21954 (indent-according-to-mode))
21955 (beginning-of-line 1)
21956 (cond
21957 ;; Headings
21958 ((looking-at org-outline-regexp) (setq column 0))
21959 ;; Footnote definition
21960 ((looking-at org-footnote-definition-re) (setq column 0))
21961 ;; Literal examples
21962 ((looking-at "[ \t]*:\\( \\|$\\)")
21963 (setq column (org-get-indentation))) ; do nothing
21964 ;; Lists
21965 ((ignore-errors (goto-char (org-in-item-p)))
21966 (setq column (if itemp
21967 (org-get-indentation)
21968 (org-list-item-body-column (point))))
21969 (goto-char pos))
21970 ;; Drawers
21971 ((and (looking-at "[ \t]*:END:")
21972 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21973 (save-excursion
21974 (goto-char (1- (match-beginning 1)))
21975 (setq column (current-column))))
21976 ;; Special blocks
21977 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21978 (save-excursion
21979 (re-search-backward
21980 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21981 (setq column (org-get-indentation (match-string 0))))
21982 ((and (not (looking-at "[ \t]*#\\+begin_"))
21983 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21984 (save-excursion
21985 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21986 (setq column
21987 (cond ((equal (downcase (match-string 1)) "src")
21988 ;; src blocks: let `org-edit-src-exit' handle them
21989 (org-get-indentation))
21990 ((equal (downcase (match-string 1)) "example")
21991 (max (org-get-indentation)
21992 (org-get-indentation (match-string 0))))
21994 (org-get-indentation (match-string 0))))))
21995 ;; This line has nothing special, look at the previous relevant
21996 ;; line to compute indentation
21998 (beginning-of-line 0)
21999 (while (and (not (bobp))
22000 (not (looking-at org-table-line-regexp))
22001 (not (looking-at org-drawer-regexp))
22002 ;; When point started in an inline task, do not move
22003 ;; above task starting line.
22004 (not (and inline-task-p (looking-at inline-re)))
22005 ;; Skip drawers, blocks, empty lines, verbatim,
22006 ;; comments, tables, footnotes definitions, lists,
22007 ;; inline tasks.
22008 (or (and (looking-at "[ \t]*:END:")
22009 (re-search-backward org-drawer-regexp nil t))
22010 (and (looking-at "[ \t]*#\\+end_")
22011 (re-search-backward "[ \t]*#\\+begin_"nil t))
22012 (looking-at "[ \t]*[\n:#|]")
22013 (looking-at org-footnote-definition-re)
22014 (and (not inline-task-p)
22015 (featurep 'org-inlinetask)
22016 (org-inlinetask-in-task-p)
22017 (or (org-inlinetask-goto-beginning) t))))
22018 (beginning-of-line 0))
22019 (cond
22020 ;; There was a list item above.
22021 ((save-excursion
22022 (and (ignore-errors (goto-char (org-in-item-p)))
22023 (goto-char
22024 (org-list-get-top-point (org-list-struct)))))
22025 (looking-at org-list-full-item-re)
22026 (setq column (length (match-string 0))))
22027 ;; There was an heading above.
22028 ((looking-at "\\*+[ \t]+")
22029 (if (not org-adapt-indentation)
22030 (setq column 0)
22031 (goto-char (match-end 0))
22032 (setq column (current-column))))
22033 ;; A drawer had started and is unfinished
22034 ((looking-at org-drawer-regexp)
22035 (goto-char (1- (match-beginning 1)))
22036 (setq column (current-column)))
22037 ;; Else, nothing noticeable found: get indentation and go on.
22038 (t (setq column (org-get-indentation))))))
22039 ;; Now apply indentation and move cursor accordingly
22040 (goto-char pos)
22041 (if (<= (current-column) (current-indentation))
22042 (org-indent-line-to column)
22043 (save-excursion (org-indent-line-to column)))
22044 ;; Special polishing for properties, see `org-property-format'
22045 (setq column (current-column))
22046 (beginning-of-line 1)
22047 (if (looking-at org-property-re)
22048 (replace-match (concat (match-string 4)
22049 (format org-property-format
22050 (match-string 1) (match-string 3)))
22051 t t))
22052 (org-move-to-column column))))
22054 (defun org-indent-drawer ()
22055 "Indent the drawer at point."
22056 (interactive)
22057 (let ((p (point))
22058 (e (and (save-excursion (re-search-forward ":END:" nil t))
22059 (match-end 0)))
22060 (folded
22061 (save-excursion
22062 (end-of-line)
22063 (when (overlays-at (point))
22064 (member 'invisible (overlay-properties
22065 (car (overlays-at (point)))))))))
22066 (when folded (org-cycle))
22067 (indent-for-tab-command)
22068 (while (and (move-beginning-of-line 2) (< (point) e))
22069 (indent-for-tab-command))
22070 (goto-char p)
22071 (when folded (org-cycle)))
22072 (message "Drawer at point indented"))
22074 (defun org-indent-block ()
22075 "Indent the block at point."
22076 (interactive)
22077 (let ((p (point))
22078 (case-fold-search t)
22079 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22080 (match-end 0)))
22081 (folded
22082 (save-excursion
22083 (end-of-line)
22084 (when (overlays-at (point))
22085 (member 'invisible (overlay-properties
22086 (car (overlays-at (point)))))))))
22087 (when folded (org-cycle))
22088 (indent-for-tab-command)
22089 (while (and (move-beginning-of-line 2) (< (point) e))
22090 (indent-for-tab-command))
22091 (goto-char p)
22092 (when folded (org-cycle)))
22093 (message "Block at point indented"))
22095 (defun org-indent-region (start end)
22096 "Indent region."
22097 (interactive "r")
22098 (save-excursion
22099 (let ((line-end (org-current-line end)))
22100 (goto-char start)
22101 (while (< (org-current-line) line-end)
22102 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22103 (t (call-interactively 'org-indent-line)))
22104 (move-beginning-of-line 2)))))
22107 ;;; Filling
22109 ;; We use our own fill-paragraph and auto-fill functions.
22111 ;; `org-fill-paragraph' relies on adaptive filling and context
22112 ;; checking. Appropriate `fill-prefix' is computed with
22113 ;; `org-adaptive-fill-function'.
22115 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22116 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22117 ;; `org-adaptive-fill-function' value. Internally,
22118 ;; `org-comment-line-break-function' breaks the line.
22120 ;; `org-setup-filling' installs filling and auto-filling related
22121 ;; variables during `org-mode' initialization.
22123 (defvar org-element-paragraph-separate) ; org-element.el
22124 (defun org-setup-filling ()
22125 (require 'org-element)
22126 ;; Prevent auto-fill from inserting unwanted new items.
22127 (when (boundp 'fill-nobreak-predicate)
22128 (org-set-local
22129 'fill-nobreak-predicate
22130 (org-uniquify
22131 (append fill-nobreak-predicate
22132 '(org-fill-line-break-nobreak-p
22133 org-fill-paragraph-with-timestamp-nobreak-p)))))
22134 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22135 (org-set-local 'paragraph-start paragraph-ending)
22136 (org-set-local 'paragraph-separate paragraph-ending))
22137 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22138 (org-set-local 'auto-fill-inhibit-regexp nil)
22139 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22140 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22141 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22143 (defun org-fill-line-break-nobreak-p ()
22144 "Non-nil when a new line at point would create an Org line break."
22145 (save-excursion
22146 (skip-chars-backward "[ \t]")
22147 (skip-chars-backward "\\\\")
22148 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22150 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22151 "Non-nil when a new line at point would split a timestamp."
22152 (and (org-at-timestamp-p t)
22153 (not (looking-at org-ts-regexp-both))))
22155 (declare-function message-in-body-p "message" ())
22156 (defvar orgtbl-line-start-regexp) ; From org-table.el
22157 (defun org-adaptive-fill-function ()
22158 "Compute a fill prefix for the current line.
22159 Return fill prefix, as a string, or nil if current line isn't
22160 meant to be filled."
22161 (let (prefix)
22162 (catch 'exit
22163 (when (derived-mode-p 'message-mode)
22164 (save-excursion
22165 (beginning-of-line)
22166 (cond ((or (not (message-in-body-p))
22167 (looking-at orgtbl-line-start-regexp))
22168 (throw 'exit nil))
22169 ((looking-at message-cite-prefix-regexp)
22170 (throw 'exit (match-string-no-properties 0)))
22171 ((looking-at org-outline-regexp)
22172 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22173 (org-with-wide-buffer
22174 (let* ((p (line-beginning-position))
22175 (element (save-excursion
22176 (beginning-of-line)
22177 (or (ignore-errors (org-element-at-point))
22178 (user-error "An element cannot be parsed line %d"
22179 (line-number-at-pos (point))))))
22180 (type (org-element-type element))
22181 (post-affiliated (org-element-property :post-affiliated element)))
22182 (unless (and post-affiliated (< p post-affiliated))
22183 (case type
22184 (comment (looking-at "[ \t]*# ?") (match-string 0))
22185 (footnote-definition "")
22186 ((item plain-list)
22187 (make-string (org-list-item-body-column
22188 (or post-affiliated
22189 (org-element-property :begin element)))
22190 ? ))
22191 (paragraph
22192 ;; Fill prefix is usually the same as the current line,
22193 ;; except if the paragraph is at the beginning of an item.
22194 (let ((parent (org-element-property :parent element)))
22195 (cond ((eq (org-element-type parent) 'item)
22196 (make-string (org-list-item-body-column
22197 (org-element-property :begin parent))
22198 ? ))
22199 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22200 (match-string 0))
22201 (t ""))))
22202 (comment-block
22203 ;; Only fill contents if P is within block boundaries.
22204 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22205 (forward-line)
22206 (point)))
22207 (cend (save-excursion
22208 (goto-char (org-element-property :end element))
22209 (skip-chars-backward " \r\t\n")
22210 (line-beginning-position))))
22211 (when (and (>= p cbeg) (< p cend))
22212 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22213 (match-string 0)
22214 "")))))))))))
22216 (declare-function message-goto-body "message" ())
22217 (defvar message-cite-prefix-regexp) ; From message.el
22218 (defun org-fill-paragraph (&optional justify)
22219 "Fill element at point, when applicable.
22221 This function only applies to comment blocks, comments, example
22222 blocks and paragraphs. Also, as a special case, re-align table
22223 when point is at one.
22225 If JUSTIFY is non-nil (interactively, with prefix argument),
22226 justify as well. If `sentence-end-double-space' is non-nil, then
22227 period followed by one space does not end a sentence, so don't
22228 break a line there. The variable `fill-column' controls the
22229 width for filling.
22231 For convenience, when point is at a plain list, an item or
22232 a footnote definition, try to fill the first paragraph within."
22233 (interactive)
22234 (if (and (derived-mode-p 'message-mode)
22235 (or (not (message-in-body-p))
22236 (save-excursion (move-beginning-of-line 1)
22237 (looking-at message-cite-prefix-regexp))))
22238 ;; First ensure filling is correct in message-mode.
22239 (let ((fill-paragraph-function
22240 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22241 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22242 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22243 (paragraph-separate
22244 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22245 (fill-paragraph nil))
22246 (with-syntax-table org-mode-transpose-word-syntax-table
22247 ;; Move to end of line in order to get the first paragraph
22248 ;; within a plain list or a footnote definition.
22249 (let ((element (save-excursion
22250 (end-of-line)
22251 (or (ignore-errors (org-element-at-point))
22252 (user-error "An element cannot be parsed line %d"
22253 (line-number-at-pos (point)))))))
22254 ;; First check if point is in a blank line at the beginning of
22255 ;; the buffer. In that case, ignore filling.
22256 (case (org-element-type element)
22257 ;; Use major mode filling function is src blocks.
22258 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22259 ;; Align Org tables, leave table.el tables as-is.
22260 (table-row (org-table-align) t)
22261 (table
22262 (when (eq (org-element-property :type element) 'org)
22263 (save-excursion
22264 (goto-char (org-element-property :post-affiliated element))
22265 (org-table-align)))
22267 (paragraph
22268 ;; Paragraphs may contain `line-break' type objects.
22269 (let ((beg (max (point-min)
22270 (org-element-property :contents-begin element)))
22271 (end (min (point-max)
22272 (org-element-property :contents-end element))))
22273 ;; Do nothing if point is at an affiliated keyword.
22274 (if (< (line-end-position) beg) t
22275 (when (derived-mode-p 'message-mode)
22276 ;; In `message-mode', do not fill following citation
22277 ;; in current paragraph nor text before message body.
22278 (let ((body-start (save-excursion (message-goto-body))))
22279 (when body-start (setq beg (max body-start beg))))
22280 (when (save-excursion
22281 (re-search-forward
22282 (concat "^" message-cite-prefix-regexp) end t))
22283 (setq end (match-beginning 0))))
22284 ;; Fill paragraph, taking line breaks into account.
22285 ;; For that, slice the paragraph using line breaks as
22286 ;; separators, and fill the parts in reverse order to
22287 ;; avoid messing with markers.
22288 (save-excursion
22289 (goto-char end)
22290 (mapc
22291 (lambda (pos)
22292 (fill-region-as-paragraph pos (point) justify)
22293 (goto-char pos))
22294 ;; Find the list of ending positions for line breaks
22295 ;; in the current paragraph. Add paragraph
22296 ;; beginning to include first slice.
22297 (nreverse
22298 (cons beg
22299 (org-element-map
22300 (org-element--parse-objects
22301 beg end nil (org-element-restriction 'paragraph))
22302 'line-break
22303 (lambda (lb) (org-element-property :end lb)))))))
22304 t)))
22305 ;; Contents of `comment-block' type elements should be
22306 ;; filled as plain text, but only if point is within block
22307 ;; markers.
22308 (comment-block
22309 (let* ((case-fold-search t)
22310 (beg (save-excursion
22311 (goto-char (org-element-property :begin element))
22312 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22313 (forward-line)
22314 (point)))
22315 (end (save-excursion
22316 (goto-char (org-element-property :end element))
22317 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22318 (line-beginning-position))))
22319 (if (or (< (point) beg) (> (point) end)) t
22320 (fill-region-as-paragraph
22321 (save-excursion (end-of-line)
22322 (re-search-backward "^[ \t]*$" beg 'move)
22323 (line-beginning-position))
22324 (save-excursion (beginning-of-line)
22325 (re-search-forward "^[ \t]*$" end 'move)
22326 (line-beginning-position))
22327 justify))))
22328 ;; Fill comments.
22329 (comment
22330 (let ((begin (org-element-property :post-affiliated element))
22331 (end (org-element-property :end element)))
22332 (when (and (>= (point) begin) (<= (point) end))
22333 (let ((begin (save-excursion
22334 (end-of-line)
22335 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22336 (progn (forward-line) (point))
22337 begin)))
22338 (end (save-excursion
22339 (end-of-line)
22340 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22341 (1- (line-beginning-position))
22342 (skip-chars-backward " \r\t\n")
22343 (line-end-position)))))
22344 ;; Do not fill comments when at a blank line or at
22345 ;; affiliated keywords.
22346 (let ((fill-prefix (save-excursion
22347 (beginning-of-line)
22348 (looking-at "[ \t]*#")
22349 (concat (match-string 0) " "))))
22350 (when (> end begin)
22351 (save-excursion
22352 (fill-region-as-paragraph begin end justify))))))
22354 ;; Ignore every other element.
22355 (otherwise t))))))
22357 (defun org-auto-fill-function ()
22358 "Auto-fill function."
22359 ;; Check if auto-filling is meaningful.
22360 (let ((fc (current-fill-column)))
22361 (when (and fc (> (current-column) fc))
22362 (let* ((fill-prefix (org-adaptive-fill-function))
22363 ;; Enforce empty fill prefix, if required. Otherwise, it
22364 ;; will be computed again.
22365 (adaptive-fill-mode (not (equal fill-prefix ""))))
22366 (when fill-prefix (do-auto-fill))))))
22368 (defun org-comment-line-break-function (&optional soft)
22369 "Break line at point and indent, continuing comment if within one.
22370 The inserted newline is marked hard if variable
22371 `use-hard-newlines' is true, unless optional argument SOFT is
22372 non-nil."
22373 (if soft (insert-and-inherit ?\n) (newline 1))
22374 (save-excursion (forward-char -1) (delete-horizontal-space))
22375 (delete-horizontal-space)
22376 (indent-to-left-margin)
22377 (insert-before-markers-and-inherit fill-prefix))
22380 ;;; Comments
22382 ;; Org comments syntax is quite complex. It requires the entire line
22383 ;; to be just a comment. Also, even with the right syntax at the
22384 ;; beginning of line, some some elements (i.e. verse-block or
22385 ;; example-block) don't accept comments. Usual Emacs comment commands
22386 ;; cannot cope with those requirements. Therefore, Org replaces them.
22388 ;; Org still relies on `comment-dwim', but cannot trust
22389 ;; `comment-only-p'. So, `comment-region-function' and
22390 ;; `uncomment-region-function' both point
22391 ;; to`org-comment-or-uncomment-region'. Eventually,
22392 ;; `org-insert-comment' takes care of insertion of comments at the
22393 ;; beginning of line.
22395 ;; `org-setup-comments-handling' install comments related variables
22396 ;; during `org-mode' initialization.
22398 (defun org-setup-comments-handling ()
22399 (interactive)
22400 (org-set-local 'comment-use-syntax nil)
22401 (org-set-local 'comment-start "# ")
22402 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22403 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22404 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22405 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22407 (defun org-insert-comment ()
22408 "Insert an empty comment above current line.
22409 If the line is empty, insert comment at its beginning."
22410 (beginning-of-line)
22411 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22412 (org-indent-line)
22413 (insert "# "))
22415 (defvar comment-empty-lines) ; From newcomment.el.
22416 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22417 "Comment or uncomment each non-blank line in the region.
22418 Uncomment each non-blank line between BEG and END if it only
22419 contains commented lines. Otherwise, comment them."
22420 (save-restriction
22421 ;; Restrict region
22422 (narrow-to-region (save-excursion (goto-char beg)
22423 (skip-chars-forward " \r\t\n" end)
22424 (line-beginning-position))
22425 (save-excursion (goto-char end)
22426 (skip-chars-backward " \r\t\n" beg)
22427 (line-end-position)))
22428 (let ((uncommentp
22429 ;; UNCOMMENTP is non-nil when every non blank line between
22430 ;; BEG and END is a comment.
22431 (save-excursion
22432 (goto-char (point-min))
22433 (while (and (not (eobp))
22434 (let ((element (org-element-at-point)))
22435 (and (eq (org-element-type element) 'comment)
22436 (goto-char (min (point-max)
22437 (org-element-property
22438 :end element)))))))
22439 (eobp))))
22440 (if uncommentp
22441 ;; Only blank lines and comments in region: uncomment it.
22442 (save-excursion
22443 (goto-char (point-min))
22444 (while (not (eobp))
22445 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22446 (replace-match "" nil nil nil 1))
22447 (forward-line)))
22448 ;; Comment each line in region.
22449 (let ((min-indent (point-max)))
22450 ;; First find the minimum indentation across all lines.
22451 (save-excursion
22452 (goto-char (point-min))
22453 (while (and (not (eobp)) (not (zerop min-indent)))
22454 (unless (looking-at "[ \t]*$")
22455 (setq min-indent (min min-indent (current-indentation))))
22456 (forward-line)))
22457 ;; Then loop over all lines.
22458 (save-excursion
22459 (goto-char (point-min))
22460 (while (not (eobp))
22461 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22462 ;; Don't get fooled by invisible text (e.g. link path)
22463 ;; when moving to column MIN-INDENT.
22464 (let ((buffer-invisibility-spec nil))
22465 (org-move-to-column min-indent t))
22466 (insert comment-start))
22467 (forward-line))))))))
22470 ;;; Planning
22472 ;; This section contains tools to operate on timestamp objects, as
22473 ;; returned by, e.g. `org-element-context'.
22475 (defun org-timestamp-has-time-p (timestamp)
22476 "Non-nil when TIMESTAMP has a time specified."
22477 (org-element-property :hour-start timestamp))
22479 (defun org-timestamp-format (timestamp format &optional end utc)
22480 "Format a TIMESTAMP element into a string.
22482 FORMAT is a format specifier to be passed to
22483 `format-time-string'.
22485 When optional argument END is non-nil, use end of date-range or
22486 time-range, if possible.
22488 When optional argument UTC is non-nil, time will be expressed as
22489 Universal Time."
22490 (format-time-string
22491 format
22492 (apply 'encode-time
22493 (cons 0
22494 (mapcar
22495 (lambda (prop) (or (org-element-property prop timestamp) 0))
22496 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22497 '(:minute-start :hour-start :day-start :month-start
22498 :year-start)))))
22499 utc))
22501 (defun org-timestamp-split-range (timestamp &optional end)
22502 "Extract a timestamp object from a date or time range.
22504 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22505 the end of the range. Otherwise, extract its start.
22507 Return a new timestamp object sharing the same parent as
22508 TIMESTAMP."
22509 (let ((type (org-element-property :type timestamp)))
22510 (if (memq type '(active inactive diary)) timestamp
22511 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22512 ;; Set new type.
22513 (org-element-put-property
22514 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22515 ;; Copy start properties over end properties if END is
22516 ;; non-nil. Otherwise, copy end properties over `start' ones.
22517 (let ((p-alist '((:minute-start . :minute-end)
22518 (:hour-start . :hour-end)
22519 (:day-start . :day-end)
22520 (:month-start . :month-end)
22521 (:year-start . :year-end))))
22522 (dolist (p-cell p-alist)
22523 (org-element-put-property
22524 split-ts
22525 (funcall (if end 'car 'cdr) p-cell)
22526 (org-element-property
22527 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22528 ;; Eventually refresh `:raw-value'.
22529 (org-element-put-property split-ts :raw-value nil)
22530 (org-element-put-property
22531 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22533 (defun org-timestamp-translate (timestamp &optional boundary)
22534 "Apply `org-translate-time' on a TIMESTAMP object.
22535 When optional argument BOUNDARY is non-nil, it is either the
22536 symbol `start' or `end'. In this case, only translate the
22537 starting or ending part of TIMESTAMP if it is a date or time
22538 range. Otherwise, translate both parts."
22539 (if (and (not boundary)
22540 (memq (org-element-property :type timestamp)
22541 '(active-range inactive-range)))
22542 (concat
22543 (org-translate-time
22544 (org-element-property :raw-value
22545 (org-timestamp-split-range timestamp)))
22546 "--"
22547 (org-translate-time
22548 (org-element-property :raw-value
22549 (org-timestamp-split-range timestamp t))))
22550 (org-translate-time
22551 (org-element-property
22552 :raw-value
22553 (if (not boundary) timestamp
22554 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22558 ;;; Other stuff.
22560 (defun org-toggle-fixed-width-section (arg)
22561 "Toggle the fixed-width export.
22562 If there is no active region, the QUOTE keyword at the current headline is
22563 inserted or removed. When present, it causes the text between this headline
22564 and the next to be exported as fixed-width text, and unmodified.
22565 If there is an active region, this command adds or removes a colon as the
22566 first character of this line. If the first character of a line is a colon,
22567 this line is also exported in fixed-width font."
22568 (interactive "P")
22569 (let* ((cc 0)
22570 (regionp (org-region-active-p))
22571 (beg (if regionp (region-beginning) (point)))
22572 (end (if regionp (region-end)))
22573 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22574 (case-fold-search nil)
22575 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22576 off)
22577 (if regionp
22578 (save-excursion
22579 (goto-char beg)
22580 (setq cc (current-column))
22581 (beginning-of-line 1)
22582 (setq off (looking-at re))
22583 (while (> nlines 0)
22584 (setq nlines (1- nlines))
22585 (beginning-of-line 1)
22586 (cond
22587 (arg
22588 (org-move-to-column cc t)
22589 (insert ": \n")
22590 (forward-line -1))
22591 ((and off (looking-at re))
22592 (replace-match "" t t nil 1))
22593 ((not off) (org-move-to-column cc t) (insert ": ")))
22594 (forward-line 1)))
22595 (save-excursion
22596 (org-back-to-heading)
22597 (cond
22598 ((looking-at (format org-heading-keyword-regexp-format
22599 org-quote-string))
22600 (goto-char (match-end 1))
22601 (looking-at (concat " +" org-quote-string))
22602 (replace-match "" t t)
22603 (when (eolp) (insert " ")))
22604 ((looking-at org-outline-regexp)
22605 (goto-char (match-end 0))
22606 (insert org-quote-string " ")))))))
22608 (defun org-reftex-citation ()
22609 "Use reftex-citation to insert a citation into the buffer.
22610 This looks for a line like
22612 #+BIBLIOGRAPHY: foo plain option:-d
22614 and derives from it that foo.bib is the bibliography file relevant
22615 for this document. It then installs the necessary environment for RefTeX
22616 to work in this buffer and calls `reftex-citation' to insert a citation
22617 into the buffer.
22619 Export of such citations to both LaTeX and HTML is handled by the contributed
22620 package ox-bibtex by Taru Karttunen."
22621 (interactive)
22622 (let ((reftex-docstruct-symbol 'rds)
22623 (reftex-cite-format "\\cite{%l}")
22624 rds bib)
22625 (save-excursion
22626 (save-restriction
22627 (widen)
22628 (let ((case-fold-search t)
22629 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22630 (if (not (save-excursion
22631 (or (re-search-forward re nil t)
22632 (re-search-backward re nil t))))
22633 (error "No bibliography defined in file")
22634 (setq bib (concat (match-string 1) ".bib")
22635 rds (list (list 'bib bib)))))))
22636 (call-interactively 'reftex-citation)))
22638 ;;;; Functions extending outline functionality
22640 (defun org-beginning-of-line (&optional arg)
22641 "Go to the beginning of the current line. If that is invisible, continue
22642 to a visible line beginning. This makes the function of C-a more intuitive.
22643 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22644 first attempt, and only move to after the tags when the cursor is already
22645 beyond the end of the headline."
22646 (interactive "P")
22647 (let ((pos (point))
22648 (special (if (consp org-special-ctrl-a/e)
22649 (car org-special-ctrl-a/e)
22650 org-special-ctrl-a/e))
22651 refpos)
22652 (if (org-bound-and-true-p visual-line-mode)
22653 (beginning-of-visual-line 1)
22654 (beginning-of-line 1))
22655 (if (and arg (fboundp 'move-beginning-of-line))
22656 (call-interactively 'move-beginning-of-line)
22657 (if (bobp)
22659 (backward-char 1)
22660 (if (org-truely-invisible-p)
22661 (while (and (not (bobp)) (org-truely-invisible-p))
22662 (backward-char 1)
22663 (beginning-of-line 1))
22664 (forward-char 1))))
22665 (when special
22666 (cond
22667 ((and (looking-at org-complex-heading-regexp)
22668 (= (char-after (match-end 1)) ?\ ))
22669 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22670 (point-at-eol)))
22671 (goto-char
22672 (if (eq special t)
22673 (cond ((> pos refpos) refpos)
22674 ((= pos (point)) refpos)
22675 (t (point)))
22676 (cond ((> pos (point)) (point))
22677 ((not (eq last-command this-command)) (point))
22678 (t refpos)))))
22679 ((org-at-item-p)
22680 ;; Being at an item and not looking at an the item means point
22681 ;; was previously moved to beginning of a visual line, which
22682 ;; doesn't contain the item. Therefore, do nothing special,
22683 ;; just stay here.
22684 (when (looking-at org-list-full-item-re)
22685 ;; Set special position at first white space character after
22686 ;; bullet, and check-box, if any.
22687 (let ((after-bullet
22688 (let ((box (match-end 3)))
22689 (if (not box) (match-end 1)
22690 (let ((after (char-after box)))
22691 (if (and after (= after ? )) (1+ box) box))))))
22692 ;; Special case: Move point to special position when
22693 ;; currently after it or at beginning of line.
22694 (if (eq special t)
22695 (when (or (> pos after-bullet) (= (point) pos))
22696 (goto-char after-bullet))
22697 ;; Reversed case: Move point to special position when
22698 ;; point was already at beginning of line and command is
22699 ;; repeated.
22700 (when (and (= (point) pos) (eq last-command this-command))
22701 (goto-char after-bullet))))))))
22702 (org-no-warnings
22703 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22704 (setq disable-point-adjustment
22705 (or (not (invisible-p (point)))
22706 (not (invisible-p (max (point-min) (1- (point))))))))
22708 (defun org-end-of-line (&optional arg)
22709 "Go to the end of the line.
22710 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22711 tags on the first attempt, and only move to after the tags when
22712 the cursor is already beyond the end of the headline."
22713 (interactive "P")
22714 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22715 org-special-ctrl-a/e))
22716 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22717 'end-of-visual-line)
22718 ((fboundp 'move-end-of-line) 'move-end-of-line)
22719 (t 'end-of-line))))
22720 (if (or (not special) arg) (call-interactively move-fun)
22721 (let* ((element (save-excursion (beginning-of-line)
22722 (org-element-at-point)))
22723 (type (org-element-type element)))
22724 (cond
22725 ((memq type '(headline inlinetask))
22726 (let ((pos (point)))
22727 (beginning-of-line 1)
22728 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22729 (if (eq special t)
22730 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22731 (goto-char (match-beginning 1))
22732 (goto-char (match-end 0)))
22733 (if (or (< pos (match-end 0))
22734 (not (eq this-command last-command)))
22735 (goto-char (match-end 0))
22736 (goto-char (match-beginning 1))))
22737 (call-interactively move-fun))))
22738 ((org-element-property :hiddenp element)
22739 ;; If element is hidden, `move-end-of-line' would put point
22740 ;; after it. Use `end-of-line' to stay on current line.
22741 (call-interactively 'end-of-line))
22742 (t (call-interactively move-fun)))))
22743 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22744 (setq disable-point-adjustment
22745 (or (not (invisible-p (point)))
22746 (not (invisible-p (max (point-min) (1- (point))))))))
22748 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22749 (define-key org-mode-map "\C-e" 'org-end-of-line)
22751 (defun org-backward-sentence (&optional arg)
22752 "Go to beginning of sentence, or beginning of table field.
22753 This will call `backward-sentence' or `org-table-beginning-of-field',
22754 depending on context."
22755 (interactive "P")
22756 (cond
22757 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22758 (t (call-interactively 'backward-sentence))))
22760 (defun org-forward-sentence (&optional arg)
22761 "Go to end of sentence, or end of table field.
22762 This will call `forward-sentence' or `org-table-end-of-field',
22763 depending on context."
22764 (interactive "P")
22765 (cond
22766 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22767 (t (call-interactively 'forward-sentence))))
22769 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22770 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22772 (defun org-kill-line (&optional arg)
22773 "Kill line, to tags or end of line."
22774 (interactive "P")
22775 (cond
22776 ((or (not org-special-ctrl-k)
22777 (bolp)
22778 (not (org-at-heading-p)))
22779 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22780 org-ctrl-k-protect-subtree)
22781 (if (or (eq org-ctrl-k-protect-subtree 'error)
22782 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22783 (user-error "C-k aborted as it would kill a hidden subtree")))
22784 (call-interactively
22785 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22786 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22787 (kill-region (point) (match-beginning 1))
22788 (org-set-tags nil t))
22789 (t (kill-region (point) (point-at-eol)))))
22791 (define-key org-mode-map "\C-k" 'org-kill-line)
22793 (defun org-yank (&optional arg)
22794 "Yank. If the kill is a subtree, treat it specially.
22795 This command will look at the current kill and check if is a single
22796 subtree, or a series of subtrees[1]. If it passes the test, and if the
22797 cursor is at the beginning of a line or after the stars of a currently
22798 empty headline, then the yank is handled specially. How exactly depends
22799 on the value of the following variables, both set by default.
22801 org-yank-folded-subtrees
22802 When set, the subtree(s) will be folded after insertion, but only
22803 if doing so would now swallow text after the yanked text.
22805 org-yank-adjusted-subtrees
22806 When set, the subtree will be promoted or demoted in order to
22807 fit into the local outline tree structure, which means that the level
22808 will be adjusted so that it becomes the smaller one of the two
22809 *visible* surrounding headings.
22811 Any prefix to this command will cause `yank' to be called directly with
22812 no special treatment. In particular, a simple \\[universal-argument] prefix \
22813 will just
22814 plainly yank the text as it is.
22816 \[1] The test checks if the first non-white line is a heading
22817 and if there are no other headings with fewer stars."
22818 (interactive "P")
22819 (org-yank-generic 'yank arg))
22821 (defun org-yank-generic (command arg)
22822 "Perform some yank-like command.
22824 This function implements the behavior described in the `org-yank'
22825 documentation. However, it has been generalized to work for any
22826 interactive command with similar behavior."
22828 ;; pretend to be command COMMAND
22829 (setq this-command command)
22831 (if arg
22832 (call-interactively command)
22834 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22835 (and (org-kill-is-subtree-p)
22836 (or (bolp)
22837 (and (looking-at "[ \t]*$")
22838 (string-match
22839 "\\`\\*+\\'"
22840 (buffer-substring (point-at-bol) (point)))))))
22841 swallowp)
22842 (cond
22843 ((and subtreep org-yank-folded-subtrees)
22844 (let ((beg (point))
22845 end)
22846 (if (and subtreep org-yank-adjusted-subtrees)
22847 (org-paste-subtree nil nil 'for-yank)
22848 (call-interactively command))
22850 (setq end (point))
22851 (goto-char beg)
22852 (when (and (bolp) subtreep
22853 (not (setq swallowp
22854 (org-yank-folding-would-swallow-text beg end))))
22855 (org-with-limited-levels
22856 (or (looking-at org-outline-regexp)
22857 (re-search-forward org-outline-regexp-bol end t))
22858 (while (and (< (point) end) (looking-at org-outline-regexp))
22859 (hide-subtree)
22860 (org-cycle-show-empty-lines 'folded)
22861 (condition-case nil
22862 (outline-forward-same-level 1)
22863 (error (goto-char end))))))
22864 (when swallowp
22865 (message
22866 "Inserted text not folded because that would swallow text"))
22868 (goto-char end)
22869 (skip-chars-forward " \t\n\r")
22870 (beginning-of-line 1)
22871 (push-mark beg 'nomsg)))
22872 ((and subtreep org-yank-adjusted-subtrees)
22873 (let ((beg (point-at-bol)))
22874 (org-paste-subtree nil nil 'for-yank)
22875 (push-mark beg 'nomsg)))
22877 (call-interactively command))))))
22879 (defun org-yank-folding-would-swallow-text (beg end)
22880 "Would hide-subtree at BEG swallow any text after END?"
22881 (let (level)
22882 (org-with-limited-levels
22883 (save-excursion
22884 (goto-char beg)
22885 (when (or (looking-at org-outline-regexp)
22886 (re-search-forward org-outline-regexp-bol end t))
22887 (setq level (org-outline-level)))
22888 (goto-char end)
22889 (skip-chars-forward " \t\r\n\v\f")
22890 (if (or (eobp)
22891 (and (bolp) (looking-at org-outline-regexp)
22892 (<= (org-outline-level) level)))
22893 nil ; Nothing would be swallowed
22894 t))))) ; something would swallow
22896 (define-key org-mode-map "\C-y" 'org-yank)
22898 (defun org-truely-invisible-p ()
22899 "Check if point is at a character currently not visible.
22900 This version does not only check the character property, but also
22901 `visible-mode'."
22902 ;; Early versions of noutline don't have `outline-invisible-p'.
22903 (if (org-bound-and-true-p visible-mode)
22905 (outline-invisible-p)))
22907 (defun org-invisible-p2 ()
22908 "Check if point is at a character currently not visible."
22909 (save-excursion
22910 (if (and (eolp) (not (bobp))) (backward-char 1))
22911 ;; Early versions of noutline don't have `outline-invisible-p'.
22912 (outline-invisible-p)))
22914 (defun org-back-to-heading (&optional invisible-ok)
22915 "Call `outline-back-to-heading', but provide a better error message."
22916 (condition-case nil
22917 (outline-back-to-heading invisible-ok)
22918 (error (error "Before first headline at position %d in buffer %s"
22919 (point) (current-buffer)))))
22921 (defun org-before-first-heading-p ()
22922 "Before first heading?"
22923 (save-excursion
22924 (end-of-line)
22925 (null (re-search-backward org-outline-regexp-bol nil t))))
22927 (defun org-at-heading-p (&optional ignored)
22928 (outline-on-heading-p t))
22929 ;; Compatibility alias with Org versions < 7.8.03
22930 (defalias 'org-on-heading-p 'org-at-heading-p)
22932 (defun org-at-comment-p nil
22933 "Is cursor in a line starting with a # character?"
22934 (save-excursion
22935 (beginning-of-line)
22936 (looking-at "^#")))
22938 (defun org-at-drawer-p nil
22939 "Is cursor at a drawer keyword?"
22940 (save-excursion
22941 (move-beginning-of-line 1)
22942 (looking-at org-drawer-regexp)))
22944 (defun org-at-block-p nil
22945 "Is cursor at a block keyword?"
22946 (save-excursion
22947 (move-beginning-of-line 1)
22948 (looking-at org-block-regexp)))
22950 (defun org-point-at-end-of-empty-headline ()
22951 "If point is at the end of an empty headline, return t, else nil.
22952 If the heading only contains a TODO keyword, it is still still considered
22953 empty."
22954 (and (looking-at "[ \t]*$")
22955 (when org-todo-line-regexp
22956 (save-excursion
22957 (beginning-of-line 1)
22958 (let ((case-fold-search nil))
22959 (looking-at org-todo-line-regexp)
22960 (string= (match-string 3) ""))))))
22962 (defun org-at-heading-or-item-p ()
22963 (or (org-at-heading-p) (org-at-item-p)))
22965 (defun org-at-target-p ()
22966 (or (org-in-regexp org-radio-target-regexp)
22967 (org-in-regexp org-target-regexp)))
22968 ;; Compatibility alias with Org versions < 7.8.03
22969 (defalias 'org-on-target-p 'org-at-target-p)
22971 (defun org-up-heading-all (arg)
22972 "Move to the heading line of which the present line is a subheading.
22973 This function considers both visible and invisible heading lines.
22974 With argument, move up ARG levels."
22975 (if (fboundp 'outline-up-heading-all)
22976 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22977 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22979 (defun org-up-heading-safe ()
22980 "Move to the heading line of which the present line is a subheading.
22981 This version will not throw an error. It will return the level of the
22982 headline found, or nil if no higher level is found.
22984 Also, this function will be a lot faster than `outline-up-heading',
22985 because it relies on stars being the outline starters. This can really
22986 make a significant difference in outlines with very many siblings."
22987 (let (start-level re)
22988 (org-back-to-heading t)
22989 (setq start-level (funcall outline-level))
22990 (if (equal start-level 1)
22992 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22993 (if (re-search-backward re nil t)
22994 (funcall outline-level)))))
22996 (defun org-first-sibling-p ()
22997 "Is this heading the first child of its parents?"
22998 (interactive)
22999 (let ((re org-outline-regexp-bol)
23000 level l)
23001 (unless (org-at-heading-p t)
23002 (user-error "Not at a heading"))
23003 (setq level (funcall outline-level))
23004 (save-excursion
23005 (if (not (re-search-backward re nil t))
23007 (setq l (funcall outline-level))
23008 (< l level)))))
23010 (defun org-goto-sibling (&optional previous)
23011 "Goto the next sibling, even if it is invisible.
23012 When PREVIOUS is set, go to the previous sibling instead. Returns t
23013 when a sibling was found. When none is found, return nil and don't
23014 move point."
23015 (let ((fun (if previous 're-search-backward 're-search-forward))
23016 (pos (point))
23017 (re org-outline-regexp-bol)
23018 level l)
23019 (when (condition-case nil (org-back-to-heading t) (error nil))
23020 (setq level (funcall outline-level))
23021 (catch 'exit
23022 (or previous (forward-char 1))
23023 (while (funcall fun re nil t)
23024 (setq l (funcall outline-level))
23025 (when (< l level) (goto-char pos) (throw 'exit nil))
23026 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23027 (goto-char pos)
23028 nil))))
23030 (defun org-show-siblings ()
23031 "Show all siblings of the current headline."
23032 (save-excursion
23033 (while (org-goto-sibling) (org-flag-heading nil)))
23034 (save-excursion
23035 (while (org-goto-sibling 'previous)
23036 (org-flag-heading nil))))
23038 (defun org-goto-first-child ()
23039 "Goto the first child, even if it is invisible.
23040 Return t when a child was found. Otherwise don't move point and
23041 return nil."
23042 (let (level (pos (point)) (re org-outline-regexp-bol))
23043 (when (condition-case nil (org-back-to-heading t) (error nil))
23044 (setq level (outline-level))
23045 (forward-char 1)
23046 (if (and (re-search-forward re nil t) (> (outline-level) level))
23047 (progn (goto-char (match-beginning 0)) t)
23048 (goto-char pos) nil))))
23050 (defun org-show-hidden-entry ()
23051 "Show an entry where even the heading is hidden."
23052 (save-excursion
23053 (org-show-entry)))
23055 (defun org-flag-heading (flag &optional entry)
23056 "Flag the current heading. FLAG non-nil means make invisible.
23057 When ENTRY is non-nil, show the entire entry."
23058 (save-excursion
23059 (org-back-to-heading t)
23060 ;; Check if we should show the entire entry
23061 (if entry
23062 (progn
23063 (org-show-entry)
23064 (save-excursion
23065 (and (outline-next-heading)
23066 (org-flag-heading nil))))
23067 (outline-flag-region (max (point-min) (1- (point)))
23068 (save-excursion (outline-end-of-heading) (point))
23069 flag))))
23071 (defun org-get-next-sibling ()
23072 "Move to next heading of the same level, and return point.
23073 If there is no such heading, return nil.
23074 This is like outline-next-sibling, but invisible headings are ok."
23075 (let ((level (funcall outline-level)))
23076 (outline-next-heading)
23077 (while (and (not (eobp)) (> (funcall outline-level) level))
23078 (outline-next-heading))
23079 (if (or (eobp) (< (funcall outline-level) level))
23081 (point))))
23083 (defun org-get-last-sibling ()
23084 "Move to previous heading of the same level, and return point.
23085 If there is no such heading, return nil."
23086 (let ((opoint (point))
23087 (level (funcall outline-level)))
23088 (outline-previous-heading)
23089 (when (and (/= (point) opoint) (outline-on-heading-p t))
23090 (while (and (> (funcall outline-level) level)
23091 (not (bobp)))
23092 (outline-previous-heading))
23093 (if (< (funcall outline-level) level)
23095 (point)))))
23097 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23098 "Goto to the end of a subtree."
23099 ;; This contains an exact copy of the original function, but it uses
23100 ;; `org-back-to-heading', to make it work also in invisible
23101 ;; trees. And is uses an invisible-ok argument.
23102 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23103 ;; Furthermore, when used inside Org, finding the end of a large subtree
23104 ;; with many children and grandchildren etc, this can be much faster
23105 ;; than the outline version.
23106 (org-back-to-heading invisible-ok)
23107 (let ((first t)
23108 (level (funcall outline-level)))
23109 (if (and (derived-mode-p 'org-mode) (< level 1000))
23110 ;; A true heading (not a plain list item), in Org-mode
23111 ;; This means we can easily find the end by looking
23112 ;; only for the right number of stars. Using a regexp to do
23113 ;; this is so much faster than using a Lisp loop.
23114 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23115 (forward-char 1)
23116 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23117 ;; something else, do it the slow way
23118 (while (and (not (eobp))
23119 (or first (> (funcall outline-level) level)))
23120 (setq first nil)
23121 (outline-next-heading)))
23122 (unless to-heading
23123 (if (memq (preceding-char) '(?\n ?\^M))
23124 (progn
23125 ;; Go to end of line before heading
23126 (forward-char -1)
23127 (if (memq (preceding-char) '(?\n ?\^M))
23128 ;; leave blank line before heading
23129 (forward-char -1))))))
23130 (point))
23132 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23133 "Use Org version in org-mode, for dramatic speed-up."
23134 (if (derived-mode-p 'org-mode)
23135 (progn
23136 (org-end-of-subtree nil t)
23137 (unless (eobp) (backward-char 1)))
23138 ad-do-it))
23140 (defun org-end-of-meta-data-and-drawers ()
23141 "Jump to the first text after meta data and drawers in the current entry.
23142 This will move over empty lines, lines with planning time stamps,
23143 clocking lines, and drawers."
23144 (org-back-to-heading t)
23145 (let ((end (save-excursion (outline-next-heading) (point)))
23146 (re (concat "\\(" org-drawer-regexp "\\)"
23147 "\\|" "[ \t]*" org-keyword-time-regexp)))
23148 (forward-line 1)
23149 (while (re-search-forward re end t)
23150 (if (not (match-end 1))
23151 ;; empty or planning line
23152 (forward-line 1)
23153 ;; a drawer, find the end
23154 (re-search-forward "^[ \t]*:END:" end 'move)
23155 (forward-line 1)))
23156 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23157 (point)))
23159 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23160 "Move forward to the ARG'th subheading at same level as this one.
23161 Stop at the first and last subheadings of a superior heading.
23162 Normally this only looks at visible headings, but when INVISIBLE-OK is
23163 non-nil it will also look at invisible ones."
23164 (interactive "p")
23165 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23166 (if (and arg (< arg 0))
23167 (goto-char (point-min))
23168 (outline-next-heading))
23169 (org-at-heading-p)
23170 (let ((level (- (match-end 0) (match-beginning 0) 1))
23171 (f (if (and arg (< arg 0))
23172 're-search-backward
23173 're-search-forward))
23174 (count (if arg (abs arg) 1))
23175 (result (point)))
23176 (while (and (prog1 (> count 0)
23177 (forward-char (if (and arg (< arg 0)) -1 1)))
23178 (funcall f org-outline-regexp-bol nil 'move))
23179 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23180 (cond ((< l level) (setq count 0))
23181 ((and (= l level)
23182 (or invisible-ok
23183 (progn
23184 (goto-char (line-beginning-position))
23185 (not (outline-invisible-p)))))
23186 (setq count (1- count))
23187 (when (eq l level)
23188 (setq result (point)))))))
23189 (goto-char result))
23190 (beginning-of-line 1)))
23192 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23193 "Move backward to the ARG'th subheading at same level as this one.
23194 Stop at the first and last subheadings of a superior heading."
23195 (interactive "p")
23196 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23198 (defun org-next-block (arg &optional backward block-regexp)
23199 "Jump to the next block.
23200 With a prefix argument ARG, jump forward ARG many source blocks.
23201 When BACKWARD is non-nil, jump to the previous block.
23202 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23203 (interactive "p")
23204 (let ((re (or block-regexp org-block-regexp))
23205 (re-search-fn (or (and backward 're-search-backward)
23206 're-search-forward)))
23207 (if (looking-at re) (forward-char 1))
23208 (condition-case nil
23209 (funcall re-search-fn re nil nil arg)
23210 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23211 (goto-char (match-beginning 0)) (org-show-context)))
23213 (defun org-previous-block (arg &optional block-regexp)
23214 "Jump to the previous block.
23215 With a prefix argument ARG, jump backward ARG many source blocks.
23216 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23217 (interactive "p")
23218 (org-next-block arg t block-regexp))
23220 (defun org-forward-element ()
23221 "Move forward by one element.
23222 Move to the next element at the same level, when possible."
23223 (interactive)
23224 (cond ((eobp) (user-error "Cannot move further down"))
23225 ((org-with-limited-levels (org-at-heading-p))
23226 (let ((origin (point)))
23227 (goto-char (org-end-of-subtree nil t))
23228 (unless (org-with-limited-levels (org-at-heading-p))
23229 (goto-char origin)
23230 (user-error "Cannot move further down"))))
23232 (let* ((elem (org-element-at-point))
23233 (end (org-element-property :end elem))
23234 (parent (org-element-property :parent elem)))
23235 (cond ((and parent (= (org-element-property :contents-end parent) end))
23236 (goto-char (org-element-property :end parent)))
23237 ((integer-or-marker-p end) (goto-char end))
23238 (t (message "No element at point")))))))
23240 (defun org-backward-element ()
23241 "Move backward by one element.
23242 Move to the previous element at the same level, when possible."
23243 (interactive)
23244 (cond ((bobp) (user-error "Cannot move further up"))
23245 ((org-with-limited-levels (org-at-heading-p))
23246 ;; At a headline, move to the previous one, if any, or stay
23247 ;; here.
23248 (let ((origin (point)))
23249 (org-with-limited-levels (org-backward-heading-same-level 1))
23250 ;; When current headline has no sibling above, move to its
23251 ;; parent.
23252 (when (= (point) origin)
23253 (or (org-with-limited-levels (org-up-heading-safe))
23254 (progn (goto-char origin)
23255 (user-error "Cannot move further up"))))))
23257 (let* ((trail (org-element-at-point 'keep-trail))
23258 (elem (car trail))
23259 (prev-elem (nth 1 trail))
23260 (beg (org-element-property :begin elem)))
23261 (cond
23262 ;; Move to beginning of current element if point isn't
23263 ;; there already.
23264 ((null beg) (message "No element at point"))
23265 ((/= (point) beg) (goto-char beg))
23266 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23267 ((org-before-first-heading-p) (goto-char (point-min)))
23268 (t (org-back-to-heading)))))))
23270 (defun org-up-element ()
23271 "Move to upper element."
23272 (interactive)
23273 (if (org-with-limited-levels (org-at-heading-p))
23274 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23275 (let* ((elem (org-element-at-point))
23276 (parent (org-element-property :parent elem)))
23277 (if parent (goto-char (org-element-property :begin parent))
23278 (if (org-with-limited-levels (org-before-first-heading-p))
23279 (user-error "No surrounding element")
23280 (org-with-limited-levels (org-back-to-heading)))))))
23282 (defvar org-element-greater-elements)
23283 (defun org-down-element ()
23284 "Move to inner element."
23285 (interactive)
23286 (let ((element (org-element-at-point)))
23287 (cond
23288 ((memq (org-element-type element) '(plain-list table))
23289 (goto-char (org-element-property :contents-begin element))
23290 (forward-char))
23291 ((memq (org-element-type element) org-element-greater-elements)
23292 ;; If contents are hidden, first disclose them.
23293 (when (org-element-property :hiddenp element) (org-cycle))
23294 (goto-char (or (org-element-property :contents-begin element)
23295 (user-error "No content for this element"))))
23296 (t (user-error "No inner element")))))
23298 (defun org-drag-element-backward ()
23299 "Move backward element at point."
23300 (interactive)
23301 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23302 (let* ((trail (org-element-at-point 'keep-trail))
23303 (elem (car trail))
23304 (prev-elem (nth 1 trail)))
23305 ;; Error out if no previous element or previous element is
23306 ;; a parent of the current one.
23307 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23308 (user-error "Cannot drag element backward")
23309 (let ((pos (point)))
23310 (org-element-swap-A-B prev-elem elem)
23311 (goto-char (+ (org-element-property :begin prev-elem)
23312 (- pos (org-element-property :begin elem)))))))))
23314 (defun org-drag-element-forward ()
23315 "Move forward element at point."
23316 (interactive)
23317 (let* ((pos (point))
23318 (elem (org-element-at-point)))
23319 (when (= (point-max) (org-element-property :end elem))
23320 (user-error "Cannot drag element forward"))
23321 (goto-char (org-element-property :end elem))
23322 (let ((next-elem (org-element-at-point)))
23323 (when (or (org-element-nested-p elem next-elem)
23324 (and (eq (org-element-type next-elem) 'headline)
23325 (not (eq (org-element-type elem) 'headline))))
23326 (goto-char pos)
23327 (user-error "Cannot drag element forward"))
23328 ;; Compute new position of point: it's shifted by NEXT-ELEM
23329 ;; body's length (without final blanks) and by the length of
23330 ;; blanks between ELEM and NEXT-ELEM.
23331 (let ((size-next (- (save-excursion
23332 (goto-char (org-element-property :end next-elem))
23333 (skip-chars-backward " \r\t\n")
23334 (forward-line)
23335 ;; Small correction if buffer doesn't end
23336 ;; with a newline character.
23337 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23338 (org-element-property :begin next-elem)))
23339 (size-blank (- (org-element-property :end elem)
23340 (save-excursion
23341 (goto-char (org-element-property :end elem))
23342 (skip-chars-backward " \r\t\n")
23343 (forward-line)
23344 (point)))))
23345 (org-element-swap-A-B elem next-elem)
23346 (goto-char (+ pos size-next size-blank))))))
23348 (defun org-drag-line-forward (arg)
23349 "Drag the line at point ARG lines forward."
23350 (interactive "p")
23351 (dotimes (n (abs arg))
23352 (let ((c (current-column)))
23353 (if (< 0 arg)
23354 (progn
23355 (beginning-of-line 2)
23356 (transpose-lines 1)
23357 (beginning-of-line 0))
23358 (transpose-lines 1)
23359 (beginning-of-line -1))
23360 (org-move-to-column c))))
23362 (defun org-drag-line-backward (arg)
23363 "Drag the line at point ARG lines backward."
23364 (interactive "p")
23365 (org-drag-line-forward (- arg)))
23367 (defun org-mark-element ()
23368 "Put point at beginning of this element, mark at end.
23370 Interactively, if this command is repeated or (in Transient Mark
23371 mode) if the mark is active, it marks the next element after the
23372 ones already marked."
23373 (interactive)
23374 (let (deactivate-mark)
23375 (if (and (org-called-interactively-p 'any)
23376 (or (and (eq last-command this-command) (mark t))
23377 (and transient-mark-mode mark-active)))
23378 (set-mark
23379 (save-excursion
23380 (goto-char (mark))
23381 (goto-char (org-element-property :end (org-element-at-point)))))
23382 (let ((element (org-element-at-point)))
23383 (end-of-line)
23384 (push-mark (org-element-property :end element) t t)
23385 (goto-char (org-element-property :begin element))))))
23387 (defun org-narrow-to-element ()
23388 "Narrow buffer to current element."
23389 (interactive)
23390 (let ((elem (org-element-at-point)))
23391 (cond
23392 ((eq (car elem) 'headline)
23393 (narrow-to-region
23394 (org-element-property :begin elem)
23395 (org-element-property :end elem)))
23396 ((memq (car elem) org-element-greater-elements)
23397 (narrow-to-region
23398 (org-element-property :contents-begin elem)
23399 (org-element-property :contents-end elem)))
23401 (narrow-to-region
23402 (org-element-property :begin elem)
23403 (org-element-property :end elem))))))
23405 (defun org-transpose-element ()
23406 "Transpose current and previous elements, keeping blank lines between.
23407 Point is moved after both elements."
23408 (interactive)
23409 (org-skip-whitespace)
23410 (let ((end (org-element-property :end (org-element-at-point))))
23411 (org-drag-element-backward)
23412 (goto-char end)))
23414 (defun org-unindent-buffer ()
23415 "Un-indent the visible part of the buffer.
23416 Relative indentation (between items, inside blocks, etc.) isn't
23417 modified."
23418 (interactive)
23419 (unless (eq major-mode 'org-mode)
23420 (user-error "Cannot un-indent a buffer not in Org mode"))
23421 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23422 unindent-tree ; For byte-compiler.
23423 (unindent-tree
23424 (function
23425 (lambda (contents)
23426 (mapc
23427 (lambda (element)
23428 (if (memq (org-element-type element) '(headline section))
23429 (funcall unindent-tree (org-element-contents element))
23430 (save-excursion
23431 (save-restriction
23432 (narrow-to-region
23433 (org-element-property :begin element)
23434 (org-element-property :end element))
23435 (org-do-remove-indentation)))))
23436 (reverse contents))))))
23437 (funcall unindent-tree (org-element-contents parse-tree))))
23439 (defun org-show-subtree ()
23440 "Show everything after this heading at deeper levels."
23441 (interactive)
23442 (outline-flag-region
23443 (point)
23444 (save-excursion
23445 (org-end-of-subtree t t))
23446 nil))
23448 (defun org-show-entry ()
23449 "Show the body directly following this heading.
23450 Show the heading too, if it is currently invisible."
23451 (interactive)
23452 (save-excursion
23453 (condition-case nil
23454 (progn
23455 (org-back-to-heading t)
23456 (outline-flag-region
23457 (max (point-min) (1- (point)))
23458 (save-excursion
23459 (if (re-search-forward
23460 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23461 (match-beginning 1)
23462 (point-max)))
23463 nil)
23464 (org-cycle-hide-drawers 'children))
23465 (error nil))))
23467 (defun org-make-options-regexp (kwds &optional extra)
23468 "Make a regular expression for keyword lines."
23469 (concat
23470 "^#\\+\\("
23471 (mapconcat 'regexp-quote kwds "\\|")
23472 (if extra (concat "\\|" extra))
23473 "\\):[ \t]*\\(.*\\)"))
23475 ;; Make isearch reveal the necessary context
23476 (defun org-isearch-end ()
23477 "Reveal context after isearch exits."
23478 (when isearch-success ; only if search was successful
23479 (if (featurep 'xemacs)
23480 ;; Under XEmacs, the hook is run in the correct place,
23481 ;; we directly show the context.
23482 (org-show-context 'isearch)
23483 ;; In Emacs the hook runs *before* restoring the overlays.
23484 ;; So we have to use a one-time post-command-hook to do this.
23485 ;; (Emacs 22 has a special variable, see function `org-mode')
23486 (unless (and (boundp 'isearch-mode-end-hook-quit)
23487 isearch-mode-end-hook-quit)
23488 ;; Only when the isearch was not quitted.
23489 (org-add-hook 'post-command-hook 'org-isearch-post-command
23490 'append 'local)))
23491 (org-fix-ellipsis-at-bol)))
23493 (defun org-isearch-post-command ()
23494 "Remove self from hook, and show context."
23495 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23496 (org-show-context 'isearch))
23499 ;;;; Integration with and fixes for other packages
23501 ;;; Imenu support
23503 (defvar org-imenu-markers nil
23504 "All markers currently used by Imenu.")
23505 (make-variable-buffer-local 'org-imenu-markers)
23507 (defun org-imenu-new-marker (&optional pos)
23508 "Return a new marker for use by Imenu, and remember the marker."
23509 (let ((m (make-marker)))
23510 (move-marker m (or pos (point)))
23511 (push m org-imenu-markers)
23514 (defun org-imenu-get-tree ()
23515 "Produce the index for Imenu."
23516 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23517 (setq org-imenu-markers nil)
23518 (let* ((n org-imenu-depth)
23519 (re (concat "^" (org-get-limited-outline-regexp)))
23520 (subs (make-vector (1+ n) nil))
23521 (last-level 0)
23522 m level head0 head)
23523 (save-excursion
23524 (save-restriction
23525 (widen)
23526 (goto-char (point-max))
23527 (while (re-search-backward re nil t)
23528 (setq level (org-reduced-level (funcall outline-level)))
23529 (when (and (<= level n)
23530 (looking-at org-complex-heading-regexp)
23531 (setq head0 (org-match-string-no-properties 4)))
23532 (setq head (org-link-display-format head0)
23533 m (org-imenu-new-marker))
23534 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23535 (if (>= level last-level)
23536 (push (cons head m) (aref subs level))
23537 (push (cons head (aref subs (1+ level))) (aref subs level))
23538 (loop for i from (1+ level) to n do (aset subs i nil)))
23539 (setq last-level level)))))
23540 (aref subs 1)))
23542 (eval-after-load "imenu"
23543 '(progn
23544 (add-hook 'imenu-after-jump-hook
23545 (lambda ()
23546 (if (derived-mode-p 'org-mode)
23547 (org-show-context 'org-goto))))))
23549 (defun org-link-display-format (link)
23550 "Replace a link with its the description.
23551 If there is no description, use the link target."
23552 (save-match-data
23553 (if (string-match org-bracket-link-analytic-regexp link)
23554 (replace-match (if (match-end 5)
23555 (match-string 5 link)
23556 (concat (match-string 1 link)
23557 (match-string 3 link)))
23558 nil t link)
23559 link)))
23561 (defun org-toggle-link-display ()
23562 "Toggle the literal or descriptive display of links."
23563 (interactive)
23564 (if org-descriptive-links
23565 (progn (org-remove-from-invisibility-spec '(org-link))
23566 (org-restart-font-lock)
23567 (setq org-descriptive-links nil))
23568 (progn (add-to-invisibility-spec '(org-link))
23569 (org-restart-font-lock)
23570 (setq org-descriptive-links t))))
23572 ;; Speedbar support
23574 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23575 "Overlay marking the agenda restriction line in speedbar.")
23576 (overlay-put org-speedbar-restriction-lock-overlay
23577 'face 'org-agenda-restriction-lock)
23578 (overlay-put org-speedbar-restriction-lock-overlay
23579 'help-echo "Agendas are currently limited to this item.")
23580 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23582 (defun org-speedbar-set-agenda-restriction ()
23583 "Restrict future agenda commands to the location at point in speedbar.
23584 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23585 (interactive)
23586 (require 'org-agenda)
23587 (let (p m tp np dir txt)
23588 (cond
23589 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23590 'org-imenu t))
23591 (setq m (get-text-property p 'org-imenu-marker))
23592 (with-current-buffer (marker-buffer m)
23593 (goto-char m)
23594 (org-agenda-set-restriction-lock 'subtree)))
23595 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23596 'speedbar-function 'speedbar-find-file))
23597 (setq tp (previous-single-property-change
23598 (1+ p) 'speedbar-function)
23599 np (next-single-property-change
23600 tp 'speedbar-function)
23601 dir (speedbar-line-directory)
23602 txt (buffer-substring-no-properties (or tp (point-min))
23603 (or np (point-max))))
23604 (with-current-buffer (find-file-noselect
23605 (let ((default-directory dir))
23606 (expand-file-name txt)))
23607 (unless (derived-mode-p 'org-mode)
23608 (user-error "Cannot restrict to non-Org-mode file"))
23609 (org-agenda-set-restriction-lock 'file)))
23610 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23611 (move-overlay org-speedbar-restriction-lock-overlay
23612 (point-at-bol) (point-at-eol))
23613 (setq current-prefix-arg nil)
23614 (org-agenda-maybe-redo)))
23616 (defvar speedbar-file-key-map)
23617 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23618 (eval-after-load "speedbar"
23619 '(progn
23620 (speedbar-add-supported-extension ".org")
23621 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23622 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23623 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23624 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23625 (add-hook 'speedbar-visiting-tag-hook
23626 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23628 ;;; Fixes and Hacks for problems with other packages
23630 ;; Make flyspell not check words in links, to not mess up our keymap
23631 (defvar org-element-affiliated-keywords) ; From org-element.el
23632 (defvar org-element-block-name-alist) ; From org-element.el
23633 (defun org-mode-flyspell-verify ()
23634 "Don't let flyspell put overlays at active buttons, or on
23635 {todo,all-time,additional-option-like}-keywords."
23636 (require 'org-element) ; For `org-element-affiliated-keywords'
23637 (let ((pos (max (1- (point)) (point-min)))
23638 (word (thing-at-point 'word)))
23639 (and (not (get-text-property pos 'keymap))
23640 (not (get-text-property pos 'org-no-flyspell))
23641 (not (member word org-todo-keywords-1))
23642 (not (member word org-all-time-keywords))
23643 (not (member word org-options-keywords))
23644 (not (member word (mapcar 'car org-startup-options)))
23645 (not (member-ignore-case word org-element-affiliated-keywords))
23646 (not (member-ignore-case word (org-get-export-keywords)))
23647 (not (member-ignore-case
23648 word (mapcar 'car org-element-block-name-alist)))
23649 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23650 (not (org-in-src-block-p)))))
23652 (defun org-remove-flyspell-overlays-in (beg end)
23653 "Remove flyspell overlays in region."
23654 (and (org-bound-and-true-p flyspell-mode)
23655 (fboundp 'flyspell-delete-region-overlays)
23656 (flyspell-delete-region-overlays beg end))
23657 (add-text-properties beg end '(org-no-flyspell t)))
23659 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23660 (eval-after-load "bookmark"
23661 '(if (boundp 'bookmark-after-jump-hook)
23662 ;; We can use the hook
23663 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23664 ;; Hook not available, use advice
23665 (defadvice bookmark-jump (after org-make-visible activate)
23666 "Make the position visible."
23667 (org-bookmark-jump-unhide))))
23669 ;; Make sure saveplace shows the location if it was hidden
23670 (eval-after-load "saveplace"
23671 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23672 "Make the position visible."
23673 (org-bookmark-jump-unhide)))
23675 ;; Make sure ecb shows the location if it was hidden
23676 (eval-after-load "ecb"
23677 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23678 "Make hierarchy visible when jumping into location from ECB tree buffer."
23679 (if (derived-mode-p 'org-mode)
23680 (org-show-context))))
23682 (defun org-bookmark-jump-unhide ()
23683 "Unhide the current position, to show the bookmark location."
23684 (and (derived-mode-p 'org-mode)
23685 (or (outline-invisible-p)
23686 (save-excursion (goto-char (max (point-min) (1- (point))))
23687 (outline-invisible-p)))
23688 (org-show-context 'bookmark-jump)))
23690 ;; Make session.el ignore our circular variable
23691 (defvar session-globals-exclude)
23692 (eval-after-load "session"
23693 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23695 ;;;; Finish up
23697 (provide 'org)
23699 (run-hooks 'org-load-hook)
23701 ;;; org.el ends here