Fix spacing and cursor position bug caused by `org-insert-property-drawer'
[org-mode.git] / lisp / org.el
blobc319c7f1240be0dadb3da9262f237d9b31a1fbb2
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: Grab links and url from various mac Applications" org-mac-link)
420 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
421 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
422 (const :tag "C mew: Links to Mew folders/messages" org-mew)
423 (const :tag "C mtags: Support for muse-like tags" org-mtags)
424 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
425 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
426 (const :tag "C registry: A registry for Org-mode links" org-registry)
427 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
428 (const :tag "C secretary: Team management with org-mode" org-secretary)
429 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
430 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
431 (const :tag "C track: Keep up with Org-mode development" org-track)
432 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
433 (const :tag "C vm: Links to VM folders/messages" org-vm)
434 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
435 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
436 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
438 (defvar org-export--registered-backends) ; From ox.el.
439 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
440 (declare-function org-export-backend-name "ox" (backend))
441 (defcustom org-export-backends '(ascii html icalendar latex)
442 "List of export back-ends that should be always available.
444 If a description starts with <C>, the file is not part of Emacs
445 and loading it will require that you have downloaded and properly
446 installed the Org mode distribution.
448 Unlike to `org-modules', libraries in this list will not be
449 loaded along with Org, but only once the export framework is
450 needed.
452 This variable needs to be set before org.el is loaded. If you
453 need to make a change while Emacs is running, use the customize
454 interface or run the following code, where VAL stands for the new
455 value of the variable, after updating it:
457 \(progn
458 \(setq org-export--registered-backends
459 \(org-remove-if-not
460 \(lambda (backend)
461 \(let ((name (org-export-backend-name backend)))
462 \(or (memq name val)
463 \(catch 'parentp
464 \(dolist (b val)
465 \(and (org-export-derived-backend-p b name)
466 \(throw 'parentp t)))))))
467 org-export--registered-backends))
468 \(let ((new-list (mapcar 'org-export-backend-name
469 org-export--registered-backends)))
470 \(dolist (backend val)
471 \(cond
472 \((not (load (format \"ox-%s\" backend) t t))
473 \(message \"Problems while trying to load export back-end `%s'\"
474 backend))
475 \((not (memq backend new-list)) (push backend new-list))))
476 \(set-default 'org-export-backends new-list)))
478 Adding a back-end to this list will also pull the back-end it
479 depends on, if any."
480 :group 'org
481 :group 'org-export
482 :version "24.4"
483 :package-version '(Org . "8.0")
484 :initialize 'custom-initialize-set
485 :set (lambda (var val)
486 (if (not (featurep 'ox)) (set-default var val)
487 ;; Any back-end not required anymore (not present in VAL and not
488 ;; a parent of any back-end in the new value) is removed from the
489 ;; list of registered back-ends.
490 (setq org-export--registered-backends
491 (org-remove-if-not
492 (lambda (backend)
493 (let ((name (org-export-backend-name backend)))
494 (or (memq name val)
495 (catch 'parentp
496 (dolist (b val)
497 (and (org-export-derived-backend-p b name)
498 (throw 'parentp t)))))))
499 org-export--registered-backends))
500 ;; Now build NEW-LIST of both new back-ends and required
501 ;; parents.
502 (let ((new-list (mapcar 'org-export-backend-name
503 org-export--registered-backends)))
504 (dolist (backend val)
505 (cond
506 ((not (load (format "ox-%s" backend) t t))
507 (message "Problems while trying to load export back-end `%s'"
508 backend))
509 ((not (memq backend new-list)) (push backend new-list))))
510 ;; Set VAR to that list with fixed dependencies.
511 (set-default var new-list))))
512 :type '(set :greedy t
513 (const :tag " ascii Export buffer to ASCII format" ascii)
514 (const :tag " beamer Export buffer to Beamer presentation" beamer)
515 (const :tag " html Export buffer to HTML format" html)
516 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
517 (const :tag " latex Export buffer to LaTeX format" latex)
518 (const :tag " man Export buffer to MAN format" man)
519 (const :tag " md Export buffer to Markdown format" md)
520 (const :tag " odt Export buffer to ODT format" odt)
521 (const :tag " org Export buffer to Org format" org)
522 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
523 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
524 (const :tag "C deck Export buffer to deck.js presentations" deck)
525 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
526 (const :tag "C groff Export buffer to Groff format" groff)
527 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
528 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
529 (const :tag "C s5 Export buffer to s5 presentations" s5)
530 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
532 (eval-after-load 'ox
533 '(mapc
534 (lambda (backend)
535 (condition-case nil (require (intern (format "ox-%s" backend)))
536 (error (message "Problems while trying to load export back-end `%s'"
537 backend))))
538 org-export-backends))
540 (defcustom org-support-shift-select nil
541 "Non-nil means make shift-cursor commands select text when possible.
543 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
544 start selecting a region, or enlarge regions started in this way.
545 In Org-mode, in special contexts, these same keys are used for
546 other purposes, important enough to compete with shift selection.
547 Org tries to balance these needs by supporting `shift-select-mode'
548 outside these special contexts, under control of this variable.
550 The default of this variable is nil, to avoid confusing behavior. Shifted
551 cursor keys will then execute Org commands in the following contexts:
552 - on a headline, changing TODO state (left/right) and priority (up/down)
553 - on a time stamp, changing the time
554 - in a plain list item, changing the bullet type
555 - in a property definition line, switching between allowed values
556 - in the BEGIN line of a clock table (changing the time block).
557 Outside these contexts, the commands will throw an error.
559 When this variable is t and the cursor is not in a special
560 context, Org-mode will support shift-selection for making and
561 enlarging regions. To make this more effective, the bullet
562 cycling will no longer happen anywhere in an item line, but only
563 if the cursor is exactly on the bullet.
565 If you set this variable to the symbol `always', then the keys
566 will not be special in headlines, property lines, and item lines,
567 to make shift selection work there as well. If this is what you
568 want, you can use the following alternative commands: `C-c C-t'
569 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
570 can be used to switch TODO sets, `C-c -' to cycle item bullet
571 types, and properties can be edited by hand or in column view.
573 However, when the cursor is on a timestamp, shift-cursor commands
574 will still edit the time stamp - this is just too good to give up.
576 XEmacs user should have this variable set to nil, because
577 `shift-select-mode' is in Emacs 23 or later only."
578 :group 'org
579 :type '(choice
580 (const :tag "Never" nil)
581 (const :tag "When outside special context" t)
582 (const :tag "Everywhere except timestamps" always)))
584 (defcustom org-loop-over-headlines-in-active-region nil
585 "Shall some commands act upon headlines in the active region?
587 When set to `t', some commands will be performed in all headlines
588 within the active region.
590 When set to `start-level', some commands will be performed in all
591 headlines within the active region, provided that these headlines
592 are of the same level than the first one.
594 When set to a string, those commands will be performed on the
595 matching headlines within the active region. Such string must be
596 a tags/property/todo match as it is used in the agenda tags view.
598 The list of commands is: `org-schedule', `org-deadline',
599 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
600 `org-archive-to-archive-sibling'. The archiving commands skip
601 already archived entries."
602 :type '(choice (const :tag "Don't loop" nil)
603 (const :tag "All headlines in active region" t)
604 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
605 (string :tag "Tags/Property/Todo matcher"))
606 :version "24.1"
607 :group 'org-todo
608 :group 'org-archive)
610 (defgroup org-startup nil
611 "Options concerning startup of Org-mode."
612 :tag "Org Startup"
613 :group 'org)
615 (defcustom org-startup-folded t
616 "Non-nil means entering Org-mode will switch to OVERVIEW.
617 This can also be configured on a per-file basis by adding one of
618 the following lines anywhere in the buffer:
620 #+STARTUP: fold (or `overview', this is equivalent)
621 #+STARTUP: nofold (or `showall', this is equivalent)
622 #+STARTUP: content
623 #+STARTUP: showeverything
625 By default, this option is ignored when Org opens agenda files
626 for the first time. If you want the agenda to honor the startup
627 option, set `org-agenda-inhibit-startup' to nil."
628 :group 'org-startup
629 :type '(choice
630 (const :tag "nofold: show all" nil)
631 (const :tag "fold: overview" t)
632 (const :tag "content: all headlines" content)
633 (const :tag "show everything, even drawers" showeverything)))
635 (defcustom org-startup-truncated t
636 "Non-nil means entering Org-mode will set `truncate-lines'.
637 This is useful since some lines containing links can be very long and
638 uninteresting. Also tables look terrible when wrapped."
639 :group 'org-startup
640 :type 'boolean)
642 (defcustom org-startup-indented nil
643 "Non-nil means turn on `org-indent-mode' on startup.
644 This can also be configured on a per-file basis by adding one of
645 the following lines anywhere in the buffer:
647 #+STARTUP: indent
648 #+STARTUP: noindent"
649 :group 'org-structure
650 :type '(choice
651 (const :tag "Not" nil)
652 (const :tag "Globally (slow on startup in large files)" t)))
654 (defcustom org-use-sub-superscripts t
655 "Non-nil means interpret \"_\" and \"^\" for display.
656 When this option is turned on, you can use TeX-like syntax for sub- and
657 superscripts. Several characters after \"_\" or \"^\" will be
658 considered as a single item - so grouping with {} is normally not
659 needed. For example, the following things will be parsed as single
660 sub- or superscripts.
662 10^24 or 10^tau several digits will be considered 1 item.
663 10^-12 or 10^-tau a leading sign with digits or a word
664 x^2-y^3 will be read as x^2 - y^3, because items are
665 terminated by almost any nonword/nondigit char.
666 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
668 Still, ambiguity is possible - so when in doubt use {} to enclose
669 the sub/superscript. If you set this variable to the symbol
670 `{}', the braces are *required* in order to trigger
671 interpretations as sub/superscript. This can be helpful in
672 documents that need \"_\" frequently in plain text."
673 :group 'org-startup
674 :version "24.1"
675 :type '(choice
676 (const :tag "Always interpret" t)
677 (const :tag "Only with braces" {})
678 (const :tag "Never interpret" nil)))
680 (defcustom org-startup-with-beamer-mode nil
681 "Non-nil means turn on `org-beamer-mode' on startup.
682 This can also be configured on a per-file basis by adding one of
683 the following lines anywhere in the buffer:
685 #+STARTUP: beamer"
686 :group 'org-startup
687 :version "24.1"
688 :type 'boolean)
690 (defcustom org-startup-align-all-tables nil
691 "Non-nil means align all tables when visiting a file.
692 This is useful when the column width in tables is forced with <N> cookies
693 in table fields. Such tables will look correct only after the first re-align.
694 This can also be configured on a per-file basis by adding one of
695 the following lines anywhere in the buffer:
696 #+STARTUP: align
697 #+STARTUP: noalign"
698 :group 'org-startup
699 :type 'boolean)
701 (defcustom org-startup-with-inline-images nil
702 "Non-nil means show inline images when loading a new Org file.
703 This can also be configured on a per-file basis by adding one of
704 the following lines anywhere in the buffer:
705 #+STARTUP: inlineimages
706 #+STARTUP: noinlineimages"
707 :group 'org-startup
708 :version "24.1"
709 :type 'boolean)
711 (defcustom org-startup-with-latex-preview nil
712 "Non-nil means preview LaTeX fragments when loading a new Org file.
714 This can also be configured on a per-file basis by adding one of
715 the followinglines anywhere in the buffer:
716 #+STARTUP: latexpreview
717 #+STARTUP: nolatexpreview"
718 :group 'org-startup
719 :version "24.4"
720 :package-version '(Org . "8.0")
721 :type 'boolean)
723 (defcustom org-insert-mode-line-in-empty-file nil
724 "Non-nil means insert the first line setting Org-mode in empty files.
725 When the function `org-mode' is called interactively in an empty file, this
726 normally means that the file name does not automatically trigger Org-mode.
727 To ensure that the file will always be in Org-mode in the future, a
728 line enforcing Org-mode will be inserted into the buffer, if this option
729 has been set."
730 :group 'org-startup
731 :type 'boolean)
733 (defcustom org-replace-disputed-keys nil
734 "Non-nil means use alternative key bindings for some keys.
735 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
736 These keys are also used by other packages like shift-selection-mode'
737 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
738 If you want to use Org-mode together with one of these other modes,
739 or more generally if you would like to move some Org-mode commands to
740 other keys, set this variable and configure the keys with the variable
741 `org-disputed-keys'.
743 This option is only relevant at load-time of Org-mode, and must be set
744 *before* org.el is loaded. Changing it requires a restart of Emacs to
745 become effective."
746 :group 'org-startup
747 :type 'boolean)
749 (defcustom org-use-extra-keys nil
750 "Non-nil means use extra key sequence definitions for certain commands.
751 This happens automatically if you run XEmacs or if `window-system'
752 is nil. This variable lets you do the same manually. You must
753 set it before loading org.
755 Example: on Carbon Emacs 22 running graphically, with an external
756 keyboard on a Powerbook, the default way of setting M-left might
757 not work for either Alt or ESC. Setting this variable will make
758 it work for ESC."
759 :group 'org-startup
760 :type 'boolean)
762 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
764 (defcustom org-disputed-keys
765 '(([(shift up)] . [(meta p)])
766 ([(shift down)] . [(meta n)])
767 ([(shift left)] . [(meta -)])
768 ([(shift right)] . [(meta +)])
769 ([(control shift right)] . [(meta shift +)])
770 ([(control shift left)] . [(meta shift -)]))
771 "Keys for which Org-mode and other modes compete.
772 This is an alist, cars are the default keys, second element specifies
773 the alternative to use when `org-replace-disputed-keys' is t.
775 Keys can be specified in any syntax supported by `define-key'.
776 The value of this option takes effect only at Org-mode's startup,
777 therefore you'll have to restart Emacs to apply it after changing."
778 :group 'org-startup
779 :type 'alist)
781 (defun org-key (key)
782 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
783 Or return the original if not disputed.
784 Also apply the translations defined in `org-xemacs-key-equivalents'."
785 (when org-replace-disputed-keys
786 (let* ((nkey (key-description key))
787 (x (org-find-if (lambda (x)
788 (equal (key-description (car x)) nkey))
789 org-disputed-keys)))
790 (setq key (if x (cdr x) key))))
791 (when (featurep 'xemacs)
792 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
793 key)
795 (defun org-find-if (predicate seq)
796 (catch 'exit
797 (while seq
798 (if (funcall predicate (car seq))
799 (throw 'exit (car seq))
800 (pop seq)))))
802 (defun org-defkey (keymap key def)
803 "Define a key, possibly translated, as returned by `org-key'."
804 (define-key keymap (org-key key) def))
806 (defcustom org-ellipsis nil
807 "The ellipsis to use in the Org-mode outline.
808 When nil, just use the standard three dots. When a string, use that instead,
809 When a face, use the standard 3 dots, but with the specified face.
810 The change affects only Org-mode (which will then use its own display table).
811 Changing this requires executing `M-x org-mode' in a buffer to become
812 effective."
813 :group 'org-startup
814 :type '(choice (const :tag "Default" nil)
815 (face :tag "Face" :value org-warning)
816 (string :tag "String" :value "...#")))
818 (defvar org-display-table nil
819 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
821 (defgroup org-keywords nil
822 "Keywords in Org-mode."
823 :tag "Org Keywords"
824 :group 'org)
826 (defcustom org-deadline-string "DEADLINE:"
827 "String to mark deadline entries.
828 A deadline is this string, followed by a time stamp. Should be a word,
829 terminated by a colon. You can insert a schedule keyword and
830 a timestamp with \\[org-deadline].
831 Changes become only effective after restarting Emacs."
832 :group 'org-keywords
833 :type 'string)
835 (defcustom org-scheduled-string "SCHEDULED:"
836 "String to mark scheduled TODO entries.
837 A schedule is this string, followed by a time stamp. Should be a word,
838 terminated by a colon. You can insert a schedule keyword and
839 a timestamp with \\[org-schedule].
840 Changes become only effective after restarting Emacs."
841 :group 'org-keywords
842 :type 'string)
844 (defcustom org-closed-string "CLOSED:"
845 "String used as the prefix for timestamps logging closing a TODO entry."
846 :group 'org-keywords
847 :type 'string)
849 (defcustom org-clock-string "CLOCK:"
850 "String used as prefix for timestamps clocking work hours on an item."
851 :group 'org-keywords
852 :type 'string)
854 (defcustom org-closed-keep-when-no-todo nil
855 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
856 :group 'org-todo
857 :group 'org-keywords
858 :version "24.4"
859 :package-version '(Org . "8.0")
860 :type 'boolean)
862 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
863 org-scheduled-string "\\|"
864 org-deadline-string "\\|"
865 org-closed-string "\\|"
866 org-clock-string "\\)")
867 "Matches a line with planning or clock info.")
869 (defcustom org-comment-string "COMMENT"
870 "Entries starting with this keyword will never be exported.
871 An entry can be toggled between COMMENT and normal with
872 \\[org-toggle-comment].
873 Changes become only effective after restarting Emacs."
874 :group 'org-keywords
875 :type 'string)
877 (defcustom org-quote-string "QUOTE"
878 "Entries starting with this keyword will be exported in fixed-width font.
879 Quoting applies only to the text in the entry following the headline, and does
880 not extend beyond the next headline, even if that is lower level.
881 An entry can be toggled between QUOTE and normal with
882 \\[org-toggle-fixed-width-section]."
883 :group 'org-keywords
884 :type 'string)
886 (defconst org-repeat-re
887 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
888 "Regular expression for specifying repeated events.
889 After a match, group 1 contains the repeat expression.")
891 (defgroup org-structure nil
892 "Options concerning the general structure of Org-mode files."
893 :tag "Org Structure"
894 :group 'org)
896 (defgroup org-reveal-location nil
897 "Options about how to make context of a location visible."
898 :tag "Org Reveal Location"
899 :group 'org-structure)
901 (defconst org-context-choice
902 '(choice
903 (const :tag "Always" t)
904 (const :tag "Never" nil)
905 (repeat :greedy t :tag "Individual contexts"
906 (cons
907 (choice :tag "Context"
908 (const agenda)
909 (const org-goto)
910 (const occur-tree)
911 (const tags-tree)
912 (const link-search)
913 (const mark-goto)
914 (const bookmark-jump)
915 (const isearch)
916 (const default))
917 (boolean))))
918 "Contexts for the reveal options.")
920 (defcustom org-show-hierarchy-above '((default . t))
921 "Non-nil means show full hierarchy when revealing a location.
922 Org-mode often shows locations in an org-mode file which might have
923 been invisible before. When this is set, the hierarchy of headings
924 above the exposed location is shown.
925 Turning this off for example for sparse trees makes them very compact.
926 Instead of t, this can also be an alist specifying this option for different
927 contexts. Valid contexts are
928 agenda when exposing an entry from the agenda
929 org-goto when using the command `org-goto' on key C-c C-j
930 occur-tree when using the command `org-occur' on key C-c /
931 tags-tree when constructing a sparse tree based on tags matches
932 link-search when exposing search matches associated with a link
933 mark-goto when exposing the jump goal of a mark
934 bookmark-jump when exposing a bookmark location
935 isearch when exiting from an incremental search
936 default default for all contexts not set explicitly"
937 :group 'org-reveal-location
938 :type org-context-choice)
940 (defcustom org-show-following-heading '((default . nil))
941 "Non-nil means show following heading when revealing a location.
942 Org-mode often shows locations in an org-mode file which might have
943 been invisible before. When this is set, the heading following the
944 match is shown.
945 Turning this off for example for sparse trees makes them very compact,
946 but makes it harder to edit the location of the match. In such a case,
947 use the command \\[org-reveal] to show more context.
948 Instead of t, this can also be an alist specifying this option for different
949 contexts. See `org-show-hierarchy-above' for valid contexts."
950 :group 'org-reveal-location
951 :type org-context-choice)
953 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
954 "Non-nil means show all sibling heading when revealing a location.
955 Org-mode often shows locations in an org-mode file which might have
956 been invisible before. When this is set, the sibling of the current entry
957 heading are all made visible. If `org-show-hierarchy-above' is t,
958 the same happens on each level of the hierarchy above the current entry.
960 By default this is on for the isearch context, off for all other contexts.
961 Turning this off for example for sparse trees makes them very compact,
962 but makes it harder to edit the location of the match. In such a case,
963 use the command \\[org-reveal] to show more context.
964 Instead of t, this can also be an alist specifying this option for different
965 contexts. See `org-show-hierarchy-above' for valid contexts."
966 :group 'org-reveal-location
967 :type org-context-choice
968 :version "24.4"
969 :package-version '(Org . "8.0"))
971 (defcustom org-show-entry-below '((default . nil))
972 "Non-nil means show the entry below a headline when revealing a location.
973 Org-mode often shows locations in an org-mode file which might have
974 been invisible before. When this is set, the text below the headline that is
975 exposed is also shown.
977 By default this is off for all contexts.
978 Instead of t, this can also be an alist specifying this option for different
979 contexts. See `org-show-hierarchy-above' for valid contexts."
980 :group 'org-reveal-location
981 :type org-context-choice)
983 (defcustom org-indirect-buffer-display 'other-window
984 "How should indirect tree buffers be displayed?
985 This applies to indirect buffers created with the commands
986 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
987 Valid values are:
988 current-window Display in the current window
989 other-window Just display in another window.
990 dedicated-frame Create one new frame, and re-use it each time.
991 new-frame Make a new frame each time. Note that in this case
992 previously-made indirect buffers are kept, and you need to
993 kill these buffers yourself."
994 :group 'org-structure
995 :group 'org-agenda-windows
996 :type '(choice
997 (const :tag "In current window" current-window)
998 (const :tag "In current frame, other window" other-window)
999 (const :tag "Each time a new frame" new-frame)
1000 (const :tag "One dedicated frame" dedicated-frame)))
1002 (defcustom org-use-speed-commands nil
1003 "Non-nil means activate single letter commands at beginning of a headline.
1004 This may also be a function to test for appropriate locations where speed
1005 commands should be active."
1006 :group 'org-structure
1007 :type '(choice
1008 (const :tag "Never" nil)
1009 (const :tag "At beginning of headline stars" t)
1010 (function)))
1012 (defcustom org-speed-commands-user nil
1013 "Alist of additional speed commands.
1014 This list will be checked before `org-speed-commands-default'
1015 when the variable `org-use-speed-commands' is non-nil
1016 and when the cursor is at the beginning of a headline.
1017 The car if each entry is a string with a single letter, which must
1018 be assigned to `self-insert-command' in the global map.
1019 The cdr is either a command to be called interactively, a function
1020 to be called, or a form to be evaluated.
1021 An entry that is just a list with a single string will be interpreted
1022 as a descriptive headline that will be added when listing the speed
1023 commands in the Help buffer using the `?' speed command."
1024 :group 'org-structure
1025 :type '(repeat :value ("k" . ignore)
1026 (choice :value ("k" . ignore)
1027 (list :tag "Descriptive Headline" (string :tag "Headline"))
1028 (cons :tag "Letter and Command"
1029 (string :tag "Command letter")
1030 (choice
1031 (function)
1032 (sexp))))))
1034 (defcustom org-bookmark-names-plist
1035 '(:last-capture "org-capture-last-stored"
1036 :last-refile "org-refile-last-stored"
1037 :last-capture-marker "org-capture-last-stored-marker")
1038 "Names for bookmarks automatically set by some Org commands.
1039 This can provide strings as names for a number of bookmakrs Org sets
1040 automatically. The following keys are currently implemented:
1041 :last-capture
1042 :last-capture-marker
1043 :last-refile
1044 When a key does not show up in the property list, the corresponding bookmark
1045 is not set."
1046 :group 'org-structure
1047 :type 'plist)
1049 (defgroup org-cycle nil
1050 "Options concerning visibility cycling in Org-mode."
1051 :tag "Org Cycle"
1052 :group 'org-structure)
1054 (defcustom org-cycle-skip-children-state-if-no-children t
1055 "Non-nil means skip CHILDREN state in entries that don't have any."
1056 :group 'org-cycle
1057 :type 'boolean)
1059 (defcustom org-cycle-max-level nil
1060 "Maximum level which should still be subject to visibility cycling.
1061 Levels higher than this will, for cycling, be treated as text, not a headline.
1062 When `org-odd-levels-only' is set, a value of N in this variable actually
1063 means 2N-1 stars as the limiting headline.
1064 When nil, cycle all levels.
1065 Note that the limiting level of cycling is also influenced by
1066 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1067 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1068 than its value."
1069 :group 'org-cycle
1070 :type '(choice
1071 (const :tag "No limit" nil)
1072 (integer :tag "Maximum level")))
1074 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1075 "Names of drawers. Drawers are not opened by cycling on the headline above.
1076 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1077 this:
1078 :DRAWERNAME:
1079 .....
1080 :END:
1081 The drawer \"PROPERTIES\" is special for capturing properties through
1082 the property API.
1084 Drawers can be defined on the per-file basis with a line like:
1086 #+DRAWERS: HIDDEN STATE PROPERTIES"
1087 :group 'org-structure
1088 :group 'org-cycle
1089 :type '(repeat (string :tag "Drawer Name")))
1091 (defcustom org-hide-block-startup nil
1092 "Non-nil means entering Org-mode will fold all blocks.
1093 This can also be set in on a per-file basis with
1095 #+STARTUP: hideblocks
1096 #+STARTUP: showblocks"
1097 :group 'org-startup
1098 :group 'org-cycle
1099 :type 'boolean)
1101 (defcustom org-cycle-global-at-bob nil
1102 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1103 This makes it possible to do global cycling without having to use S-TAB or
1104 \\[universal-argument] TAB. For this special case to work, the first line
1105 of the buffer must not be a headline -- it may be empty or some other text.
1106 When used in this way, `org-cycle-hook' is disabled temporarily to make
1107 sure the cursor stays at the beginning of the buffer. When this option is
1108 nil, don't do anything special at the beginning of the buffer."
1109 :group 'org-cycle
1110 :type 'boolean)
1112 (defcustom org-cycle-level-after-item/entry-creation t
1113 "Non-nil means cycle entry level or item indentation in new empty entries.
1115 When the cursor is at the end of an empty headline, i.e., with only stars
1116 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1117 and then all possible ancestor states, before returning to the original state.
1118 This makes data entry extremely fast: M-RET to create a new headline,
1119 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1121 When the cursor is at the end of an empty plain list item, one TAB will
1122 make it a subitem, two or more tabs will back up to make this an item
1123 higher up in the item hierarchy."
1124 :group 'org-cycle
1125 :type 'boolean)
1127 (defcustom org-cycle-emulate-tab t
1128 "Where should `org-cycle' emulate TAB.
1129 nil Never
1130 white Only in completely white lines
1131 whitestart Only at the beginning of lines, before the first non-white char
1132 t Everywhere except in headlines
1133 exc-hl-bol Everywhere except at the start of a headline
1134 If TAB is used in a place where it does not emulate TAB, the current subtree
1135 visibility is cycled."
1136 :group 'org-cycle
1137 :type '(choice (const :tag "Never" nil)
1138 (const :tag "Only in completely white lines" white)
1139 (const :tag "Before first char in a line" whitestart)
1140 (const :tag "Everywhere except in headlines" t)
1141 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1143 (defcustom org-cycle-separator-lines 2
1144 "Number of empty lines needed to keep an empty line between collapsed trees.
1145 If you leave an empty line between the end of a subtree and the following
1146 headline, this empty line is hidden when the subtree is folded.
1147 Org-mode will leave (exactly) one empty line visible if the number of
1148 empty lines is equal or larger to the number given in this variable.
1149 So the default 2 means at least 2 empty lines after the end of a subtree
1150 are needed to produce free space between a collapsed subtree and the
1151 following headline.
1153 If the number is negative, and the number of empty lines is at least -N,
1154 all empty lines are shown.
1156 Special case: when 0, never leave empty lines in collapsed view."
1157 :group 'org-cycle
1158 :type 'integer)
1159 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1161 (defcustom org-pre-cycle-hook nil
1162 "Hook that is run before visibility cycling is happening.
1163 The function(s) in this hook must accept a single argument which indicates
1164 the new state that will be set right after running this hook. The
1165 argument is a symbol. Before a global state change, it can have the values
1166 `overview', `content', or `all'. Before a local state change, it can have
1167 the values `folded', `children', or `subtree'."
1168 :group 'org-cycle
1169 :type 'hook)
1171 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1172 org-cycle-hide-drawers
1173 org-cycle-hide-inline-tasks
1174 org-cycle-show-empty-lines
1175 org-optimize-window-after-visibility-change)
1176 "Hook that is run after `org-cycle' has changed the buffer visibility.
1177 The function(s) in this hook must accept a single argument which indicates
1178 the new state that was set by the most recent `org-cycle' command. The
1179 argument is a symbol. After a global state change, it can have the values
1180 `overview', `contents', or `all'. After a local state change, it can have
1181 the values `folded', `children', or `subtree'."
1182 :group 'org-cycle
1183 :type 'hook)
1185 (defgroup org-edit-structure nil
1186 "Options concerning structure editing in Org-mode."
1187 :tag "Org Edit Structure"
1188 :group 'org-structure)
1190 (defcustom org-odd-levels-only nil
1191 "Non-nil means skip even levels and only use odd levels for the outline.
1192 This has the effect that two stars are being added/taken away in
1193 promotion/demotion commands. It also influences how levels are
1194 handled by the exporters.
1195 Changing it requires restart of `font-lock-mode' to become effective
1196 for fontification also in regions already fontified.
1197 You may also set this on a per-file basis by adding one of the following
1198 lines to the buffer:
1200 #+STARTUP: odd
1201 #+STARTUP: oddeven"
1202 :group 'org-edit-structure
1203 :group 'org-appearance
1204 :type 'boolean)
1206 (defcustom org-adapt-indentation t
1207 "Non-nil means adapt indentation to outline node level.
1209 When this variable is set, Org assumes that you write outlines by
1210 indenting text in each node to align with the headline (after the stars).
1211 The following issues are influenced by this variable:
1213 - When this is set and the *entire* text in an entry is indented, the
1214 indentation is increased by one space in a demotion command, and
1215 decreased by one in a promotion command. If any line in the entry
1216 body starts with text at column 0, indentation is not changed at all.
1218 - Property drawers and planning information is inserted indented when
1219 this variable s set. When nil, they will not be indented.
1221 - TAB indents a line relative to context. The lines below a headline
1222 will be indented when this variable is set.
1224 Note that this is all about true indentation, by adding and removing
1225 space characters. See also `org-indent.el' which does level-dependent
1226 indentation in a virtual way, i.e. at display time in Emacs."
1227 :group 'org-edit-structure
1228 :type 'boolean)
1230 (defcustom org-special-ctrl-a/e nil
1231 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1233 When t, `C-a' will bring back the cursor to the beginning of the
1234 headline text, i.e. after the stars and after a possible TODO
1235 keyword. In an item, this will be the position after bullet and
1236 check-box, if any. When the cursor is already at that position,
1237 another `C-a' will bring it to the beginning of the line.
1239 `C-e' will jump to the end of the headline, ignoring the presence
1240 of tags in the headline. A second `C-e' will then jump to the
1241 true end of the line, after any tags. This also means that, when
1242 this variable is non-nil, `C-e' also will never jump beyond the
1243 end of the heading of a folded section, i.e. not after the
1244 ellipses.
1246 When set to the symbol `reversed', the first `C-a' or `C-e' works
1247 normally, going to the true line boundary first. Only a directly
1248 following, identical keypress will bring the cursor to the
1249 special positions.
1251 This may also be a cons cell where the behavior for `C-a' and
1252 `C-e' is set separately."
1253 :group 'org-edit-structure
1254 :type '(choice
1255 (const :tag "off" nil)
1256 (const :tag "on: after stars/bullet and before tags first" t)
1257 (const :tag "reversed: true line boundary first" reversed)
1258 (cons :tag "Set C-a and C-e separately"
1259 (choice :tag "Special C-a"
1260 (const :tag "off" nil)
1261 (const :tag "on: after stars/bullet first" t)
1262 (const :tag "reversed: before stars/bullet first" reversed))
1263 (choice :tag "Special C-e"
1264 (const :tag "off" nil)
1265 (const :tag "on: before tags first" t)
1266 (const :tag "reversed: after tags first" reversed)))))
1267 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1269 (defcustom org-special-ctrl-k nil
1270 "Non-nil means `C-k' will behave specially in headlines.
1271 When nil, `C-k' will call the default `kill-line' command.
1272 When t, the following will happen while the cursor is in the headline:
1274 - When the cursor is at the beginning of a headline, kill the entire
1275 line and possible the folded subtree below the line.
1276 - When in the middle of the headline text, kill the headline up to the tags.
1277 - When after the headline text, kill the tags."
1278 :group 'org-edit-structure
1279 :type 'boolean)
1281 (defcustom org-ctrl-k-protect-subtree nil
1282 "Non-nil means, do not delete a hidden subtree with C-k.
1283 When set to the symbol `error', simply throw an error when C-k is
1284 used to kill (part-of) a headline that has hidden text behind it.
1285 Any other non-nil value will result in a query to the user, if it is
1286 OK to kill that hidden subtree. When nil, kill without remorse."
1287 :group 'org-edit-structure
1288 :version "24.1"
1289 :type '(choice
1290 (const :tag "Do not protect hidden subtrees" nil)
1291 (const :tag "Protect hidden subtrees with a security query" t)
1292 (const :tag "Never kill a hidden subtree with C-k" error)))
1294 (defcustom org-special-ctrl-o t
1295 "Non-nil means, make `C-o' insert a row in tables."
1296 :group 'org-edit-structure
1297 :type 'boolean)
1299 (defcustom org-catch-invisible-edits nil
1300 "Check if in invisible region before inserting or deleting a character.
1301 Valid values are:
1303 nil Do not check, so just do invisible edits.
1304 error Throw an error and do nothing.
1305 show Make point visible, and do the requested edit.
1306 show-and-error Make point visible, then throw an error and abort the edit.
1307 smart Make point visible, and do insertion/deletion if it is
1308 adjacent to visible text and the change feels predictable.
1309 Never delete a previously invisible character or add in the
1310 middle or right after an invisible region. Basically, this
1311 allows insertion and backward-delete right before ellipses.
1312 FIXME: maybe in this case we should not even show?"
1313 :group 'org-edit-structure
1314 :version "24.1"
1315 :type '(choice
1316 (const :tag "Do not check" nil)
1317 (const :tag "Throw error when trying to edit" error)
1318 (const :tag "Unhide, but do not do the edit" show-and-error)
1319 (const :tag "Show invisible part and do the edit" show)
1320 (const :tag "Be smart and do the right thing" smart)))
1322 (defcustom org-yank-folded-subtrees t
1323 "Non-nil means when yanking subtrees, fold them.
1324 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1325 it starts with a heading and all other headings in it are either children
1326 or siblings, then fold all the subtrees. However, do this only if no
1327 text after the yank would be swallowed into a folded tree by this action."
1328 :group 'org-edit-structure
1329 :type 'boolean)
1331 (defcustom org-yank-adjusted-subtrees nil
1332 "Non-nil means when yanking subtrees, adjust the level.
1333 With this setting, `org-paste-subtree' is used to insert the subtree, see
1334 this function for details."
1335 :group 'org-edit-structure
1336 :type 'boolean)
1338 (defcustom org-M-RET-may-split-line '((default . t))
1339 "Non-nil means M-RET will split the line at the cursor position.
1340 When nil, it will go to the end of the line before making a
1341 new line.
1342 You may also set this option in a different way for different
1343 contexts. Valid contexts are:
1345 headline when creating a new headline
1346 item when creating a new item
1347 table in a table field
1348 default the value to be used for all contexts not explicitly
1349 customized"
1350 :group 'org-structure
1351 :group 'org-table
1352 :type '(choice
1353 (const :tag "Always" t)
1354 (const :tag "Never" nil)
1355 (repeat :greedy t :tag "Individual contexts"
1356 (cons
1357 (choice :tag "Context"
1358 (const headline)
1359 (const item)
1360 (const table)
1361 (const default))
1362 (boolean)))))
1365 (defcustom org-insert-heading-respect-content nil
1366 "Non-nil means insert new headings after the current subtree.
1367 When nil, the new heading is created directly after the current line.
1368 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1369 this variable on for the duration of the command."
1370 :group 'org-structure
1371 :type 'boolean)
1373 (defcustom org-blank-before-new-entry '((heading . auto)
1374 (plain-list-item . auto))
1375 "Should `org-insert-heading' leave a blank line before new heading/item?
1376 The value is an alist, with `heading' and `plain-list-item' as CAR,
1377 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1378 which case Org will look at the surrounding headings/items and try to
1379 make an intelligent decision whether to insert a blank line or not.
1381 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1382 the setting here is ignored and no empty line is inserted to avoid breaking
1383 the list structure."
1384 :group 'org-edit-structure
1385 :type '(list
1386 (cons (const heading)
1387 (choice (const :tag "Never" nil)
1388 (const :tag "Always" t)
1389 (const :tag "Auto" auto)))
1390 (cons (const plain-list-item)
1391 (choice (const :tag "Never" nil)
1392 (const :tag "Always" t)
1393 (const :tag "Auto" auto)))))
1395 (defcustom org-insert-heading-hook nil
1396 "Hook being run after inserting a new heading."
1397 :group 'org-edit-structure
1398 :type 'hook)
1400 (defcustom org-enable-fixed-width-editor t
1401 "Non-nil means lines starting with \":\" are treated as fixed-width.
1402 This currently only means they are never auto-wrapped.
1403 When nil, such lines will be treated like ordinary lines.
1404 See also the QUOTE keyword."
1405 :group 'org-edit-structure
1406 :type 'boolean)
1408 (defcustom org-goto-auto-isearch t
1409 "Non-nil means typing characters in `org-goto' starts incremental search.
1410 When nil, you can use these keybindings to navigate the buffer:
1412 q Quit the org-goto interface
1413 n Go to the next visible heading
1414 p Go to the previous visible heading
1415 f Go one heading forward on same level
1416 b Go one heading backward on same level
1417 u Go one heading up"
1418 :group 'org-edit-structure
1419 :type 'boolean)
1421 (defgroup org-sparse-trees nil
1422 "Options concerning sparse trees in Org-mode."
1423 :tag "Org Sparse Trees"
1424 :group 'org-structure)
1426 (defcustom org-highlight-sparse-tree-matches t
1427 "Non-nil means highlight all matches that define a sparse tree.
1428 The highlights will automatically disappear the next time the buffer is
1429 changed by an edit command."
1430 :group 'org-sparse-trees
1431 :type 'boolean)
1433 (defcustom org-remove-highlights-with-change t
1434 "Non-nil means any change to the buffer will remove temporary highlights.
1435 Such highlights are created by `org-occur' and `org-clock-display'.
1436 When nil, `C-c C-c needs to be used to get rid of the highlights.
1437 The highlights created by `org-preview-latex-fragment' always need
1438 `C-c C-c' to be removed."
1439 :group 'org-sparse-trees
1440 :group 'org-time
1441 :type 'boolean)
1444 (defcustom org-occur-hook '(org-first-headline-recenter)
1445 "Hook that is run after `org-occur' has constructed a sparse tree.
1446 This can be used to recenter the window to show as much of the structure
1447 as possible."
1448 :group 'org-sparse-trees
1449 :type 'hook)
1451 (defgroup org-imenu-and-speedbar nil
1452 "Options concerning imenu and speedbar in Org-mode."
1453 :tag "Org Imenu and Speedbar"
1454 :group 'org-structure)
1456 (defcustom org-imenu-depth 2
1457 "The maximum level for Imenu access to Org-mode headlines.
1458 This also applied for speedbar access."
1459 :group 'org-imenu-and-speedbar
1460 :type 'integer)
1462 (defgroup org-table nil
1463 "Options concerning tables in Org-mode."
1464 :tag "Org Table"
1465 :group 'org)
1467 (defcustom org-enable-table-editor 'optimized
1468 "Non-nil means lines starting with \"|\" are handled by the table editor.
1469 When nil, such lines will be treated like ordinary lines.
1471 When equal to the symbol `optimized', the table editor will be optimized to
1472 do the following:
1473 - Automatic overwrite mode in front of whitespace in table fields.
1474 This makes the structure of the table stay in tact as long as the edited
1475 field does not exceed the column width.
1476 - Minimize the number of realigns. Normally, the table is aligned each time
1477 TAB or RET are pressed to move to another field. With optimization this
1478 happens only if changes to a field might have changed the column width.
1479 Optimization requires replacing the functions `self-insert-command',
1480 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1481 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1482 very good at guessing when a re-align will be necessary, but you can always
1483 force one with \\[org-ctrl-c-ctrl-c].
1485 If you would like to use the optimized version in Org-mode, but the
1486 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1488 This variable can be used to turn on and off the table editor during a session,
1489 but in order to toggle optimization, a restart is required.
1491 See also the variable `org-table-auto-blank-field'."
1492 :group 'org-table
1493 :type '(choice
1494 (const :tag "off" nil)
1495 (const :tag "on" t)
1496 (const :tag "on, optimized" optimized)))
1498 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1499 (version<= emacs-version "24.1"))
1500 "Non-nil means cluster self-insert commands for undo when possible.
1501 If this is set, then, like in the Emacs command loop, 20 consecutive
1502 characters will be undone together.
1503 This is configurable, because there is some impact on typing performance."
1504 :group 'org-table
1505 :type 'boolean)
1507 (defcustom org-table-tab-recognizes-table.el t
1508 "Non-nil means TAB will automatically notice a table.el table.
1509 When it sees such a table, it moves point into it and - if necessary -
1510 calls `table-recognize-table'."
1511 :group 'org-table-editing
1512 :type 'boolean)
1514 (defgroup org-link nil
1515 "Options concerning links in Org-mode."
1516 :tag "Org Link"
1517 :group 'org)
1519 (defvar org-link-abbrev-alist-local nil
1520 "Buffer-local version of `org-link-abbrev-alist', which see.
1521 The value of this is taken from the #+LINK lines.")
1522 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1524 (defcustom org-link-abbrev-alist nil
1525 "Alist of link abbreviations.
1526 The car of each element is a string, to be replaced at the start of a link.
1527 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1528 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1530 [[linkkey:tag][description]]
1532 The 'linkkey' must be a word word, starting with a letter, followed
1533 by letters, numbers, '-' or '_'.
1535 If REPLACE is a string, the tag will simply be appended to create the link.
1536 If the string contains \"%s\", the tag will be inserted there. If the string
1537 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1538 at that point (see the function `url-hexify-string'). If the string contains
1539 the specifier \"%(my-function)\", then the custom function `my-function' will
1540 be invoked: this function takes the tag as its only argument and must return
1541 a string.
1543 REPLACE may also be a function that will be called with the tag as the
1544 only argument to create the link, which should be returned as a string.
1546 See the manual for examples."
1547 :group 'org-link
1548 :type '(repeat
1549 (cons
1550 (string :tag "Protocol")
1551 (choice
1552 (string :tag "Format")
1553 (function)))))
1555 (defcustom org-descriptive-links t
1556 "Non-nil means Org will display descriptive links.
1557 E.g. [[http://orgmode.org][Org website]] will be displayed as
1558 \"Org Website\", hiding the link itself and just displaying its
1559 description. When set to `nil', Org will display the full links
1560 literally.
1562 You can interactively set the value of this variable by calling
1563 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1564 :group 'org-link
1565 :type 'boolean)
1567 (defcustom org-link-file-path-type 'adaptive
1568 "How the path name in file links should be stored.
1569 Valid values are:
1571 relative Relative to the current directory, i.e. the directory of the file
1572 into which the link is being inserted.
1573 absolute Absolute path, if possible with ~ for home directory.
1574 noabbrev Absolute path, no abbreviation of home directory.
1575 adaptive Use relative path for files in the current directory and sub-
1576 directories of it. For other files, use an absolute path."
1577 :group 'org-link
1578 :type '(choice
1579 (const relative)
1580 (const absolute)
1581 (const noabbrev)
1582 (const adaptive)))
1584 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1585 "Types of links that should be activated in Org-mode files.
1586 This is a list of symbols, each leading to the activation of a certain link
1587 type. In principle, it does not hurt to turn on most link types - there may
1588 be a small gain when turning off unused link types. The types are:
1590 bracket The recommended [[link][description]] or [[link]] links with hiding.
1591 angle Links in angular brackets that may contain whitespace like
1592 <bbdb:Carsten Dominik>.
1593 plain Plain links in normal text, no whitespace, like http://google.com.
1594 radio Text that is matched by a radio target, see manual for details.
1595 tag Tag settings in a headline (link to tag search).
1596 date Time stamps (link to calendar).
1597 footnote Footnote labels.
1599 Changing this variable requires a restart of Emacs to become effective."
1600 :group 'org-link
1601 :type '(set :greedy t
1602 (const :tag "Double bracket links" bracket)
1603 (const :tag "Angular bracket links" angle)
1604 (const :tag "Plain text links" plain)
1605 (const :tag "Radio target matches" radio)
1606 (const :tag "Tags" tag)
1607 (const :tag "Timestamps" date)
1608 (const :tag "Footnotes" footnote)))
1610 (defcustom org-make-link-description-function nil
1611 "Function to use for generating link descriptions from links.
1612 When nil, the link location will be used. This function must take
1613 two parameters: the first one is the link, the second one is the
1614 description generated by `org-insert-link'. The function should
1615 return the description to use."
1616 :group 'org-link
1617 :type '(choice (const nil) (function)))
1619 (defgroup org-link-store nil
1620 "Options concerning storing links in Org-mode."
1621 :tag "Org Store Link"
1622 :group 'org-link)
1624 (defcustom org-url-hexify-p t
1625 "When non-nil, hexify URL when creating a link."
1626 :type 'boolean
1627 :version "24.3"
1628 :group 'org-link-store)
1630 (defcustom org-email-link-description-format "Email %c: %.30s"
1631 "Format of the description part of a link to an email or usenet message.
1632 The following %-escapes will be replaced by corresponding information:
1634 %F full \"From\" field
1635 %f name, taken from \"From\" field, address if no name
1636 %T full \"To\" field
1637 %t first name in \"To\" field, address if no name
1638 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1639 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1640 %s subject
1641 %d date
1642 %m message-id.
1644 You may use normal field width specification between the % and the letter.
1645 This is for example useful to limit the length of the subject.
1647 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1648 :group 'org-link-store
1649 :type 'string)
1651 (defcustom org-from-is-user-regexp
1652 (let (r1 r2)
1653 (when (and user-mail-address (not (string= user-mail-address "")))
1654 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1655 (when (and user-full-name (not (string= user-full-name "")))
1656 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1657 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1658 "Regexp matched against the \"From:\" header of an email or usenet message.
1659 It should match if the message is from the user him/herself."
1660 :group 'org-link-store
1661 :type 'regexp)
1663 (defcustom org-context-in-file-links t
1664 "Non-nil means file links from `org-store-link' contain context.
1665 A search string will be added to the file name with :: as separator and
1666 used to find the context when the link is activated by the command
1667 `org-open-at-point'. When this option is t, the entire active region
1668 will be placed in the search string of the file link. If set to a
1669 positive integer, only the first n lines of context will be stored.
1671 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1672 negates this setting for the duration of the command."
1673 :group 'org-link-store
1674 :type '(choice boolean integer))
1676 (defcustom org-keep-stored-link-after-insertion nil
1677 "Non-nil means keep link in list for entire session.
1679 The command `org-store-link' adds a link pointing to the current
1680 location to an internal list. These links accumulate during a session.
1681 The command `org-insert-link' can be used to insert links into any
1682 Org-mode file (offering completion for all stored links). When this
1683 option is nil, every link which has been inserted once using \\[org-insert-link]
1684 will be removed from the list, to make completing the unused links
1685 more efficient."
1686 :group 'org-link-store
1687 :type 'boolean)
1689 (defgroup org-link-follow nil
1690 "Options concerning following links in Org-mode."
1691 :tag "Org Follow Link"
1692 :group 'org-link)
1694 (defcustom org-link-translation-function nil
1695 "Function to translate links with different syntax to Org syntax.
1696 This can be used to translate links created for example by the Planner
1697 or emacs-wiki packages to Org syntax.
1698 The function must accept two parameters, a TYPE containing the link
1699 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1700 which is everything after the link protocol. It should return a cons
1701 with possibly modified values of type and path.
1702 Org contains a function for this, so if you set this variable to
1703 `org-translate-link-from-planner', you should be able follow many
1704 links created by planner."
1705 :group 'org-link-follow
1706 :type '(choice (const nil) (function)))
1708 (defcustom org-follow-link-hook nil
1709 "Hook that is run after a link has been followed."
1710 :group 'org-link-follow
1711 :type 'hook)
1713 (defcustom org-tab-follows-link nil
1714 "Non-nil means on links TAB will follow the link.
1715 Needs to be set before org.el is loaded.
1716 This really should not be used, it does not make sense, and the
1717 implementation is bad."
1718 :group 'org-link-follow
1719 :type 'boolean)
1721 (defcustom org-return-follows-link nil
1722 "Non-nil means on links RET will follow the link.
1723 In tables, the special behavior of RET has precedence."
1724 :group 'org-link-follow
1725 :type 'boolean)
1727 (defcustom org-mouse-1-follows-link
1728 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1729 "Non-nil means mouse-1 on a link will follow the link.
1730 A longer mouse click will still set point. Does not work on XEmacs.
1731 Needs to be set before org.el is loaded."
1732 :group 'org-link-follow
1733 :type 'boolean)
1735 (defcustom org-mark-ring-length 4
1736 "Number of different positions to be recorded in the ring.
1737 Changing this requires a restart of Emacs to work correctly."
1738 :group 'org-link-follow
1739 :type 'integer)
1741 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1742 "Non-nil means internal links in Org files must exactly match a headline.
1743 When nil, the link search tries to match a phrase with all words
1744 in the search text."
1745 :group 'org-link-follow
1746 :version "24.1"
1747 :type '(choice
1748 (const :tag "Use fuzzy text search" nil)
1749 (const :tag "Match only exact headline" t)
1750 (const :tag "Match exact headline or query to create it"
1751 query-to-create)))
1753 (defcustom org-link-frame-setup
1754 '((vm . vm-visit-folder-other-frame)
1755 (vm-imap . vm-visit-imap-folder-other-frame)
1756 (gnus . org-gnus-no-new-news)
1757 (file . find-file-other-window)
1758 (wl . wl-other-frame))
1759 "Setup the frame configuration for following links.
1760 When following a link with Emacs, it may often be useful to display
1761 this link in another window or frame. This variable can be used to
1762 set this up for the different types of links.
1763 For VM, use any of
1764 `vm-visit-folder'
1765 `vm-visit-folder-other-window'
1766 `vm-visit-folder-other-frame'
1767 For Gnus, use any of
1768 `gnus'
1769 `gnus-other-frame'
1770 `org-gnus-no-new-news'
1771 For FILE, use any of
1772 `find-file'
1773 `find-file-other-window'
1774 `find-file-other-frame'
1775 For Wanderlust use any of
1776 `wl'
1777 `wl-other-frame'
1778 For the calendar, use the variable `calendar-setup'.
1779 For BBDB, it is currently only possible to display the matches in
1780 another window."
1781 :group 'org-link-follow
1782 :type '(list
1783 (cons (const vm)
1784 (choice
1785 (const vm-visit-folder)
1786 (const vm-visit-folder-other-window)
1787 (const vm-visit-folder-other-frame)))
1788 (cons (const vm-imap)
1789 (choice
1790 (const vm-visit-imap-folder)
1791 (const vm-visit-imap-folder-other-window)
1792 (const vm-visit-imap-folder-other-frame)))
1793 (cons (const gnus)
1794 (choice
1795 (const gnus)
1796 (const gnus-other-frame)
1797 (const org-gnus-no-new-news)))
1798 (cons (const file)
1799 (choice
1800 (const find-file)
1801 (const find-file-other-window)
1802 (const find-file-other-frame)))
1803 (cons (const wl)
1804 (choice
1805 (const wl)
1806 (const wl-other-frame)))))
1808 (defcustom org-display-internal-link-with-indirect-buffer nil
1809 "Non-nil means use indirect buffer to display infile links.
1810 Activating internal links (from one location in a file to another location
1811 in the same file) normally just jumps to the location. When the link is
1812 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1813 is displayed in
1814 another window. When this option is set, the other window actually displays
1815 an indirect buffer clone of the current buffer, to avoid any visibility
1816 changes to the current buffer."
1817 :group 'org-link-follow
1818 :type 'boolean)
1820 (defcustom org-open-non-existing-files nil
1821 "Non-nil means `org-open-file' will open non-existing files.
1822 When nil, an error will be generated.
1823 This variable applies only to external applications because they
1824 might choke on non-existing files. If the link is to a file that
1825 will be opened in Emacs, the variable is ignored."
1826 :group 'org-link-follow
1827 :type 'boolean)
1829 (defcustom org-open-directory-means-index-dot-org nil
1830 "Non-nil means a link to a directory really means to index.org.
1831 When nil, following a directory link will run dired or open a finder/explorer
1832 window on that directory."
1833 :group 'org-link-follow
1834 :type 'boolean)
1836 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1837 "Function and arguments to call for following mailto links.
1838 This is a list with the first element being a Lisp function, and the
1839 remaining elements being arguments to the function. In string arguments,
1840 %a will be replaced by the address, and %s will be replaced by the subject
1841 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1842 :group 'org-link-follow
1843 :type '(choice
1844 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1845 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1846 (const :tag "message-mail" (message-mail "%a" "%s"))
1847 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1849 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1850 "Non-nil means ask for confirmation before executing shell links.
1851 Shell links can be dangerous: just think about a link
1853 [[shell:rm -rf ~/*][Google Search]]
1855 This link would show up in your Org-mode document as \"Google Search\",
1856 but really it would remove your entire home directory.
1857 Therefore we advise against setting this variable to nil.
1858 Just change it to `y-or-n-p' if you want to confirm with a
1859 single keystroke rather than having to type \"yes\"."
1860 :group 'org-link-follow
1861 :type '(choice
1862 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1863 (const :tag "with y-or-n (faster)" y-or-n-p)
1864 (const :tag "no confirmation (dangerous)" nil)))
1865 (put 'org-confirm-shell-link-function
1866 'safe-local-variable
1867 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1869 (defcustom org-confirm-shell-link-not-regexp ""
1870 "A regexp to skip confirmation for shell links."
1871 :group 'org-link-follow
1872 :version "24.1"
1873 :type 'regexp)
1875 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1876 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1877 Elisp links can be dangerous: just think about a link
1879 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1881 This link would show up in your Org-mode document as \"Google Search\",
1882 but really it would remove your entire home directory.
1883 Therefore we advise against setting this variable to nil.
1884 Just change it to `y-or-n-p' if you want to confirm with a
1885 single keystroke rather than having to type \"yes\"."
1886 :group 'org-link-follow
1887 :type '(choice
1888 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1889 (const :tag "with y-or-n (faster)" y-or-n-p)
1890 (const :tag "no confirmation (dangerous)" nil)))
1891 (put 'org-confirm-shell-link-function
1892 'safe-local-variable
1893 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1895 (defcustom org-confirm-elisp-link-not-regexp ""
1896 "A regexp to skip confirmation for Elisp links."
1897 :group 'org-link-follow
1898 :version "24.1"
1899 :type 'regexp)
1901 (defconst org-file-apps-defaults-gnu
1902 (append
1903 '((remote . emacs))
1904 (if (executable-find "xdg-open")
1905 '((system . "xdg-open %s")
1906 (t . "xdg-open %s"))
1907 '((system . mailcap)
1908 (t . mailcap))))
1909 "Default file applications on a UNIX or GNU/Linux system.
1910 See `org-file-apps'.")
1912 (defconst org-file-apps-defaults-macosx
1913 '((remote . emacs)
1914 (t . "open %s")
1915 (system . "open %s")
1916 ("ps.gz" . "gv %s")
1917 ("eps.gz" . "gv %s")
1918 ("dvi" . "xdvi %s")
1919 ("fig" . "xfig %s"))
1920 "Default file applications on a MacOS X system.
1921 The system \"open\" is known as a default, but we use X11 applications
1922 for some files for which the OS does not have a good default.
1923 See `org-file-apps'.")
1925 (defconst org-file-apps-defaults-windowsnt
1926 (list
1927 '(remote . emacs)
1928 (cons t
1929 (list (if (featurep 'xemacs)
1930 'mswindows-shell-execute
1931 'w32-shell-execute)
1932 "open" 'file))
1933 (cons 'system
1934 (list (if (featurep 'xemacs)
1935 'mswindows-shell-execute
1936 'w32-shell-execute)
1937 "open" 'file)))
1938 "Default file applications on a Windows NT system.
1939 The system \"open\" is used for most files.
1940 See `org-file-apps'.")
1942 (defcustom org-file-apps
1943 '((auto-mode . emacs)
1944 ("\\.mm\\'" . default)
1945 ("\\.x?html?\\'" . default)
1946 ("\\.pdf\\'" . default))
1947 "External applications for opening `file:path' items in a document.
1948 Org-mode uses system defaults for different file types, but
1949 you can use this variable to set the application for a given file
1950 extension. The entries in this list are cons cells where the car identifies
1951 files and the cdr the corresponding command. Possible values for the
1952 file identifier are
1953 \"string\" A string as a file identifier can be interpreted in different
1954 ways, depending on its contents:
1956 - Alphanumeric characters only:
1957 Match links with this file extension.
1958 Example: (\"pdf\" . \"evince %s\")
1959 to open PDFs with evince.
1961 - Regular expression: Match links where the
1962 filename matches the regexp. If you want to
1963 use groups here, use shy groups.
1965 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1966 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1967 to open *.html and *.xhtml with firefox.
1969 - Regular expression which contains (non-shy) groups:
1970 Match links where the whole link, including \"::\", and
1971 anything after that, matches the regexp.
1972 In a custom command string, %1, %2, etc. are replaced with
1973 the parts of the link that were matched by the groups.
1974 For backwards compatibility, if a command string is given
1975 that does not use any of the group matches, this case is
1976 handled identically to the second one (i.e. match against
1977 file name only).
1978 In a custom lisp form, you can access the group matches with
1979 (match-string n link).
1981 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1982 to open [[file:document.pdf::5]] with evince at page 5.
1984 `directory' Matches a directory
1985 `remote' Matches a remote file, accessible through tramp or efs.
1986 Remote files most likely should be visited through Emacs
1987 because external applications cannot handle such paths.
1988 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1989 so all files Emacs knows how to handle. Using this with
1990 command `emacs' will open most files in Emacs. Beware that this
1991 will also open html files inside Emacs, unless you add
1992 (\"html\" . default) to the list as well.
1993 t Default for files not matched by any of the other options.
1994 `system' The system command to open files, like `open' on Windows
1995 and Mac OS X, and mailcap under GNU/Linux. This is the command
1996 that will be selected if you call `C-c C-o' with a double
1997 \\[universal-argument] \\[universal-argument] prefix.
1999 Possible values for the command are:
2000 `emacs' The file will be visited by the current Emacs process.
2001 `default' Use the default application for this file type, which is the
2002 association for t in the list, most likely in the system-specific
2003 part.
2004 This can be used to overrule an unwanted setting in the
2005 system-specific variable.
2006 `system' Use the system command for opening files, like \"open\".
2007 This command is specified by the entry whose car is `system'.
2008 Most likely, the system-specific version of this variable
2009 does define this command, but you can overrule/replace it
2010 here.
2011 string A command to be executed by a shell; %s will be replaced
2012 by the path to the file.
2013 sexp A Lisp form which will be evaluated. The file path will
2014 be available in the Lisp variable `file'.
2015 For more examples, see the system specific constants
2016 `org-file-apps-defaults-macosx'
2017 `org-file-apps-defaults-windowsnt'
2018 `org-file-apps-defaults-gnu'."
2019 :group 'org-link-follow
2020 :type '(repeat
2021 (cons (choice :value ""
2022 (string :tag "Extension")
2023 (const :tag "System command to open files" system)
2024 (const :tag "Default for unrecognized files" t)
2025 (const :tag "Remote file" remote)
2026 (const :tag "Links to a directory" directory)
2027 (const :tag "Any files that have Emacs modes"
2028 auto-mode))
2029 (choice :value ""
2030 (const :tag "Visit with Emacs" emacs)
2031 (const :tag "Use default" default)
2032 (const :tag "Use the system command" system)
2033 (string :tag "Command")
2034 (sexp :tag "Lisp form")))))
2036 (defcustom org-doi-server-url "http://dx.doi.org/"
2037 "The URL of the DOI server."
2038 :type 'string
2039 :version "24.3"
2040 :group 'org-link-follow)
2042 (defgroup org-refile nil
2043 "Options concerning refiling entries in Org-mode."
2044 :tag "Org Refile"
2045 :group 'org)
2047 (defcustom org-directory "~/org"
2048 "Directory with org files.
2049 This is just a default location to look for Org files. There is no need
2050 at all to put your files into this directory. It is only used in the
2051 following situations:
2053 1. When a capture template specifies a target file that is not an
2054 absolute path. The path will then be interpreted relative to
2055 `org-directory'
2056 2. When a capture note is filed away in an interactive way (when exiting the
2057 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2058 with `org-directory' as the default path."
2059 :group 'org-refile
2060 :group 'org-remember
2061 :group 'org-capture
2062 :type 'directory)
2064 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2065 "Default target for storing notes.
2066 Used as a fall back file for org-remember.el and org-capture.el, for
2067 templates that do not specify a target file."
2068 :group 'org-refile
2069 :group 'org-remember
2070 :group 'org-capture
2071 :type '(choice
2072 (const :tag "Default from remember-data-file" nil)
2073 file))
2075 (defcustom org-goto-interface 'outline
2076 "The default interface to be used for `org-goto'.
2077 Allowed values are:
2078 outline The interface shows an outline of the relevant file
2079 and the correct heading is found by moving through
2080 the outline or by searching with incremental search.
2081 outline-path-completion Headlines in the current buffer are offered via
2082 completion. This is the interface also used by
2083 the refile command."
2084 :group 'org-refile
2085 :type '(choice
2086 (const :tag "Outline" outline)
2087 (const :tag "Outline-path-completion" outline-path-completion)))
2089 (defcustom org-goto-max-level 5
2090 "Maximum target level when running `org-goto' with refile interface."
2091 :group 'org-refile
2092 :type 'integer)
2094 (defcustom org-reverse-note-order nil
2095 "Non-nil means store new notes at the beginning of a file or entry.
2096 When nil, new notes will be filed to the end of a file or entry.
2097 This can also be a list with cons cells of regular expressions that
2098 are matched against file names, and values."
2099 :group 'org-remember
2100 :group 'org-capture
2101 :group 'org-refile
2102 :type '(choice
2103 (const :tag "Reverse always" t)
2104 (const :tag "Reverse never" nil)
2105 (repeat :tag "By file name regexp"
2106 (cons regexp boolean))))
2108 (defcustom org-log-refile nil
2109 "Information to record when a task is refiled.
2111 Possible values are:
2113 nil Don't add anything
2114 time Add a time stamp to the task
2115 note Prompt for a note and add it with template `org-log-note-headings'
2117 This option can also be set with on a per-file-basis with
2119 #+STARTUP: nologrefile
2120 #+STARTUP: logrefile
2121 #+STARTUP: lognoterefile
2123 You can have local logging settings for a subtree by setting the LOGGING
2124 property to one or more of these keywords.
2126 When bulk-refiling from the agenda, the value `note' is forbidden and
2127 will temporarily be changed to `time'."
2128 :group 'org-refile
2129 :group 'org-progress
2130 :version "24.1"
2131 :type '(choice
2132 (const :tag "No logging" nil)
2133 (const :tag "Record timestamp" time)
2134 (const :tag "Record timestamp with note." note)))
2136 (defcustom org-refile-targets nil
2137 "Targets for refiling entries with \\[org-refile].
2138 This is a list of cons cells. Each cell contains:
2139 - a specification of the files to be considered, either a list of files,
2140 or a symbol whose function or variable value will be used to retrieve
2141 a file name or a list of file names. If you use `org-agenda-files' for
2142 that, all agenda files will be scanned for targets. Nil means consider
2143 headings in the current buffer.
2144 - A specification of how to find candidate refile targets. This may be
2145 any of:
2146 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2147 This tag has to be present in all target headlines, inheritance will
2148 not be considered.
2149 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2150 todo keyword.
2151 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2152 headlines that are refiling targets.
2153 - a cons cell (:level . N). Any headline of level N is considered a target.
2154 Note that, when `org-odd-levels-only' is set, level corresponds to
2155 order in hierarchy, not to the number of stars.
2156 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2157 Note that, when `org-odd-levels-only' is set, level corresponds to
2158 order in hierarchy, not to the number of stars.
2160 Each element of this list generates a set of possible targets.
2161 The union of these sets is presented (with completion) to
2162 the user by `org-refile'.
2164 You can set the variable `org-refile-target-verify-function' to a function
2165 to verify each headline found by the simple criteria above.
2167 When this variable is nil, all top-level headlines in the current buffer
2168 are used, equivalent to the value `((nil . (:level . 1))'."
2169 :group 'org-refile
2170 :type '(repeat
2171 (cons
2172 (choice :value org-agenda-files
2173 (const :tag "All agenda files" org-agenda-files)
2174 (const :tag "Current buffer" nil)
2175 (function) (variable) (file))
2176 (choice :tag "Identify target headline by"
2177 (cons :tag "Specific tag" (const :value :tag) (string))
2178 (cons :tag "TODO keyword" (const :value :todo) (string))
2179 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2180 (cons :tag "Level number" (const :value :level) (integer))
2181 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2183 (defcustom org-refile-target-verify-function nil
2184 "Function to verify if the headline at point should be a refile target.
2185 The function will be called without arguments, with point at the
2186 beginning of the headline. It should return t and leave point
2187 where it is if the headline is a valid target for refiling.
2189 If the target should not be selected, the function must return nil.
2190 In addition to this, it may move point to a place from where the search
2191 should be continued. For example, the function may decide that the entire
2192 subtree of the current entry should be excluded and move point to the end
2193 of the subtree."
2194 :group 'org-refile
2195 :type '(choice
2196 (const nil)
2197 (function)))
2199 (defcustom org-refile-use-cache nil
2200 "Non-nil means cache refile targets to speed up the process.
2201 The cache for a particular file will be updated automatically when
2202 the buffer has been killed, or when any of the marker used for flagging
2203 refile targets no longer points at a live buffer.
2204 If you have added new entries to a buffer that might themselves be targets,
2205 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2206 find that easier, `C-u C-u C-u C-c C-w'."
2207 :group 'org-refile
2208 :version "24.1"
2209 :type 'boolean)
2211 (defcustom org-refile-use-outline-path nil
2212 "Non-nil means provide refile targets as paths.
2213 So a level 3 headline will be available as level1/level2/level3.
2215 When the value is `file', also include the file name (without directory)
2216 into the path. In this case, you can also stop the completion after
2217 the file name, to get entries inserted as top level in the file.
2219 When `full-file-path', include the full file path."
2220 :group 'org-refile
2221 :type '(choice
2222 (const :tag "Not" nil)
2223 (const :tag "Yes" t)
2224 (const :tag "Start with file name" file)
2225 (const :tag "Start with full file path" full-file-path)))
2227 (defcustom org-outline-path-complete-in-steps t
2228 "Non-nil means complete the outline path in hierarchical steps.
2229 When Org-mode uses the refile interface to select an outline path
2230 \(see variable `org-refile-use-outline-path'), the completion of
2231 the path can be done is a single go, or if can be done in steps down
2232 the headline hierarchy. Going in steps is probably the best if you
2233 do not use a special completion package like `ido' or `icicles'.
2234 However, when using these packages, going in one step can be very
2235 fast, while still showing the whole path to the entry."
2236 :group 'org-refile
2237 :type 'boolean)
2239 (defcustom org-refile-allow-creating-parent-nodes nil
2240 "Non-nil means allow to create new nodes as refile targets.
2241 New nodes are then created by adding \"/new node name\" to the completion
2242 of an existing node. When the value of this variable is `confirm',
2243 new node creation must be confirmed by the user (recommended)
2244 When nil, the completion must match an existing entry.
2246 Note that, if the new heading is not seen by the criteria
2247 listed in `org-refile-targets', multiple instances of the same
2248 heading would be created by trying again to file under the new
2249 heading."
2250 :group 'org-refile
2251 :type '(choice
2252 (const :tag "Never" nil)
2253 (const :tag "Always" t)
2254 (const :tag "Prompt for confirmation" confirm)))
2256 (defcustom org-refile-active-region-within-subtree nil
2257 "Non-nil means also refile active region within a subtree.
2259 By default `org-refile' doesn't allow refiling regions if they
2260 don't contain a set of subtrees, but it might be convenient to
2261 do so sometimes: in that case, the first line of the region is
2262 converted to a headline before refiling."
2263 :group 'org-refile
2264 :version "24.1"
2265 :type 'boolean)
2267 (defgroup org-todo nil
2268 "Options concerning TODO items in Org-mode."
2269 :tag "Org TODO"
2270 :group 'org)
2272 (defgroup org-progress nil
2273 "Options concerning Progress logging in Org-mode."
2274 :tag "Org Progress"
2275 :group 'org-time)
2277 (defvar org-todo-interpretation-widgets
2278 '((:tag "Sequence (cycling hits every state)" sequence)
2279 (:tag "Type (cycling directly to DONE)" type))
2280 "The available interpretation symbols for customizing `org-todo-keywords'.
2281 Interested libraries should add to this list.")
2283 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2284 "List of TODO entry keyword sequences and their interpretation.
2285 \\<org-mode-map>This is a list of sequences.
2287 Each sequence starts with a symbol, either `sequence' or `type',
2288 indicating if the keywords should be interpreted as a sequence of
2289 action steps, or as different types of TODO items. The first
2290 keywords are states requiring action - these states will select a headline
2291 for inclusion into the global TODO list Org-mode produces. If one of
2292 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2293 signify that no further action is necessary. If \"|\" is not found,
2294 the last keyword is treated as the only DONE state of the sequence.
2296 The command \\[org-todo] cycles an entry through these states, and one
2297 additional state where no keyword is present. For details about this
2298 cycling, see the manual.
2300 TODO keywords and interpretation can also be set on a per-file basis with
2301 the special #+SEQ_TODO and #+TYP_TODO lines.
2303 Each keyword can optionally specify a character for fast state selection
2304 \(in combination with the variable `org-use-fast-todo-selection')
2305 and specifiers for state change logging, using the same syntax that
2306 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2307 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2308 indicates to record a time stamp each time this state is selected.
2310 Each keyword may also specify if a timestamp or a note should be
2311 recorded when entering or leaving the state, by adding additional
2312 characters in the parenthesis after the keyword. This looks like this:
2313 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2314 record only the time of the state change. With X and Y being either
2315 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2316 Y when leaving the state if and only if the *target* state does not
2317 define X. You may omit any of the fast-selection key or X or /Y,
2318 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2320 For backward compatibility, this variable may also be just a list
2321 of keywords. In this case the interpretation (sequence or type) will be
2322 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2323 :group 'org-todo
2324 :group 'org-keywords
2325 :type '(choice
2326 (repeat :tag "Old syntax, just keywords"
2327 (string :tag "Keyword"))
2328 (repeat :tag "New syntax"
2329 (cons
2330 (choice
2331 :tag "Interpretation"
2332 ;;Quick and dirty way to see
2333 ;;`org-todo-interpretations'. This takes the
2334 ;;place of item arguments
2335 :convert-widget
2336 (lambda (widget)
2337 (widget-put widget
2338 :args (mapcar
2339 #'(lambda (x)
2340 (widget-convert
2341 (cons 'const x)))
2342 org-todo-interpretation-widgets))
2343 widget))
2344 (repeat
2345 (string :tag "Keyword"))))))
2347 (defvar org-todo-keywords-1 nil
2348 "All TODO and DONE keywords active in a buffer.")
2349 (make-variable-buffer-local 'org-todo-keywords-1)
2350 (defvar org-todo-keywords-for-agenda nil)
2351 (defvar org-done-keywords-for-agenda nil)
2352 (defvar org-drawers-for-agenda nil)
2353 (defvar org-todo-keyword-alist-for-agenda nil)
2354 (defvar org-tag-alist-for-agenda nil
2355 "Alist of all tags from all agenda files.")
2356 (defvar org-tag-groups-alist-for-agenda nil
2357 "Alist of all groups tags from all current agenda files.")
2358 (defvar org-tag-groups-alist nil)
2359 (make-variable-buffer-local 'org-tag-groups-alist)
2360 (defvar org-agenda-contributing-files nil)
2361 (defvar org-not-done-keywords nil)
2362 (make-variable-buffer-local 'org-not-done-keywords)
2363 (defvar org-done-keywords nil)
2364 (make-variable-buffer-local 'org-done-keywords)
2365 (defvar org-todo-heads nil)
2366 (make-variable-buffer-local 'org-todo-heads)
2367 (defvar org-todo-sets nil)
2368 (make-variable-buffer-local 'org-todo-sets)
2369 (defvar org-todo-log-states nil)
2370 (make-variable-buffer-local 'org-todo-log-states)
2371 (defvar org-todo-kwd-alist nil)
2372 (make-variable-buffer-local 'org-todo-kwd-alist)
2373 (defvar org-todo-key-alist nil)
2374 (make-variable-buffer-local 'org-todo-key-alist)
2375 (defvar org-todo-key-trigger nil)
2376 (make-variable-buffer-local 'org-todo-key-trigger)
2378 (defcustom org-todo-interpretation 'sequence
2379 "Controls how TODO keywords are interpreted.
2380 This variable is in principle obsolete and is only used for
2381 backward compatibility, if the interpretation of todo keywords is
2382 not given already in `org-todo-keywords'. See that variable for
2383 more information."
2384 :group 'org-todo
2385 :group 'org-keywords
2386 :type '(choice (const sequence)
2387 (const type)))
2389 (defcustom org-use-fast-todo-selection t
2390 "Non-nil means use the fast todo selection scheme with C-c C-t.
2391 This variable describes if and under what circumstances the cycling
2392 mechanism for TODO keywords will be replaced by a single-key, direct
2393 selection scheme.
2395 When nil, fast selection is never used.
2397 When the symbol `prefix', it will be used when `org-todo' is called
2398 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2399 `C-u t' in an agenda buffer.
2401 When t, fast selection is used by default. In this case, the prefix
2402 argument forces cycling instead.
2404 In all cases, the special interface is only used if access keys have
2405 actually been assigned by the user, i.e. if keywords in the configuration
2406 are followed by a letter in parenthesis, like TODO(t)."
2407 :group 'org-todo
2408 :type '(choice
2409 (const :tag "Never" nil)
2410 (const :tag "By default" t)
2411 (const :tag "Only with C-u C-c C-t" prefix)))
2413 (defcustom org-provide-todo-statistics t
2414 "Non-nil means update todo statistics after insert and toggle.
2415 ALL-HEADLINES means update todo statistics by including headlines
2416 with no TODO keyword as well, counting them as not done.
2417 A list of TODO keywords means the same, but skip keywords that are
2418 not in this list.
2420 When this is set, todo statistics is updated in the parent of the
2421 current entry each time a todo state is changed."
2422 :group 'org-todo
2423 :type '(choice
2424 (const :tag "Yes, only for TODO entries" t)
2425 (const :tag "Yes, including all entries" 'all-headlines)
2426 (repeat :tag "Yes, for TODOs in this list"
2427 (string :tag "TODO keyword"))
2428 (other :tag "No TODO statistics" nil)))
2430 (defcustom org-hierarchical-todo-statistics t
2431 "Non-nil means TODO statistics covers just direct children.
2432 When nil, all entries in the subtree are considered.
2433 This has only an effect if `org-provide-todo-statistics' is set.
2434 To set this to nil for only a single subtree, use a COOKIE_DATA
2435 property and include the word \"recursive\" into the value."
2436 :group 'org-todo
2437 :type 'boolean)
2439 (defcustom org-after-todo-state-change-hook nil
2440 "Hook which is run after the state of a TODO item was changed.
2441 The new state (a string with a TODO keyword, or nil) is available in the
2442 Lisp variable `org-state'."
2443 :group 'org-todo
2444 :type 'hook)
2446 (defvar org-blocker-hook nil
2447 "Hook for functions that are allowed to block a state change.
2449 Functions in this hook should not modify the buffer.
2450 Each function gets as its single argument a property list,
2451 see `org-trigger-hook' for more information about this list.
2453 If any of the functions in this hook returns nil, the state change
2454 is blocked.")
2456 (defvar org-trigger-hook nil
2457 "Hook for functions that are triggered by a state change.
2459 Each function gets as its single argument a property list with at
2460 least the following elements:
2462 (:type type-of-change :position pos-at-entry-start
2463 :from old-state :to new-state)
2465 Depending on the type, more properties may be present.
2467 This mechanism is currently implemented for:
2469 TODO state changes
2470 ------------------
2471 :type todo-state-change
2472 :from previous state (keyword as a string), or nil, or a symbol
2473 'todo' or 'done', to indicate the general type of state.
2474 :to new state, like in :from")
2476 (defcustom org-enforce-todo-dependencies nil
2477 "Non-nil means undone TODO entries will block switching the parent to DONE.
2478 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2479 be blocked if any prior sibling is not yet done.
2480 Finally, if the parent is blocked because of ordered siblings of its own,
2481 the child will also be blocked."
2482 :set (lambda (var val)
2483 (set var val)
2484 (if val
2485 (add-hook 'org-blocker-hook
2486 'org-block-todo-from-children-or-siblings-or-parent)
2487 (remove-hook 'org-blocker-hook
2488 'org-block-todo-from-children-or-siblings-or-parent)))
2489 :group 'org-todo
2490 :type 'boolean)
2492 (defcustom org-enforce-todo-checkbox-dependencies nil
2493 "Non-nil means unchecked boxes will block switching the parent to DONE.
2494 When this is nil, checkboxes have no influence on switching TODO states.
2495 When non-nil, you first need to check off all check boxes before the TODO
2496 entry can be switched to DONE.
2497 This variable needs to be set before org.el is loaded, and you need to
2498 restart Emacs after a change to make the change effective. The only way
2499 to change is while Emacs is running is through the customize interface."
2500 :set (lambda (var val)
2501 (set var val)
2502 (if val
2503 (add-hook 'org-blocker-hook
2504 'org-block-todo-from-checkboxes)
2505 (remove-hook 'org-blocker-hook
2506 'org-block-todo-from-checkboxes)))
2507 :group 'org-todo
2508 :type 'boolean)
2510 (defcustom org-treat-insert-todo-heading-as-state-change nil
2511 "Non-nil means inserting a TODO heading is treated as state change.
2512 So when the command \\[org-insert-todo-heading] is used, state change
2513 logging will apply if appropriate. When nil, the new TODO item will
2514 be inserted directly, and no logging will take place."
2515 :group 'org-todo
2516 :type 'boolean)
2518 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2519 "Non-nil means switching TODO states with S-cursor counts as state change.
2520 This is the default behavior. However, setting this to nil allows a
2521 convenient way to select a TODO state and bypass any logging associated
2522 with that."
2523 :group 'org-todo
2524 :type 'boolean)
2526 (defcustom org-todo-state-tags-triggers nil
2527 "Tag changes that should be triggered by TODO state changes.
2528 This is a list. Each entry is
2530 (state-change (tag . flag) .......)
2532 State-change can be a string with a state, and empty string to indicate the
2533 state that has no TODO keyword, or it can be one of the symbols `todo'
2534 or `done', meaning any not-done or done state, respectively."
2535 :group 'org-todo
2536 :group 'org-tags
2537 :type '(repeat
2538 (cons (choice :tag "When changing to"
2539 (const :tag "Not-done state" todo)
2540 (const :tag "Done state" done)
2541 (string :tag "State"))
2542 (repeat
2543 (cons :tag "Tag action"
2544 (string :tag "Tag")
2545 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2547 (defcustom org-log-done nil
2548 "Information to record when a task moves to the DONE state.
2550 Possible values are:
2552 nil Don't add anything, just change the keyword
2553 time Add a time stamp to the task
2554 note Prompt for a note and add it with template `org-log-note-headings'
2556 This option can also be set with on a per-file-basis with
2558 #+STARTUP: nologdone
2559 #+STARTUP: logdone
2560 #+STARTUP: lognotedone
2562 You can have local logging settings for a subtree by setting the LOGGING
2563 property to one or more of these keywords."
2564 :group 'org-todo
2565 :group 'org-progress
2566 :type '(choice
2567 (const :tag "No logging" nil)
2568 (const :tag "Record CLOSED timestamp" time)
2569 (const :tag "Record CLOSED timestamp with note." note)))
2571 ;; Normalize old uses of org-log-done.
2572 (cond
2573 ((eq org-log-done t) (setq org-log-done 'time))
2574 ((and (listp org-log-done) (memq 'done org-log-done))
2575 (setq org-log-done 'note)))
2577 (defcustom org-log-reschedule nil
2578 "Information to record when the scheduling date of a tasks is modified.
2580 Possible values are:
2582 nil Don't add anything, just change the date
2583 time Add a time stamp to the task
2584 note Prompt for a note and add it with template `org-log-note-headings'
2586 This option can also be set with on a per-file-basis with
2588 #+STARTUP: nologreschedule
2589 #+STARTUP: logreschedule
2590 #+STARTUP: lognotereschedule"
2591 :group 'org-todo
2592 :group 'org-progress
2593 :type '(choice
2594 (const :tag "No logging" nil)
2595 (const :tag "Record timestamp" time)
2596 (const :tag "Record timestamp with note." note)))
2598 (defcustom org-log-redeadline nil
2599 "Information to record when the deadline date of a tasks is modified.
2601 Possible values are:
2603 nil Don't add anything, just change the date
2604 time Add a time stamp to the task
2605 note Prompt for a note and add it with template `org-log-note-headings'
2607 This option can also be set with on a per-file-basis with
2609 #+STARTUP: nologredeadline
2610 #+STARTUP: logredeadline
2611 #+STARTUP: lognoteredeadline
2613 You can have local logging settings for a subtree by setting the LOGGING
2614 property to one or more of these keywords."
2615 :group 'org-todo
2616 :group 'org-progress
2617 :type '(choice
2618 (const :tag "No logging" nil)
2619 (const :tag "Record timestamp" time)
2620 (const :tag "Record timestamp with note." note)))
2622 (defcustom org-log-note-clock-out nil
2623 "Non-nil means record a note when clocking out of an item.
2624 This can also be configured on a per-file basis by adding one of
2625 the following lines anywhere in the buffer:
2627 #+STARTUP: lognoteclock-out
2628 #+STARTUP: nolognoteclock-out"
2629 :group 'org-todo
2630 :group 'org-progress
2631 :type 'boolean)
2633 (defcustom org-log-done-with-time t
2634 "Non-nil means the CLOSED time stamp will contain date and time.
2635 When nil, only the date will be recorded."
2636 :group 'org-progress
2637 :type 'boolean)
2639 (defcustom org-log-note-headings
2640 '((done . "CLOSING NOTE %t")
2641 (state . "State %-12s from %-12S %t")
2642 (note . "Note taken on %t")
2643 (reschedule . "Rescheduled from %S on %t")
2644 (delschedule . "Not scheduled, was %S on %t")
2645 (redeadline . "New deadline from %S on %t")
2646 (deldeadline . "Removed deadline, was %S on %t")
2647 (refile . "Refiled on %t")
2648 (clock-out . ""))
2649 "Headings for notes added to entries.
2650 The value is an alist, with the car being a symbol indicating the note
2651 context, and the cdr is the heading to be used. The heading may also be the
2652 empty string.
2653 %t in the heading will be replaced by a time stamp.
2654 %T will be an active time stamp instead the default inactive one
2655 %d will be replaced by a short-format time stamp.
2656 %D will be replaced by an active short-format time stamp.
2657 %s will be replaced by the new TODO state, in double quotes.
2658 %S will be replaced by the old TODO state, in double quotes.
2659 %u will be replaced by the user name.
2660 %U will be replaced by the full user name.
2662 In fact, it is not a good idea to change the `state' entry, because
2663 agenda log mode depends on the format of these entries."
2664 :group 'org-todo
2665 :group 'org-progress
2666 :type '(list :greedy t
2667 (cons (const :tag "Heading when closing an item" done) string)
2668 (cons (const :tag
2669 "Heading when changing todo state (todo sequence only)"
2670 state) string)
2671 (cons (const :tag "Heading when just taking a note" note) string)
2672 (cons (const :tag "Heading when clocking out" clock-out) string)
2673 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2674 (cons (const :tag "Heading when rescheduling" reschedule) string)
2675 (cons (const :tag "Heading when changing deadline" redeadline) string)
2676 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2677 (cons (const :tag "Heading when refiling" refile) string)))
2679 (unless (assq 'note org-log-note-headings)
2680 (push '(note . "%t") org-log-note-headings))
2682 (defcustom org-log-into-drawer nil
2683 "Non-nil means insert state change notes and time stamps into a drawer.
2684 When nil, state changes notes will be inserted after the headline and
2685 any scheduling and clock lines, but not inside a drawer.
2687 The value of this variable should be the name of the drawer to use.
2688 LOGBOOK is proposed as the default drawer for this purpose, you can
2689 also set this to a string to define the drawer of your choice.
2691 A value of t is also allowed, representing \"LOGBOOK\".
2693 A value of t or nil can also be set with on a per-file-basis with
2695 #+STARTUP: logdrawer
2696 #+STARTUP: nologdrawer
2698 If this variable is set, `org-log-state-notes-insert-after-drawers'
2699 will be ignored.
2701 You can set the property LOG_INTO_DRAWER to overrule this setting for
2702 a subtree."
2703 :group 'org-todo
2704 :group 'org-progress
2705 :type '(choice
2706 (const :tag "Not into a drawer" nil)
2707 (const :tag "LOGBOOK" t)
2708 (string :tag "Other")))
2710 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2712 (defun org-log-into-drawer ()
2713 "Return the value of `org-log-into-drawer', but let properties overrule.
2714 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2715 used instead of the default value."
2716 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2717 (cond
2718 ((not p) org-log-into-drawer)
2719 ((equal p "nil") nil)
2720 ((equal p "t") "LOGBOOK")
2721 (t p))))
2723 (defcustom org-log-state-notes-insert-after-drawers nil
2724 "Non-nil means insert state change notes after any drawers in entry.
2725 Only the drawers that *immediately* follow the headline and the
2726 deadline/scheduled line are skipped.
2727 When nil, insert notes right after the heading and perhaps the line
2728 with deadline/scheduling if present.
2730 This variable will have no effect if `org-log-into-drawer' is
2731 set."
2732 :group 'org-todo
2733 :group 'org-progress
2734 :type 'boolean)
2736 (defcustom org-log-states-order-reversed t
2737 "Non-nil means the latest state note will be directly after heading.
2738 When nil, the state change notes will be ordered according to time.
2740 This option can also be set with on a per-file-basis with
2742 #+STARTUP: logstatesreversed
2743 #+STARTUP: nologstatesreversed"
2744 :group 'org-todo
2745 :group 'org-progress
2746 :type 'boolean)
2748 (defcustom org-todo-repeat-to-state nil
2749 "The TODO state to which a repeater should return the repeating task.
2750 By default this is the first task in a TODO sequence, or the previous state
2751 in a TODO_TYP set. But you can specify another task here.
2752 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2753 :group 'org-todo
2754 :version "24.1"
2755 :type '(choice (const :tag "Head of sequence" nil)
2756 (string :tag "Specific state")))
2758 (defcustom org-log-repeat 'time
2759 "Non-nil means record moving through the DONE state when triggering repeat.
2760 An auto-repeating task is immediately switched back to TODO when
2761 marked DONE. If you are not logging state changes (by adding \"@\"
2762 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2763 record a closing note, there will be no record of the task moving
2764 through DONE. This variable forces taking a note anyway.
2766 nil Don't force a record
2767 time Record a time stamp
2768 note Prompt for a note and add it with template `org-log-note-headings'
2770 This option can also be set with on a per-file-basis with
2772 #+STARTUP: nologrepeat
2773 #+STARTUP: logrepeat
2774 #+STARTUP: lognoterepeat
2776 You can have local logging settings for a subtree by setting the LOGGING
2777 property to one or more of these keywords."
2778 :group 'org-todo
2779 :group 'org-progress
2780 :type '(choice
2781 (const :tag "Don't force a record" nil)
2782 (const :tag "Force recording the DONE state" time)
2783 (const :tag "Force recording a note with the DONE state" note)))
2786 (defgroup org-priorities nil
2787 "Priorities in Org-mode."
2788 :tag "Org Priorities"
2789 :group 'org-todo)
2791 (defcustom org-enable-priority-commands t
2792 "Non-nil means priority commands are active.
2793 When nil, these commands will be disabled, so that you never accidentally
2794 set a priority."
2795 :group 'org-priorities
2796 :type 'boolean)
2798 (defcustom org-highest-priority ?A
2799 "The highest priority of TODO items. A character like ?A, ?B etc.
2800 Must have a smaller ASCII number than `org-lowest-priority'."
2801 :group 'org-priorities
2802 :type 'character)
2804 (defcustom org-lowest-priority ?C
2805 "The lowest priority of TODO items. A character like ?A, ?B etc.
2806 Must have a larger ASCII number than `org-highest-priority'."
2807 :group 'org-priorities
2808 :type 'character)
2810 (defcustom org-default-priority ?B
2811 "The default priority of TODO items.
2812 This is the priority an item gets if no explicit priority is given.
2813 When starting to cycle on an empty priority the first step in the cycle
2814 depends on `org-priority-start-cycle-with-default'. The resulting first
2815 step priority must not exceed the range from `org-highest-priority' to
2816 `org-lowest-priority' which means that `org-default-priority' has to be
2817 in this range exclusive or inclusive the range boundaries. Else the
2818 first step refuses to set the default and the second will fall back
2819 to (depending on the command used) the highest or lowest priority."
2820 :group 'org-priorities
2821 :type 'character)
2823 (defcustom org-priority-start-cycle-with-default t
2824 "Non-nil means start with default priority when starting to cycle.
2825 When this is nil, the first step in the cycle will be (depending on the
2826 command used) one higher or lower than the default priority.
2827 See also `org-default-priority'."
2828 :group 'org-priorities
2829 :type 'boolean)
2831 (defcustom org-get-priority-function nil
2832 "Function to extract the priority from a string.
2833 The string is normally the headline. If this is nil Org computes the
2834 priority from the priority cookie like [#A] in the headline. It returns
2835 an integer, increasing by 1000 for each priority level.
2836 The user can set a different function here, which should take a string
2837 as an argument and return the numeric priority."
2838 :group 'org-priorities
2839 :version "24.1"
2840 :type '(choice
2841 (const nil)
2842 (function)))
2844 (defgroup org-time nil
2845 "Options concerning time stamps and deadlines in Org-mode."
2846 :tag "Org Time"
2847 :group 'org)
2849 (defcustom org-insert-labeled-timestamps-at-point nil
2850 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2851 When nil, these labeled time stamps are forces into the second line of an
2852 entry, just after the headline. When scheduling from the global TODO list,
2853 the time stamp will always be forced into the second line."
2854 :group 'org-time
2855 :type 'boolean)
2857 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2858 "Formats for `format-time-string' which are used for time stamps.
2859 It is not recommended to change this constant.")
2861 (defcustom org-time-stamp-rounding-minutes '(0 5)
2862 "Number of minutes to round time stamps to.
2863 These are two values, the first applies when first creating a time stamp.
2864 The second applies when changing it with the commands `S-up' and `S-down'.
2865 When changing the time stamp, this means that it will change in steps
2866 of N minutes, as given by the second value.
2868 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2869 numbers should be factors of 60, so for example 5, 10, 15.
2871 When this is larger than 1, you can still force an exact time stamp by using
2872 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2873 and by using a prefix arg to `S-up/down' to specify the exact number
2874 of minutes to shift."
2875 :group 'org-time
2876 :get #'(lambda (var) ; Make sure both elements are there
2877 (if (integerp (default-value var))
2878 (list (default-value var) 5)
2879 (default-value var)))
2880 :type '(list
2881 (integer :tag "when inserting times")
2882 (integer :tag "when modifying times")))
2884 ;; Normalize old customizations of this variable.
2885 (when (integerp org-time-stamp-rounding-minutes)
2886 (setq org-time-stamp-rounding-minutes
2887 (list org-time-stamp-rounding-minutes
2888 org-time-stamp-rounding-minutes)))
2890 (defcustom org-display-custom-times nil
2891 "Non-nil means overlay custom formats over all time stamps.
2892 The formats are defined through the variable `org-time-stamp-custom-formats'.
2893 To turn this on on a per-file basis, insert anywhere in the file:
2894 #+STARTUP: customtime"
2895 :group 'org-time
2896 :set 'set-default
2897 :type 'sexp)
2898 (make-variable-buffer-local 'org-display-custom-times)
2900 (defcustom org-time-stamp-custom-formats
2901 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2902 "Custom formats for time stamps. See `format-time-string' for the syntax.
2903 These are overlaid over the default ISO format if the variable
2904 `org-display-custom-times' is set. Time like %H:%M should be at the
2905 end of the second format. The custom formats are also honored by export
2906 commands, if custom time display is turned on at the time of export."
2907 :group 'org-time
2908 :type 'sexp)
2910 (defun org-time-stamp-format (&optional long inactive)
2911 "Get the right format for a time string."
2912 (let ((f (if long (cdr org-time-stamp-formats)
2913 (car org-time-stamp-formats))))
2914 (if inactive
2915 (concat "[" (substring f 1 -1) "]")
2916 f)))
2918 (defcustom org-time-clocksum-format
2919 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2920 "The format string used when creating CLOCKSUM lines.
2921 This is also used when Org mode generates a time duration.
2923 The value can be a single format string containing two
2924 %-sequences, which will be filled with the number of hours and
2925 minutes in that order.
2927 Alternatively, the value can be a plist associating any of the
2928 keys :years, :months, :weeks, :days, :hours or :minutes with
2929 format strings. The time duration is formatted using only the
2930 time components that are needed and concatenating the results.
2931 If a time unit in absent, it falls back to the next smallest
2932 unit.
2934 The keys :require-years, :require-months, :require-days,
2935 :require-weeks, :require-hours, :require-minutes are also
2936 meaningful. A non-nil value for these keys indicates that the
2937 corresponding time component should always be included, even if
2938 its value is 0.
2941 For example,
2943 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2944 :require-minutes t)
2946 means durations longer than a day will be expressed in days,
2947 hours and minutes, and durations less than a day will always be
2948 expressed in hours and minutes (even for durations less than an
2949 hour).
2951 The value
2953 \(:days \"%dd\" :minutes \"%dm\")
2955 means durations longer than a day will be expressed in days and
2956 minutes, and durations less than a day will be expressed entirely
2957 in minutes (even for durations longer than an hour)."
2958 :group 'org-time
2959 :group 'org-clock
2960 :version "24.4"
2961 :package-version '(Org . "8.0")
2962 :type '(choice (string :tag "Format string")
2963 (set :tag "Plist"
2964 (group :inline t (const :tag "Years" :years)
2965 (string :tag "Format string"))
2966 (group :inline t
2967 (const :tag "Always show years" :require-years)
2968 (const t))
2969 (group :inline t (const :tag "Months" :months)
2970 (string :tag "Format string"))
2971 (group :inline t
2972 (const :tag "Always show months" :require-months)
2973 (const t))
2974 (group :inline t (const :tag "Weeks" :weeks)
2975 (string :tag "Format string"))
2976 (group :inline t
2977 (const :tag "Always show weeks" :require-weeks)
2978 (const t))
2979 (group :inline t (const :tag "Days" :days)
2980 (string :tag "Format string"))
2981 (group :inline t
2982 (const :tag "Always show days" :require-days)
2983 (const t))
2984 (group :inline t (const :tag "Hours" :hours)
2985 (string :tag "Format string"))
2986 (group :inline t
2987 (const :tag "Always show hours" :require-hours)
2988 (const t))
2989 (group :inline t (const :tag "Minutes" :minutes)
2990 (string :tag "Format string"))
2991 (group :inline t
2992 (const :tag "Always show minutes" :require-minutes)
2993 (const t)))))
2995 (defcustom org-time-clocksum-use-fractional nil
2996 "When non-nil, \\[org-clock-display] uses fractional times.
2997 See `org-time-clocksum-format' for more on time clock formats."
2998 :group 'org-time
2999 :group 'org-clock
3000 :version "24.3"
3001 :type 'boolean)
3003 (defcustom org-time-clocksum-use-effort-durations nil
3004 "When non-nil, \\[org-clock-display] uses effort durations.
3005 E.g. by default, one day is considered to be a 8 hours effort,
3006 so a task that has been clocked for 16 hours will be displayed
3007 as during 2 days in the clock display or in the clocktable.
3009 See `org-effort-durations' on how to set effort durations
3010 and `org-time-clocksum-format' for more on time clock formats."
3011 :group 'org-time
3012 :group 'org-clock
3013 :version "24.4"
3014 :package-version '(Org . "8.0")
3015 :type 'boolean)
3017 (defcustom org-time-clocksum-fractional-format "%.2f"
3018 "The format string used when creating CLOCKSUM lines,
3019 or when Org mode generates a time duration, if
3020 `org-time-clocksum-use-fractional' is enabled.
3022 The value can be a single format string containing one
3023 %-sequence, which will be filled with the number of hours as
3024 a float.
3026 Alternatively, the value can be a plist associating any of the
3027 keys :years, :months, :weeks, :days, :hours or :minutes with
3028 a format string. The time duration is formatted using the
3029 largest time unit which gives a non-zero integer part. If all
3030 specified formats have zero integer part, the smallest time unit
3031 is used."
3032 :group 'org-time
3033 :type '(choice (string :tag "Format string")
3034 (set (group :inline t (const :tag "Years" :years)
3035 (string :tag "Format string"))
3036 (group :inline t (const :tag "Months" :months)
3037 (string :tag "Format string"))
3038 (group :inline t (const :tag "Weeks" :weeks)
3039 (string :tag "Format string"))
3040 (group :inline t (const :tag "Days" :days)
3041 (string :tag "Format string"))
3042 (group :inline t (const :tag "Hours" :hours)
3043 (string :tag "Format string"))
3044 (group :inline t (const :tag "Minutes" :minutes)
3045 (string :tag "Format string")))))
3047 (defcustom org-deadline-warning-days 14
3048 "Number of days before expiration during which a deadline becomes active.
3049 This variable governs the display in sparse trees and in the agenda.
3050 When 0 or negative, it means use this number (the absolute value of it)
3051 even if a deadline has a different individual lead time specified.
3053 Custom commands can set this variable in the options section."
3054 :group 'org-time
3055 :group 'org-agenda-daily/weekly
3056 :type 'integer)
3058 (defcustom org-scheduled-delay-days 0
3059 "Number of days before a scheduled item becomes active.
3060 This variable governs the display in sparse trees and in the agenda.
3061 The default value (i.e. 0) means: don't delay scheduled item.
3062 When negative, it means use this number (the absolute value of it)
3063 even if a scheduled item has a different individual delay time
3064 specified.
3066 Custom commands can set this variable in the options section."
3067 :group 'org-time
3068 :group 'org-agenda-daily/weekly
3069 :version "24.4"
3070 :package-version '(Org . "8.0")
3071 :type 'integer)
3073 (defcustom org-read-date-prefer-future t
3074 "Non-nil means assume future for incomplete date input from user.
3075 This affects the following situations:
3076 1. The user gives a month but not a year.
3077 For example, if it is April and you enter \"feb 2\", this will be read
3078 as Feb 2, *next* year. \"May 5\", however, will be this year.
3079 2. The user gives a day, but no month.
3080 For example, if today is the 15th, and you enter \"3\", Org-mode will
3081 read this as the third of *next* month. However, if you enter \"17\",
3082 it will be considered as *this* month.
3084 If you set this variable to the symbol `time', then also the following
3085 will work:
3087 3. If the user gives a time.
3088 If the time is before now, it will be interpreted as tomorrow.
3090 Currently none of this works for ISO week specifications.
3092 When this option is nil, the current day, month and year will always be
3093 used as defaults.
3095 See also `org-agenda-jump-prefer-future'."
3096 :group 'org-time
3097 :type '(choice
3098 (const :tag "Never" nil)
3099 (const :tag "Check month and day" t)
3100 (const :tag "Check month, day, and time" time)))
3102 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3103 "Should the agenda jump command prefer the future for incomplete dates?
3104 The default is to do the same as configured in `org-read-date-prefer-future'.
3105 But you can also set a deviating value here.
3106 This may t or nil, or the symbol `org-read-date-prefer-future'."
3107 :group 'org-agenda
3108 :group 'org-time
3109 :version "24.1"
3110 :type '(choice
3111 (const :tag "Use org-read-date-prefer-future"
3112 org-read-date-prefer-future)
3113 (const :tag "Never" nil)
3114 (const :tag "Always" t)))
3116 (defcustom org-read-date-force-compatible-dates t
3117 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3119 Depending on the system Emacs is running on, certain dates cannot
3120 be represented with the type used internally to represent time.
3121 Dates between 1970-1-1 and 2038-1-1 can always be represented
3122 correctly. Some systems allow for earlier dates, some for later,
3123 some for both. One way to find out it to insert any date into an
3124 Org buffer, putting the cursor on the year and hitting S-up and
3125 S-down to test the range.
3127 When this variable is set to t, the date/time prompt will not let
3128 you specify dates outside the 1970-2037 range, so it is certain that
3129 these dates will work in whatever version of Emacs you are
3130 running, and also that you can move a file from one Emacs implementation
3131 to another. WHenever Org is forcing the year for you, it will display
3132 a message and beep.
3134 When this variable is nil, Org will check if the date is
3135 representable in the specific Emacs implementation you are using.
3136 If not, it will force a year, usually the current year, and beep
3137 to remind you. Currently this setting is not recommended because
3138 the likelihood that you will open your Org files in an Emacs that
3139 has limited date range is not negligible.
3141 A workaround for this problem is to use diary sexp dates for time
3142 stamps outside of this range."
3143 :group 'org-time
3144 :version "24.1"
3145 :type 'boolean)
3147 (defcustom org-read-date-display-live t
3148 "Non-nil means display current interpretation of date prompt live.
3149 This display will be in an overlay, in the minibuffer."
3150 :group 'org-time
3151 :type 'boolean)
3153 (defcustom org-read-date-popup-calendar t
3154 "Non-nil means pop up a calendar when prompting for a date.
3155 In the calendar, the date can be selected with mouse-1. However, the
3156 minibuffer will also be active, and you can simply enter the date as well.
3157 When nil, only the minibuffer will be available."
3158 :group 'org-time
3159 :type 'boolean)
3160 (org-defvaralias 'org-popup-calendar-for-date-prompt
3161 'org-read-date-popup-calendar)
3163 (make-obsolete-variable
3164 'org-read-date-minibuffer-setup-hook
3165 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3166 (defcustom org-read-date-minibuffer-setup-hook nil
3167 "Hook to be used to set up keys for the date/time interface.
3168 Add key definitions to `minibuffer-local-map', which will be a
3169 temporary copy.
3171 WARNING: This option is obsolete, you should use
3172 `org-read-date-minibuffer-local-map' to set up keys."
3173 :group 'org-time
3174 :type 'hook)
3176 (defcustom org-extend-today-until 0
3177 "The hour when your day really ends. Must be an integer.
3178 This has influence for the following applications:
3179 - When switching the agenda to \"today\". It it is still earlier than
3180 the time given here, the day recognized as TODAY is actually yesterday.
3181 - When a date is read from the user and it is still before the time given
3182 here, the current date and time will be assumed to be yesterday, 23:59.
3183 Also, timestamps inserted in capture templates follow this rule.
3185 IMPORTANT: This is a feature whose implementation is and likely will
3186 remain incomplete. Really, it is only here because past midnight seems to
3187 be the favorite working time of John Wiegley :-)"
3188 :group 'org-time
3189 :type 'integer)
3191 (defcustom org-use-effective-time nil
3192 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3193 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3194 \"effective time\" of any timestamps between midnight and 8am will be
3195 23:59 of the previous day."
3196 :group 'org-time
3197 :version "24.1"
3198 :type 'boolean)
3200 (defcustom org-use-last-clock-out-time-as-effective-time nil
3201 "When non-nil, use the last clock out time for `org-todo'.
3202 Note that this option has precedence over the combined use of
3203 `org-use-effective-time' and `org-extend-today-until'."
3204 :group 'org-time
3205 :version "24.4"
3206 :package-version '(Org . "8.0")
3207 :type 'boolean)
3209 (defcustom org-edit-timestamp-down-means-later nil
3210 "Non-nil means S-down will increase the time in a time stamp.
3211 When nil, S-up will increase."
3212 :group 'org-time
3213 :type 'boolean)
3215 (defcustom org-calendar-follow-timestamp-change t
3216 "Non-nil means make the calendar window follow timestamp changes.
3217 When a timestamp is modified and the calendar window is visible, it will be
3218 moved to the new date."
3219 :group 'org-time
3220 :type 'boolean)
3222 (defgroup org-tags nil
3223 "Options concerning tags in Org-mode."
3224 :tag "Org Tags"
3225 :group 'org)
3227 (defcustom org-tag-alist nil
3228 "List of tags allowed in Org-mode files.
3229 When this list is nil, Org-mode will base TAG input on what is already in the
3230 buffer.
3231 The value of this variable is an alist, the car of each entry must be a
3232 keyword as a string, the cdr may be a character that is used to select
3233 that tag through the fast-tag-selection interface.
3234 See the manual for details."
3235 :group 'org-tags
3236 :type '(repeat
3237 (choice
3238 (cons (string :tag "Tag name")
3239 (character :tag "Access char"))
3240 (list :tag "Start radio group"
3241 (const :startgroup)
3242 (option (string :tag "Group description")))
3243 (list :tag "Group tags delimiter"
3244 (const :grouptags))
3245 (list :tag "End radio group"
3246 (const :endgroup)
3247 (option (string :tag "Group description")))
3248 (const :tag "New line" (:newline)))))
3250 (defcustom org-tag-persistent-alist nil
3251 "List of tags that will always appear in all Org-mode files.
3252 This is in addition to any in buffer settings or customizations
3253 of `org-tag-alist'.
3254 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3255 The value of this variable is an alist, the car of each entry must be a
3256 keyword as a string, the cdr may be a character that is used to select
3257 that tag through the fast-tag-selection interface.
3258 See the manual for details.
3259 To disable these tags on a per-file basis, insert anywhere in the file:
3260 #+STARTUP: noptag"
3261 :group 'org-tags
3262 :type '(repeat
3263 (choice
3264 (cons (string :tag "Tag name")
3265 (character :tag "Access char"))
3266 (const :tag "Start radio group" (:startgroup))
3267 (const :tag "Group tags delimiter" (:grouptags))
3268 (const :tag "End radio group" (:endgroup))
3269 (const :tag "New line" (:newline)))))
3271 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3272 "If non-nil, always offer completion for all tags of all agenda files.
3273 Instead of customizing this variable directly, you might want to
3274 set it locally for capture buffers, because there no list of
3275 tags in that file can be created dynamically (there are none).
3277 (add-hook 'org-capture-mode-hook
3278 (lambda ()
3279 (set (make-local-variable
3280 'org-complete-tags-always-offer-all-agenda-tags)
3281 t)))"
3282 :group 'org-tags
3283 :version "24.1"
3284 :type 'boolean)
3286 (defvar org-file-tags nil
3287 "List of tags that can be inherited by all entries in the file.
3288 The tags will be inherited if the variable `org-use-tag-inheritance'
3289 says they should be.
3290 This variable is populated from #+FILETAGS lines.")
3292 (defcustom org-use-fast-tag-selection 'auto
3293 "Non-nil means use fast tag selection scheme.
3294 This is a special interface to select and deselect tags with single keys.
3295 When nil, fast selection is never used.
3296 When the symbol `auto', fast selection is used if and only if selection
3297 characters for tags have been configured, either through the variable
3298 `org-tag-alist' or through a #+TAGS line in the buffer.
3299 When t, fast selection is always used and selection keys are assigned
3300 automatically if necessary."
3301 :group 'org-tags
3302 :type '(choice
3303 (const :tag "Always" t)
3304 (const :tag "Never" nil)
3305 (const :tag "When selection characters are configured" auto)))
3307 (defcustom org-fast-tag-selection-single-key nil
3308 "Non-nil means fast tag selection exits after first change.
3309 When nil, you have to press RET to exit it.
3310 During fast tag selection, you can toggle this flag with `C-c'.
3311 This variable can also have the value `expert'. In this case, the window
3312 displaying the tags menu is not even shown, until you press C-c again."
3313 :group 'org-tags
3314 :type '(choice
3315 (const :tag "No" nil)
3316 (const :tag "Yes" t)
3317 (const :tag "Expert" expert)))
3319 (defvar org-fast-tag-selection-include-todo nil
3320 "Non-nil means fast tags selection interface will also offer TODO states.
3321 This is an undocumented feature, you should not rely on it.")
3323 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3324 "The column to which tags should be indented in a headline.
3325 If this number is positive, it specifies the column. If it is negative,
3326 it means that the tags should be flushright to that column. For example,
3327 -80 works well for a normal 80 character screen.
3328 When 0, place tags directly after headline text, with only one space in
3329 between."
3330 :group 'org-tags
3331 :type 'integer)
3333 (defcustom org-auto-align-tags t
3334 "Non-nil keeps tags aligned when modifying headlines.
3335 Some operations (i.e. demoting) change the length of a headline and
3336 therefore shift the tags around. With this option turned on, after
3337 each such operation the tags are again aligned to `org-tags-column'."
3338 :group 'org-tags
3339 :type 'boolean)
3341 (defcustom org-use-tag-inheritance t
3342 "Non-nil means tags in levels apply also for sublevels.
3343 When nil, only the tags directly given in a specific line apply there.
3344 This may also be a list of tags that should be inherited, or a regexp that
3345 matches tags that should be inherited. Additional control is possible
3346 with the variable `org-tags-exclude-from-inheritance' which gives an
3347 explicit list of tags to be excluded from inheritance, even if the value of
3348 `org-use-tag-inheritance' would select it for inheritance.
3350 If this option is t, a match early-on in a tree can lead to a large
3351 number of matches in the subtree when constructing the agenda or creating
3352 a sparse tree. If you only want to see the first match in a tree during
3353 a search, check out the variable `org-tags-match-list-sublevels'."
3354 :group 'org-tags
3355 :type '(choice
3356 (const :tag "Not" nil)
3357 (const :tag "Always" t)
3358 (repeat :tag "Specific tags" (string :tag "Tag"))
3359 (regexp :tag "Tags matched by regexp")))
3361 (defcustom org-tags-exclude-from-inheritance nil
3362 "List of tags that should never be inherited.
3363 This is a way to exclude a few tags from inheritance. For way to do
3364 the opposite, to actively allow inheritance for selected tags,
3365 see the variable `org-use-tag-inheritance'."
3366 :group 'org-tags
3367 :type '(repeat (string :tag "Tag")))
3369 (defun org-tag-inherit-p (tag)
3370 "Check if TAG is one that should be inherited."
3371 (cond
3372 ((member tag org-tags-exclude-from-inheritance) nil)
3373 ((eq org-use-tag-inheritance t) t)
3374 ((not org-use-tag-inheritance) nil)
3375 ((stringp org-use-tag-inheritance)
3376 (string-match org-use-tag-inheritance tag))
3377 ((listp org-use-tag-inheritance)
3378 (member tag org-use-tag-inheritance))
3379 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3381 (defcustom org-tags-match-list-sublevels t
3382 "Non-nil means list also sublevels of headlines matching a search.
3383 This variable applies to tags/property searches, and also to stuck
3384 projects because this search is based on a tags match as well.
3386 When set to the symbol `indented', sublevels are indented with
3387 leading dots.
3389 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3390 the sublevels of a headline matching a tag search often also match
3391 the same search. Listing all of them can create very long lists.
3392 Setting this variable to nil causes subtrees of a match to be skipped.
3394 This variable is semi-obsolete and probably should always be true. It
3395 is better to limit inheritance to certain tags using the variables
3396 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3397 :group 'org-tags
3398 :type '(choice
3399 (const :tag "No, don't list them" nil)
3400 (const :tag "Yes, do list them" t)
3401 (const :tag "List them, indented with leading dots" indented)))
3403 (defcustom org-tags-sort-function nil
3404 "When set, tags are sorted using this function as a comparator."
3405 :group 'org-tags
3406 :type '(choice
3407 (const :tag "No sorting" nil)
3408 (const :tag "Alphabetical" string<)
3409 (const :tag "Reverse alphabetical" string>)
3410 (function :tag "Custom function" nil)))
3412 (defvar org-tags-history nil
3413 "History of minibuffer reads for tags.")
3414 (defvar org-last-tags-completion-table nil
3415 "The last used completion table for tags.")
3416 (defvar org-after-tags-change-hook nil
3417 "Hook that is run after the tags in a line have changed.")
3419 (defgroup org-properties nil
3420 "Options concerning properties in Org-mode."
3421 :tag "Org Properties"
3422 :group 'org)
3424 (defcustom org-property-format "%-10s %s"
3425 "How property key/value pairs should be formatted by `indent-line'.
3426 When `indent-line' hits a property definition, it will format the line
3427 according to this format, mainly to make sure that the values are
3428 lined-up with respect to each other."
3429 :group 'org-properties
3430 :type 'string)
3432 (defcustom org-properties-postprocess-alist nil
3433 "Alist of properties and functions to adjust inserted values.
3434 Elements of this alist must be of the form
3436 ([string] [function])
3438 where [string] must be a property name and [function] must be a
3439 lambda expression: this lambda expression must take one argument,
3440 the value to adjust, and return the new value as a string.
3442 For example, this element will allow the property \"Remaining\"
3443 to be updated wrt the relation between the \"Effort\" property
3444 and the clock summary:
3446 ((\"Remaining\" (lambda(value)
3447 (let ((clocksum (org-clock-sum-current-item))
3448 (effort (org-duration-string-to-minutes
3449 (org-entry-get (point) \"Effort\"))))
3450 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3451 :group 'org-properties
3452 :version "24.1"
3453 :type '(alist :key-type (string :tag "Property")
3454 :value-type (function :tag "Function")))
3456 (defcustom org-use-property-inheritance nil
3457 "Non-nil means properties apply also for sublevels.
3459 This setting is chiefly used during property searches. Turning it on can
3460 cause significant overhead when doing a search, which is why it is not
3461 on by default.
3463 When nil, only the properties directly given in the current entry count.
3464 When t, every property is inherited. The value may also be a list of
3465 properties that should have inheritance, or a regular expression matching
3466 properties that should be inherited.
3468 However, note that some special properties use inheritance under special
3469 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3470 and the properties ending in \"_ALL\" when they are used as descriptor
3471 for valid values of a property.
3473 Note for programmers:
3474 When querying an entry with `org-entry-get', you can control if inheritance
3475 should be used. By default, `org-entry-get' looks only at the local
3476 properties. You can request inheritance by setting the inherit argument
3477 to t (to force inheritance) or to `selective' (to respect the setting
3478 in this variable)."
3479 :group 'org-properties
3480 :type '(choice
3481 (const :tag "Not" nil)
3482 (const :tag "Always" t)
3483 (repeat :tag "Specific properties" (string :tag "Property"))
3484 (regexp :tag "Properties matched by regexp")))
3486 (defun org-property-inherit-p (property)
3487 "Check if PROPERTY is one that should be inherited."
3488 (cond
3489 ((eq org-use-property-inheritance t) t)
3490 ((not org-use-property-inheritance) nil)
3491 ((stringp org-use-property-inheritance)
3492 (string-match org-use-property-inheritance property))
3493 ((listp org-use-property-inheritance)
3494 (member property org-use-property-inheritance))
3495 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3497 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3498 "The default column format, if no other format has been defined.
3499 This variable can be set on the per-file basis by inserting a line
3501 #+COLUMNS: %25ITEM ....."
3502 :group 'org-properties
3503 :type 'string)
3505 (defcustom org-columns-ellipses ".."
3506 "The ellipses to be used when a field in column view is truncated.
3507 When this is the empty string, as many characters as possible are shown,
3508 but then there will be no visual indication that the field has been truncated.
3509 When this is a string of length N, the last N characters of a truncated
3510 field are replaced by this string. If the column is narrower than the
3511 ellipses string, only part of the ellipses string will be shown."
3512 :group 'org-properties
3513 :type 'string)
3515 (defcustom org-columns-modify-value-for-display-function nil
3516 "Function that modifies values for display in column view.
3517 For example, it can be used to cut out a certain part from a time stamp.
3518 The function must take 2 arguments:
3520 column-title The title of the column (*not* the property name)
3521 value The value that should be modified.
3523 The function should return the value that should be displayed,
3524 or nil if the normal value should be used."
3525 :group 'org-properties
3526 :type '(choice (const nil) (function)))
3528 (defcustom org-effort-property "Effort"
3529 "The property that is being used to keep track of effort estimates.
3530 Effort estimates given in this property need to have the format H:MM."
3531 :group 'org-properties
3532 :group 'org-progress
3533 :type '(string :tag "Property"))
3535 (defconst org-global-properties-fixed
3536 '(("VISIBILITY_ALL" . "folded children content all")
3537 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3538 "List of property/value pairs that can be inherited by any entry.
3540 These are fixed values, for the preset properties. The user variable
3541 that can be used to add to this list is `org-global-properties'.
3543 The entries in this list are cons cells where the car is a property
3544 name and cdr is a string with the value. If the value represents
3545 multiple items like an \"_ALL\" property, separate the items by
3546 spaces.")
3548 (defcustom org-global-properties nil
3549 "List of property/value pairs that can be inherited by any entry.
3551 This list will be combined with the constant `org-global-properties-fixed'.
3553 The entries in this list are cons cells where the car is a property
3554 name and cdr is a string with the value.
3556 You can set buffer-local values for the same purpose in the variable
3557 `org-file-properties' this by adding lines like
3559 #+PROPERTY: NAME VALUE"
3560 :group 'org-properties
3561 :type '(repeat
3562 (cons (string :tag "Property")
3563 (string :tag "Value"))))
3565 (defvar org-file-properties nil
3566 "List of property/value pairs that can be inherited by any entry.
3567 Valid for the current buffer.
3568 This variable is populated from #+PROPERTY lines.")
3569 (make-variable-buffer-local 'org-file-properties)
3571 (defgroup org-agenda nil
3572 "Options concerning agenda views in Org-mode."
3573 :tag "Org Agenda"
3574 :group 'org)
3576 (defvar org-category nil
3577 "Variable used by org files to set a category for agenda display.
3578 Such files should use a file variable to set it, for example
3580 # -*- mode: org; org-category: \"ELisp\"
3582 or contain a special line
3584 #+CATEGORY: ELisp
3586 If the file does not specify a category, then file's base name
3587 is used instead.")
3588 (make-variable-buffer-local 'org-category)
3589 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3591 (defcustom org-agenda-files nil
3592 "The files to be used for agenda display.
3593 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3594 \\[org-remove-file]. You can also use customize to edit the list.
3596 If an entry is a directory, all files in that directory that are matched by
3597 `org-agenda-file-regexp' will be part of the file list.
3599 If the value of the variable is not a list but a single file name, then
3600 the list of agenda files is actually stored and maintained in that file, one
3601 agenda file per line. In this file paths can be given relative to
3602 `org-directory'. Tilde expansion and environment variable substitution
3603 are also made."
3604 :group 'org-agenda
3605 :type '(choice
3606 (repeat :tag "List of files and directories" file)
3607 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3609 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3610 "Regular expression to match files for `org-agenda-files'.
3611 If any element in the list in that variable contains a directory instead
3612 of a normal file, all files in that directory that are matched by this
3613 regular expression will be included."
3614 :group 'org-agenda
3615 :type 'regexp)
3617 (defcustom org-agenda-text-search-extra-files nil
3618 "List of extra files to be searched by text search commands.
3619 These files will be searched in addition to the agenda files by the
3620 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3621 Note that these files will only be searched for text search commands,
3622 not for the other agenda views like todo lists, tag searches or the weekly
3623 agenda. This variable is intended to list notes and possibly archive files
3624 that should also be searched by these two commands.
3625 In fact, if the first element in the list is the symbol `agenda-archives',
3626 then all archive files of all agenda files will be added to the search
3627 scope."
3628 :group 'org-agenda
3629 :type '(set :greedy t
3630 (const :tag "Agenda Archives" agenda-archives)
3631 (repeat :inline t (file))))
3633 (org-defvaralias 'org-agenda-multi-occur-extra-files
3634 'org-agenda-text-search-extra-files)
3636 (defcustom org-agenda-skip-unavailable-files nil
3637 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3638 A nil value means to remove them, after a query, from the list."
3639 :group 'org-agenda
3640 :type 'boolean)
3642 (defcustom org-calendar-to-agenda-key [?c]
3643 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3644 The command `org-calendar-goto-agenda' will be bound to this key. The
3645 default is the character `c' because then `c' can be used to switch back and
3646 forth between agenda and calendar."
3647 :group 'org-agenda
3648 :type 'sexp)
3650 (defcustom org-calendar-insert-diary-entry-key [?i]
3651 "The key to be installed in `calendar-mode-map' for adding diary entries.
3652 This option is irrelevant until `org-agenda-diary-file' has been configured
3653 to point to an Org-mode file. When that is the case, the command
3654 `org-agenda-diary-entry' will be bound to the key given here, by default
3655 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3656 if you want to continue doing this, you need to change this to a different
3657 key."
3658 :group 'org-agenda
3659 :type 'sexp)
3661 (defcustom org-agenda-diary-file 'diary-file
3662 "File to which to add new entries with the `i' key in agenda and calendar.
3663 When this is the symbol `diary-file', the functionality in the Emacs
3664 calendar will be used to add entries to the `diary-file'. But when this
3665 points to a file, `org-agenda-diary-entry' will be used instead."
3666 :group 'org-agenda
3667 :type '(choice
3668 (const :tag "The standard Emacs diary file" diary-file)
3669 (file :tag "Special Org file diary entries")))
3671 (eval-after-load "calendar"
3672 '(progn
3673 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3674 'org-calendar-goto-agenda)
3675 (add-hook 'calendar-mode-hook
3676 (lambda ()
3677 (unless (eq org-agenda-diary-file 'diary-file)
3678 (define-key calendar-mode-map
3679 org-calendar-insert-diary-entry-key
3680 'org-agenda-diary-entry))))))
3682 (defgroup org-latex nil
3683 "Options for embedding LaTeX code into Org-mode."
3684 :tag "Org LaTeX"
3685 :group 'org)
3687 (defcustom org-format-latex-options
3688 '(:foreground default :background default :scale 1.0
3689 :html-foreground "Black" :html-background "Transparent"
3690 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3691 "Options for creating images from LaTeX fragments.
3692 This is a property list with the following properties:
3693 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3694 `default' means use the foreground of the default face.
3695 `auto' means use the foreground from the text face.
3696 :background the background color, or \"Transparent\".
3697 `default' means use the background of the default face.
3698 `auto' means use the background from the text face.
3699 :scale a scaling factor for the size of the images, to get more pixels
3700 :html-foreground, :html-background, :html-scale
3701 the same numbers for HTML export.
3702 :matchers a list indicating which matchers should be used to
3703 find LaTeX fragments. Valid members of this list are:
3704 \"begin\" find environments
3705 \"$1\" find single characters surrounded by $.$
3706 \"$\" find math expressions surrounded by $...$
3707 \"$$\" find math expressions surrounded by $$....$$
3708 \"\\(\" find math expressions surrounded by \\(...\\)
3709 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3710 :group 'org-latex
3711 :type 'plist)
3713 (defcustom org-format-latex-signal-error t
3714 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3715 When nil, just push out a message."
3716 :group 'org-latex
3717 :version "24.1"
3718 :type 'boolean)
3720 (defcustom org-latex-to-mathml-jar-file nil
3721 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3722 Use this to specify additional executable file say a jar file.
3724 When using MathToWeb as the converter, specify the full-path to
3725 your mathtoweb.jar file."
3726 :group 'org-latex
3727 :version "24.1"
3728 :type '(choice
3729 (const :tag "None" nil)
3730 (file :tag "JAR file" :must-match t)))
3732 (defcustom org-latex-to-mathml-convert-command nil
3733 "Command to convert LaTeX fragments to MathML.
3734 Replace format-specifiers in the command as noted below and use
3735 `shell-command' to convert LaTeX to MathML.
3736 %j: Executable file in fully expanded form as specified by
3737 `org-latex-to-mathml-jar-file'.
3738 %I: Input LaTeX file in fully expanded form
3739 %o: Output MathML file
3740 This command is used by `org-create-math-formula'.
3742 When using MathToWeb as the converter, set this to
3743 \"java -jar %j -unicode -force -df %o %I\"."
3744 :group 'org-latex
3745 :version "24.1"
3746 :type '(choice
3747 (const :tag "None" nil)
3748 (string :tag "\nShell command")))
3750 (defcustom org-latex-create-formula-image-program 'dvipng
3751 "Program to convert LaTeX fragments with.
3753 dvipng Process the LaTeX fragments to dvi file, then convert
3754 dvi files to png files using dvipng.
3755 This will also include processing of non-math environments.
3756 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3757 to convert pdf files to png files"
3758 :group 'org-latex
3759 :version "24.1"
3760 :type '(choice
3761 (const :tag "dvipng" dvipng)
3762 (const :tag "imagemagick" imagemagick)))
3764 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3765 "Path to store latex preview images.
3766 A relative path here creates many directories relative to the
3767 processed org files paths. An absolute path puts all preview
3768 images at the same place."
3769 :group 'org-latex
3770 :version "24.3"
3771 :type 'string)
3773 (defun org-format-latex-mathml-available-p ()
3774 "Return t if `org-latex-to-mathml-convert-command' is usable."
3775 (save-match-data
3776 (when (and (boundp 'org-latex-to-mathml-convert-command)
3777 org-latex-to-mathml-convert-command)
3778 (let ((executable (car (split-string
3779 org-latex-to-mathml-convert-command))))
3780 (when (executable-find executable)
3781 (if (string-match
3782 "%j" org-latex-to-mathml-convert-command)
3783 (file-readable-p org-latex-to-mathml-jar-file)
3784 t))))))
3786 (defcustom org-format-latex-header "\\documentclass{article}
3787 \\usepackage[usenames]{color}
3788 \[PACKAGES]
3789 \[DEFAULT-PACKAGES]
3790 \\pagestyle{empty} % do not remove
3791 % The settings below are copied from fullpage.sty
3792 \\setlength{\\textwidth}{\\paperwidth}
3793 \\addtolength{\\textwidth}{-3cm}
3794 \\setlength{\\oddsidemargin}{1.5cm}
3795 \\addtolength{\\oddsidemargin}{-2.54cm}
3796 \\setlength{\\evensidemargin}{\\oddsidemargin}
3797 \\setlength{\\textheight}{\\paperheight}
3798 \\addtolength{\\textheight}{-\\headheight}
3799 \\addtolength{\\textheight}{-\\headsep}
3800 \\addtolength{\\textheight}{-\\footskip}
3801 \\addtolength{\\textheight}{-3cm}
3802 \\setlength{\\topmargin}{1.5cm}
3803 \\addtolength{\\topmargin}{-2.54cm}"
3804 "The document header used for processing LaTeX fragments.
3805 It is imperative that this header make sure that no page number
3806 appears on the page. The package defined in the variables
3807 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3808 will either replace the placeholder \"[PACKAGES]\" in this
3809 header, or they will be appended."
3810 :group 'org-latex
3811 :type 'string)
3813 (defun org-set-packages-alist (var val)
3814 "Set the packages alist and make sure it has 3 elements per entry."
3815 (set var (mapcar (lambda (x)
3816 (if (and (consp x) (= (length x) 2))
3817 (list (car x) (nth 1 x) t)
3819 val)))
3821 (defun org-get-packages-alist (var)
3822 "Get the packages alist and make sure it has 3 elements per entry."
3823 (mapcar (lambda (x)
3824 (if (and (consp x) (= (length x) 2))
3825 (list (car x) (nth 1 x) t)
3827 (default-value var)))
3829 (defcustom org-latex-default-packages-alist
3830 '(("AUTO" "inputenc" t)
3831 ("T1" "fontenc" t)
3832 ("" "fixltx2e" nil)
3833 ("" "graphicx" t)
3834 ("" "longtable" nil)
3835 ("" "float" nil)
3836 ("" "wrapfig" nil)
3837 ("normalem" "ulem" t)
3838 ("" "amsmath" t)
3839 ("" "textcomp" t)
3840 ("" "marvosym" t)
3841 ("" "wasysym" t)
3842 ("" "amssymb" t)
3843 ("" "hyperref" nil)
3844 "\\tolerance=1000")
3845 "Alist of default packages to be inserted in the header.
3847 Change this only if one of the packages here causes an
3848 incompatibility with another package you are using.
3850 The packages in this list are needed by one part or another of
3851 Org mode to function properly:
3853 - inputenc, fontenc: for basic font and character selection
3854 - amsmath: for subscript and superscript and math environments
3855 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3856 for interpreting the entities in `org-entities'. You can skip
3857 some of these packages if you don't use any of their symbols.
3858 - ulem: for underline and strike-through
3859 - graphicx: for including images
3860 - float, wrapfig: for figure placement
3861 - longtable: for long tables
3862 - hyperref: for cross references
3864 Therefore you should not modify this variable unless you know
3865 what you are doing. The one reason to change it anyway is that
3866 you might be loading some other package that conflicts with one
3867 of the default packages. Each cell is of the format
3868 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3869 the package also needs to be included when compiling LaTeX
3870 snippets into images for inclusion into non-LaTeX output."
3871 :group 'org-latex
3872 :group 'org-export-latex
3873 :set 'org-set-packages-alist
3874 :get 'org-get-packages-alist
3875 :version "24.1"
3876 :type '(repeat
3877 (choice
3878 (list :tag "options/package pair"
3879 (string :tag "options")
3880 (string :tag "package")
3881 (boolean :tag "Snippet"))
3882 (string :tag "A line of LaTeX"))))
3884 (defcustom org-latex-packages-alist nil
3885 "Alist of packages to be inserted in every LaTeX header.
3887 These will be inserted after `org-latex-default-packages-alist'.
3888 Each cell is of the format:
3890 \(\"options\" \"package\" snippet-flag)
3892 SNIPPET-FLAG, when t, indicates that this package is also needed
3893 when turning LaTeX snippets into images for inclusion into
3894 non-LaTeX output.
3896 Make sure that you only list packages here which:
3898 - you want in every file
3899 - do not conflict with the setup in `org-format-latex-header'.
3900 - do not conflict with the default packages in
3901 `org-latex-default-packages-alist'."
3902 :group 'org-latex
3903 :group 'org-export-latex
3904 :set 'org-set-packages-alist
3905 :get 'org-get-packages-alist
3906 :type '(repeat
3907 (choice
3908 (list :tag "options/package pair"
3909 (string :tag "options")
3910 (string :tag "package")
3911 (boolean :tag "Snippet"))
3912 (string :tag "A line of LaTeX"))))
3914 (defgroup org-appearance nil
3915 "Settings for Org-mode appearance."
3916 :tag "Org Appearance"
3917 :group 'org)
3919 (defcustom org-level-color-stars-only nil
3920 "Non-nil means fontify only the stars in each headline.
3921 When nil, the entire headline is fontified.
3922 Changing it requires restart of `font-lock-mode' to become effective
3923 also in regions already fontified."
3924 :group 'org-appearance
3925 :type 'boolean)
3927 (defcustom org-hide-leading-stars nil
3928 "Non-nil means hide the first N-1 stars in a headline.
3929 This works by using the face `org-hide' for these stars. This
3930 face is white for a light background, and black for a dark
3931 background. You may have to customize the face `org-hide' to
3932 make this work.
3933 Changing it requires restart of `font-lock-mode' to become effective
3934 also in regions already fontified.
3935 You may also set this on a per-file basis by adding one of the following
3936 lines to the buffer:
3938 #+STARTUP: hidestars
3939 #+STARTUP: showstars"
3940 :group 'org-appearance
3941 :type 'boolean)
3943 (defcustom org-hidden-keywords nil
3944 "List of symbols corresponding to keywords to be hidden the org buffer.
3945 For example, a value '(title) for this list will make the document's title
3946 appear in the buffer without the initial #+TITLE: keyword."
3947 :group 'org-appearance
3948 :version "24.1"
3949 :type '(set (const :tag "#+AUTHOR" author)
3950 (const :tag "#+DATE" date)
3951 (const :tag "#+EMAIL" email)
3952 (const :tag "#+TITLE" title)))
3954 (defcustom org-custom-properties nil
3955 "List of properties (as strings) with a special meaning.
3956 The default use of these custom properties is to let the user
3957 hide them with `org-toggle-custom-properties-visibility'."
3958 :group 'org-properties
3959 :group 'org-appearance
3960 :version "24.3"
3961 :type '(repeat (string :tag "Property Name")))
3963 (defcustom org-fontify-done-headline nil
3964 "Non-nil means change the face of a headline if it is marked DONE.
3965 Normally, only the TODO/DONE keyword indicates the state of a headline.
3966 When this is non-nil, the headline after the keyword is set to the
3967 `org-headline-done' as an additional indication."
3968 :group 'org-appearance
3969 :type 'boolean)
3971 (defcustom org-fontify-emphasized-text t
3972 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3973 Changing this variable requires a restart of Emacs to take effect."
3974 :group 'org-appearance
3975 :type 'boolean)
3977 (defcustom org-fontify-whole-heading-line nil
3978 "Non-nil means fontify the whole line for headings.
3979 This is useful when setting a background color for the
3980 org-level-* faces."
3981 :group 'org-appearance
3982 :type 'boolean)
3984 (defcustom org-highlight-latex-and-related nil
3985 "Non-nil means highlight LaTeX related syntax in the buffer.
3986 When non nil, the value should be a list containing any of the
3987 following symbols:
3988 `latex' Highlight LaTeX snippets and environments.
3989 `script' Highlight subscript and superscript.
3990 `entities' Highlight entities."
3991 :group 'org-appearance
3992 :version "24.4"
3993 :package-version '(Org . "8.0")
3994 :type '(choice
3995 (const :tag "No highlighting" nil)
3996 (set :greedy t :tag "Highlight"
3997 (const :tag "LaTeX snippets and environments" latex)
3998 (const :tag "Subscript and superscript" script)
3999 (const :tag "Entities" entities))))
4001 (defcustom org-hide-emphasis-markers nil
4002 "Non-nil mean font-lock should hide the emphasis marker characters."
4003 :group 'org-appearance
4004 :type 'boolean)
4006 (defcustom org-pretty-entities nil
4007 "Non-nil means show entities as UTF8 characters.
4008 When nil, the \\name form remains in the buffer."
4009 :group 'org-appearance
4010 :version "24.1"
4011 :type 'boolean)
4013 (defcustom org-pretty-entities-include-sub-superscripts t
4014 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4015 :group 'org-appearance
4016 :version "24.1"
4017 :type 'boolean)
4019 (defvar org-emph-re nil
4020 "Regular expression for matching emphasis.
4021 After a match, the match groups contain these elements:
4022 0 The match of the full regular expression, including the characters
4023 before and after the proper match
4024 1 The character before the proper match, or empty at beginning of line
4025 2 The proper match, including the leading and trailing markers
4026 3 The leading marker like * or /, indicating the type of highlighting
4027 4 The text between the emphasis markers, not including the markers
4028 5 The character after the match, empty at the end of a line")
4029 (defvar org-verbatim-re nil
4030 "Regular expression for matching verbatim text.")
4031 (defvar org-emphasis-regexp-components) ; defined just below
4032 (defvar org-emphasis-alist) ; defined just below
4033 (defun org-set-emph-re (var val)
4034 "Set variable and compute the emphasis regular expression."
4035 (set var val)
4036 (when (and (boundp 'org-emphasis-alist)
4037 (boundp 'org-emphasis-regexp-components)
4038 org-emphasis-alist org-emphasis-regexp-components)
4039 (let* ((e org-emphasis-regexp-components)
4040 (pre (car e))
4041 (post (nth 1 e))
4042 (border (nth 2 e))
4043 (body (nth 3 e))
4044 (nl (nth 4 e))
4045 (body1 (concat body "*?"))
4046 (markers (mapconcat 'car org-emphasis-alist ""))
4047 (vmarkers (mapconcat
4048 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4049 org-emphasis-alist "")))
4050 ;; make sure special characters appear at the right position in the class
4051 (if (string-match "\\^" markers)
4052 (setq markers (concat (replace-match "" t t markers) "^")))
4053 (if (string-match "-" markers)
4054 (setq markers (concat (replace-match "" t t markers) "-")))
4055 (if (string-match "\\^" vmarkers)
4056 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4057 (if (string-match "-" vmarkers)
4058 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4059 (if (> nl 0)
4060 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4061 (int-to-string nl) "\\}")))
4062 ;; Make the regexp
4063 (setq org-emph-re
4064 (concat "\\([" pre "]\\|^\\)"
4065 "\\("
4066 "\\([" markers "]\\)"
4067 "\\("
4068 "[^" border "]\\|"
4069 "[^" border "]"
4070 body1
4071 "[^" border "]"
4072 "\\)"
4073 "\\3\\)"
4074 "\\([" post "]\\|$\\)"))
4075 (setq org-verbatim-re
4076 (concat "\\([" pre "]\\|^\\)"
4077 "\\("
4078 "\\([" vmarkers "]\\)"
4079 "\\("
4080 "[^" border "]\\|"
4081 "[^" border "]"
4082 body1
4083 "[^" border "]"
4084 "\\)"
4085 "\\3\\)"
4086 "\\([" post "]\\|$\\)")))))
4088 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4089 ;; set this option proved cumbersome. See this message/thread:
4090 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4091 (defvar org-emphasis-regexp-components
4092 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4093 "Components used to build the regular expression for emphasis.
4094 This is a list with five entries. Terminology: In an emphasis string
4095 like \" *strong word* \", we call the initial space PREMATCH, the final
4096 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4097 and \"trong wor\" is the body. The different components in this variable
4098 specify what is allowed/forbidden in each part:
4100 pre Chars allowed as prematch. Beginning of line will be allowed too.
4101 post Chars allowed as postmatch. End of line will be allowed too.
4102 border The chars *forbidden* as border characters.
4103 body-regexp A regexp like \".\" to match a body character. Don't use
4104 non-shy groups here, and don't allow newline here.
4105 newline The maximum number of newlines allowed in an emphasis exp.
4107 You need to reload Org or to restart Emacs after customizing this.")
4109 (defcustom org-emphasis-alist
4110 `(("*" bold)
4111 ("/" italic)
4112 ("_" underline)
4113 ("=" org-code verbatim)
4114 ("~" org-verbatim verbatim)
4115 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4116 "Alist of characters and faces to emphasize text.
4117 Text starting and ending with a special character will be emphasized,
4118 for example *bold*, _underlined_ and /italic/. This variable sets the
4119 marker characters and the face to be used by font-lock for highlighting
4120 in Org-mode Emacs buffers.
4122 You need to reload Org or to restart Emacs after customizing this."
4123 :group 'org-appearance
4124 :set 'org-set-emph-re
4125 :version "24.4"
4126 :package-version '(Org . "8.0")
4127 :type '(repeat
4128 (list
4129 (string :tag "Marker character")
4130 (choice
4131 (face :tag "Font-lock-face")
4132 (plist :tag "Face property list"))
4133 (option (const verbatim)))))
4135 (defvar org-protecting-blocks
4136 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4137 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4138 This is needed for font-lock setup.")
4140 ;;; Miscellaneous options
4142 (defgroup org-completion nil
4143 "Completion in Org-mode."
4144 :tag "Org Completion"
4145 :group 'org)
4147 (defcustom org-completion-use-ido nil
4148 "Non-nil means use ido completion wherever possible.
4149 Note that `ido-mode' must be active for this variable to be relevant.
4150 If you decide to turn this variable on, you might well want to turn off
4151 `org-outline-path-complete-in-steps'.
4152 See also `org-completion-use-iswitchb'."
4153 :group 'org-completion
4154 :type 'boolean)
4156 (defcustom org-completion-use-iswitchb nil
4157 "Non-nil means use iswitchb completion wherever possible.
4158 Note that `iswitchb-mode' must be active for this variable to be relevant.
4159 If you decide to turn this variable on, you might well want to turn off
4160 `org-outline-path-complete-in-steps'.
4161 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4162 :group 'org-completion
4163 :type 'boolean)
4165 (defcustom org-completion-fallback-command 'hippie-expand
4166 "The expansion command called by \\[pcomplete] in normal context.
4167 Normal means, no org-mode-specific context."
4168 :group 'org-completion
4169 :type 'function)
4171 ;;; Functions and variables from their packages
4172 ;; Declared here to avoid compiler warnings
4174 ;; XEmacs only
4175 (defvar outline-mode-menu-heading)
4176 (defvar outline-mode-menu-show)
4177 (defvar outline-mode-menu-hide)
4178 (defvar zmacs-regions) ; XEmacs regions
4180 ;; Emacs only
4181 (defvar mark-active)
4183 ;; Various packages
4184 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4185 (declare-function calendar-forward-day "cal-move" (arg))
4186 (declare-function calendar-goto-date "cal-move" (date))
4187 (declare-function calendar-goto-today "cal-move" ())
4188 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4189 (defvar calc-embedded-close-formula)
4190 (defvar calc-embedded-open-formula)
4191 (declare-function cdlatex-tab "ext:cdlatex" ())
4192 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4193 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4194 (defvar font-lock-unfontify-region-function)
4195 (declare-function iswitchb-read-buffer "iswitchb"
4196 (prompt &optional default require-match start matches-set))
4197 (defvar iswitchb-temp-buflist)
4198 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4199 (defvar org-agenda-tags-todo-honor-ignore-options)
4200 (declare-function org-agenda-skip "org-agenda" ())
4201 (declare-function
4202 org-agenda-format-item "org-agenda"
4203 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4204 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4205 (declare-function org-agenda-change-all-lines "org-agenda"
4206 (newhead hdmarker &optional fixface just-this))
4207 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4208 (declare-function org-agenda-maybe-redo "org-agenda" ())
4209 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4210 (beg end))
4211 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4212 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4213 "org-agenda" (&optional end))
4214 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4215 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4216 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4217 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4218 (declare-function org-indent-mode "org-indent" (&optional arg))
4219 (declare-function parse-time-string "parse-time" (string))
4220 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4221 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4222 (defvar remember-data-file)
4223 (defvar texmathp-why)
4224 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4225 (declare-function table--at-cell-p "table" (position &optional object at-column))
4227 (defvar org-latex-regexps)
4229 ;;; Autoload and prepare some org modules
4231 ;; Some table stuff that needs to be defined here, because it is used
4232 ;; by the functions setting up org-mode or checking for table context.
4234 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4235 "Detect an org-type or table-type table.")
4236 (defconst org-table-line-regexp "^[ \t]*|"
4237 "Detect an org-type table line.")
4238 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4239 "Detect an org-type table line.")
4240 (defconst org-table-hline-regexp "^[ \t]*|-"
4241 "Detect an org-type table hline.")
4242 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4243 "Detect a table-type table hline.")
4244 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4245 "Detect the first line outside a table when searching from within it.
4246 This works for both table types.")
4248 ;; Autoload the functions in org-table.el that are needed by functions here.
4250 (eval-and-compile
4251 (org-autoload "org-table"
4252 '(org-table-begin org-table-blank-field org-table-end)))
4254 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4255 "Detect a #+TBLFM line.")
4257 ;;;###autoload
4258 (defun turn-on-orgtbl ()
4259 "Unconditionally turn on `orgtbl-mode'."
4260 (require 'org-table)
4261 (orgtbl-mode 1))
4263 (defun org-at-table-p (&optional table-type)
4264 "Return t if the cursor is inside an org-type table.
4265 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4266 (if org-enable-table-editor
4267 (save-excursion
4268 (beginning-of-line 1)
4269 (looking-at (if table-type org-table-any-line-regexp
4270 org-table-line-regexp)))
4271 nil))
4272 (defsubst org-table-p () (org-at-table-p))
4274 (defun org-at-table.el-p ()
4275 "Return t if and only if we are at a table.el table."
4276 (and (org-at-table-p 'any)
4277 (save-excursion
4278 (goto-char (org-table-begin 'any))
4279 (looking-at org-table1-hline-regexp))))
4281 (defun org-table-recognize-table.el ()
4282 "If there is a table.el table nearby, recognize it and move into it."
4283 (if org-table-tab-recognizes-table.el
4284 (if (org-at-table.el-p)
4285 (progn
4286 (beginning-of-line 1)
4287 (if (looking-at org-table-dataline-regexp)
4289 (if (looking-at org-table1-hline-regexp)
4290 (progn
4291 (beginning-of-line 2)
4292 (if (looking-at org-table-any-border-regexp)
4293 (beginning-of-line -1)))))
4294 (if (re-search-forward "|" (org-table-end t) t)
4295 (progn
4296 (require 'table)
4297 (if (table--at-cell-p (point))
4299 (message "recognizing table.el table...")
4300 (table-recognize-table)
4301 (message "recognizing table.el table...done")))
4302 (error "This should not happen"))
4304 nil)
4305 nil))
4307 (defun org-at-table-hline-p ()
4308 "Return t if the cursor is inside a hline in a table."
4309 (if org-enable-table-editor
4310 (save-excursion
4311 (beginning-of-line 1)
4312 (looking-at org-table-hline-regexp))
4313 nil))
4315 (defun org-table-map-tables (function &optional quietly)
4316 "Apply FUNCTION to the start of all tables in the buffer."
4317 (save-excursion
4318 (save-restriction
4319 (widen)
4320 (goto-char (point-min))
4321 (while (re-search-forward org-table-any-line-regexp nil t)
4322 (unless quietly
4323 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4324 (beginning-of-line 1)
4325 (when (and (looking-at org-table-line-regexp)
4326 ;; Exclude tables in src/example/verbatim/clocktable blocks
4327 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4328 (save-excursion (funcall function))
4329 (or (looking-at org-table-line-regexp)
4330 (forward-char 1)))
4331 (re-search-forward org-table-any-border-regexp nil 1))))
4332 (unless quietly (message "Mapping tables: done")))
4334 ;; Declare and autoload functions from org-agenda.el
4336 (eval-and-compile
4337 (org-autoload "org-agenda"
4338 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4340 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4341 (declare-function org-clock-update-mode-line "org-clock" ())
4342 (declare-function org-resolve-clocks "org-clock"
4343 (&optional also-non-dangling-p prompt last-valid))
4345 (defun org-at-TBLFM-p (&optional pos)
4346 "Return t when point (or POS) is in #+TBLFM line."
4347 (save-excursion
4348 (let ((pos pos)))
4349 (goto-char (or pos (point)))
4350 (beginning-of-line 1)
4351 (looking-at org-TBLFM-regexp)))
4353 (defvar org-clock-start-time)
4354 (defvar org-clock-marker (make-marker)
4355 "Marker recording the last clock-in.")
4356 (defvar org-clock-hd-marker (make-marker)
4357 "Marker recording the last clock-in, but the headline position.")
4358 (defvar org-clock-heading ""
4359 "The heading of the current clock entry.")
4360 (defun org-clock-is-active ()
4361 "Return the buffer where the clock is currently running.
4362 Return nil if no clock is running."
4363 (marker-buffer org-clock-marker))
4365 (eval-and-compile
4366 (org-autoload "org-clock" '(org-clock-remove-overlays
4367 org-clock-update-time-maybe
4368 org-clocktable-shift)))
4370 (defun org-check-running-clock ()
4371 "Check if the current buffer contains the running clock.
4372 If yes, offer to stop it and to save the buffer with the changes."
4373 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4374 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4375 (buffer-name))))
4376 (org-clock-out)
4377 (when (y-or-n-p "Save changed buffer?")
4378 (save-buffer))))
4380 (defun org-clocktable-try-shift (dir n)
4381 "Check if this line starts a clock table, if yes, shift the time block."
4382 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4383 (org-clocktable-shift dir n)))
4385 ;;;###autoload
4386 (defun org-clock-persistence-insinuate ()
4387 "Set up hooks for clock persistence."
4388 (require 'org-clock)
4389 (add-hook 'org-mode-hook 'org-clock-load)
4390 (add-hook 'kill-emacs-hook 'org-clock-save))
4392 ;; Define the variable already here, to make sure we have it.
4393 (defvar org-indent-mode nil
4394 "Non-nil if Org-Indent mode is enabled.
4395 Use the command `org-indent-mode' to change this variable.")
4397 ;; Autoload archiving code
4398 ;; The stuff that is needed for cycling and tags has to be defined here.
4400 (defgroup org-archive nil
4401 "Options concerning archiving in Org-mode."
4402 :tag "Org Archive"
4403 :group 'org-structure)
4405 (defcustom org-archive-location "%s_archive::"
4406 "The location where subtrees should be archived.
4408 The value of this variable is a string, consisting of two parts,
4409 separated by a double-colon. The first part is a filename and
4410 the second part is a headline.
4412 When the filename is omitted, archiving happens in the same file.
4413 %s in the filename will be replaced by the current file
4414 name (without the directory part). Archiving to a different file
4415 is useful to keep archived entries from contributing to the
4416 Org-mode Agenda.
4418 The archived entries will be filed as subtrees of the specified
4419 headline. When the headline is omitted, the subtrees are simply
4420 filed away at the end of the file, as top-level entries. Also in
4421 the heading you can use %s to represent the file name, this can be
4422 useful when using the same archive for a number of different files.
4424 Here are a few examples:
4425 \"%s_archive::\"
4426 If the current file is Projects.org, archive in file
4427 Projects.org_archive, as top-level trees. This is the default.
4429 \"::* Archived Tasks\"
4430 Archive in the current file, under the top-level headline
4431 \"* Archived Tasks\".
4433 \"~/org/archive.org::\"
4434 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4436 \"~/org/archive.org::* From %s\"
4437 Archive in file ~/org/archive.org (absolute path), under headlines
4438 \"From FILENAME\" where file name is the current file name.
4440 \"~/org/datetree.org::datetree/* Finished Tasks\"
4441 The \"datetree/\" string is special, signifying to archive
4442 items to the datetree. Items are placed in either the CLOSED
4443 date of the item, or the current date if there is no CLOSED date.
4444 The heading will be a subentry to the current date. There doesn't
4445 need to be a heading, but there always needs to be a slash after
4446 datetree. For example, to store archived items directly in the
4447 datetree, use \"~/org/datetree.org::datetree/\".
4449 \"basement::** Finished Tasks\"
4450 Archive in file ./basement (relative path), as level 3 trees
4451 below the level 2 heading \"** Finished Tasks\".
4453 You may set this option on a per-file basis by adding to the buffer a
4454 line like
4456 #+ARCHIVE: basement::** Finished Tasks
4458 You may also define it locally for a subtree by setting an ARCHIVE property
4459 in the entry. If such a property is found in an entry, or anywhere up
4460 the hierarchy, it will be used."
4461 :group 'org-archive
4462 :type 'string)
4464 (defcustom org-archive-tag "ARCHIVE"
4465 "The tag that marks a subtree as archived.
4466 An archived subtree does not open during visibility cycling, and does
4467 not contribute to the agenda listings.
4468 After changing this, font-lock must be restarted in the relevant buffers to
4469 get the proper fontification."
4470 :group 'org-archive
4471 :group 'org-keywords
4472 :type 'string)
4474 (defcustom org-agenda-skip-archived-trees t
4475 "Non-nil means the agenda will skip any items located in archived trees.
4476 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4477 variable is no longer recommended, you should leave it at the value t.
4478 Instead, use the key `v' to cycle the archives-mode in the agenda."
4479 :group 'org-archive
4480 :group 'org-agenda-skip
4481 :type 'boolean)
4483 (defcustom org-columns-skip-archived-trees t
4484 "Non-nil means ignore archived trees when creating column view."
4485 :group 'org-archive
4486 :group 'org-properties
4487 :type 'boolean)
4489 (defcustom org-cycle-open-archived-trees nil
4490 "Non-nil means `org-cycle' will open archived trees.
4491 An archived tree is a tree marked with the tag ARCHIVE.
4492 When nil, archived trees will stay folded. You can still open them with
4493 normal outline commands like `show-all', but not with the cycling commands."
4494 :group 'org-archive
4495 :group 'org-cycle
4496 :type 'boolean)
4498 (defcustom org-sparse-tree-open-archived-trees nil
4499 "Non-nil means sparse tree construction shows matches in archived trees.
4500 When nil, matches in these trees are highlighted, but the trees are kept in
4501 collapsed state."
4502 :group 'org-archive
4503 :group 'org-sparse-trees
4504 :type 'boolean)
4506 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4507 "The default date type when building a sparse tree.
4508 When this is nil, a date is a scheduled or a deadline timestamp.
4509 Otherwise, these types are allowed:
4511 all: all timestamps
4512 active: only active timestamps (<...>)
4513 inactive: only inactive timestamps (<...)
4514 scheduled: only scheduled timestamps
4515 deadline: only deadline timestamps"
4516 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4517 (const :tag "All timestamps" all)
4518 (const :tag "Only active timestamps" active)
4519 (const :tag "Only inactive timestamps" inactive)
4520 (const :tag "Only scheduled timestamps" scheduled)
4521 (const :tag "Only deadline timestamps" deadline)
4522 (const :tag "Only closed timestamps" closed))
4523 :version "24.3"
4524 :group 'org-sparse-trees)
4526 (defun org-cycle-hide-archived-subtrees (state)
4527 "Re-hide all archived subtrees after a visibility state change."
4528 (when (and (not org-cycle-open-archived-trees)
4529 (not (memq state '(overview folded))))
4530 (save-excursion
4531 (let* ((globalp (memq state '(contents all)))
4532 (beg (if globalp (point-min) (point)))
4533 (end (if globalp (point-max) (org-end-of-subtree t))))
4534 (org-hide-archived-subtrees beg end)
4535 (goto-char beg)
4536 (if (looking-at (concat ".*:" org-archive-tag ":"))
4537 (message "%s" (substitute-command-keys
4538 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4540 (defun org-force-cycle-archived ()
4541 "Cycle subtree even if it is archived."
4542 (interactive)
4543 (setq this-command 'org-cycle)
4544 (let ((org-cycle-open-archived-trees t))
4545 (call-interactively 'org-cycle)))
4547 (defun org-hide-archived-subtrees (beg end)
4548 "Re-hide all archived subtrees after a visibility state change."
4549 (save-excursion
4550 (let* ((re (concat ":" org-archive-tag ":")))
4551 (goto-char beg)
4552 (while (re-search-forward re end t)
4553 (when (org-at-heading-p)
4554 (org-flag-subtree t)
4555 (org-end-of-subtree t))))))
4557 (declare-function outline-end-of-heading "outline" ())
4558 (declare-function outline-flag-region "outline" (from to flag))
4559 (defun org-flag-subtree (flag)
4560 (save-excursion
4561 (org-back-to-heading t)
4562 (outline-end-of-heading)
4563 (outline-flag-region (point)
4564 (progn (org-end-of-subtree t) (point))
4565 flag)))
4567 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4569 (eval-and-compile
4570 (org-autoload "org-archive"
4571 '(org-add-archive-files)))
4573 ;; Autoload Column View Code
4575 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4576 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4577 (declare-function org-columns-compute "org-colview" (property))
4579 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4580 '(org-columns-number-to-string
4581 org-columns-get-format-and-top-level
4582 org-columns-compute
4583 org-columns-remove-overlays))
4585 ;; Autoload ID code
4587 (declare-function org-id-store-link "org-id")
4588 (declare-function org-id-locations-load "org-id")
4589 (declare-function org-id-locations-save "org-id")
4590 (defvar org-id-track-globally)
4591 (org-autoload "org-id"
4592 '(org-id-new
4593 org-id-copy
4594 org-id-get-with-outline-path-completion
4595 org-id-get-with-outline-drilling))
4597 ;;; Variables for pre-computed regular expressions, all buffer local
4599 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4600 "Matches first line of a hidden block.")
4601 (make-variable-buffer-local 'org-drawer-regexp)
4602 (defvar org-todo-regexp nil
4603 "Matches any of the TODO state keywords.")
4604 (make-variable-buffer-local 'org-todo-regexp)
4605 (defvar org-not-done-regexp nil
4606 "Matches any of the TODO state keywords except the last one.")
4607 (make-variable-buffer-local 'org-not-done-regexp)
4608 (defvar org-not-done-heading-regexp nil
4609 "Matches a TODO headline that is not done.")
4610 (make-variable-buffer-local 'org-not-done-regexp)
4611 (defvar org-todo-line-regexp nil
4612 "Matches a headline and puts TODO state into group 2 if present.")
4613 (make-variable-buffer-local 'org-todo-line-regexp)
4614 (defvar org-complex-heading-regexp nil
4615 "Matches a headline and puts everything into groups:
4616 group 1: the stars
4617 group 2: The todo keyword, maybe
4618 group 3: Priority cookie
4619 group 4: True headline
4620 group 5: Tags")
4621 (make-variable-buffer-local 'org-complex-heading-regexp)
4622 (defvar org-complex-heading-regexp-format nil
4623 "Printf format to make regexp to match an exact headline.
4624 This regexp will match the headline of any node which has the
4625 exact headline text that is put into the format, but may have any
4626 TODO state, priority and tags.")
4627 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4628 (defvar org-todo-line-tags-regexp nil
4629 "Matches a headline and puts TODO state into group 2 if present.
4630 Also put tags into group 4 if tags are present.")
4631 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4632 (defvar org-ds-keyword-length 12
4633 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4634 (make-variable-buffer-local 'org-ds-keyword-length)
4635 (defvar org-deadline-regexp nil
4636 "Matches the DEADLINE keyword.")
4637 (make-variable-buffer-local 'org-deadline-regexp)
4638 (defvar org-deadline-time-regexp nil
4639 "Matches the DEADLINE keyword together with a time stamp.")
4640 (make-variable-buffer-local 'org-deadline-time-regexp)
4641 (defvar org-deadline-time-hour-regexp nil
4642 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4643 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4644 (defvar org-deadline-line-regexp nil
4645 "Matches the DEADLINE keyword and the rest of the line.")
4646 (make-variable-buffer-local 'org-deadline-line-regexp)
4647 (defvar org-scheduled-regexp nil
4648 "Matches the SCHEDULED keyword.")
4649 (make-variable-buffer-local 'org-scheduled-regexp)
4650 (defvar org-scheduled-time-regexp nil
4651 "Matches the SCHEDULED keyword together with a time stamp.")
4652 (make-variable-buffer-local 'org-scheduled-time-regexp)
4653 (defvar org-scheduled-time-hour-regexp nil
4654 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4655 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4656 (defvar org-closed-time-regexp nil
4657 "Matches the CLOSED keyword together with a time stamp.")
4658 (make-variable-buffer-local 'org-closed-time-regexp)
4660 (defvar org-keyword-time-regexp nil
4661 "Matches any of the 4 keywords, together with the time stamp.")
4662 (make-variable-buffer-local 'org-keyword-time-regexp)
4663 (defvar org-keyword-time-not-clock-regexp nil
4664 "Matches any of the 3 keywords, together with the time stamp.")
4665 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4666 (defvar org-maybe-keyword-time-regexp nil
4667 "Matches a timestamp, possibly preceded by a keyword.")
4668 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4669 (defvar org-all-time-keywords nil
4670 "List of time keywords.")
4671 (make-variable-buffer-local 'org-all-time-keywords)
4673 (defconst org-plain-time-of-day-regexp
4674 (concat
4675 "\\(\\<[012]?[0-9]"
4676 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4677 "\\(--?"
4678 "\\(\\<[012]?[0-9]"
4679 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4680 "\\)?")
4681 "Regular expression to match a plain time or time range.
4682 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4683 groups carry important information:
4684 0 the full match
4685 1 the first time, range or not
4686 8 the second time, if it is a range.")
4688 (defconst org-plain-time-extension-regexp
4689 (concat
4690 "\\(\\<[012]?[0-9]"
4691 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4692 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4693 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4694 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4695 groups carry important information:
4696 0 the full match
4697 7 hours of duration
4698 9 minutes of duration")
4700 (defconst org-stamp-time-of-day-regexp
4701 (concat
4702 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4703 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4704 "\\(--?"
4705 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4706 "Regular expression to match a timestamp time or time range.
4707 After a match, the following groups carry important information:
4708 0 the full match
4709 1 date plus weekday, for back referencing to make sure both times are on the same day
4710 2 the first time, range or not
4711 4 the second time, if it is a range.")
4713 (defconst org-startup-options
4714 '(("fold" org-startup-folded t)
4715 ("overview" org-startup-folded t)
4716 ("nofold" org-startup-folded nil)
4717 ("showall" org-startup-folded nil)
4718 ("showeverything" org-startup-folded showeverything)
4719 ("content" org-startup-folded content)
4720 ("indent" org-startup-indented t)
4721 ("noindent" org-startup-indented nil)
4722 ("hidestars" org-hide-leading-stars t)
4723 ("showstars" org-hide-leading-stars nil)
4724 ("odd" org-odd-levels-only t)
4725 ("oddeven" org-odd-levels-only nil)
4726 ("align" org-startup-align-all-tables t)
4727 ("noalign" org-startup-align-all-tables nil)
4728 ("inlineimages" org-startup-with-inline-images t)
4729 ("noinlineimages" org-startup-with-inline-images nil)
4730 ("latexpreview" org-startup-with-latex-preview t)
4731 ("nolatexpreview" org-startup-with-latex-preview nil)
4732 ("customtime" org-display-custom-times t)
4733 ("logdone" org-log-done time)
4734 ("lognotedone" org-log-done note)
4735 ("nologdone" org-log-done nil)
4736 ("lognoteclock-out" org-log-note-clock-out t)
4737 ("nolognoteclock-out" org-log-note-clock-out nil)
4738 ("logrepeat" org-log-repeat state)
4739 ("lognoterepeat" org-log-repeat note)
4740 ("logdrawer" org-log-into-drawer t)
4741 ("nologdrawer" org-log-into-drawer nil)
4742 ("logstatesreversed" org-log-states-order-reversed t)
4743 ("nologstatesreversed" org-log-states-order-reversed nil)
4744 ("nologrepeat" org-log-repeat nil)
4745 ("logreschedule" org-log-reschedule time)
4746 ("lognotereschedule" org-log-reschedule note)
4747 ("nologreschedule" org-log-reschedule nil)
4748 ("logredeadline" org-log-redeadline time)
4749 ("lognoteredeadline" org-log-redeadline note)
4750 ("nologredeadline" org-log-redeadline nil)
4751 ("logrefile" org-log-refile time)
4752 ("lognoterefile" org-log-refile note)
4753 ("nologrefile" org-log-refile nil)
4754 ("fninline" org-footnote-define-inline t)
4755 ("nofninline" org-footnote-define-inline nil)
4756 ("fnlocal" org-footnote-section nil)
4757 ("fnauto" org-footnote-auto-label t)
4758 ("fnprompt" org-footnote-auto-label nil)
4759 ("fnconfirm" org-footnote-auto-label confirm)
4760 ("fnplain" org-footnote-auto-label plain)
4761 ("fnadjust" org-footnote-auto-adjust t)
4762 ("nofnadjust" org-footnote-auto-adjust nil)
4763 ("constcgs" constants-unit-system cgs)
4764 ("constSI" constants-unit-system SI)
4765 ("noptag" org-tag-persistent-alist nil)
4766 ("hideblocks" org-hide-block-startup t)
4767 ("nohideblocks" org-hide-block-startup nil)
4768 ("beamer" org-startup-with-beamer-mode t)
4769 ("entitiespretty" org-pretty-entities t)
4770 ("entitiesplain" org-pretty-entities nil))
4771 "Variable associated with STARTUP options for org-mode.
4772 Each element is a list of three items: the startup options (as written
4773 in the #+STARTUP line), the corresponding variable, and the value to set
4774 this variable to if the option is found. An optional forth element PUSH
4775 means to push this value onto the list in the variable.")
4777 (defun org-update-property-plist (key val props)
4778 "Update PROPS with KEY and VAL."
4779 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4780 (key (if appending (substring key 0 (- (length key) 1)) key))
4781 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4782 (previous (cdr (assoc key props))))
4783 (if appending
4784 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4785 (cons (cons key val) remainder))))
4787 (defconst org-block-regexp
4788 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4789 "Regular expression for hiding blocks.")
4790 (defconst org-heading-keyword-regexp-format
4791 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4792 "Printf format for a regexp matching a headline with some keyword.
4793 This regexp will match the headline of any node which has the
4794 exact keyword that is put into the format. The keyword isn't in
4795 any group by default, but the stars and the body are.")
4796 (defconst org-heading-keyword-maybe-regexp-format
4797 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4798 "Printf format for a regexp matching a headline, possibly with some keyword.
4799 This regexp can match any headline with the specified keyword, or
4800 without a keyword. The keyword isn't in any group by default,
4801 but the stars and the body are.")
4803 (defcustom org-group-tags t
4804 "When non-nil (the default), use group tags.
4805 This can be turned on/off through `org-toggle-tags-groups'."
4806 :group 'org-tags
4807 :group 'org-startup
4808 :type 'boolean)
4810 (defun org-toggle-tags-groups ()
4811 "Toggle support for group tags.
4812 Support for group tags is controlled by the option
4813 `org-group-tags', which is non-nil by default."
4814 (interactive)
4815 (setq org-group-tags (not org-group-tags))
4816 (cond ((and (derived-mode-p 'org-agenda-mode)
4817 org-group-tags)
4818 (org-agenda-redo))
4819 ((derived-mode-p 'org-mode)
4820 (let ((org-inhibit-startup t)) (org-mode))))
4821 (message "Groups tags support has been turned %s"
4822 (if org-group-tags "on" "off")))
4824 (defun org-set-regexps-and-options-for-tags ()
4825 "Precompute variables used for tags."
4826 (when (derived-mode-p 'org-mode)
4827 (org-set-local 'org-file-tags nil)
4828 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4829 (splitre "[ \t]+")
4830 (start 0)
4831 tags ftags key value)
4832 (save-excursion
4833 (save-restriction
4834 (widen)
4835 (goto-char (point-min))
4836 (while (re-search-forward re nil t)
4837 (setq key (upcase (org-match-string-no-properties 1))
4838 value (org-match-string-no-properties 2))
4839 (if (stringp value) (setq value (org-trim value)))
4840 (cond
4841 ((equal key "TAGS")
4842 (setq tags (append tags (if tags '("\\n") nil)
4843 (org-split-string value splitre))))
4844 ((equal key "FILETAGS")
4845 (when (string-match "\\S-" value)
4846 (setq ftags
4847 (append
4848 ftags
4849 (apply 'append
4850 (mapcar (lambda (x) (org-split-string x ":"))
4851 (org-split-string value)))))))))))
4852 ;; Process the file tags.
4853 (and ftags (org-set-local 'org-file-tags
4854 (mapcar 'org-add-prop-inherited ftags)))
4855 (org-set-local 'org-tag-groups-alist nil)
4856 ;; Process the tags.
4857 (when (and (not tags) org-tag-alist)
4858 (setq tags
4859 (mapcar
4860 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4861 ((eq (car tg) :endgroup) "}")
4862 ((eq (car tg) :grouptags) ":")
4863 ((eq (car tg) :newline) "\n")
4864 (t (concat (car tg)
4865 (if (characterp (cdr tg))
4866 (format "(%s)" (char-to-string (cdr tg))) "")))))
4867 org-tag-alist)))
4868 (let (e tgs g)
4869 (while (setq e (pop tags))
4870 (cond
4871 ((equal e "{")
4872 (progn (push '(:startgroup) tgs)
4873 (when (equal (nth 1 tags) ":")
4874 (push (list (replace-regexp-in-string
4875 "(.+)$" "" (nth 0 tags)))
4876 org-tag-groups-alist)
4877 (setq g 0))))
4878 ((equal e ":") (push '(:grouptags) tgs))
4879 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4880 ((equal e "\\n") (push '(:newline) tgs))
4881 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4882 (push (cons (match-string 1 e)
4883 (string-to-char (match-string 2 e))) tgs)
4884 (if (and g (> g 0))
4885 (setcar org-tag-groups-alist
4886 (append (car org-tag-groups-alist)
4887 (list (match-string 1 e)))))
4888 (if g (setq g (1+ g))))
4889 (t (push (list e) tgs)
4890 (if (and g (> g 0))
4891 (setcar org-tag-groups-alist
4892 (append (car org-tag-groups-alist) (list e))))
4893 (if g (setq g (1+ g))))))
4894 (org-set-local 'org-tag-alist nil)
4895 (while (setq e (pop tgs))
4896 (or (and (stringp (car e))
4897 (assoc (car e) org-tag-alist))
4898 (push e org-tag-alist)))
4899 ;; Return a list with tag variables
4900 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4902 (defvar org-ota nil)
4903 (defun org-set-regexps-and-options ()
4904 "Precompute regular expressions used in the current buffer."
4905 (when (derived-mode-p 'org-mode)
4906 (org-set-local 'org-todo-kwd-alist nil)
4907 (org-set-local 'org-todo-key-alist nil)
4908 (org-set-local 'org-todo-key-trigger nil)
4909 (org-set-local 'org-todo-keywords-1 nil)
4910 (org-set-local 'org-done-keywords nil)
4911 (org-set-local 'org-todo-heads nil)
4912 (org-set-local 'org-todo-sets nil)
4913 (org-set-local 'org-todo-log-states nil)
4914 (org-set-local 'org-file-properties nil)
4915 (let ((re (org-make-options-regexp
4916 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4917 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4918 "SETUPFILE" "OPTIONS")
4919 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4920 (splitre "[ \t]+")
4921 (scripts org-use-sub-superscripts)
4922 kwds kws0 kwsa key log value cat arch const links hw dws
4923 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4924 (start 0))
4925 (save-excursion
4926 (save-restriction
4927 (widen)
4928 (goto-char (point-min))
4929 (while
4930 (or (and
4931 ext-setup-or-nil
4932 (not org-ota)
4933 (let (ret)
4934 (with-temp-buffer
4935 (insert ext-setup-or-nil)
4936 (let ((major-mode 'org-mode) org-ota)
4937 (setq ret (save-match-data
4938 (org-set-regexps-and-options-for-tags)))))
4939 ;; Append setupfile tags to existing tags
4940 (setq org-ota t)
4941 (setq org-file-tags
4942 (delq nil (append org-file-tags (nth 0 ret)))
4943 org-tag-alist
4944 (delq nil (append org-tag-alist (nth 1 ret)))
4945 org-tag-groups-alist
4946 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4947 (and ext-setup-or-nil
4948 (string-match re ext-setup-or-nil start)
4949 (setq start (match-end 0)))
4950 (and (setq ext-setup-or-nil nil start 0)
4951 (re-search-forward re nil t)))
4952 (setq key (upcase (match-string 1 ext-setup-or-nil))
4953 value (org-match-string-no-properties 2 ext-setup-or-nil))
4954 (if (stringp value) (setq value (org-trim value)))
4955 (cond
4956 ((equal key "CATEGORY")
4957 (setq cat value))
4958 ((member key '("SEQ_TODO" "TODO"))
4959 (push (cons 'sequence (org-split-string value splitre)) kwds))
4960 ((equal key "TYP_TODO")
4961 (push (cons 'type (org-split-string value splitre)) kwds))
4962 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4963 ;; general TODO-like setup
4964 (push (cons (intern (downcase (match-string 1 key)))
4965 (org-split-string value splitre)) kwds))
4966 ((equal key "COLUMNS")
4967 (org-set-local 'org-columns-default-format value))
4968 ((equal key "LINK")
4969 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4970 (push (cons (match-string 1 value)
4971 (org-trim (match-string 2 value)))
4972 links)))
4973 ((equal key "PRIORITIES")
4974 (setq prio (org-split-string value " +")))
4975 ((equal key "PROPERTY")
4976 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4977 (setq props (org-update-property-plist (match-string 1 value)
4978 (match-string 2 value)
4979 props))))
4980 ((equal key "DRAWERS")
4981 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4982 ((equal key "CONSTANTS")
4983 (org-table-set-constants))
4984 ((equal key "STARTUP")
4985 (let ((opts (org-split-string value splitre))
4986 l var val)
4987 (while (setq l (pop opts))
4988 (when (setq l (assoc l org-startup-options))
4989 (setq var (nth 1 l) val (nth 2 l))
4990 (if (not (nth 3 l))
4991 (set (make-local-variable var) val)
4992 (if (not (listp (symbol-value var)))
4993 (set (make-local-variable var) nil))
4994 (set (make-local-variable var) (symbol-value var))
4995 (add-to-list var val))))))
4996 ((equal key "ARCHIVE")
4997 (setq arch value)
4998 (remove-text-properties 0 (length arch)
4999 '(face t fontified t) arch))
5000 ((equal key "OPTIONS")
5001 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5002 (setq scripts (read (match-string 2 value)))))
5003 ((and (equal key "SETUPFILE")
5004 ;; Prevent checking in Gnus messages
5005 (not buffer-read-only))
5006 (setq setup-contents (org-file-contents
5007 (expand-file-name
5008 (org-remove-double-quotes value))
5009 'noerror))
5010 (if (not ext-setup-or-nil)
5011 (setq ext-setup-or-nil setup-contents start 0)
5012 (setq ext-setup-or-nil
5013 (concat (substring ext-setup-or-nil 0 start)
5014 "\n" setup-contents "\n"
5015 (substring ext-setup-or-nil start)))))))
5016 ;; search for property blocks
5017 (goto-char (point-min))
5018 (while (re-search-forward org-block-regexp nil t)
5019 (when (equal "PROPERTY" (upcase (match-string 1)))
5020 (setq value (replace-regexp-in-string
5021 "[\n\r]" " " (match-string 4)))
5022 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5023 (setq props (org-update-property-plist (match-string 1 value)
5024 (match-string 2 value)
5025 props)))))))
5026 (org-set-local 'org-use-sub-superscripts scripts)
5027 (when cat
5028 (org-set-local 'org-category (intern cat))
5029 (push (cons "CATEGORY" cat) props))
5030 (when prio
5031 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5032 (setq prio (mapcar 'string-to-char prio))
5033 (org-set-local 'org-highest-priority (nth 0 prio))
5034 (org-set-local 'org-lowest-priority (nth 1 prio))
5035 (org-set-local 'org-default-priority (nth 2 prio)))
5036 (and props (org-set-local 'org-file-properties (nreverse props)))
5037 (and drawers (org-set-local 'org-drawers drawers))
5038 (and arch (org-set-local 'org-archive-location arch))
5039 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5040 ;; Process the TODO keywords
5041 (unless kwds
5042 ;; Use the global values as if they had been given locally.
5043 (setq kwds (default-value 'org-todo-keywords))
5044 (if (stringp (car kwds))
5045 (setq kwds (list (cons org-todo-interpretation
5046 (default-value 'org-todo-keywords)))))
5047 (setq kwds (reverse kwds)))
5048 (setq kwds (nreverse kwds))
5049 (let (inter kws kw)
5050 (while (setq kws (pop kwds))
5051 (let ((kws (or
5052 (run-hook-with-args-until-success
5053 'org-todo-setup-filter-hook kws)
5054 kws)))
5055 (setq inter (pop kws) sep (member "|" kws)
5056 kws0 (delete "|" (copy-sequence kws))
5057 kwsa nil
5058 kws1 (mapcar
5059 (lambda (x)
5060 ;; 1 2
5061 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5062 (progn
5063 (setq kw (match-string 1 x)
5064 key (and (match-end 2) (match-string 2 x))
5065 log (org-extract-log-state-settings x))
5066 (push (cons kw (and key (string-to-char key))) kwsa)
5067 (and log (push log org-todo-log-states))
5069 (error "Invalid TODO keyword %s" x)))
5070 kws0)
5071 kwsa (if kwsa (append '((:startgroup))
5072 (nreverse kwsa)
5073 '((:endgroup))))
5074 hw (car kws1)
5075 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5076 tail (list inter hw (car dws) (org-last dws))))
5077 (add-to-list 'org-todo-heads hw 'append)
5078 (push kws1 org-todo-sets)
5079 (setq org-done-keywords (append org-done-keywords dws nil))
5080 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5081 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5082 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5083 (setq org-todo-sets (nreverse org-todo-sets)
5084 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5085 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5086 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5087 ;; Compute the regular expressions and other local variables.
5088 ;; Using `org-outline-regexp-bol' would complicate them much,
5089 ;; because of the fixed white space at the end of that string.
5090 (if (not org-done-keywords)
5091 (setq org-done-keywords (and org-todo-keywords-1
5092 (list (org-last org-todo-keywords-1)))))
5093 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5094 (length org-scheduled-string)
5095 (length org-clock-string)
5096 (length org-closed-string)))
5097 org-drawer-regexp
5098 (concat "^[ \t]*:\\("
5099 (mapconcat 'regexp-quote org-drawers "\\|")
5100 "\\):[ \t]*$")
5101 org-not-done-keywords
5102 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5103 org-todo-regexp
5104 (concat "\\("
5105 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5106 "\\)")
5107 org-not-done-regexp
5108 (concat "\\("
5109 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5110 "\\)")
5111 org-not-done-heading-regexp
5112 (format org-heading-keyword-regexp-format org-not-done-regexp)
5113 org-todo-line-regexp
5114 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5115 org-complex-heading-regexp
5116 (concat "^\\(\\*+\\)"
5117 "\\(?: +" org-todo-regexp "\\)?"
5118 "\\(?: +\\(\\[#.\\]\\)\\)?"
5119 "\\(?: +\\(.*?\\)\\)??"
5120 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5121 "[ \t]*$")
5122 org-complex-heading-regexp-format
5123 (concat "^\\(\\*+\\)"
5124 "\\(?: +" org-todo-regexp "\\)?"
5125 "\\(?: +\\(\\[#.\\]\\)\\)?"
5126 "\\(?: +"
5127 ;; Stats cookies can be stuck to body.
5128 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5129 "\\(%s\\)"
5130 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5131 "\\)"
5132 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5133 "[ \t]*$")
5134 org-todo-line-tags-regexp
5135 (concat "^\\(\\*+\\)"
5136 "\\(?: +" org-todo-regexp "\\)?"
5137 "\\(?: +\\(.*?\\)\\)??"
5138 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5139 "[ \t]*$")
5140 org-deadline-regexp (concat "\\<" org-deadline-string)
5141 org-deadline-time-regexp
5142 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5143 org-deadline-time-hour-regexp
5144 (concat "\\<" org-deadline-string
5145 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5146 org-deadline-line-regexp
5147 (concat "\\<\\(" org-deadline-string "\\).*")
5148 org-scheduled-regexp
5149 (concat "\\<" org-scheduled-string)
5150 org-scheduled-time-regexp
5151 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5152 org-scheduled-time-hour-regexp
5153 (concat "\\<" org-scheduled-string
5154 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5155 org-closed-time-regexp
5156 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5157 org-keyword-time-regexp
5158 (concat "\\<\\(" org-scheduled-string
5159 "\\|" org-deadline-string
5160 "\\|" org-closed-string
5161 "\\|" org-clock-string "\\)"
5162 " *[[<]\\([^]>]+\\)[]>]")
5163 org-keyword-time-not-clock-regexp
5164 (concat "\\<\\(" org-scheduled-string
5165 "\\|" org-deadline-string
5166 "\\|" org-closed-string
5167 "\\)"
5168 " *[[<]\\([^]>]+\\)[]>]")
5169 org-maybe-keyword-time-regexp
5170 (concat "\\(\\<\\(" org-scheduled-string
5171 "\\|" org-deadline-string
5172 "\\|" org-closed-string
5173 "\\|" org-clock-string "\\)\\)?"
5174 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5175 org-all-time-keywords
5176 (mapcar (lambda (w) (substring w 0 -1))
5177 (list org-scheduled-string org-deadline-string
5178 org-clock-string org-closed-string)))
5179 (setq org-ota nil)
5180 (org-compute-latex-and-related-regexp))))
5182 (defun org-file-contents (file &optional noerror)
5183 "Return the contents of FILE, as a string."
5184 (if (or (not file)
5185 (not (file-readable-p file)))
5186 (if noerror
5187 (message "Cannot read file \"%s\"" file)
5188 (error "Cannot read file \"%s\"" file))
5189 (with-temp-buffer
5190 (insert-file-contents file)
5191 (buffer-string))))
5193 (defun org-extract-log-state-settings (x)
5194 "Extract the log state setting from a TODO keyword string.
5195 This will extract info from a string like \"WAIT(w@/!)\"."
5196 (let (kw key log1 log2)
5197 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5198 (setq kw (match-string 1 x)
5199 key (and (match-end 2) (match-string 2 x))
5200 log1 (and (match-end 3) (match-string 3 x))
5201 log2 (and (match-end 4) (match-string 4 x)))
5202 (and (or log1 log2)
5203 (list kw
5204 (and log1 (if (equal log1 "!") 'time 'note))
5205 (and log2 (if (equal log2 "!") 'time 'note)))))))
5207 (defun org-remove-keyword-keys (list)
5208 "Remove a pair of parenthesis at the end of each string in LIST."
5209 (mapcar (lambda (x)
5210 (if (string-match "(.*)$" x)
5211 (substring x 0 (match-beginning 0))
5213 list))
5215 (defun org-assign-fast-keys (alist)
5216 "Assign fast keys to a keyword-key alist.
5217 Respect keys that are already there."
5218 (let (new e (alt ?0))
5219 (while (setq e (pop alist))
5220 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5221 (cdr e)) ;; Key already assigned.
5222 (push e new)
5223 (let ((clist (string-to-list (downcase (car e))))
5224 (used (append new alist)))
5225 (when (= (car clist) ?@)
5226 (pop clist))
5227 (while (and clist (rassoc (car clist) used))
5228 (pop clist))
5229 (unless clist
5230 (while (rassoc alt used)
5231 (incf alt)))
5232 (push (cons (car e) (or (car clist) alt)) new))))
5233 (nreverse new)))
5235 ;;; Some variables used in various places
5237 (defvar org-window-configuration nil
5238 "Used in various places to store a window configuration.")
5239 (defvar org-selected-window nil
5240 "Used in various places to store a window configuration.")
5241 (defvar org-finish-function nil
5242 "Function to be called when `C-c C-c' is used.
5243 This is for getting out of special buffers like capture.")
5246 ;; FIXME: Occasionally check by commenting these, to make sure
5247 ;; no other functions uses these, forgetting to let-bind them.
5248 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5249 (defvar org-last-state)
5250 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5252 ;; Defined somewhere in this file, but used before definition.
5253 (defvar org-entities) ;; defined in org-entities.el
5254 (defvar org-struct-menu)
5255 (defvar org-org-menu)
5256 (defvar org-tbl-menu)
5258 ;;;; Define the Org-mode
5260 ;; We use a before-change function to check if a table might need
5261 ;; an update.
5262 (defvar org-table-may-need-update t
5263 "Indicates that a table might need an update.
5264 This variable is set by `org-before-change-function'.
5265 `org-table-align' sets it back to nil.")
5266 (defun org-before-change-function (beg end)
5267 "Every change indicates that a table might need an update."
5268 (setq org-table-may-need-update t))
5269 (defvar org-mode-map)
5270 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5271 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5272 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5273 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5274 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5275 (defvar org-table-buffer-is-an nil)
5277 (defvar bidi-paragraph-direction)
5278 (defvar buffer-face-mode-face)
5280 (require 'outline)
5281 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5282 (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"))
5283 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5285 ;; Other stuff we need.
5286 (require 'time-date)
5287 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5288 (require 'easymenu)
5289 (require 'overlay)
5291 ;; (require 'org-macs) moved higher up in the file before it is first used
5292 (require 'org-entities)
5293 ;; (require 'org-compat) moved higher up in the file before it is first used
5294 (require 'org-faces)
5295 (require 'org-list)
5296 (require 'org-pcomplete)
5297 (require 'org-src)
5298 (require 'org-footnote)
5299 (require 'org-macro)
5301 ;; babel
5302 (require 'ob)
5304 ;;;###autoload
5305 (define-derived-mode org-mode outline-mode "Org"
5306 "Outline-based notes management and organizer, alias
5307 \"Carsten's outline-mode for keeping track of everything.\"
5309 Org-mode develops organizational tasks around a NOTES file which
5310 contains information about projects as plain text. Org-mode is
5311 implemented on top of outline-mode, which is ideal to keep the content
5312 of large files well structured. It supports ToDo items, deadlines and
5313 time stamps, which magically appear in the diary listing of the Emacs
5314 calendar. Tables are easily created with a built-in table editor.
5315 Plain text URL-like links connect to websites, emails (VM), Usenet
5316 messages (Gnus), BBDB entries, and any files related to the project.
5317 For printing and sharing of notes, an Org-mode file (or a part of it)
5318 can be exported as a structured ASCII or HTML file.
5320 The following commands are available:
5322 \\{org-mode-map}"
5324 ;; Get rid of Outline menus, they are not needed
5325 ;; Need to do this here because define-derived-mode sets up
5326 ;; the keymap so late. Still, it is a waste to call this each time
5327 ;; we switch another buffer into org-mode.
5328 (if (featurep 'xemacs)
5329 (when (boundp 'outline-mode-menu-heading)
5330 ;; Assume this is Greg's port, it uses easymenu
5331 (easy-menu-remove outline-mode-menu-heading)
5332 (easy-menu-remove outline-mode-menu-show)
5333 (easy-menu-remove outline-mode-menu-hide))
5334 (define-key org-mode-map [menu-bar headings] 'undefined)
5335 (define-key org-mode-map [menu-bar hide] 'undefined)
5336 (define-key org-mode-map [menu-bar show] 'undefined))
5338 (org-load-modules-maybe)
5339 (easy-menu-add org-org-menu)
5340 (easy-menu-add org-tbl-menu)
5341 (org-install-agenda-files-menu)
5342 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5343 (add-to-invisibility-spec '(org-cwidth))
5344 (add-to-invisibility-spec '(org-hide-block . t))
5345 (when (featurep 'xemacs)
5346 (org-set-local 'line-move-ignore-invisible t))
5347 (org-set-local 'outline-regexp org-outline-regexp)
5348 (org-set-local 'outline-level 'org-outline-level)
5349 (setq bidi-paragraph-direction 'left-to-right)
5350 (when (and org-ellipsis
5351 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5352 (fboundp 'make-glyph-code))
5353 (unless org-display-table
5354 (setq org-display-table (make-display-table)))
5355 (set-display-table-slot
5356 org-display-table 4
5357 (vconcat (mapcar
5358 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5359 org-ellipsis)))
5360 (if (stringp org-ellipsis) org-ellipsis "..."))))
5361 (setq buffer-display-table org-display-table))
5362 (org-set-regexps-and-options-for-tags)
5363 (org-set-regexps-and-options)
5364 (org-set-font-lock-defaults)
5365 (when (and org-tag-faces (not org-tags-special-faces-re))
5366 ;; tag faces set outside customize.... force initialization.
5367 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5368 ;; Calc embedded
5369 (org-set-local 'calc-embedded-open-mode "# ")
5370 ;; Modify a few syntax entries
5371 (modify-syntax-entry ?@ "w")
5372 (modify-syntax-entry ?\" "\"")
5373 (if org-startup-truncated (setq truncate-lines t))
5374 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5375 (org-set-local 'font-lock-unfontify-region-function
5376 'org-unfontify-region)
5377 ;; Activate before-change-function
5378 (org-set-local 'org-table-may-need-update t)
5379 (org-add-hook 'before-change-functions 'org-before-change-function nil
5380 'local)
5381 ;; Check for running clock before killing a buffer
5382 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5383 ;; Initialize macros templates.
5384 (org-macro-initialize-templates)
5385 ;; Initialize radio targets.
5386 (org-update-radio-target-regexp)
5387 ;; Indentation.
5388 (org-set-local 'indent-line-function 'org-indent-line)
5389 (org-set-local 'indent-region-function 'org-indent-region)
5390 ;; Filling and auto-filling.
5391 (org-setup-filling)
5392 ;; Comments.
5393 (org-setup-comments-handling)
5394 ;; Beginning/end of defun
5395 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5396 (org-set-local 'end-of-defun-function 'org-forward-element)
5397 ;; Next error for sparse trees
5398 (org-set-local 'next-error-function 'org-occur-next-match)
5399 ;; Make sure dependence stuff works reliably, even for users who set it
5400 ;; too late :-(
5401 (if org-enforce-todo-dependencies
5402 (add-hook 'org-blocker-hook
5403 'org-block-todo-from-children-or-siblings-or-parent)
5404 (remove-hook 'org-blocker-hook
5405 'org-block-todo-from-children-or-siblings-or-parent))
5406 (if org-enforce-todo-checkbox-dependencies
5407 (add-hook 'org-blocker-hook
5408 'org-block-todo-from-checkboxes)
5409 (remove-hook 'org-blocker-hook
5410 'org-block-todo-from-checkboxes))
5412 ;; Align options lines
5413 (org-set-local
5414 'align-mode-rules-list
5415 '((org-in-buffer-settings
5416 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5417 (modes . '(org-mode)))))
5419 ;; Imenu
5420 (org-set-local 'imenu-create-index-function
5421 'org-imenu-get-tree)
5423 ;; Make isearch reveal context
5424 (if (or (featurep 'xemacs)
5425 (not (boundp 'outline-isearch-open-invisible-function)))
5426 ;; Emacs 21 and XEmacs make use of the hook
5427 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5428 ;; Emacs 22 deals with this through a special variable
5429 (org-set-local 'outline-isearch-open-invisible-function
5430 (lambda (&rest ignore) (org-show-context 'isearch)))
5431 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5433 ;; Setup the pcomplete hooks
5434 (set (make-local-variable 'pcomplete-command-completion-function)
5435 'org-pcomplete-initial)
5436 (set (make-local-variable 'pcomplete-command-name-function)
5437 'org-command-at-point)
5438 (set (make-local-variable 'pcomplete-default-completion-function)
5439 'ignore)
5440 (set (make-local-variable 'pcomplete-parse-arguments-function)
5441 'org-parse-arguments)
5442 (set (make-local-variable 'pcomplete-termination-string) "")
5443 (when (>= emacs-major-version 23)
5444 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5446 ;; If empty file that did not turn on org-mode automatically, make it to.
5447 (if (and org-insert-mode-line-in-empty-file
5448 (org-called-interactively-p 'any)
5449 (= (point-min) (point-max)))
5450 (insert "# -*- mode: org -*-\n\n"))
5451 (unless org-inhibit-startup
5452 (org-unmodified
5453 (and org-startup-with-beamer-mode (org-beamer-mode))
5454 (when org-startup-align-all-tables
5455 (org-table-map-tables 'org-table-align 'quietly))
5456 (when org-startup-with-inline-images
5457 (org-display-inline-images))
5458 (when org-startup-with-latex-preview
5459 (org-preview-latex-fragment))
5460 (unless org-inhibit-startup-visibility-stuff
5461 (org-set-startup-visibility))))
5462 ;; Try to set org-hide correctly
5463 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5465 ;; Update `customize-package-emacs-version-alist'
5466 (add-to-list 'customize-package-emacs-version-alist
5467 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5468 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5469 ("8.0" . "24.4")))
5471 (defvar org-mode-transpose-word-syntax-table
5472 (let ((st (make-syntax-table)))
5473 (mapc (lambda(c) (modify-syntax-entry
5474 (string-to-char (car c)) "w p" st))
5475 org-emphasis-alist)
5476 st))
5478 (when (fboundp 'abbrev-table-put)
5479 (abbrev-table-put org-mode-abbrev-table
5480 :parents (list text-mode-abbrev-table)))
5482 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5484 (defsubst org-fix-ellipsis-at-bol ()
5485 (save-excursion (goto-char (window-start)) (recenter 0)))
5487 (defun org-find-invisible-foreground ()
5488 (let ((candidates (remove
5489 "unspecified-bg"
5490 (nconc
5491 (list (face-background 'default)
5492 (face-background 'org-default))
5493 (mapcar
5494 (lambda (alist)
5495 (when (boundp alist)
5496 (cdr (assoc 'background-color (symbol-value alist)))))
5497 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5498 (list (face-foreground 'org-hide))))))
5499 (car (remove nil candidates))))
5501 (defun org-current-time (&optional rounding-minutes past)
5502 "Current time, possibly rounded to ROUNDING-MINUTES.
5503 When ROUNDING-MINUTES is not an integer, fall back on the car of
5504 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5505 the rounding returns a past time."
5506 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5507 (car org-time-stamp-rounding-minutes)))
5508 (time (decode-time)) res)
5509 (if (< r 1)
5510 (current-time)
5511 (setq res
5512 (apply 'encode-time
5513 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5514 (nthcdr 2 time))))
5515 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5516 (seconds-to-time (- (org-float-time res) (* r 60)))
5517 res))))
5519 (defun org-today ()
5520 "Return today date, considering `org-extend-today-until'."
5521 (time-to-days
5522 (time-subtract (current-time)
5523 (list 0 (* 3600 org-extend-today-until) 0))))
5525 ;;;; Font-Lock stuff, including the activators
5527 (defvar org-mouse-map (make-sparse-keymap))
5528 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5529 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5530 (when org-mouse-1-follows-link
5531 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5532 (when org-tab-follows-link
5533 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5534 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5536 (require 'font-lock)
5538 (defconst org-non-link-chars "]\t\n\r<>")
5539 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5540 "shell" "elisp" "doi" "message"))
5541 (defvar org-link-types-re nil
5542 "Matches a link that has a url-like prefix like \"http:\"")
5543 (defvar org-link-re-with-space nil
5544 "Matches a link with spaces, optional angular brackets around it.")
5545 (defvar org-link-re-with-space2 nil
5546 "Matches a link with spaces, optional angular brackets around it.")
5547 (defvar org-link-re-with-space3 nil
5548 "Matches a link with spaces, only for internal part in bracket links.")
5549 (defvar org-angle-link-re nil
5550 "Matches link with angular brackets, spaces are allowed.")
5551 (defvar org-plain-link-re nil
5552 "Matches plain link, without spaces.")
5553 (defvar org-bracket-link-regexp nil
5554 "Matches a link in double brackets.")
5555 (defvar org-bracket-link-analytic-regexp nil
5556 "Regular expression used to analyze links.
5557 Here is what the match groups contain after a match:
5558 1: http:
5559 2: http
5560 3: path
5561 4: [desc]
5562 5: desc")
5563 (defvar org-bracket-link-analytic-regexp++ nil
5564 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5565 (defvar org-any-link-re nil
5566 "Regular expression matching any link.")
5568 (defconst org-match-sexp-depth 3
5569 "Number of stacked braces for sub/superscript matching.")
5571 (defun org-create-multibrace-regexp (left right n)
5572 "Create a regular expression which will match a balanced sexp.
5573 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5574 as single character strings.
5575 The regexp returned will match the entire expression including the
5576 delimiters. It will also define a single group which contains the
5577 match except for the outermost delimiters. The maximum depth of
5578 stacked delimiters is N. Escaping delimiters is not possible."
5579 (let* ((nothing (concat "[^" left right "]*?"))
5580 (or "\\|")
5581 (re nothing)
5582 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5583 (while (> n 1)
5584 (setq n (1- n)
5585 re (concat re or next)
5586 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5587 (concat left "\\(" re "\\)" right)))
5589 (defvar org-match-substring-regexp
5590 (concat
5591 "\\(\\S-\\)\\([_^]\\)\\("
5592 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5593 "\\|"
5594 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5595 "\\|"
5596 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5597 "The regular expression matching a sub- or superscript.")
5599 (defvar org-match-substring-with-braces-regexp
5600 (concat
5601 "\\(\\S-\\)\\([_^]\\)\\("
5602 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5603 "\\)")
5604 "The regular expression matching a sub- or superscript, forcing braces.")
5606 (defun org-make-link-regexps ()
5607 "Update the link regular expressions.
5608 This should be called after the variable `org-link-types' has changed."
5609 (setq org-link-types-re
5610 (concat
5611 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5612 org-link-re-with-space
5613 (concat
5614 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5615 "\\([^" org-non-link-chars " ]"
5616 "[^" org-non-link-chars "]*"
5617 "[^" org-non-link-chars " ]\\)>?")
5618 org-link-re-with-space2
5619 (concat
5620 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5621 "\\([^" org-non-link-chars " ]"
5622 "[^\t\n\r]*"
5623 "[^" org-non-link-chars " ]\\)>?")
5624 org-link-re-with-space3
5625 (concat
5626 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5627 "\\([^" org-non-link-chars " ]"
5628 "[^\t\n\r]*\\)")
5629 org-angle-link-re
5630 (concat
5631 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5632 "\\([^" org-non-link-chars " ]"
5633 "[^" org-non-link-chars "]*"
5634 "\\)>")
5635 org-plain-link-re
5636 (concat
5637 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5638 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5639 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5640 org-bracket-link-regexp
5641 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5642 org-bracket-link-analytic-regexp
5643 (concat
5644 "\\[\\["
5645 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5646 "\\([^]]+\\)"
5647 "\\]"
5648 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5649 "\\]")
5650 org-bracket-link-analytic-regexp++
5651 (concat
5652 "\\[\\["
5653 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5654 "\\([^]]+\\)"
5655 "\\]"
5656 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5657 "\\]")
5658 org-any-link-re
5659 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5660 org-angle-link-re "\\)\\|\\("
5661 org-plain-link-re "\\)")))
5663 (org-make-link-regexps)
5665 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5666 "Regular expression for fast time stamp matching.")
5667 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5668 "Regular expression for fast time stamp matching.")
5669 (defconst org-ts-regexp0
5670 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5671 "Regular expression matching time strings for analysis.
5672 This one does not require the space after the date, so it can be used
5673 on a string that terminates immediately after the date.")
5674 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5675 "Regular expression matching time strings for analysis.")
5676 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5677 "Regular expression matching time stamps, with groups.")
5678 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5679 "Regular expression matching time stamps (also [..]), with groups.")
5680 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5681 "Regular expression matching a time stamp range.")
5682 (defconst org-tr-regexp-both
5683 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5684 "Regular expression matching a time stamp range.")
5685 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5686 org-ts-regexp "\\)?")
5687 "Regular expression matching a time stamp or time stamp range.")
5688 (defconst org-tsr-regexp-both
5689 (concat org-ts-regexp-both "\\(--?-?"
5690 org-ts-regexp-both "\\)?")
5691 "Regular expression matching a time stamp or time stamp range.
5692 The time stamps may be either active or inactive.")
5694 (defvar org-emph-face nil)
5696 (defun org-do-emphasis-faces (limit)
5697 "Run through the buffer and add overlays to emphasized strings."
5698 (let (rtn a)
5699 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5700 (if (not (= (char-after (match-beginning 3))
5701 (char-after (match-beginning 4))))
5702 (progn
5703 (setq rtn t)
5704 (setq a (assoc (match-string 3) org-emphasis-alist))
5705 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5706 'face
5707 (nth 1 a))
5708 (and (nth 4 a)
5709 (org-remove-flyspell-overlays-in
5710 (match-beginning 0) (match-end 0)))
5711 (add-text-properties (match-beginning 2) (match-end 2)
5712 '(font-lock-multiline t org-emphasis t))
5713 (when org-hide-emphasis-markers
5714 (add-text-properties (match-end 4) (match-beginning 5)
5715 '(invisible org-link))
5716 (add-text-properties (match-beginning 3) (match-end 3)
5717 '(invisible org-link)))))
5718 (backward-char 1))
5719 rtn))
5721 (defun org-emphasize (&optional char)
5722 "Insert or change an emphasis, i.e. a font like bold or italic.
5723 If there is an active region, change that region to a new emphasis.
5724 If there is no region, just insert the marker characters and position
5725 the cursor between them.
5726 CHAR should be the marker character. If it is a space, it means to
5727 remove the emphasis of the selected region.
5728 If CHAR is not given (for example in an interactive call) it will be
5729 prompted for."
5730 (interactive)
5731 (let ((erc org-emphasis-regexp-components)
5732 (prompt "")
5733 (string "") beg end move c s)
5734 (if (org-region-active-p)
5735 (setq beg (region-beginning) end (region-end)
5736 string (buffer-substring beg end))
5737 (setq move t))
5739 (unless char
5740 (message "Emphasis marker or tag: [%s]"
5741 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5742 (setq char (read-char-exclusive)))
5743 (if (equal char ?\ )
5744 (setq s "" move nil)
5745 (unless (assoc (char-to-string char) org-emphasis-alist)
5746 (user-error "No such emphasis marker: \"%c\"" char))
5747 (setq s (char-to-string char)))
5748 (while (and (> (length string) 1)
5749 (equal (substring string 0 1) (substring string -1))
5750 (assoc (substring string 0 1) org-emphasis-alist))
5751 (setq string (substring string 1 -1)))
5752 (setq string (concat s string s))
5753 (if beg (delete-region beg end))
5754 (unless (or (bolp)
5755 (string-match (concat "[" (nth 0 erc) "\n]")
5756 (char-to-string (char-before (point)))))
5757 (insert " "))
5758 (unless (or (eobp)
5759 (string-match (concat "[" (nth 1 erc) "\n]")
5760 (char-to-string (char-after (point)))))
5761 (insert " ") (backward-char 1))
5762 (insert string)
5763 (and move (backward-char 1))))
5765 (defconst org-nonsticky-props
5766 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5768 (defsubst org-rear-nonsticky-at (pos)
5769 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5771 (defun org-activate-plain-links (limit)
5772 "Run through the buffer and add overlays to links."
5773 (let (f hl)
5774 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5775 (not (org-in-src-block-p)))
5776 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5777 (setq f (get-text-property (match-beginning 0) 'face))
5778 (setq hl (org-match-string-no-properties 0))
5779 (if (or (eq f 'org-tag)
5780 (and (listp f) (memq 'org-tag f)))
5782 (add-text-properties (match-beginning 0) (match-end 0)
5783 (list 'mouse-face 'highlight
5784 'face 'org-link
5785 'htmlize-link `(:uri ,hl)
5786 'keymap org-mouse-map))
5787 (org-rear-nonsticky-at (match-end 0)))
5788 t)))
5790 (defun org-activate-code (limit)
5791 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5792 (progn
5793 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5794 (remove-text-properties (match-beginning 0) (match-end 0)
5795 '(display t invisible t intangible t))
5796 t)))
5798 (defcustom org-src-fontify-natively nil
5799 "When non-nil, fontify code in code blocks."
5800 :type 'boolean
5801 :version "24.1"
5802 :group 'org-appearance
5803 :group 'org-babel)
5805 (defcustom org-allow-promoting-top-level-subtree nil
5806 "When non-nil, allow promoting a top level subtree.
5807 The leading star of the top level headline will be replaced
5808 by a #."
5809 :type 'boolean
5810 :version "24.1"
5811 :group 'org-appearance)
5813 (defun org-fontify-meta-lines-and-blocks (limit)
5814 (condition-case nil
5815 (org-fontify-meta-lines-and-blocks-1 limit)
5816 (error (message "org-mode fontification error"))))
5818 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5819 "Fontify #+ lines and blocks."
5820 (let ((case-fold-search t))
5821 (if (re-search-forward
5822 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5823 limit t)
5824 (let ((beg (match-beginning 0))
5825 (block-start (match-end 0))
5826 (block-end nil)
5827 (lang (match-string 7))
5828 (beg1 (line-beginning-position 2))
5829 (dc1 (downcase (match-string 2)))
5830 (dc3 (downcase (match-string 3)))
5831 end end1 quoting block-type ovl)
5832 (cond
5833 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5834 ;; a single line of backend-specific content
5835 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5836 (remove-text-properties (match-beginning 0) (match-end 0)
5837 '(display t invisible t intangible t))
5838 (add-text-properties (match-beginning 1) (match-end 3)
5839 '(font-lock-fontified t face org-meta-line))
5840 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5841 '(font-lock-fontified t face org-block))
5842 ; for backend-specific code
5844 ((and (match-end 4) (equal dc3 "+begin"))
5845 ;; Truly a block
5846 (setq block-type (downcase (match-string 5))
5847 quoting (member block-type org-protecting-blocks))
5848 (when (re-search-forward
5849 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5850 nil t) ;; on purpose, we look further than LIMIT
5851 (setq end (min (point-max) (match-end 0))
5852 end1 (min (point-max) (1- (match-beginning 0))))
5853 (setq block-end (match-beginning 0))
5854 (when quoting
5855 (remove-text-properties beg end
5856 '(display t invisible t intangible t)))
5857 (add-text-properties
5858 beg end
5859 '(font-lock-fontified t font-lock-multiline t))
5860 (add-text-properties beg beg1 '(face org-meta-line))
5861 (add-text-properties end1 (min (point-max) (1+ end))
5862 '(face org-meta-line)) ; for end_src
5863 (cond
5864 ((and lang (not (string= lang "")) org-src-fontify-natively)
5865 (org-src-font-lock-fontify-block lang block-start block-end)
5866 ;; remove old background overlays
5867 (mapc (lambda (ov)
5868 (if (eq (overlay-get ov 'face) 'org-block-background)
5869 (delete-overlay ov)))
5870 (overlays-at (/ (+ beg1 block-end) 2)))
5871 ;; add a background overlay
5872 (setq ovl (make-overlay beg1 block-end))
5873 (overlay-put ovl 'face 'org-block-background)
5874 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5875 (quoting
5876 (add-text-properties beg1 (min (point-max) (1+ end1))
5877 '(face org-block))) ; end of source block
5878 ((not org-fontify-quote-and-verse-blocks))
5879 ((string= block-type "quote")
5880 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5881 ((string= block-type "verse")
5882 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5883 (add-text-properties beg beg1 '(face org-block-begin-line))
5884 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5885 '(face org-block-end-line))
5887 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5888 (add-text-properties
5889 beg (match-end 3)
5890 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5891 '(font-lock-fontified t invisible t)
5892 '(font-lock-fontified t face org-document-info-keyword)))
5893 (add-text-properties
5894 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5895 (if (string-equal dc1 "+title:")
5896 '(font-lock-fontified t face org-document-title)
5897 '(font-lock-fontified t face org-document-info))))
5898 ((or (equal dc1 "+results")
5899 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5900 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5901 "+call:" "+header:" "+headers:" "+name:"))
5902 (and (match-end 4) (equal dc3 "+attr")))
5903 (add-text-properties
5904 beg (match-end 0)
5905 '(font-lock-fontified t face org-meta-line))
5907 ((member dc3 '(" " ""))
5908 (add-text-properties
5909 beg (match-end 0)
5910 '(font-lock-fontified t face font-lock-comment-face)))
5911 ((not (member (char-after beg) '(?\ ?\t)))
5912 ;; just any other in-buffer setting, but not indented
5913 (add-text-properties
5914 beg (match-end 0)
5915 '(font-lock-fontified t face org-meta-line))
5917 (t nil))))))
5919 (defun org-activate-angle-links (limit)
5920 "Run through the buffer and add overlays to links."
5921 (if (and (re-search-forward org-angle-link-re limit t)
5922 (not (org-in-src-block-p)))
5923 (progn
5924 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5925 (add-text-properties (match-beginning 0) (match-end 0)
5926 (list 'mouse-face 'highlight
5927 'keymap org-mouse-map))
5928 (org-rear-nonsticky-at (match-end 0))
5929 t)))
5931 (defun org-activate-footnote-links (limit)
5932 "Run through the buffer and add overlays to footnotes."
5933 (let ((fn (org-footnote-next-reference-or-definition limit)))
5934 (when fn
5935 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5936 (org-remove-flyspell-overlays-in beg end)
5937 (add-text-properties beg end
5938 (list 'mouse-face 'highlight
5939 'keymap org-mouse-map
5940 'help-echo
5941 (if (= (point-at-bol) beg)
5942 "Footnote definition"
5943 "Footnote reference")
5944 'font-lock-fontified t
5945 'font-lock-multiline t
5946 'face 'org-footnote))))))
5948 (defun org-activate-bracket-links (limit)
5949 "Run through the buffer and add overlays to bracketed links."
5950 (if (and (re-search-forward org-bracket-link-regexp limit t)
5951 (not (org-in-src-block-p)))
5952 (let* ((hl (org-match-string-no-properties 1))
5953 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5954 (ip (org-maybe-intangible
5955 (list 'invisible 'org-link
5956 'keymap org-mouse-map 'mouse-face 'highlight
5957 'font-lock-multiline t 'help-echo help
5958 'htmlize-link `(:uri ,hl))))
5959 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5960 'font-lock-multiline t 'help-echo help
5961 'htmlize-link `(:uri ,hl))))
5962 ;; We need to remove the invisible property here. Table narrowing
5963 ;; may have made some of this invisible.
5964 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5965 (remove-text-properties (match-beginning 0) (match-end 0)
5966 '(invisible nil))
5967 (if (match-end 3)
5968 (progn
5969 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5970 (org-rear-nonsticky-at (match-beginning 3))
5971 (add-text-properties (match-beginning 3) (match-end 3) vp)
5972 (org-rear-nonsticky-at (match-end 3))
5973 (add-text-properties (match-end 3) (match-end 0) ip)
5974 (org-rear-nonsticky-at (match-end 0)))
5975 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5976 (org-rear-nonsticky-at (match-beginning 1))
5977 (add-text-properties (match-beginning 1) (match-end 1) vp)
5978 (org-rear-nonsticky-at (match-end 1))
5979 (add-text-properties (match-end 1) (match-end 0) ip)
5980 (org-rear-nonsticky-at (match-end 0)))
5981 t)))
5983 (defun org-activate-dates (limit)
5984 "Run through the buffer and add overlays to dates."
5985 (if (and (re-search-forward org-tsr-regexp-both limit t)
5986 (not (equal (char-before (match-beginning 0)) 91)))
5987 (progn
5988 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5989 (add-text-properties (match-beginning 0) (match-end 0)
5990 (list 'mouse-face 'highlight
5991 'keymap org-mouse-map))
5992 (org-rear-nonsticky-at (match-end 0))
5993 (when org-display-custom-times
5994 (if (match-end 3)
5995 (org-display-custom-time (match-beginning 3) (match-end 3)))
5996 (org-display-custom-time (match-beginning 1) (match-end 1)))
5997 t)))
5999 (defvar org-target-link-regexp nil
6000 "Regular expression matching radio targets in plain text.")
6001 (make-variable-buffer-local 'org-target-link-regexp)
6002 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6003 "Regular expression matching a link target.")
6004 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6005 "Regular expression matching a radio target.")
6006 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6007 "Regular expression matching any target.")
6009 (defun org-activate-target-links (limit)
6010 "Run through the buffer and add overlays to target matches."
6011 (when org-target-link-regexp
6012 (let ((case-fold-search t))
6013 (if (re-search-forward org-target-link-regexp limit t)
6014 (progn
6015 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6016 (add-text-properties (match-beginning 0) (match-end 0)
6017 (list 'mouse-face 'highlight
6018 'keymap org-mouse-map
6019 'help-echo "Radio target link"
6020 'org-linked-text t))
6021 (org-rear-nonsticky-at (match-end 0))
6022 t)))))
6024 (defun org-update-radio-target-regexp ()
6025 "Find all radio targets in this file and update the regular expression."
6026 (interactive)
6027 (when (memq 'radio org-activate-links)
6028 (setq org-target-link-regexp
6029 (org-make-target-link-regexp (org-all-targets 'radio)))
6030 (org-restart-font-lock)))
6032 (defun org-hide-wide-columns (limit)
6033 (let (s e)
6034 (setq s (text-property-any (point) (or limit (point-max))
6035 'org-cwidth t))
6036 (when s
6037 (setq e (next-single-property-change s 'org-cwidth))
6038 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6039 (goto-char e)
6040 t)))
6042 (defvar org-latex-and-related-regexp nil
6043 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6044 (defvar org-match-substring-regexp)
6045 (defvar org-match-substring-with-braces-regexp)
6047 (defun org-compute-latex-and-related-regexp ()
6048 "Compute regular expression for LaTeX, entities and sub/superscript.
6049 Result depends on variable `org-highlight-latex-and-related'."
6050 (org-set-local
6051 'org-latex-and-related-regexp
6052 (let* ((re-sub
6053 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6054 ((eq org-use-sub-superscripts '{})
6055 (list org-match-substring-with-braces-regexp))
6056 (org-use-sub-superscripts (list org-match-substring-regexp))))
6057 (re-latex
6058 (when (memq 'latex org-highlight-latex-and-related)
6059 (let ((matchers (plist-get org-format-latex-options :matchers)))
6060 (delq nil
6061 (mapcar (lambda (x)
6062 (and (member (car x) matchers) (nth 1 x)))
6063 org-latex-regexps)))))
6064 (re-entities
6065 (when (memq 'entities org-highlight-latex-and-related)
6066 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6067 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6069 (defun org-do-latex-and-related (limit)
6070 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6071 LIMIT bounds the search for syntax to highlight. Stop at first
6072 highlighted object, if any. Return t if some highlighting was
6073 done, nil otherwise."
6074 (when (org-string-nw-p org-latex-and-related-regexp)
6075 (catch 'found
6076 (while (re-search-forward org-latex-and-related-regexp limit t)
6077 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6078 'face))
6079 '(org-code org-verbatim underline))
6080 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6081 '(?_ ?^))
6083 0)))
6084 (font-lock-prepend-text-property
6085 (+ offset (match-beginning 0)) (match-end 0)
6086 'face 'org-latex-and-related)
6087 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6088 '(font-lock-multiline t)))
6089 (throw 'found t)))
6090 nil)))
6092 (defun org-restart-font-lock ()
6093 "Restart `font-lock-mode', to force refontification."
6094 (when (and (boundp 'font-lock-mode) font-lock-mode)
6095 (font-lock-mode -1)
6096 (font-lock-mode 1)))
6098 (defun org-all-targets (&optional radio)
6099 "Return a list of all targets in this file.
6100 When optional argument RADIO is non-nil, only find radio
6101 targets."
6102 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6103 (save-excursion
6104 (goto-char (point-min))
6105 (while (re-search-forward re nil t)
6106 ;; Make sure point is really within the object.
6107 (backward-char)
6108 (let ((obj (org-element-context)))
6109 (when (memq (org-element-type obj) '(radio-target target))
6110 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6111 rtn)))
6113 (defun org-make-target-link-regexp (targets)
6114 "Make regular expression matching all strings in TARGETS.
6115 The regular expression finds the targets also if there is a line break
6116 between words."
6117 (and targets
6118 (concat
6119 "\\<\\("
6120 (mapconcat
6121 (lambda (x)
6122 (setq x (regexp-quote x))
6123 (while (string-match " +" x)
6124 (setq x (replace-match "\\s-+" t t x)))
6126 targets
6127 "\\|")
6128 "\\)\\>")))
6130 (defun org-activate-tags (limit)
6131 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6132 (progn
6133 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6134 (add-text-properties (match-beginning 1) (match-end 1)
6135 (list 'mouse-face 'highlight
6136 'keymap org-mouse-map))
6137 (org-rear-nonsticky-at (match-end 1))
6138 t)))
6140 (defun org-outline-level ()
6141 "Compute the outline level of the heading at point.
6142 If this is called at a normal headline, the level is the number of stars.
6143 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6144 (save-excursion
6145 (if (not (condition-case nil
6146 (org-back-to-heading t)
6147 (error nil)))
6149 (looking-at org-outline-regexp)
6150 (1- (- (match-end 0) (match-beginning 0))))))
6152 (defvar org-font-lock-keywords nil)
6154 (defsubst org-re-property (property &optional literal)
6155 "Return a regexp matching a PROPERTY line.
6156 Match group 3 will be set to the value if it exists."
6157 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6158 (if literal property (regexp-quote property))
6159 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6161 (defconst org-property-re
6162 (org-re-property ".*?" 'literal)
6163 "Regular expression matching a property line.
6164 There are four matching groups:
6165 1: :PROPKEY: including the leading and trailing colon,
6166 2: PROPKEY without the leading and trailing colon,
6167 3: PROPVAL without leading or trailing spaces,
6168 4: the indentation of the current line,
6169 5: trailing whitespace.")
6171 (defvar org-font-lock-hook nil
6172 "Functions to be called for special font lock stuff.")
6174 (defvar org-font-lock-set-keywords-hook nil
6175 "Functions that can manipulate `org-font-lock-extra-keywords'.
6176 This is called after `org-font-lock-extra-keywords' is defined, but before
6177 it is installed to be used by font lock. This can be useful if something
6178 needs to be inserted at a specific position in the font-lock sequence.")
6180 (defun org-font-lock-hook (limit)
6181 "Run `org-font-lock-hook' within LIMIT."
6182 (run-hook-with-args 'org-font-lock-hook limit))
6184 (defun org-set-font-lock-defaults ()
6185 "Set font lock defaults for the current buffer."
6186 (let* ((em org-fontify-emphasized-text)
6187 (lk org-activate-links)
6188 (org-font-lock-extra-keywords
6189 (list
6190 ;; Call the hook
6191 '(org-font-lock-hook)
6192 ;; Headlines
6193 `(,(if org-fontify-whole-heading-line
6194 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6195 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6196 (1 (org-get-level-face 1))
6197 (2 (org-get-level-face 2))
6198 (3 (org-get-level-face 3)))
6199 ;; Table lines
6200 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6201 (1 'org-table t))
6202 ;; Table internals
6203 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6204 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6205 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6206 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6207 ;; Drawers
6208 (list org-drawer-regexp '(0 'org-special-keyword t))
6209 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6210 ;; Properties
6211 (list org-property-re
6212 '(1 'org-special-keyword t)
6213 '(3 'org-property-value t))
6214 ;; Links
6215 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6216 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6217 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6218 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6219 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6220 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6221 (if (memq 'footnote lk) '(org-activate-footnote-links))
6222 ;; Targets.
6223 (list org-any-target-regexp '(0 'org-target t))
6224 ;; Diary sexps.
6225 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6226 ;; Macro
6227 '("{{{.+}}}" (0 'org-macro t))
6228 '(org-hide-wide-columns (0 nil append))
6229 ;; TODO keyword
6230 (list (format org-heading-keyword-regexp-format
6231 org-todo-regexp)
6232 '(2 (org-get-todo-face 2) t))
6233 ;; DONE
6234 (if org-fontify-done-headline
6235 (list (format org-heading-keyword-regexp-format
6236 (concat
6237 "\\(?:"
6238 (mapconcat 'regexp-quote org-done-keywords "\\|")
6239 "\\)"))
6240 '(2 'org-headline-done t))
6241 nil)
6242 ;; Priorities
6243 '(org-font-lock-add-priority-faces)
6244 ;; Tags
6245 '(org-font-lock-add-tag-faces)
6246 ;; Tags groups
6247 (if (and org-group-tags org-tag-groups-alist)
6248 (list (concat org-outline-regexp-bol ".+\\(:"
6249 (regexp-opt (mapcar 'car org-tag-groups-alist))
6250 ":\\).*$")
6251 '(1 'org-tag-group prepend)))
6252 ;; Special keywords
6253 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6254 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6255 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6256 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6257 ;; Emphasis
6258 (if em
6259 (if (featurep 'xemacs)
6260 '(org-do-emphasis-faces (0 nil append))
6261 '(org-do-emphasis-faces)))
6262 ;; Checkboxes
6263 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6264 1 'org-checkbox prepend)
6265 (if (cdr (assq 'checkbox org-list-automatic-rules))
6266 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6267 (0 (org-get-checkbox-statistics-face) t)))
6268 ;; Description list items
6269 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6270 1 'org-list-dt prepend)
6271 ;; ARCHIVEd headings
6272 (list (concat
6273 org-outline-regexp-bol
6274 "\\(.*:" org-archive-tag ":.*\\)")
6275 '(1 'org-archived prepend))
6276 ;; Specials
6277 '(org-do-latex-and-related)
6278 '(org-fontify-entities)
6279 '(org-raise-scripts)
6280 ;; Code
6281 '(org-activate-code (1 'org-code t))
6282 ;; COMMENT
6283 (list (format org-heading-keyword-regexp-format
6284 (concat "\\("
6285 org-comment-string "\\|" org-quote-string
6286 "\\)"))
6287 '(2 'org-special-keyword t))
6288 ;; Blocks and meta lines
6289 '(org-fontify-meta-lines-and-blocks))))
6290 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6291 (run-hooks 'org-font-lock-set-keywords-hook)
6292 ;; Now set the full font-lock-keywords
6293 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6294 (org-set-local 'font-lock-defaults
6295 '(org-font-lock-keywords t nil nil backward-paragraph))
6296 (kill-local-variable 'font-lock-keywords) nil))
6298 (defun org-toggle-pretty-entities ()
6299 "Toggle the composition display of entities as UTF8 characters."
6300 (interactive)
6301 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6302 (org-restart-font-lock)
6303 (if org-pretty-entities
6304 (message "Entities are now displayed as UTF8 characters")
6305 (save-restriction
6306 (widen)
6307 (org-decompose-region (point-min) (point-max))
6308 (message "Entities are now displayed as plain text"))))
6310 (defvar org-custom-properties-overlays nil
6311 "List of overlays used for custom properties.")
6312 (make-variable-buffer-local 'org-custom-properties-overlays)
6314 (defun org-toggle-custom-properties-visibility ()
6315 "Display or hide properties in `org-custom-properties'."
6316 (interactive)
6317 (if org-custom-properties-overlays
6318 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6319 (setq org-custom-properties-overlays nil))
6320 (unless (not org-custom-properties)
6321 (save-excursion
6322 (save-restriction
6323 (widen)
6324 (goto-char (point-min))
6325 (while (re-search-forward org-property-re nil t)
6326 (mapc (lambda(p)
6327 (when (equal p (substring (match-string 1) 1 -1))
6328 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6329 (overlay-put o 'invisible t)
6330 (overlay-put o 'org-custom-property t)
6331 (push o org-custom-properties-overlays))))
6332 org-custom-properties)))))))
6334 (defun org-fontify-entities (limit)
6335 "Find an entity to fontify."
6336 (let (ee)
6337 (when org-pretty-entities
6338 (catch 'match
6339 (while (re-search-forward
6340 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6341 limit t)
6342 (if (and (not (org-in-indented-comment-line))
6343 (setq ee (org-entity-get (match-string 1)))
6344 (= (length (nth 6 ee)) 1))
6345 (let*
6346 ((end (if (equal (match-string 2) "{}")
6347 (match-end 2)
6348 (match-end 1))))
6349 (add-text-properties
6350 (match-beginning 0) end
6351 (list 'font-lock-fontified t))
6352 (compose-region (match-beginning 0) end
6353 (nth 6 ee) nil)
6354 (backward-char 1)
6355 (throw 'match t))))
6356 nil))))
6358 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6359 "Fontify string S like in Org-mode."
6360 (with-temp-buffer
6361 (insert s)
6362 (let ((org-odd-levels-only odd-levels))
6363 (org-mode)
6364 (font-lock-fontify-buffer)
6365 (buffer-string))))
6367 (defvar org-m nil)
6368 (defvar org-l nil)
6369 (defvar org-f nil)
6370 (defun org-get-level-face (n)
6371 "Get the right face for match N in font-lock matching of headlines."
6372 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6373 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6374 (if org-cycle-level-faces
6375 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6376 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6377 (cond
6378 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6379 ((eq n 2) org-f)
6380 (t (if org-level-color-stars-only nil org-f))))
6383 (defun org-get-todo-face (kwd)
6384 "Get the right face for a TODO keyword KWD.
6385 If KWD is a number, get the corresponding match group."
6386 (if (numberp kwd) (setq kwd (match-string kwd)))
6387 (or (org-face-from-face-or-color
6388 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6389 (and (member kwd org-done-keywords) 'org-done)
6390 'org-todo))
6392 (defun org-face-from-face-or-color (context inherit face-or-color)
6393 "Create a face list that inherits INHERIT, but sets the foreground color.
6394 When FACE-OR-COLOR is not a string, just return it."
6395 (if (stringp face-or-color)
6396 (list :inherit inherit
6397 (cdr (assoc context org-faces-easy-properties))
6398 face-or-color)
6399 face-or-color))
6401 (defun org-font-lock-add-tag-faces (limit)
6402 "Add the special tag faces."
6403 (when (and org-tag-faces org-tags-special-faces-re)
6404 (while (re-search-forward org-tags-special-faces-re limit t)
6405 (add-text-properties (match-beginning 1) (match-end 1)
6406 (list 'face (org-get-tag-face 1)
6407 'font-lock-fontified t))
6408 (backward-char 1))))
6410 (defun org-font-lock-add-priority-faces (limit)
6411 "Add the special priority faces."
6412 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6413 (when (save-match-data (org-at-heading-p))
6414 (add-text-properties
6415 (match-beginning 0) (match-end 0)
6416 (list 'face (or (org-face-from-face-or-color
6417 'priority 'org-priority
6418 (cdr (assoc (char-after (match-beginning 1))
6419 org-priority-faces)))
6420 'org-priority)
6421 'font-lock-fontified t)))))
6423 (defun org-get-tag-face (kwd)
6424 "Get the right face for a TODO keyword KWD.
6425 If KWD is a number, get the corresponding match group."
6426 (if (numberp kwd) (setq kwd (match-string kwd)))
6427 (or (org-face-from-face-or-color
6428 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6429 'org-tag))
6431 (defun org-unfontify-region (beg end &optional maybe_loudly)
6432 "Remove fontification and activation overlays from links."
6433 (font-lock-default-unfontify-region beg end)
6434 (let* ((buffer-undo-list t)
6435 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6436 (inhibit-modification-hooks t)
6437 deactivate-mark buffer-file-name buffer-file-truename)
6438 (org-decompose-region beg end)
6439 (remove-text-properties beg end
6440 '(mouse-face t keymap t org-linked-text t
6441 invisible t intangible t
6442 org-no-flyspell t org-emphasis t))
6443 (org-remove-font-lock-display-properties beg end)))
6445 (defconst org-script-display '(((raise -0.3) (height 0.7))
6446 ((raise 0.3) (height 0.7))
6447 ((raise -0.5))
6448 ((raise 0.5)))
6449 "Display properties for showing superscripts and subscripts.")
6451 (defun org-remove-font-lock-display-properties (beg end)
6452 "Remove specific display properties that have been added by font lock.
6453 The will remove the raise properties that are used to show superscripts
6454 and subscripts."
6455 (let (next prop)
6456 (while (< beg end)
6457 (setq next (next-single-property-change beg 'display nil end)
6458 prop (get-text-property beg 'display))
6459 (if (member prop org-script-display)
6460 (put-text-property beg next 'display nil))
6461 (setq beg next))))
6463 (defun org-raise-scripts (limit)
6464 "Add raise properties to sub/superscripts."
6465 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6466 (if (re-search-forward
6467 (if (eq org-use-sub-superscripts t)
6468 org-match-substring-regexp
6469 org-match-substring-with-braces-regexp)
6470 limit t)
6471 (let* ((pos (point)) table-p comment-p
6472 (mpos (match-beginning 3))
6473 (emph-p (get-text-property mpos 'org-emphasis))
6474 (link-p (get-text-property mpos 'mouse-face))
6475 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6476 (goto-char (point-at-bol))
6477 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6478 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6479 (goto-char pos)
6480 ;; Handle a_b^c
6481 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6482 (if (or comment-p emph-p link-p keyw-p)
6484 (put-text-property (match-beginning 3) (match-end 0)
6485 'display
6486 (if (equal (char-after (match-beginning 2)) ?^)
6487 (nth (if table-p 3 1) org-script-display)
6488 (nth (if table-p 2 0) org-script-display)))
6489 (add-text-properties (match-beginning 2) (match-end 2)
6490 (list 'invisible t
6491 'org-dwidth t 'org-dwidth-n 1))
6492 (if (and (eq (char-after (match-beginning 3)) ?{)
6493 (eq (char-before (match-end 3)) ?}))
6494 (progn
6495 (add-text-properties
6496 (match-beginning 3) (1+ (match-beginning 3))
6497 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6498 (add-text-properties
6499 (1- (match-end 3)) (match-end 3)
6500 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6501 t)))))
6503 ;;;; Visibility cycling, including org-goto and indirect buffer
6505 ;;; Cycling
6507 (defvar org-cycle-global-status nil)
6508 (make-variable-buffer-local 'org-cycle-global-status)
6509 (put 'org-cycle-global-status 'org-state t)
6510 (defvar org-cycle-subtree-status nil)
6511 (make-variable-buffer-local 'org-cycle-subtree-status)
6512 (put 'org-cycle-subtree-status 'org-state t)
6514 (defvar org-inlinetask-min-level)
6516 (defun org-unlogged-message (&rest args)
6517 "Display a message, but avoid logging it in the *Messages* buffer."
6518 (let ((message-log-max nil))
6519 (apply 'message args)))
6521 ;;;###autoload
6522 (defun org-cycle (&optional arg)
6523 "TAB-action and visibility cycling for Org-mode.
6525 This is the command invoked in Org-mode by the TAB key. Its main purpose
6526 is outline visibility cycling, but it also invokes other actions
6527 in special contexts.
6529 - When this function is called with a prefix argument, rotate the entire
6530 buffer through 3 states (global cycling)
6531 1. OVERVIEW: Show only top-level headlines.
6532 2. CONTENTS: Show all headlines of all levels, but no body text.
6533 3. SHOW ALL: Show everything.
6534 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6535 determined by the variable `org-startup-folded', and by any VISIBILITY
6536 properties in the buffer.
6537 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6538 including any drawers.
6540 - When inside a table, re-align the table and move to the next field.
6542 - When point is at the beginning of a headline, rotate the subtree started
6543 by this line through 3 different states (local cycling)
6544 1. FOLDED: Only the main headline is shown.
6545 2. CHILDREN: The main headline and the direct children are shown.
6546 From this state, you can move to one of the children
6547 and zoom in further.
6548 3. SUBTREE: Show the entire subtree, including body text.
6549 If there is no subtree, switch directly from CHILDREN to FOLDED.
6551 - When point is at the beginning of an empty headline and the variable
6552 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6553 of the headline by demoting and promoting it to likely levels. This
6554 speeds up creation document structure by pressing TAB once or several
6555 times right after creating a new headline.
6557 - When there is a numeric prefix, go up to a heading with level ARG, do
6558 a `show-subtree' and return to the previous cursor position. If ARG
6559 is negative, go up that many levels.
6561 - When point is not at the beginning of a headline, execute the global
6562 binding for TAB, which is re-indenting the line. See the option
6563 `org-cycle-emulate-tab' for details.
6565 - Special case: if point is at the beginning of the buffer and there is
6566 no headline in line 1, this function will act as if called with prefix arg
6567 (C-u TAB, same as S-TAB) also when called without prefix arg.
6568 But only if also the variable `org-cycle-global-at-bob' is t."
6569 (interactive "P")
6570 (org-load-modules-maybe)
6571 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6572 (and org-cycle-level-after-item/entry-creation
6573 (or (org-cycle-level)
6574 (org-cycle-item-indentation))))
6575 (let* ((limit-level
6576 (or org-cycle-max-level
6577 (and (boundp 'org-inlinetask-min-level)
6578 org-inlinetask-min-level
6579 (1- org-inlinetask-min-level))))
6580 (nstars (and limit-level
6581 (if org-odd-levels-only
6582 (and limit-level (1- (* limit-level 2)))
6583 limit-level)))
6584 (org-outline-regexp
6585 (if (not (derived-mode-p 'org-mode))
6586 outline-regexp
6587 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6588 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6589 (not (looking-at org-outline-regexp))))
6590 (org-cycle-hook
6591 (if bob-special
6592 (delq 'org-optimize-window-after-visibility-change
6593 (copy-sequence org-cycle-hook))
6594 org-cycle-hook))
6595 (pos (point)))
6597 (if (or bob-special (equal arg '(4)))
6598 ;; special case: use global cycling
6599 (setq arg t))
6601 (cond
6603 ((equal arg '(16))
6604 (setq last-command 'dummy)
6605 (org-set-startup-visibility)
6606 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6608 ((equal arg '(64))
6609 (show-all)
6610 (org-unlogged-message "Entire buffer visible, including drawers"))
6612 ;; Table: enter it or move to the next field.
6613 ((org-at-table-p 'any)
6614 (if (org-at-table.el-p)
6615 (message "Use C-c ' to edit table.el tables")
6616 (if arg (org-table-edit-field t)
6617 (org-table-justify-field-maybe)
6618 (call-interactively 'org-table-next-field))))
6620 ((run-hook-with-args-until-success
6621 'org-tab-after-check-for-table-hook))
6623 ;; Global cycling: delegate to `org-cycle-internal-global'.
6624 ((eq arg t) (org-cycle-internal-global))
6626 ;; Drawers: delegate to `org-flag-drawer'.
6627 ((and org-drawers org-drawer-regexp
6628 (save-excursion
6629 (beginning-of-line 1)
6630 (looking-at org-drawer-regexp)))
6631 (org-flag-drawer ; toggle block visibility
6632 (not (get-char-property (match-end 0) 'invisible))))
6634 ;; Show-subtree, ARG levels up from here.
6635 ((integerp arg)
6636 (save-excursion
6637 (org-back-to-heading)
6638 (outline-up-heading (if (< arg 0) (- arg)
6639 (- (funcall outline-level) arg)))
6640 (org-show-subtree)))
6642 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6643 ((and (featurep 'org-inlinetask)
6644 (org-inlinetask-at-task-p)
6645 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6646 (org-inlinetask-toggle-visibility))
6648 ((org-try-cdlatex-tab))
6650 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6651 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6652 (save-excursion (beginning-of-line 1)
6653 (looking-at org-outline-regexp)))
6654 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6655 (org-cycle-internal-local))
6657 ;; From there: TAB emulation and template completion.
6658 (buffer-read-only (org-back-to-heading))
6660 ((run-hook-with-args-until-success
6661 'org-tab-after-check-for-cycling-hook))
6663 ((org-try-structure-completion))
6665 ((run-hook-with-args-until-success
6666 'org-tab-before-tab-emulation-hook))
6668 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6669 (or (not (bolp))
6670 (not (looking-at org-outline-regexp))))
6671 (call-interactively (global-key-binding "\t")))
6673 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6674 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6675 (or (and (eq org-cycle-emulate-tab 'white)
6676 (= (match-end 0) (point-at-eol)))
6677 (and (eq org-cycle-emulate-tab 'whitestart)
6678 (>= (match-end 0) pos))))
6680 (eq org-cycle-emulate-tab t))
6681 (call-interactively (global-key-binding "\t")))
6683 (t (save-excursion
6684 (org-back-to-heading)
6685 (org-cycle)))))))
6687 (defun org-cycle-internal-global ()
6688 "Do the global cycling action."
6689 ;; Hack to avoid display of messages for .org attachments in Gnus
6690 (let ((ga (string-match "\\*fontification" (buffer-name))))
6691 (cond
6692 ((and (eq last-command this-command)
6693 (eq org-cycle-global-status 'overview))
6694 ;; We just created the overview - now do table of contents
6695 ;; This can be slow in very large buffers, so indicate action
6696 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6697 (unless ga (org-unlogged-message "CONTENTS..."))
6698 (org-content)
6699 (unless ga (org-unlogged-message "CONTENTS...done"))
6700 (setq org-cycle-global-status 'contents)
6701 (run-hook-with-args 'org-cycle-hook 'contents))
6703 ((and (eq last-command this-command)
6704 (eq org-cycle-global-status 'contents))
6705 ;; We just showed the table of contents - now show everything
6706 (run-hook-with-args 'org-pre-cycle-hook 'all)
6707 (show-all)
6708 (unless ga (org-unlogged-message "SHOW ALL"))
6709 (setq org-cycle-global-status 'all)
6710 (run-hook-with-args 'org-cycle-hook 'all))
6713 ;; Default action: go to overview
6714 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6715 (org-overview)
6716 (unless ga (org-unlogged-message "OVERVIEW"))
6717 (setq org-cycle-global-status 'overview)
6718 (run-hook-with-args 'org-cycle-hook 'overview)))))
6720 (defun org-cycle-internal-local ()
6721 "Do the local cycling action."
6722 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6723 ;; First, determine end of headline (EOH), end of subtree or item
6724 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6725 (save-excursion
6726 (if (org-at-item-p)
6727 (progn
6728 (beginning-of-line)
6729 (setq struct (org-list-struct))
6730 (setq eoh (point-at-eol))
6731 (setq eos (org-list-get-item-end-before-blank (point) struct))
6732 (setq has-children (org-list-has-child-p (point) struct)))
6733 (org-back-to-heading)
6734 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6735 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6736 (setq has-children
6737 (or (save-excursion
6738 (let ((level (funcall outline-level)))
6739 (outline-next-heading)
6740 (and (org-at-heading-p t)
6741 (> (funcall outline-level) level))))
6742 (save-excursion
6743 (org-list-search-forward (org-item-beginning-re) eos t)))))
6744 ;; Determine end invisible part of buffer (EOL)
6745 (beginning-of-line 2)
6746 ;; XEmacs doesn't have `next-single-char-property-change'
6747 (if (featurep 'xemacs)
6748 (while (and (not (eobp)) ;; this is like `next-line'
6749 (get-char-property (1- (point)) 'invisible))
6750 (beginning-of-line 2))
6751 (while (and (not (eobp)) ;; this is like `next-line'
6752 (get-char-property (1- (point)) 'invisible))
6753 (goto-char (next-single-char-property-change (point) 'invisible))
6754 (and (eolp) (beginning-of-line 2))))
6755 (setq eol (point)))
6756 ;; Find out what to do next and set `this-command'
6757 (cond
6758 ((= eos eoh)
6759 ;; Nothing is hidden behind this heading
6760 (unless (org-before-first-heading-p)
6761 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6762 (org-unlogged-message "EMPTY ENTRY")
6763 (setq org-cycle-subtree-status nil)
6764 (save-excursion
6765 (goto-char eos)
6766 (outline-next-heading)
6767 (if (outline-invisible-p) (org-flag-heading nil))))
6768 ((and (or (>= eol eos)
6769 (not (string-match "\\S-" (buffer-substring eol eos))))
6770 (or has-children
6771 (not (setq children-skipped
6772 org-cycle-skip-children-state-if-no-children))))
6773 ;; Entire subtree is hidden in one line: children view
6774 (unless (org-before-first-heading-p)
6775 (run-hook-with-args 'org-pre-cycle-hook 'children))
6776 (if (org-at-item-p)
6777 (org-list-set-item-visibility (point-at-bol) struct 'children)
6778 (org-show-entry)
6779 (org-with-limited-levels (show-children))
6780 ;; FIXME: This slows down the func way too much.
6781 ;; How keep drawers hidden in subtree anyway?
6782 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6783 ;; (org-cycle-hide-drawers 'subtree))
6785 ;; Fold every list in subtree to top-level items.
6786 (when (eq org-cycle-include-plain-lists 'integrate)
6787 (save-excursion
6788 (org-back-to-heading)
6789 (while (org-list-search-forward (org-item-beginning-re) eos t)
6790 (beginning-of-line 1)
6791 (let* ((struct (org-list-struct))
6792 (prevs (org-list-prevs-alist struct))
6793 (end (org-list-get-bottom-point struct)))
6794 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6795 (org-list-get-all-items (point) struct prevs))
6796 (goto-char (if (< end eos) end eos)))))))
6797 (org-unlogged-message "CHILDREN")
6798 (save-excursion
6799 (goto-char eos)
6800 (outline-next-heading)
6801 (if (outline-invisible-p) (org-flag-heading nil)))
6802 (setq org-cycle-subtree-status 'children)
6803 (unless (org-before-first-heading-p)
6804 (run-hook-with-args 'org-cycle-hook 'children)))
6805 ((or children-skipped
6806 (and (eq last-command this-command)
6807 (eq org-cycle-subtree-status 'children)))
6808 ;; We just showed the children, or no children are there,
6809 ;; now show everything.
6810 (unless (org-before-first-heading-p)
6811 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6812 (outline-flag-region eoh eos nil)
6813 (org-unlogged-message
6814 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6815 (setq org-cycle-subtree-status 'subtree)
6816 (unless (org-before-first-heading-p)
6817 (run-hook-with-args 'org-cycle-hook 'subtree)))
6819 ;; Default action: hide the subtree.
6820 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6821 (outline-flag-region eoh eos t)
6822 (org-unlogged-message "FOLDED")
6823 (setq org-cycle-subtree-status 'folded)
6824 (unless (org-before-first-heading-p)
6825 (run-hook-with-args 'org-cycle-hook 'folded))))))
6827 ;;;###autoload
6828 (defun org-global-cycle (&optional arg)
6829 "Cycle the global visibility. For details see `org-cycle'.
6830 With \\[universal-argument] prefix arg, switch to startup visibility.
6831 With a numeric prefix, show all headlines up to that level."
6832 (interactive "P")
6833 (let ((org-cycle-include-plain-lists
6834 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6835 (cond
6836 ((integerp arg)
6837 (show-all)
6838 (hide-sublevels arg)
6839 (setq org-cycle-global-status 'contents))
6840 ((equal arg '(4))
6841 (org-set-startup-visibility)
6842 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6844 (org-cycle '(4))))))
6846 (defun org-set-startup-visibility ()
6847 "Set the visibility required by startup options and properties."
6848 (cond
6849 ((eq org-startup-folded t)
6850 (org-cycle '(4)))
6851 ((eq org-startup-folded 'content)
6852 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6853 (org-cycle '(4)) (org-cycle '(4)))))
6854 (unless (eq org-startup-folded 'showeverything)
6855 (if org-hide-block-startup (org-hide-block-all))
6856 (org-set-visibility-according-to-property 'no-cleanup)
6857 (org-cycle-hide-archived-subtrees 'all)
6858 (org-cycle-hide-drawers 'all)
6859 (org-cycle-show-empty-lines t)))
6861 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6862 "Switch subtree visibilities according to :VISIBILITY: property."
6863 (interactive)
6864 (let (org-show-entry-below state)
6865 (save-excursion
6866 (goto-char (point-min))
6867 (while (re-search-forward
6868 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6869 nil t)
6870 (setq state (match-string 1))
6871 (save-excursion
6872 (org-back-to-heading t)
6873 (hide-subtree)
6874 (org-reveal)
6875 (cond
6876 ((equal state '("fold" "folded"))
6877 (hide-subtree))
6878 ((equal state "children")
6879 (org-show-hidden-entry)
6880 (show-children))
6881 ((equal state "content")
6882 (save-excursion
6883 (save-restriction
6884 (org-narrow-to-subtree)
6885 (org-content))))
6886 ((member state '("all" "showall"))
6887 (show-subtree)))))
6888 (unless no-cleanup
6889 (org-cycle-hide-archived-subtrees 'all)
6890 (org-cycle-hide-drawers 'all)
6891 (org-cycle-show-empty-lines 'all)))))
6893 ;; This function uses outline-regexp instead of the more fundamental
6894 ;; org-outline-regexp so that org-cycle-global works outside of Org
6895 ;; buffers, where outline-regexp is needed.
6896 (defun org-overview ()
6897 "Switch to overview mode, showing only top-level headlines.
6898 Really, this shows all headlines with level equal or greater than the level
6899 of the first headline in the buffer. This is important, because if the
6900 first headline is not level one, then (hide-sublevels 1) gives confusing
6901 results."
6902 (interactive)
6903 (let ((pos (point))
6904 (level (save-excursion
6905 (goto-char (point-min))
6906 (if (re-search-forward (concat "^" outline-regexp) nil t)
6907 (progn
6908 (goto-char (match-beginning 0))
6909 (funcall outline-level))))))
6910 (and level (hide-sublevels level))
6911 (recenter '(4))
6912 (goto-char pos)))
6914 (defun org-content (&optional arg)
6915 "Show all headlines in the buffer, like a table of contents.
6916 With numerical argument N, show content up to level N."
6917 (interactive "P")
6918 (save-excursion
6919 ;; Visit all headings and show their offspring
6920 (and (integerp arg) (org-overview))
6921 (goto-char (point-max))
6922 (catch 'exit
6923 (while (and (progn (condition-case nil
6924 (outline-previous-visible-heading 1)
6925 (error (goto-char (point-min))))
6927 (looking-at org-outline-regexp))
6928 (if (integerp arg)
6929 (show-children (1- arg))
6930 (show-branches))
6931 (if (bobp) (throw 'exit nil))))))
6934 (defun org-optimize-window-after-visibility-change (state)
6935 "Adjust the window after a change in outline visibility.
6936 This function is the default value of the hook `org-cycle-hook'."
6937 (when (get-buffer-window (current-buffer))
6938 (cond
6939 ((eq state 'content) nil)
6940 ((eq state 'all) nil)
6941 ((eq state 'folded) nil)
6942 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6943 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6945 (defun org-remove-empty-overlays-at (pos)
6946 "Remove outline overlays that do not contain non-white stuff."
6947 (mapc
6948 (lambda (o)
6949 (and (eq 'outline (overlay-get o 'invisible))
6950 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6951 (overlay-end o))))
6952 (delete-overlay o)))
6953 (overlays-at pos)))
6955 (defun org-clean-visibility-after-subtree-move ()
6956 "Fix visibility issues after moving a subtree."
6957 ;; First, find a reasonable region to look at:
6958 ;; Start two siblings above, end three below
6959 (let* ((beg (save-excursion
6960 (and (org-get-last-sibling)
6961 (org-get-last-sibling))
6962 (point)))
6963 (end (save-excursion
6964 (and (org-get-next-sibling)
6965 (org-get-next-sibling)
6966 (org-get-next-sibling))
6967 (if (org-at-heading-p)
6968 (point-at-eol)
6969 (point))))
6970 (level (looking-at "\\*+"))
6971 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6972 (save-excursion
6973 (save-restriction
6974 (narrow-to-region beg end)
6975 (when re
6976 ;; Properly fold already folded siblings
6977 (goto-char (point-min))
6978 (while (re-search-forward re nil t)
6979 (if (and (not (outline-invisible-p))
6980 (save-excursion
6981 (goto-char (point-at-eol)) (outline-invisible-p)))
6982 (hide-entry))))
6983 (org-cycle-show-empty-lines 'overview)
6984 (org-cycle-hide-drawers 'overview)))))
6986 (defun org-cycle-show-empty-lines (state)
6987 "Show empty lines above all visible headlines.
6988 The region to be covered depends on STATE when called through
6989 `org-cycle-hook'. Lisp program can use t for STATE to get the
6990 entire buffer covered. Note that an empty line is only shown if there
6991 are at least `org-cycle-separator-lines' empty lines before the headline."
6992 (when (not (= org-cycle-separator-lines 0))
6993 (save-excursion
6994 (let* ((n (abs org-cycle-separator-lines))
6995 (re (cond
6996 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6997 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6998 (t (let ((ns (number-to-string (- n 2))))
6999 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7000 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7001 beg end b e)
7002 (cond
7003 ((memq state '(overview contents t))
7004 (setq beg (point-min) end (point-max)))
7005 ((memq state '(children folded))
7006 (setq beg (point) end (progn (org-end-of-subtree t t)
7007 (beginning-of-line 2)
7008 (point)))))
7009 (when beg
7010 (goto-char beg)
7011 (while (re-search-forward re end t)
7012 (unless (get-char-property (match-end 1) 'invisible)
7013 (setq e (match-end 1))
7014 (if (< org-cycle-separator-lines 0)
7015 (setq b (save-excursion
7016 (goto-char (match-beginning 0))
7017 (org-back-over-empty-lines)
7018 (if (save-excursion
7019 (goto-char (max (point-min) (1- (point))))
7020 (org-at-heading-p))
7021 (1- (point))
7022 (point))))
7023 (setq b (match-beginning 1)))
7024 (outline-flag-region b e nil)))))))
7025 ;; Never hide empty lines at the end of the file.
7026 (save-excursion
7027 (goto-char (point-max))
7028 (outline-previous-heading)
7029 (outline-end-of-heading)
7030 (if (and (looking-at "[ \t\n]+")
7031 (= (match-end 0) (point-max)))
7032 (outline-flag-region (point) (match-end 0) nil))))
7034 (defun org-show-empty-lines-in-parent ()
7035 "Move to the parent and re-show empty lines before visible headlines."
7036 (save-excursion
7037 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7038 (org-cycle-show-empty-lines context))))
7040 (defun org-files-list ()
7041 "Return `org-agenda-files' list, plus all open org-mode files.
7042 This is useful for operations that need to scan all of a user's
7043 open and agenda-wise Org files."
7044 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7045 (dolist (buf (buffer-list))
7046 (with-current-buffer buf
7047 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7048 (let ((file (expand-file-name (buffer-file-name))))
7049 (unless (member file files)
7050 (push file files))))))
7051 files))
7053 (defsubst org-entry-beginning-position ()
7054 "Return the beginning position of the current entry."
7055 (save-excursion (outline-back-to-heading t) (point)))
7057 (defsubst org-entry-end-position ()
7058 "Return the end position of the current entry."
7059 (save-excursion (outline-next-heading) (point)))
7061 (defun org-cycle-hide-drawers (state)
7062 "Re-hide all drawers after a visibility state change."
7063 (when (and (derived-mode-p 'org-mode)
7064 (not (memq state '(overview folded contents))))
7065 (save-excursion
7066 (let* ((globalp (memq state '(contents all)))
7067 (beg (if globalp (point-min) (point)))
7068 (end (if globalp (point-max)
7069 (if (eq state 'children)
7070 (save-excursion (outline-next-heading) (point))
7071 (org-end-of-subtree t)))))
7072 (goto-char beg)
7073 (while (re-search-forward org-drawer-regexp end t)
7074 (org-flag-drawer t))))))
7076 (defun org-cycle-hide-inline-tasks (state)
7077 "Re-hide inline task when switching to 'contents visibility state."
7078 (when (and (eq state 'contents)
7079 (boundp 'org-inlinetask-min-level)
7080 org-inlinetask-min-level)
7081 (hide-sublevels (1- org-inlinetask-min-level))))
7083 (defun org-flag-drawer (flag)
7084 "When FLAG is non-nil, hide the drawer we are within.
7085 Otherwise make it visible."
7086 (save-excursion
7087 (beginning-of-line 1)
7088 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7089 (let ((b (match-end 0)))
7090 (if (re-search-forward
7091 "^[ \t]*:END:"
7092 (save-excursion (outline-next-heading) (point)) t)
7093 (outline-flag-region b (point-at-eol) flag)
7094 (user-error ":END: line missing at position %s" b))))))
7096 (defun org-subtree-end-visible-p ()
7097 "Is the end of the current subtree visible?"
7098 (pos-visible-in-window-p
7099 (save-excursion (org-end-of-subtree t) (point))))
7101 (defun org-first-headline-recenter (&optional N)
7102 "Move cursor to the first headline and recenter the headline.
7103 Optional argument N means put the headline into the Nth line of the window."
7104 (goto-char (point-min))
7105 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7106 (beginning-of-line)
7107 (recenter (prefix-numeric-value N))))
7109 ;;; Saving and restoring visibility
7111 (defun org-outline-overlay-data (&optional use-markers)
7112 "Return a list of the locations of all outline overlays.
7113 These are overlays with the `invisible' property value `outline'.
7114 The return value is a list of cons cells, with start and stop
7115 positions for each overlay.
7116 If USE-MARKERS is set, return the positions as markers."
7117 (let (beg end)
7118 (save-excursion
7119 (save-restriction
7120 (widen)
7121 (delq nil
7122 (mapcar (lambda (o)
7123 (when (eq (overlay-get o 'invisible) 'outline)
7124 (setq beg (overlay-start o)
7125 end (overlay-end o))
7126 (and beg end (> end beg)
7127 (if use-markers
7128 (cons (move-marker (make-marker) beg)
7129 (move-marker (make-marker) end))
7130 (cons beg end)))))
7131 (overlays-in (point-min) (point-max))))))))
7133 (defun org-set-outline-overlay-data (data)
7134 "Create visibility overlays for all positions in DATA.
7135 DATA should have been made by `org-outline-overlay-data'."
7136 (let (o)
7137 (save-excursion
7138 (save-restriction
7139 (widen)
7140 (show-all)
7141 (mapc (lambda (c)
7142 (outline-flag-region (car c) (cdr c) t))
7143 data)))))
7145 ;;; Folding of blocks
7147 (defvar org-hide-block-overlays nil
7148 "Overlays hiding blocks.")
7149 (make-variable-buffer-local 'org-hide-block-overlays)
7151 (defun org-block-map (function &optional start end)
7152 "Call FUNCTION at the head of all source blocks in the current buffer.
7153 Optional arguments START and END can be used to limit the range."
7154 (let ((start (or start (point-min)))
7155 (end (or end (point-max))))
7156 (save-excursion
7157 (goto-char start)
7158 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7159 (save-excursion
7160 (save-match-data
7161 (goto-char (match-beginning 0))
7162 (funcall function)))))))
7164 (defun org-hide-block-toggle-all ()
7165 "Toggle the visibility of all blocks in the current buffer."
7166 (org-block-map #'org-hide-block-toggle))
7168 (defun org-hide-block-all ()
7169 "Fold all blocks in the current buffer."
7170 (interactive)
7171 (org-show-block-all)
7172 (org-block-map #'org-hide-block-toggle-maybe))
7174 (defun org-show-block-all ()
7175 "Unfold all blocks in the current buffer."
7176 (interactive)
7177 (mapc 'delete-overlay org-hide-block-overlays)
7178 (setq org-hide-block-overlays nil))
7180 (defun org-hide-block-toggle-maybe ()
7181 "Toggle visibility of block at point."
7182 (interactive)
7183 (let ((case-fold-search t))
7184 (if (save-excursion
7185 (beginning-of-line 1)
7186 (looking-at org-block-regexp))
7187 (progn (org-hide-block-toggle)
7188 t) ;; to signal that we took action
7189 nil))) ;; to signal that we did not
7191 (defun org-hide-block-toggle (&optional force)
7192 "Toggle the visibility of the current block."
7193 (interactive)
7194 (save-excursion
7195 (beginning-of-line)
7196 (if (re-search-forward org-block-regexp nil t)
7197 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7198 (end (match-end 0)) ;; end of entire body
7200 (if (memq t (mapcar (lambda (overlay)
7201 (eq (overlay-get overlay 'invisible)
7202 'org-hide-block))
7203 (overlays-at start)))
7204 (if (or (not force) (eq force 'off))
7205 (mapc (lambda (ov)
7206 (when (member ov org-hide-block-overlays)
7207 (setq org-hide-block-overlays
7208 (delq ov org-hide-block-overlays)))
7209 (when (eq (overlay-get ov 'invisible)
7210 'org-hide-block)
7211 (delete-overlay ov)))
7212 (overlays-at start)))
7213 (setq ov (make-overlay start end))
7214 (overlay-put ov 'invisible 'org-hide-block)
7215 ;; make the block accessible to isearch
7216 (overlay-put
7217 ov 'isearch-open-invisible
7218 (lambda (ov)
7219 (when (member ov org-hide-block-overlays)
7220 (setq org-hide-block-overlays
7221 (delq ov org-hide-block-overlays)))
7222 (when (eq (overlay-get ov 'invisible)
7223 'org-hide-block)
7224 (delete-overlay ov))))
7225 (push ov org-hide-block-overlays)))
7226 (user-error "Not looking at a source block"))))
7228 ;; org-tab-after-check-for-cycling-hook
7229 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7230 ;; Remove overlays when changing major mode
7231 (add-hook 'org-mode-hook
7232 (lambda () (org-add-hook 'change-major-mode-hook
7233 'org-show-block-all 'append 'local)))
7235 ;;; Org-goto
7237 (defvar org-goto-window-configuration nil)
7238 (defvar org-goto-marker nil)
7239 (defvar org-goto-map)
7240 (defun org-goto-map ()
7241 "Set the keymap `org-goto'."
7242 (setq org-goto-map
7243 (let ((map (make-sparse-keymap)))
7244 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7245 mouse-drag-region universal-argument org-occur))
7246 cmd)
7247 (while (setq cmd (pop cmds))
7248 (substitute-key-definition cmd cmd map global-map)))
7249 (suppress-keymap map)
7250 (org-defkey map "\C-m" 'org-goto-ret)
7251 (org-defkey map [(return)] 'org-goto-ret)
7252 (org-defkey map [(left)] 'org-goto-left)
7253 (org-defkey map [(right)] 'org-goto-right)
7254 (org-defkey map [(control ?g)] 'org-goto-quit)
7255 (org-defkey map "\C-i" 'org-cycle)
7256 (org-defkey map [(tab)] 'org-cycle)
7257 (org-defkey map [(down)] 'outline-next-visible-heading)
7258 (org-defkey map [(up)] 'outline-previous-visible-heading)
7259 (if org-goto-auto-isearch
7260 (if (fboundp 'define-key-after)
7261 (define-key-after map [t] 'org-goto-local-auto-isearch)
7262 nil)
7263 (org-defkey map "q" 'org-goto-quit)
7264 (org-defkey map "n" 'outline-next-visible-heading)
7265 (org-defkey map "p" 'outline-previous-visible-heading)
7266 (org-defkey map "f" 'outline-forward-same-level)
7267 (org-defkey map "b" 'outline-backward-same-level)
7268 (org-defkey map "u" 'outline-up-heading))
7269 (org-defkey map "/" 'org-occur)
7270 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7271 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7272 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7273 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7274 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7275 map)))
7277 (defconst org-goto-help
7278 "Browse buffer copy, to find location or copy text.%s
7279 RET=jump to location C-g=quit and return to previous location
7280 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7282 (defvar org-goto-start-pos) ; dynamically scoped parameter
7284 (defun org-goto (&optional alternative-interface)
7285 "Look up a different location in the current file, keeping current visibility.
7287 When you want look-up or go to a different location in a
7288 document, the fastest way is often to fold the entire buffer and
7289 then dive into the tree. This method has the disadvantage, that
7290 the previous location will be folded, which may not be what you
7291 want.
7293 This command works around this by showing a copy of the current
7294 buffer in an indirect buffer, in overview mode. You can dive
7295 into the tree in that copy, use org-occur and incremental search
7296 to find a location. When pressing RET or `Q', the command
7297 returns to the original buffer in which the visibility is still
7298 unchanged. After RET it will also jump to the location selected
7299 in the indirect buffer and expose the headline hierarchy above.
7301 With a prefix argument, use the alternative interface: e.g. if
7302 `org-goto-interface' is 'outline use 'outline-path-completion."
7303 (interactive "P")
7304 (org-goto-map)
7305 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7306 (org-refile-use-outline-path t)
7307 (org-refile-target-verify-function nil)
7308 (interface
7309 (if (not alternative-interface)
7310 org-goto-interface
7311 (if (eq org-goto-interface 'outline)
7312 'outline-path-completion
7313 'outline)))
7314 (org-goto-start-pos (point))
7315 (selected-point
7316 (if (eq interface 'outline)
7317 (car (org-get-location (current-buffer) org-goto-help))
7318 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7319 (org-refile-check-position pa)
7320 (nth 3 pa)))))
7321 (if selected-point
7322 (progn
7323 (org-mark-ring-push org-goto-start-pos)
7324 (goto-char selected-point)
7325 (if (or (outline-invisible-p) (org-invisible-p2))
7326 (org-show-context 'org-goto)))
7327 (message "Quit"))))
7329 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7330 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7331 (defvar org-goto-local-auto-isearch-map) ; defined below
7333 (defun org-get-location (buf help)
7334 "Let the user select a location in the Org-mode buffer BUF.
7335 This function uses a recursive edit. It returns the selected position
7336 or nil."
7337 (org-no-popups
7338 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7339 (isearch-hide-immediately nil)
7340 (isearch-search-fun-function
7341 (lambda () 'org-goto-local-search-headings))
7342 (org-goto-selected-point org-goto-exit-command))
7343 (save-excursion
7344 (save-window-excursion
7345 (delete-other-windows)
7346 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7347 (org-pop-to-buffer-same-window
7348 (condition-case nil
7349 (make-indirect-buffer (current-buffer) "*org-goto*")
7350 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7351 (with-output-to-temp-buffer "*Org Help*"
7352 (princ (format help (if org-goto-auto-isearch
7353 " Just type for auto-isearch."
7354 " n/p/f/b/u to navigate, q to quit."))))
7355 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7356 (setq buffer-read-only nil)
7357 (let ((org-startup-truncated t)
7358 (org-startup-folded nil)
7359 (org-startup-align-all-tables nil))
7360 (org-mode)
7361 (org-overview))
7362 (setq buffer-read-only t)
7363 (if (and (boundp 'org-goto-start-pos)
7364 (integer-or-marker-p org-goto-start-pos))
7365 (let ((org-show-hierarchy-above t)
7366 (org-show-siblings t)
7367 (org-show-following-heading t))
7368 (goto-char org-goto-start-pos)
7369 (and (outline-invisible-p) (org-show-context)))
7370 (goto-char (point-min)))
7371 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7372 (message "Select location and press RET")
7373 (use-local-map org-goto-map)
7374 (recursive-edit)))
7375 (kill-buffer "*org-goto*")
7376 (cons org-goto-selected-point org-goto-exit-command))))
7378 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7379 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7380 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7381 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7383 (defun org-goto-local-search-headings (string bound noerror)
7384 "Search and make sure that any matches are in headlines."
7385 (catch 'return
7386 (while (if isearch-forward
7387 (search-forward string bound noerror)
7388 (search-backward string bound noerror))
7389 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7390 (and (member :headline context)
7391 (not (member :tags context))))
7392 (throw 'return (point))))))
7394 (defun org-goto-local-auto-isearch ()
7395 "Start isearch."
7396 (interactive)
7397 (goto-char (point-min))
7398 (let ((keys (this-command-keys)))
7399 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7400 (isearch-mode t)
7401 (isearch-process-search-char (string-to-char keys)))))
7403 (defun org-goto-ret (&optional arg)
7404 "Finish `org-goto' by going to the new location."
7405 (interactive "P")
7406 (setq org-goto-selected-point (point)
7407 org-goto-exit-command 'return)
7408 (throw 'exit nil))
7410 (defun org-goto-left ()
7411 "Finish `org-goto' by going to the new location."
7412 (interactive)
7413 (if (org-at-heading-p)
7414 (progn
7415 (beginning-of-line 1)
7416 (setq org-goto-selected-point (point)
7417 org-goto-exit-command 'left)
7418 (throw 'exit nil))
7419 (user-error "Not on a heading")))
7421 (defun org-goto-right ()
7422 "Finish `org-goto' by going to the new location."
7423 (interactive)
7424 (if (org-at-heading-p)
7425 (progn
7426 (setq org-goto-selected-point (point)
7427 org-goto-exit-command 'right)
7428 (throw 'exit nil))
7429 (user-error "Not on a heading")))
7431 (defun org-goto-quit ()
7432 "Finish `org-goto' without cursor motion."
7433 (interactive)
7434 (setq org-goto-selected-point nil)
7435 (setq org-goto-exit-command 'quit)
7436 (throw 'exit nil))
7438 ;;; Indirect buffer display of subtrees
7440 (defvar org-indirect-dedicated-frame nil
7441 "This is the frame being used for indirect tree display.")
7442 (defvar org-last-indirect-buffer nil)
7444 (defun org-tree-to-indirect-buffer (&optional arg)
7445 "Create indirect buffer and narrow it to current subtree.
7446 With a numerical prefix ARG, go up to this level and then take that tree.
7447 If ARG is negative, go up that many levels.
7449 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7450 indirect buffer previously made with this command, to avoid proliferation of
7451 indirect buffers. However, when you call the command with a \
7452 \\[universal-argument] prefix, or
7453 when `org-indirect-buffer-display' is `new-frame', the last buffer
7454 is kept so that you can work with several indirect buffers at the same time.
7455 If `org-indirect-buffer-display' is `dedicated-frame', the \
7456 \\[universal-argument] prefix also
7457 requests that a new frame be made for the new buffer, so that the dedicated
7458 frame is not changed."
7459 (interactive "P")
7460 (let ((cbuf (current-buffer))
7461 (cwin (selected-window))
7462 (pos (point))
7463 beg end level heading ibuf)
7464 (save-excursion
7465 (org-back-to-heading t)
7466 (when (numberp arg)
7467 (setq level (org-outline-level))
7468 (if (< arg 0) (setq arg (+ level arg)))
7469 (while (> (setq level (org-outline-level)) arg)
7470 (org-up-heading-safe)))
7471 (setq beg (point)
7472 heading (org-get-heading))
7473 (org-end-of-subtree t t)
7474 (if (org-at-heading-p) (backward-char 1))
7475 (setq end (point)))
7476 (if (and (buffer-live-p org-last-indirect-buffer)
7477 (not (eq org-indirect-buffer-display 'new-frame))
7478 (not arg))
7479 (kill-buffer org-last-indirect-buffer))
7480 (setq ibuf (org-get-indirect-buffer cbuf)
7481 org-last-indirect-buffer ibuf)
7482 (cond
7483 ((or (eq org-indirect-buffer-display 'new-frame)
7484 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7485 (select-frame (make-frame))
7486 (delete-other-windows)
7487 (org-pop-to-buffer-same-window ibuf)
7488 (org-set-frame-title heading))
7489 ((eq org-indirect-buffer-display 'dedicated-frame)
7490 (raise-frame
7491 (select-frame (or (and org-indirect-dedicated-frame
7492 (frame-live-p org-indirect-dedicated-frame)
7493 org-indirect-dedicated-frame)
7494 (setq org-indirect-dedicated-frame (make-frame)))))
7495 (delete-other-windows)
7496 (org-pop-to-buffer-same-window ibuf)
7497 (org-set-frame-title (concat "Indirect: " heading)))
7498 ((eq org-indirect-buffer-display 'current-window)
7499 (org-pop-to-buffer-same-window ibuf))
7500 ((eq org-indirect-buffer-display 'other-window)
7501 (pop-to-buffer ibuf))
7502 (t (error "Invalid value")))
7503 (if (featurep 'xemacs)
7504 (save-excursion (org-mode) (turn-on-font-lock)))
7505 (narrow-to-region beg end)
7506 (show-all)
7507 (goto-char pos)
7508 (run-hook-with-args 'org-cycle-hook 'all)
7509 (and (window-live-p cwin) (select-window cwin))))
7511 (defun org-get-indirect-buffer (&optional buffer)
7512 (setq buffer (or buffer (current-buffer)))
7513 (let ((n 1) (base (buffer-name buffer)) bname)
7514 (while (buffer-live-p
7515 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7516 (setq n (1+ n)))
7517 (condition-case nil
7518 (make-indirect-buffer buffer bname 'clone)
7519 (error (make-indirect-buffer buffer bname)))))
7521 (defun org-set-frame-title (title)
7522 "Set the title of the current frame to the string TITLE."
7523 ;; FIXME: how to name a single frame in XEmacs???
7524 (unless (featurep 'xemacs)
7525 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7527 ;;;; Structure editing
7529 ;;; Inserting headlines
7531 (defun org-previous-line-empty-p (&optional next)
7532 "Is the previous line a blank line?
7533 When NEXT is non-nil, check the next line instead."
7534 (save-excursion
7535 (and (not (bobp))
7536 (or (beginning-of-line (if next 2 0)) t)
7537 (save-match-data
7538 (looking-at "[ \t]*$")))))
7540 (defun org-insert-heading (&optional arg invisible-ok)
7541 "Insert a new heading or item with same depth at point.
7542 If point is in a plain list and ARG is nil, create a new list item.
7543 With one universal prefix argument, insert a heading even in lists.
7544 With two universal prefix arguments, insert the heading at the end
7545 of the parent subtree.
7547 If point is at the beginning of a headline, insert a sibling before
7548 the current headline. If point is not at the beginning, split the line
7549 and create a new headline with the text in the current line after point
7550 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7552 If point is at the beginning of a normal line, turn this line into
7553 a heading.
7555 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7556 This is important for non-interactive uses of the command."
7557 (interactive "P")
7558 (if (org-called-interactively-p 'any) (org-reveal))
7559 (let ((itemp (org-in-item-p))
7560 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7561 (respect-content (or org-insert-heading-respect-content
7562 (equal arg '(16))))
7563 (initial-content "")
7564 (adjust-empty-lines t))
7566 (cond
7568 ((or (= (buffer-size) 0)
7569 (and (not (save-excursion
7570 (and (ignore-errors (org-back-to-heading invisible-ok))
7571 (org-at-heading-p))))
7572 (or arg (not itemp))))
7573 ;; At beginning of buffer or so hight up that only a heading makes sense.
7574 (insert
7575 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7576 (if (org-in-src-block-p) ",* " "* "))
7577 (run-hooks 'org-insert-heading-hook))
7579 ((and itemp (not (equal arg '(4))))
7580 ;; Insert an item
7581 (org-insert-item))
7584 ;; Insert a heading
7585 (save-restriction
7586 (widen)
7587 (let* ((level nil)
7588 (on-heading (org-at-heading-p))
7589 (empty-line-p (if on-heading
7590 (org-previous-line-empty-p)
7591 ;; We will decide later
7592 nil))
7593 ;; Get a level string to fall back on
7594 (fix-level
7595 (save-excursion
7596 (org-back-to-heading t)
7597 (if (org-previous-line-empty-p) (setq empty-line-p t))
7598 (looking-at org-outline-regexp)
7599 (make-string (1- (length (match-string 0))) ?*)))
7600 (stars
7601 (save-excursion
7602 (condition-case nil
7603 (progn
7604 (org-back-to-heading invisible-ok)
7605 (when (and (not on-heading)
7606 (featurep 'org-inlinetask)
7607 (integerp org-inlinetask-min-level)
7608 (>= (length (match-string 0))
7609 org-inlinetask-min-level))
7610 ;; Find a heading level before the inline task
7611 (while (and (setq level (org-up-heading-safe))
7612 (>= level org-inlinetask-min-level)))
7613 (if (org-at-heading-p)
7614 (org-back-to-heading invisible-ok)
7615 (error "This should not happen")))
7616 (unless (and (save-excursion
7617 (save-match-data
7618 (org-backward-heading-same-level
7619 1 invisible-ok))
7620 (= (point) (match-beginning 0)))
7621 (not (org-previous-line-empty-p t)))
7622 (setq empty-line-p (or empty-line-p
7623 (org-previous-line-empty-p))))
7624 (match-string 0))
7625 (error (or fix-level "* ")))))
7626 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7627 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7628 pos hide-previous previous-pos)
7630 ;; If we insert after content, move there and clean up whitespace
7631 (when respect-content
7632 (org-end-of-subtree nil t)
7633 (when (looking-at "^\\*")
7634 (backward-char 1)
7635 (insert "\n")))
7637 ;; If we are splitting, grab the text that should be moved to the new headline
7638 (when may-split
7639 (if (org-on-heading-p)
7640 ;; This is a heading, we split intelligently (keeping tags)
7641 (let ((pos (point)))
7642 (goto-char (point-at-bol))
7643 (unless (looking-at org-complex-heading-regexp)
7644 (error "This should not happen"))
7645 (when (and (match-beginning 4)
7646 (> pos (match-beginning 4))
7647 (< pos (match-end 4)))
7648 (setq initial-content (buffer-substring pos (match-end 4)))
7649 (goto-char pos)
7650 (delete-region (point) (match-end 4))
7651 (if (looking-at "[ \t]*$")
7652 (replace-match "")
7653 (insert (make-string (length initial-content) ?\ )))
7654 (setq initial-content (org-trim initial-content)))
7655 (goto-char pos))
7656 ;; a normal line
7657 (unless (bolp)
7658 (setq initial-content (buffer-substring (point) (point-at-eol)))
7659 (delete-region (point) (point-at-eol))
7660 (setq initial-content (org-trim initial-content)))))
7662 ;; If we are at the beginning of the line, insert before it. Else after
7663 (cond
7664 ((and (bolp) (looking-at "[ \t]*$")))
7665 ((and (bolp) (not (looking-at "[ \t]*$")))
7666 (open-line 1))
7668 (goto-char (point-at-eol))
7669 (insert "\n")))
7671 ;; Insert the new heading
7672 (insert stars)
7673 (just-one-space)
7674 (insert initial-content)
7675 (when adjust-empty-lines
7676 (if (or (not blank)
7677 (and blank (not (org-previous-line-empty-p))))
7678 (org-N-empty-lines-before-current (if blank 1 0))))
7679 (run-hooks 'org-insert-heading-hook)))))))
7681 (defun org-N-empty-lines-before-current (N)
7682 "Make the number of empty lines before current exactly N.
7683 So this will delete or add empty lines."
7684 (save-excursion
7685 (goto-char (point-at-bol))
7686 (if (looking-back "\\s-+" nil 'greedy)
7687 (replace-match ""))
7688 (or (bobp) (insert "\n"))
7689 (while (> N 0)
7690 (insert "\n")
7691 (setq N (1- N)))))
7693 (defun org-get-heading (&optional no-tags no-todo)
7694 "Return the heading of the current entry, without the stars.
7695 When NO-TAGS is non-nil, don't include tags.
7696 When NO-TODO is non-nil, don't include TODO keywords."
7697 (save-excursion
7698 (org-back-to-heading t)
7699 (cond
7700 ((and no-tags no-todo)
7701 (looking-at org-complex-heading-regexp)
7702 (match-string 4))
7703 (no-tags
7704 (looking-at (concat org-outline-regexp
7705 "\\(.*?\\)"
7706 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7707 (match-string 1))
7708 (no-todo
7709 (looking-at org-todo-line-regexp)
7710 (match-string 3))
7711 (t (looking-at org-heading-regexp)
7712 (match-string 2)))))
7714 (defvar orgstruct-mode) ; defined below
7716 (defun org-heading-components ()
7717 "Return the components of the current heading.
7718 This is a list with the following elements:
7719 - the level as an integer
7720 - the reduced level, different if `org-odd-levels-only' is set.
7721 - the TODO keyword, or nil
7722 - the priority character, like ?A, or nil if no priority is given
7723 - the headline text itself, or the tags string if no headline text
7724 - the tags string, or nil."
7725 (save-excursion
7726 (org-back-to-heading t)
7727 (if (let (case-fold-search)
7728 (looking-at
7729 (if orgstruct-mode
7730 org-heading-regexp
7731 org-complex-heading-regexp)))
7732 (if orgstruct-mode
7733 (list (length (match-string 1))
7734 (org-reduced-level (length (match-string 1)))
7737 (match-string 2)
7738 nil)
7739 (list (length (match-string 1))
7740 (org-reduced-level (length (match-string 1)))
7741 (org-match-string-no-properties 2)
7742 (and (match-end 3) (aref (match-string 3) 2))
7743 (org-match-string-no-properties 4)
7744 (org-match-string-no-properties 5))))))
7746 (defun org-get-entry ()
7747 "Get the entry text, after heading, entire subtree."
7748 (save-excursion
7749 (org-back-to-heading t)
7750 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7752 (defun org-insert-heading-after-current ()
7753 "Insert a new heading with same level as current, after current subtree."
7754 (interactive)
7755 (org-back-to-heading)
7756 (org-insert-heading)
7757 (org-move-subtree-down)
7758 (end-of-line 1))
7760 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7761 "Insert heading with `org-insert-heading-respect-content' set to t."
7762 (interactive "P")
7763 (let ((org-insert-heading-respect-content t))
7764 (org-insert-heading '(4) invisible-ok)))
7766 (defun org-insert-todo-heading-respect-content (&optional force-state)
7767 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7768 (interactive "P")
7769 (let ((org-insert-heading-respect-content t))
7770 (org-insert-todo-heading force-state t)))
7772 (defun org-insert-todo-heading (arg &optional force-heading)
7773 "Insert a new heading with the same level and TODO state as current heading.
7774 If the heading has no TODO state, or if the state is DONE, use the first
7775 state (TODO by default). Also one prefix arg, force first state. With two
7776 prefix args, force inserting at the end of the parent subtree."
7777 (interactive "P")
7778 (when (or force-heading (not (org-insert-item 'checkbox)))
7779 (org-insert-heading (or (and (equal arg '(16)) '(16))
7780 force-heading))
7781 (save-excursion
7782 (org-back-to-heading)
7783 (outline-previous-heading)
7784 (looking-at org-todo-line-regexp))
7785 (let*
7786 ((new-mark-x
7787 (if (or arg
7788 (not (match-beginning 2))
7789 (member (match-string 2) org-done-keywords))
7790 (car org-todo-keywords-1)
7791 (match-string 2)))
7792 (new-mark
7794 (run-hook-with-args-until-success
7795 'org-todo-get-default-hook new-mark-x nil)
7796 new-mark-x)))
7797 (beginning-of-line 1)
7798 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7799 (if org-treat-insert-todo-heading-as-state-change
7800 (org-todo new-mark)
7801 (insert new-mark " "))))
7802 (when org-provide-todo-statistics
7803 (org-update-parent-todo-statistics))))
7805 (defun org-insert-subheading (arg)
7806 "Insert a new subheading and demote it.
7807 Works for outline headings and for plain lists alike."
7808 (interactive "P")
7809 (org-insert-heading arg)
7810 (cond
7811 ((org-at-heading-p) (org-do-demote))
7812 ((org-at-item-p) (org-indent-item))))
7814 (defun org-insert-todo-subheading (arg)
7815 "Insert a new subheading with TODO keyword or checkbox and demote it.
7816 Works for outline headings and for plain lists alike."
7817 (interactive "P")
7818 (org-insert-todo-heading arg)
7819 (cond
7820 ((org-at-heading-p) (org-do-demote))
7821 ((org-at-item-p) (org-indent-item))))
7823 ;;; Promotion and Demotion
7825 (defvar org-after-demote-entry-hook nil
7826 "Hook run after an entry has been demoted.
7827 The cursor will be at the beginning of the entry.
7828 When a subtree is being demoted, the hook will be called for each node.")
7830 (defvar org-after-promote-entry-hook nil
7831 "Hook run after an entry has been promoted.
7832 The cursor will be at the beginning of the entry.
7833 When a subtree is being promoted, the hook will be called for each node.")
7835 (defun org-promote-subtree ()
7836 "Promote the entire subtree.
7837 See also `org-promote'."
7838 (interactive)
7839 (save-excursion
7840 (org-with-limited-levels (org-map-tree 'org-promote)))
7841 (org-fix-position-after-promote))
7843 (defun org-demote-subtree ()
7844 "Demote the entire subtree. See `org-demote'.
7845 See also `org-promote'."
7846 (interactive)
7847 (save-excursion
7848 (org-with-limited-levels (org-map-tree 'org-demote)))
7849 (org-fix-position-after-promote))
7852 (defun org-do-promote ()
7853 "Promote the current heading higher up the tree.
7854 If the region is active in `transient-mark-mode', promote all headings
7855 in the region."
7856 (interactive)
7857 (save-excursion
7858 (if (org-region-active-p)
7859 (org-map-region 'org-promote (region-beginning) (region-end))
7860 (org-promote)))
7861 (org-fix-position-after-promote))
7863 (defun org-do-demote ()
7864 "Demote the current heading lower down the tree.
7865 If the region is active in `transient-mark-mode', demote all headings
7866 in the region."
7867 (interactive)
7868 (save-excursion
7869 (if (org-region-active-p)
7870 (org-map-region 'org-demote (region-beginning) (region-end))
7871 (org-demote)))
7872 (org-fix-position-after-promote))
7874 (defun org-fix-position-after-promote ()
7875 "Make sure that after pro/demotion cursor position is right."
7876 (let ((pos (point)))
7877 (when (save-excursion
7878 (beginning-of-line 1)
7879 (looking-at org-todo-line-regexp)
7880 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7881 (cond ((eobp) (insert " "))
7882 ((eolp) (insert " "))
7883 ((equal (char-after) ?\ ) (forward-char 1))))))
7885 (defun org-current-level ()
7886 "Return the level of the current entry, or nil if before the first headline.
7887 The level is the number of stars at the beginning of the headline."
7888 (save-excursion
7889 (org-with-limited-levels
7890 (if (ignore-errors (org-back-to-heading t))
7891 (funcall outline-level)))))
7893 (defun org-get-previous-line-level ()
7894 "Return the outline depth of the last headline before the current line.
7895 Returns 0 for the first headline in the buffer, and nil if before the
7896 first headline."
7897 (let ((current-level (org-current-level))
7898 (prev-level (when (> (line-number-at-pos) 1)
7899 (save-excursion
7900 (beginning-of-line 0)
7901 (org-current-level)))))
7902 (cond ((null current-level) nil) ; Before first headline
7903 ((null prev-level) 0) ; At first headline
7904 (prev-level))))
7906 (defun org-reduced-level (l)
7907 "Compute the effective level of a heading.
7908 This takes into account the setting of `org-odd-levels-only'."
7909 (cond
7910 ((zerop l) 0)
7911 (org-odd-levels-only (1+ (floor (/ l 2))))
7912 (t l)))
7914 (defun org-level-increment ()
7915 "Return the number of stars that will be added or removed at a
7916 time to headlines when structure editing, based on the value of
7917 `org-odd-levels-only'."
7918 (if org-odd-levels-only 2 1))
7920 (defun org-get-valid-level (level &optional change)
7921 "Rectify a level change under the influence of `org-odd-levels-only'
7922 LEVEL is a current level, CHANGE is by how much the level should be
7923 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7924 even level numbers will become the next higher odd number."
7925 (if org-odd-levels-only
7926 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7927 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7928 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7929 (max 1 (+ level (or change 0)))))
7931 (if (boundp 'define-obsolete-function-alias)
7932 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7933 (define-obsolete-function-alias 'org-get-legal-level
7934 'org-get-valid-level)
7935 (define-obsolete-function-alias 'org-get-legal-level
7936 'org-get-valid-level "23.1")))
7938 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7939 ;; ̀org-with-limited-levels'
7940 (defun org-promote ()
7941 "Promote the current heading higher up the tree.
7942 If the region is active in `transient-mark-mode', promote all headings
7943 in the region."
7944 (org-back-to-heading t)
7945 (let* ((level (save-match-data (funcall outline-level)))
7946 (after-change-functions (remove 'flyspell-after-change-function
7947 after-change-functions))
7948 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7949 (diff (abs (- level (length up-head) -1))))
7950 (cond ((and (= level 1) org-called-with-limited-levels
7951 org-allow-promoting-top-level-subtree)
7952 (replace-match "# " nil t))
7953 ((= level 1)
7954 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7955 (t (replace-match up-head nil t)))
7956 ;; Fixup tag positioning
7957 (unless (= level 1)
7958 (and org-auto-align-tags (org-set-tags nil t))
7959 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7960 (run-hooks 'org-after-promote-entry-hook)))
7962 (defun org-demote ()
7963 "Demote the current heading lower down the tree.
7964 If the region is active in `transient-mark-mode', demote all headings
7965 in the region."
7966 (org-back-to-heading t)
7967 (let* ((level (save-match-data (funcall outline-level)))
7968 (after-change-functions (remove 'flyspell-after-change-function
7969 after-change-functions))
7970 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7971 (diff (abs (- level (length down-head) -1))))
7972 (replace-match down-head nil t)
7973 ;; Fixup tag positioning
7974 (and org-auto-align-tags (org-set-tags nil t))
7975 (if org-adapt-indentation (org-fixup-indentation diff))
7976 (run-hooks 'org-after-demote-entry-hook)))
7978 (defun org-cycle-level ()
7979 "Cycle the level of an empty headline through possible states.
7980 This goes first to child, then to parent, level, then up the hierarchy.
7981 After top level, it switches back to sibling level."
7982 (interactive)
7983 (let ((org-adapt-indentation nil))
7984 (when (org-point-at-end-of-empty-headline)
7985 (setq this-command 'org-cycle-level) ; Only needed for caching
7986 (let ((cur-level (org-current-level))
7987 (prev-level (org-get-previous-line-level)))
7988 (cond
7989 ;; If first headline in file, promote to top-level.
7990 ((= prev-level 0)
7991 (loop repeat (/ (- cur-level 1) (org-level-increment))
7992 do (org-do-promote)))
7993 ;; If same level as prev, demote one.
7994 ((= prev-level cur-level)
7995 (org-do-demote))
7996 ;; If parent is top-level, promote to top level if not already.
7997 ((= prev-level 1)
7998 (loop repeat (/ (- cur-level 1) (org-level-increment))
7999 do (org-do-promote)))
8000 ;; If top-level, return to prev-level.
8001 ((= cur-level 1)
8002 (loop repeat (/ (- prev-level 1) (org-level-increment))
8003 do (org-do-demote)))
8004 ;; If less than prev-level, promote one.
8005 ((< cur-level prev-level)
8006 (org-do-promote))
8007 ;; If deeper than prev-level, promote until higher than
8008 ;; prev-level.
8009 ((> cur-level prev-level)
8010 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8011 do (org-do-promote))))
8012 t))))
8014 (defun org-map-tree (fun)
8015 "Call FUN for every heading underneath the current one."
8016 (org-back-to-heading)
8017 (let ((level (funcall outline-level)))
8018 (save-excursion
8019 (funcall fun)
8020 (while (and (progn
8021 (outline-next-heading)
8022 (> (funcall outline-level) level))
8023 (not (eobp)))
8024 (funcall fun)))))
8026 (defun org-map-region (fun beg end)
8027 "Call FUN for every heading between BEG and END."
8028 (let ((org-ignore-region t))
8029 (save-excursion
8030 (setq end (copy-marker end))
8031 (goto-char beg)
8032 (if (and (re-search-forward org-outline-regexp-bol nil t)
8033 (< (point) end))
8034 (funcall fun))
8035 (while (and (progn
8036 (outline-next-heading)
8037 (< (point) end))
8038 (not (eobp)))
8039 (funcall fun)))))
8041 (defvar org-property-end-re) ; silence byte-compiler
8042 (defun org-fixup-indentation (diff)
8043 "Change the indentation in the current entry by DIFF.
8044 However, if any line in the current entry has no indentation, or if it
8045 would end up with no indentation after the change, nothing at all is done."
8046 (save-excursion
8047 (let ((end (save-excursion (outline-next-heading)
8048 (point-marker)))
8049 (prohibit (if (> diff 0)
8050 "^\\S-"
8051 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8052 col)
8053 (unless (save-excursion (end-of-line 1)
8054 (re-search-forward prohibit end t))
8055 (while (and (< (point) end)
8056 (re-search-forward "^[ \t]+" end t))
8057 (goto-char (match-end 0))
8058 (setq col (current-column))
8059 (if (< diff 0) (replace-match ""))
8060 (org-indent-to-column (+ diff col))))
8061 (move-marker end nil))))
8063 (defun org-convert-to-odd-levels ()
8064 "Convert an org-mode file with all levels allowed to one with odd levels.
8065 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8066 level 5 etc."
8067 (interactive)
8068 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8069 (let ((outline-level 'org-outline-level)
8070 (org-odd-levels-only nil) n)
8071 (save-excursion
8072 (goto-char (point-min))
8073 (while (re-search-forward "^\\*\\*+ " nil t)
8074 (setq n (- (length (match-string 0)) 2))
8075 (while (>= (setq n (1- n)) 0)
8076 (org-demote))
8077 (end-of-line 1))))))
8079 (defun org-convert-to-oddeven-levels ()
8080 "Convert an org-mode file with only odd levels to one with odd/even levels.
8081 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8082 file contains a section with an even level, conversion would
8083 destroy the structure of the file. An error is signaled in this
8084 case."
8085 (interactive)
8086 (goto-char (point-min))
8087 ;; First check if there are no even levels
8088 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8089 (org-show-context t)
8090 (error "Not all levels are odd in this file. Conversion not possible"))
8091 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8092 (let ((outline-regexp org-outline-regexp)
8093 (outline-level 'org-outline-level)
8094 (org-odd-levels-only nil) n)
8095 (save-excursion
8096 (goto-char (point-min))
8097 (while (re-search-forward "^\\*\\*+ " nil t)
8098 (setq n (/ (1- (length (match-string 0))) 2))
8099 (while (>= (setq n (1- n)) 0)
8100 (org-promote))
8101 (end-of-line 1))))))
8103 (defun org-tr-level (n)
8104 "Make N odd if required."
8105 (if org-odd-levels-only (1+ (/ n 2)) n))
8107 ;;; Vertical tree motion, cutting and pasting of subtrees
8109 (defun org-move-subtree-up (&optional arg)
8110 "Move the current subtree up past ARG headlines of the same level."
8111 (interactive "p")
8112 (org-move-subtree-down (- (prefix-numeric-value arg))))
8114 (defun org-move-subtree-down (&optional arg)
8115 "Move the current subtree down past ARG headlines of the same level."
8116 (interactive "p")
8117 (setq arg (prefix-numeric-value arg))
8118 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8119 'org-get-last-sibling))
8120 (ins-point (make-marker))
8121 (cnt (abs arg))
8122 (col (current-column))
8123 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8124 ;; Select the tree
8125 (org-back-to-heading)
8126 (setq beg0 (point))
8127 (save-excursion
8128 (setq ne-beg (org-back-over-empty-lines))
8129 (setq beg (point)))
8130 (save-match-data
8131 (save-excursion (outline-end-of-heading)
8132 (setq folded (outline-invisible-p)))
8133 (outline-end-of-subtree))
8134 (outline-next-heading)
8135 (setq ne-end (org-back-over-empty-lines))
8136 (setq end (point))
8137 (goto-char beg0)
8138 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8139 ;; include less whitespace
8140 (save-excursion
8141 (goto-char beg)
8142 (forward-line (- ne-beg ne-end))
8143 (setq beg (point))))
8144 ;; Find insertion point, with error handling
8145 (while (> cnt 0)
8146 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8147 (progn (goto-char beg0)
8148 (user-error "Cannot move past superior level or buffer limit")))
8149 (setq cnt (1- cnt)))
8150 (if (> arg 0)
8151 ;; Moving forward - still need to move over subtree
8152 (progn (org-end-of-subtree t t)
8153 (save-excursion
8154 (org-back-over-empty-lines)
8155 (or (bolp) (newline)))))
8156 (setq ne-ins (org-back-over-empty-lines))
8157 (move-marker ins-point (point))
8158 (setq txt (buffer-substring beg end))
8159 (org-save-markers-in-region beg end)
8160 (delete-region beg end)
8161 (org-remove-empty-overlays-at beg)
8162 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8163 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8164 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8165 (let ((bbb (point)))
8166 (insert-before-markers txt)
8167 (org-reinstall-markers-in-region bbb)
8168 (move-marker ins-point bbb))
8169 (or (bolp) (insert "\n"))
8170 (setq ins-end (point))
8171 (goto-char ins-point)
8172 (org-skip-whitespace)
8173 (when (and (< arg 0)
8174 (org-first-sibling-p)
8175 (> ne-ins ne-beg))
8176 ;; Move whitespace back to beginning
8177 (save-excursion
8178 (goto-char ins-end)
8179 (let ((kill-whole-line t))
8180 (kill-line (- ne-ins ne-beg)) (point)))
8181 (insert (make-string (- ne-ins ne-beg) ?\n)))
8182 (move-marker ins-point nil)
8183 (if folded
8184 (hide-subtree)
8185 (org-show-entry)
8186 (show-children)
8187 (org-cycle-hide-drawers 'children))
8188 (org-clean-visibility-after-subtree-move)
8189 ;; move back to the initial column we were at
8190 (move-to-column col)))
8192 (defvar org-subtree-clip ""
8193 "Clipboard for cut and paste of subtrees.
8194 This is actually only a copy of the kill, because we use the normal kill
8195 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8197 (defvar org-subtree-clip-folded nil
8198 "Was the last copied subtree folded?
8199 This is used to fold the tree back after pasting.")
8201 (defun org-cut-subtree (&optional n)
8202 "Cut the current subtree into the clipboard.
8203 With prefix arg N, cut this many sequential subtrees.
8204 This is a short-hand for marking the subtree and then cutting it."
8205 (interactive "p")
8206 (org-copy-subtree n 'cut))
8208 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8209 "Copy the current subtree it in the clipboard.
8210 With prefix arg N, copy this many sequential subtrees.
8211 This is a short-hand for marking the subtree and then copying it.
8212 If CUT is non-nil, actually cut the subtree.
8213 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8214 of some markers in the region, even if CUT is non-nil. This is
8215 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8216 (interactive "p")
8217 (let (beg end folded (beg0 (point)))
8218 (if (org-called-interactively-p 'any)
8219 (org-back-to-heading nil) ; take what looks like a subtree
8220 (org-back-to-heading t)) ; take what is really there
8221 (setq beg (point))
8222 (skip-chars-forward " \t\r\n")
8223 (save-match-data
8224 (if nosubtrees
8225 (outline-next-heading)
8226 (save-excursion (outline-end-of-heading)
8227 (setq folded (outline-invisible-p)))
8228 (condition-case nil
8229 (org-forward-heading-same-level (1- n) t)
8230 (error nil))
8231 (org-end-of-subtree t t)))
8232 (setq end (point))
8233 (goto-char beg0)
8234 (when (> end beg)
8235 (setq org-subtree-clip-folded folded)
8236 (when (or cut force-store-markers)
8237 (org-save-markers-in-region beg end))
8238 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8239 (setq org-subtree-clip (current-kill 0))
8240 (message "%s: Subtree(s) with %d characters"
8241 (if cut "Cut" "Copied")
8242 (length org-subtree-clip)))))
8244 (defun org-paste-subtree (&optional level tree for-yank)
8245 "Paste the clipboard as a subtree, with modification of headline level.
8246 The entire subtree is promoted or demoted in order to match a new headline
8247 level.
8249 If the cursor is at the beginning of a headline, the same level as
8250 that headline is used to paste the tree.
8252 If not, the new level is derived from the *visible* headings
8253 before and after the insertion point, and taken to be the inferior headline
8254 level of the two. So if the previous visible heading is level 3 and the
8255 next is level 4 (or vice versa), level 4 will be used for insertion.
8256 This makes sure that the subtree remains an independent subtree and does
8257 not swallow low level entries.
8259 You can also force a different level, either by using a numeric prefix
8260 argument, or by inserting the heading marker by hand. For example, if the
8261 cursor is after \"*****\", then the tree will be shifted to level 5.
8263 If optional TREE is given, use this text instead of the kill ring.
8265 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8266 move back over whitespace before inserting, and move point to the end of
8267 the inserted text when done."
8268 (interactive "P")
8269 (setq tree (or tree (and kill-ring (current-kill 0))))
8270 (unless (org-kill-is-subtree-p tree)
8271 (user-error "%s"
8272 (substitute-command-keys
8273 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8274 (org-with-limited-levels
8275 (let* ((visp (not (outline-invisible-p)))
8276 (txt tree)
8277 (^re_ "\\(\\*+\\)[ \t]*")
8278 (old-level (if (string-match org-outline-regexp-bol txt)
8279 (- (match-end 0) (match-beginning 0) 1)
8280 -1))
8281 (force-level (cond (level (prefix-numeric-value level))
8282 ((and (looking-at "[ \t]*$")
8283 (string-match
8284 "^\\*+$" (buffer-substring
8285 (point-at-bol) (point))))
8286 (- (match-end 1) (match-beginning 1)))
8287 ((and (bolp)
8288 (looking-at org-outline-regexp))
8289 (- (match-end 0) (point) 1))))
8290 (previous-level (save-excursion
8291 (condition-case nil
8292 (progn
8293 (outline-previous-visible-heading 1)
8294 (if (looking-at ^re_)
8295 (- (match-end 0) (match-beginning 0) 1)
8297 (error 1))))
8298 (next-level (save-excursion
8299 (condition-case nil
8300 (progn
8301 (or (looking-at org-outline-regexp)
8302 (outline-next-visible-heading 1))
8303 (if (looking-at ^re_)
8304 (- (match-end 0) (match-beginning 0) 1)
8306 (error 1))))
8307 (new-level (or force-level (max previous-level next-level)))
8308 (shift (if (or (= old-level -1)
8309 (= new-level -1)
8310 (= old-level new-level))
8312 (- new-level old-level)))
8313 (delta (if (> shift 0) -1 1))
8314 (func (if (> shift 0) 'org-demote 'org-promote))
8315 (org-odd-levels-only nil)
8316 beg end newend)
8317 ;; Remove the forced level indicator
8318 (if force-level
8319 (delete-region (point-at-bol) (point)))
8320 ;; Paste
8321 (beginning-of-line (if (bolp) 1 2))
8322 (setq beg (point))
8323 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8324 (insert-before-markers txt)
8325 (unless (string-match "\n\\'" txt) (insert "\n"))
8326 (setq newend (point))
8327 (org-reinstall-markers-in-region beg)
8328 (setq end (point))
8329 (goto-char beg)
8330 (skip-chars-forward " \t\n\r")
8331 (setq beg (point))
8332 (if (and (outline-invisible-p) visp)
8333 (save-excursion (outline-show-heading)))
8334 ;; Shift if necessary
8335 (unless (= shift 0)
8336 (save-restriction
8337 (narrow-to-region beg end)
8338 (while (not (= shift 0))
8339 (org-map-region func (point-min) (point-max))
8340 (setq shift (+ delta shift)))
8341 (goto-char (point-min))
8342 (setq newend (point-max))))
8343 (when (or (org-called-interactively-p 'interactive) for-yank)
8344 (message "Clipboard pasted as level %d subtree" new-level))
8345 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8346 kill-ring
8347 (eq org-subtree-clip (current-kill 0))
8348 org-subtree-clip-folded)
8349 ;; The tree was folded before it was killed/copied
8350 (hide-subtree))
8351 (and for-yank (goto-char newend)))))
8353 (defun org-kill-is-subtree-p (&optional txt)
8354 "Check if the current kill is an outline subtree, or a set of trees.
8355 Returns nil if kill does not start with a headline, or if the first
8356 headline level is not the largest headline level in the tree.
8357 So this will actually accept several entries of equal levels as well,
8358 which is OK for `org-paste-subtree'.
8359 If optional TXT is given, check this string instead of the current kill."
8360 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8361 (re (org-get-limited-outline-regexp))
8362 (^re (concat "^" re))
8363 (start-level (and kill
8364 (string-match
8365 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8366 kill)
8367 (- (match-end 2) (match-beginning 2) 1)))
8368 (start (1+ (or (match-beginning 2) -1))))
8369 (if (not start-level)
8370 (progn
8371 nil) ;; does not even start with a heading
8372 (catch 'exit
8373 (while (setq start (string-match ^re kill (1+ start)))
8374 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8375 (throw 'exit nil)))
8376 t))))
8378 (defvar org-markers-to-move nil
8379 "Markers that should be moved with a cut-and-paste operation.
8380 Those markers are stored together with their positions relative to
8381 the start of the region.")
8383 (defun org-save-markers-in-region (beg end)
8384 "Check markers in region.
8385 If these markers are between BEG and END, record their position relative
8386 to BEG, so that after moving the block of text, we can put the markers back
8387 into place.
8388 This function gets called just before an entry or tree gets cut from the
8389 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8390 called immediately, to move the markers with the entries."
8391 (setq org-markers-to-move nil)
8392 (when (featurep 'org-clock)
8393 (org-clock-save-markers-for-cut-and-paste beg end))
8394 (when (featurep 'org-agenda)
8395 (org-agenda-save-markers-for-cut-and-paste beg end)))
8397 (defun org-check-and-save-marker (marker beg end)
8398 "Check if MARKER is between BEG and END.
8399 If yes, remember the marker and the distance to BEG."
8400 (when (and (marker-buffer marker)
8401 (equal (marker-buffer marker) (current-buffer)))
8402 (if (and (>= marker beg) (< marker end))
8403 (push (cons marker (- marker beg)) org-markers-to-move))))
8405 (defun org-reinstall-markers-in-region (beg)
8406 "Move all remembered markers to their position relative to BEG."
8407 (mapc (lambda (x)
8408 (move-marker (car x) (+ beg (cdr x))))
8409 org-markers-to-move)
8410 (setq org-markers-to-move nil))
8412 (defun org-narrow-to-subtree ()
8413 "Narrow buffer to the current subtree."
8414 (interactive)
8415 (save-excursion
8416 (save-match-data
8417 (org-with-limited-levels
8418 (narrow-to-region
8419 (progn (org-back-to-heading t) (point))
8420 (progn (org-end-of-subtree t t)
8421 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8422 (point)))))))
8424 (defun org-narrow-to-block ()
8425 "Narrow buffer to the current block."
8426 (interactive)
8427 (let* ((case-fold-search t)
8428 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8429 "^[ \t]*#\\+end_.*")))
8430 (if blockp
8431 (narrow-to-region (car blockp) (cdr blockp))
8432 (user-error "Not in a block"))))
8434 (eval-when-compile
8435 (defvar org-property-drawer-re))
8437 (defvar org-property-start-re) ;; defined below
8438 (defun org-clone-subtree-with-time-shift (n &optional shift)
8439 "Clone the task (subtree) at point N times.
8440 The clones will be inserted as siblings.
8442 In interactive use, the user will be prompted for the number of
8443 clones to be produced. If the entry has a timestamp, the user
8444 will also be prompted for a time shift, which may be a repeater
8445 as used in time stamps, for example `+3d'. To disable this,
8446 you can call the function with a universal prefix argument.
8448 When a valid repeater is given and the entry contains any time
8449 stamps, the clones will become a sequence in time, with time
8450 stamps in the subtree shifted for each clone produced. If SHIFT
8451 is nil or the empty string, time stamps will be left alone. The
8452 ID property of the original subtree is removed.
8454 If the original subtree did contain time stamps with a repeater,
8455 the following will happen:
8456 - the repeater will be removed in each clone
8457 - an additional clone will be produced, with the current, unshifted
8458 date(s) in the entry.
8459 - the original entry will be placed *after* all the clones, with
8460 repeater intact.
8461 - the start days in the repeater in the original entry will be shifted
8462 to past the last clone.
8463 In this way you can spell out a number of instances of a repeating task,
8464 and still retain the repeater to cover future instances of the task."
8465 (interactive "nNumber of clones to produce: ")
8466 (let ((shift
8467 (or shift
8468 (if (and (not (equal current-prefix-arg '(4)))
8469 (save-excursion
8470 (re-search-forward org-ts-regexp-both
8471 (save-excursion
8472 (org-end-of-subtree t)
8473 (point)) t)))
8474 (read-from-minibuffer
8475 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8476 ""))) ;; No time shift
8477 (n-no-remove -1)
8478 (drawer-re org-drawer-regexp)
8479 beg end template task idprop
8480 shift-n shift-what doshift nmin nmax)
8481 (if (not (and (integerp n) (> n 0)))
8482 (error "Invalid number of replications %s" n))
8483 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8484 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8485 shift)))
8486 (error "Invalid shift specification %s" shift))
8487 (when doshift
8488 (setq shift-n (string-to-number (match-string 1 shift))
8489 shift-what (cdr (assoc (match-string 2 shift)
8490 '(("d" . day) ("w" . week)
8491 ("m" . month) ("y" . year))))))
8492 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8493 (setq nmin 1 nmax n)
8494 (org-back-to-heading t)
8495 (setq beg (point))
8496 (setq idprop (org-entry-get nil "ID"))
8497 (org-end-of-subtree t t)
8498 (or (bolp) (insert "\n"))
8499 (setq end (point))
8500 (setq template (buffer-substring beg end))
8501 (when (and doshift
8502 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8503 (delete-region beg end)
8504 (setq end beg)
8505 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8506 (goto-char end)
8507 (loop for n from nmin to nmax do
8508 ;; prepare clone
8509 (with-temp-buffer
8510 (insert template)
8511 (org-mode)
8512 (goto-char (point-min))
8513 (org-show-subtree)
8514 (and idprop (if org-clone-delete-id
8515 (org-entry-delete nil "ID")
8516 (org-id-get-create t)))
8517 (unless (= n 0)
8518 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8519 (kill-whole-line))
8520 (goto-char (point-min))
8521 (while (re-search-forward drawer-re nil t)
8522 (mapc (lambda (d)
8523 (org-remove-empty-drawer-at d (point))) org-drawers)))
8524 (goto-char (point-min))
8525 (when doshift
8526 (while (re-search-forward org-ts-regexp-both nil t)
8527 (org-timestamp-change (* n shift-n) shift-what))
8528 (unless (= n n-no-remove)
8529 (goto-char (point-min))
8530 (while (re-search-forward org-ts-regexp nil t)
8531 (save-excursion
8532 (goto-char (match-beginning 0))
8533 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8534 (delete-region (match-beginning 1) (match-end 1)))))))
8535 (setq task (buffer-string)))
8536 (insert task))
8537 (goto-char beg)))
8539 ;;; Outline Sorting
8541 (defun org-sort (with-case)
8542 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8543 Optional argument WITH-CASE means sort case-sensitively."
8544 (interactive "P")
8545 (cond
8546 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8547 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8549 (org-call-with-arg 'org-sort-entries with-case))))
8551 (defun org-sort-remove-invisible (s)
8552 "Remove invisible links from string S."
8553 (remove-text-properties 0 (length s) org-rm-props s)
8554 (while (string-match org-bracket-link-regexp s)
8555 (setq s (replace-match (if (match-end 2)
8556 (match-string 3 s)
8557 (match-string 1 s)) t t s)))
8558 (let ((st (format " %s " s)))
8559 (while (string-match org-emph-re st)
8560 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8561 (setq s (substring st 1 -1)))
8564 (defvar org-priority-regexp) ; defined later in the file
8566 (defvar org-after-sorting-entries-or-items-hook nil
8567 "Hook that is run after a bunch of entries or items have been sorted.
8568 When children are sorted, the cursor is in the parent line when this
8569 hook gets called. When a region or a plain list is sorted, the cursor
8570 will be in the first entry of the sorted region/list.")
8572 (defun org-sort-entries
8573 (&optional with-case sorting-type getkey-func compare-func property)
8574 "Sort entries on a certain level of an outline tree.
8575 If there is an active region, the entries in the region are sorted.
8576 Else, if the cursor is before the first entry, sort the top-level items.
8577 Else, the children of the entry at point are sorted.
8579 Sorting can be alphabetically, numerically, by date/time as given by
8580 a time stamp, by a property, by priority order, or by a custom function.
8582 The command prompts for the sorting type unless it has been given to the
8583 function through the SORTING-TYPE argument, which needs to be a character,
8584 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8585 precise meaning of each character:
8587 n Numerically, by converting the beginning of the entry/item to a number.
8588 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8589 o By order of TODO keywords.
8590 t By date/time, either the first active time stamp in the entry, or, if
8591 none exist, by the first inactive one.
8592 s By the scheduled date/time.
8593 d By deadline date/time.
8594 c By creation time, which is assumed to be the first inactive time stamp
8595 at the beginning of a line.
8596 p By priority according to the cookie.
8597 r By the value of a property.
8599 Capital letters will reverse the sort order.
8601 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8602 called with point at the beginning of the record. It must return either
8603 a string or a number that should serve as the sorting key for that record.
8605 Comparing entries ignores case by default. However, with an optional argument
8606 WITH-CASE, the sorting considers case as well.
8608 Sorting is done against the visible part of the headlines, it ignores hidden
8609 links."
8610 (interactive "P")
8611 (let ((case-func (if with-case 'identity 'downcase))
8612 (cmstr
8613 ;; The clock marker is lost when using `sort-subr', let's
8614 ;; store the clocking string.
8615 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8616 (save-excursion
8617 (goto-char org-clock-marker)
8618 (looking-back "^.*") (match-string-no-properties 0))))
8619 start beg end stars re re2
8620 txt what tmp)
8621 ;; Find beginning and end of region to sort
8622 (cond
8623 ((org-region-active-p)
8624 ;; we will sort the region
8625 (setq end (region-end)
8626 what "region")
8627 (goto-char (region-beginning))
8628 (if (not (org-at-heading-p)) (outline-next-heading))
8629 (setq start (point)))
8630 ((or (org-at-heading-p)
8631 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8632 ;; we will sort the children of the current headline
8633 (org-back-to-heading)
8634 (setq start (point)
8635 end (progn (org-end-of-subtree t t)
8636 (or (bolp) (insert "\n"))
8637 (org-back-over-empty-lines)
8638 (point))
8639 what "children")
8640 (goto-char start)
8641 (show-subtree)
8642 (outline-next-heading))
8644 ;; we will sort the top-level entries in this file
8645 (goto-char (point-min))
8646 (or (org-at-heading-p) (outline-next-heading))
8647 (setq start (point))
8648 (goto-char (point-max))
8649 (beginning-of-line 1)
8650 (when (looking-at ".*?\\S-")
8651 ;; File ends in a non-white line
8652 (end-of-line 1)
8653 (insert "\n"))
8654 (setq end (point-max))
8655 (setq what "top-level")
8656 (goto-char start)
8657 (show-all)))
8659 (setq beg (point))
8660 (if (>= beg end) (user-error "Nothing to sort"))
8662 (looking-at "\\(\\*+\\)")
8663 (setq stars (match-string 1)
8664 re (concat "^" (regexp-quote stars) " +")
8665 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8666 txt (buffer-substring beg end))
8667 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8668 (if (and (not (equal stars "*")) (string-match re2 txt))
8669 (user-error "Region to sort contains a level above the first entry"))
8671 (unless sorting-type
8672 (message
8673 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8674 [t]ime [s]cheduled [d]eadline [c]reated
8675 A/N/P/R/O/F/T/S/D/C means reversed:"
8676 what)
8677 (setq sorting-type (read-char-exclusive))
8679 (unless getkey-func
8680 (and (= (downcase sorting-type) ?f)
8681 (setq getkey-func
8682 (org-icompleting-read "Sort using function: "
8683 obarray 'fboundp t nil nil))
8684 (setq getkey-func (intern getkey-func))))
8686 (and (= (downcase sorting-type) ?r)
8687 (not property)
8688 (setq property
8689 (org-icompleting-read "Property: "
8690 (mapcar 'list (org-buffer-property-keys t))
8691 nil t))))
8693 (message "Sorting entries...")
8695 (save-restriction
8696 (narrow-to-region start end)
8697 (let ((dcst (downcase sorting-type))
8698 (case-fold-search nil)
8699 (now (current-time)))
8700 (sort-subr
8701 (/= dcst sorting-type)
8702 ;; This function moves to the beginning character of the "record" to
8703 ;; be sorted.
8704 (lambda nil
8705 (if (re-search-forward re nil t)
8706 (goto-char (match-beginning 0))
8707 (goto-char (point-max))))
8708 ;; This function moves to the last character of the "record" being
8709 ;; sorted.
8710 (lambda nil
8711 (save-match-data
8712 (condition-case nil
8713 (outline-forward-same-level 1)
8714 (error
8715 (goto-char (point-max))))))
8716 ;; This function returns the value that gets sorted against.
8717 (lambda nil
8718 (cond
8719 ((= dcst ?n)
8720 (if (looking-at org-complex-heading-regexp)
8721 (string-to-number (org-sort-remove-invisible (match-string 4)))
8722 nil))
8723 ((= dcst ?a)
8724 (if (looking-at org-complex-heading-regexp)
8725 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8726 nil))
8727 ((= dcst ?t)
8728 (let ((end (save-excursion (outline-next-heading) (point))))
8729 (if (or (re-search-forward org-ts-regexp end t)
8730 (re-search-forward org-ts-regexp-both end t))
8731 (org-time-string-to-seconds (match-string 0))
8732 (org-float-time now))))
8733 ((= dcst ?c)
8734 (let ((end (save-excursion (outline-next-heading) (point))))
8735 (if (re-search-forward
8736 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8737 end t)
8738 (org-time-string-to-seconds (match-string 0))
8739 (org-float-time now))))
8740 ((= dcst ?s)
8741 (let ((end (save-excursion (outline-next-heading) (point))))
8742 (if (re-search-forward org-scheduled-time-regexp end t)
8743 (org-time-string-to-seconds (match-string 1))
8744 (org-float-time now))))
8745 ((= dcst ?d)
8746 (let ((end (save-excursion (outline-next-heading) (point))))
8747 (if (re-search-forward org-deadline-time-regexp end t)
8748 (org-time-string-to-seconds (match-string 1))
8749 (org-float-time now))))
8750 ((= dcst ?p)
8751 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8752 (string-to-char (match-string 2))
8753 org-default-priority))
8754 ((= dcst ?r)
8755 (or (org-entry-get nil property) ""))
8756 ((= dcst ?o)
8757 (if (looking-at org-complex-heading-regexp)
8758 (- 9999 (length (member (match-string 2)
8759 org-todo-keywords-1)))))
8760 ((= dcst ?f)
8761 (if getkey-func
8762 (progn
8763 (setq tmp (funcall getkey-func))
8764 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8765 tmp)
8766 (error "Invalid key function `%s'" getkey-func)))
8767 (t (error "Invalid sorting type `%c'" sorting-type))))
8769 (cond
8770 ((= dcst ?a) 'string<)
8771 ((= dcst ?f) compare-func)
8772 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8773 (run-hooks 'org-after-sorting-entries-or-items-hook)
8774 ;; Reset the clock marker if needed
8775 (when cmstr
8776 (save-excursion
8777 (goto-char start)
8778 (search-forward cmstr nil t)
8779 (move-marker org-clock-marker (point))))
8780 (message "Sorting entries...done")))
8782 (defun org-do-sort (table what &optional with-case sorting-type)
8783 "Sort TABLE of WHAT according to SORTING-TYPE.
8784 The user will be prompted for the SORTING-TYPE if the call to this
8785 function does not specify it. WHAT is only for the prompt, to indicate
8786 what is being sorted. The sorting key will be extracted from
8787 the car of the elements of the table.
8788 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8789 (unless sorting-type
8790 (message
8791 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8792 what)
8793 (setq sorting-type (read-char-exclusive)))
8794 (let ((dcst (downcase sorting-type))
8795 extractfun comparefun)
8796 ;; Define the appropriate functions
8797 (cond
8798 ((= dcst ?n)
8799 (setq extractfun 'string-to-number
8800 comparefun (if (= dcst sorting-type) '< '>)))
8801 ((= dcst ?a)
8802 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8803 (lambda(x) (downcase (org-sort-remove-invisible x))))
8804 comparefun (if (= dcst sorting-type)
8805 'string<
8806 (lambda (a b) (and (not (string< a b))
8807 (not (string= a b)))))))
8808 ((= dcst ?t)
8809 (setq extractfun
8810 (lambda (x)
8811 (if (or (string-match org-ts-regexp x)
8812 (string-match org-ts-regexp-both x))
8813 (org-float-time
8814 (org-time-string-to-time (match-string 0 x)))
8816 comparefun (if (= dcst sorting-type) '< '>)))
8817 (t (error "Invalid sorting type `%c'" sorting-type)))
8819 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8820 table)
8821 (lambda (a b) (funcall comparefun (car a) (car b))))))
8824 ;;; The orgstruct minor mode
8826 ;; Define a minor mode which can be used in other modes in order to
8827 ;; integrate the org-mode structure editing commands.
8829 ;; This is really a hack, because the org-mode structure commands use
8830 ;; keys which normally belong to the major mode. Here is how it
8831 ;; works: The minor mode defines all the keys necessary to operate the
8832 ;; structure commands, but wraps the commands into a function which
8833 ;; tests if the cursor is currently at a headline or a plain list
8834 ;; item. If that is the case, the structure command is used,
8835 ;; temporarily setting many Org-mode variables like regular
8836 ;; expressions for filling etc. However, when any of those keys is
8837 ;; used at a different location, function uses `key-binding' to look
8838 ;; up if the key has an associated command in another currently active
8839 ;; keymap (minor modes, major mode, global), and executes that
8840 ;; command. There might be problems if any of the keys is otherwise
8841 ;; used as a prefix key.
8843 (defcustom orgstruct-heading-prefix-regexp nil
8844 "Regexp that matches the custom prefix of Org headlines in
8845 orgstruct(++)-mode."
8846 :group 'org
8847 :version "24.4"
8848 :package-version '(Org . "8.0")
8849 :type 'string)
8850 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8852 (defcustom orgstruct-setup-hook nil
8853 "Hook run after orgstruct-mode-map is filled."
8854 :group 'org
8855 :version "24.4"
8856 :package-version '(Org . "8.0")
8857 :type 'hook)
8859 (defvar orgstruct-initialized nil)
8861 (defvar org-local-vars nil
8862 "List of local variables, for use by `orgstruct-mode'.")
8864 ;;;###autoload
8865 (define-minor-mode orgstruct-mode
8866 "Toggle the minor mode `orgstruct-mode'.
8867 This mode is for using Org-mode structure commands in other
8868 modes. The following keys behave as if Org-mode were active, if
8869 the cursor is on a headline, or on a plain list item (both as
8870 defined by Org-mode)."
8871 nil " OrgStruct" (make-sparse-keymap)
8872 (funcall (if orgstruct-mode
8873 'add-to-invisibility-spec
8874 'remove-from-invisibility-spec)
8875 '(outline . t))
8876 (when orgstruct-mode
8877 (org-load-modules-maybe)
8878 (unless orgstruct-initialized
8879 (orgstruct-setup)
8880 (setq orgstruct-initialized t))))
8882 ;;;###autoload
8883 (defun turn-on-orgstruct ()
8884 "Unconditionally turn on `orgstruct-mode'."
8885 (orgstruct-mode 1))
8887 (defvar org-fb-vars nil)
8888 (make-variable-buffer-local 'org-fb-vars)
8889 (defun orgstruct++-mode (&optional arg)
8890 "Toggle `orgstruct-mode', the enhanced version of it.
8891 In addition to setting orgstruct-mode, this also exports all
8892 indentation and autofilling variables from org-mode into the
8893 buffer. It will also recognize item context in multiline items."
8894 (interactive "P")
8895 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8896 (if (< arg 1)
8897 (progn (orgstruct-mode -1)
8898 (mapc (lambda(v)
8899 (org-set-local (car v)
8900 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8901 org-fb-vars))
8902 (orgstruct-mode 1)
8903 (setq org-fb-vars nil)
8904 (unless org-local-vars
8905 (setq org-local-vars (org-get-local-variables)))
8906 (let (var val)
8907 (mapc
8908 (lambda (x)
8909 (when (string-match
8910 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8911 (symbol-name (car x)))
8912 (setq var (car x) val (nth 1 x))
8913 (push (list var `(quote ,(eval var))) org-fb-vars)
8914 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8915 org-local-vars)
8916 (org-set-local 'orgstruct-is-++ t))))
8918 (defvar orgstruct-is-++ nil
8919 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8920 (make-variable-buffer-local 'orgstruct-is-++)
8922 ;;;###autoload
8923 (defun turn-on-orgstruct++ ()
8924 "Unconditionally turn on `orgstruct++-mode'."
8925 (orgstruct++-mode 1))
8927 (defun orgstruct-error ()
8928 "Error when there is no default binding for a structure key."
8929 (interactive)
8930 (funcall (if (fboundp 'user-error)
8931 'user-error
8932 'error)
8933 "This key has no function outside structure elements"))
8935 (defun orgstruct-setup ()
8936 "Setup orgstruct keymap."
8937 (dolist (cell '((org-demote . t)
8938 (org-metaleft . t)
8939 (org-metaright . t)
8940 (org-promote . t)
8941 (org-shiftmetaleft . t)
8942 (org-shiftmetaright . t)
8943 org-backward-element
8944 org-backward-heading-same-level
8945 org-ctrl-c-ret
8946 org-ctrl-c-minus
8947 org-ctrl-c-star
8948 org-cycle
8949 org-forward-heading-same-level
8950 org-insert-heading
8951 org-insert-heading-respect-content
8952 org-kill-note-or-show-branches
8953 org-mark-subtree
8954 org-meta-return
8955 org-metadown
8956 org-metaup
8957 org-narrow-to-subtree
8958 org-promote-subtree
8959 org-reveal
8960 org-shiftdown
8961 org-shiftleft
8962 org-shiftmetadown
8963 org-shiftmetaup
8964 org-shiftright
8965 org-shifttab
8966 org-shifttab
8967 org-shiftup
8968 org-show-subtree
8969 org-sort
8970 org-up-element
8971 outline-demote
8972 outline-next-visible-heading
8973 outline-previous-visible-heading
8974 outline-promote
8975 outline-up-heading
8976 show-children))
8977 (let ((f (or (car-safe cell) cell))
8978 (disable-when-heading-prefix (cdr-safe cell)))
8979 (when (fboundp f)
8980 (let ((new-bindings))
8981 (dolist (binding (nconc (where-is-internal f org-mode-map)
8982 (where-is-internal f outline-mode-map)))
8983 (push binding new-bindings)
8984 ;; TODO use local-function-key-map
8985 (dolist (rep '(("<tab>" . "TAB")
8986 ("<return>" . "RET")
8987 ("<escape>" . "ESC")
8988 ("<delete>" . "DEL")))
8989 (setq binding (read-kbd-macro
8990 (let ((case-fold-search))
8991 (replace-regexp-in-string
8992 (regexp-quote (cdr rep))
8993 (car rep)
8994 (key-description binding)))))
8995 (pushnew binding new-bindings :test 'equal)))
8996 (dolist (binding new-bindings)
8997 (let ((key (lookup-key orgstruct-mode-map binding)))
8998 (when (or (not key) (numberp key))
8999 (condition-case nil
9000 (org-defkey orgstruct-mode-map
9001 binding
9002 (orgstruct-make-binding f binding disable-when-heading-prefix))
9003 (error nil)))))))))
9004 (run-hooks 'orgstruct-setup-hook))
9006 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9007 "Create a function for binding in the structure minor mode.
9008 FUN is the command to call inside a table. KEY is the key that
9009 should be checked in for a command to execute outside of tables.
9010 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
9011 if `orgstruct-heading-prefix-regexp' is non-nil."
9012 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9013 (let ((nname name)
9014 (i 0))
9015 (while (fboundp (intern nname))
9016 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9017 (setq name (intern nname)))
9018 (eval
9019 (let ((bindings '((org-heading-regexp
9020 (concat "^"
9021 orgstruct-heading-prefix-regexp
9022 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9023 (org-outline-regexp
9024 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9025 (org-outline-regexp-bol
9026 (concat "^" org-outline-regexp))
9027 (outline-regexp org-outline-regexp)
9028 (outline-heading-end-regexp "\n")
9029 (outline-level 'org-outline-level)
9030 (outline-heading-alist))))
9031 `(defun ,name (arg)
9032 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9033 "Outside of structure, run the binding of `"
9034 (key-description key) "'."
9035 (when disable-when-heading-prefix
9036 (concat
9037 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9038 "back to the default binding due to limitations of Org's implementation of\n"
9039 "`" (symbol-name fun) "'.")))
9040 (interactive "p")
9041 (let* ((disable
9042 ,(when disable-when-heading-prefix
9043 '(and orgstruct-heading-prefix-regexp
9044 (not (string= orgstruct-heading-prefix-regexp "")))))
9045 (fallback
9046 (or disable
9047 (not
9048 (let* ,bindings
9049 (org-context-p 'headline 'item
9050 ,(when (memq fun
9051 '(org-insert-heading
9052 org-insert-heading-respect-content
9053 org-meta-return))
9054 '(when orgstruct-is-++
9055 'item-body))))))))
9056 (if fallback
9057 (let* ((orgstruct-mode)
9058 (binding
9059 (loop with key = ,key
9060 for rep in
9061 '(nil
9062 ("<\\([^>]*\\)tab>" . "\\1TAB")
9063 ("<\\([^>]*\\)return>" . "\\1RET")
9064 ("<\\([^>]*\\)escape>" . "\\1ESC")
9065 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9067 (when rep
9068 (setq key (read-kbd-macro
9069 (let ((case-fold-search))
9070 (replace-regexp-in-string
9071 (car rep)
9072 (cdr rep)
9073 (key-description key))))))
9074 thereis (key-binding key))))
9075 (if (keymapp binding)
9076 (set-temporary-overlay-map binding)
9077 (let ((func (or binding
9078 (unless disable
9079 'orgstruct-error))))
9080 (when func
9081 (call-interactively func)))))
9082 (org-run-like-in-org-mode
9083 (lambda ()
9084 (interactive)
9085 (let* ,bindings
9086 (call-interactively ',fun)))))))))
9087 name))
9089 (defun org-contextualize-keys (alist contexts)
9090 "Return valid elements in ALIST depending on CONTEXTS.
9092 `org-agenda-custom-commands' or `org-capture-templates' are the
9093 values used for ALIST, and `org-agenda-custom-commands-contexts'
9094 or `org-capture-templates-contexts' are the associated contexts
9095 definitions."
9096 (let ((contexts
9097 ;; normalize contexts
9098 (mapcar
9099 (lambda(c) (cond ((listp (cadr c))
9100 (list (car c) (car c) (cadr c)))
9101 ((string= "" (cadr c))
9102 (list (car c) (car c) (caddr c)))
9103 (t c))) contexts))
9104 (a alist) c r s)
9105 ;; loop over all commands or templates
9106 (while (setq c (pop a))
9107 (let (vrules repl)
9108 (cond
9109 ((not (assoc (car c) contexts))
9110 (push c r))
9111 ((and (assoc (car c) contexts)
9112 (setq vrules (org-contextualize-validate-key
9113 (car c) contexts)))
9114 (mapc (lambda (vr)
9115 (when (not (equal (car vr) (cadr vr)))
9116 (setq repl vr))) vrules)
9117 (if (not repl) (push c r)
9118 (push (cadr repl) s)
9119 (push
9120 (cons (car c)
9121 (cdr (or (assoc (cadr repl) alist)
9122 (error "Undefined key `%s' as contextual replacement for `%s'"
9123 (cadr repl) (car c)))))
9124 r))))))
9125 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9126 (delq
9128 (delete-dups
9129 (mapcar (lambda (x)
9130 (let ((tpl (car x)))
9131 (when (not (delq
9133 (mapcar (lambda(y)
9134 (equal y tpl)) s))) x)))
9135 (reverse r))))))
9137 (defun org-contextualize-validate-key (key contexts)
9138 "Check CONTEXTS for agenda or capture KEY."
9139 (let (r rr res)
9140 (while (setq r (pop contexts))
9141 (mapc
9142 (lambda (rr)
9143 (when
9144 (and (equal key (car r))
9145 (if (functionp rr) (funcall rr)
9146 (or (and (eq (car rr) 'in-file)
9147 (buffer-file-name)
9148 (string-match (cdr rr) (buffer-file-name)))
9149 (and (eq (car rr) 'in-mode)
9150 (string-match (cdr rr) (symbol-name major-mode)))
9151 (and (eq (car rr) 'in-buffer)
9152 (string-match (cdr rr) (buffer-name)))
9153 (when (and (eq (car rr) 'not-in-file)
9154 (buffer-file-name))
9155 (not (string-match (cdr rr) (buffer-file-name))))
9156 (when (eq (car rr) 'not-in-mode)
9157 (not (string-match (cdr rr) (symbol-name major-mode))))
9158 (when (eq (car rr) 'not-in-buffer)
9159 (not (string-match (cdr rr) (buffer-name)))))))
9160 (push r res)))
9161 (car (last r))))
9162 (delete-dups (delq nil res))))
9164 (defun org-context-p (&rest contexts)
9165 "Check if local context is any of CONTEXTS.
9166 Possible values in the list of contexts are `table', `headline', and `item'."
9167 (let ((pos (point)))
9168 (goto-char (point-at-bol))
9169 (prog1 (or (and (memq 'table contexts)
9170 (looking-at "[ \t]*|"))
9171 (and (memq 'headline contexts)
9172 (looking-at org-outline-regexp))
9173 (and (memq 'item contexts)
9174 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9175 (and (memq 'item-body contexts)
9176 (org-in-item-p)))
9177 (goto-char pos))))
9179 (defun org-get-local-variables ()
9180 "Return a list of all local variables in an Org mode buffer."
9181 (let (varlist)
9182 (with-current-buffer (get-buffer-create "*Org tmp*")
9183 (erase-buffer)
9184 (org-mode)
9185 (setq varlist (buffer-local-variables)))
9186 (kill-buffer "*Org tmp*")
9187 (delq nil
9188 (mapcar
9189 (lambda (x)
9190 (setq x
9191 (if (symbolp x)
9192 (list x)
9193 (list (car x) (cdr x))))
9194 (if (and (not (get (car x) 'org-state))
9195 (string-match
9196 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9197 (symbol-name (car x))))
9198 x nil))
9199 varlist))))
9201 (defun org-clone-local-variables (from-buffer &optional regexp)
9202 "Clone local variables from FROM-BUFFER.
9203 Optional argument REGEXP selects variables to clone."
9204 (mapc
9205 (lambda (pair)
9206 (and (symbolp (car pair))
9207 (or (null regexp)
9208 (string-match regexp (symbol-name (car pair))))
9209 (set (make-local-variable (car pair))
9210 (cdr pair))))
9211 (buffer-local-variables from-buffer)))
9213 ;;;###autoload
9214 (defun org-run-like-in-org-mode (cmd)
9215 "Run a command, pretending that the current buffer is in Org-mode.
9216 This will temporarily bind local variables that are typically bound in
9217 Org-mode to the values they have in Org-mode, and then interactively
9218 call CMD."
9219 (org-load-modules-maybe)
9220 (unless org-local-vars
9221 (setq org-local-vars (org-get-local-variables)))
9222 (let (binds)
9223 (dolist (var org-local-vars)
9224 (when (or (not (boundp (car var)))
9225 (eq (symbol-value (car var))
9226 (default-value (car var))))
9227 (push (list (car var) `(quote ,(cadr var))) binds)))
9228 (eval `(let ,binds
9229 (call-interactively (quote ,cmd))))))
9231 ;;;; Archiving
9233 (defun org-get-category (&optional pos force-refresh)
9234 "Get the category applying to position POS."
9235 (save-match-data
9236 (if force-refresh (org-refresh-category-properties))
9237 (let ((pos (or pos (point))))
9238 (or (get-text-property pos 'org-category)
9239 (progn (org-refresh-category-properties)
9240 (get-text-property pos 'org-category))))))
9242 (defun org-refresh-category-properties ()
9243 "Refresh category text properties in the buffer."
9244 (let ((case-fold-search t)
9245 (inhibit-read-only t)
9246 (def-cat (cond
9247 ((null org-category)
9248 (if buffer-file-name
9249 (file-name-sans-extension
9250 (file-name-nondirectory buffer-file-name))
9251 "???"))
9252 ((symbolp org-category) (symbol-name org-category))
9253 (t org-category)))
9254 beg end cat pos optionp)
9255 (org-with-silent-modifications
9256 (save-excursion
9257 (save-restriction
9258 (widen)
9259 (goto-char (point-min))
9260 (put-text-property (point) (point-max) 'org-category def-cat)
9261 (while (re-search-forward
9262 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9263 (setq pos (match-end 0)
9264 optionp (equal (char-after (match-beginning 0)) ?#)
9265 cat (org-trim (match-string 2)))
9266 (if optionp
9267 (setq beg (point-at-bol) end (point-max))
9268 (org-back-to-heading t)
9269 (setq beg (point) end (org-end-of-subtree t t)))
9270 (put-text-property beg end 'org-category cat)
9271 (put-text-property beg end 'org-category-position beg)
9272 (goto-char pos)))))))
9274 (defun org-refresh-properties (dprop tprop)
9275 "Refresh buffer text properties.
9276 DPROP is the drawer property and TPROP is the corresponding text
9277 property to set."
9278 (let ((case-fold-search t)
9279 (inhibit-read-only t) p)
9280 (org-with-silent-modifications
9281 (save-excursion
9282 (save-restriction
9283 (widen)
9284 (goto-char (point-min))
9285 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9286 (setq p (org-match-string-no-properties 1))
9287 (save-excursion
9288 (org-back-to-heading t)
9289 (put-text-property
9290 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9293 ;;;; Link Stuff
9295 ;;; Link abbreviations
9297 (defun org-link-expand-abbrev (link)
9298 "Apply replacements as defined in `org-link-abbrev-alist'."
9299 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9300 (let* ((key (match-string 1 link))
9301 (as (or (assoc key org-link-abbrev-alist-local)
9302 (assoc key org-link-abbrev-alist)))
9303 (tag (and (match-end 2) (match-string 3 link)))
9304 rpl)
9305 (if (not as)
9306 link
9307 (setq rpl (cdr as))
9308 (cond
9309 ((symbolp rpl) (funcall rpl tag))
9310 ((string-match "%(\\([^)]+\\))" rpl)
9311 (replace-match
9312 (save-match-data
9313 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9314 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9315 ((string-match "%h" rpl)
9316 (replace-match (url-hexify-string (or tag "")) t t rpl))
9317 (t (concat rpl tag)))))
9318 link))
9320 ;;; Storing and inserting links
9322 (defvar org-insert-link-history nil
9323 "Minibuffer history for links inserted with `org-insert-link'.")
9325 (defvar org-stored-links nil
9326 "Contains the links stored with `org-store-link'.")
9328 (defvar org-store-link-plist nil
9329 "Plist with info about the most recently link created with `org-store-link'.")
9331 (defvar org-link-protocols nil
9332 "Link protocols added to Org-mode using `org-add-link-type'.")
9334 (defvar org-store-link-functions nil
9335 "List of functions that are called to create and store a link.
9336 Each function will be called in turn until one returns a non-nil
9337 value. Each function should check if it is responsible for creating
9338 this link (for example by looking at the major mode).
9339 If not, it must exit and return nil.
9340 If yes, it should return a non-nil value after a calling
9341 `org-store-link-props' with a list of properties and values.
9342 Special properties are:
9344 :type The link prefix, like \"http\". This must be given.
9345 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9346 This is obligatory as well.
9347 :description Optional default description for the second pair
9348 of brackets in an Org-mode link. The user can still change
9349 this when inserting this link into an Org-mode buffer.
9351 In addition to these, any additional properties can be specified
9352 and then used in capture templates.")
9354 (defun org-add-link-type (type &optional follow export)
9355 "Add TYPE to the list of `org-link-types'.
9356 Re-compute all regular expressions depending on `org-link-types'
9358 FOLLOW and EXPORT are two functions.
9360 FOLLOW should take the link path as the single argument and do whatever
9361 is necessary to follow the link, for example find a file or display
9362 a mail message.
9364 EXPORT should format the link path for export to one of the export formats.
9365 It should be a function accepting three arguments:
9367 path the path of the link, the text after the prefix (like \"http:\")
9368 desc the description of the link, if any, or a description added by
9369 org-export-normalize-links if there is none
9370 format the export format, a symbol like `html' or `latex' or `ascii'..
9372 The function may use the FORMAT information to return different values
9373 depending on the format. The return value will be put literally into
9374 the exported file. If the return value is nil, this means Org should
9375 do what it normally does with links which do not have EXPORT defined.
9377 Org-mode has a built-in default for exporting links. If you are happy with
9378 this default, there is no need to define an export function for the link
9379 type. For a simple example of an export function, see `org-bbdb.el'."
9380 (add-to-list 'org-link-types type t)
9381 (org-make-link-regexps)
9382 (if (assoc type org-link-protocols)
9383 (setcdr (assoc type org-link-protocols) (list follow export))
9384 (push (list type follow export) org-link-protocols)))
9386 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9387 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9389 ;;;###autoload
9390 (defun org-store-link (arg)
9391 "\\<org-mode-map>Store an org-link to the current location.
9392 This link is added to `org-stored-links' and can later be inserted
9393 into an org-buffer with \\[org-insert-link].
9395 For some link types, a prefix arg is interpreted.
9396 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9397 For file links, arg negates `org-context-in-file-links'.
9399 A double prefix arg force skipping storing functions that are not
9400 part of Org's core.
9402 A triple prefix arg force storing a link for each line in the
9403 active region."
9404 (interactive "P")
9405 (org-load-modules-maybe)
9406 (if (and (equal arg '(64)) (org-region-active-p))
9407 (save-excursion
9408 (let ((end (region-end)))
9409 (goto-char (region-beginning))
9410 (set-mark (point))
9411 (while (< (point-at-eol) end)
9412 (move-end-of-line 1) (activate-mark)
9413 (let (current-prefix-arg)
9414 (call-interactively 'org-store-link))
9415 (move-beginning-of-line 2)
9416 (set-mark (point)))))
9417 (org-with-limited-levels
9418 (setq org-store-link-plist nil)
9419 (let (link cpltxt desc description search
9420 txt custom-id agenda-link sfuns sfunsn)
9421 (cond
9423 ;; Store a link using an external link type
9424 ((and (not (equal arg '(16)))
9425 (setq sfuns
9426 (delq
9427 nil (mapcar (lambda (f)
9428 (let (fs) (if (funcall f) (push f fs))))
9429 org-store-link-functions))
9430 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9431 (or (and (cdr sfuns)
9432 (funcall (intern
9433 (completing-read
9434 "Which function for creating the link? "
9435 sfunsn t (car sfunsn)))))
9436 (funcall (caar sfuns)))
9437 (setq link (plist-get org-store-link-plist :link)
9438 desc (or (plist-get org-store-link-plist
9439 :description) link))))
9441 ;; Store a link from a source code buffer
9442 ((org-src-edit-buffer-p)
9443 (let (label gc)
9444 (while (or (not label)
9445 (save-excursion
9446 (save-restriction
9447 (widen)
9448 (goto-char (point-min))
9449 (re-search-forward
9450 (regexp-quote (format org-coderef-label-format label))
9451 nil t))))
9452 (when label (message "Label exists already") (sit-for 2))
9453 (setq label (read-string "Code line label: " label)))
9454 (end-of-line 1)
9455 (setq link (format org-coderef-label-format label))
9456 (setq gc (- 79 (length link)))
9457 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9458 (insert link)
9459 (setq link (concat "(" label ")") desc nil)))
9461 ;; We are in the agenda, link to referenced location
9462 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9463 (let ((m (or (get-text-property (point) 'org-hd-marker)
9464 (get-text-property (point) 'org-marker))))
9465 (when m
9466 (org-with-point-at m
9467 (setq agenda-link
9468 (if (org-called-interactively-p 'any)
9469 (call-interactively 'org-store-link)
9470 (org-store-link nil)))))))
9472 ((eq major-mode 'calendar-mode)
9473 (let ((cd (calendar-cursor-to-date)))
9474 (setq link
9475 (format-time-string
9476 (car org-time-stamp-formats)
9477 (apply 'encode-time
9478 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9479 nil nil nil))))
9480 (org-store-link-props :type "calendar" :date cd)))
9482 ((eq major-mode 'help-mode)
9483 (setq link (concat "help:" (save-excursion
9484 (goto-char (point-min))
9485 (looking-at "^[^ ]+")
9486 (match-string 0))))
9487 (org-store-link-props :type "help"))
9489 ((eq major-mode 'w3-mode)
9490 (setq cpltxt (if (and (buffer-name)
9491 (not (string-match "Untitled" (buffer-name))))
9492 (buffer-name)
9493 (url-view-url t))
9494 link (url-view-url t))
9495 (org-store-link-props :type "w3" :url (url-view-url t)))
9497 ((eq major-mode 'image-mode)
9498 (setq cpltxt (concat "file:"
9499 (abbreviate-file-name buffer-file-name))
9500 link cpltxt)
9501 (org-store-link-props :type "image" :file buffer-file-name))
9503 ;; In dired, store a link to the file of the current line
9504 ((eq major-mode 'dired-mode)
9505 (let ((file (dired-get-filename nil t)))
9506 (setq file (if file
9507 (abbreviate-file-name
9508 (expand-file-name (dired-get-filename nil t)))
9509 ;; otherwise, no file so use current directory.
9510 default-directory))
9511 (setq cpltxt (concat "file:" file)
9512 link cpltxt)))
9514 ((setq search (run-hook-with-args-until-success
9515 'org-create-file-search-functions))
9516 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9517 "::" search))
9518 (setq cpltxt (or description link)))
9520 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9521 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9522 (cond
9523 ;; Store a link using the target at point
9524 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9525 (setq cpltxt
9526 (concat "file:"
9527 (abbreviate-file-name
9528 (buffer-file-name (buffer-base-buffer)))
9529 "::" (match-string 1))
9530 link cpltxt))
9531 ((and (featurep 'org-id)
9532 (or (eq org-id-link-to-org-use-id t)
9533 (and (org-called-interactively-p 'any)
9534 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9535 (and (eq org-id-link-to-org-use-id
9536 'create-if-interactive-and-no-custom-id)
9537 (not custom-id))))
9538 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9539 ;; Store a link using the ID at point
9540 (setq link (condition-case nil
9541 (prog1 (org-id-store-link)
9542 (setq desc (plist-get org-store-link-plist
9543 :description)))
9544 (error
9545 ;; Probably before first headline, link only to file
9546 (concat "file:"
9547 (abbreviate-file-name
9548 (buffer-file-name (buffer-base-buffer))))))))
9550 ;; Just link to current headline
9551 (setq cpltxt (concat "file:"
9552 (abbreviate-file-name
9553 (buffer-file-name (buffer-base-buffer)))))
9554 ;; Add a context search string
9555 (when (org-xor org-context-in-file-links arg)
9556 (let* ((ee (org-element-at-point))
9557 (et (org-element-type ee))
9558 (ev (plist-get (cadr ee) :value))
9559 (ek (plist-get (cadr ee) :key))
9560 (eok (and (stringp ek) (string-match "name" ek))))
9561 (setq txt (cond
9562 ((org-at-heading-p) nil)
9563 ((and (eq et 'keyword) eok) ev)
9564 ((org-region-active-p)
9565 (buffer-substring (region-beginning) (region-end)))))
9566 (when (or (null txt) (string-match "\\S-" txt))
9567 (setq cpltxt
9568 (concat cpltxt "::"
9569 (condition-case nil
9570 (org-make-org-heading-search-string txt)
9571 (error "")))
9572 desc (or (and (eq et 'keyword) eok ev)
9573 (nth 4 (ignore-errors (org-heading-components)))
9574 "NONE")))))
9575 (if (string-match "::\\'" cpltxt)
9576 (setq cpltxt (substring cpltxt 0 -2)))
9577 (setq link cpltxt))))
9579 ((buffer-file-name (buffer-base-buffer))
9580 ;; Just link to this file here.
9581 (setq cpltxt (concat "file:"
9582 (abbreviate-file-name
9583 (buffer-file-name (buffer-base-buffer)))))
9584 ;; Add a context string.
9585 (when (org-xor org-context-in-file-links arg)
9586 (setq txt (if (org-region-active-p)
9587 (buffer-substring (region-beginning) (region-end))
9588 (buffer-substring (point-at-bol) (point-at-eol))))
9589 ;; Only use search option if there is some text.
9590 (when (string-match "\\S-" txt)
9591 (setq cpltxt
9592 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9593 desc "NONE")))
9594 (setq link cpltxt))
9596 ((org-called-interactively-p 'interactive)
9597 (user-error "No method for storing a link from this buffer"))
9599 (t (setq link nil)))
9601 ;; We're done setting link and desc, clean up
9602 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9603 (setq link (or link cpltxt)
9604 desc (or desc cpltxt))
9605 (cond ((equal desc "NONE") (setq desc nil))
9606 ((string-match org-bracket-link-analytic-regexp desc)
9607 (let ((d0 (match-string 3 desc))
9608 (p0 (match-string 5 desc)))
9609 (setq desc
9610 (replace-regexp-in-string
9611 org-bracket-link-regexp
9612 (concat (or p0 d0)
9613 (if (equal (length (match-string 0 desc))
9614 (length desc)) "*" "")) desc)))))
9616 ;; Return the link
9617 (if (not (and (or (org-called-interactively-p 'any)
9618 executing-kbd-macro) link))
9619 (or agenda-link (and link (org-make-link-string link desc)))
9620 (push (list link desc) org-stored-links)
9621 (message "Stored: %s" (or desc link))
9622 (when custom-id
9623 (setq link (concat "file:" (abbreviate-file-name
9624 (buffer-file-name)) "::#" custom-id))
9625 (push (list link desc) org-stored-links)))))))
9627 (defun org-store-link-props (&rest plist)
9628 "Store link properties, extract names and addresses."
9629 (let (x adr)
9630 (when (setq x (plist-get plist :from))
9631 (setq adr (mail-extract-address-components x))
9632 (setq plist (plist-put plist :fromname (car adr)))
9633 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9634 (when (setq x (plist-get plist :to))
9635 (setq adr (mail-extract-address-components x))
9636 (setq plist (plist-put plist :toname (car adr)))
9637 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9638 (let ((from (plist-get plist :from))
9639 (to (plist-get plist :to)))
9640 (when (and from to org-from-is-user-regexp)
9641 (setq plist
9642 (plist-put plist :fromto
9643 (if (string-match org-from-is-user-regexp from)
9644 (concat "to %t")
9645 (concat "from %f"))))))
9646 (setq org-store-link-plist plist))
9648 (defun org-add-link-props (&rest plist)
9649 "Add these properties to the link property list."
9650 (let (key value)
9651 (while plist
9652 (setq key (pop plist) value (pop plist))
9653 (setq org-store-link-plist
9654 (plist-put org-store-link-plist key value)))))
9656 (defun org-email-link-description (&optional fmt)
9657 "Return the description part of an email link.
9658 This takes information from `org-store-link-plist' and formats it
9659 according to FMT (default from `org-email-link-description-format')."
9660 (setq fmt (or fmt org-email-link-description-format))
9661 (let* ((p org-store-link-plist)
9662 (to (plist-get p :toaddress))
9663 (from (plist-get p :fromaddress))
9664 (table
9665 (list
9666 (cons "%c" (plist-get p :fromto))
9667 (cons "%F" (plist-get p :from))
9668 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9669 (cons "%T" (plist-get p :to))
9670 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9671 (cons "%s" (plist-get p :subject))
9672 (cons "%d" (plist-get p :date))
9673 (cons "%m" (plist-get p :message-id)))))
9674 (when (string-match "%c" fmt)
9675 ;; Check if the user wrote this message
9676 (if (and org-from-is-user-regexp from to
9677 (save-match-data (string-match org-from-is-user-regexp from)))
9678 (setq fmt (replace-match "to %t" t t fmt))
9679 (setq fmt (replace-match "from %f" t t fmt))))
9680 (org-replace-escapes fmt table)))
9682 (defun org-make-org-heading-search-string (&optional string)
9683 "Make search string for the current headline or STRING."
9684 (let ((s (or string
9685 (and (derived-mode-p 'org-mode)
9686 (save-excursion
9687 (org-back-to-heading t)
9688 (org-element-property :raw-value (org-element-at-point))))))
9689 (lines org-context-in-file-links))
9690 (or string (setq s (concat "*" s))) ; Add * for headlines
9691 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9692 (when (and string (integerp lines) (> lines 0))
9693 (let ((slines (org-split-string s "\n")))
9694 (when (< lines (length slines))
9695 (setq s (mapconcat
9696 'identity
9697 (reverse (nthcdr (- (length slines) lines)
9698 (reverse slines))) "\n")))))
9699 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9701 (defun org-make-link-string (link &optional description)
9702 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9703 (unless (string-match "\\S-" link)
9704 (error "Empty link"))
9705 (when (and description
9706 (stringp description)
9707 (not (string-match "\\S-" description)))
9708 (setq description nil))
9709 (when (stringp description)
9710 ;; Remove brackets from the description, they are fatal.
9711 (while (string-match "\\[" description)
9712 (setq description (replace-match "{" t t description)))
9713 (while (string-match "\\]" description)
9714 (setq description (replace-match "}" t t description))))
9715 (when (equal link description)
9716 ;; No description needed, it is identical
9717 (setq description nil))
9718 (when (and (not description)
9719 (not (string-match (org-image-file-name-regexp) link))
9720 (not (equal link (org-link-escape link))))
9721 (setq description (org-extract-attributes link)))
9722 (setq link
9723 (cond ((string-match (org-image-file-name-regexp) link) link)
9724 ((string-match org-link-types-re link)
9725 (concat (match-string 1 link)
9726 (org-link-escape (substring link (match-end 1)))))
9727 (t (org-link-escape link))))
9728 (concat "[[" link "]"
9729 (if description (concat "[" description "]") "")
9730 "]"))
9732 (defconst org-link-escape-chars
9733 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9734 "List of characters that should be escaped in link.
9735 This is the list that is used for internal purposes.")
9737 (defconst org-link-escape-chars-browser
9738 '(?\ ?\")
9739 "List of escapes for characters that are problematic in links.
9740 This is the list that is used before handing over to the browser.")
9742 (defun org-link-escape (text &optional table merge)
9743 "Return percent escaped representation of TEXT.
9744 TEXT is a string with the text to escape.
9745 Optional argument TABLE is a list with characters that should be
9746 escaped. When nil, `org-link-escape-chars' is used.
9747 If optional argument MERGE is set, merge TABLE into
9748 `org-link-escape-chars'."
9749 (cond
9750 ((and table merge)
9751 (mapc (lambda (defchr)
9752 (unless (member defchr table)
9753 (setq table (cons defchr table)))) org-link-escape-chars))
9754 ((null table)
9755 (setq table org-link-escape-chars)))
9756 (mapconcat
9757 (lambda (char)
9758 (if (or (member char table)
9759 (and (or (< char 32) (= char 37) (> char 126))
9760 org-url-hexify-p))
9761 (mapconcat (lambda (sequence-element)
9762 (format "%%%.2X" sequence-element))
9763 (or (encode-coding-char char 'utf-8)
9764 (error "Unable to percent escape character: %s"
9765 (char-to-string char))) "")
9766 (char-to-string char))) text ""))
9768 (defun org-link-unescape (str)
9769 "Unhex hexified Unicode strings as returned from the JavaScript function
9770 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9771 (unless (and (null str) (string= "" str))
9772 (let ((pos 0) (case-fold-search t) unhexed)
9773 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9774 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9775 (setq str (replace-match unhexed t t str))
9776 (setq pos (+ pos (length unhexed))))))
9777 str)
9779 (defun org-link-unescape-compound (hex)
9780 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9781 Note: this function also decodes single byte encodings like
9782 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9783 (save-match-data
9784 (let* ((bytes (cdr (split-string hex "%")))
9785 (ret "")
9786 (eat 0)
9787 (sum 0))
9788 (while bytes
9789 (let* ((val (string-to-number (pop bytes) 16))
9790 (shift-xor
9791 (if (= 0 eat)
9792 (cond
9793 ((>= val 252) (cons 6 252))
9794 ((>= val 248) (cons 5 248))
9795 ((>= val 240) (cons 4 240))
9796 ((>= val 224) (cons 3 224))
9797 ((>= val 192) (cons 2 192))
9798 (t (cons 0 0)))
9799 (cons 6 128))))
9800 (if (>= val 192) (setq eat (car shift-xor)))
9801 (setq val (logxor val (cdr shift-xor)))
9802 (setq sum (+ (lsh sum (car shift-xor)) val))
9803 (if (> eat 0) (setq eat (- eat 1)))
9804 (cond
9805 ((= 0 eat) ;multi byte
9806 (setq ret (concat ret (org-char-to-string sum)))
9807 (setq sum 0))
9808 ((not bytes) ; single byte(s)
9809 (setq ret (org-link-unescape-single-byte-sequence hex))))
9810 )) ;; end (while bytes
9811 ret )))
9813 (defun org-link-unescape-single-byte-sequence (hex)
9814 "Unhexify hex-encoded single byte character sequences."
9815 (mapconcat (lambda (byte)
9816 (char-to-string (string-to-number byte 16)))
9817 (cdr (split-string hex "%")) ""))
9819 (defun org-xor (a b)
9820 "Exclusive or."
9821 (if a (not b) b))
9823 (defun org-fixup-message-id-for-http (s)
9824 "Replace special characters in a message id, so it can be used in an http query."
9825 (when (string-match "%" s)
9826 (setq s (mapconcat (lambda (c)
9827 (if (eq c ?%)
9828 "%25"
9829 (char-to-string c)))
9830 s "")))
9831 (while (string-match "<" s)
9832 (setq s (replace-match "%3C" t t s)))
9833 (while (string-match ">" s)
9834 (setq s (replace-match "%3E" t t s)))
9835 (while (string-match "@" s)
9836 (setq s (replace-match "%40" t t s)))
9839 (defun org-link-prettify (link)
9840 "Return a human-readable representation of LINK.
9841 The car of LINK must be a raw link the cdr of LINK must be either
9842 a link description or nil."
9843 (let ((desc (or (cadr link) "<no description>")))
9844 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9845 "<" (car link) ">")))
9847 ;;;###autoload
9848 (defun org-insert-link-global ()
9849 "Insert a link like Org-mode does.
9850 This command can be called in any mode to insert a link in Org-mode syntax."
9851 (interactive)
9852 (org-load-modules-maybe)
9853 (org-run-like-in-org-mode 'org-insert-link))
9855 (defun org-insert-all-links (&optional keep)
9856 "Insert all links in `org-stored-links'."
9857 (interactive "P")
9858 (let ((links (copy-sequence org-stored-links)) l)
9859 (while (setq l (if keep (pop links) (pop org-stored-links)))
9860 (insert "- ")
9861 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9862 (insert "\n"))))
9864 (defun org-link-fontify-links-to-this-file ()
9865 "Fontify links to the current file in `org-stored-links'."
9866 (let ((f (buffer-file-name)) a b)
9867 (setq a (mapcar (lambda(l)
9868 (let ((ll (car l)))
9869 (when (and (string-match "^file:\\(.+\\)::" ll)
9870 (equal f (expand-file-name (match-string 1 ll))))
9871 ll)))
9872 org-stored-links))
9873 (when (featurep 'org-id)
9874 (setq b (mapcar (lambda(l)
9875 (let ((ll (car l)))
9876 (when (and (string-match "^id:\\(.+\\)$" ll)
9877 (equal f (expand-file-name
9878 (or (org-id-find-id-file
9879 (match-string 1 ll)) ""))))
9880 ll)))
9881 org-stored-links)))
9882 (mapcar (lambda(l)
9883 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9884 (delq nil (append a b)))))
9886 (defvar org-link-links-in-this-file nil)
9887 (defun org-insert-link (&optional complete-file link-location default-description)
9888 "Insert a link. At the prompt, enter the link.
9890 Completion can be used to insert any of the link protocol prefixes like
9891 http or ftp in use.
9893 The history can be used to select a link previously stored with
9894 `org-store-link'. When the empty string is entered (i.e. if you just
9895 press RET at the prompt), the link defaults to the most recently
9896 stored link. As SPC triggers completion in the minibuffer, you need to
9897 use M-SPC or C-q SPC to force the insertion of a space character.
9899 You will also be prompted for a description, and if one is given, it will
9900 be displayed in the buffer instead of the link.
9902 If there is already a link at point, this command will allow you to edit link
9903 and description parts.
9905 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9906 be selected using completion. The path to the file will be relative to the
9907 current directory if the file is in the current directory or a subdirectory.
9908 Otherwise, the link will be the absolute path as completed in the minibuffer
9909 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9910 option `org-link-file-path-type'.
9912 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9913 the current directory or below.
9915 With three \\[universal-argument] prefixes, negate the meaning of
9916 `org-keep-stored-link-after-insertion'.
9918 If `org-make-link-description-function' is non-nil, this function will be
9919 called with the link target, and the result will be the default
9920 link description.
9922 If the LINK-LOCATION parameter is non-nil, this value will be
9923 used as the link location instead of reading one interactively.
9925 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9926 be used as the default description."
9927 (interactive "P")
9928 (let* ((wcf (current-window-configuration))
9929 (origbuf (current-buffer))
9930 (region (if (org-region-active-p)
9931 (buffer-substring (region-beginning) (region-end))))
9932 (remove (and region (list (region-beginning) (region-end))))
9933 (desc region)
9934 tmphist ; byte-compile incorrectly complains about this
9935 (link link-location)
9936 (abbrevs org-link-abbrev-alist-local)
9937 entry file all-prefixes auto-desc)
9938 (cond
9939 (link-location) ; specified by arg, just use it.
9940 ((org-in-regexp org-bracket-link-regexp 1)
9941 ;; We do have a link at point, and we are going to edit it.
9942 (setq remove (list (match-beginning 0) (match-end 0)))
9943 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9944 (setq link (read-string "Link: "
9945 (org-link-unescape
9946 (org-match-string-no-properties 1)))))
9947 ((or (org-in-regexp org-angle-link-re)
9948 (org-in-regexp org-plain-link-re))
9949 ;; Convert to bracket link
9950 (setq remove (list (match-beginning 0) (match-end 0))
9951 link (read-string "Link: "
9952 (org-remove-angle-brackets (match-string 0)))))
9953 ((member complete-file '((4) (16)))
9954 ;; Completing read for file names.
9955 (setq link (org-file-complete-link complete-file)))
9957 ;; Read link, with completion for stored links.
9958 (org-link-fontify-links-to-this-file)
9959 (org-switch-to-buffer-other-window "*Org Links*")
9960 (with-current-buffer "*Org Links*"
9961 (erase-buffer)
9962 (insert "Insert a link.
9963 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9964 (when org-stored-links
9965 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9966 (insert (mapconcat 'org-link-prettify
9967 (reverse org-stored-links) "\n")))
9968 (goto-char (point-min)))
9969 (let ((cw (selected-window)))
9970 (select-window (get-buffer-window "*Org Links*" 'visible))
9971 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9972 (unless (pos-visible-in-window-p (point-max))
9973 (org-fit-window-to-buffer))
9974 (and (window-live-p cw) (select-window cw)))
9975 ;; Fake a link history, containing the stored links.
9976 (setq tmphist (append (mapcar 'car org-stored-links)
9977 org-insert-link-history))
9978 (setq all-prefixes (append (mapcar 'car abbrevs)
9979 (mapcar 'car org-link-abbrev-alist)
9980 org-link-types))
9981 (unwind-protect
9982 (progn
9983 (setq link
9984 (org-completing-read
9985 "Link: "
9986 (append
9987 (mapcar (lambda (x) (concat x ":"))
9988 all-prefixes)
9989 (mapcar 'car org-stored-links))
9990 nil nil nil
9991 'tmphist
9992 (caar org-stored-links)))
9993 (if (not (string-match "\\S-" link))
9994 (user-error "No link selected"))
9995 (mapc (lambda(l)
9996 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9997 org-stored-links)
9998 (if (or (member link all-prefixes)
9999 (and (equal ":" (substring link -1))
10000 (member (substring link 0 -1) all-prefixes)
10001 (setq link (substring link 0 -1))))
10002 (setq link (with-current-buffer origbuf
10003 (org-link-try-special-completion link)))))
10004 (set-window-configuration wcf)
10005 (kill-buffer "*Org Links*"))
10006 (setq entry (assoc link org-stored-links))
10007 (or entry (push link org-insert-link-history))
10008 (setq desc (or desc (nth 1 entry)))))
10010 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10011 (not org-keep-stored-link-after-insertion))
10012 (setq org-stored-links (delq (assoc link org-stored-links)
10013 org-stored-links)))
10015 (if (string-match org-plain-link-re link)
10016 ;; URL-like link, normalize the use of angular brackets.
10017 (setq link (org-remove-angle-brackets link)))
10019 ;; Check if we are linking to the current file with a search
10020 ;; option If yes, simplify the link by using only the search
10021 ;; option.
10022 (when (and buffer-file-name
10023 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10024 (let* ((path (match-string 1 link))
10025 (case-fold-search nil)
10026 (search (match-string 2 link)))
10027 (save-match-data
10028 (if (equal (file-truename buffer-file-name) (file-truename path))
10029 ;; We are linking to this same file, with a search option
10030 (setq link search)))))
10032 ;; Check if we can/should use a relative path. If yes, simplify the link
10033 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10034 (let* ((type (match-string 1 link))
10035 (path (match-string 2 link))
10036 (origpath path)
10037 (case-fold-search nil))
10038 (cond
10039 ((or (eq org-link-file-path-type 'absolute)
10040 (equal complete-file '(16)))
10041 (setq path (abbreviate-file-name (expand-file-name path))))
10042 ((eq org-link-file-path-type 'noabbrev)
10043 (setq path (expand-file-name path)))
10044 ((eq org-link-file-path-type 'relative)
10045 (setq path (file-relative-name path)))
10047 (save-match-data
10048 (if (string-match (concat "^" (regexp-quote
10049 (expand-file-name
10050 (file-name-as-directory
10051 default-directory))))
10052 (expand-file-name path))
10053 ;; We are linking a file with relative path name.
10054 (setq path (substring (expand-file-name path)
10055 (match-end 0)))
10056 (setq path (abbreviate-file-name (expand-file-name path)))))))
10057 (setq link (concat type path))
10058 (if (equal desc origpath)
10059 (setq desc path))))
10061 (if org-make-link-description-function
10062 (setq desc
10063 (or (condition-case nil
10064 (funcall org-make-link-description-function link desc)
10065 (error (progn (message "Can't get link description from `%s'"
10066 (symbol-name org-make-link-description-function))
10067 (sit-for 2) nil)))
10068 (read-string "Description: " default-description)))
10069 (if default-description (setq desc default-description)
10070 (setq desc (or (and auto-desc desc)
10071 (read-string "Description: " desc)))))
10073 (unless (string-match "\\S-" desc) (setq desc nil))
10074 (if remove (apply 'delete-region remove))
10075 (insert (org-make-link-string link desc))))
10077 (defun org-link-try-special-completion (type)
10078 "If there is completion support for link type TYPE, offer it."
10079 (let ((fun (intern (concat "org-" type "-complete-link"))))
10080 (if (functionp fun)
10081 (funcall fun)
10082 (read-string "Link (no completion support): " (concat type ":")))))
10084 (defun org-file-complete-link (&optional arg)
10085 "Create a file link using completion."
10086 (let (file link)
10087 (setq file (org-iread-file-name "File: "))
10088 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10089 (pwd1 (file-name-as-directory (abbreviate-file-name
10090 (expand-file-name ".")))))
10091 (cond
10092 ((equal arg '(16))
10093 (setq link (concat
10094 "file:"
10095 (abbreviate-file-name (expand-file-name file)))))
10096 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10097 (setq link (concat "file:" (match-string 1 file))))
10098 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10099 (expand-file-name file))
10100 (setq link (concat
10101 "file:" (match-string 1 (expand-file-name file)))))
10102 (t (setq link (concat "file:" file)))))
10103 link))
10105 (defun org-iread-file-name (&rest args)
10106 "Read-file-name using `ido-mode' speedup if available.
10107 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10108 See `read-file-name' for a description of parameters."
10109 (org-without-partial-completion
10110 (if (and org-completion-use-ido
10111 (fboundp 'ido-read-file-name)
10112 (boundp 'ido-mode) ido-mode
10113 (listp (second args)))
10114 (let ((ido-enter-matching-directory nil))
10115 (apply 'ido-read-file-name args))
10116 (apply 'read-file-name args))))
10118 (defun org-completing-read (&rest args)
10119 "Completing-read with SPACE being a normal character."
10120 (let ((enable-recursive-minibuffers t)
10121 (minibuffer-local-completion-map
10122 (copy-keymap minibuffer-local-completion-map)))
10123 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10124 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10125 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10126 (apply 'org-icompleting-read args)))
10128 (defun org-completing-read-no-i (&rest args)
10129 (let (org-completion-use-ido org-completion-use-iswitchb)
10130 (apply 'org-completing-read args)))
10132 (defun org-iswitchb-completing-read (prompt choices &rest args)
10133 "Use iswitch as a completing-read replacement to choose from choices.
10134 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10135 from."
10136 (let* ((iswitchb-use-virtual-buffers nil)
10137 (iswitchb-make-buflist-hook
10138 (lambda ()
10139 (setq iswitchb-temp-buflist choices))))
10140 (iswitchb-read-buffer prompt)))
10142 (defun org-icompleting-read (&rest args)
10143 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10144 (org-without-partial-completion
10145 (if (and org-completion-use-ido
10146 (fboundp 'ido-completing-read)
10147 (boundp 'ido-mode) ido-mode
10148 (listp (second args)))
10149 (let ((ido-enter-matching-directory nil))
10150 (apply 'ido-completing-read (concat (car args))
10151 (if (consp (car (nth 1 args)))
10152 (mapcar 'car (nth 1 args))
10153 (nth 1 args))
10154 (cddr args)))
10155 (if (and org-completion-use-iswitchb
10156 (boundp 'iswitchb-mode) iswitchb-mode
10157 (listp (second args)))
10158 (apply 'org-iswitchb-completing-read (concat (car args))
10159 (if (consp (car (nth 1 args)))
10160 (mapcar 'car (nth 1 args))
10161 (nth 1 args))
10162 (cddr args))
10163 (apply 'completing-read args)))))
10165 (defun org-extract-attributes (s)
10166 "Extract the attributes cookie from a string and set as text property."
10167 (let (a attr (start 0) key value)
10168 (save-match-data
10169 (when (string-match "{{\\([^}]+\\)}}$" s)
10170 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10171 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10172 (setq key (match-string 1 a) value (match-string 2 a)
10173 start (match-end 0)
10174 attr (plist-put attr (intern key) value))))
10175 (org-add-props s nil 'org-attr attr))
10178 ;;; Opening/following a link
10180 (defvar org-link-search-failed nil)
10182 (defvar org-open-link-functions nil
10183 "Hook for functions finding a plain text link.
10184 These functions must take a single argument, the link content.
10185 They will be called for links that look like [[link text][description]]
10186 when LINK TEXT does not have a protocol like \"http:\" and does not look
10187 like a filename (e.g. \"./blue.png\").
10189 These functions will be called *before* Org attempts to resolve the
10190 link by doing text searches in the current buffer - so if you want a
10191 link \"[[target]]\" to still find \"<<target>>\", your function should
10192 handle this as a special case.
10194 When the function does handle the link, it must return a non-nil value.
10195 If it decides that it is not responsible for this link, it must return
10196 nil to indicate that that Org-mode can continue with other options
10197 like exact and fuzzy text search.")
10199 (defun org-next-link (&optional search-backward)
10200 "Move forward to the next link.
10201 If the link is in hidden text, expose it."
10202 (interactive "P")
10203 (when (and org-link-search-failed (eq this-command last-command))
10204 (goto-char (point-min))
10205 (message "Link search wrapped back to beginning of buffer"))
10206 (setq org-link-search-failed nil)
10207 (let* ((pos (point))
10208 (ct (org-context))
10209 (a (assoc :link ct))
10210 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10211 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10212 ((looking-at org-any-link-re)
10213 ;; Don't stay stuck at link without an org-link face
10214 (forward-char (if search-backward -1 1))))
10215 (if (funcall srch-fun org-any-link-re nil t)
10216 (progn
10217 (goto-char (match-beginning 0))
10218 (if (outline-invisible-p) (org-show-context)))
10219 (goto-char pos)
10220 (setq org-link-search-failed t)
10221 (message "No further link found"))))
10223 (defun org-previous-link ()
10224 "Move backward to the previous link.
10225 If the link is in hidden text, expose it."
10226 (interactive)
10227 (funcall 'org-next-link t))
10229 (defun org-translate-link (s)
10230 "Translate a link string if a translation function has been defined."
10231 (if (and org-link-translation-function
10232 (fboundp org-link-translation-function)
10233 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10234 (progn
10235 (setq s (funcall org-link-translation-function
10236 (match-string 1 s) (match-string 2 s)))
10237 (concat (car s) ":" (cdr s)))
10240 (defun org-translate-link-from-planner (type path)
10241 "Translate a link from Emacs Planner syntax so that Org can follow it.
10242 This is still an experimental function, your mileage may vary."
10243 (cond
10244 ((member type '("http" "https" "news" "ftp"))
10245 ;; standard Internet links are the same.
10246 nil)
10247 ((and (equal type "irc") (string-match "^//" path))
10248 ;; Planner has two / at the beginning of an irc link, we have 1.
10249 ;; We should have zero, actually....
10250 (setq path (substring path 1)))
10251 ((and (equal type "lisp") (string-match "^/" path))
10252 ;; Planner has a slash, we do not.
10253 (setq type "elisp" path (substring path 1)))
10254 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10255 ;; A typical message link. Planner has the id after the final slash,
10256 ;; we separate it with a hash mark
10257 (setq path (concat (match-string 1 path) "#"
10258 (org-remove-angle-brackets (match-string 2 path))))))
10259 (cons type path))
10261 (defun org-find-file-at-mouse (ev)
10262 "Open file link or URL at mouse."
10263 (interactive "e")
10264 (mouse-set-point ev)
10265 (org-open-at-point 'in-emacs))
10267 (defun org-open-at-mouse (ev)
10268 "Open file link or URL at mouse.
10269 See the docstring of `org-open-file' for details."
10270 (interactive "e")
10271 (mouse-set-point ev)
10272 (if (eq major-mode 'org-agenda-mode)
10273 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10274 (org-open-at-point))
10276 (defvar org-window-config-before-follow-link nil
10277 "The window configuration before following a link.
10278 This is saved in case the need arises to restore it.")
10280 (defvar org-open-link-marker (make-marker)
10281 "Marker pointing to the location where `org-open-at-point; was called.")
10283 ;;;###autoload
10284 (defun org-open-at-point-global ()
10285 "Follow a link like Org-mode does.
10286 This command can be called in any mode to follow a link that has
10287 Org-mode syntax."
10288 (interactive)
10289 (org-run-like-in-org-mode 'org-open-at-point))
10291 ;;;###autoload
10292 (defun org-open-link-from-string (s &optional arg reference-buffer)
10293 "Open a link in the string S, as if it was in Org-mode."
10294 (interactive "sLink: \nP")
10295 (let ((reference-buffer (or reference-buffer (current-buffer))))
10296 (with-temp-buffer
10297 (let ((org-inhibit-startup (not reference-buffer)))
10298 (org-mode)
10299 (insert s)
10300 (goto-char (point-min))
10301 (when reference-buffer
10302 (setq org-link-abbrev-alist-local
10303 (with-current-buffer reference-buffer
10304 org-link-abbrev-alist-local)))
10305 (org-open-at-point arg reference-buffer)))))
10307 (defvar org-open-at-point-functions nil
10308 "Hook that is run when following a link at point.
10310 Functions in this hook must return t if they identify and follow
10311 a link at point. If they don't find anything interesting at point,
10312 they must return nil.")
10314 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10315 (defun org-open-at-point (&optional arg reference-buffer)
10316 "Open link at or after point.
10317 If there is no link at point, this function will search forward up to
10318 the end of the current line.
10319 Normally, files will be opened by an appropriate application. If the
10320 optional prefix argument ARG is non-nil, Emacs will visit the file.
10321 With a double prefix argument, try to open outside of Emacs, in the
10322 application the system uses for this file type."
10323 (interactive "P")
10324 ;; if in a code block, then open the block's results
10325 (unless (call-interactively #'org-babel-open-src-block-result)
10326 (org-load-modules-maybe)
10327 (move-marker org-open-link-marker (point))
10328 (setq org-window-config-before-follow-link (current-window-configuration))
10329 (org-remove-occur-highlights nil nil t)
10330 (cond
10331 ((and (org-at-heading-p)
10332 (not (org-at-timestamp-p t))
10333 (not (org-in-regexp
10334 (concat org-plain-link-re "\\|"
10335 org-bracket-link-regexp "\\|"
10336 org-angle-link-re "\\|"
10337 "[ \t]:[^ \t\n]+:[ \t]*$")))
10338 (not (get-text-property (point) 'org-linked-text)))
10339 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10340 (lk0 (car lkall))
10341 (lk (if (stringp lk0) (list lk0) lk0))
10342 (lkend (cdr lkall)))
10343 (mapcar (lambda(l)
10344 (search-forward l nil lkend)
10345 (goto-char (match-beginning 0))
10346 (org-open-at-point))
10347 lk))
10348 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10349 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10350 ((and (org-at-timestamp-p t)
10351 (not (org-in-regexp org-bracket-link-regexp)))
10352 (org-follow-timestamp-link))
10353 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10354 (not (org-in-regexp org-any-link-re)))
10355 (org-footnote-action))
10357 (let (type path link line search (pos (point)))
10358 (catch 'match
10359 (save-excursion
10360 (skip-chars-forward "^]\n\r")
10361 (when (org-in-regexp org-bracket-link-regexp 1)
10362 (setq link (org-extract-attributes
10363 (org-link-unescape (org-match-string-no-properties 1))))
10364 (while (string-match " *\n *" link)
10365 (setq link (replace-match " " t t link)))
10366 (setq link (org-link-expand-abbrev link))
10367 (cond
10368 ((or (file-name-absolute-p link)
10369 (string-match "^\\.\\.?/" link))
10370 (setq type "file" path link))
10371 ((string-match org-link-re-with-space3 link)
10372 (setq type (match-string 1 link) path (match-string 2 link)))
10373 ((string-match "^help:+\\(.+\\)" link)
10374 (setq type "help" path (match-string 1 link)))
10375 (t (setq type "thisfile" path link)))
10376 (throw 'match t)))
10378 (when (get-text-property (point) 'org-linked-text)
10379 (setq type "thisfile"
10380 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10381 (1+ (point)) (point))
10382 path (buffer-substring
10383 (or (previous-single-property-change pos 'org-linked-text)
10384 (point-min))
10385 (or (next-single-property-change pos 'org-linked-text)
10386 (point-max)))
10387 ;; Ensure we will search for a <<<radio>>> link, not
10388 ;; a simple reference like <<ref>>
10389 path (concat "<" path))
10390 (throw 'match t))
10392 (save-excursion
10393 (when (or (org-in-regexp org-angle-link-re)
10394 (let ((match (org-in-regexp org-plain-link-re)))
10395 ;; Check a plain link is not within a bracket link
10396 (and match
10397 (save-excursion
10398 (progn
10399 (goto-char (car match))
10400 (not (org-in-regexp org-bracket-link-regexp))))))
10401 (let ((line_ending (save-excursion (end-of-line) (point))))
10402 ;; We are in a line before a plain or bracket link
10403 (or (re-search-forward org-plain-link-re line_ending t)
10404 (re-search-forward org-bracket-link-regexp line_ending t))))
10405 (setq type (match-string 1)
10406 path (org-link-unescape (match-string 2)))
10407 (throw 'match t)))
10408 (save-excursion
10409 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10410 (setq type "tags"
10411 path (match-string 1))
10412 (while (string-match ":" path)
10413 (setq path (replace-match "+" t t path)))
10414 (throw 'match t)))
10415 (when (org-in-regexp "<\\([^><\n]+\\)>")
10416 (setq type "tree-match"
10417 path (match-string 1))
10418 (throw 'match t)))
10419 (unless path
10420 (user-error "No link found"))
10422 ;; switch back to reference buffer
10423 ;; needed when if called in a temporary buffer through
10424 ;; org-open-link-from-string
10425 (with-current-buffer (or reference-buffer (current-buffer))
10427 ;; Remove any trailing spaces in path
10428 (if (string-match " +\\'" path)
10429 (setq path (replace-match "" t t path)))
10430 (if (and org-link-translation-function
10431 (fboundp org-link-translation-function))
10432 ;; Check if we need to translate the link
10433 (let ((tmp (funcall org-link-translation-function type path)))
10434 (setq type (car tmp) path (cdr tmp))))
10436 (cond
10438 ((assoc type org-link-protocols)
10439 (funcall (nth 1 (assoc type org-link-protocols)) path))
10441 ((equal type "help")
10442 (let ((f-or-v (intern path)))
10443 (cond ((fboundp f-or-v)
10444 (describe-function f-or-v))
10445 ((boundp f-or-v)
10446 (describe-variable f-or-v))
10447 (t (error "Not a known function or variable")))))
10449 ((equal type "mailto")
10450 (let ((cmd (car org-link-mailto-program))
10451 (args (cdr org-link-mailto-program)) args1
10452 (address path) (subject "") a)
10453 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10454 (setq address (match-string 1 path)
10455 subject (org-link-escape (match-string 2 path))))
10456 (while args
10457 (cond
10458 ((not (stringp (car args))) (push (pop args) args1))
10459 (t (setq a (pop args))
10460 (if (string-match "%a" a)
10461 (setq a (replace-match address t t a)))
10462 (if (string-match "%s" a)
10463 (setq a (replace-match subject t t a)))
10464 (push a args1))))
10465 (apply cmd (nreverse args1))))
10467 ((member type '("http" "https" "ftp" "news"))
10468 (browse-url
10469 (concat type ":"
10470 (if (org-string-match-p
10471 (concat "[[:nonascii:]"
10472 org-link-escape-chars-browser "]")
10473 path)
10474 (org-link-escape path org-link-escape-chars-browser)
10475 path))))
10477 ((string= type "doi")
10478 (browse-url
10479 (concat org-doi-server-url
10480 (if (org-string-match-p
10481 (concat "[[:nonascii:]"
10482 org-link-escape-chars-browser "]")
10483 path)
10484 (org-link-escape path org-link-escape-chars-browser)
10485 path))))
10487 ((member type '("message"))
10488 (browse-url (concat type ":" path)))
10490 ((string= type "tags")
10491 (org-tags-view arg path))
10493 ((string= type "tree-match")
10494 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10496 ((string= type "file")
10497 (if (string-match "::\\([0-9]+\\)\\'" path)
10498 (setq line (string-to-number (match-string 1 path))
10499 path (substring path 0 (match-beginning 0)))
10500 (if (string-match "::\\(.+\\)\\'" path)
10501 (setq search (match-string 1 path)
10502 path (substring path 0 (match-beginning 0)))))
10503 (if (string-match "[*?{]" (file-name-nondirectory path))
10504 (dired path)
10505 (org-open-file path arg line search)))
10507 ((string= type "shell")
10508 (let ((buf (generate-new-buffer "*Org Shell Output"))
10509 (cmd path))
10510 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10511 (string-match org-confirm-shell-link-not-regexp cmd))
10512 (not org-confirm-shell-link-function)
10513 (funcall org-confirm-shell-link-function
10514 (format "Execute \"%s\" in shell? "
10515 (org-add-props cmd nil
10516 'face 'org-warning))))
10517 (progn
10518 (message "Executing %s" cmd)
10519 (shell-command cmd buf)
10520 (if (featurep 'midnight)
10521 (setq clean-buffer-list-kill-buffer-names
10522 (cons buf clean-buffer-list-kill-buffer-names))))
10523 (error "Abort"))))
10525 ((string= type "elisp")
10526 (let ((cmd path))
10527 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10528 (string-match org-confirm-elisp-link-not-regexp cmd))
10529 (not org-confirm-elisp-link-function)
10530 (funcall org-confirm-elisp-link-function
10531 (format "Execute \"%s\" as elisp? "
10532 (org-add-props cmd nil
10533 'face 'org-warning))))
10534 (message "%s => %s" cmd
10535 (if (equal (string-to-char cmd) ?\()
10536 (eval (read cmd))
10537 (call-interactively (read cmd))))
10538 (error "Abort"))))
10540 ((and (string= type "thisfile")
10541 (or (run-hook-with-args-until-success
10542 'org-open-link-functions path)
10543 (and (string-match "^id:" link)
10544 (or (featurep 'org-id) (require 'org-id))
10545 (progn
10546 (funcall (nth 1 (assoc "id" org-link-protocols))
10547 (substring path 3))
10548 t)))))
10550 ((string= type "thisfile")
10551 (if arg
10552 (switch-to-buffer-other-window
10553 (org-get-buffer-for-internal-link (current-buffer)))
10554 (org-mark-ring-push))
10555 (let ((cmd `(org-link-search
10556 ,path
10557 ,(cond ((equal arg '(4)) ''occur)
10558 ((equal arg '(16)) ''org-occur))
10559 ,pos)))
10560 (condition-case nil (let ((org-link-search-inhibit-query t))
10561 (eval cmd))
10562 (error (progn (widen) (eval cmd))))))
10564 (t (browse-url-at-point)))))))
10565 (move-marker org-open-link-marker nil)
10566 (run-hook-with-args 'org-follow-link-hook)))
10568 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10569 "Offer links in the current entry and return the selected link.
10570 If there is only one link, return it.
10571 If NTH is an integer, return the NTH link found.
10572 If ZERO is a string, check also this string for a link, and if
10573 there is one, return it."
10574 (with-current-buffer buffer
10575 (save-excursion
10576 (save-restriction
10577 (widen)
10578 (goto-char marker)
10579 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10580 "\\(" org-angle-link-re "\\)\\|"
10581 "\\(" org-plain-link-re "\\)"))
10582 (cnt ?0)
10583 (in-emacs (if (integerp nth) nil nth))
10584 have-zero end links link c)
10585 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10586 (push (match-string 0 zero) links)
10587 (setq cnt (1- cnt) have-zero t))
10588 (save-excursion
10589 (org-back-to-heading t)
10590 (setq end (save-excursion (outline-next-heading) (point)))
10591 (while (re-search-forward re end t)
10592 (push (match-string 0) links))
10593 (setq links (org-uniquify (reverse links))))
10594 (cond
10595 ((null links)
10596 (message "No links"))
10597 ((equal (length links) 1)
10598 (setq link (car links)))
10599 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10600 (setq link (nth (if have-zero nth (1- nth)) links)))
10601 (t ; we have to select a link
10602 (save-excursion
10603 (save-window-excursion
10604 (delete-other-windows)
10605 (with-output-to-temp-buffer "*Select Link*"
10606 (mapc (lambda (l)
10607 (if (not (string-match org-bracket-link-regexp l))
10608 (princ (format "[%c] %s\n" (incf cnt)
10609 (org-remove-angle-brackets l)))
10610 (if (match-end 3)
10611 (princ (format "[%c] %s (%s)\n" (incf cnt)
10612 (match-string 3 l) (match-string 1 l)))
10613 (princ (format "[%c] %s\n" (incf cnt)
10614 (match-string 1 l))))))
10615 links))
10616 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10617 (message "Select link to open, RET to open all:")
10618 (setq c (read-char-exclusive))
10619 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10620 (when (equal c ?q) (error "Abort"))
10621 (if (equal c ?\C-m)
10622 (setq link links)
10623 (setq nth (- c ?0))
10624 (if have-zero (setq nth (1+ nth)))
10625 (unless (and (integerp nth) (>= (length links) nth))
10626 (user-error "Invalid link selection"))
10627 (setq link (nth (1- nth) links)))))
10628 (cons link end))))))
10630 ;; Add special file links that specify the way of opening
10632 (org-add-link-type "file+sys" 'org-open-file-with-system)
10633 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10634 (defun org-open-file-with-system (path)
10635 "Open file at PATH using the system way of opening it."
10636 (org-open-file path 'system))
10637 (defun org-open-file-with-emacs (path)
10638 "Open file at PATH in Emacs."
10639 (org-open-file path 'emacs))
10642 ;;; File search
10644 (defvar org-create-file-search-functions nil
10645 "List of functions to construct the right search string for a file link.
10646 These functions are called in turn with point at the location to
10647 which the link should point.
10649 A function in the hook should first test if it would like to
10650 handle this file type, for example by checking the `major-mode'
10651 or the file extension. If it decides not to handle this file, it
10652 should just return nil to give other functions a chance. If it
10653 does handle the file, it must return the search string to be used
10654 when following the link. The search string will be part of the
10655 file link, given after a double colon, and `org-open-at-point'
10656 will automatically search for it. If special measures must be
10657 taken to make the search successful, another function should be
10658 added to the companion hook `org-execute-file-search-functions',
10659 which see.
10661 A function in this hook may also use `setq' to set the variable
10662 `description' to provide a suggestion for the descriptive text to
10663 be used for this link when it gets inserted into an Org-mode
10664 buffer with \\[org-insert-link].")
10666 (defvar org-execute-file-search-functions nil
10667 "List of functions to execute a file search triggered by a link.
10669 Functions added to this hook must accept a single argument, the
10670 search string that was part of the file link, the part after the
10671 double colon. The function must first check if it would like to
10672 handle this search, for example by checking the `major-mode' or
10673 the file extension. If it decides not to handle this search, it
10674 should just return nil to give other functions a chance. If it
10675 does handle the search, it must return a non-nil value to keep
10676 other functions from trying.
10678 Each function can access the current prefix argument through the
10679 variable `current-prefix-arg'. Note that a single prefix is used
10680 to force opening a link in Emacs, so it may be good to only use a
10681 numeric or double prefix to guide the search function.
10683 In case this is needed, a function in this hook can also restore
10684 the window configuration before `org-open-at-point' was called using:
10686 (set-window-configuration org-window-config-before-follow-link)")
10688 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10689 (defun org-link-search (s &optional type avoid-pos stealth)
10690 "Search for a link search option.
10691 If S is surrounded by forward slashes, it is interpreted as a
10692 regular expression. In org-mode files, this will create an `org-occur'
10693 sparse tree. In ordinary files, `occur' will be used to list matches.
10694 If the current buffer is in `dired-mode', grep will be used to search
10695 in all files. If AVOID-POS is given, ignore matches near that position.
10697 When optional argument STEALTH is non-nil, do not modify
10698 visibility around point, thus ignoring
10699 `org-show-hierarchy-above', `org-show-following-heading' and
10700 `org-show-siblings' variables."
10701 (let ((case-fold-search t)
10702 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10703 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10704 (append '(("") (" ") ("\t") ("\n"))
10705 org-emphasis-alist)
10706 "\\|") "\\)"))
10707 (pos (point))
10708 (pre nil) (post nil)
10709 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10710 (cond
10711 ;; First check if there are any special search functions
10712 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10713 ;; Now try the builtin stuff
10714 ((and (equal (string-to-char s0) ?#)
10715 (> (length s0) 1)
10716 (save-excursion
10717 (goto-char (point-min))
10718 (and
10719 (re-search-forward
10720 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10721 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10722 (setq type 'dedicated
10723 pos (match-beginning 0))))
10724 ;; There is an exact target for this
10725 (goto-char pos)
10726 (org-back-to-heading t)))
10727 ((save-excursion
10728 (goto-char (point-min))
10729 (and
10730 (re-search-forward
10731 (concat "<<" (regexp-quote s0) ">>") nil t)
10732 (setq type 'dedicated
10733 pos (match-beginning 0))))
10734 ;; There is an exact target for this
10735 (goto-char pos))
10736 ((save-excursion
10737 (goto-char (point-min))
10738 (and
10739 (re-search-forward
10740 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10741 (setq type 'dedicated pos (match-beginning 0))))
10742 ;; Found an element with a matching #+name affiliated keyword.
10743 (goto-char pos))
10744 ((and (string-match "^(\\(.*\\))$" s0)
10745 (save-excursion
10746 (goto-char (point-min))
10747 (and
10748 (re-search-forward
10749 (concat "[^[]" (regexp-quote
10750 (format org-coderef-label-format
10751 (match-string 1 s0))))
10752 nil t)
10753 (setq type 'dedicated
10754 pos (1+ (match-beginning 0))))))
10755 ;; There is a coderef target for this
10756 (goto-char pos))
10757 ((string-match "^/\\(.*\\)/$" s)
10758 ;; A regular expression
10759 (cond
10760 ((derived-mode-p 'org-mode)
10761 (org-occur (match-string 1 s)))
10762 (t (org-do-occur (match-string 1 s)))))
10763 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10764 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10765 (goto-char (point-min))
10766 (cond
10767 ((let (case-fold-search)
10768 (re-search-forward (format org-complex-heading-regexp-format
10769 (regexp-quote s))
10770 nil t))
10771 ;; OK, found a match
10772 (setq type 'dedicated)
10773 (goto-char (match-beginning 0)))
10774 ((and (not org-link-search-inhibit-query)
10775 (eq org-link-search-must-match-exact-headline 'query-to-create)
10776 (y-or-n-p "No match - create this as a new heading? "))
10777 (goto-char (point-max))
10778 (or (bolp) (newline))
10779 (insert "* " s "\n")
10780 (beginning-of-line 0))
10782 (goto-char pos)
10783 (error "No match"))))
10785 ;; A normal search string
10786 (when (equal (string-to-char s) ?*)
10787 ;; Anchor on headlines, post may include tags.
10788 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10789 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10790 s (substring s 1)))
10791 (remove-text-properties
10792 0 (length s)
10793 '(face nil mouse-face nil keymap nil fontified nil) s)
10794 ;; Make a series of regular expressions to find a match
10795 (setq words (org-split-string s "[ \n\r\t]+")
10797 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10798 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10799 "\\)" markers)
10800 re2a_ (concat "\\(" (mapconcat 'downcase words
10801 "[ \t\r\n]+") "\\)[ \t\r\n]")
10802 re2a (concat "[ \t\r\n]" re2a_)
10803 re4_ (concat "\\(" (mapconcat 'downcase words
10804 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10805 re4 (concat "[^a-zA-Z_]" re4_)
10807 re1 (concat pre re2 post)
10808 re3 (concat pre (if pre re4_ re4) post)
10809 re5 (concat pre ".*" re4)
10810 re2 (concat pre re2)
10811 re2a (concat pre (if pre re2a_ re2a))
10812 re4 (concat pre (if pre re4_ re4))
10813 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10814 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10815 re5 "\\)"))
10816 (cond
10817 ((eq type 'org-occur) (org-occur reall))
10818 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10819 (t (goto-char (point-min))
10820 (setq type 'fuzzy)
10821 (if (or (and (org-search-not-self 1 re0 nil t)
10822 (setq type 'dedicated))
10823 (org-search-not-self 1 re1 nil t)
10824 (org-search-not-self 1 re2 nil t)
10825 (org-search-not-self 1 re2a nil t)
10826 (org-search-not-self 1 re3 nil t)
10827 (org-search-not-self 1 re4 nil t)
10828 (org-search-not-self 1 re5 nil t))
10829 (goto-char (match-beginning 1))
10830 (goto-char pos)
10831 (error "No match"))))))
10832 (and (derived-mode-p 'org-mode)
10833 (not stealth)
10834 (org-show-context 'link-search))
10835 type))
10837 (defun org-search-not-self (group &rest args)
10838 "Execute `re-search-forward', but only accept matches that do not
10839 enclose the position of `org-open-link-marker'."
10840 (let ((m org-open-link-marker))
10841 (catch 'exit
10842 (while (apply 're-search-forward args)
10843 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10844 (goto-char (match-end group))
10845 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10846 (> (match-beginning 0) (marker-position m))
10847 (< (match-end 0) (marker-position m)))
10848 (save-match-data
10849 (or (not (org-in-regexp
10850 org-bracket-link-analytic-regexp 1))
10851 (not (match-end 4)) ; no description
10852 (and (<= (match-beginning 4) (point))
10853 (>= (match-end 4) (point))))))
10854 (throw 'exit (point))))))))
10856 (defun org-get-buffer-for-internal-link (buffer)
10857 "Return a buffer to be used for displaying the link target of internal links."
10858 (cond
10859 ((not org-display-internal-link-with-indirect-buffer)
10860 buffer)
10861 ((string-match "(Clone)$" (buffer-name buffer))
10862 (message "Buffer is already a clone, not making another one")
10863 ;; we also do not modify visibility in this case
10864 buffer)
10865 (t ; make a new indirect buffer for displaying the link
10866 (let* ((bn (buffer-name buffer))
10867 (ibn (concat bn "(Clone)"))
10868 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10869 (with-current-buffer ib (org-overview))
10870 ib))))
10872 (defun org-do-occur (regexp &optional cleanup)
10873 "Call the Emacs command `occur'.
10874 If CLEANUP is non-nil, remove the printout of the regular expression
10875 in the *Occur* buffer. This is useful if the regex is long and not useful
10876 to read."
10877 (occur regexp)
10878 (when cleanup
10879 (let ((cwin (selected-window)) win beg end)
10880 (when (setq win (get-buffer-window "*Occur*"))
10881 (select-window win))
10882 (goto-char (point-min))
10883 (when (re-search-forward "match[a-z]+" nil t)
10884 (setq beg (match-end 0))
10885 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10886 (setq end (1- (match-beginning 0)))))
10887 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10888 (goto-char (point-min))
10889 (select-window cwin))))
10891 ;;; The mark ring for links jumps
10893 (defvar org-mark-ring nil
10894 "Mark ring for positions before jumps in Org-mode.")
10895 (defvar org-mark-ring-last-goto nil
10896 "Last position in the mark ring used to go back.")
10897 ;; Fill and close the ring
10898 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10899 (loop for i from 1 to org-mark-ring-length do
10900 (push (make-marker) org-mark-ring))
10901 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10902 org-mark-ring)
10904 (defun org-mark-ring-push (&optional pos buffer)
10905 "Put the current position or POS into the mark ring and rotate it."
10906 (interactive)
10907 (setq pos (or pos (point)))
10908 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10909 (move-marker (car org-mark-ring)
10910 (or pos (point))
10911 (or buffer (current-buffer)))
10912 (message "%s"
10913 (substitute-command-keys
10914 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10916 (defun org-mark-ring-goto (&optional n)
10917 "Jump to the previous position in the mark ring.
10918 With prefix arg N, jump back that many stored positions. When
10919 called several times in succession, walk through the entire ring.
10920 Org-mode commands jumping to a different position in the current file,
10921 or to another Org-mode file, automatically push the old position
10922 onto the ring."
10923 (interactive "p")
10924 (let (p m)
10925 (if (eq last-command this-command)
10926 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10927 (setq p org-mark-ring))
10928 (setq org-mark-ring-last-goto p)
10929 (setq m (car p))
10930 (org-pop-to-buffer-same-window (marker-buffer m))
10931 (goto-char m)
10932 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10934 (defun org-remove-angle-brackets (s)
10935 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10936 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10938 (defun org-add-angle-brackets (s)
10939 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10940 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10942 (defun org-remove-double-quotes (s)
10943 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10944 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10947 ;;; Following specific links
10949 (defun org-follow-timestamp-link ()
10950 "Open an agenda view for the time-stamp date/range at point."
10951 (cond
10952 ((org-at-date-range-p t)
10953 (let ((org-agenda-start-on-weekday)
10954 (t1 (match-string 1))
10955 (t2 (match-string 2)) tt1 tt2)
10956 (setq tt1 (time-to-days (org-time-string-to-time t1))
10957 tt2 (time-to-days (org-time-string-to-time t2)))
10958 (let ((org-agenda-buffer-tmp-name
10959 (format "*Org Agenda(a:%s)"
10960 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10961 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10962 ((org-at-timestamp-p t)
10963 (let ((org-agenda-buffer-tmp-name
10964 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10965 (org-agenda-list nil (time-to-days (org-time-string-to-time
10966 (substring (match-string 1) 0 10)))
10967 1)))
10968 (t (error "This should not happen"))))
10971 ;;; Following file links
10972 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10973 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10974 (declare-function mailcap-mime-info
10975 "mailcap" (string &optional request no-decode))
10976 (defvar org-wait nil)
10977 (defun org-open-file (path &optional in-emacs line search)
10978 "Open the file at PATH.
10979 First, this expands any special file name abbreviations. Then the
10980 configuration variable `org-file-apps' is checked if it contains an
10981 entry for this file type, and if yes, the corresponding command is launched.
10983 If no application is found, Emacs simply visits the file.
10985 With optional prefix argument IN-EMACS, Emacs will visit the file.
10986 With a double \\[universal-argument] \\[universal-argument] \
10987 prefix arg, Org tries to avoid opening in Emacs
10988 and to use an external application to visit the file.
10990 Optional LINE specifies a line to go to, optional SEARCH a string
10991 to search for. If LINE or SEARCH is given, the file will be
10992 opened in Emacs, unless an entry from org-file-apps that makes
10993 use of groups in a regexp matches.
10995 If you want to change the way frames are used when following a
10996 link, please customize `org-link-frame-setup'.
10998 If the file does not exist, an error is thrown."
10999 (let* ((file (if (equal path "")
11000 buffer-file-name
11001 (substitute-in-file-name (expand-file-name path))))
11002 (file-apps (append org-file-apps (org-default-apps)))
11003 (apps (org-remove-if
11004 'org-file-apps-entry-match-against-dlink-p file-apps))
11005 (apps-dlink (org-remove-if-not
11006 'org-file-apps-entry-match-against-dlink-p file-apps))
11007 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11008 (dirp (if remp nil (file-directory-p file)))
11009 (file (if (and dirp org-open-directory-means-index-dot-org)
11010 (concat (file-name-as-directory file) "index.org")
11011 file))
11012 (a-m-a-p (assq 'auto-mode apps))
11013 (dfile (downcase file))
11014 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11015 (link (cond ((and (eq line nil)
11016 (eq search nil))
11017 file)
11018 (line
11019 (concat file "::" (number-to-string line)))
11020 (search
11021 (concat file "::" search))))
11022 (dlink (downcase link))
11023 (old-buffer (current-buffer))
11024 (old-pos (point))
11025 (old-mode major-mode)
11026 ext cmd link-match-data)
11027 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11028 (setq ext (match-string 1 dfile))
11029 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11030 (setq ext (match-string 1 dfile))))
11031 (cond
11032 ((member in-emacs '((16) system))
11033 (setq cmd (cdr (assoc 'system apps))))
11034 (in-emacs (setq cmd 'emacs))
11036 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11037 (and dirp (cdr (assoc 'directory apps)))
11038 ; first, try matching against apps-dlink
11039 ; if we get a match here, store the match data for later
11040 (let ((match (assoc-default dlink apps-dlink
11041 'string-match)))
11042 (if match
11043 (progn (setq link-match-data (match-data))
11044 match)
11045 (progn (setq in-emacs (or in-emacs line search))
11046 nil))) ; if we have no match in apps-dlink,
11047 ; always open the file in emacs if line or search
11048 ; is given (for backwards compatibility)
11049 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11050 'string-match)
11051 (cdr (assoc ext apps))
11052 (cdr (assoc t apps))))))
11053 (when (eq cmd 'system)
11054 (setq cmd (cdr (assoc 'system apps))))
11055 (when (eq cmd 'default)
11056 (setq cmd (cdr (assoc t apps))))
11057 (when (eq cmd 'mailcap)
11058 (require 'mailcap)
11059 (mailcap-parse-mailcaps)
11060 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11061 (command (mailcap-mime-info mime-type)))
11062 (if (stringp command)
11063 (setq cmd command)
11064 (setq cmd 'emacs))))
11065 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11066 (not (file-exists-p file))
11067 (not org-open-non-existing-files))
11068 (user-error "No such file: %s" file))
11069 (cond
11070 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11071 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11072 (while (string-match "['\"]%s['\"]" cmd)
11073 (setq cmd (replace-match "%s" t t cmd)))
11074 (while (string-match "%s" cmd)
11075 (setq cmd (replace-match
11076 (save-match-data
11077 (shell-quote-argument
11078 (convert-standard-filename file)))
11079 t t cmd)))
11081 ;; Replace "%1", "%2" etc. in command with group matches from regex
11082 (save-match-data
11083 (let ((match-index 1)
11084 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11085 (set-match-data link-match-data)
11086 (while (<= match-index number-of-groups)
11087 (let ((regex (concat "%" (number-to-string match-index)))
11088 (replace-with (match-string match-index dlink)))
11089 (while (string-match regex cmd)
11090 (setq cmd (replace-match replace-with t t cmd))))
11091 (setq match-index (+ match-index 1)))))
11093 (save-window-excursion
11094 (message "Running %s...done" cmd)
11095 (start-process-shell-command cmd nil cmd)
11096 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11097 ((or (stringp cmd)
11098 (eq cmd 'emacs))
11099 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11100 (widen)
11101 (if line (org-goto-line line)
11102 (if search (org-link-search search))))
11103 ((consp cmd)
11104 (let ((file (convert-standard-filename file)))
11105 (save-match-data
11106 (set-match-data link-match-data)
11107 (eval cmd))))
11108 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11109 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11110 (or (not (equal old-buffer (current-buffer)))
11111 (not (equal old-pos (point))))
11112 (org-mark-ring-push old-pos old-buffer))))
11114 (defun org-file-apps-entry-match-against-dlink-p (entry)
11115 "This function returns non-nil if `entry' uses a regular
11116 expression which should be matched against the whole link by
11117 org-open-file.
11119 It assumes that is the case when the entry uses a regular
11120 expression which has at least one grouping construct and the
11121 action is either a lisp form or a command string containing
11122 '%1', i.e. using at least one subexpression match as a
11123 parameter."
11124 (let ((selector (car entry))
11125 (action (cdr entry)))
11126 (if (stringp selector)
11127 (and (> (regexp-opt-depth selector) 0)
11128 (or (and (stringp action)
11129 (string-match "%[0-9]" action))
11130 (consp action)))
11131 nil)))
11133 (defun org-default-apps ()
11134 "Return the default applications for this operating system."
11135 (cond
11136 ((eq system-type 'darwin)
11137 org-file-apps-defaults-macosx)
11138 ((eq system-type 'windows-nt)
11139 org-file-apps-defaults-windowsnt)
11140 (t org-file-apps-defaults-gnu)))
11142 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11143 "Convert extensions to regular expressions in the cars of LIST.
11144 Also, weed out any non-string entries, because the return value is used
11145 only for regexp matching.
11146 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11147 point to the symbol `emacs', indicating that the file should
11148 be opened in Emacs."
11149 (append
11150 (delq nil
11151 (mapcar (lambda (x)
11152 (if (not (stringp (car x)))
11154 (if (string-match "\\W" (car x))
11156 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11157 list))
11158 (if add-auto-mode
11159 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11161 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11162 (defun org-file-remote-p (file)
11163 "Test whether FILE specifies a location on a remote system.
11164 Return non-nil if the location is indeed remote.
11166 For example, the filename \"/user@host:/foo\" specifies a location
11167 on the system \"/user@host:\"."
11168 (cond ((fboundp 'file-remote-p)
11169 (file-remote-p file))
11170 ((fboundp 'tramp-handle-file-remote-p)
11171 (tramp-handle-file-remote-p file))
11172 ((and (boundp 'ange-ftp-name-format)
11173 (string-match (car ange-ftp-name-format) file))
11174 t)))
11177 ;;;; Refiling
11179 (defun org-get-org-file ()
11180 "Read a filename, with default directory `org-directory'."
11181 (let ((default (or org-default-notes-file remember-data-file)))
11182 (read-file-name (format "File name [%s]: " default)
11183 (file-name-as-directory org-directory)
11184 default)))
11186 (defun org-notes-order-reversed-p ()
11187 "Check if the current file should receive notes in reversed order."
11188 (cond
11189 ((not org-reverse-note-order) nil)
11190 ((eq t org-reverse-note-order) t)
11191 ((not (listp org-reverse-note-order)) nil)
11192 (t (catch 'exit
11193 (let ((all org-reverse-note-order)
11194 entry)
11195 (while (setq entry (pop all))
11196 (if (string-match (car entry) buffer-file-name)
11197 (throw 'exit (cdr entry))))
11198 nil)))))
11200 (defvar org-refile-target-table nil
11201 "The list of refile targets, created by `org-refile'.")
11203 (defvar org-agenda-new-buffers nil
11204 "Buffers created to visit agenda files.")
11206 (defvar org-refile-cache nil
11207 "Cache for refile targets.")
11209 (defvar org-refile-markers nil
11210 "All the markers used for caching refile locations.")
11212 (defun org-refile-marker (pos)
11213 "Get a new refile marker, but only if caching is in use."
11214 (if (not org-refile-use-cache)
11216 (let ((m (make-marker)))
11217 (move-marker m pos)
11218 (push m org-refile-markers)
11219 m)))
11221 (defun org-refile-cache-clear ()
11222 "Clear the refile cache and disable all the markers."
11223 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11224 (setq org-refile-markers nil)
11225 (setq org-refile-cache nil)
11226 (message "Refile cache has been cleared"))
11228 (defun org-refile-cache-check-set (set)
11229 "Check if all the markers in the cache still have live buffers."
11230 (let (marker)
11231 (catch 'exit
11232 (while (and set (setq marker (nth 3 (pop set))))
11233 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11234 (when (and marker (null (marker-buffer marker)))
11235 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11236 (sit-for 3)
11237 (throw 'exit nil)))
11238 t)))
11240 (defun org-refile-cache-put (set &rest identifiers)
11241 "Push the refile targets SET into the cache, under IDENTIFIERS."
11242 (let* ((key (sha1 (prin1-to-string identifiers)))
11243 (entry (assoc key org-refile-cache)))
11244 (if entry
11245 (setcdr entry set)
11246 (push (cons key set) org-refile-cache))))
11248 (defun org-refile-cache-get (&rest identifiers)
11249 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11250 (cond
11251 ((not org-refile-cache) nil)
11252 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11254 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11255 org-refile-cache))))
11256 (and set (org-refile-cache-check-set set) set)))))
11258 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11259 "Produce a table with refile targets."
11260 (let ((case-fold-search nil)
11261 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11262 (entries (or org-refile-targets '((nil . (:level . 1)))))
11263 targets tgs txt re files f desc descre fast-path-p level pos0)
11264 (message "Getting targets...")
11265 (with-current-buffer (or default-buffer (current-buffer))
11266 (while (setq entry (pop entries))
11267 (setq files (car entry) desc (cdr entry))
11268 (setq fast-path-p nil)
11269 (cond
11270 ((null files) (setq files (list (current-buffer))))
11271 ((eq files 'org-agenda-files)
11272 (setq files (org-agenda-files 'unrestricted)))
11273 ((and (symbolp files) (fboundp files))
11274 (setq files (funcall files)))
11275 ((and (symbolp files) (boundp files))
11276 (setq files (symbol-value files))))
11277 (if (stringp files) (setq files (list files)))
11278 (cond
11279 ((eq (car desc) :tag)
11280 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11281 ((eq (car desc) :todo)
11282 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11283 ((eq (car desc) :regexp)
11284 (setq descre (cdr desc)))
11285 ((eq (car desc) :level)
11286 (setq descre (concat "^\\*\\{" (number-to-string
11287 (if org-odd-levels-only
11288 (1- (* 2 (cdr desc)))
11289 (cdr desc)))
11290 "\\}[ \t]")))
11291 ((eq (car desc) :maxlevel)
11292 (setq fast-path-p t)
11293 (setq descre (concat "^\\*\\{1," (number-to-string
11294 (if org-odd-levels-only
11295 (1- (* 2 (cdr desc)))
11296 (cdr desc)))
11297 "\\}[ \t]")))
11298 (t (error "Bad refiling target description %s" desc)))
11299 (while (setq f (pop files))
11300 (with-current-buffer
11301 (if (bufferp f) f (org-get-agenda-file-buffer f))
11303 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11304 (progn
11305 (if (bufferp f) (setq f (buffer-file-name
11306 (buffer-base-buffer f))))
11307 (setq f (and f (expand-file-name f)))
11308 (if (eq org-refile-use-outline-path 'file)
11309 (push (list (file-name-nondirectory f) f nil nil) tgs))
11310 (save-excursion
11311 (save-restriction
11312 (widen)
11313 (goto-char (point-min))
11314 (while (re-search-forward descre nil t)
11315 (goto-char (setq pos0 (point-at-bol)))
11316 (catch 'next
11317 (when org-refile-target-verify-function
11318 (save-match-data
11319 (or (funcall org-refile-target-verify-function)
11320 (throw 'next t))))
11321 (when (and (looking-at org-complex-heading-regexp)
11322 (not (member (match-string 4) excluded-entries))
11323 (match-string 4))
11324 (setq level (org-reduced-level
11325 (- (match-end 1) (match-beginning 1)))
11326 txt (org-link-display-format (match-string 4))
11327 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11328 re (format org-complex-heading-regexp-format
11329 (regexp-quote (match-string 4))))
11330 (when org-refile-use-outline-path
11331 (setq txt (mapconcat
11332 'org-protect-slash
11333 (append
11334 (if (eq org-refile-use-outline-path
11335 'file)
11336 (list (file-name-nondirectory
11337 (buffer-file-name
11338 (buffer-base-buffer))))
11339 (if (eq org-refile-use-outline-path
11340 'full-file-path)
11341 (list (buffer-file-name
11342 (buffer-base-buffer)))))
11343 (org-get-outline-path fast-path-p
11344 level txt)
11345 (list txt))
11346 "/")))
11347 (push (list txt f re (org-refile-marker (point)))
11348 tgs)))
11349 (when (= (point) pos0)
11350 ;; verification function has not moved point
11351 (goto-char (point-at-eol))))))))
11352 (when org-refile-use-cache
11353 (org-refile-cache-put tgs (buffer-file-name) descre))
11354 (setq targets (append tgs targets))))))
11355 (message "Getting targets...done")
11356 (nreverse targets)))
11358 (defun org-protect-slash (s)
11359 (while (string-match "/" s)
11360 (setq s (replace-match "\\" t t s)))
11363 (defvar org-olpa (make-vector 20 nil))
11365 (defun org-get-outline-path (&optional fastp level heading)
11366 "Return the outline path to the current entry, as a list.
11368 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11369 routine which makes outline path derivations for an entire file,
11370 avoiding backtracing. Refile target collection makes use of that."
11371 (if fastp
11372 (progn
11373 (if (> level 19)
11374 (error "Outline path failure, more than 19 levels"))
11375 (loop for i from level upto 19 do
11376 (aset org-olpa i nil))
11377 (prog1
11378 (delq nil (append org-olpa nil))
11379 (aset org-olpa level heading)))
11380 (let (rtn case-fold-search)
11381 (save-excursion
11382 (save-restriction
11383 (widen)
11384 (while (org-up-heading-safe)
11385 (when (looking-at org-complex-heading-regexp)
11386 (push (org-trim
11387 (replace-regexp-in-string
11388 ;; Remove statistical/checkboxes cookies
11389 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11390 (org-match-string-no-properties 4)))
11391 rtn)))
11392 rtn)))))
11394 (defun org-format-outline-path (path &optional width prefix separator)
11395 "Format the outline path PATH for display.
11396 WIDTH is the maximum number of characters that is available.
11397 PREFIX is a prefix to be included in the returned string,
11398 such as the file name.
11399 SEPARATOR is inserted between the different parts of the path,
11400 the default is \"/\"."
11401 (setq width (or width 79))
11402 (if prefix (setq width (- width (length prefix))))
11403 (if (not path)
11404 (or prefix "")
11405 (let* ((nsteps (length path))
11406 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11407 (maxwidth (if (<= total-width width)
11408 10000 ;; everything fits
11409 ;; we need to shorten the level headings
11410 (/ (- width nsteps) nsteps)))
11411 (org-odd-levels-only nil)
11412 (n 0)
11413 (total (1+ (length prefix))))
11414 (setq maxwidth (max maxwidth 10))
11415 (concat prefix
11416 (if prefix (or separator "/"))
11417 (mapconcat
11418 (lambda (h)
11419 (setq n (1+ n))
11420 (if (and (= n nsteps) (< maxwidth 10000))
11421 (setq maxwidth (- total-width total)))
11422 (if (< (length h) maxwidth)
11423 (progn (setq total (+ total (length h) 1)) h)
11424 (setq h (substring h 0 (- maxwidth 2))
11425 total (+ total maxwidth 1))
11426 (if (string-match "[ \t]+\\'" h)
11427 (setq h (substring h 0 (match-beginning 0))))
11428 (setq h (concat h "..")))
11429 (org-add-props h nil 'face
11430 (nth (% (1- n) org-n-level-faces)
11431 org-level-faces))
11433 path (or separator "/"))))))
11435 (defun org-display-outline-path (&optional file current separator just-return-string)
11436 "Display the current outline path in the echo area.
11438 If FILE is non-nil, prepend the output with the file name.
11439 If CURRENT is non-nil, append the current heading to the output.
11440 SEPARATOR is passed through to `org-format-outline-path'. It separates
11441 the different parts of the path and defaults to \"/\".
11442 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11443 (interactive "P")
11444 (let* (case-fold-search
11445 (bfn (buffer-file-name (buffer-base-buffer)))
11446 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11447 res)
11448 (if current (setq path (append path
11449 (save-excursion
11450 (org-back-to-heading t)
11451 (if (looking-at org-complex-heading-regexp)
11452 (list (match-string 4)))))))
11453 (setq res
11454 (org-format-outline-path
11455 path
11456 (1- (frame-width))
11457 (and file bfn (concat (file-name-nondirectory bfn) separator))
11458 separator))
11459 (if just-return-string
11460 (org-no-properties res)
11461 (org-unlogged-message "%s" res))))
11463 (defvar org-refile-history nil
11464 "History for refiling operations.")
11466 (defvar org-after-refile-insert-hook nil
11467 "Hook run after `org-refile' has inserted its stuff at the new location.
11468 Note that this is still *before* the stuff will be removed from
11469 the *old* location.")
11471 (defvar org-capture-last-stored-marker)
11472 (defvar org-refile-keep nil
11473 "Non-nil means `org-refile' will copy instead of refile.")
11475 (defun org-copy ()
11476 "Like `org-refile', but copy."
11477 (interactive)
11478 (let ((org-refile-keep t))
11479 (funcall 'org-refile nil nil nil "Copy")))
11481 (defun org-refile (&optional goto default-buffer rfloc msg)
11482 "Move the entry or entries at point to another heading.
11483 The list of target headings is compiled using the information in
11484 `org-refile-targets', which see.
11486 At the target location, the entry is filed as a subitem of the target
11487 heading. Depending on `org-reverse-note-order', the new subitem will
11488 either be the first or the last subitem.
11490 If there is an active region, all entries in that region will be moved.
11491 However, the region must fulfill the requirement that the first heading
11492 is the first one sets the top-level of the moved text - at most siblings
11493 below it are allowed.
11495 With prefix arg GOTO, the command will only visit the target location
11496 and not actually move anything.
11498 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11499 go to the location where the last refiling operation has put the subtree.
11501 With a numeric prefix argument of `2', refile to the running clock.
11503 With a numeric prefix argument of `3', emulate `org-refile-keep'
11504 being set to `t' and copy to the target location, don't move it.
11505 Beware that keeping refiled entries may result in duplicated ID
11506 properties.
11508 RFLOC can be a refile location obtained in a different way.
11510 MSG is a string to replace \"Refile\" in the default prompt with
11511 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11513 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11515 If you are using target caching (see `org-refile-use-cache'),
11516 you have to clear the target cache in order to find new targets.
11517 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11518 prefix argument (`C-u C-u C-u C-c C-w')."
11520 (interactive "P")
11521 (if (member goto '(0 (64)))
11522 (org-refile-cache-clear)
11523 (let* ((actionmsg (or msg "Refile"))
11524 (cbuf (current-buffer))
11525 (regionp (org-region-active-p))
11526 (region-start (and regionp (region-beginning)))
11527 (region-end (and regionp (region-end)))
11528 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11529 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11530 pos it nbuf file re level reversed)
11531 (setq last-command nil)
11532 (when regionp
11533 (goto-char region-start)
11534 (or (bolp) (goto-char (point-at-bol)))
11535 (setq region-start (point))
11536 (unless (or (org-kill-is-subtree-p
11537 (buffer-substring region-start region-end))
11538 (prog1 org-refile-active-region-within-subtree
11539 (let ((s (point-at-eol)))
11540 (org-toggle-heading)
11541 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11542 (user-error "The region is not a (sequence of) subtree(s)")))
11543 (if (equal goto '(16))
11544 (org-refile-goto-last-stored)
11545 (when (or
11546 (and (equal goto 2)
11547 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11548 (prog1
11549 (setq it (list (or org-clock-heading "running clock")
11550 (buffer-file-name
11551 (marker-buffer org-clock-hd-marker))
11553 (marker-position org-clock-hd-marker)))
11554 (setq goto nil)))
11555 (setq it (or rfloc
11556 (let (heading-text)
11557 (save-excursion
11558 (unless goto
11559 (org-back-to-heading t)
11560 (setq heading-text
11561 (nth 4 (org-heading-components))))
11563 (org-refile-get-location
11564 (cond (goto "Goto")
11565 (regionp (concat actionmsg " region to"))
11566 (t (concat actionmsg " subtree \""
11567 heading-text "\" to")))
11568 default-buffer
11569 (and (not (equal '(4) goto))
11570 org-refile-allow-creating-parent-nodes)
11571 goto))))))
11572 (setq file (nth 1 it)
11573 re (nth 2 it)
11574 pos (nth 3 it))
11575 (if (and (not goto)
11577 (equal (buffer-file-name) file)
11578 (if regionp
11579 (and (>= pos region-start)
11580 (<= pos region-end))
11581 (and (>= pos (point))
11582 (< pos (save-excursion
11583 (org-end-of-subtree t t))))))
11584 (error "Cannot refile to position inside the tree or region"))
11586 (setq nbuf (or (find-buffer-visiting file)
11587 (find-file-noselect file)))
11588 (if (and goto (not (equal goto 3)))
11589 (progn
11590 (org-pop-to-buffer-same-window nbuf)
11591 (goto-char pos)
11592 (org-show-context 'org-goto))
11593 (if regionp
11594 (progn
11595 (org-kill-new (buffer-substring region-start region-end))
11596 (org-save-markers-in-region region-start region-end))
11597 (org-copy-subtree 1 nil t))
11598 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11599 (find-file-noselect file)))
11600 (setq reversed (org-notes-order-reversed-p))
11601 (save-excursion
11602 (save-restriction
11603 (widen)
11604 (if pos
11605 (progn
11606 (goto-char pos)
11607 (looking-at org-outline-regexp)
11608 (setq level (org-get-valid-level (funcall outline-level) 1))
11609 (goto-char
11610 (if reversed
11611 (or (outline-next-heading) (point-max))
11612 (or (save-excursion (org-get-next-sibling))
11613 (org-end-of-subtree t t)
11614 (point-max)))))
11615 (setq level 1)
11616 (if (not reversed)
11617 (goto-char (point-max))
11618 (goto-char (point-min))
11619 (or (outline-next-heading) (goto-char (point-max)))))
11620 (if (not (bolp)) (newline))
11621 (org-paste-subtree level)
11622 (when org-log-refile
11623 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11624 (unless (eq org-log-refile 'note)
11625 (save-excursion (org-add-log-note))))
11626 (and org-auto-align-tags
11627 (let ((org-loop-over-headlines-in-active-region nil))
11628 (org-set-tags nil t)))
11629 (let ((bookmark-name (plist-get org-bookmark-names-plist
11630 :last-refile)))
11631 (when bookmark-name
11632 (with-demoted-errors
11633 (bookmark-set bookmark-name))))
11634 ;; If we are refiling for capture, make sure that the
11635 ;; last-capture pointers point here
11636 (when (org-bound-and-true-p org-refile-for-capture)
11637 (let ((bookmark-name (plist-get org-bookmark-names-plist
11638 :last-capture-marker)))
11639 (when bookmark-name
11640 (with-demoted-errors
11641 (bookmark-set bookmark-name))))
11642 (move-marker org-capture-last-stored-marker (point)))
11643 (if (fboundp 'deactivate-mark) (deactivate-mark))
11644 (run-hooks 'org-after-refile-insert-hook))))
11645 (unless org-refile-keep
11646 (if regionp
11647 (delete-region (point) (+ (point) (- region-end region-start)))
11648 (delete-region
11649 (and (org-back-to-heading t) (point))
11650 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11651 (when (featurep 'org-inlinetask)
11652 (org-inlinetask-remove-END-maybe))
11653 (setq org-markers-to-move nil)
11654 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11656 (defun org-refile-goto-last-stored ()
11657 "Go to the location where the last refile was stored."
11658 (interactive)
11659 (bookmark-jump "org-refile-last-stored")
11660 (message "This is the location of the last refile"))
11662 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11663 no-exclude)
11664 "Prompt the user for a refile location, using PROMPT.
11665 PROMPT should not be suffixed with a colon and a space, because
11666 this function appends the default value from
11667 `org-refile-history' automatically, if that is not empty.
11668 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11669 this is used for the GOTO interface."
11670 (let ((org-refile-targets org-refile-targets)
11671 (org-refile-use-outline-path org-refile-use-outline-path)
11672 excluded-entries)
11673 (when (and (derived-mode-p 'org-mode)
11674 (not org-refile-use-cache)
11675 (not no-exclude))
11676 (org-map-tree
11677 (lambda()
11678 (setq excluded-entries
11679 (append excluded-entries (list (org-get-heading t t)))))))
11680 (setq org-refile-target-table
11681 (org-refile-get-targets default-buffer excluded-entries)))
11682 (unless org-refile-target-table
11683 (user-error "No refile targets"))
11684 (let* ((cbuf (current-buffer))
11685 (partial-completion-mode nil)
11686 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11687 (cfunc (if (and org-refile-use-outline-path
11688 org-outline-path-complete-in-steps)
11689 'org-olpath-completing-read
11690 'org-icompleting-read))
11691 (extra (if org-refile-use-outline-path "/" ""))
11692 (cbnex (concat (buffer-name) extra))
11693 (filename (and cfn (expand-file-name cfn)))
11694 (tbl (mapcar
11695 (lambda (x)
11696 (if (and (not (member org-refile-use-outline-path
11697 '(file full-file-path)))
11698 (not (equal filename (nth 1 x))))
11699 (cons (concat (car x) extra " ("
11700 (file-name-nondirectory (nth 1 x)) ")")
11701 (cdr x))
11702 (cons (concat (car x) extra) (cdr x))))
11703 org-refile-target-table))
11704 (completion-ignore-case t)
11705 cdef
11706 (prompt (concat prompt
11707 (or (and (car org-refile-history)
11708 (concat " (default " (car org-refile-history) ")"))
11709 (and (assoc cbnex tbl) (setq cdef cbnex)
11710 (concat " (default " cbnex ")"))) ": "))
11711 pa answ parent-target child parent old-hist)
11712 (setq old-hist org-refile-history)
11713 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11714 nil 'org-refile-history (or cdef (car org-refile-history))))
11715 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11716 (org-refile-check-position pa)
11717 (if pa
11718 (progn
11719 (when (or (not org-refile-history)
11720 (not (eq old-hist org-refile-history))
11721 (not (equal (car pa) (car org-refile-history))))
11722 (setq org-refile-history
11723 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11724 org-refile-history
11725 (cdr org-refile-history))))
11726 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11727 (pop org-refile-history)))
11729 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11730 (progn
11731 (setq parent (match-string 1 answ)
11732 child (match-string 2 answ))
11733 (setq parent-target (or (assoc parent tbl)
11734 (assoc (concat parent "/") tbl)))
11735 (when (and parent-target
11736 (or (eq new-nodes t)
11737 (and (eq new-nodes 'confirm)
11738 (y-or-n-p (format "Create new node \"%s\"? "
11739 child)))))
11740 (org-refile-new-child parent-target child)))
11741 (user-error "Invalid target location")))))
11743 (declare-function org-string-nw-p "org-macs" (s))
11744 (defun org-refile-check-position (refile-pointer)
11745 "Check if the refile pointer matches the headline to which it points."
11746 (let* ((file (nth 1 refile-pointer))
11747 (re (nth 2 refile-pointer))
11748 (pos (nth 3 refile-pointer))
11749 buffer)
11750 (if (and (not (markerp pos)) (not file))
11751 (user-error "Please save the buffer to a file before refiling")
11752 (when (org-string-nw-p re)
11753 (setq buffer (if (markerp pos)
11754 (marker-buffer pos)
11755 (or (find-buffer-visiting file)
11756 (find-file-noselect file))))
11757 (with-current-buffer buffer
11758 (save-excursion
11759 (save-restriction
11760 (widen)
11761 (goto-char pos)
11762 (beginning-of-line 1)
11763 (unless (org-looking-at-p re)
11764 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11766 (defun org-refile-new-child (parent-target child)
11767 "Use refile target PARENT-TARGET to add new CHILD below it."
11768 (unless parent-target
11769 (error "Cannot find parent for new node"))
11770 (let ((file (nth 1 parent-target))
11771 (pos (nth 3 parent-target))
11772 level)
11773 (with-current-buffer (or (find-buffer-visiting file)
11774 (find-file-noselect file))
11775 (save-excursion
11776 (save-restriction
11777 (widen)
11778 (if pos
11779 (goto-char pos)
11780 (goto-char (point-max))
11781 (if (not (bolp)) (newline)))
11782 (when (looking-at org-outline-regexp)
11783 (setq level (funcall outline-level))
11784 (org-end-of-subtree t t))
11785 (org-back-over-empty-lines)
11786 (insert "\n" (make-string
11787 (if pos (org-get-valid-level level 1) 1) ?*)
11788 " " child "\n")
11789 (beginning-of-line 0)
11790 (list (concat (car parent-target) "/" child) file "" (point)))))))
11792 (defun org-olpath-completing-read (prompt collection &rest args)
11793 "Read an outline path like a file name."
11794 (let ((thetable collection)
11795 (org-completion-use-ido nil) ; does not work with ido.
11796 (org-completion-use-iswitchb nil)) ; or iswitchb
11797 (apply
11798 'org-icompleting-read prompt
11799 (lambda (string predicate &optional flag)
11800 (let (rtn r f (l (length string)))
11801 (cond
11802 ((eq flag nil)
11803 ;; try completion
11804 (try-completion string thetable))
11805 ((eq flag t)
11806 ;; all-completions
11807 (setq rtn (all-completions string thetable predicate))
11808 (mapcar
11809 (lambda (x)
11810 (setq r (substring x l))
11811 (if (string-match " ([^)]*)$" x)
11812 (setq f (match-string 0 x))
11813 (setq f ""))
11814 (if (string-match "/" r)
11815 (concat string (substring r 0 (match-end 0)) f)
11817 rtn))
11818 ((eq flag 'lambda)
11819 ;; exact match?
11820 (assoc string thetable)))))
11821 args)))
11823 ;;;; Dynamic blocks
11825 (defun org-find-dblock (name)
11826 "Find the first dynamic block with name NAME in the buffer.
11827 If not found, stay at current position and return nil."
11828 (let ((case-fold-search t) pos)
11829 (save-excursion
11830 (goto-char (point-min))
11831 (setq pos (and (re-search-forward
11832 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11833 (match-beginning 0))))
11834 (if pos (goto-char pos))
11835 pos))
11837 (defconst org-dblock-start-re
11838 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11839 "Matches the start line of a dynamic block, with parameters.")
11841 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11842 "Matches the end of a dynamic block.")
11844 (defun org-create-dblock (plist)
11845 "Create a dynamic block section, with parameters taken from PLIST.
11846 PLIST must contain a :name entry which is used as name of the block."
11847 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11848 (end-of-line 1)
11849 (newline))
11850 (let ((col (current-column))
11851 (name (plist-get plist :name)))
11852 (insert "#+BEGIN: " name)
11853 (while plist
11854 (if (eq (car plist) :name)
11855 (setq plist (cddr plist))
11856 (insert " " (prin1-to-string (pop plist)))))
11857 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11858 (beginning-of-line -2)))
11860 (defun org-prepare-dblock ()
11861 "Prepare dynamic block for refresh.
11862 This empties the block, puts the cursor at the insert position and returns
11863 the property list including an extra property :name with the block name."
11864 (unless (looking-at org-dblock-start-re)
11865 (user-error "Not at a dynamic block"))
11866 (let* ((begdel (1+ (match-end 0)))
11867 (name (org-no-properties (match-string 1)))
11868 (params (append (list :name name)
11869 (read (concat "(" (match-string 3) ")")))))
11870 (save-excursion
11871 (beginning-of-line 1)
11872 (skip-chars-forward " \t")
11873 (setq params (plist-put params :indentation-column (current-column))))
11874 (unless (re-search-forward org-dblock-end-re nil t)
11875 (error "Dynamic block not terminated"))
11876 (setq params
11877 (append params
11878 (list :content (buffer-substring
11879 begdel (match-beginning 0)))))
11880 (delete-region begdel (match-beginning 0))
11881 (goto-char begdel)
11882 (open-line 1)
11883 params))
11885 (defun org-map-dblocks (&optional command)
11886 "Apply COMMAND to all dynamic blocks in the current buffer.
11887 If COMMAND is not given, use `org-update-dblock'."
11888 (let ((cmd (or command 'org-update-dblock)))
11889 (save-excursion
11890 (goto-char (point-min))
11891 (while (re-search-forward org-dblock-start-re nil t)
11892 (goto-char (match-beginning 0))
11893 (save-excursion
11894 (condition-case nil
11895 (funcall cmd)
11896 (error (message "Error during update of dynamic block"))))
11897 (unless (re-search-forward org-dblock-end-re nil t)
11898 (error "Dynamic block not terminated"))))))
11900 (defun org-dblock-update (&optional arg)
11901 "User command for updating dynamic blocks.
11902 Update the dynamic block at point. With prefix ARG, update all dynamic
11903 blocks in the buffer."
11904 (interactive "P")
11905 (if arg
11906 (org-update-all-dblocks)
11907 (or (looking-at org-dblock-start-re)
11908 (org-beginning-of-dblock))
11909 (org-update-dblock)))
11911 (defun org-update-dblock ()
11912 "Update the dynamic block at point.
11913 This means to empty the block, parse for parameters and then call
11914 the correct writing function."
11915 (interactive)
11916 (save-window-excursion
11917 (let* ((pos (point))
11918 (line (org-current-line))
11919 (params (org-prepare-dblock))
11920 (name (plist-get params :name))
11921 (indent (plist-get params :indentation-column))
11922 (cmd (intern (concat "org-dblock-write:" name))))
11923 (message "Updating dynamic block `%s' at line %d..." name line)
11924 (funcall cmd params)
11925 (message "Updating dynamic block `%s' at line %d...done" name line)
11926 (goto-char pos)
11927 (when (and indent (> indent 0))
11928 (setq indent (make-string indent ?\ ))
11929 (save-excursion
11930 (org-beginning-of-dblock)
11931 (forward-line 1)
11932 (while (not (looking-at org-dblock-end-re))
11933 (insert indent)
11934 (beginning-of-line 2))
11935 (when (looking-at org-dblock-end-re)
11936 (and (looking-at "[ \t]+")
11937 (replace-match ""))
11938 (insert indent)))))))
11940 (defun org-beginning-of-dblock ()
11941 "Find the beginning of the dynamic block at point.
11942 Error if there is no such block at point."
11943 (let ((pos (point))
11944 beg)
11945 (end-of-line 1)
11946 (if (and (re-search-backward org-dblock-start-re nil t)
11947 (setq beg (match-beginning 0))
11948 (re-search-forward org-dblock-end-re nil t)
11949 (> (match-end 0) pos))
11950 (goto-char beg)
11951 (goto-char pos)
11952 (error "Not in a dynamic block"))))
11954 (defun org-update-all-dblocks ()
11955 "Update all dynamic blocks in the buffer.
11956 This function can be used in a hook."
11957 (interactive)
11958 (when (derived-mode-p 'org-mode)
11959 (org-map-dblocks 'org-update-dblock)))
11962 ;;;; Completion
11964 (declare-function org-export-backend-name "org-export" (cl-x))
11965 (declare-function org-export-backend-options "org-export" (cl-x))
11966 (defun org-get-export-keywords ()
11967 "Return a list of all currently understood export keywords.
11968 Export keywords include options, block names, attributes and
11969 keywords relative to each registered export back-end."
11970 (let (keywords)
11971 (dolist (backend
11972 (org-bound-and-true-p org-export--registered-backends)
11973 (delq nil keywords))
11974 ;; Back-end name (for keywords, like #+LATEX:)
11975 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11976 (dolist (option-entry (org-export-backend-options backend))
11977 ;; Back-end options.
11978 (push (nth 1 option-entry) keywords)))))
11980 (defconst org-options-keywords
11981 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11982 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11983 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11984 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11985 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11987 (defcustom org-structure-template-alist
11988 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11989 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11990 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11991 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11992 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11993 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11994 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11995 "<literal style=\"latex\">\n?\n</literal>")
11996 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11997 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11998 "<literal style=\"html\">\n?\n</literal>")
11999 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12000 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12001 ("A" "#+ASCII: " "")
12002 ("i" "#+INDEX: ?" "#+INDEX: ?")
12003 ("I" "#+INCLUDE: %file ?"
12004 "<include file=%file markup=\"?\">"))
12005 "Structure completion elements.
12006 This is a list of abbreviation keys and values. The value gets inserted
12007 if you type `<' followed by the key and then press the completion key,
12008 usually `M-TAB'. %file will be replaced by a file name after prompting
12009 for the file using completion. The cursor will be placed at the position
12010 of the `?` in the template.
12011 There are two templates for each key, the first uses the original Org syntax,
12012 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12013 the default when the /org-mtags.el/ module has been loaded. See also the
12014 variable `org-mtags-prefer-muse-templates'."
12015 :group 'org-completion
12016 :type '(repeat
12017 (list
12018 (string :tag "Key")
12019 (string :tag "Template")
12020 (string :tag "Muse Template"))))
12022 (defun org-try-structure-completion ()
12023 "Try to complete a structure template before point.
12024 This looks for strings like \"<e\" on an otherwise empty line and
12025 expands them."
12026 (let ((l (buffer-substring (point-at-bol) (point)))
12028 (when (and (looking-at "[ \t]*$")
12029 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12030 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12031 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12032 (match-beginning 1)) a)
12033 t)))
12035 (defun org-complete-expand-structure-template (start cell)
12036 "Expand a structure template."
12037 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12038 (rpl (nth (if musep 2 1) cell))
12039 (ind ""))
12040 (delete-region start (point))
12041 (when (string-match "\\`#\\+" rpl)
12042 (cond
12043 ((bolp))
12044 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12045 (setq ind (buffer-substring (point-at-bol) (point))))
12046 (t (newline))))
12047 (setq start (point))
12048 (if (string-match "%file" rpl)
12049 (setq rpl (replace-match
12050 (concat
12051 "\""
12052 (save-match-data
12053 (abbreviate-file-name (read-file-name "Include file: ")))
12054 "\"")
12055 t t rpl)))
12056 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12057 (concat "\n" ind)))
12058 (insert rpl)
12059 (if (re-search-backward "\\?" start t) (delete-char 1))))
12061 ;;;; TODO, DEADLINE, Comments
12063 (defun org-toggle-comment ()
12064 "Change the COMMENT state of an entry."
12065 (interactive)
12066 (save-excursion
12067 (org-back-to-heading)
12068 (let (case-fold-search)
12069 (cond
12070 ((looking-at (format org-heading-keyword-regexp-format
12071 org-comment-string))
12072 (goto-char (match-end 1))
12073 (looking-at (concat " +" org-comment-string))
12074 (replace-match "" t t)
12075 (when (eolp) (insert " ")))
12076 ((looking-at org-outline-regexp)
12077 (goto-char (match-end 0))
12078 (insert org-comment-string " "))))))
12080 (defvar org-last-todo-state-is-todo nil
12081 "This is non-nil when the last TODO state change led to a TODO state.
12082 If the last change removed the TODO tag or switched to DONE, then
12083 this is nil.")
12085 (defvar org-setting-tags nil) ; dynamically skipped
12087 (defvar org-todo-setup-filter-hook nil
12088 "Hook for functions that pre-filter todo specs.
12089 Each function takes a todo spec and returns either nil or the spec
12090 transformed into canonical form." )
12092 (defvar org-todo-get-default-hook nil
12093 "Hook for functions that get a default item for todo.
12094 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12095 nil or a string to be used for the todo mark." )
12097 (defvar org-agenda-headline-snapshot-before-repeat)
12099 (defun org-current-effective-time ()
12100 "Return current time adjusted for `org-extend-today-until' variable."
12101 (let* ((ct (org-current-time))
12102 (dct (decode-time ct))
12103 (ct1
12104 (cond
12105 (org-use-last-clock-out-time-as-effective-time
12106 (or (org-clock-get-last-clock-out-time) ct))
12107 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12108 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12109 (t ct))))
12110 ct1))
12112 (defun org-todo-yesterday (&optional arg)
12113 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12114 (interactive "P")
12115 (if (eq major-mode 'org-agenda-mode)
12116 (apply 'org-agenda-todo-yesterday arg)
12117 (let* ((hour (third (decode-time
12118 (org-current-time))))
12119 (org-extend-today-until (1+ hour)))
12120 (org-todo arg))))
12122 (defvar org-block-entry-blocking ""
12123 "First entry preventing the TODO state change.")
12125 (defun org-todo (&optional arg)
12126 "Change the TODO state of an item.
12127 The state of an item is given by a keyword at the start of the heading,
12128 like
12129 *** TODO Write paper
12130 *** DONE Call mom
12132 The different keywords are specified in the variable `org-todo-keywords'.
12133 By default the available states are \"TODO\" and \"DONE\".
12134 So for this example: when the item starts with TODO, it is changed to DONE.
12135 When it starts with DONE, the DONE is removed. And when neither TODO nor
12136 DONE are present, add TODO at the beginning of the heading.
12138 With \\[universal-argument] prefix arg, use completion to determine the new \
12139 state.
12140 With numeric prefix arg, switch to that state.
12141 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12142 keywords (nextset).
12143 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12144 With a numeric prefix arg of 0, inhibit note taking for the change.
12146 For calling through lisp, arg is also interpreted in the following way:
12147 'none -> empty state
12148 \"\"(empty string) -> switch to empty state
12149 'done -> switch to DONE
12150 'nextset -> switch to the next set of keywords
12151 'previousset -> switch to the previous set of keywords
12152 \"WAITING\" -> switch to the specified keyword, but only if it
12153 really is a member of `org-todo-keywords'."
12154 (interactive "P")
12155 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12156 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12157 'region-start-level 'region))
12158 org-loop-over-headlines-in-active-region)
12159 (org-map-entries
12160 `(org-todo ,arg)
12161 org-loop-over-headlines-in-active-region
12162 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12163 (if (equal arg '(16)) (setq arg 'nextset))
12164 (let ((org-blocker-hook org-blocker-hook)
12165 commentp
12166 case-fold-search)
12167 (when (equal arg '(64))
12168 (setq arg nil org-blocker-hook nil))
12169 (when (and org-blocker-hook
12170 (or org-inhibit-blocking
12171 (org-entry-get nil "NOBLOCKING")))
12172 (setq org-blocker-hook nil))
12173 (save-excursion
12174 (catch 'exit
12175 (org-back-to-heading t)
12176 (when (looking-at (concat "^\\*+ " org-comment-string))
12177 (org-toggle-comment)
12178 (setq commentp t))
12179 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12180 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12181 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12182 (let* ((match-data (match-data))
12183 (startpos (point-at-bol))
12184 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12185 (org-log-done org-log-done)
12186 (org-log-repeat org-log-repeat)
12187 (org-todo-log-states org-todo-log-states)
12188 (org-inhibit-logging
12189 (if (equal arg 0)
12190 (progn (setq arg nil) 'note) org-inhibit-logging))
12191 (this (match-string 1))
12192 (hl-pos (match-beginning 0))
12193 (head (org-get-todo-sequence-head this))
12194 (ass (assoc head org-todo-kwd-alist))
12195 (interpret (nth 1 ass))
12196 (done-word (nth 3 ass))
12197 (final-done-word (nth 4 ass))
12198 (org-last-state (or this ""))
12199 (completion-ignore-case t)
12200 (member (member this org-todo-keywords-1))
12201 (tail (cdr member))
12202 (org-state (cond
12203 ((and org-todo-key-trigger
12204 (or (and (equal arg '(4))
12205 (eq org-use-fast-todo-selection 'prefix))
12206 (and (not arg) org-use-fast-todo-selection
12207 (not (eq org-use-fast-todo-selection
12208 'prefix)))))
12209 ;; Use fast selection
12210 (org-fast-todo-selection))
12211 ((and (equal arg '(4))
12212 (or (not org-use-fast-todo-selection)
12213 (not org-todo-key-trigger)))
12214 ;; Read a state with completion
12215 (org-icompleting-read
12216 "State: " (mapcar 'list org-todo-keywords-1)
12217 nil t))
12218 ((eq arg 'right)
12219 (if this
12220 (if tail (car tail) nil)
12221 (car org-todo-keywords-1)))
12222 ((eq arg 'left)
12223 (if (equal member org-todo-keywords-1)
12225 (if this
12226 (nth (- (length org-todo-keywords-1)
12227 (length tail) 2)
12228 org-todo-keywords-1)
12229 (org-last org-todo-keywords-1))))
12230 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12231 (setq arg nil))) ; hack to fall back to cycling
12232 (arg
12233 ;; user or caller requests a specific state
12234 (cond
12235 ((equal arg "") nil)
12236 ((eq arg 'none) nil)
12237 ((eq arg 'done) (or done-word (car org-done-keywords)))
12238 ((eq arg 'nextset)
12239 (or (car (cdr (member head org-todo-heads)))
12240 (car org-todo-heads)))
12241 ((eq arg 'previousset)
12242 (let ((org-todo-heads (reverse org-todo-heads)))
12243 (or (car (cdr (member head org-todo-heads)))
12244 (car org-todo-heads))))
12245 ((car (member arg org-todo-keywords-1)))
12246 ((stringp arg)
12247 (user-error "State `%s' not valid in this file" arg))
12248 ((nth (1- (prefix-numeric-value arg))
12249 org-todo-keywords-1))))
12250 ((null member) (or head (car org-todo-keywords-1)))
12251 ((equal this final-done-word) nil) ;; -> make empty
12252 ((null tail) nil) ;; -> first entry
12253 ((memq interpret '(type priority))
12254 (if (eq this-command last-command)
12255 (car tail)
12256 (if (> (length tail) 0)
12257 (or done-word (car org-done-keywords))
12258 nil)))
12260 (car tail))))
12261 (org-state (or
12262 (run-hook-with-args-until-success
12263 'org-todo-get-default-hook org-state org-last-state)
12264 org-state))
12265 (next (if org-state (concat " " org-state " ") " "))
12266 (change-plist (list :type 'todo-state-change :from this :to org-state
12267 :position startpos))
12268 dolog now-done-p)
12269 (when org-blocker-hook
12270 (setq org-last-todo-state-is-todo
12271 (not (member this org-done-keywords)))
12272 (unless (save-excursion
12273 (save-match-data
12274 (org-with-wide-buffer
12275 (run-hook-with-args-until-failure
12276 'org-blocker-hook change-plist))))
12277 (if (org-called-interactively-p 'interactive)
12278 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12279 this org-state org-block-entry-blocking)
12280 ;; fail silently
12281 (message "TODO state change from %s to %s blocked (by \"%s\")"
12282 this org-state org-block-entry-blocking)
12283 (throw 'exit nil))))
12284 (store-match-data match-data)
12285 (replace-match next t t)
12286 (unless (pos-visible-in-window-p hl-pos)
12287 (message "TODO state changed to %s" (org-trim next)))
12288 (unless head
12289 (setq head (org-get-todo-sequence-head org-state)
12290 ass (assoc head org-todo-kwd-alist)
12291 interpret (nth 1 ass)
12292 done-word (nth 3 ass)
12293 final-done-word (nth 4 ass)))
12294 (when (memq arg '(nextset previousset))
12295 (message "Keyword-Set %d/%d: %s"
12296 (- (length org-todo-sets) -1
12297 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12298 (length org-todo-sets)
12299 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12300 (setq org-last-todo-state-is-todo
12301 (not (member org-state org-done-keywords)))
12302 (setq now-done-p (and (member org-state org-done-keywords)
12303 (not (member this org-done-keywords))))
12304 (and logging (org-local-logging logging))
12305 (when (and (or org-todo-log-states org-log-done)
12306 (not (eq org-inhibit-logging t))
12307 (not (memq arg '(nextset previousset))))
12308 ;; we need to look at recording a time and note
12309 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12310 (nth 2 (assoc this org-todo-log-states))))
12311 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12312 (setq dolog 'time))
12313 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12314 (and org-state
12315 (member org-state org-not-done-keywords)
12316 (not (member this org-not-done-keywords))))
12317 ;; This is now a todo state and was not one before
12318 ;; If there was a CLOSED time stamp, get rid of it.
12319 (org-add-planning-info nil nil 'closed))
12320 (when (and now-done-p org-log-done)
12321 ;; It is now done, and it was not done before
12322 (org-add-planning-info 'closed (org-current-effective-time))
12323 (if (and (not dolog) (eq 'note org-log-done))
12324 (org-add-log-setup 'done org-state this 'findpos 'note)))
12325 (when (and org-state dolog)
12326 ;; This is a non-nil state, and we need to log it
12327 (org-add-log-setup 'state org-state this 'findpos dolog)))
12328 ;; Fixup tag positioning
12329 (org-todo-trigger-tag-changes org-state)
12330 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12331 (when org-provide-todo-statistics
12332 (org-update-parent-todo-statistics))
12333 (run-hooks 'org-after-todo-state-change-hook)
12334 (if (and arg (not (member org-state org-done-keywords)))
12335 (setq head (org-get-todo-sequence-head org-state)))
12336 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12337 ;; Do we need to trigger a repeat?
12338 (when now-done-p
12339 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12340 ;; This is for the agenda, take a snapshot of the headline.
12341 (save-match-data
12342 (setq org-agenda-headline-snapshot-before-repeat
12343 (org-get-heading))))
12344 (org-auto-repeat-maybe org-state))
12345 ;; Fixup cursor location if close to the keyword
12346 (if (and (outline-on-heading-p)
12347 (not (bolp))
12348 (save-excursion (beginning-of-line 1)
12349 (looking-at org-todo-line-regexp))
12350 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12351 (progn
12352 (goto-char (or (match-end 2) (match-end 1)))
12353 (and (looking-at " ") (just-one-space))))
12354 (when org-trigger-hook
12355 (save-excursion
12356 (run-hook-with-args 'org-trigger-hook change-plist)))
12357 (when commentp (org-toggle-comment))))))))
12359 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12360 "Block turning an entry into a TODO, using the hierarchy.
12361 This checks whether the current task should be blocked from state
12362 changes. Such blocking occurs when:
12364 1. The task has children which are not all in a completed state.
12366 2. A task has a parent with the property :ORDERED:, and there
12367 are siblings prior to the current task with incomplete
12368 status.
12370 3. The parent of the task is blocked because it has siblings that should
12371 be done first, or is child of a block grandparent TODO entry."
12373 (if (not org-enforce-todo-dependencies)
12374 t ; if locally turned off don't block
12375 (catch 'dont-block
12376 ;; If this is not a todo state change, or if this entry is already DONE,
12377 ;; do not block
12378 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12379 (member (plist-get change-plist :from)
12380 (cons 'done org-done-keywords))
12381 (member (plist-get change-plist :to)
12382 (cons 'todo org-not-done-keywords))
12383 (not (plist-get change-plist :to)))
12384 (throw 'dont-block t))
12385 ;; If this task has children, and any are undone, it's blocked
12386 (save-excursion
12387 (org-back-to-heading t)
12388 (let ((this-level (funcall outline-level)))
12389 (outline-next-heading)
12390 (let ((child-level (funcall outline-level)))
12391 (while (and (not (eobp))
12392 (> child-level this-level))
12393 ;; this todo has children, check whether they are all
12394 ;; completed
12395 (if (and (not (org-entry-is-done-p))
12396 (org-entry-is-todo-p))
12397 (progn (setq org-block-entry-blocking (org-get-heading))
12398 (throw 'dont-block nil)))
12399 (outline-next-heading)
12400 (setq child-level (funcall outline-level))))))
12401 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12402 ;; any previous siblings are undone, it's blocked
12403 (save-excursion
12404 (org-back-to-heading t)
12405 (let* ((pos (point))
12406 (parent-pos (and (org-up-heading-safe) (point))))
12407 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12408 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12409 (forward-line 1)
12410 (re-search-forward org-not-done-heading-regexp pos t))
12411 (setq org-block-entry-blocking (match-string 0))
12412 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12413 ;; Search further up the hierarchy, to see if an ancestor is blocked
12414 (while t
12415 (goto-char parent-pos)
12416 (if (not (looking-at org-not-done-heading-regexp))
12417 (throw 'dont-block t)) ; do not block, parent is not a TODO
12418 (setq pos (point))
12419 (setq parent-pos (and (org-up-heading-safe) (point)))
12420 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12421 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12422 (forward-line 1)
12423 (re-search-forward org-not-done-heading-regexp pos t)
12424 (setq org-block-entry-blocking (org-get-heading)))
12425 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12427 (defcustom org-track-ordered-property-with-tag nil
12428 "Should the ORDERED property also be shown as a tag?
12429 The ORDERED property decides if an entry should require subtasks to be
12430 completed in sequence. Since a property is not very visible, setting
12431 this option means that toggling the ORDERED property with the command
12432 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12433 not relevant for the behavior, but it makes things more visible.
12435 Note that toggling the tag with tags commands will not change the property
12436 and therefore not influence behavior!
12438 This can be t, meaning the tag ORDERED should be used, It can also be a
12439 string to select a different tag for this task."
12440 :group 'org-todo
12441 :type '(choice
12442 (const :tag "No tracking" nil)
12443 (const :tag "Track with ORDERED tag" t)
12444 (string :tag "Use other tag")))
12446 (defun org-toggle-ordered-property ()
12447 "Toggle the ORDERED property of the current entry.
12448 For better visibility, you can track the value of this property with a tag.
12449 See variable `org-track-ordered-property-with-tag'."
12450 (interactive)
12451 (let* ((t1 org-track-ordered-property-with-tag)
12452 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12453 (save-excursion
12454 (org-back-to-heading)
12455 (if (org-entry-get nil "ORDERED")
12456 (progn
12457 (org-delete-property "ORDERED" "PROPERTIES")
12458 (and tag (org-toggle-tag tag 'off))
12459 (message "Subtasks can be completed in arbitrary order"))
12460 (org-entry-put nil "ORDERED" "t")
12461 (and tag (org-toggle-tag tag 'on))
12462 (message "Subtasks must be completed in sequence")))))
12464 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12465 (defun org-block-todo-from-checkboxes (change-plist)
12466 "Block turning an entry into a TODO, using checkboxes.
12467 This checks whether the current task should be blocked from state
12468 changes because there are unchecked boxes in this entry."
12469 (if (not org-enforce-todo-checkbox-dependencies)
12470 t ; if locally turned off don't block
12471 (catch 'dont-block
12472 ;; If this is not a todo state change, or if this entry is already DONE,
12473 ;; do not block
12474 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12475 (member (plist-get change-plist :from)
12476 (cons 'done org-done-keywords))
12477 (member (plist-get change-plist :to)
12478 (cons 'todo org-not-done-keywords))
12479 (not (plist-get change-plist :to)))
12480 (throw 'dont-block t))
12481 ;; If this task has checkboxes that are not checked, it's blocked
12482 (save-excursion
12483 (org-back-to-heading t)
12484 (let ((beg (point)) end)
12485 (outline-next-heading)
12486 (setq end (point))
12487 (goto-char beg)
12488 (if (org-list-search-forward
12489 (concat (org-item-beginning-re)
12490 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12491 "\\[[- ]\\]")
12492 end t)
12493 (progn
12494 (if (boundp 'org-blocked-by-checkboxes)
12495 (setq org-blocked-by-checkboxes t))
12496 (throw 'dont-block nil)))))
12497 t))) ; do not block
12499 (defun org-entry-blocked-p ()
12500 "Is the current entry blocked?"
12501 (org-with-silent-modifications
12502 (if (org-entry-get nil "NOBLOCKING")
12503 nil ;; Never block this entry
12504 (not (run-hook-with-args-until-failure
12505 'org-blocker-hook
12506 (list :type 'todo-state-change
12507 :position (point)
12508 :from 'todo
12509 :to 'done))))))
12511 (defun org-update-statistics-cookies (all)
12512 "Update the statistics cookie, either from TODO or from checkboxes.
12513 This should be called with the cursor in a line with a statistics cookie."
12514 (interactive "P")
12515 (if all
12516 (progn
12517 (org-update-checkbox-count 'all)
12518 (org-map-entries 'org-update-parent-todo-statistics))
12519 (if (not (org-at-heading-p))
12520 (org-update-checkbox-count)
12521 (let ((pos (point-marker))
12522 end l1 l2)
12523 (ignore-errors (org-back-to-heading t))
12524 (if (not (org-at-heading-p))
12525 (org-update-checkbox-count)
12526 (setq l1 (org-outline-level))
12527 (setq end (save-excursion
12528 (outline-next-heading)
12529 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12530 (point)))
12531 (if (and (save-excursion
12532 (re-search-forward
12533 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12534 (not (save-excursion (re-search-forward
12535 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12536 (org-update-checkbox-count)
12537 (if (and l2 (> l2 l1))
12538 (progn
12539 (goto-char end)
12540 (org-update-parent-todo-statistics))
12541 (goto-char pos)
12542 (beginning-of-line 1)
12543 (while (re-search-forward
12544 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12545 (point-at-eol) t)
12546 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12547 (goto-char pos)
12548 (move-marker pos nil)))))
12550 (defvar org-entry-property-inherited-from) ;; defined below
12551 (defun org-update-parent-todo-statistics ()
12552 "Update any statistics cookie in the parent of the current headline.
12553 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12554 the entire subtree and this will travel up the hierarchy and update
12555 statistics everywhere."
12556 (let* ((prop (save-excursion (org-up-heading-safe)
12557 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12558 (recursive (or (not org-hierarchical-todo-statistics)
12559 (and prop (string-match "\\<recursive\\>" prop))))
12560 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12562 (first t)
12563 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12564 level ltoggle l1 new ndel
12565 (cnt-all 0) (cnt-done 0) is-percent kwd
12566 checkbox-beg ov ovs ove cookie-present)
12567 (catch 'exit
12568 (save-excursion
12569 (beginning-of-line 1)
12570 (setq ltoggle (funcall outline-level))
12571 ;; Three situations are to consider:
12573 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12574 ;; to the top-level ancestor on the headline;
12576 ;; 2. If parent has "recursive" property, repeat up to the
12577 ;; headline setting that property, taking inheritance into
12578 ;; account;
12580 ;; 3. Else, move up to direct parent and proceed only once.
12581 (while (and (setq level (org-up-heading-safe))
12582 (or recursive first)
12583 (>= (point) lim))
12584 (setq first nil cookie-present nil)
12585 (unless (and level
12586 (not (string-match
12587 "\\<checkbox\\>"
12588 (downcase (or (org-entry-get nil "COOKIE_DATA")
12589 "")))))
12590 (throw 'exit nil))
12591 (while (re-search-forward box-re (point-at-eol) t)
12592 (setq cnt-all 0 cnt-done 0 cookie-present t)
12593 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12594 (save-match-data
12595 (unless (outline-next-heading) (throw 'exit nil))
12596 (while (and (looking-at org-complex-heading-regexp)
12597 (> (setq l1 (length (match-string 1))) level))
12598 (setq kwd (and (or recursive (= l1 ltoggle))
12599 (match-string 2)))
12600 (if (or (eq org-provide-todo-statistics 'all-headlines)
12601 (and (listp org-provide-todo-statistics)
12602 (or (member kwd org-provide-todo-statistics)
12603 (member kwd org-done-keywords))))
12604 (setq cnt-all (1+ cnt-all))
12605 (if (eq org-provide-todo-statistics t)
12606 (and kwd (setq cnt-all (1+ cnt-all)))))
12607 (and (member kwd org-done-keywords)
12608 (setq cnt-done (1+ cnt-done)))
12609 (outline-next-heading)))
12610 (setq new
12611 (if is-percent
12612 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12613 (format "[%d/%d]" cnt-done cnt-all))
12614 ndel (- (match-end 0) checkbox-beg))
12615 ;; handle overlays when updating cookie from column view
12616 (when (setq ov (car (overlays-at checkbox-beg)))
12617 (setq ovs (overlay-start ov) ove (overlay-end ov))
12618 (delete-overlay ov))
12619 (goto-char checkbox-beg)
12620 (insert new)
12621 (delete-region (point) (+ (point) ndel))
12622 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12623 (when ov (move-overlay ov ovs ove)))
12624 (when cookie-present
12625 (run-hook-with-args 'org-after-todo-statistics-hook
12626 cnt-done (- cnt-all cnt-done))))))
12627 (run-hooks 'org-todo-statistics-hook)))
12629 (defvar org-after-todo-statistics-hook nil
12630 "Hook that is called after a TODO statistics cookie has been updated.
12631 Each function is called with two arguments: the number of not-done entries
12632 and the number of done entries.
12634 For example, the following function, when added to this hook, will switch
12635 an entry to DONE when all children are done, and back to TODO when new
12636 entries are set to a TODO status. Note that this hook is only called
12637 when there is a statistics cookie in the headline!
12639 (defun org-summary-todo (n-done n-not-done)
12640 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12641 (let (org-log-done org-log-states) ; turn off logging
12642 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12645 (defvar org-todo-statistics-hook nil
12646 "Hook that is run whenever Org thinks TODO statistics should be updated.
12647 This hook runs even if there is no statistics cookie present, in which case
12648 `org-after-todo-statistics-hook' would not run.")
12650 (defun org-todo-trigger-tag-changes (state)
12651 "Apply the changes defined in `org-todo-state-tags-triggers'."
12652 (let ((l org-todo-state-tags-triggers)
12653 changes)
12654 (when (or (not state) (equal state ""))
12655 (setq changes (append changes (cdr (assoc "" l)))))
12656 (when (and (stringp state) (> (length state) 0))
12657 (setq changes (append changes (cdr (assoc state l)))))
12658 (when (member state org-not-done-keywords)
12659 (setq changes (append changes (cdr (assoc 'todo l)))))
12660 (when (member state org-done-keywords)
12661 (setq changes (append changes (cdr (assoc 'done l)))))
12662 (dolist (c changes)
12663 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12665 (defun org-local-logging (value)
12666 "Get logging settings from a property VALUE."
12667 (let* (words w a)
12668 ;; directly set the variables, they are already local.
12669 (setq org-log-done nil
12670 org-log-repeat nil
12671 org-todo-log-states nil)
12672 (setq words (org-split-string value))
12673 (while (setq w (pop words))
12674 (cond
12675 ((setq a (assoc w org-startup-options))
12676 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12677 (set (nth 1 a) (nth 2 a))))
12678 ((setq a (org-extract-log-state-settings w))
12679 (and (member (car a) org-todo-keywords-1)
12680 (push a org-todo-log-states)))))))
12682 (defun org-get-todo-sequence-head (kwd)
12683 "Return the head of the TODO sequence to which KWD belongs.
12684 If KWD is not set, check if there is a text property remembering the
12685 right sequence."
12686 (let (p)
12687 (cond
12688 ((not kwd)
12689 (or (get-text-property (point-at-bol) 'org-todo-head)
12690 (progn
12691 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12692 nil (point-at-eol)))
12693 (get-text-property p 'org-todo-head))))
12694 ((not (member kwd org-todo-keywords-1))
12695 (car org-todo-keywords-1))
12696 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12698 (defun org-fast-todo-selection ()
12699 "Fast TODO keyword selection with single keys.
12700 Returns the new TODO keyword, or nil if no state change should occur."
12701 (let* ((fulltable org-todo-key-alist)
12702 (done-keywords org-done-keywords) ;; needed for the faces.
12703 (maxlen (apply 'max (mapcar
12704 (lambda (x)
12705 (if (stringp (car x)) (string-width (car x)) 0))
12706 fulltable)))
12707 (expert nil)
12708 (fwidth (+ maxlen 3 1 3))
12709 (ncol (/ (- (window-width) 4) fwidth))
12710 tg cnt e c tbl
12711 groups ingroup)
12712 (save-excursion
12713 (save-window-excursion
12714 (if expert
12715 (set-buffer (get-buffer-create " *Org todo*"))
12716 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12717 (erase-buffer)
12718 (org-set-local 'org-done-keywords done-keywords)
12719 (setq tbl fulltable cnt 0)
12720 (while (setq e (pop tbl))
12721 (cond
12722 ((equal e '(:startgroup))
12723 (push '() groups) (setq ingroup t)
12724 (when (not (= cnt 0))
12725 (setq cnt 0)
12726 (insert "\n"))
12727 (insert "{ "))
12728 ((equal e '(:endgroup))
12729 (setq ingroup nil cnt 0)
12730 (insert "}\n"))
12731 ((equal e '(:newline))
12732 (when (not (= cnt 0))
12733 (setq cnt 0)
12734 (insert "\n")
12735 (setq e (car tbl))
12736 (while (equal (car tbl) '(:newline))
12737 (insert "\n")
12738 (setq tbl (cdr tbl)))))
12740 (setq tg (car e) c (cdr e))
12741 (if ingroup (push tg (car groups)))
12742 (setq tg (org-add-props tg nil 'face
12743 (org-get-todo-face tg)))
12744 (if (and (= cnt 0) (not ingroup)) (insert " "))
12745 (insert "[" c "] " tg (make-string
12746 (- fwidth 4 (length tg)) ?\ ))
12747 (when (= (setq cnt (1+ cnt)) ncol)
12748 (insert "\n")
12749 (if ingroup (insert " "))
12750 (setq cnt 0)))))
12751 (insert "\n")
12752 (goto-char (point-min))
12753 (if (not expert) (org-fit-window-to-buffer))
12754 (message "[a-z..]:Set [SPC]:clear")
12755 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12756 (cond
12757 ((or (= c ?\C-g)
12758 (and (= c ?q) (not (rassoc c fulltable))))
12759 (setq quit-flag t))
12760 ((= c ?\ ) nil)
12761 ((setq e (rassoc c fulltable) tg (car e))
12763 (t (setq quit-flag t)))))))
12765 (defun org-entry-is-todo-p ()
12766 (member (org-get-todo-state) org-not-done-keywords))
12768 (defun org-entry-is-done-p ()
12769 (member (org-get-todo-state) org-done-keywords))
12771 (defun org-get-todo-state ()
12772 "Return the TODO keyword of the current subtree."
12773 (save-excursion
12774 (org-back-to-heading t)
12775 (and (looking-at org-todo-line-regexp)
12776 (match-end 2)
12777 (match-string 2))))
12779 (defun org-at-date-range-p (&optional inactive-ok)
12780 "Is the cursor inside a date range?"
12781 (interactive)
12782 (save-excursion
12783 (catch 'exit
12784 (let ((pos (point)))
12785 (skip-chars-backward "^[<\r\n")
12786 (skip-chars-backward "<[")
12787 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12788 (>= (match-end 0) pos)
12789 (throw 'exit t))
12790 (skip-chars-backward "^<[\r\n")
12791 (skip-chars-backward "<[")
12792 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12793 (>= (match-end 0) pos)
12794 (throw 'exit t)))
12795 nil)))
12797 (defun org-get-repeat (&optional tagline)
12798 "Check if there is a deadline/schedule with repeater in this entry."
12799 (save-match-data
12800 (save-excursion
12801 (org-back-to-heading t)
12802 (and (re-search-forward (if tagline
12803 (concat tagline "\\s-*" org-repeat-re)
12804 org-repeat-re)
12805 (org-entry-end-position) t)
12806 (match-string-no-properties 1)))))
12808 (defvar org-last-changed-timestamp)
12809 (defvar org-last-inserted-timestamp)
12810 (defvar org-log-post-message)
12811 (defvar org-log-note-purpose)
12812 (defvar org-log-note-how)
12813 (defvar org-log-note-extra)
12814 (defun org-auto-repeat-maybe (done-word)
12815 "Check if the current headline contains a repeated deadline/schedule.
12816 If yes, set TODO state back to what it was and change the base date
12817 of repeating deadline/scheduled time stamps to new date.
12818 This function is run automatically after each state change to a DONE state."
12819 ;; last-state is dynamically scoped into this function
12820 (let* ((repeat (org-get-repeat))
12821 (aa (assoc org-last-state org-todo-kwd-alist))
12822 (interpret (nth 1 aa))
12823 (head (nth 2 aa))
12824 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12825 (msg "Entry repeats: ")
12826 (org-log-done nil)
12827 (org-todo-log-states nil)
12828 re type n what ts time to-state)
12829 (when repeat
12830 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12831 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12832 org-todo-repeat-to-state))
12833 (unless (and to-state (member to-state org-todo-keywords-1))
12834 (setq to-state (if (eq interpret 'type) org-last-state head)))
12835 (org-todo to-state)
12836 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12837 (org-entry-put nil "LAST_REPEAT" (format-time-string
12838 (org-time-stamp-format t t))))
12839 (when org-log-repeat
12840 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12841 (memq 'org-add-log-note post-command-hook))
12842 ;; OK, we are already setup for some record
12843 (if (eq org-log-repeat 'note)
12844 ;; make sure we take a note, not only a time stamp
12845 (setq org-log-note-how 'note))
12846 ;; Set up for taking a record
12847 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12848 org-last-state
12849 'findpos org-log-repeat)))
12850 (org-back-to-heading t)
12851 (org-add-planning-info nil nil 'closed)
12852 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12853 org-deadline-time-regexp "\\)\\|\\("
12854 org-ts-regexp "\\)"))
12855 (while (re-search-forward
12856 re (save-excursion (outline-next-heading) (point)) t)
12857 (setq type (if (match-end 1) org-scheduled-string
12858 (if (match-end 3) org-deadline-string "Plain:"))
12859 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12860 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12861 (setq n (string-to-number (match-string 2 ts))
12862 what (match-string 3 ts))
12863 (if (equal what "w") (setq n (* n 7) what "d"))
12864 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12865 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12866 ;; Preparation, see if we need to modify the start date for the change
12867 (when (match-end 1)
12868 (setq time (save-match-data (org-time-string-to-time ts)))
12869 (cond
12870 ((equal (match-string 1 ts) ".")
12871 ;; Shift starting date to today
12872 (org-timestamp-change
12873 (- (org-today) (time-to-days time))
12874 'day))
12875 ((equal (match-string 1 ts) "+")
12876 (let ((nshiftmax 10) (nshift 0))
12877 (while (or (= nshift 0)
12878 (<= (time-to-days time)
12879 (time-to-days (current-time))))
12880 (when (= (incf nshift) nshiftmax)
12881 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12882 (error "Abort")))
12883 (org-timestamp-change n (cdr (assoc what whata)))
12884 (org-at-timestamp-p t)
12885 (setq ts (match-string 1))
12886 (setq time (save-match-data (org-time-string-to-time ts)))))
12887 (org-timestamp-change (- n) (cdr (assoc what whata)))
12888 ;; rematch, so that we have everything in place for the real shift
12889 (org-at-timestamp-p t)
12890 (setq ts (match-string 1))
12891 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12892 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12893 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12894 (setq org-log-post-message msg)
12895 (message "%s" msg))))
12897 (defun org-show-todo-tree (arg)
12898 "Make a compact tree which shows all headlines marked with TODO.
12899 The tree will show the lines where the regexp matches, and all higher
12900 headlines above the match.
12901 With a \\[universal-argument] prefix, prompt for a regexp to match.
12902 With a numeric prefix N, construct a sparse tree for the Nth element
12903 of `org-todo-keywords-1'."
12904 (interactive "P")
12905 (let ((case-fold-search nil)
12906 (kwd-re
12907 (cond ((null arg) org-not-done-regexp)
12908 ((equal arg '(4))
12909 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12910 (mapcar 'list org-todo-keywords-1))))
12911 (concat "\\("
12912 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12913 "\\)\\>")))
12914 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12915 (regexp-quote (nth (1- (prefix-numeric-value arg))
12916 org-todo-keywords-1)))
12917 (t (user-error "Invalid prefix argument: %s" arg)))))
12918 (message "%d TODO entries found"
12919 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12921 (defun org-deadline (arg &optional time)
12922 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12923 With one universal prefix argument, remove any deadline from the item.
12924 With two universal prefix arguments, prompt for a warning delay.
12925 With argument TIME, set the deadline at the corresponding date. TIME
12926 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12927 (interactive "P")
12928 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12929 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12930 'region-start-level 'region))
12931 org-loop-over-headlines-in-active-region)
12932 (org-map-entries
12933 `(org-deadline ',arg ,time)
12934 org-loop-over-headlines-in-active-region
12935 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12936 (let* ((old-date (org-entry-get nil "DEADLINE"))
12937 (old-date-time (if old-date (org-time-string-to-time old-date)))
12938 (repeater (and old-date
12939 (string-match
12940 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12941 old-date)
12942 (match-string 1 old-date))))
12943 (cond
12944 ((equal arg '(4))
12945 (when (and old-date org-log-redeadline)
12946 (org-add-log-setup 'deldeadline nil old-date 'findpos
12947 org-log-redeadline))
12948 (org-remove-timestamp-with-keyword org-deadline-string)
12949 (message "Item no longer has a deadline."))
12950 ((equal arg '(16))
12951 (save-excursion
12952 (if (re-search-forward
12953 org-deadline-time-regexp
12954 (save-excursion (outline-next-heading) (point)) t)
12955 (let* ((rpl0 (match-string 1))
12956 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12957 (replace-match
12958 (concat org-deadline-string
12959 " <" rpl
12960 (format " -%dd"
12961 (abs
12962 (- (time-to-days
12963 (save-match-data
12964 (org-read-date nil t nil "Warn starting from" old-date-time)))
12965 (time-to-days old-date-time))))
12966 ">") t t))
12967 (user-error "No deadline information to update"))))
12969 (org-add-planning-info 'deadline time 'closed)
12970 (when (and old-date org-log-redeadline
12971 (not (equal old-date
12972 (substring org-last-inserted-timestamp 1 -1))))
12973 (org-add-log-setup 'redeadline nil old-date 'findpos
12974 org-log-redeadline))
12975 (when repeater
12976 (save-excursion
12977 (org-back-to-heading t)
12978 (when (re-search-forward (concat org-deadline-string " "
12979 org-last-inserted-timestamp)
12980 (save-excursion
12981 (outline-next-heading) (point)) t)
12982 (goto-char (1- (match-end 0)))
12983 (insert " " repeater)
12984 (setq org-last-inserted-timestamp
12985 (concat (substring org-last-inserted-timestamp 0 -1)
12986 " " repeater
12987 (substring org-last-inserted-timestamp -1))))))
12988 (message "Deadline on %s" org-last-inserted-timestamp))))))
12990 (defun org-schedule (arg &optional time)
12991 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12992 With one universal prefix argument, remove any scheduling date from the item.
12993 With two universal prefix arguments, prompt for a delay cookie.
12994 With argument TIME, scheduled at the corresponding date. TIME can
12995 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12996 (interactive "P")
12997 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12998 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12999 'region-start-level 'region))
13000 org-loop-over-headlines-in-active-region)
13001 (org-map-entries
13002 `(org-schedule ',arg ,time)
13003 org-loop-over-headlines-in-active-region
13004 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13005 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13006 (old-date-time (if old-date (org-time-string-to-time old-date)))
13007 (repeater (and old-date
13008 (string-match
13009 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13010 old-date)
13011 (match-string 1 old-date))))
13012 (cond
13013 ((equal arg '(4))
13014 (progn
13015 (when (and old-date org-log-reschedule)
13016 (org-add-log-setup 'delschedule nil old-date 'findpos
13017 org-log-reschedule))
13018 (org-remove-timestamp-with-keyword org-scheduled-string)
13019 (message "Item is no longer scheduled.")))
13020 ((equal arg '(16))
13021 (save-excursion
13022 (if (re-search-forward
13023 org-scheduled-time-regexp
13024 (save-excursion (outline-next-heading) (point)) t)
13025 (let* ((rpl0 (match-string 1))
13026 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13027 (replace-match
13028 (concat org-scheduled-string
13029 " <" rpl
13030 (format " -%dd"
13031 (abs
13032 (- (time-to-days
13033 (save-match-data
13034 (org-read-date nil t nil "Delay until" old-date-time)))
13035 (time-to-days old-date-time))))
13036 ">") t t))
13037 (user-error "No scheduled information to update"))))
13039 (org-add-planning-info 'scheduled time 'closed)
13040 (when (and old-date org-log-reschedule
13041 (not (equal old-date
13042 (substring org-last-inserted-timestamp 1 -1))))
13043 (org-add-log-setup 'reschedule nil old-date 'findpos
13044 org-log-reschedule))
13045 (when repeater
13046 (save-excursion
13047 (org-back-to-heading t)
13048 (when (re-search-forward (concat org-scheduled-string " "
13049 org-last-inserted-timestamp)
13050 (save-excursion
13051 (outline-next-heading) (point)) t)
13052 (goto-char (1- (match-end 0)))
13053 (insert " " repeater)
13054 (setq org-last-inserted-timestamp
13055 (concat (substring org-last-inserted-timestamp 0 -1)
13056 " " repeater
13057 (substring org-last-inserted-timestamp -1))))))
13058 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13060 (defun org-get-scheduled-time (pom &optional inherit)
13061 "Get the scheduled time as a time tuple, of a format suitable
13062 for calling org-schedule with, or if there is no scheduling,
13063 returns nil."
13064 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13065 (when time
13066 (apply 'encode-time (org-parse-time-string time)))))
13068 (defun org-get-deadline-time (pom &optional inherit)
13069 "Get the deadline as a time tuple, of a format suitable for
13070 calling org-deadline with, or if there is no scheduling, returns
13071 nil."
13072 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13073 (when time
13074 (apply 'encode-time (org-parse-time-string time)))))
13076 (defun org-remove-timestamp-with-keyword (keyword)
13077 "Remove all time stamps with KEYWORD in the current entry."
13078 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13079 beg)
13080 (save-excursion
13081 (org-back-to-heading t)
13082 (setq beg (point))
13083 (outline-next-heading)
13084 (while (re-search-backward re beg t)
13085 (replace-match "")
13086 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13087 (equal (char-before) ?\ ))
13088 (backward-delete-char 1)
13089 (if (string-match "^[ \t]*$" (buffer-substring
13090 (point-at-bol) (point-at-eol)))
13091 (delete-region (point-at-bol)
13092 (min (point-max) (1+ (point-at-eol))))))))))
13094 (defun org-add-planning-info (what &optional time &rest remove)
13095 "Insert new timestamp with keyword in the line directly after the headline.
13096 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13097 If non is given, the user is prompted for a date.
13098 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13099 be removed."
13100 (interactive)
13101 (let (org-time-was-given org-end-time-was-given ts
13102 end default-time default-input)
13104 (catch 'exit
13105 (when (and (memq what '(scheduled deadline))
13106 (or (not time)
13107 (and (stringp time)
13108 (string-match "^[-+]+[0-9]" time))))
13109 ;; Try to get a default date/time from existing timestamp
13110 (save-excursion
13111 (org-back-to-heading t)
13112 (setq end (save-excursion (outline-next-heading) (point)))
13113 (when (re-search-forward (if (eq what 'scheduled)
13114 org-scheduled-time-regexp
13115 org-deadline-time-regexp)
13116 end t)
13117 (setq ts (match-string 1)
13118 default-time
13119 (apply 'encode-time (org-parse-time-string ts))
13120 default-input (and ts (org-get-compact-tod ts))))))
13121 (when what
13122 (setq time
13123 (if (stringp time)
13124 ;; This is a string (relative or absolute), set proper date
13125 (apply 'encode-time
13126 (org-read-date-analyze
13127 time default-time (decode-time default-time)))
13128 ;; If necessary, get the time from the user
13129 (or time (org-read-date nil 'to-time nil nil
13130 default-time default-input)))))
13132 (when (and org-insert-labeled-timestamps-at-point
13133 (member what '(scheduled deadline)))
13134 (insert
13135 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13136 (org-insert-time-stamp time org-time-was-given
13137 nil nil nil (list org-end-time-was-given))
13138 (setq what nil))
13139 (save-excursion
13140 (save-restriction
13141 (let (col list elt ts buffer-invisibility-spec)
13142 (org-back-to-heading t)
13143 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13144 (goto-char (match-end 1))
13145 (setq col (current-column))
13146 (goto-char (match-end 0))
13147 (if (eobp) (insert "\n") (forward-char 1))
13148 (when (and (not what)
13149 (not (looking-at
13150 (concat "[ \t]*"
13151 org-keyword-time-not-clock-regexp))))
13152 ;; Nothing to add, nothing to remove...... :-)
13153 (throw 'exit nil))
13154 (if (and (not (looking-at org-outline-regexp))
13155 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13156 "[^\r\n]*"))
13157 (not (equal (match-string 1) org-clock-string)))
13158 (narrow-to-region (match-beginning 0) (match-end 0))
13159 (insert-before-markers "\n")
13160 (backward-char 1)
13161 (narrow-to-region (point) (point))
13162 (and org-adapt-indentation (org-indent-to-column col)))
13163 ;; Check if we have to remove something.
13164 (setq list (cons what remove))
13165 (while list
13166 (setq elt (pop list))
13167 (when (or (and (eq elt 'scheduled)
13168 (re-search-forward org-scheduled-time-regexp nil t))
13169 (and (eq elt 'deadline)
13170 (re-search-forward org-deadline-time-regexp nil t))
13171 (and (eq elt 'closed)
13172 (re-search-forward org-closed-time-regexp nil t)))
13173 (replace-match "")
13174 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13175 (and (looking-at "[ \t]+") (replace-match ""))
13176 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13177 (when what
13178 (insert
13179 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13180 (cond ((eq what 'scheduled) org-scheduled-string)
13181 ((eq what 'deadline) org-deadline-string)
13182 ((eq what 'closed) org-closed-string))
13183 " ")
13184 (setq ts (org-insert-time-stamp
13185 time
13186 (or org-time-was-given
13187 (and (eq what 'closed) org-log-done-with-time))
13188 (eq what 'closed)
13189 nil nil (list org-end-time-was-given)))
13190 (insert
13191 (if (not (or (bolp) (eq (char-before) ?\ )
13192 (memq (char-after) '(32 10))
13193 (eobp))) " " ""))
13194 (end-of-line 1))
13195 (goto-char (point-min))
13196 (widen)
13197 (if (and (looking-at "[ \t]*\n")
13198 (equal (char-before) ?\n))
13199 (delete-region (1- (point)) (point-at-eol)))
13200 ts))))))
13202 (defvar org-log-note-marker (make-marker))
13203 (defvar org-log-note-purpose nil)
13204 (defvar org-log-note-state nil)
13205 (defvar org-log-note-previous-state nil)
13206 (defvar org-log-note-how nil)
13207 (defvar org-log-note-extra nil)
13208 (defvar org-log-note-window-configuration nil)
13209 (defvar org-log-note-return-to (make-marker))
13210 (defvar org-log-note-effective-time nil
13211 "Remembered current time so that dynamically scoped
13212 `org-extend-today-until' affects tha timestamps in state change
13213 log")
13215 (defvar org-log-post-message nil
13216 "Message to be displayed after a log note has been stored.
13217 The auto-repeater uses this.")
13219 (defun org-add-note ()
13220 "Add a note to the current entry.
13221 This is done in the same way as adding a state change note."
13222 (interactive)
13223 (org-add-log-setup 'note nil nil 'findpos nil))
13225 (defvar org-property-end-re)
13226 (defun org-add-log-setup (&optional purpose state prev-state
13227 findpos how extra)
13228 "Set up the post command hook to take a note.
13229 If this is about to TODO state change, the new state is expected in STATE.
13230 When FINDPOS is non-nil, find the correct position for the note in
13231 the current entry. If not, assume that it can be inserted at point.
13232 HOW is an indicator what kind of note should be created.
13233 EXTRA is additional text that will be inserted into the notes buffer."
13234 (let* ((org-log-into-drawer (org-log-into-drawer))
13235 (drawer (cond ((stringp org-log-into-drawer)
13236 org-log-into-drawer)
13237 (org-log-into-drawer "LOGBOOK"))))
13238 (save-restriction
13239 (save-excursion
13240 (when findpos
13241 (org-back-to-heading t)
13242 (narrow-to-region (point) (save-excursion
13243 (outline-next-heading) (point)))
13244 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13245 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13246 "[^\r\n]*\\)?"))
13247 (goto-char (match-end 0))
13248 (cond
13249 (drawer
13250 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13251 nil t)
13252 (progn
13253 (goto-char (match-end 0))
13254 (or org-log-states-order-reversed
13255 (and (re-search-forward org-property-end-re nil t)
13256 (goto-char (1- (match-beginning 0))))))
13257 (insert "\n:" drawer ":\n:END:")
13258 (beginning-of-line 0)
13259 (org-indent-line)
13260 (beginning-of-line 2)
13261 (org-indent-line)
13262 (end-of-line 0)))
13263 ((and org-log-state-notes-insert-after-drawers
13264 (save-excursion
13265 (forward-line) (looking-at org-drawer-regexp)))
13266 (forward-line)
13267 (while (looking-at org-drawer-regexp)
13268 (goto-char (match-end 0))
13269 (re-search-forward org-property-end-re (point-max) t)
13270 (forward-line))
13271 (forward-line -1)))
13272 (unless org-log-states-order-reversed
13273 (and (= (char-after) ?\n) (forward-char 1))
13274 (org-skip-over-state-notes)
13275 (skip-chars-backward " \t\n\r")))
13276 (move-marker org-log-note-marker (point))
13277 (setq org-log-note-purpose purpose
13278 org-log-note-state state
13279 org-log-note-previous-state prev-state
13280 org-log-note-how how
13281 org-log-note-extra extra
13282 org-log-note-effective-time (org-current-effective-time))
13283 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13285 (defun org-skip-over-state-notes ()
13286 "Skip past the list of State notes in an entry."
13287 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13288 (when (ignore-errors (goto-char (org-in-item-p)))
13289 (let* ((struct (org-list-struct))
13290 (prevs (org-list-prevs-alist struct)))
13291 (while (looking-at "[ \t]*- State")
13292 (goto-char (or (org-list-get-next-item (point) struct prevs)
13293 (org-list-get-item-end (point) struct)))))))
13295 (defun org-add-log-note (&optional purpose)
13296 "Pop up a window for taking a note, and add this note later at point."
13297 (remove-hook 'post-command-hook 'org-add-log-note)
13298 (setq org-log-note-window-configuration (current-window-configuration))
13299 (delete-other-windows)
13300 (move-marker org-log-note-return-to (point))
13301 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13302 (goto-char org-log-note-marker)
13303 (org-switch-to-buffer-other-window "*Org Note*")
13304 (erase-buffer)
13305 (if (memq org-log-note-how '(time state))
13306 (let (current-prefix-arg) (org-store-log-note))
13307 (let ((org-inhibit-startup t)) (org-mode))
13308 (insert (format "# Insert note for %s.
13309 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13310 (cond
13311 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13312 ((eq org-log-note-purpose 'done) "closed todo item")
13313 ((eq org-log-note-purpose 'state)
13314 (format "state change from \"%s\" to \"%s\""
13315 (or org-log-note-previous-state "")
13316 (or org-log-note-state "")))
13317 ((eq org-log-note-purpose 'reschedule)
13318 "rescheduling")
13319 ((eq org-log-note-purpose 'delschedule)
13320 "no longer scheduled")
13321 ((eq org-log-note-purpose 'redeadline)
13322 "changing deadline")
13323 ((eq org-log-note-purpose 'deldeadline)
13324 "removing deadline")
13325 ((eq org-log-note-purpose 'refile)
13326 "refiling")
13327 ((eq org-log-note-purpose 'note)
13328 "this entry")
13329 (t (error "This should not happen")))))
13330 (if org-log-note-extra (insert org-log-note-extra))
13331 (org-set-local 'org-finish-function 'org-store-log-note)
13332 (run-hooks 'org-log-buffer-setup-hook)))
13334 (defvar org-note-abort nil) ; dynamically scoped
13335 (defun org-store-log-note ()
13336 "Finish taking a log note, and insert it to where it belongs."
13337 (let ((txt (buffer-string)))
13338 (kill-buffer (current-buffer))
13339 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13340 lines ind bul)
13341 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13342 (setq txt (replace-match "" t t txt)))
13343 (if (string-match "\\s-+\\'" txt)
13344 (setq txt (replace-match "" t t txt)))
13345 (setq lines (org-split-string txt "\n"))
13346 (when (and note (string-match "\\S-" note))
13347 (setq note
13348 (org-replace-escapes
13349 note
13350 (list (cons "%u" (user-login-name))
13351 (cons "%U" user-full-name)
13352 (cons "%t" (format-time-string
13353 (org-time-stamp-format 'long 'inactive)
13354 org-log-note-effective-time))
13355 (cons "%T" (format-time-string
13356 (org-time-stamp-format 'long nil)
13357 org-log-note-effective-time))
13358 (cons "%d" (format-time-string
13359 (org-time-stamp-format nil 'inactive)
13360 org-log-note-effective-time))
13361 (cons "%D" (format-time-string
13362 (org-time-stamp-format nil nil)
13363 org-log-note-effective-time))
13364 (cons "%s" (if org-log-note-state
13365 (concat "\"" org-log-note-state "\"")
13366 ""))
13367 (cons "%S" (if org-log-note-previous-state
13368 (concat "\"" org-log-note-previous-state "\"")
13369 "\"\"")))))
13370 (if lines (setq note (concat note " \\\\")))
13371 (push note lines))
13372 (when (or current-prefix-arg org-note-abort)
13373 (when org-log-into-drawer
13374 (org-remove-empty-drawer-at
13375 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13376 org-log-note-marker))
13377 (setq lines nil))
13378 (when lines
13379 (with-current-buffer (marker-buffer org-log-note-marker)
13380 (save-excursion
13381 (goto-char org-log-note-marker)
13382 (move-marker org-log-note-marker nil)
13383 (end-of-line 1)
13384 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13385 (setq ind (save-excursion
13386 (if (ignore-errors (goto-char (org-in-item-p)))
13387 (let ((struct (org-list-struct)))
13388 (org-list-get-ind
13389 (org-list-get-top-point struct) struct))
13390 (skip-chars-backward " \r\t\n")
13391 (cond
13392 ((and (org-at-heading-p)
13393 org-adapt-indentation)
13394 (1+ (org-current-level)))
13395 ((org-at-heading-p) 0)
13396 (t (org-get-indentation))))))
13397 (setq bul (org-list-bullet-string "-"))
13398 (org-indent-line-to ind)
13399 (insert bul (pop lines))
13400 (let ((ind-body (+ (length bul) ind)))
13401 (while lines
13402 (insert "\n")
13403 (org-indent-line-to ind-body)
13404 (insert (pop lines))))
13405 (message "Note stored")
13406 (org-back-to-heading t)
13407 (org-cycle-hide-drawers 'children))
13408 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13409 ;; from within `org-add-log-note' because `buffer-undo-list'
13410 ;; is then modified outside of `org-with-remote-undo'.
13411 (when (eq this-command 'org-agenda-todo)
13412 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13413 ;; Don't add undo information when called from `org-agenda-todo'
13414 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13415 (set-window-configuration org-log-note-window-configuration)
13416 (with-current-buffer (marker-buffer org-log-note-return-to)
13417 (goto-char org-log-note-return-to))
13418 (move-marker org-log-note-return-to nil)
13419 (and org-log-post-message (message "%s" org-log-post-message))))
13421 (defun org-remove-empty-drawer-at (drawer pos)
13422 "Remove an empty drawer DRAWER at position POS.
13423 POS may also be a marker."
13424 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13425 (save-excursion
13426 (save-restriction
13427 (widen)
13428 (goto-char pos)
13429 (if (org-in-regexp
13430 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13431 (replace-match ""))))))
13433 (defvar org-ts-type nil)
13434 (defun org-sparse-tree (&optional arg type)
13435 "Create a sparse tree, prompt for the details.
13436 This command can create sparse trees. You first need to select the type
13437 of match used to create the tree:
13439 t Show all TODO entries.
13440 T Show entries with a specific TODO keyword.
13441 m Show entries selected by a tags/property match.
13442 p Enter a property name and its value (both with completion on existing
13443 names/values) and show entries with that property.
13444 r Show entries matching a regular expression (`/' can be used as well).
13445 b Show deadlines and scheduled items before a date.
13446 a Show deadlines and scheduled items after a date.
13447 d Show deadlines due within `org-deadline-warning-days'.
13448 D Show deadlines and scheduled items between a date range."
13449 (interactive "P")
13450 (let (ans kwd value ts-type)
13451 (setq type (or type org-sparse-tree-default-date-type))
13452 (setq org-ts-type type)
13453 (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"
13454 (cond ((eq type 'all) "all timestamps")
13455 ((eq type 'scheduled) "only scheduled")
13456 ((eq type 'deadline) "only deadline")
13457 ((eq type 'active) "only active timestamps")
13458 ((eq type 'inactive) "only inactive timestamps")
13459 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13460 ((eq type 'closed) "with a closed time-stamp")
13461 (t "scheduled/deadline")))
13462 (setq ans (read-char-exclusive))
13463 (cond
13464 ((equal ans ?c)
13465 (org-sparse-tree
13466 arg (cadr (member type '(scheduled-or-deadline
13467 all scheduled deadline active inactive closed)))))
13468 ((equal ans ?d)
13469 (call-interactively 'org-check-deadlines))
13470 ((equal ans ?b)
13471 (call-interactively 'org-check-before-date))
13472 ((equal ans ?a)
13473 (call-interactively 'org-check-after-date))
13474 ((equal ans ?D)
13475 (call-interactively 'org-check-dates-range))
13476 ((equal ans ?t)
13477 (call-interactively 'org-show-todo-tree))
13478 ((equal ans ?T)
13479 (org-show-todo-tree '(4)))
13480 ((member ans '(?T ?m))
13481 (call-interactively 'org-match-sparse-tree))
13482 ((member ans '(?p ?P))
13483 (setq kwd (org-icompleting-read "Property: "
13484 (mapcar 'list (org-buffer-property-keys))))
13485 (setq value (org-icompleting-read "Value: "
13486 (mapcar 'list (org-property-values kwd))))
13487 (unless (string-match "\\`{.*}\\'" value)
13488 (setq value (concat "\"" value "\"")))
13489 (org-match-sparse-tree arg (concat kwd "=" value)))
13490 ((member ans '(?r ?R ?/))
13491 (call-interactively 'org-occur))
13492 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13494 (defvar org-occur-highlights nil
13495 "List of overlays used for occur matches.")
13496 (make-variable-buffer-local 'org-occur-highlights)
13497 (defvar org-occur-parameters nil
13498 "Parameters of the active org-occur calls.
13499 This is a list, each call to org-occur pushes as cons cell,
13500 containing the regular expression and the callback, onto the list.
13501 The list can contain several entries if `org-occur' has been called
13502 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13503 will only contain one set of parameters. When the highlights are
13504 removed (for example with `C-c C-c', or with the next edit (depending
13505 on `org-remove-highlights-with-change'), this variable is emptied
13506 as well.")
13507 (make-variable-buffer-local 'org-occur-parameters)
13509 (defun org-occur (regexp &optional keep-previous callback)
13510 "Make a compact tree which shows all matches of REGEXP.
13511 The tree will show the lines where the regexp matches, and all higher
13512 headlines above the match. It will also show the heading after the match,
13513 to make sure editing the matching entry is easy.
13514 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13515 call to `org-occur' will be kept, to allow stacking of calls to this
13516 command.
13517 If CALLBACK is non-nil, it is a function which is called to confirm
13518 that the match should indeed be shown."
13519 (interactive "sRegexp: \nP")
13520 (when (equal regexp "")
13521 (user-error "Regexp cannot be empty"))
13522 (unless keep-previous
13523 (org-remove-occur-highlights nil nil t))
13524 (push (cons regexp callback) org-occur-parameters)
13525 (let ((cnt 0))
13526 (save-excursion
13527 (goto-char (point-min))
13528 (if (or (not keep-previous) ; do not want to keep
13529 (not org-occur-highlights)) ; no previous matches
13530 ;; hide everything
13531 (org-overview))
13532 (while (re-search-forward regexp nil t)
13533 (when (or (not callback)
13534 (save-match-data (funcall callback)))
13535 (setq cnt (1+ cnt))
13536 (when org-highlight-sparse-tree-matches
13537 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13538 (org-show-context 'occur-tree))))
13539 (when org-remove-highlights-with-change
13540 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13541 nil 'local))
13542 (unless org-sparse-tree-open-archived-trees
13543 (org-hide-archived-subtrees (point-min) (point-max)))
13544 (run-hooks 'org-occur-hook)
13545 (if (org-called-interactively-p 'interactive)
13546 (message "%d match(es) for regexp %s" cnt regexp))
13547 cnt))
13549 (defun org-occur-next-match (&optional n reset)
13550 "Function for `next-error-function' to find sparse tree matches.
13551 N is the number of matches to move, when negative move backwards.
13552 RESET is entirely ignored - this function always goes back to the
13553 starting point when no match is found."
13554 (let* ((limit (if (< n 0) (point-min) (point-max)))
13555 (search-func (if (< n 0)
13556 'previous-single-char-property-change
13557 'next-single-char-property-change))
13558 (n (abs n))
13559 (pos (point))
13561 (catch 'exit
13562 (while (setq p1 (funcall search-func (point) 'org-type))
13563 (when (equal p1 limit)
13564 (goto-char pos)
13565 (error "No more matches"))
13566 (when (equal (get-char-property p1 'org-type) 'org-occur)
13567 (setq n (1- n))
13568 (when (= n 0)
13569 (goto-char p1)
13570 (throw 'exit (point))))
13571 (goto-char p1))
13572 (goto-char p1)
13573 (error "No more matches"))))
13575 (defun org-show-context (&optional key)
13576 "Make sure point and context are visible.
13577 How much context is shown depends upon the variables
13578 `org-show-hierarchy-above', `org-show-following-heading',
13579 `org-show-entry-below' and `org-show-siblings'."
13580 (let ((heading-p (org-at-heading-p t))
13581 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13582 (following-p (org-get-alist-option org-show-following-heading key))
13583 (entry-p (org-get-alist-option org-show-entry-below key))
13584 (siblings-p (org-get-alist-option org-show-siblings key)))
13585 ;; Show heading or entry text
13586 (if (and heading-p (not entry-p))
13587 (org-flag-heading nil) ; only show the heading
13588 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13589 (org-show-hidden-entry))) ; show entire entry
13590 (when following-p
13591 ;; Show next sibling, or heading below text
13592 (save-excursion
13593 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13594 (org-flag-heading nil))))
13595 (when siblings-p (org-show-siblings))
13596 (when hierarchy-p
13597 ;; show all higher headings, possibly with siblings
13598 (save-excursion
13599 (while (and (condition-case nil
13600 (progn (org-up-heading-all 1) t)
13601 (error nil))
13602 (not (bobp)))
13603 (org-flag-heading nil)
13604 (when siblings-p (org-show-siblings)))))
13605 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13607 (defvar org-reveal-start-hook nil
13608 "Hook run before revealing a location.")
13610 (defun org-reveal (&optional siblings)
13611 "Show current entry, hierarchy above it, and the following headline.
13612 This can be used to show a consistent set of context around locations
13613 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13614 not t for the search context.
13616 With optional argument SIBLINGS, on each level of the hierarchy all
13617 siblings are shown. This repairs the tree structure to what it would
13618 look like when opened with hierarchical calls to `org-cycle'.
13619 With double optional argument \\[universal-argument] \\[universal-argument], \
13620 go to the parent and show the
13621 entire tree."
13622 (interactive "P")
13623 (run-hooks 'org-reveal-start-hook)
13624 (let ((org-show-hierarchy-above t)
13625 (org-show-following-heading t)
13626 (org-show-siblings (if siblings t org-show-siblings)))
13627 (org-show-context nil))
13628 (when (equal siblings '(16))
13629 (save-excursion
13630 (when (org-up-heading-safe)
13631 (org-show-subtree)
13632 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13634 (defun org-highlight-new-match (beg end)
13635 "Highlight from BEG to END and mark the highlight is an occur headline."
13636 (let ((ov (make-overlay beg end)))
13637 (overlay-put ov 'face 'secondary-selection)
13638 (overlay-put ov 'org-type 'org-occur)
13639 (push ov org-occur-highlights)))
13641 (defun org-remove-occur-highlights (&optional beg end noremove)
13642 "Remove the occur highlights from the buffer.
13643 BEG and END are ignored. If NOREMOVE is nil, remove this function
13644 from the `before-change-functions' in the current buffer."
13645 (interactive)
13646 (unless org-inhibit-highlight-removal
13647 (mapc 'delete-overlay org-occur-highlights)
13648 (setq org-occur-highlights nil)
13649 (setq org-occur-parameters nil)
13650 (unless noremove
13651 (remove-hook 'before-change-functions
13652 'org-remove-occur-highlights 'local))))
13654 ;;;; Priorities
13656 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13657 "Regular expression matching the priority indicator.")
13659 (defvar org-remove-priority-next-time nil)
13661 (defun org-priority-up ()
13662 "Increase the priority of the current item."
13663 (interactive)
13664 (org-priority 'up))
13666 (defun org-priority-down ()
13667 "Decrease the priority of the current item."
13668 (interactive)
13669 (org-priority 'down))
13671 (defun org-priority (&optional action show)
13672 "Change the priority of an item.
13673 ACTION can be `set', `up', `down', or a character."
13674 (interactive "P")
13675 (if (equal action '(4))
13676 (org-show-priority)
13677 (unless org-enable-priority-commands
13678 (user-error "Priority commands are disabled"))
13679 (setq action (or action 'set))
13680 (let (current new news have remove)
13681 (save-excursion
13682 (org-back-to-heading t)
13683 (if (looking-at org-priority-regexp)
13684 (setq current (string-to-char (match-string 2))
13685 have t))
13686 (cond
13687 ((eq action 'remove)
13688 (setq remove t new ?\ ))
13689 ((or (eq action 'set)
13690 (if (featurep 'xemacs) (characterp action) (integerp action)))
13691 (if (not (eq action 'set))
13692 (setq new action)
13693 (message "Priority %c-%c, SPC to remove: "
13694 org-highest-priority org-lowest-priority)
13695 (save-match-data
13696 (setq new (read-char-exclusive))))
13697 (if (and (= (upcase org-highest-priority) org-highest-priority)
13698 (= (upcase org-lowest-priority) org-lowest-priority))
13699 (setq new (upcase new)))
13700 (cond ((equal new ?\ ) (setq remove t))
13701 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13702 (user-error "Priority must be between `%c' and `%c'"
13703 org-highest-priority org-lowest-priority))))
13704 ((eq action 'up)
13705 (setq new (if have
13706 (1- current) ; normal cycling
13707 ;; last priority was empty
13708 (if (eq last-command this-command)
13709 org-lowest-priority ; wrap around empty to lowest
13710 ;; default
13711 (if org-priority-start-cycle-with-default
13712 org-default-priority
13713 (1- org-default-priority))))))
13714 ((eq action 'down)
13715 (setq new (if have
13716 (1+ current) ; normal cycling
13717 ;; last priority was empty
13718 (if (eq last-command this-command)
13719 org-highest-priority ; wrap around empty to highest
13720 ;; default
13721 (if org-priority-start-cycle-with-default
13722 org-default-priority
13723 (1+ org-default-priority))))))
13724 (t (user-error "Invalid action")))
13725 (if (or (< (upcase new) org-highest-priority)
13726 (> (upcase new) org-lowest-priority))
13727 (if (and (memq action '(up down))
13728 (not have) (not (eq last-command this-command)))
13729 ;; `new' is from default priority
13730 (error
13731 "The default can not be set, see `org-default-priority' why")
13732 ;; normal cycling: `new' is beyond highest/lowest priority
13733 ;; and is wrapped around to the empty priority
13734 (setq remove t)))
13735 (setq news (format "%c" new))
13736 (if have
13737 (if remove
13738 (replace-match "" t t nil 1)
13739 (replace-match news t t nil 2))
13740 (if remove
13741 (user-error "No priority cookie found in line")
13742 (let ((case-fold-search nil))
13743 (looking-at org-todo-line-regexp))
13744 (if (match-end 2)
13745 (progn
13746 (goto-char (match-end 2))
13747 (insert " [#" news "]"))
13748 (goto-char (match-beginning 3))
13749 (insert "[#" news "] "))))
13750 (org-preserve-lc (org-set-tags nil 'align)))
13751 (if remove
13752 (message "Priority removed")
13753 (message "Priority of current item set to %s" news)))))
13755 (defun org-show-priority ()
13756 "Show the priority of the current item.
13757 This priority is composed of the main priority given with the [#A] cookies,
13758 and by additional input from the age of a schedules or deadline entry."
13759 (interactive)
13760 (let ((pri (if (eq major-mode 'org-agenda-mode)
13761 (org-get-at-bol 'priority)
13762 (save-excursion
13763 (save-match-data
13764 (beginning-of-line)
13765 (and (looking-at org-heading-regexp)
13766 (org-get-priority (match-string 0))))))))
13767 (message "Priority is %d" (if pri pri -1000))))
13769 (defun org-get-priority (s)
13770 "Find priority cookie and return priority."
13771 (save-match-data
13772 (if (functionp org-get-priority-function)
13773 (funcall org-get-priority-function)
13774 (if (not (string-match org-priority-regexp s))
13775 (* 1000 (- org-lowest-priority org-default-priority))
13776 (* 1000 (- org-lowest-priority
13777 (string-to-char (match-string 2 s))))))))
13779 ;;;; Tags
13781 (defvar org-agenda-archives-mode)
13782 (defvar org-map-continue-from nil
13783 "Position from where mapping should continue.
13784 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13786 (defvar org-scanner-tags nil
13787 "The current tag list while the tags scanner is running.")
13788 (defvar org-trust-scanner-tags nil
13789 "Should `org-get-tags-at' use the tags for the scanner.
13790 This is for internal dynamical scoping only.
13791 When this is non-nil, the function `org-get-tags-at' will return the value
13792 of `org-scanner-tags' instead of building the list by itself. This
13793 can lead to large speed-ups when the tags scanner is used in a file with
13794 many entries, and when the list of tags is retrieved, for example to
13795 obtain a list of properties. Building the tags list for each entry in such
13796 a file becomes an N^2 operation - but with this variable set, it scales
13797 as N.")
13799 (defun org-scan-tags (action matcher todo-only &optional start-level)
13800 "Sca headline tags with inheritance and produce output ACTION.
13802 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13803 or `agenda' to produce an entry list for an agenda view. It can also be
13804 a Lisp form or a function that should be called at each matched headline, in
13805 this case the return value is a list of all return values from these calls.
13807 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13808 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13809 only lines with a not-done TODO keyword are included in the output.
13810 This should be the same variable that was scoped into
13811 and set by `org-make-tags-matcher' when it constructed MATCHER.
13813 START-LEVEL can be a string with asterisks, reducing the scope to
13814 headlines matching this string."
13815 (require 'org-agenda)
13816 (let* ((re (concat "^"
13817 (if start-level
13818 ;; Get the correct level to match
13819 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13820 org-outline-regexp)
13821 " *\\(\\<\\("
13822 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13823 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13824 (props (list 'face 'default
13825 'done-face 'org-agenda-done
13826 'undone-face 'default
13827 'mouse-face 'highlight
13828 'org-not-done-regexp org-not-done-regexp
13829 'org-todo-regexp org-todo-regexp
13830 'org-complex-heading-regexp org-complex-heading-regexp
13831 'help-echo
13832 (format "mouse-2 or RET jump to org file %s"
13833 (abbreviate-file-name
13834 (or (buffer-file-name (buffer-base-buffer))
13835 (buffer-name (buffer-base-buffer)))))))
13836 (org-map-continue-from nil)
13837 lspos tags tags-list
13838 (tags-alist (list (cons 0 org-file-tags)))
13839 (llast 0) rtn rtn1 level category i txt
13840 todo marker entry priority)
13841 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13842 (setq action (list 'lambda nil action)))
13843 (save-excursion
13844 (goto-char (point-min))
13845 (when (eq action 'sparse-tree)
13846 (org-overview)
13847 (org-remove-occur-highlights))
13848 (while (let (case-fold-search)
13849 (re-search-forward re nil t))
13850 (setq org-map-continue-from nil)
13851 (catch :skip
13852 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13853 tags (if (match-end 4) (org-match-string-no-properties 4)))
13854 (goto-char (setq lspos (match-beginning 0)))
13855 (setq level (org-reduced-level (org-outline-level))
13856 category (org-get-category))
13857 (setq i llast llast level)
13858 ;; remove tag lists from same and sublevels
13859 (while (>= i level)
13860 (when (setq entry (assoc i tags-alist))
13861 (setq tags-alist (delete entry tags-alist)))
13862 (setq i (1- i)))
13863 ;; add the next tags
13864 (when tags
13865 (setq tags (org-split-string tags ":")
13866 tags-alist
13867 (cons (cons level tags) tags-alist)))
13868 ;; compile tags for current headline
13869 (setq tags-list
13870 (if org-use-tag-inheritance
13871 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13872 tags)
13873 org-scanner-tags tags-list)
13874 (when org-use-tag-inheritance
13875 (setcdr (car tags-alist)
13876 (mapcar (lambda (x)
13877 (setq x (copy-sequence x))
13878 (org-add-prop-inherited x))
13879 (cdar tags-alist))))
13880 (when (and tags org-use-tag-inheritance
13881 (or (not (eq t org-use-tag-inheritance))
13882 org-tags-exclude-from-inheritance))
13883 ;; selective inheritance, remove uninherited ones
13884 (setcdr (car tags-alist)
13885 (org-remove-uninherited-tags (cdar tags-alist))))
13886 (when (and
13888 ;; eval matcher only when the todo condition is OK
13889 (and (or (not todo-only) (member todo org-not-done-keywords))
13890 (let ((case-fold-search t) (org-trust-scanner-tags t))
13891 (eval matcher)))
13893 ;; Call the skipper, but return t if it does not skip,
13894 ;; so that the `and' form continues evaluating
13895 (progn
13896 (unless (eq action 'sparse-tree) (org-agenda-skip))
13899 ;; Check if timestamps are deselecting this entry
13900 (or (not todo-only)
13901 (and (member todo org-not-done-keywords)
13902 (or (not org-agenda-tags-todo-honor-ignore-options)
13903 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13905 ;; select this headline
13906 (cond
13907 ((eq action 'sparse-tree)
13908 (and org-highlight-sparse-tree-matches
13909 (org-get-heading) (match-end 0)
13910 (org-highlight-new-match
13911 (match-beginning 1) (match-end 1)))
13912 (org-show-context 'tags-tree))
13913 ((eq action 'agenda)
13914 (setq txt (org-agenda-format-item
13916 (concat
13917 (if (eq org-tags-match-list-sublevels 'indented)
13918 (make-string (1- level) ?.) "")
13919 (org-get-heading))
13920 level category
13921 tags-list)
13922 priority (org-get-priority txt))
13923 (goto-char lspos)
13924 (setq marker (org-agenda-new-marker))
13925 (org-add-props txt props
13926 'org-marker marker 'org-hd-marker marker 'org-category category
13927 'todo-state todo
13928 'priority priority 'type "tagsmatch")
13929 (push txt rtn))
13930 ((functionp action)
13931 (setq org-map-continue-from nil)
13932 (save-excursion
13933 (setq rtn1 (funcall action))
13934 (push rtn1 rtn)))
13935 (t (user-error "Invalid action")))
13937 ;; if we are to skip sublevels, jump to end of subtree
13938 (unless org-tags-match-list-sublevels
13939 (org-end-of-subtree t)
13940 (backward-char 1))))
13941 ;; Get the correct position from where to continue
13942 (if org-map-continue-from
13943 (goto-char org-map-continue-from)
13944 (and (= (point) lspos) (end-of-line 1)))))
13945 (when (and (eq action 'sparse-tree)
13946 (not org-sparse-tree-open-archived-trees))
13947 (org-hide-archived-subtrees (point-min) (point-max)))
13948 (nreverse rtn)))
13950 (defun org-remove-uninherited-tags (tags)
13951 "Remove all tags that are not inherited from the list TAGS."
13952 (cond
13953 ((eq org-use-tag-inheritance t)
13954 (if org-tags-exclude-from-inheritance
13955 (org-delete-all org-tags-exclude-from-inheritance tags)
13956 tags))
13957 ((not org-use-tag-inheritance) nil)
13958 ((stringp org-use-tag-inheritance)
13959 (delq nil (mapcar
13960 (lambda (x)
13961 (if (and (string-match org-use-tag-inheritance x)
13962 (not (member x org-tags-exclude-from-inheritance)))
13963 x nil))
13964 tags)))
13965 ((listp org-use-tag-inheritance)
13966 (delq nil (mapcar
13967 (lambda (x)
13968 (if (member x org-use-tag-inheritance) x nil))
13969 tags)))))
13971 (defun org-match-sparse-tree (&optional todo-only match)
13972 "Create a sparse tree according to tags string MATCH.
13973 MATCH can contain positive and negative selection of tags, like
13974 \"+WORK+URGENT-WITHBOSS\".
13975 If optional argument TODO-ONLY is non-nil, only select lines that are
13976 also TODO lines."
13977 (interactive "P")
13978 (org-agenda-prepare-buffers (list (current-buffer)))
13979 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13981 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13983 (defvar org-cached-props nil)
13984 (defun org-cached-entry-get (pom property)
13985 (if (or (eq t org-use-property-inheritance)
13986 (and (stringp org-use-property-inheritance)
13987 (string-match org-use-property-inheritance property))
13988 (and (listp org-use-property-inheritance)
13989 (member property org-use-property-inheritance)))
13990 ;; Caching is not possible, check it directly
13991 (org-entry-get pom property 'inherit)
13992 ;; Get all properties, so that we can do complicated checks easily
13993 (cdr (assoc property (or org-cached-props
13994 (setq org-cached-props
13995 (org-entry-properties pom)))))))
13997 (defun org-global-tags-completion-table (&optional files)
13998 "Return the list of all tags in all agenda buffer/files.
13999 Optional FILES argument is a list of files which can be used
14000 instead of the agenda files."
14001 (save-excursion
14002 (org-uniquify
14003 (delq nil
14004 (apply 'append
14005 (mapcar
14006 (lambda (file)
14007 (set-buffer (find-file-noselect file))
14008 (append (org-get-buffer-tags)
14009 (mapcar (lambda (x) (if (stringp (car-safe x))
14010 (list (car-safe x)) nil))
14011 org-tag-alist)))
14012 (if (and files (car files))
14013 files
14014 (org-agenda-files))))))))
14016 (defun org-make-tags-matcher (match)
14017 "Create the TAGS/TODO matcher form for the selection string MATCH.
14019 The variable `todo-only' is scoped dynamically into this function.
14020 It will be set to t if the matcher restricts matching to TODO entries,
14021 otherwise will not be touched.
14023 Returns a cons of the selection string MATCH and the constructed
14024 lisp form implementing the matcher. The matcher is to be evaluated
14025 at an Org entry, with point on the headline, and returns t if the
14026 entry matches the selection string MATCH. The returned lisp form
14027 references two variables with information about the entry, which
14028 must be bound around the form's evaluation: todo, the TODO keyword
14029 at the entry (or nil of none); and tags-list, the list of all tags
14030 at the entry including inherited ones. Additionally, the category
14031 of the entry (if any) must be specified as the text property
14032 'org-category on the headline.
14034 See also `org-scan-tags'.
14036 (declare (special todo-only))
14037 (unless (boundp 'todo-only)
14038 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14039 (unless match
14040 ;; Get a new match request, with completion against the global
14041 ;; tags table and the local tags in current buffer
14042 (let ((org-last-tags-completion-table
14043 (org-uniquify
14044 (delq nil (append (org-get-buffer-tags)
14045 (org-global-tags-completion-table))))))
14046 (setq match (org-completing-read-no-i
14047 "Match: " 'org-tags-completion-function nil nil nil
14048 'org-tags-history))))
14050 ;; Parse the string and create a lisp form
14051 (let ((match0 match)
14052 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14053 minus tag mm
14054 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14055 orterms term orlist re-p str-p level-p level-op time-p
14056 prop-p pn pv po gv rest (start 0) (ss 0))
14057 ;; Expand group tags
14058 (setq match (org-tags-expand match))
14060 ;; Check if there is a TODO part of this match, which would be the
14061 ;; part after a "/". TO make sure that this slash is not part of
14062 ;; a property value to be matched against, we also check that there
14063 ;; is no " after that slash.
14064 ;; First, find the last slash
14065 (while (string-match "/+" match ss)
14066 (setq start (match-beginning 0) ss (match-end 0)))
14067 (if (and (string-match "/+" match start)
14068 (not (save-match-data (string-match "\"" match start))))
14069 ;; match contains also a todo-matching request
14070 (progn
14071 (setq tagsmatch (substring match 0 (match-beginning 0))
14072 todomatch (substring match (match-end 0)))
14073 (if (string-match "^!" todomatch)
14074 (setq todo-only t todomatch (substring todomatch 1)))
14075 (if (string-match "^\\s-*$" todomatch)
14076 (setq todomatch nil)))
14077 ;; only matching tags
14078 (setq tagsmatch match todomatch nil))
14080 ;; Make the tags matcher
14081 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14082 (setq tagsmatcher t)
14083 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14084 (while (setq term (pop orterms))
14085 (while (and (equal (substring term -1) "\\") orterms)
14086 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14087 (while (string-match re term)
14088 (setq rest (substring term (match-end 0))
14089 minus (and (match-end 1)
14090 (equal (match-string 1 term) "-"))
14091 tag (save-match-data (replace-regexp-in-string
14092 "\\\\-" "-"
14093 (match-string 2 term)))
14094 re-p (equal (string-to-char tag) ?{)
14095 level-p (match-end 4)
14096 prop-p (match-end 5)
14097 mm (cond
14098 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14099 (level-p
14100 (setq level-op (org-op-to-function (match-string 3 term)))
14101 `(,level-op level ,(string-to-number
14102 (match-string 4 term))))
14103 (prop-p
14104 (setq pn (match-string 5 term)
14105 po (match-string 6 term)
14106 pv (match-string 7 term)
14107 re-p (equal (string-to-char pv) ?{)
14108 str-p (equal (string-to-char pv) ?\")
14109 time-p (save-match-data
14110 (string-match "^\"[[<].*[]>]\"$" pv))
14111 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14112 (if time-p (setq pv (org-matcher-time pv)))
14113 (setq po (org-op-to-function po (if time-p 'time str-p)))
14114 (cond
14115 ((equal pn "CATEGORY")
14116 (setq gv '(get-text-property (point) 'org-category)))
14117 ((equal pn "TODO")
14118 (setq gv 'todo))
14120 (setq gv `(org-cached-entry-get nil ,pn))))
14121 (if re-p
14122 (if (eq po 'org<>)
14123 `(not (string-match ,pv (or ,gv "")))
14124 `(string-match ,pv (or ,gv "")))
14125 (if str-p
14126 `(,po (or ,gv "") ,pv)
14127 `(,po (string-to-number (or ,gv ""))
14128 ,(string-to-number pv) ))))
14129 (t `(member ,tag tags-list)))
14130 mm (if minus (list 'not mm) mm)
14131 term rest)
14132 (push mm tagsmatcher))
14133 (push (if (> (length tagsmatcher) 1)
14134 (cons 'and tagsmatcher)
14135 (car tagsmatcher))
14136 orlist)
14137 (setq tagsmatcher nil))
14138 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14139 (setq tagsmatcher
14140 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14141 ;; Make the todo matcher
14142 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14143 (setq todomatcher t)
14144 (setq orterms (org-split-string todomatch "|") orlist nil)
14145 (while (setq term (pop orterms))
14146 (while (string-match re term)
14147 (setq minus (and (match-end 1)
14148 (equal (match-string 1 term) "-"))
14149 kwd (match-string 2 term)
14150 re-p (equal (string-to-char kwd) ?{)
14151 term (substring term (match-end 0))
14152 mm (if re-p
14153 `(string-match ,(substring kwd 1 -1) todo)
14154 (list 'equal 'todo kwd))
14155 mm (if minus (list 'not mm) mm))
14156 (push mm todomatcher))
14157 (push (if (> (length todomatcher) 1)
14158 (cons 'and todomatcher)
14159 (car todomatcher))
14160 orlist)
14161 (setq todomatcher nil))
14162 (setq todomatcher (if (> (length orlist) 1)
14163 (cons 'or orlist) (car orlist))))
14165 ;; Return the string and lisp forms of the matcher
14166 (setq matcher (if todomatcher
14167 (list 'and tagsmatcher todomatcher)
14168 tagsmatcher))
14169 (when todo-only
14170 (setq matcher (list 'and '(member todo org-not-done-keywords)
14171 matcher)))
14172 (cons match0 matcher)))
14174 (defun org-tags-expand (match &optional single-as-list downcased)
14175 "Expand group tags in MATCH.
14177 This replaces every group tag in MATCH with a regexp tag search.
14178 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14179 will be replaced like this:
14181 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14182 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14183 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14185 Replacing by a regexp preserves the structure of the match.
14186 E.g., this expansion
14188 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14190 will match anything tagged with \"Lab\" and \"Home\", or tagged
14191 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14193 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14194 assumed to be a single group tag, and the function will return
14195 the list of tags in this group.
14197 When DOWNCASE is non-nil, expand downcased TAGS."
14198 (if org-group-tags
14199 (let* ((case-fold-search t)
14200 (stable org-mode-syntax-table)
14201 (tal (or org-tag-groups-alist-for-agenda
14202 org-tag-groups-alist))
14203 (tal (if downcased
14204 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14205 (tml (mapcar 'car tal))
14206 (rtnmatch match) rpl)
14207 ;; @ and _ are allowed as word-components in tags
14208 (modify-syntax-entry ?@ "w" stable)
14209 (modify-syntax-entry ?_ "w" stable)
14210 (while (and tml
14211 (with-syntax-table stable
14212 (string-match
14213 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14214 (regexp-opt tml) "\\>\\)") rtnmatch)))
14215 (let* ((dir (match-string 1 rtnmatch))
14216 (tag (match-string 2 rtnmatch))
14217 (tag (if downcased (downcase tag) tag)))
14218 (setq tml (delete tag tml))
14219 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14220 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14221 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14222 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14223 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14224 (if single-as-list
14225 (or (reverse rpl) (list rtnmatch))
14226 rtnmatch))
14227 (if single-as-list (list (if downcased (downcase match) match))
14228 match)))
14230 (defun org-op-to-function (op &optional stringp)
14231 "Turn an operator into the appropriate function."
14232 (setq op
14233 (cond
14234 ((equal op "<" ) '(< string< org-time<))
14235 ((equal op ">" ) '(> org-string> org-time>))
14236 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14237 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14238 ((member op '("=" "==")) '(= string= org-time=))
14239 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14240 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14242 (defun org<> (a b) (not (= a b)))
14243 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14244 (defun org-string>= (a b) (not (string< a b)))
14245 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14246 (defun org-string<> (a b) (not (string= a b)))
14247 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14248 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14249 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14250 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14251 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14252 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14253 (defun org-2ft (s)
14254 "Convert S to a floating point time.
14255 If S is already a number, just return it. If it is a string, parse
14256 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14257 (cond
14258 ((numberp s) s)
14259 ((stringp s)
14260 (condition-case nil
14261 (float-time (apply 'encode-time (org-parse-time-string s)))
14262 (error 0.)))
14263 (t 0.)))
14265 (defun org-time-today ()
14266 "Time in seconds today at 0:00.
14267 Returns the float number of seconds since the beginning of the
14268 epoch to the beginning of today (00:00)."
14269 (float-time (apply 'encode-time
14270 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14272 (defun org-matcher-time (s)
14273 "Interpret a time comparison value."
14274 (save-match-data
14275 (cond
14276 ((string= s "<now>") (float-time))
14277 ((string= s "<today>") (org-time-today))
14278 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14279 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14280 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14281 (+ (org-time-today)
14282 (* (string-to-number (match-string 1 s))
14283 (cdr (assoc (match-string 2 s)
14284 '(("d" . 86400.0) ("w" . 604800.0)
14285 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14286 (t (org-2ft s)))))
14288 (defun org-match-any-p (re list)
14289 "Does re match any element of list?"
14290 (setq list (mapcar (lambda (x) (string-match re x)) list))
14291 (delq nil list))
14293 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14294 (defvar org-tags-overlay (make-overlay 1 1))
14295 (org-detach-overlay org-tags-overlay)
14297 (defun org-get-local-tags-at (&optional pos)
14298 "Get a list of tags defined in the current headline."
14299 (org-get-tags-at pos 'local))
14301 (defun org-get-local-tags ()
14302 "Get a list of tags defined in the current headline."
14303 (org-get-tags-at nil 'local))
14305 (defun org-get-tags-at (&optional pos local)
14306 "Get a list of all headline tags applicable at POS.
14307 POS defaults to point. If tags are inherited, the list contains
14308 the targets in the same sequence as the headlines appear, i.e.
14309 the tags of the current headline come last.
14310 When LOCAL is non-nil, only return tags from the current headline,
14311 ignore inherited ones."
14312 (interactive)
14313 (if (and org-trust-scanner-tags
14314 (or (not pos) (equal pos (point)))
14315 (not local))
14316 org-scanner-tags
14317 (let (tags ltags lastpos parent)
14318 (save-excursion
14319 (save-restriction
14320 (widen)
14321 (goto-char (or pos (point)))
14322 (save-match-data
14323 (catch 'done
14324 (condition-case nil
14325 (progn
14326 (org-back-to-heading t)
14327 (while (not (equal lastpos (point)))
14328 (setq lastpos (point))
14329 (when (looking-at
14330 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14331 (setq ltags (org-split-string
14332 (org-match-string-no-properties 1) ":"))
14333 (when parent
14334 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14335 (setq tags (append
14336 (if parent
14337 (org-remove-uninherited-tags ltags)
14338 ltags)
14339 tags)))
14340 (or org-use-tag-inheritance (throw 'done t))
14341 (if local (throw 'done t))
14342 (or (org-up-heading-safe) (error nil))
14343 (setq parent t)))
14344 (error nil)))))
14345 (if local
14346 tags
14347 (reverse (delete-dups
14348 (reverse (append
14349 (org-remove-uninherited-tags
14350 org-file-tags) tags)))))))))
14352 (defun org-add-prop-inherited (s)
14353 (add-text-properties 0 (length s) '(inherited t) s)
14356 (defun org-toggle-tag (tag &optional onoff)
14357 "Toggle the tag TAG for the current line.
14358 If ONOFF is `on' or `off', don't toggle but set to this state."
14359 (let (res current)
14360 (save-excursion
14361 (org-back-to-heading t)
14362 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14363 (point-at-eol) t)
14364 (progn
14365 (setq current (match-string 1))
14366 (replace-match ""))
14367 (setq current ""))
14368 (setq current (nreverse (org-split-string current ":")))
14369 (cond
14370 ((eq onoff 'on)
14371 (setq res t)
14372 (or (member tag current) (push tag current)))
14373 ((eq onoff 'off)
14374 (or (not (member tag current)) (setq current (delete tag current))))
14375 (t (if (member tag current)
14376 (setq current (delete tag current))
14377 (setq res t)
14378 (push tag current))))
14379 (end-of-line 1)
14380 (if current
14381 (progn
14382 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14383 (org-set-tags nil t))
14384 (delete-horizontal-space))
14385 (run-hooks 'org-after-tags-change-hook))
14386 res))
14388 (defun org-align-tags-here (to-col)
14389 ;; Assumes that this is a headline
14390 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14391 (beginning-of-line 1)
14392 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14393 (< pos (match-beginning 2)))
14394 (progn
14395 (setq tags-l (- (match-end 2) (match-beginning 2)))
14396 (goto-char (match-beginning 1))
14397 (insert " ")
14398 (delete-region (point) (1+ (match-beginning 2)))
14399 (setq ncol (max (current-column)
14400 (1+ col)
14401 (if (> to-col 0)
14402 to-col
14403 (- (abs to-col) tags-l))))
14404 (setq p (point))
14405 (insert (make-string (- ncol (current-column)) ?\ ))
14406 (setq ncol (current-column))
14407 (when indent-tabs-mode (tabify p (point-at-eol)))
14408 (org-move-to-column (min ncol col) t))
14409 (goto-char pos))))
14411 (defun org-set-tags-command (&optional arg just-align)
14412 "Call the set-tags command for the current entry."
14413 (interactive "P")
14414 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14415 (org-set-tags arg just-align)
14416 (save-excursion
14417 (unless (and (org-region-active-p)
14418 org-loop-over-headlines-in-active-region)
14419 (org-back-to-heading t))
14420 (org-set-tags arg just-align))))
14422 (defun org-set-tags-to (data)
14423 "Set the tags of the current entry to DATA, replacing the current tags.
14424 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14425 If DATA is nil or the empty string, any tags will be removed."
14426 (interactive "sTags: ")
14427 (setq data
14428 (cond
14429 ((eq data nil) "")
14430 ((equal data "") "")
14431 ((stringp data)
14432 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14433 ":"))
14434 ((listp data)
14435 (concat ":" (mapconcat 'identity data ":") ":"))))
14436 (when data
14437 (save-excursion
14438 (org-back-to-heading t)
14439 (when (looking-at org-complex-heading-regexp)
14440 (if (match-end 5)
14441 (progn
14442 (goto-char (match-beginning 5))
14443 (insert data)
14444 (delete-region (point) (point-at-eol))
14445 (org-set-tags nil 'align))
14446 (goto-char (point-at-eol))
14447 (insert " " data)
14448 (org-set-tags nil 'align)))
14449 (beginning-of-line 1)
14450 (if (looking-at ".*?\\([ \t]+\\)$")
14451 (delete-region (match-beginning 1) (match-end 1))))))
14453 (defun org-align-all-tags ()
14454 "Align the tags i all headings."
14455 (interactive)
14456 (save-excursion
14457 (or (ignore-errors (org-back-to-heading t))
14458 (outline-next-heading))
14459 (if (org-at-heading-p)
14460 (org-set-tags t)
14461 (message "No headings"))))
14463 (defvar org-indent-indentation-per-level)
14464 (defun org-set-tags (&optional arg just-align)
14465 "Set the tags for the current headline.
14466 With prefix ARG, realign all tags in headings in the current buffer."
14467 (interactive "P")
14468 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14469 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14470 'region-start-level 'region))
14471 org-loop-over-headlines-in-active-region)
14472 (org-map-entries
14473 ;; We don't use ARG and JUST-ALIGN here these args are not
14474 ;; useful when looping over headlines
14475 `(org-set-tags)
14476 org-loop-over-headlines-in-active-region
14477 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14478 (let* ((re org-outline-regexp-bol)
14479 (current (unless arg (org-get-tags-string)))
14480 (col (current-column))
14481 (org-setting-tags t)
14482 table current-tags inherited-tags ; computed below when needed
14483 tags p0 c0 c1 rpl di tc level)
14484 (if arg
14485 (save-excursion
14486 (goto-char (point-min))
14487 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14488 (while (re-search-forward re nil t)
14489 (org-set-tags nil t)
14490 (end-of-line 1)))
14491 (message "All tags realigned to column %d" org-tags-column))
14492 (if just-align
14493 (setq tags current)
14494 ;; Get a new set of tags from the user
14495 (save-excursion
14496 (setq table (append org-tag-persistent-alist
14497 (or org-tag-alist (org-get-buffer-tags))
14498 (and
14499 org-complete-tags-always-offer-all-agenda-tags
14500 (org-global-tags-completion-table
14501 (org-agenda-files))))
14502 org-last-tags-completion-table table
14503 current-tags (org-split-string current ":")
14504 inherited-tags (nreverse
14505 (nthcdr (length current-tags)
14506 (nreverse (org-get-tags-at))))
14507 tags
14508 (if (or (eq t org-use-fast-tag-selection)
14509 (and org-use-fast-tag-selection
14510 (delq nil (mapcar 'cdr table))))
14511 (org-fast-tag-selection
14512 current-tags inherited-tags table
14513 (if org-fast-tag-selection-include-todo
14514 org-todo-key-alist))
14515 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14516 (org-trim
14517 (org-icompleting-read "Tags: "
14518 'org-tags-completion-function
14519 nil nil current 'org-tags-history))))))
14520 (while (string-match "[-+&]+" tags)
14521 ;; No boolean logic, just a list
14522 (setq tags (replace-match ":" t t tags))))
14524 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14526 (if org-tags-sort-function
14527 (setq tags (mapconcat 'identity
14528 (sort (org-split-string
14529 tags (org-re "[^[:alnum:]_@#%]+"))
14530 org-tags-sort-function) ":")))
14532 (if (string-match "\\`[\t ]*\\'" tags)
14533 (setq tags "")
14534 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14535 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14537 ;; Insert new tags at the correct column
14538 (beginning-of-line 1)
14539 (setq level (or (and (looking-at org-outline-regexp)
14540 (- (match-end 0) (point) 1))
14542 (cond
14543 ((and (equal current "") (equal tags "")))
14544 ((re-search-forward
14545 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14546 (point-at-eol) t)
14547 (if (equal tags "")
14548 (setq rpl "")
14549 (goto-char (match-beginning 0))
14550 (setq c0 (current-column)
14551 ;; compute offset for the case of org-indent-mode active
14552 di (if org-indent-mode
14553 (* (1- org-indent-indentation-per-level) (1- level))
14555 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14556 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14557 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14558 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14559 (replace-match rpl t t)
14560 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14561 tags)
14562 (t (error "Tags alignment failed")))
14563 (org-move-to-column col)
14564 (unless just-align
14565 (run-hooks 'org-after-tags-change-hook))))))
14567 (defun org-change-tag-in-region (beg end tag off)
14568 "Add or remove TAG for each entry in the region.
14569 This works in the agenda, and also in an org-mode buffer."
14570 (interactive
14571 (list (region-beginning) (region-end)
14572 (let ((org-last-tags-completion-table
14573 (if (derived-mode-p 'org-mode)
14574 (org-uniquify
14575 (delq nil (append (org-get-buffer-tags)
14576 (org-global-tags-completion-table))))
14577 (org-global-tags-completion-table))))
14578 (org-icompleting-read
14579 "Tag: " 'org-tags-completion-function nil nil nil
14580 'org-tags-history))
14581 (progn
14582 (message "[s]et or [r]emove? ")
14583 (equal (read-char-exclusive) ?r))))
14584 (if (fboundp 'deactivate-mark) (deactivate-mark))
14585 (let ((agendap (equal major-mode 'org-agenda-mode))
14586 l1 l2 m buf pos newhead (cnt 0))
14587 (goto-char end)
14588 (setq l2 (1- (org-current-line)))
14589 (goto-char beg)
14590 (setq l1 (org-current-line))
14591 (loop for l from l1 to l2 do
14592 (org-goto-line l)
14593 (setq m (get-text-property (point) 'org-hd-marker))
14594 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14595 (and agendap m))
14596 (setq buf (if agendap (marker-buffer m) (current-buffer))
14597 pos (if agendap m (point)))
14598 (with-current-buffer buf
14599 (save-excursion
14600 (save-restriction
14601 (goto-char pos)
14602 (setq cnt (1+ cnt))
14603 (org-toggle-tag tag (if off 'off 'on))
14604 (setq newhead (org-get-heading)))))
14605 (and agendap (org-agenda-change-all-lines newhead m))))
14606 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14608 (defun org-tags-completion-function (string predicate &optional flag)
14609 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14610 (confirm (lambda (x) (stringp (car x)))))
14611 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14612 (setq s1 (match-string 1 string)
14613 s2 (match-string 2 string))
14614 (setq s1 "" s2 string))
14615 (cond
14616 ((eq flag nil)
14617 ;; try completion
14618 (setq rtn (try-completion s2 ctable confirm))
14619 (if (stringp rtn)
14620 (setq rtn
14621 (concat s1 s2 (substring rtn (length s2))
14622 (if (and org-add-colon-after-tag-completion
14623 (assoc rtn ctable))
14624 ":" ""))))
14625 rtn)
14626 ((eq flag t)
14627 ;; all-completions
14628 (all-completions s2 ctable confirm))
14629 ((eq flag 'lambda)
14630 ;; exact match?
14631 (assoc s2 ctable)))))
14633 (defun org-fast-tag-insert (kwd tags face &optional end)
14634 "Insert KDW, and the TAGS, the latter with face FACE.
14635 Also insert END."
14636 (insert (format "%-12s" (concat kwd ":"))
14637 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14638 (or end "")))
14640 (defun org-fast-tag-show-exit (flag)
14641 (save-excursion
14642 (org-goto-line 3)
14643 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14644 (replace-match ""))
14645 (when flag
14646 (end-of-line 1)
14647 (org-move-to-column (- (window-width) 19) t)
14648 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14650 (defun org-set-current-tags-overlay (current prefix)
14651 "Add an overlay to CURRENT tag with PREFIX."
14652 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14653 (if (featurep 'xemacs)
14654 (org-overlay-display org-tags-overlay (concat prefix s)
14655 'secondary-selection)
14656 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14657 (org-overlay-display org-tags-overlay (concat prefix s)))))
14659 (defvar org-last-tag-selection-key nil)
14660 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14661 "Fast tag selection with single keys.
14662 CURRENT is the current list of tags in the headline, INHERITED is the
14663 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14664 possibly with grouping information. TODO-TABLE is a similar table with
14665 TODO keywords, should these have keys assigned to them.
14666 If the keys are nil, a-z are automatically assigned.
14667 Returns the new tags string, or nil to not change the current settings."
14668 (let* ((fulltable (append table todo-table))
14669 (maxlen (apply 'max (mapcar
14670 (lambda (x)
14671 (if (stringp (car x)) (string-width (car x)) 0))
14672 fulltable)))
14673 (buf (current-buffer))
14674 (expert (eq org-fast-tag-selection-single-key 'expert))
14675 (buffer-tags nil)
14676 (fwidth (+ maxlen 3 1 3))
14677 (ncol (/ (- (window-width) 4) fwidth))
14678 (i-face 'org-done)
14679 (c-face 'org-todo)
14680 tg cnt e c char c1 c2 ntable tbl rtn
14681 ov-start ov-end ov-prefix
14682 (exit-after-next org-fast-tag-selection-single-key)
14683 (done-keywords org-done-keywords)
14684 groups ingroup)
14685 (save-excursion
14686 (beginning-of-line 1)
14687 (if (looking-at
14688 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14689 (setq ov-start (match-beginning 1)
14690 ov-end (match-end 1)
14691 ov-prefix "")
14692 (setq ov-start (1- (point-at-eol))
14693 ov-end (1+ ov-start))
14694 (skip-chars-forward "^\n\r")
14695 (setq ov-prefix
14696 (concat
14697 (buffer-substring (1- (point)) (point))
14698 (if (> (current-column) org-tags-column)
14700 (make-string (- org-tags-column (current-column)) ?\ ))))))
14701 (move-overlay org-tags-overlay ov-start ov-end)
14702 (save-window-excursion
14703 (if expert
14704 (set-buffer (get-buffer-create " *Org tags*"))
14705 (delete-other-windows)
14706 (split-window-vertically)
14707 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14708 (erase-buffer)
14709 (org-set-local 'org-done-keywords done-keywords)
14710 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14711 (org-fast-tag-insert "Current" current c-face "\n\n")
14712 (org-fast-tag-show-exit exit-after-next)
14713 (org-set-current-tags-overlay current ov-prefix)
14714 (setq tbl fulltable char ?a cnt 0)
14715 (while (setq e (pop tbl))
14716 (cond
14717 ((equal (car e) :startgroup)
14718 (push '() groups) (setq ingroup t)
14719 (when (not (= cnt 0))
14720 (setq cnt 0)
14721 (insert "\n"))
14722 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14723 ((equal (car e) :endgroup)
14724 (setq ingroup nil cnt 0)
14725 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14726 ((equal e '(:newline))
14727 (when (not (= cnt 0))
14728 (setq cnt 0)
14729 (insert "\n")
14730 (setq e (car tbl))
14731 (while (equal (car tbl) '(:newline))
14732 (insert "\n")
14733 (setq tbl (cdr tbl)))))
14734 ((equal e '(:grouptags)) nil)
14736 (setq tg (copy-sequence (car e)) c2 nil)
14737 (if (cdr e)
14738 (setq c (cdr e))
14739 ;; automatically assign a character.
14740 (setq c1 (string-to-char
14741 (downcase (substring
14742 tg (if (= (string-to-char tg) ?@) 1 0)))))
14743 (if (or (rassoc c1 ntable) (rassoc c1 table))
14744 (while (or (rassoc char ntable) (rassoc char table))
14745 (setq char (1+ char)))
14746 (setq c2 c1))
14747 (setq c (or c2 char)))
14748 (if ingroup (push tg (car groups)))
14749 (setq tg (org-add-props tg nil 'face
14750 (cond
14751 ((not (assoc tg table))
14752 (org-get-todo-face tg))
14753 ((member tg current) c-face)
14754 ((member tg inherited) i-face))))
14755 (if (equal (caar tbl) :grouptags)
14756 (org-add-props tg nil 'face 'org-tag-group))
14757 (if (and (= cnt 0) (not ingroup)) (insert " "))
14758 (insert "[" c "] " tg (make-string
14759 (- fwidth 4 (length tg)) ?\ ))
14760 (push (cons tg c) ntable)
14761 (when (= (setq cnt (1+ cnt)) ncol)
14762 (insert "\n")
14763 (if ingroup (insert " "))
14764 (setq cnt 0)))))
14765 (setq ntable (nreverse ntable))
14766 (insert "\n")
14767 (goto-char (point-min))
14768 (if (not expert) (org-fit-window-to-buffer))
14769 (setq rtn
14770 (catch 'exit
14771 (while t
14772 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14773 (if (not groups) "no " "")
14774 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14775 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14776 (setq org-last-tag-selection-key c)
14777 (cond
14778 ((= c ?\r) (throw 'exit t))
14779 ((= c ?!)
14780 (setq groups (not groups))
14781 (goto-char (point-min))
14782 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14783 ((= c ?\C-c)
14784 (if (not expert)
14785 (org-fast-tag-show-exit
14786 (setq exit-after-next (not exit-after-next)))
14787 (setq expert nil)
14788 (delete-other-windows)
14789 (set-window-buffer (split-window-vertically) " *Org tags*")
14790 (org-switch-to-buffer-other-window " *Org tags*")
14791 (org-fit-window-to-buffer)))
14792 ((or (= c ?\C-g)
14793 (and (= c ?q) (not (rassoc c ntable))))
14794 (org-detach-overlay org-tags-overlay)
14795 (setq quit-flag t))
14796 ((= c ?\ )
14797 (setq current nil)
14798 (if exit-after-next (setq exit-after-next 'now)))
14799 ((= c ?\t)
14800 (condition-case nil
14801 (setq tg (org-icompleting-read
14802 "Tag: "
14803 (or buffer-tags
14804 (with-current-buffer buf
14805 (org-get-buffer-tags)))))
14806 (quit (setq tg "")))
14807 (when (string-match "\\S-" tg)
14808 (add-to-list 'buffer-tags (list tg))
14809 (if (member tg current)
14810 (setq current (delete tg current))
14811 (push tg current)))
14812 (if exit-after-next (setq exit-after-next 'now)))
14813 ((setq e (rassoc c todo-table) tg (car e))
14814 (with-current-buffer buf
14815 (save-excursion (org-todo tg)))
14816 (if exit-after-next (setq exit-after-next 'now)))
14817 ((setq e (rassoc c ntable) tg (car e))
14818 (if (member tg current)
14819 (setq current (delete tg current))
14820 (loop for g in groups do
14821 (if (member tg g)
14822 (mapc (lambda (x)
14823 (setq current (delete x current)))
14824 g)))
14825 (push tg current))
14826 (if exit-after-next (setq exit-after-next 'now))))
14828 ;; Create a sorted list
14829 (setq current
14830 (sort current
14831 (lambda (a b)
14832 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14833 (if (eq exit-after-next 'now) (throw 'exit t))
14834 (goto-char (point-min))
14835 (beginning-of-line 2)
14836 (delete-region (point) (point-at-eol))
14837 (org-fast-tag-insert "Current" current c-face)
14838 (org-set-current-tags-overlay current ov-prefix)
14839 (while (re-search-forward
14840 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14841 (setq tg (match-string 1))
14842 (add-text-properties
14843 (match-beginning 1) (match-end 1)
14844 (list 'face
14845 (cond
14846 ((member tg current) c-face)
14847 ((member tg inherited) i-face)
14848 (t (get-text-property (match-beginning 1) 'face))))))
14849 (goto-char (point-min)))))
14850 (org-detach-overlay org-tags-overlay)
14851 (if rtn
14852 (mapconcat 'identity current ":")
14853 nil))))
14855 (defun org-get-tags-string ()
14856 "Get the TAGS string in the current headline."
14857 (unless (org-at-heading-p t)
14858 (user-error "Not on a heading"))
14859 (save-excursion
14860 (beginning-of-line 1)
14861 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14862 (org-match-string-no-properties 1)
14863 "")))
14865 (defun org-get-tags ()
14866 "Get the list of tags specified in the current headline."
14867 (org-split-string (org-get-tags-string) ":"))
14869 (defun org-get-buffer-tags ()
14870 "Get a table of all tags used in the buffer, for completion."
14871 (let (tags)
14872 (save-excursion
14873 (goto-char (point-min))
14874 (while (re-search-forward
14875 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14876 (when (equal (char-after (point-at-bol 0)) ?*)
14877 (mapc (lambda (x) (add-to-list 'tags x))
14878 (org-split-string (org-match-string-no-properties 1) ":")))))
14879 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14880 (mapcar 'list tags)))
14882 ;;;; The mapping API
14884 (defun org-map-entries (func &optional match scope &rest skip)
14885 "Call FUNC at each headline selected by MATCH in SCOPE.
14887 FUNC is a function or a lisp form. The function will be called without
14888 arguments, with the cursor positioned at the beginning of the headline.
14889 The return values of all calls to the function will be collected and
14890 returned as a list.
14892 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14893 does not need to preserve point. After evaluation, the cursor will be
14894 moved to the end of the line (presumably of the headline of the
14895 processed entry) and search continues from there. Under some
14896 circumstances, this may not produce the wanted results. For example,
14897 if you have removed (e.g. archived) the current (sub)tree it could
14898 mean that the next entry will be skipped entirely. In such cases, you
14899 can specify the position from where search should continue by making
14900 FUNC set the variable `org-map-continue-from' to the desired buffer
14901 position.
14903 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14904 Only headlines that are matched by this query will be considered during
14905 the iteration. When MATCH is nil or t, all headlines will be
14906 visited by the iteration.
14908 SCOPE determines the scope of this command. It can be any of:
14910 nil The current buffer, respecting the restriction if any
14911 tree The subtree started with the entry at point
14912 region The entries within the active region, if any
14913 region-start-level
14914 The entries within the active region, but only those at
14915 the same level than the first one.
14916 file The current buffer, without restriction
14917 file-with-archives
14918 The current buffer, and any archives associated with it
14919 agenda All agenda files
14920 agenda-with-archives
14921 All agenda files with any archive files associated with them
14922 \(file1 file2 ...)
14923 If this is a list, all files in the list will be scanned
14925 The remaining args are treated as settings for the skipping facilities of
14926 the scanner. The following items can be given here:
14928 archive skip trees with the archive tag
14929 comment skip trees with the COMMENT keyword
14930 function or Emacs Lisp form:
14931 will be used as value for `org-agenda-skip-function', so
14932 whenever the function returns a position, FUNC will not be
14933 called for that entry and search will continue from the
14934 position returned
14936 If your function needs to retrieve the tags including inherited tags
14937 at the *current* entry, you can use the value of the variable
14938 `org-scanner-tags' which will be much faster than getting the value
14939 with `org-get-tags-at'. If your function gets properties with
14940 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14941 to t around the call to `org-entry-properties' to get the same speedup.
14942 Note that if your function moves around to retrieve tags and properties at
14943 a *different* entry, you cannot use these techniques."
14944 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14945 (not (org-region-active-p)))
14946 (let* ((org-agenda-archives-mode nil) ; just to make sure
14947 (org-agenda-skip-archived-trees (memq 'archive skip))
14948 (org-agenda-skip-comment-trees (memq 'comment skip))
14949 (org-agenda-skip-function
14950 (car (org-delete-all '(comment archive) skip)))
14951 (org-tags-match-list-sublevels t)
14952 (start-level (eq scope 'region-start-level))
14953 matcher file res
14954 org-todo-keywords-for-agenda
14955 org-done-keywords-for-agenda
14956 org-todo-keyword-alist-for-agenda
14957 org-drawers-for-agenda
14958 org-tag-alist-for-agenda
14959 todo-only)
14961 (cond
14962 ((eq match t) (setq matcher t))
14963 ((eq match nil) (setq matcher t))
14964 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14966 (save-window-excursion
14967 (save-restriction
14968 (cond ((eq scope 'tree)
14969 (org-back-to-heading t)
14970 (org-narrow-to-subtree)
14971 (setq scope nil))
14972 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14973 (org-region-active-p))
14974 ;; If needed, set start-level to a string like "2"
14975 (when start-level
14976 (save-excursion
14977 (goto-char (region-beginning))
14978 (unless (org-at-heading-p) (outline-next-heading))
14979 (setq start-level (org-current-level))))
14980 (narrow-to-region (region-beginning)
14981 (save-excursion
14982 (goto-char (region-end))
14983 (unless (and (bolp) (org-at-heading-p))
14984 (outline-next-heading))
14985 (point)))
14986 (setq scope nil)))
14988 (if (not scope)
14989 (progn
14990 (org-agenda-prepare-buffers
14991 (list (buffer-file-name (current-buffer))))
14992 (setq res (org-scan-tags func matcher todo-only start-level)))
14993 ;; Get the right scope
14994 (cond
14995 ((and scope (listp scope) (symbolp (car scope)))
14996 (setq scope (eval scope)))
14997 ((eq scope 'agenda)
14998 (setq scope (org-agenda-files t)))
14999 ((eq scope 'agenda-with-archives)
15000 (setq scope (org-agenda-files t))
15001 (setq scope (org-add-archive-files scope)))
15002 ((eq scope 'file)
15003 (setq scope (list (buffer-file-name))))
15004 ((eq scope 'file-with-archives)
15005 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15006 (org-agenda-prepare-buffers scope)
15007 (while (setq file (pop scope))
15008 (with-current-buffer (org-find-base-buffer-visiting file)
15009 (save-excursion
15010 (save-restriction
15011 (widen)
15012 (goto-char (point-min))
15013 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15014 res)))
15016 ;;;; Properties
15018 ;;; Setting and retrieving properties
15020 (defconst org-special-properties
15021 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15022 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15023 "The special properties valid in Org-mode.
15025 These are properties that are not defined in the property drawer,
15026 but in some other way.")
15028 (defconst org-default-properties
15029 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15030 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15031 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15032 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15033 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15034 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15035 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15036 "Some properties that are used by Org-mode for various purposes.
15037 Being in this list makes sure that they are offered for completion.")
15039 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15040 "Regular expression matching the first line of a property drawer.")
15042 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15043 "Regular expression matching the last line of a property drawer.")
15045 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15046 "Regular expression matching the first line of a property drawer.")
15048 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15049 "Regular expression matching the first line of a property drawer.")
15051 (defconst org-property-drawer-re
15052 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15053 org-property-end-re "\\)\n?")
15054 "Matches an entire property drawer.")
15056 (defconst org-clock-drawer-re
15057 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15058 org-property-end-re "\\)\n?")
15059 "Matches an entire clock drawer.")
15061 (defun org-property-action ()
15062 "Do an action on properties."
15063 (interactive)
15064 (let (c)
15065 (org-at-property-p)
15066 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15067 (setq c (read-char-exclusive))
15068 (cond
15069 ((equal c ?s)
15070 (call-interactively 'org-set-property))
15071 ((equal c ?d)
15072 (call-interactively 'org-delete-property))
15073 ((equal c ?D)
15074 (call-interactively 'org-delete-property-globally))
15075 ((equal c ?c)
15076 (call-interactively 'org-compute-property-at-point))
15077 (t (user-error "No such property action %c" c)))))
15079 (defun org-inc-effort ()
15080 "Increment the value of the effort property in the current entry."
15081 (interactive)
15082 (org-set-effort nil t))
15084 (defvar org-clock-effort) ;; Defined in org-clock.el
15085 (defvar org-clock-current-task) ;; Defined in org-clock.el
15086 (defun org-set-effort (&optional value increment)
15087 "Set the effort property of the current entry.
15088 With numerical prefix arg, use the nth allowed value, 0 stands for the
15089 10th allowed value.
15091 When INCREMENT is non-nil, set the property to the next allowed value."
15092 (interactive "P")
15093 (if (equal value 0) (setq value 10))
15094 (let* ((completion-ignore-case t)
15095 (prop org-effort-property)
15096 (cur (org-entry-get nil prop))
15097 (allowed (org-property-get-allowed-values nil prop 'table))
15098 (existing (mapcar 'list (org-property-values prop)))
15099 (heading (nth 4 (org-heading-components)))
15101 (val (cond
15102 ((stringp value) value)
15103 ((and allowed (integerp value))
15104 (or (car (nth (1- value) allowed))
15105 (car (org-last allowed))))
15106 ((and allowed increment)
15107 (or (caadr (member (list cur) allowed))
15108 (user-error "Allowed effort values are not set")))
15109 (allowed
15110 (message "Select 1-9,0, [RET%s]: %s"
15111 (if cur (concat "=" cur) "")
15112 (mapconcat 'car allowed " "))
15113 (setq rpl (read-char-exclusive))
15114 (if (equal rpl ?\r)
15116 (setq rpl (- rpl ?0))
15117 (if (equal rpl 0) (setq rpl 10))
15118 (if (and (> rpl 0) (<= rpl (length allowed)))
15119 (car (nth (1- rpl) allowed))
15120 (org-completing-read "Effort: " allowed nil))))
15122 (let (org-completion-use-ido org-completion-use-iswitchb)
15123 (org-completing-read
15124 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15125 (concat "[" cur "]") "")
15126 ": ")
15127 existing nil nil "" nil cur))))))
15128 (unless (equal (org-entry-get nil prop) val)
15129 (org-entry-put nil prop val))
15130 (save-excursion
15131 (org-back-to-heading t)
15132 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15133 (when (string= heading org-clock-current-task)
15134 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15135 (org-clock-update-mode-line))
15136 (message "%s is now %s" prop val)))
15138 (defun org-at-property-p ()
15139 "Is cursor inside a property drawer?"
15140 (save-excursion
15141 (when (equal 'node-property (car (org-element-at-point)))
15142 (beginning-of-line 1)
15143 (looking-at org-property-re))))
15145 (defun org-get-property-block (&optional beg end force)
15146 "Return the (beg . end) range of the body of the property drawer.
15147 BEG and END are the beginning and end of the current subtree, or of
15148 the part before the first headline. If they are not given, they will
15149 be found. If the drawer does not exist and FORCE is non-nil, create
15150 the drawer."
15151 (catch 'exit
15152 (save-excursion
15153 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15154 (progn (org-back-to-heading t) (point))))
15155 (end (or end (and (not (outline-next-heading)) (point-max))
15156 (point))))
15157 (goto-char beg)
15158 (if (re-search-forward org-property-start-re end t)
15159 (setq beg (1+ (match-end 0)))
15160 (if force
15161 (save-excursion
15162 (org-insert-property-drawer)
15163 (setq end (progn (outline-next-heading) (point))))
15164 (throw 'exit nil))
15165 (goto-char beg)
15166 (if (re-search-forward org-property-start-re end t)
15167 (setq beg (1+ (match-end 0)))))
15168 (if (re-search-forward org-property-end-re end t)
15169 (setq end (match-beginning 0))
15170 (or force (throw 'exit nil))
15171 (goto-char beg)
15172 (setq end beg)
15173 (org-indent-line)
15174 (insert ":END:\n"))
15175 (cons beg end)))))
15177 (defun org-entry-properties (&optional pom which specific)
15178 "Get all properties of the entry at point-or-marker POM.
15179 This includes the TODO keyword, the tags, time strings for deadline,
15180 scheduled, and clocking, and any additional properties defined in the
15181 entry. The return value is an alist, keys may occur multiple times
15182 if the property key was used several times.
15183 POM may also be nil, in which case the current entry is used.
15184 If WHICH is nil or `all', get all properties. If WHICH is
15185 `special' or `standard', only get that subclass. If WHICH
15186 is a string only get exactly this property. SPECIFIC can be a string, the
15187 specific property we are interested in. Specifying it can speed
15188 things up because then unnecessary parsing is avoided."
15189 (setq which (or which 'all))
15190 (org-with-point-at pom
15191 (let ((clockstr (substring org-clock-string 0 -1))
15192 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15193 (case-fold-search nil)
15194 beg end range props sum-props key key1 value string clocksum clocksumt)
15195 (save-excursion
15196 (when (condition-case nil
15197 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15198 (error nil))
15199 (setq beg (point))
15200 (setq sum-props (get-text-property (point) 'org-summaries))
15201 (setq clocksum (get-text-property (point) :org-clock-minutes)
15202 clocksumt (get-text-property (point) :org-clock-minutes-today))
15203 (outline-next-heading)
15204 (setq end (point))
15205 (when (memq which '(all special))
15206 ;; Get the special properties, like TODO and tags
15207 (goto-char beg)
15208 (when (and (or (not specific) (string= specific "TODO"))
15209 (looking-at org-todo-line-regexp) (match-end 2))
15210 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15211 (when (and (or (not specific) (string= specific "PRIORITY"))
15212 (looking-at org-priority-regexp))
15213 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15214 (when (or (not specific) (string= specific "FILE"))
15215 (push (cons "FILE" buffer-file-name) props))
15216 (when (and (or (not specific) (string= specific "TAGS"))
15217 (setq value (org-get-tags-string))
15218 (string-match "\\S-" value))
15219 (push (cons "TAGS" value) props))
15220 (when (and (or (not specific) (string= specific "ALLTAGS"))
15221 (setq value (org-get-tags-at)))
15222 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15223 ":"))
15224 props))
15225 (when (or (not specific) (string= specific "BLOCKED"))
15226 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15227 (when (or (not specific)
15228 (member specific
15229 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15230 "TIMESTAMP" "TIMESTAMP_IA")))
15231 (catch 'match
15232 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15233 (setq key (if (match-end 1)
15234 (substring (org-match-string-no-properties 1)
15235 0 -1))
15236 string (if (equal key clockstr)
15237 (org-trim
15238 (buffer-substring-no-properties
15239 (match-beginning 3) (goto-char
15240 (point-at-eol))))
15241 (substring (org-match-string-no-properties 3)
15242 1 -1)))
15243 ;; Get the correct property name from the key. This is
15244 ;; necessary if the user has configured time keywords.
15245 (setq key1 (concat key ":"))
15246 (cond
15247 ((not key)
15248 (setq key
15249 (if (= (char-after (match-beginning 3)) ?\[)
15250 "TIMESTAMP_IA" "TIMESTAMP")))
15251 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15252 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15253 ((equal key1 org-closed-string) (setq key "CLOSED"))
15254 ((equal key1 org-clock-string) (setq key "CLOCK")))
15255 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15256 (progn
15257 (push (cons key string) props)
15258 ;; no need to search further if match is found
15259 (throw 'match t))
15260 (when (or (equal key "CLOCK") (not (assoc key props)))
15261 (push (cons key string) props)))))))
15263 (when (memq which '(all standard))
15264 ;; Get the standard properties, like :PROP: ...
15265 (setq range (org-get-property-block beg end))
15266 (when range
15267 (goto-char (car range))
15268 (while (re-search-forward org-property-re
15269 (cdr range) t)
15270 (setq key (org-match-string-no-properties 2)
15271 value (org-trim (or (org-match-string-no-properties 3) "")))
15272 (unless (member key excluded)
15273 (push (cons key (or value "")) props)))))
15274 (if clocksum
15275 (push (cons "CLOCKSUM"
15276 (org-columns-number-to-string (/ (float clocksum) 60.)
15277 'add_times))
15278 props))
15279 (if clocksumt
15280 (push (cons "CLOCKSUM_T"
15281 (org-columns-number-to-string (/ (float clocksumt) 60.)
15282 'add_times))
15283 props))
15284 (unless (assoc "CATEGORY" props)
15285 (push (cons "CATEGORY" (org-get-category)) props))
15286 (append sum-props (nreverse props)))))))
15288 (defun org-entry-get (pom property &optional inherit literal-nil)
15289 "Get value of PROPERTY for entry or content at point-or-marker POM.
15290 If INHERIT is non-nil and the entry does not have the property,
15291 then also check higher levels of the hierarchy.
15292 If INHERIT is the symbol `selective', use inheritance only if the setting
15293 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15294 If the property is present but empty, the return value is the empty string.
15295 If the property is not present at all, nil is returned.
15297 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15298 do not interpret it as the list atom nil. This is used for inheritance
15299 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15300 (org-with-point-at pom
15301 (if (and inherit (if (eq inherit 'selective)
15302 (org-property-inherit-p property)
15304 (org-entry-get-with-inheritance property literal-nil)
15305 (if (member property org-special-properties)
15306 ;; We need a special property. Use `org-entry-properties' to
15307 ;; retrieve it, but specify the wanted property
15308 (cdr (assoc property (org-entry-properties nil 'special property)))
15309 (let ((range (org-get-property-block)))
15310 (when (and range (not (eq (car range) (cdr range))))
15311 (let* ((props (list (or (assoc property org-file-properties)
15312 (assoc property org-global-properties)
15313 (assoc property org-global-properties-fixed))))
15314 (ap (lambda (key)
15315 (when (re-search-forward
15316 (org-re-property key) (cdr range) t)
15317 (setq props
15318 (org-update-property-plist
15320 (if (match-end 3)
15321 (org-match-string-no-properties 3) "")
15322 props)))))
15323 val)
15324 (goto-char (car range))
15325 (funcall ap property)
15326 (goto-char (car range))
15327 (while (funcall ap (concat property "+")))
15328 (setq val (cdr (assoc property props)))
15329 (when val (if literal-nil val (org-not-nil val))))))))))
15331 (defun org-property-or-variable-value (var &optional inherit)
15332 "Check if there is a property fixing the value of VAR.
15333 If yes, return this value. If not, return the current value of the variable."
15334 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15335 (if (and prop (stringp prop) (string-match "\\S-" prop))
15336 (read prop)
15337 (symbol-value var))))
15339 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15340 "Delete the property PROPERTY from entry at point-or-marker POM.
15341 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15342 an empty drawer to delete."
15343 (org-with-point-at pom
15344 (if (member property org-special-properties)
15345 nil ; cannot delete these properties.
15346 (let ((range (org-get-property-block)))
15347 (if (and range
15348 (goto-char (car range))
15349 (re-search-forward
15350 (org-re-property property)
15351 (cdr range) t))
15352 (progn
15353 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15354 (and delete-empty-drawer
15355 (org-remove-empty-drawer-at
15356 delete-empty-drawer (car range)))
15358 nil)))))
15360 ;; Multi-values properties are properties that contain multiple values
15361 ;; These values are assumed to be single words, separated by whitespace.
15362 (defun org-entry-add-to-multivalued-property (pom property value)
15363 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15364 (let* ((old (org-entry-get pom property))
15365 (values (and old (org-split-string old "[ \t]"))))
15366 (setq value (org-entry-protect-space value))
15367 (unless (member value values)
15368 (setq values (append values (list value)))
15369 (org-entry-put pom property
15370 (mapconcat 'identity values " ")))))
15372 (defun org-entry-remove-from-multivalued-property (pom property value)
15373 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15374 (let* ((old (org-entry-get pom property))
15375 (values (and old (org-split-string old "[ \t]"))))
15376 (setq value (org-entry-protect-space value))
15377 (when (member value values)
15378 (setq values (delete value values))
15379 (org-entry-put pom property
15380 (mapconcat 'identity values " ")))))
15382 (defun org-entry-member-in-multivalued-property (pom property value)
15383 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15384 (let* ((old (org-entry-get pom property))
15385 (values (and old (org-split-string old "[ \t]"))))
15386 (setq value (org-entry-protect-space value))
15387 (member value values)))
15389 (defun org-entry-get-multivalued-property (pom property)
15390 "Return a list of values in a multivalued property."
15391 (let* ((value (org-entry-get pom property))
15392 (values (and value (org-split-string value "[ \t]"))))
15393 (mapcar 'org-entry-restore-space values)))
15395 (defun org-entry-put-multivalued-property (pom property &rest values)
15396 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15397 VALUES should be a list of strings. Spaces will be protected."
15398 (org-entry-put pom property
15399 (mapconcat 'org-entry-protect-space values " "))
15400 (let* ((value (org-entry-get pom property))
15401 (values (and value (org-split-string value "[ \t]"))))
15402 (mapcar 'org-entry-restore-space values)))
15404 (defun org-entry-protect-space (s)
15405 "Protect spaces and newline in string S."
15406 (while (string-match " " s)
15407 (setq s (replace-match "%20" t t s)))
15408 (while (string-match "\n" s)
15409 (setq s (replace-match "%0A" t t s)))
15412 (defun org-entry-restore-space (s)
15413 "Restore spaces and newline in string S."
15414 (while (string-match "%20" s)
15415 (setq s (replace-match " " t t s)))
15416 (while (string-match "%0A" s)
15417 (setq s (replace-match "\n" t t s)))
15420 (defvar org-entry-property-inherited-from (make-marker)
15421 "Marker pointing to the entry from where a property was inherited.
15422 Each call to `org-entry-get-with-inheritance' will set this marker to the
15423 location of the entry where the inheritance search matched. If there was
15424 no match, the marker will point nowhere.
15425 Note that also `org-entry-get' calls this function, if the INHERIT flag
15426 is set.")
15428 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15429 "Get PROPERTY of entry or content at point, search higher levels if needed.
15430 The search will stop at the first ancestor which has the property defined.
15431 If the value found is \"nil\", return nil to show that the property
15432 should be considered as undefined (this is the meaning of nil here).
15433 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15434 (move-marker org-entry-property-inherited-from nil)
15435 (let (tmp)
15436 (save-excursion
15437 (save-restriction
15438 (widen)
15439 (catch 'ex
15440 (while t
15441 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15442 (or (ignore-errors (org-back-to-heading t))
15443 (goto-char (point-min)))
15444 (move-marker org-entry-property-inherited-from (point))
15445 (throw 'ex tmp))
15446 (or (ignore-errors (org-up-heading-safe))
15447 (throw 'ex nil))))))
15448 (setq tmp (or tmp
15449 (cdr (assoc property org-file-properties))
15450 (cdr (assoc property org-global-properties))
15451 (cdr (assoc property org-global-properties-fixed))))
15452 (if literal-nil tmp (org-not-nil tmp))))
15454 (defvar org-property-changed-functions nil
15455 "Hook called when the value of a property has changed.
15456 Each hook function should accept two arguments, the name of the property
15457 and the new value.")
15459 (defun org-entry-put (pom property value)
15460 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15461 (org-with-point-at pom
15462 (org-back-to-heading t)
15463 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15464 range)
15465 (cond
15466 ((equal property "TODO")
15467 (when (and (stringp value) (string-match "\\S-" value)
15468 (not (member value org-todo-keywords-1)))
15469 (user-error "\"%s\" is not a valid TODO state" value))
15470 (if (or (not value)
15471 (not (string-match "\\S-" value)))
15472 (setq value 'none))
15473 (org-todo value)
15474 (org-set-tags nil 'align))
15475 ((equal property "PRIORITY")
15476 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15477 (string-to-char value) ?\ ))
15478 (org-set-tags nil 'align))
15479 ((equal property "CLOCKSUM")
15480 (if (not (re-search-forward
15481 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15482 (error "Cannot find a clock log")
15483 (goto-char (- (match-end 1) 2))
15484 (cond
15485 ((eq value 'earlier) (org-timestamp-down))
15486 ((eq value 'later) (org-timestamp-up)))
15487 (org-clock-sum-current-item)))
15488 ((equal property "SCHEDULED")
15489 (if (re-search-forward org-scheduled-time-regexp end t)
15490 (cond
15491 ((eq value 'earlier) (org-timestamp-change -1 'day))
15492 ((eq value 'later) (org-timestamp-change 1 'day))
15493 (t (call-interactively 'org-schedule)))
15494 (call-interactively 'org-schedule)))
15495 ((equal property "DEADLINE")
15496 (if (re-search-forward org-deadline-time-regexp end t)
15497 (cond
15498 ((eq value 'earlier) (org-timestamp-change -1 'day))
15499 ((eq value 'later) (org-timestamp-change 1 'day))
15500 (t (call-interactively 'org-deadline)))
15501 (call-interactively 'org-deadline)))
15502 ((member property org-special-properties)
15503 (error "The %s property can not yet be set with `org-entry-put'"
15504 property))
15505 (t ; a non-special property
15506 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15507 (setq range (org-get-property-block beg end 'force))
15508 (goto-char (car range))
15509 (if (re-search-forward
15510 (org-re-property property) (cdr range) t)
15511 (progn
15512 (delete-region (match-beginning 0) (match-end 0))
15513 (goto-char (match-beginning 0)))
15514 (goto-char (cdr range))
15515 (insert "\n")
15516 (backward-char 1)
15517 (org-indent-line))
15518 (insert ":" property ":")
15519 (and value (insert " " value))
15520 (org-indent-line)))))
15521 (run-hook-with-args 'org-property-changed-functions property value)))
15523 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15524 "Get all property keys in the current buffer.
15525 With INCLUDE-SPECIALS, also list the special properties that reflect things
15526 like tags and TODO state.
15527 With INCLUDE-DEFAULTS, also include properties that has special meaning
15528 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15529 and others.
15530 With INCLUDE-COLUMNS, also include property names given in COLUMN
15531 formats in the current buffer."
15532 (let (rtn range cfmt s p)
15533 (save-excursion
15534 (save-restriction
15535 (widen)
15536 (goto-char (point-min))
15537 (while (re-search-forward org-property-start-re nil t)
15538 (setq range (org-get-property-block))
15539 (goto-char (car range))
15540 (while (re-search-forward org-property-re
15541 (cdr range) t)
15542 (add-to-list 'rtn (org-match-string-no-properties 2)))
15543 (outline-next-heading))))
15545 (when include-specials
15546 (setq rtn (append org-special-properties rtn)))
15548 (when include-defaults
15549 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15550 (add-to-list 'rtn org-effort-property))
15552 (when include-columns
15553 (save-excursion
15554 (save-restriction
15555 (widen)
15556 (goto-char (point-min))
15557 (while (re-search-forward
15558 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15559 nil t)
15560 (setq cfmt (match-string 2) s 0)
15561 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15562 cfmt s)
15563 (setq s (match-end 0)
15564 p (match-string 1 cfmt))
15565 (unless (or (equal p "ITEM")
15566 (member p org-special-properties))
15567 (add-to-list 'rtn (match-string 1 cfmt))))))))
15569 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15571 (defun org-property-values (key)
15572 "Return a list of all values of property KEY in the current buffer."
15573 (save-excursion
15574 (save-restriction
15575 (widen)
15576 (goto-char (point-min))
15577 (let ((re (org-re-property key))
15578 values)
15579 (while (re-search-forward re nil t)
15580 (add-to-list 'values (org-trim (match-string 3))))
15581 (delete "" values)))))
15583 (defun org-insert-property-drawer ()
15584 "Insert a property drawer into the current entry."
15585 (org-back-to-heading t)
15586 (looking-at org-outline-regexp)
15587 (let ((indent (if org-adapt-indentation
15588 (- (match-end 0) (match-beginning 0))
15590 (beg (point))
15591 (re (concat "^[ \t]*" org-keyword-time-regexp))
15592 end hiddenp)
15593 (outline-next-heading)
15594 (setq end (point))
15595 (goto-char beg)
15596 (while (re-search-forward re end t))
15597 (setq hiddenp (outline-invisible-p))
15598 (end-of-line 1)
15599 (and (equal (char-after) ?\n) (forward-char 1))
15600 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15601 (if (member (match-string 1) '("CLOCK:" ":END:"))
15602 ;; just skip this line
15603 (beginning-of-line 2)
15604 ;; Drawer start, find the end
15605 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15606 (beginning-of-line 1)))
15607 (org-skip-over-state-notes)
15608 (skip-chars-backward " \t\n\r")
15609 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15610 (forward-char 1))
15611 (goto-char (point-at-eol))
15612 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15613 (beginning-of-line 0)
15614 (org-indent-to-column indent)
15615 (beginning-of-line 2)
15616 (org-indent-to-column indent)
15617 (beginning-of-line 0)
15618 (if hiddenp
15619 (save-excursion
15620 (org-back-to-heading t)
15621 (hide-entry))
15622 (org-flag-drawer t))))
15624 (defun org-insert-drawer (&optional arg drawer)
15625 "Insert a drawer at point.
15627 Optional argument DRAWER, when non-nil, is a string representing
15628 drawer's name. Otherwise, the user is prompted for a name.
15630 If a region is active, insert the drawer around that region
15631 instead.
15633 Point is left between drawer's boundaries."
15634 (interactive "P")
15635 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15636 "LOGBOOK"))
15637 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15638 ;; internally by Org. They are meant to be inserted
15639 ;; automatically.
15640 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15641 ;; Remove system drawers from list. Note: For some reason,
15642 ;; `org-completing-read' ignores the predicate while
15643 ;; `completing-read' handles it fine.
15644 (drawer (if arg "PROPERTIES"
15645 (or drawer
15646 (completing-read
15647 "Drawer: " org-drawers
15648 (lambda (d) (not (member d system-drawers))))))))
15649 (cond
15650 ;; With C-u, fall back on `org-insert-property-drawer'
15651 (arg (org-insert-property-drawer))
15652 ;; With an active region, insert a drawer at point.
15653 ((not (org-region-active-p))
15654 (progn
15655 (unless (bolp) (insert "\n"))
15656 (insert (format ":%s:\n\n:END:\n" drawer))
15657 (forward-line -2)))
15658 ;; Otherwise, insert the drawer at point
15660 (let ((rbeg (region-beginning))
15661 (rend (copy-marker (region-end))))
15662 (unwind-protect
15663 (progn
15664 (goto-char rbeg)
15665 (beginning-of-line)
15666 (when (save-excursion
15667 (re-search-forward org-outline-regexp-bol rend t))
15668 (user-error "Drawers cannot contain headlines"))
15669 ;; Position point at the beginning of the first
15670 ;; non-blank line in region. Insert drawer's opening
15671 ;; there, then indent it.
15672 (org-skip-whitespace)
15673 (beginning-of-line)
15674 (insert ":" drawer ":\n")
15675 (forward-line -1)
15676 (indent-for-tab-command)
15677 ;; Move point to the beginning of the first blank line
15678 ;; after the last non-blank line in region. Insert
15679 ;; drawer's closing, then indent it.
15680 (goto-char rend)
15681 (skip-chars-backward " \r\t\n")
15682 (insert "\n:END:")
15683 (deactivate-mark t)
15684 (indent-for-tab-command)
15685 (unless (eolp) (insert "\n")))
15686 ;; Clear marker, whatever the outcome of insertion is.
15687 (set-marker rend nil)))))))
15689 (defvar org-property-set-functions-alist nil
15690 "Property set function alist.
15691 Each entry should have the following format:
15693 (PROPERTY . READ-FUNCTION)
15695 The read function will be called with the same argument as
15696 `org-completing-read'.")
15698 (defun org-set-property-function (property)
15699 "Get the function that should be used to set PROPERTY.
15700 This is computed according to `org-property-set-functions-alist'."
15701 (or (cdr (assoc property org-property-set-functions-alist))
15702 'org-completing-read))
15704 (defun org-read-property-value (property)
15705 "Read PROPERTY value from user."
15706 (let* ((completion-ignore-case t)
15707 (allowed (org-property-get-allowed-values nil property 'table))
15708 (cur (org-entry-get nil property))
15709 (prompt (concat property " value"
15710 (if (and cur (string-match "\\S-" cur))
15711 (concat " [" cur "]") "") ": "))
15712 (set-function (org-set-property-function property))
15713 (val (if allowed
15714 (funcall set-function prompt allowed nil
15715 (not (get-text-property 0 'org-unrestricted
15716 (caar allowed))))
15717 (let (org-completion-use-ido org-completion-use-iswitchb)
15718 (funcall set-function prompt
15719 (mapcar 'list (org-property-values property))
15720 nil nil "" nil cur)))))
15721 (if (equal val "")
15723 val)))
15725 (defvar org-last-set-property nil)
15726 (defvar org-last-set-property-value nil)
15727 (defun org-read-property-name ()
15728 "Read a property name."
15729 (let* ((completion-ignore-case t)
15730 (keys (org-buffer-property-keys nil t t))
15731 (default-prop (or (save-excursion
15732 (save-match-data
15733 (beginning-of-line)
15734 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15735 (null (string= (match-string 1) "END"))
15736 (match-string 1))))
15737 org-last-set-property))
15738 (property (org-icompleting-read
15739 (concat "Property"
15740 (if default-prop (concat " [" default-prop "]") "")
15741 ": ")
15742 (mapcar 'list keys)
15743 nil nil nil nil
15744 default-prop)))
15745 (if (member property keys)
15746 property
15747 (or (cdr (assoc (downcase property)
15748 (mapcar (lambda (x) (cons (downcase x) x))
15749 keys)))
15750 property))))
15752 (defun org-set-property-and-value (use-last)
15753 "Allow to set [PROPERTY]: [value] direction from prompt.
15754 When use-default, don't even ask, just use the last
15755 \"[PROPERTY]: [value]\" string from the history."
15756 (interactive "P")
15757 (let* ((completion-ignore-case t)
15758 (pv (or (and use-last org-last-set-property-value)
15759 (org-completing-read
15760 "Enter a \"[Property]: [value]\" pair: "
15761 nil nil nil nil nil
15762 org-last-set-property-value)))
15763 prop val)
15764 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15765 (setq prop (match-string 1 pv)
15766 val (match-string 2 pv))
15767 (org-set-property prop val))))
15769 (defun org-set-property (property value)
15770 "In the current entry, set PROPERTY to VALUE.
15771 When called interactively, this will prompt for a property name, offering
15772 completion on existing and default properties. And then it will prompt
15773 for a value, offering completion either on allowed values (via an inherited
15774 xxx_ALL property) or on existing values in other instances of this property
15775 in the current file."
15776 (interactive (list nil nil))
15777 (let* ((property (or property (org-read-property-name)))
15778 (value (or value (org-read-property-value property)))
15779 (fn (cdr (assoc property org-properties-postprocess-alist))))
15780 (setq org-last-set-property property)
15781 (setq org-last-set-property-value (concat property ": " value))
15782 ;; Possibly postprocess the inserted value:
15783 (when fn (setq value (funcall fn value)))
15784 (unless (equal (org-entry-get nil property) value)
15785 (org-entry-put nil property value))))
15787 (defun org-delete-property (property &optional delete-empty-drawer)
15788 "In the current entry, delete PROPERTY.
15789 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15790 an empty drawer to delete."
15791 (interactive
15792 (let* ((completion-ignore-case t)
15793 (prop (org-icompleting-read "Property: "
15794 (org-entry-properties nil 'standard))))
15795 (list prop)))
15796 (message "Property %s %s" property
15797 (if (org-entry-delete nil property delete-empty-drawer)
15798 "deleted"
15799 "was not present in the entry")))
15801 (defun org-delete-property-globally (property)
15802 "Remove PROPERTY globally, from all entries."
15803 (interactive
15804 (let* ((completion-ignore-case t)
15805 (prop (org-icompleting-read
15806 "Globally remove property: "
15807 (mapcar 'list (org-buffer-property-keys)))))
15808 (list prop)))
15809 (save-excursion
15810 (save-restriction
15811 (widen)
15812 (goto-char (point-min))
15813 (let ((cnt 0))
15814 (while (re-search-forward
15815 (org-re-property property)
15816 nil t)
15817 (setq cnt (1+ cnt))
15818 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15819 (message "Property \"%s\" removed from %d entries" property cnt)))))
15821 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15823 (defun org-compute-property-at-point ()
15824 "Compute the property at point.
15825 This looks for an enclosing column format, extracts the operator and
15826 then applies it to the property in the column format's scope."
15827 (interactive)
15828 (unless (org-at-property-p)
15829 (user-error "Not at a property"))
15830 (let ((prop (org-match-string-no-properties 2)))
15831 (org-columns-get-format-and-top-level)
15832 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15833 (user-error "No operator defined for property %s" prop))
15834 (org-columns-compute prop)))
15836 (defvar org-property-allowed-value-functions nil
15837 "Hook for functions supplying allowed values for a specific property.
15838 The functions must take a single argument, the name of the property, and
15839 return a flat list of allowed values. If \":ETC\" is one of
15840 the values, this means that these values are intended as defaults for
15841 completion, but that other values should be allowed too.
15842 The functions must return nil if they are not responsible for this
15843 property.")
15845 (defun org-property-get-allowed-values (pom property &optional table)
15846 "Get allowed values for the property PROPERTY.
15847 When TABLE is non-nil, return an alist that can directly be used for
15848 completion."
15849 (let (vals)
15850 (cond
15851 ((equal property "TODO")
15852 (setq vals (org-with-point-at pom
15853 (append org-todo-keywords-1 '("")))))
15854 ((equal property "PRIORITY")
15855 (let ((n org-lowest-priority))
15856 (while (>= n org-highest-priority)
15857 (push (char-to-string n) vals)
15858 (setq n (1- n)))))
15859 ((member property org-special-properties))
15860 ((setq vals (run-hook-with-args-until-success
15861 'org-property-allowed-value-functions property)))
15863 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15864 (when (and vals (string-match "\\S-" vals))
15865 (setq vals (car (read-from-string (concat "(" vals ")"))))
15866 (setq vals (mapcar (lambda (x)
15867 (cond ((stringp x) x)
15868 ((numberp x) (number-to-string x))
15869 ((symbolp x) (symbol-name x))
15870 (t "???")))
15871 vals)))))
15872 (when (member ":ETC" vals)
15873 (setq vals (remove ":ETC" vals))
15874 (org-add-props (car vals) '(org-unrestricted t)))
15875 (if table (mapcar 'list vals) vals)))
15877 (defun org-property-previous-allowed-value (&optional previous)
15878 "Switch to the next allowed value for this property."
15879 (interactive)
15880 (org-property-next-allowed-value t))
15882 (defun org-property-next-allowed-value (&optional previous)
15883 "Switch to the next allowed value for this property."
15884 (interactive)
15885 (unless (org-at-property-p)
15886 (user-error "Not at a property"))
15887 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15888 (key (match-string 2))
15889 (value (match-string 3))
15890 (allowed (or (org-property-get-allowed-values (point) key)
15891 (and (member value '("[ ]" "[-]" "[X]"))
15892 '("[ ]" "[X]"))))
15893 (heading (save-match-data (nth 4 (org-heading-components))))
15894 nval)
15895 (unless allowed
15896 (user-error "Allowed values for this property have not been defined"))
15897 (if previous (setq allowed (reverse allowed)))
15898 (if (member value allowed)
15899 (setq nval (car (cdr (member value allowed)))))
15900 (setq nval (or nval (car allowed)))
15901 (if (equal nval value)
15902 (user-error "Only one allowed value for this property"))
15903 (org-at-property-p)
15904 (replace-match (concat " :" key ": " nval) t t)
15905 (org-indent-line)
15906 (beginning-of-line 1)
15907 (skip-chars-forward " \t")
15908 (when (equal prop org-effort-property)
15909 (save-excursion
15910 (org-back-to-heading t)
15911 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15912 (when (string= org-clock-current-task heading)
15913 (setq org-clock-effort nval)
15914 (org-clock-update-mode-line)))
15915 (run-hook-with-args 'org-property-changed-functions key nval)))
15917 (defun org-find-olp (path &optional this-buffer)
15918 "Return a marker pointing to the entry at outline path OLP.
15919 If anything goes wrong, throw an error.
15920 You can wrap this call to catch the error like this:
15922 (condition-case msg
15923 (org-mobile-locate-entry (match-string 4))
15924 (error (nth 1 msg)))
15926 The return value will then be either a string with the error message,
15927 or a marker if everything is OK.
15929 If THIS-BUFFER is set, the outline path does not contain a file,
15930 only headings."
15931 (let* ((file (if this-buffer buffer-file-name (pop path)))
15932 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15933 (level 1)
15934 (lmin 1)
15935 (lmax 1)
15936 limit re end found pos heading cnt flevel)
15937 (unless buffer (error "File not found :%s" file))
15938 (with-current-buffer buffer
15939 (save-excursion
15940 (save-restriction
15941 (widen)
15942 (setq limit (point-max))
15943 (goto-char (point-min))
15944 (while (setq heading (pop path))
15945 (setq re (format org-complex-heading-regexp-format
15946 (regexp-quote heading)))
15947 (setq cnt 0 pos (point))
15948 (while (re-search-forward re end t)
15949 (setq level (- (match-end 1) (match-beginning 1)))
15950 (if (and (>= level lmin) (<= level lmax))
15951 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15952 (when (= cnt 0) (error "Heading not found on level %d: %s"
15953 lmax heading))
15954 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15955 lmax heading))
15956 (goto-char found)
15957 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15958 (setq end (save-excursion (org-end-of-subtree t t))))
15959 (when (org-at-heading-p)
15960 (point-marker)))))))
15962 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15963 "Find node HEADING in BUFFER.
15964 Return a marker to the heading if it was found, or nil if not.
15965 If POS-ONLY is set, return just the position instead of a marker.
15967 The heading text must match exact, but it may have a TODO keyword,
15968 a priority cookie and tags in the standard locations."
15969 (with-current-buffer (or buffer (current-buffer))
15970 (save-excursion
15971 (save-restriction
15972 (widen)
15973 (goto-char (point-min))
15974 (let (case-fold-search)
15975 (if (re-search-forward
15976 (format org-complex-heading-regexp-format
15977 (regexp-quote heading)) nil t)
15978 (if pos-only
15979 (match-beginning 0)
15980 (move-marker (make-marker) (match-beginning 0)))))))))
15982 (defun org-find-exact-heading-in-directory (heading &optional dir)
15983 "Find Org node headline HEADING in all .org files in directory DIR.
15984 When the target headline is found, return a marker to this location."
15985 (let ((files (directory-files (or dir default-directory)
15986 nil "\\`[^.#].*\\.org\\'"))
15987 file visiting m buffer)
15988 (catch 'found
15989 (while (setq file (pop files))
15990 (message "trying %s" file)
15991 (setq visiting (org-find-base-buffer-visiting file))
15992 (setq buffer (or visiting (find-file-noselect file)))
15993 (setq m (org-find-exact-headline-in-buffer
15994 heading buffer))
15995 (when (and (not m) (not visiting)) (kill-buffer buffer))
15996 (and m (throw 'found m))))))
15998 (defun org-find-entry-with-id (ident)
15999 "Locate the entry that contains the ID property with exact value IDENT.
16000 IDENT can be a string, a symbol or a number, this function will search for
16001 the string representation of it.
16002 Return the position where this entry starts, or nil if there is no such entry."
16003 (interactive "sID: ")
16004 (let ((id (cond
16005 ((stringp ident) ident)
16006 ((symbol-name ident) (symbol-name ident))
16007 ((numberp ident) (number-to-string ident))
16008 (t (error "IDENT %s must be a string, symbol or number" ident))))
16009 (case-fold-search nil))
16010 (save-excursion
16011 (save-restriction
16012 (widen)
16013 (goto-char (point-min))
16014 (when (re-search-forward
16015 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16016 nil t)
16017 (org-back-to-heading t)
16018 (point))))))
16020 ;;;; Timestamps
16022 (defvar org-last-changed-timestamp nil)
16023 (defvar org-last-inserted-timestamp nil
16024 "The last time stamp inserted with `org-insert-time-stamp'.")
16025 (defvar org-time-was-given) ; dynamically scoped parameter
16026 (defvar org-end-time-was-given) ; dynamically scoped parameter
16027 (defvar org-ts-what) ; dynamically scoped parameter
16029 (defun org-time-stamp (arg &optional inactive)
16030 "Prompt for a date/time and insert a time stamp.
16031 If the user specifies a time like HH:MM or if this command is
16032 called with at least one prefix argument, the time stamp contains
16033 the date and the time. Otherwise, only the date is be included.
16035 All parts of a date not specified by the user is filled in from
16036 the current date/time. So if you just press return without
16037 typing anything, the time stamp will represent the current
16038 date/time.
16040 If there is already a timestamp at the cursor, it will be
16041 modified.
16043 With two universal prefix arguments, insert an active timestamp
16044 with the current time without prompting the user."
16045 (interactive "P")
16046 (let* ((ts nil)
16047 (default-time
16048 ;; Default time is either today, or, when entering a range,
16049 ;; the range start.
16050 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16051 (save-excursion
16052 (re-search-backward
16053 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16054 (- (point) 20) t)))
16055 (apply 'encode-time (org-parse-time-string (match-string 1)))
16056 (current-time)))
16057 (default-input (and ts (org-get-compact-tod ts)))
16058 (repeater (save-excursion
16059 (save-match-data
16060 (beginning-of-line)
16061 (when (re-search-forward
16062 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16063 (save-excursion (progn (end-of-line) (point))) t)
16064 (match-string 0)))))
16065 org-time-was-given org-end-time-was-given time)
16066 (cond
16067 ((and (org-at-timestamp-p t)
16068 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16069 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16070 (insert "--")
16071 (setq time (let ((this-command this-command))
16072 (org-read-date arg 'totime nil nil
16073 default-time default-input inactive)))
16074 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16075 ((org-at-timestamp-p t)
16076 (setq time (let ((this-command this-command))
16077 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16078 (when (org-at-timestamp-p t) ; just to get the match data
16079 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16080 (replace-match "")
16081 (setq org-last-changed-timestamp
16082 (org-insert-time-stamp
16083 time (or org-time-was-given arg)
16084 inactive nil nil (list org-end-time-was-given)))
16085 (when repeater (goto-char (1- (point))) (insert " " repeater)
16086 (setq org-last-changed-timestamp
16087 (concat (substring org-last-inserted-timestamp 0 -1)
16088 " " repeater ">"))))
16089 (message "Timestamp updated"))
16090 ((equal arg '(16))
16091 (org-insert-time-stamp (current-time) t))
16093 (setq time (let ((this-command this-command))
16094 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16095 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16096 nil nil (list org-end-time-was-given))))))
16098 ;; FIXME: can we use this for something else, like computing time differences?
16099 (defun org-get-compact-tod (s)
16100 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16101 (let* ((t1 (match-string 1 s))
16102 (h1 (string-to-number (match-string 2 s)))
16103 (m1 (string-to-number (match-string 3 s)))
16104 (t2 (and (match-end 4) (match-string 5 s)))
16105 (h2 (and t2 (string-to-number (match-string 6 s))))
16106 (m2 (and t2 (string-to-number (match-string 7 s))))
16107 dh dm)
16108 (if (not t2)
16110 (setq dh (- h2 h1) dm (- m2 m1))
16111 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16112 (concat t1 "+" (number-to-string dh)
16113 (and (/= 0 dm) (format ":%02d" dm)))))))
16115 (defun org-time-stamp-inactive (&optional arg)
16116 "Insert an inactive time stamp.
16117 An inactive time stamp is enclosed in square brackets instead of angle
16118 brackets. It is inactive in the sense that it does not trigger agenda entries,
16119 does not link to the calendar and cannot be changed with the S-cursor keys.
16120 So these are more for recording a certain time/date."
16121 (interactive "P")
16122 (org-time-stamp arg 'inactive))
16124 (defvar org-date-ovl (make-overlay 1 1))
16125 (overlay-put org-date-ovl 'face 'org-date-selected)
16126 (org-detach-overlay org-date-ovl)
16128 (defvar org-ans1) ; dynamically scoped parameter
16129 (defvar org-ans2) ; dynamically scoped parameter
16131 (defvar org-plain-time-of-day-regexp) ; defined below
16133 (defvar org-overriding-default-time nil) ; dynamically scoped
16134 (defvar org-read-date-overlay nil)
16135 (defvar org-dcst nil) ; dynamically scoped
16136 (defvar org-read-date-history nil)
16137 (defvar org-read-date-final-answer nil)
16138 (defvar org-read-date-analyze-futurep nil)
16139 (defvar org-read-date-analyze-forced-year nil)
16140 (defvar org-read-date-inactive)
16142 (defvar org-read-date-minibuffer-local-map
16143 (let* ((org-replace-disputed-keys nil)
16144 (map (make-sparse-keymap)))
16145 (set-keymap-parent map minibuffer-local-map)
16146 (org-defkey map (kbd ".")
16147 (lambda () (interactive)
16148 ;; Are we at the beginning of the prompt?
16149 (if (looking-back "^[^:]+: ")
16150 (org-eval-in-calendar '(calendar-goto-today))
16151 (insert "."))))
16152 (org-defkey map (kbd "C-.")
16153 (lambda () (interactive)
16154 (org-eval-in-calendar '(calendar-goto-today))))
16155 (org-defkey map [(meta shift left)]
16156 (lambda () (interactive)
16157 (org-eval-in-calendar '(calendar-backward-month 1))))
16158 (org-defkey map [(meta shift right)]
16159 (lambda () (interactive)
16160 (org-eval-in-calendar '(calendar-forward-month 1))))
16161 (org-defkey map [(meta shift up)]
16162 (lambda () (interactive)
16163 (org-eval-in-calendar '(calendar-backward-year 1))))
16164 (org-defkey map [(meta shift down)]
16165 (lambda () (interactive)
16166 (org-eval-in-calendar '(calendar-forward-year 1))))
16167 (org-defkey map [?\e (shift left)]
16168 (lambda () (interactive)
16169 (org-eval-in-calendar '(calendar-backward-month 1))))
16170 (org-defkey map [?\e (shift right)]
16171 (lambda () (interactive)
16172 (org-eval-in-calendar '(calendar-forward-month 1))))
16173 (org-defkey map [?\e (shift up)]
16174 (lambda () (interactive)
16175 (org-eval-in-calendar '(calendar-backward-year 1))))
16176 (org-defkey map [?\e (shift down)]
16177 (lambda () (interactive)
16178 (org-eval-in-calendar '(calendar-forward-year 1))))
16179 (org-defkey map [(shift up)]
16180 (lambda () (interactive)
16181 (org-eval-in-calendar '(calendar-backward-week 1))))
16182 (org-defkey map [(shift down)]
16183 (lambda () (interactive)
16184 (org-eval-in-calendar '(calendar-forward-week 1))))
16185 (org-defkey map [(shift left)]
16186 (lambda () (interactive)
16187 (org-eval-in-calendar '(calendar-backward-day 1))))
16188 (org-defkey map [(shift right)]
16189 (lambda () (interactive)
16190 (org-eval-in-calendar '(calendar-forward-day 1))))
16191 (org-defkey map "!"
16192 (lambda () (interactive)
16193 (org-eval-in-calendar '(diary-view-entries))
16194 (message "")))
16195 (org-defkey map ">"
16196 (lambda () (interactive)
16197 (org-eval-in-calendar '(scroll-calendar-left 1))))
16198 (org-defkey map "<"
16199 (lambda () (interactive)
16200 (org-eval-in-calendar '(scroll-calendar-right 1))))
16201 (org-defkey map "\C-v"
16202 (lambda () (interactive)
16203 (org-eval-in-calendar
16204 '(calendar-scroll-left-three-months 1))))
16205 (org-defkey map "\M-v"
16206 (lambda () (interactive)
16207 (org-eval-in-calendar
16208 '(calendar-scroll-right-three-months 1))))
16209 map)
16210 "Keymap for minibuffer commands when using `org-read-date'.")
16212 (defun org-read-date (&optional org-with-time to-time from-string prompt
16213 default-time default-input inactive)
16214 "Read a date, possibly a time, and make things smooth for the user.
16215 The prompt will suggest to enter an ISO date, but you can also enter anything
16216 which will at least partially be understood by `parse-time-string'.
16217 Unrecognized parts of the date will default to the current day, month, year,
16218 hour and minute. If this command is called to replace a timestamp at point,
16219 or to enter the second timestamp of a range, the default time is taken
16220 from the existing stamp. Furthermore, the command prefers the future,
16221 so if you are giving a date where the year is not given, and the day-month
16222 combination is already past in the current year, it will assume you
16223 mean next year. For details, see the manual. A few examples:
16225 3-2-5 --> 2003-02-05
16226 feb 15 --> currentyear-02-15
16227 2/15 --> currentyear-02-15
16228 sep 12 9 --> 2009-09-12
16229 12:45 --> today 12:45
16230 22 sept 0:34 --> currentyear-09-22 0:34
16231 12 --> currentyear-currentmonth-12
16232 Fri --> nearest Friday after today
16233 -Tue --> last Tuesday
16234 etc.
16236 Furthermore you can specify a relative date by giving, as the *first* thing
16237 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16238 change in days weeks, months, years.
16239 With a single plus or minus, the date is relative to today. With a double
16240 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16241 +4d --> four days from today
16242 +4 --> same as above
16243 +2w --> two weeks from today
16244 ++5 --> five days from default date
16246 The function understands only English month and weekday abbreviations.
16248 While prompting, a calendar is popped up - you can also select the
16249 date with the mouse (button 1). The calendar shows a period of three
16250 months. To scroll it to other months, use the keys `>' and `<'.
16251 If you don't like the calendar, turn it off with
16252 \(setq org-read-date-popup-calendar nil)
16254 With optional argument TO-TIME, the date will immediately be converted
16255 to an internal time.
16256 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16257 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16258 still enter a time, and this function will inform the calling routine
16259 about this change. The calling routine may then choose to change the
16260 format used to insert the time stamp into the buffer to include the time.
16261 With optional argument FROM-STRING, read from this string instead from
16262 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16263 the time/date that is used for everything that is not specified by the
16264 user."
16265 (require 'parse-time)
16266 (let* ((org-time-stamp-rounding-minutes
16267 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16268 (org-dcst org-display-custom-times)
16269 (ct (org-current-time))
16270 (org-def (or org-overriding-default-time default-time ct))
16271 (org-defdecode (decode-time org-def))
16272 (dummy (progn
16273 (when (< (nth 2 org-defdecode) org-extend-today-until)
16274 (setcar (nthcdr 2 org-defdecode) -1)
16275 (setcar (nthcdr 1 org-defdecode) 59)
16276 (setq org-def (apply 'encode-time org-defdecode)
16277 org-defdecode (decode-time org-def)))))
16278 (mouse-autoselect-window nil) ; Don't let the mouse jump
16279 (calendar-frame-setup nil)
16280 (calendar-setup nil)
16281 (calendar-move-hook nil)
16282 (calendar-view-diary-initially-flag nil)
16283 (calendar-view-holidays-initially-flag nil)
16284 (timestr (format-time-string
16285 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16286 (prompt (concat (if prompt (concat prompt " ") "")
16287 (format "Date+time [%s]: " timestr)))
16288 ans (org-ans0 "") org-ans1 org-ans2 final)
16290 (cond
16291 (from-string (setq ans from-string))
16292 (org-read-date-popup-calendar
16293 (save-excursion
16294 (save-window-excursion
16295 (calendar)
16296 (org-eval-in-calendar '(setq cursor-type nil) t)
16297 (unwind-protect
16298 (progn
16299 (calendar-forward-day (- (time-to-days org-def)
16300 (calendar-absolute-from-gregorian
16301 (calendar-current-date))))
16302 (org-eval-in-calendar nil t)
16303 (let* ((old-map (current-local-map))
16304 (map (copy-keymap calendar-mode-map))
16305 (minibuffer-local-map
16306 (copy-keymap org-read-date-minibuffer-local-map)))
16307 (org-defkey map (kbd "RET") 'org-calendar-select)
16308 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16309 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16310 (unwind-protect
16311 (progn
16312 (use-local-map map)
16313 (setq org-read-date-inactive inactive)
16314 (add-hook 'post-command-hook 'org-read-date-display)
16315 (setq org-ans0 (read-string prompt default-input
16316 'org-read-date-history nil))
16317 ;; org-ans0: from prompt
16318 ;; org-ans1: from mouse click
16319 ;; org-ans2: from calendar motion
16320 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16321 (remove-hook 'post-command-hook 'org-read-date-display)
16322 (use-local-map old-map)
16323 (when org-read-date-overlay
16324 (delete-overlay org-read-date-overlay)
16325 (setq org-read-date-overlay nil)))))
16326 (bury-buffer "*Calendar*")))))
16328 (t ; Naked prompt only
16329 (unwind-protect
16330 (setq ans (read-string prompt default-input
16331 'org-read-date-history timestr))
16332 (when org-read-date-overlay
16333 (delete-overlay org-read-date-overlay)
16334 (setq org-read-date-overlay nil)))))
16336 (setq final (org-read-date-analyze ans org-def org-defdecode))
16338 (when org-read-date-analyze-forced-year
16339 (message "Year was forced into %s"
16340 (if org-read-date-force-compatible-dates
16341 "compatible range (1970-2037)"
16342 "range representable on this machine"))
16343 (ding))
16345 ;; One round trip to get rid of 34th of August and stuff like that....
16346 (setq final (decode-time (apply 'encode-time final)))
16348 (setq org-read-date-final-answer ans)
16350 (if to-time
16351 (apply 'encode-time final)
16352 (if (and (boundp 'org-time-was-given) org-time-was-given)
16353 (format "%04d-%02d-%02d %02d:%02d"
16354 (nth 5 final) (nth 4 final) (nth 3 final)
16355 (nth 2 final) (nth 1 final))
16356 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16358 (defvar org-def)
16359 (defvar org-defdecode)
16360 (defvar org-with-time)
16361 (defun org-read-date-display ()
16362 "Display the current date prompt interpretation in the minibuffer."
16363 (when org-read-date-display-live
16364 (when org-read-date-overlay
16365 (delete-overlay org-read-date-overlay))
16366 (when (minibufferp (current-buffer))
16367 (save-excursion
16368 (end-of-line 1)
16369 (while (not (equal (buffer-substring
16370 (max (point-min) (- (point) 4)) (point))
16371 " "))
16372 (insert " ")))
16373 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16374 " " (or org-ans1 org-ans2)))
16375 (org-end-time-was-given nil)
16376 (f (org-read-date-analyze ans org-def org-defdecode))
16377 (fmts (if org-dcst
16378 org-time-stamp-custom-formats
16379 org-time-stamp-formats))
16380 (fmt (if (or org-with-time
16381 (and (boundp 'org-time-was-given) org-time-was-given))
16382 (cdr fmts)
16383 (car fmts)))
16384 (txt (format-time-string fmt (apply 'encode-time f)))
16385 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16386 (txt (concat "=> " txt)))
16387 (when (and org-end-time-was-given
16388 (string-match org-plain-time-of-day-regexp txt))
16389 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16390 org-end-time-was-given
16391 (substring txt (match-end 0)))))
16392 (when org-read-date-analyze-futurep
16393 (setq txt (concat txt " (=>F)")))
16394 (setq org-read-date-overlay
16395 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16396 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16398 (defun org-read-date-analyze (ans org-def org-defdecode)
16399 "Analyze the combined answer of the date prompt."
16400 ;; FIXME: cleanup and comment
16401 (let ((nowdecode (decode-time (current-time)))
16402 delta deltan deltaw deltadef year month day
16403 hour minute second wday pm h2 m2 tl wday1
16404 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16405 (setq org-read-date-analyze-futurep nil
16406 org-read-date-analyze-forced-year nil)
16407 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16408 (setq ans "+0"))
16410 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16411 (setq ans (replace-match "" t t ans)
16412 deltan (car delta)
16413 deltaw (nth 1 delta)
16414 deltadef (nth 2 delta)))
16416 ;; Check if there is an iso week date in there. If yes, store the
16417 ;; info and postpone interpreting it until the rest of the parsing
16418 ;; is done.
16419 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16420 (setq iso-year (if (match-end 1)
16421 (org-small-year-to-year
16422 (string-to-number (match-string 1 ans))))
16423 iso-weekday (if (match-end 3)
16424 (string-to-number (match-string 3 ans)))
16425 iso-week (string-to-number (match-string 2 ans)))
16426 (setq ans (replace-match "" t t ans)))
16428 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16429 (when (string-match
16430 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16431 (setq year (if (match-end 2)
16432 (string-to-number (match-string 2 ans))
16433 (progn (setq kill-year t)
16434 (string-to-number (format-time-string "%Y"))))
16435 month (string-to-number (match-string 3 ans))
16436 day (string-to-number (match-string 4 ans)))
16437 (if (< year 100) (setq year (+ 2000 year)))
16438 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16439 t nil ans)))
16441 ;; Help matching dotted european dates
16442 (when (string-match
16443 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16444 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16445 (setq kill-year t)
16446 (string-to-number (format-time-string "%Y")))
16447 day (string-to-number (match-string 1 ans))
16448 month (string-to-number (match-string 2 ans))
16449 ans (replace-match (format "%04d-%02d-%02d" year month day)
16450 t nil ans)))
16452 ;; Help matching american dates, like 5/30 or 5/30/7
16453 (when (string-match
16454 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16455 (setq year (if (match-end 4)
16456 (string-to-number (match-string 4 ans))
16457 (progn (setq kill-year t)
16458 (string-to-number (format-time-string "%Y"))))
16459 month (string-to-number (match-string 1 ans))
16460 day (string-to-number (match-string 2 ans)))
16461 (if (< year 100) (setq year (+ 2000 year)))
16462 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16463 t nil ans)))
16464 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16465 ;; If there is a time with am/pm, and *no* time without it, we convert
16466 ;; so that matching will be successful.
16467 (loop for i from 1 to 2 do ; twice, for end time as well
16468 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16469 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16470 (setq hour (string-to-number (match-string 1 ans))
16471 minute (if (match-end 3)
16472 (string-to-number (match-string 3 ans))
16474 pm (equal ?p
16475 (string-to-char (downcase (match-string 4 ans)))))
16476 (if (and (= hour 12) (not pm))
16477 (setq hour 0)
16478 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16479 (setq ans (replace-match (format "%02d:%02d" hour minute)
16480 t t ans))))
16482 ;; Check if a time range is given as a duration
16483 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16484 (setq hour (string-to-number (match-string 1 ans))
16485 h2 (+ hour (string-to-number (match-string 3 ans)))
16486 minute (string-to-number (match-string 2 ans))
16487 m2 (+ minute (if (match-end 5) (string-to-number
16488 (match-string 5 ans))0)))
16489 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16490 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16491 t t ans)))
16493 ;; Check if there is a time range
16494 (when (boundp 'org-end-time-was-given)
16495 (setq org-time-was-given nil)
16496 (when (and (string-match org-plain-time-of-day-regexp ans)
16497 (match-end 8))
16498 (setq org-end-time-was-given (match-string 8 ans))
16499 (setq ans (concat (substring ans 0 (match-beginning 7))
16500 (substring ans (match-end 7))))))
16502 (setq tl (parse-time-string ans)
16503 day (or (nth 3 tl) (nth 3 org-defdecode))
16504 month (or (nth 4 tl)
16505 (if (and org-read-date-prefer-future
16506 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16507 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16508 (nth 4 org-defdecode)))
16509 year (or (and (not kill-year) (nth 5 tl))
16510 (if (and org-read-date-prefer-future
16511 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16512 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16513 (nth 5 org-defdecode)))
16514 hour (or (nth 2 tl) (nth 2 org-defdecode))
16515 minute (or (nth 1 tl) (nth 1 org-defdecode))
16516 second (or (nth 0 tl) 0)
16517 wday (nth 6 tl))
16519 (when (and (eq org-read-date-prefer-future 'time)
16520 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16521 (equal day (nth 3 nowdecode))
16522 (equal month (nth 4 nowdecode))
16523 (equal year (nth 5 nowdecode))
16524 (nth 2 tl)
16525 (or (< (nth 2 tl) (nth 2 nowdecode))
16526 (and (= (nth 2 tl) (nth 2 nowdecode))
16527 (nth 1 tl)
16528 (< (nth 1 tl) (nth 1 nowdecode)))))
16529 (setq day (1+ day)
16530 futurep t))
16532 ;; Special date definitions below
16533 (cond
16534 (iso-week
16535 ;; There was an iso week
16536 (require 'cal-iso)
16537 (setq futurep nil)
16538 (setq year (or iso-year year)
16539 day (or iso-weekday wday 1)
16540 wday nil ; to make sure that the trigger below does not match
16541 iso-date (calendar-gregorian-from-absolute
16542 (calendar-absolute-from-iso
16543 (list iso-week day year))))
16544 ; FIXME: Should we also push ISO weeks into the future?
16545 ; (when (and org-read-date-prefer-future
16546 ; (not iso-year)
16547 ; (< (calendar-absolute-from-gregorian iso-date)
16548 ; (time-to-days (current-time))))
16549 ; (setq year (1+ year)
16550 ; iso-date (calendar-gregorian-from-absolute
16551 ; (calendar-absolute-from-iso
16552 ; (list iso-week day year)))))
16553 (setq month (car iso-date)
16554 year (nth 2 iso-date)
16555 day (nth 1 iso-date)))
16556 (deltan
16557 (setq futurep nil)
16558 (unless deltadef
16559 (let ((now (decode-time (current-time))))
16560 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16561 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16562 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16563 ((equal deltaw "m") (setq month (+ month deltan)))
16564 ((equal deltaw "y") (setq year (+ year deltan)))))
16565 ((and wday (not (nth 3 tl)))
16566 ;; Weekday was given, but no day, so pick that day in the week
16567 ;; on or after the derived date.
16568 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16569 (unless (equal wday wday1)
16570 (setq day (+ day (% (- wday wday1 -7) 7))))))
16571 (if (and (boundp 'org-time-was-given)
16572 (nth 2 tl))
16573 (setq org-time-was-given t))
16574 (if (< year 100) (setq year (+ 2000 year)))
16575 ;; Check of the date is representable
16576 (if org-read-date-force-compatible-dates
16577 (progn
16578 (if (< year 1970)
16579 (setq year 1970 org-read-date-analyze-forced-year t))
16580 (if (> year 2037)
16581 (setq year 2037 org-read-date-analyze-forced-year t)))
16582 (condition-case nil
16583 (ignore (encode-time second minute hour day month year))
16584 (error
16585 (setq year (nth 5 org-defdecode))
16586 (setq org-read-date-analyze-forced-year t))))
16587 (setq org-read-date-analyze-futurep futurep)
16588 (list second minute hour day month year)))
16590 (defvar parse-time-weekdays)
16591 (defun org-read-date-get-relative (s today default)
16592 "Check string S for special relative date string.
16593 TODAY and DEFAULT are internal times, for today and for a default.
16594 Return shift list (N what def-flag)
16595 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16596 N is the number of WHATs to shift.
16597 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16598 the DEFAULT date rather than TODAY."
16599 (require 'parse-time)
16600 (when (and
16601 (string-match
16602 (concat
16603 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16604 "\\([0-9]+\\)?"
16605 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16606 "\\([ \t]\\|$\\)") s)
16607 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16608 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16609 (string-to-char (substring (match-string 1 s) -1))
16610 ?+))
16611 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16612 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16613 (what (if (match-end 3) (match-string 3 s) "d"))
16614 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16615 (date (if rel default today))
16616 (wday (nth 6 (decode-time date)))
16617 delta)
16618 (if wday1
16619 (progn
16620 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16621 (if (= delta 0) (setq delta 7))
16622 (if (= dir ?-)
16623 (progn
16624 (setq delta (- delta 7))
16625 (if (= delta 0) (setq delta -7))))
16626 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16627 (list delta "d" rel))
16628 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16630 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16631 "Turn a user-specified date into the internal representation.
16632 The internal representation needed by the calendar is (month day year).
16633 This is a wrapper to handle the brain-dead convention in calendar that
16634 user function argument order change dependent on argument order."
16635 (if (boundp 'calendar-date-style)
16636 (cond
16637 ((eq calendar-date-style 'american)
16638 (list arg1 arg2 arg3))
16639 ((eq calendar-date-style 'european)
16640 (list arg2 arg1 arg3))
16641 ((eq calendar-date-style 'iso)
16642 (list arg2 arg3 arg1)))
16643 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16644 (if (org-bound-and-true-p european-calendar-style)
16645 (list arg2 arg1 arg3)
16646 (list arg1 arg2 arg3)))))
16648 (defun org-eval-in-calendar (form &optional keepdate)
16649 "Eval FORM in the calendar window and return to current window.
16650 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16651 otherwise stick to the current value of `org-ans2'."
16652 (let ((sf (selected-frame))
16653 (sw (selected-window)))
16654 (select-window (get-buffer-window "*Calendar*" t))
16655 (eval form)
16656 (when (and (not keepdate) (calendar-cursor-to-date))
16657 (let* ((date (calendar-cursor-to-date))
16658 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16659 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16660 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16661 (select-window sw)
16662 (org-select-frame-set-input-focus sf)))
16664 (defun org-calendar-select ()
16665 "Return to `org-read-date' with the date currently selected.
16666 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16667 (interactive)
16668 (when (calendar-cursor-to-date)
16669 (let* ((date (calendar-cursor-to-date))
16670 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16671 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16672 (if (active-minibuffer-window) (exit-minibuffer))))
16674 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16675 "Insert a date stamp for the date given by the internal TIME.
16676 WITH-HM means use the stamp format that includes the time of the day.
16677 INACTIVE means use square brackets instead of angular ones, so that the
16678 stamp will not contribute to the agenda.
16679 PRE and POST are optional strings to be inserted before and after the
16680 stamp.
16681 The command returns the inserted time stamp."
16682 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16683 stamp)
16684 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16685 (insert-before-markers (or pre ""))
16686 (when (listp extra)
16687 (setq extra (car extra))
16688 (if (and (stringp extra)
16689 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16690 (setq extra (format "-%02d:%02d"
16691 (string-to-number (match-string 1 extra))
16692 (string-to-number (match-string 2 extra))))
16693 (setq extra nil)))
16694 (when extra
16695 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16696 (insert-before-markers (setq stamp (format-time-string fmt time)))
16697 (insert-before-markers (or post ""))
16698 (setq org-last-inserted-timestamp stamp)))
16700 (defun org-toggle-time-stamp-overlays ()
16701 "Toggle the use of custom time stamp formats."
16702 (interactive)
16703 (setq org-display-custom-times (not org-display-custom-times))
16704 (unless org-display-custom-times
16705 (let ((p (point-min)) (bmp (buffer-modified-p)))
16706 (while (setq p (next-single-property-change p 'display))
16707 (if (and (get-text-property p 'display)
16708 (eq (get-text-property p 'face) 'org-date))
16709 (remove-text-properties
16710 p (setq p (next-single-property-change p 'display))
16711 '(display t))))
16712 (set-buffer-modified-p bmp)))
16713 (if (featurep 'xemacs)
16714 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16715 (org-restart-font-lock)
16716 (setq org-table-may-need-update t)
16717 (if org-display-custom-times
16718 (message "Time stamps are overlaid with custom format")
16719 (message "Time stamp overlays removed")))
16721 (defun org-display-custom-time (beg end)
16722 "Overlay modified time stamp format over timestamp between BEG and END."
16723 (let* ((ts (buffer-substring beg end))
16724 t1 w1 with-hm tf time str w2 (off 0))
16725 (save-match-data
16726 (setq t1 (org-parse-time-string ts t))
16727 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16728 (setq off (- (match-end 0) (match-beginning 0)))))
16729 (setq end (- end off))
16730 (setq w1 (- end beg)
16731 with-hm (and (nth 1 t1) (nth 2 t1))
16732 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16733 time (org-fix-decoded-time t1)
16734 str (org-add-props
16735 (format-time-string
16736 (substring tf 1 -1) (apply 'encode-time time))
16737 nil 'mouse-face 'highlight)
16738 w2 (length str))
16739 (if (not (= w2 w1))
16740 (add-text-properties (1+ beg) (+ 2 beg)
16741 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16742 (if (featurep 'xemacs)
16743 (progn
16744 (put-text-property beg end 'invisible t)
16745 (put-text-property beg end 'end-glyph (make-glyph str)))
16746 (put-text-property beg end 'display str))))
16748 (defun org-translate-time (string)
16749 "Translate all timestamps in STRING to custom format.
16750 But do this only if the variable `org-display-custom-times' is set."
16751 (when org-display-custom-times
16752 (save-match-data
16753 (let* ((start 0)
16754 (re org-ts-regexp-both)
16755 t1 with-hm inactive tf time str beg end)
16756 (while (setq start (string-match re string start))
16757 (setq beg (match-beginning 0)
16758 end (match-end 0)
16759 t1 (save-match-data
16760 (org-parse-time-string (substring string beg end) t))
16761 with-hm (and (nth 1 t1) (nth 2 t1))
16762 inactive (equal (substring string beg (1+ beg)) "[")
16763 tf (funcall (if with-hm 'cdr 'car)
16764 org-time-stamp-custom-formats)
16765 time (org-fix-decoded-time t1)
16766 str (format-time-string
16767 (concat
16768 (if inactive "[" "<") (substring tf 1 -1)
16769 (if inactive "]" ">"))
16770 (apply 'encode-time time))
16771 string (replace-match str t t string)
16772 start (+ start (length str)))))))
16773 string)
16775 (defun org-fix-decoded-time (time)
16776 "Set 0 instead of nil for the first 6 elements of time.
16777 Don't touch the rest."
16778 (let ((n 0))
16779 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16781 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16783 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16784 "Difference between TIMESTAMP-STRING and now in days.
16785 If SECONDS is non-nil, return the difference in seconds."
16786 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16787 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16788 (funcall fdiff (current-time)))))
16790 (defun org-deadline-close (timestamp-string &optional ndays)
16791 "Is the time in TIMESTAMP-STRING close to the current date?"
16792 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16793 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16794 (not (org-entry-is-done-p))))
16796 (defun org-get-wdays (ts &optional delay zero-delay)
16797 "Get the deadline lead time appropriate for timestring TS.
16798 When DELAY is non-nil, get the delay time for scheduled items
16799 instead of the deadline lead time. When ZERO-DELAY is non-nil
16800 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16801 don't try to find the delay cookie in the scheduled timestamp."
16802 (let ((tv (if delay org-scheduled-delay-days
16803 org-deadline-warning-days)))
16804 (cond
16805 ((or (and delay (< tv 0))
16806 (and delay zero-delay (<= tv 0))
16807 (and (not delay) (<= tv 0)))
16808 ;; Enforce this value no matter what
16809 (- tv))
16810 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16811 ;; lead time is specified.
16812 (floor (* (string-to-number (match-string 1 ts))
16813 (cdr (assoc (match-string 2 ts)
16814 '(("d" . 1) ("w" . 7)
16815 ("m" . 30.4) ("y" . 365.25)
16816 ("h" . 0.041667)))))))
16817 ;; go for the default.
16818 (t tv))))
16820 (defun org-calendar-select-mouse (ev)
16821 "Return to `org-read-date' with the date currently selected.
16822 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16823 (interactive "e")
16824 (mouse-set-point ev)
16825 (when (calendar-cursor-to-date)
16826 (let* ((date (calendar-cursor-to-date))
16827 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16828 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16829 (if (active-minibuffer-window) (exit-minibuffer))))
16831 (defun org-check-deadlines (ndays)
16832 "Check if there are any deadlines due or past due.
16833 A deadline is considered due if it happens within `org-deadline-warning-days'
16834 days from today's date. If the deadline appears in an entry marked DONE,
16835 it is not shown. The prefix arg NDAYS can be used to test that many
16836 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16837 (interactive "P")
16838 (let* ((org-warn-days
16839 (cond
16840 ((equal ndays '(4)) 100000)
16841 (ndays (prefix-numeric-value ndays))
16842 (t (abs org-deadline-warning-days))))
16843 (case-fold-search nil)
16844 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16845 (callback
16846 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16848 (message "%d deadlines past-due or due within %d days"
16849 (org-occur regexp nil callback)
16850 org-warn-days)))
16852 (defsubst org-re-timestamp (type)
16853 "Return a regexp for timestamp TYPE.
16854 Allowed values for TYPE are:
16856 all: all timestamps
16857 active: only active timestamps (<...>)
16858 inactive: only inactive timestamps ([...])
16859 scheduled: only scheduled timestamps
16860 deadline: only deadline timestamps
16861 closed: only closed time-stamps
16863 When TYPE is nil, fall back on returning a regexp that matches
16864 both scheduled and deadline timestamps."
16865 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16866 ((eq type 'active) org-ts-regexp)
16867 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16868 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16869 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16870 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16871 ((eq type 'scheduled-or-deadline)
16872 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16874 (defun org-check-before-date (date)
16875 "Check if there are deadlines or scheduled entries before DATE."
16876 (interactive (list (org-read-date)))
16877 (let ((case-fold-search nil)
16878 (regexp (org-re-timestamp org-ts-type))
16879 (callback
16880 (lambda () (time-less-p
16881 (org-time-string-to-time (match-string 1))
16882 (org-time-string-to-time date)))))
16883 (message "%d entries before %s"
16884 (org-occur regexp nil callback) date)))
16886 (defun org-check-after-date (date)
16887 "Check if there are deadlines or scheduled entries after DATE."
16888 (interactive (list (org-read-date)))
16889 (let ((case-fold-search nil)
16890 (regexp (org-re-timestamp org-ts-type))
16891 (callback
16892 (lambda () (not
16893 (time-less-p
16894 (org-time-string-to-time (match-string 1))
16895 (org-time-string-to-time date))))))
16896 (message "%d entries after %s"
16897 (org-occur regexp nil callback) date)))
16899 (defun org-check-dates-range (start-date end-date)
16900 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16901 (interactive (list (org-read-date nil nil nil "Range starts")
16902 (org-read-date nil nil nil "Range end")))
16903 (let ((case-fold-search nil)
16904 (regexp (org-re-timestamp org-ts-type))
16905 (callback
16906 (lambda ()
16907 (let ((match (match-string 1)))
16908 (and
16909 (not (time-less-p
16910 (org-time-string-to-time match)
16911 (org-time-string-to-time start-date)))
16912 (time-less-p
16913 (org-time-string-to-time match)
16914 (org-time-string-to-time end-date)))))))
16915 (message "%d entries between %s and %s"
16916 (org-occur regexp nil callback) start-date end-date)))
16918 (defun org-evaluate-time-range (&optional to-buffer)
16919 "Evaluate a time range by computing the difference between start and end.
16920 Normally the result is just printed in the echo area, but with prefix arg
16921 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16922 If the time range is actually in a table, the result is inserted into the
16923 next column.
16924 For time difference computation, a year is assumed to be exactly 365
16925 days in order to avoid rounding problems."
16926 (interactive "P")
16928 (org-clock-update-time-maybe)
16929 (save-excursion
16930 (unless (org-at-date-range-p t)
16931 (goto-char (point-at-bol))
16932 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16933 (if (not (org-at-date-range-p t))
16934 (user-error "Not at a time-stamp range, and none found in current line")))
16935 (let* ((ts1 (match-string 1))
16936 (ts2 (match-string 2))
16937 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16938 (match-end (match-end 0))
16939 (time1 (org-time-string-to-time ts1))
16940 (time2 (org-time-string-to-time ts2))
16941 (t1 (org-float-time time1))
16942 (t2 (org-float-time time2))
16943 (diff (abs (- t2 t1)))
16944 (negative (< (- t2 t1) 0))
16945 ;; (ys (floor (* 365 24 60 60)))
16946 (ds (* 24 60 60))
16947 (hs (* 60 60))
16948 (fy "%dy %dd %02d:%02d")
16949 (fy1 "%dy %dd")
16950 (fd "%dd %02d:%02d")
16951 (fd1 "%dd")
16952 (fh "%02d:%02d")
16953 y d h m align)
16954 (if havetime
16955 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16957 d (floor (/ diff ds)) diff (mod diff ds)
16958 h (floor (/ diff hs)) diff (mod diff hs)
16959 m (floor (/ diff 60)))
16960 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16962 d (floor (+ (/ diff ds) 0.5))
16963 h 0 m 0))
16964 (if (not to-buffer)
16965 (message "%s" (org-make-tdiff-string y d h m))
16966 (if (org-at-table-p)
16967 (progn
16968 (goto-char match-end)
16969 (setq align t)
16970 (and (looking-at " *|") (goto-char (match-end 0))))
16971 (goto-char match-end))
16972 (if (looking-at
16973 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16974 (replace-match ""))
16975 (if negative (insert " -"))
16976 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16977 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16978 (insert " " (format fh h m))))
16979 (if align (org-table-align))
16980 (message "Time difference inserted")))))
16982 (defun org-make-tdiff-string (y d h m)
16983 (let ((fmt "")
16984 (l nil))
16985 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16986 l (push y l)))
16987 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16988 l (push d l)))
16989 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16990 l (push h l)))
16991 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16992 l (push m l)))
16993 (apply 'format fmt (nreverse l))))
16995 (defun org-time-string-to-time (s &optional buffer pos)
16996 "Convert a timestamp string into internal time."
16997 (condition-case errdata
16998 (apply 'encode-time (org-parse-time-string s))
16999 (error (error "Bad timestamp `%s'%s\nError was: %s"
17000 s (if (not (and buffer pos))
17002 (format " at %d in buffer `%s'" pos buffer))
17003 (cdr errdata)))))
17005 (defun org-time-string-to-seconds (s)
17006 "Convert a timestamp string to a number of seconds."
17007 (org-float-time (org-time-string-to-time s)))
17009 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17010 "Convert a time stamp to an absolute day number.
17011 If there is a specifier for a cyclic time stamp, get the closest
17012 date to DAYNR.
17013 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17014 The variable `date' is bound by the calendar when this is called."
17015 (cond
17016 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17017 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17018 daynr
17019 (+ daynr 1000)))
17020 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17021 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17022 (time-to-days (current-time))) (match-string 0 s)
17023 prefer show-all))
17024 (t (time-to-days
17025 (condition-case errdata
17026 (apply 'encode-time (org-parse-time-string s))
17027 (error (error "Bad timestamp `%s'%s\nError was: %s"
17028 s (if (not (and buffer pos))
17030 (format " at %d in buffer `%s'" pos buffer))
17031 (cdr errdata))))))))
17033 (defun org-days-to-iso-week (days)
17034 "Return the iso week number."
17035 (require 'cal-iso)
17036 (car (calendar-iso-from-absolute days)))
17038 (defun org-small-year-to-year (year)
17039 "Convert 2-digit years into 4-digit years.
17040 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17041 The year 2000 cannot be abbreviated. Any year larger than 99
17042 is returned unchanged."
17043 (if (< year 38)
17044 (setq year (+ 2000 year))
17045 (if (< year 100)
17046 (setq year (+ 1900 year))))
17047 year)
17049 (defun org-time-from-absolute (d)
17050 "Return the time corresponding to date D.
17051 D may be an absolute day number, or a calendar-type list (month day year)."
17052 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17053 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17055 (defun org-calendar-holiday ()
17056 "List of holidays, for Diary display in Org-mode."
17057 (require 'holidays)
17058 (let ((hl (funcall
17059 (if (fboundp 'calendar-check-holidays)
17060 'calendar-check-holidays 'check-calendar-holidays) date)))
17061 (if hl (mapconcat 'identity hl "; "))))
17063 (defun org-diary-sexp-entry (sexp entry date)
17064 "Process a SEXP diary ENTRY for DATE."
17065 (require 'diary-lib)
17066 (let ((result (if calendar-debug-sexp
17067 (let ((stack-trace-on-error t))
17068 (eval (car (read-from-string sexp))))
17069 (condition-case nil
17070 (eval (car (read-from-string sexp)))
17071 (error
17072 (beep)
17073 (message "Bad sexp at line %d in %s: %s"
17074 (org-current-line)
17075 (buffer-file-name) sexp)
17076 (sleep-for 2))))))
17077 (cond ((stringp result) (split-string result "; "))
17078 ((and (consp result)
17079 (not (consp (cdr result)))
17080 (stringp (cdr result))) (cdr result))
17081 ((and (consp result)
17082 (stringp (car result))) result)
17083 (result entry))))
17085 (defun org-diary-to-ical-string (frombuf)
17086 "Get iCalendar entries from diary entries in buffer FROMBUF.
17087 This uses the icalendar.el library."
17088 (let* ((tmpdir (if (featurep 'xemacs)
17089 (temp-directory)
17090 temporary-file-directory))
17091 (tmpfile (make-temp-name
17092 (expand-file-name "orgics" tmpdir)))
17093 buf rtn b e)
17094 (with-current-buffer frombuf
17095 (icalendar-export-region (point-min) (point-max) tmpfile)
17096 (setq buf (find-buffer-visiting tmpfile))
17097 (set-buffer buf)
17098 (goto-char (point-min))
17099 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17100 (setq b (match-beginning 0)))
17101 (goto-char (point-max))
17102 (if (re-search-backward "^END:VEVENT" nil t)
17103 (setq e (match-end 0)))
17104 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17105 (kill-buffer buf)
17106 (delete-file tmpfile)
17107 rtn))
17109 (defun org-closest-date (start current change prefer show-all)
17110 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17111 When PREFER is `past', return a date that is either CURRENT or past.
17112 When PREFER is `future', return a date that is either CURRENT or future.
17113 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17114 ;; Make the proper lists from the dates
17115 (catch 'exit
17116 (let ((a1 '(("h" . hour)
17117 ("d" . day)
17118 ("w" . week)
17119 ("m" . month)
17120 ("y" . year)))
17121 (shour (nth 2 (org-parse-time-string start)))
17122 dn dw sday cday n1 n2 n0
17123 d m y y1 y2 date1 date2 nmonths nm ny m2)
17125 (setq start (org-date-to-gregorian start)
17126 current (org-date-to-gregorian
17127 (if show-all
17128 current
17129 (time-to-days (current-time))))
17130 sday (calendar-absolute-from-gregorian start)
17131 cday (calendar-absolute-from-gregorian current))
17133 (if (<= cday sday) (throw 'exit sday))
17135 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17136 (setq dn (string-to-number (match-string 1 change))
17137 dw (cdr (assoc (match-string 2 change) a1)))
17138 (user-error "Invalid change specifier: %s" change))
17139 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17140 (cond
17141 ((eq dw 'hour)
17142 (let ((missing-hours
17143 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17144 dn)))
17145 (setq n1 (if (zerop missing-hours) cday
17146 (- cday (1+ (floor (/ missing-hours 24)))))
17147 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17148 ((eq dw 'day)
17149 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17150 n2 (+ n1 dn)))
17151 ((eq dw 'year)
17152 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17153 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17154 (setq date1 (list m d y1)
17155 n1 (calendar-absolute-from-gregorian date1)
17156 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17157 n2 (calendar-absolute-from-gregorian date2)))
17158 ((eq dw 'month)
17159 ;; approx number of month between the two dates
17160 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17161 ;; How often does dn fit in there?
17162 (setq d (nth 1 start) m (car start) y (nth 2 start)
17163 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17164 m (+ m nm)
17165 ny (floor (/ m 12))
17166 y (+ y ny)
17167 m (- m (* ny 12)))
17168 (while (> m 12) (setq m (- m 12) y (1+ y)))
17169 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17170 (setq m2 (+ m dn) y2 y)
17171 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17172 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17173 (while (<= n2 cday)
17174 (setq n1 n2 m m2 y y2)
17175 (setq m2 (+ m dn) y2 y)
17176 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17177 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17178 ;; Make sure n1 is the earlier date
17179 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17180 (if show-all
17181 (cond
17182 ((eq prefer 'past) (if (= cday n2) n2 n1))
17183 ((eq prefer 'future) (if (= cday n1) n1 n2))
17184 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17185 (cond
17186 ((eq prefer 'past) (if (= cday n2) n2 n1))
17187 ((eq prefer 'future) (if (= cday n1) n1 n2))
17188 (t (if (= cday n1) n1 n2)))))))
17190 (defun org-date-to-gregorian (date)
17191 "Turn any specification of DATE into a Gregorian date for the calendar."
17192 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17193 ((and (listp date) (= (length date) 3)) date)
17194 ((stringp date)
17195 (setq date (org-parse-time-string date))
17196 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17197 ((listp date)
17198 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17200 (defun org-parse-time-string (s &optional nodefault)
17201 "Parse the standard Org-mode time string.
17202 This should be a lot faster than the normal `parse-time-string'.
17203 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17204 hour and minute fields will be nil if not given."
17205 (cond ((string-match org-ts-regexp0 s)
17206 (list 0
17207 (if (or (match-beginning 8) (not nodefault))
17208 (string-to-number (or (match-string 8 s) "0")))
17209 (if (or (match-beginning 7) (not nodefault))
17210 (string-to-number (or (match-string 7 s) "0")))
17211 (string-to-number (match-string 4 s))
17212 (string-to-number (match-string 3 s))
17213 (string-to-number (match-string 2 s))
17214 nil nil nil))
17215 ((string-match "^<[^>]+>$" s)
17216 (decode-time (seconds-to-time (org-matcher-time s))))
17217 (t (error "Not a standard Org-mode time string: %s" s))))
17219 (defun org-timestamp-up (&optional arg)
17220 "Increase the date item at the cursor by one.
17221 If the cursor is on the year, change the year. If it is on the month,
17222 the day or the time, change that.
17223 With prefix ARG, change by that many units."
17224 (interactive "p")
17225 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17227 (defun org-timestamp-down (&optional arg)
17228 "Decrease the date item at the cursor by one.
17229 If the cursor is on the year, change the year. If it is on the month,
17230 the day or the time, change that.
17231 With prefix ARG, change by that many units."
17232 (interactive "p")
17233 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17235 (defun org-timestamp-up-day (&optional arg)
17236 "Increase the date in the time stamp by one day.
17237 With prefix ARG, change that many days."
17238 (interactive "p")
17239 (if (and (not (org-at-timestamp-p t))
17240 (org-at-heading-p))
17241 (org-todo 'up)
17242 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17244 (defun org-timestamp-down-day (&optional arg)
17245 "Decrease the date in the time stamp by one day.
17246 With prefix ARG, change that many days."
17247 (interactive "p")
17248 (if (and (not (org-at-timestamp-p t))
17249 (org-at-heading-p))
17250 (org-todo 'down)
17251 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17253 (defun org-at-timestamp-p (&optional inactive-ok)
17254 "Determine if the cursor is in or at a timestamp."
17255 (interactive)
17256 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17257 (pos (point))
17258 (ans (or (looking-at tsr)
17259 (save-excursion
17260 (skip-chars-backward "^[<\n\r\t")
17261 (if (> (point) (point-min)) (backward-char 1))
17262 (and (looking-at tsr)
17263 (> (- (match-end 0) pos) -1))))))
17264 (and ans
17265 (boundp 'org-ts-what)
17266 (setq org-ts-what
17267 (cond
17268 ((= pos (match-beginning 0)) 'bracket)
17269 ;; Point is considered to be "on the bracket" whether
17270 ;; it's really on it or right after it.
17271 ((= pos (1- (match-end 0))) 'bracket)
17272 ((= pos (match-end 0)) 'after)
17273 ((org-pos-in-match-range pos 2) 'year)
17274 ((org-pos-in-match-range pos 3) 'month)
17275 ((org-pos-in-match-range pos 7) 'hour)
17276 ((org-pos-in-match-range pos 8) 'minute)
17277 ((or (org-pos-in-match-range pos 4)
17278 (org-pos-in-match-range pos 5)) 'day)
17279 ((and (> pos (or (match-end 8) (match-end 5)))
17280 (< pos (match-end 0)))
17281 (- pos (or (match-end 8) (match-end 5))))
17282 (t 'day))))
17283 ans))
17285 (defun org-toggle-timestamp-type ()
17286 "Toggle the type (<active> or [inactive]) of a time stamp."
17287 (interactive)
17288 (when (org-at-timestamp-p t)
17289 (let ((beg (match-beginning 0)) (end (match-end 0))
17290 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17291 (save-excursion
17292 (goto-char beg)
17293 (while (re-search-forward "[][<>]" end t)
17294 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17295 t t)))
17296 (message "Timestamp is now %sactive"
17297 (if (equal (char-after beg) ?<) "" "in")))))
17299 (defun org-at-clock-log-p nil
17300 "Is the cursor on the clock log line?"
17301 (save-excursion
17302 (move-beginning-of-line 1)
17303 (looking-at "^[ \t]*CLOCK:")))
17305 (defvar org-clock-history) ; defined in org-clock.el
17306 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17307 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17308 "Change the date in the time stamp at point.
17309 The date will be changed by N times WHAT. WHAT can be `day', `month',
17310 `year', `minute', `second'. If WHAT is not given, the cursor position
17311 in the timestamp determines what will be changed.
17312 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17313 (let ((origin (point)) origin-cat
17314 with-hm inactive
17315 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17316 org-ts-what
17317 extra rem
17318 ts time time0 fixnext clrgx)
17319 (if (not (org-at-timestamp-p t))
17320 (user-error "Not at a timestamp"))
17321 (if (and (not what) (eq org-ts-what 'bracket))
17322 (org-toggle-timestamp-type)
17323 ;; Point isn't on brackets. Remember the part of the time-stamp
17324 ;; the point was in. Indeed, size of time-stamps may change,
17325 ;; but point must be kept in the same category nonetheless.
17326 (setq origin-cat org-ts-what)
17327 (if (and (not what) (not (eq org-ts-what 'day))
17328 org-display-custom-times
17329 (get-text-property (point) 'display)
17330 (not (get-text-property (1- (point)) 'display)))
17331 (setq org-ts-what 'day))
17332 (setq org-ts-what (or what org-ts-what)
17333 inactive (= (char-after (match-beginning 0)) ?\[)
17334 ts (match-string 0))
17335 (replace-match "")
17336 (when (string-match
17337 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17339 (setq extra (match-string 1 ts))
17340 (if suppress-tmp-delay
17341 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17342 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17343 (setq with-hm t))
17344 (setq time0 (org-parse-time-string ts))
17345 (when (and updown
17346 (eq org-ts-what 'minute)
17347 (not current-prefix-arg))
17348 ;; This looks like s-up and s-down. Change by one rounding step.
17349 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17350 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17351 (setcar (cdr time0) (+ (nth 1 time0)
17352 (if (> n 0) (- rem) (- dm rem))))))
17353 (setq time
17354 (encode-time (or (car time0) 0)
17355 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17356 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17357 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17358 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17359 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17360 (nthcdr 6 time0)))
17361 (when (and (member org-ts-what '(hour minute))
17362 extra
17363 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17364 (setq extra (org-modify-ts-extra
17365 extra
17366 (if (eq org-ts-what 'hour) 2 5)
17367 n dm)))
17368 (when (integerp org-ts-what)
17369 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17370 (if (eq what 'calendar)
17371 (let ((cal-date (org-get-date-from-calendar)))
17372 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17373 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17374 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17375 (setcar time0 (or (car time0) 0))
17376 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17377 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17378 (setq time (apply 'encode-time time0))))
17379 ;; Insert the new time-stamp, and ensure point stays in the same
17380 ;; category as before (i.e. not after the last position in that
17381 ;; category).
17382 (let ((pos (point)))
17383 ;; Stay before inserted string. `save-excursion' is of no use.
17384 (setq org-last-changed-timestamp
17385 (org-insert-time-stamp time with-hm inactive nil nil extra))
17386 (goto-char pos))
17387 (save-match-data
17388 (looking-at org-ts-regexp3)
17389 (goto-char (cond
17390 ;; `day' category ends before `hour' if any, or at
17391 ;; the end of the day name.
17392 ((eq origin-cat 'day)
17393 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17394 ((eq origin-cat 'hour) (min (match-end 7) origin))
17395 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17396 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17397 ;; `year' and `month' have both fixed size: point
17398 ;; couldn't have moved into another part.
17399 (t origin))))
17400 ;; Update clock if on a CLOCK line.
17401 (org-clock-update-time-maybe)
17402 ;; Maybe adjust the closest clock in `org-clock-history'
17403 (when org-clock-adjust-closest
17404 (if (not (and (org-at-clock-log-p)
17405 (< 1 (length (delq nil (mapcar 'marker-position
17406 org-clock-history))))))
17407 (message "No clock to adjust")
17408 (cond ((save-excursion ; fix previous clock?
17409 (re-search-backward org-ts-regexp0 nil t)
17410 (org-looking-back (concat org-clock-string " \\[")))
17411 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17412 ((save-excursion ; fix next clock?
17413 (re-search-backward org-ts-regexp0 nil t)
17414 (looking-at (concat org-ts-regexp0 "\\] =>")))
17415 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17416 (save-window-excursion
17417 ;; Find closest clock to point, adjust the previous/next one in history
17418 (let* ((p (save-excursion (org-back-to-heading t)))
17419 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17420 (clfixnth
17421 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17422 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17423 (if (not clfixpos)
17424 (message "No clock to adjust")
17425 (save-excursion
17426 (org-goto-marker-or-bmk clfixpos)
17427 (org-show-subtree)
17428 (when (re-search-forward clrgx nil t)
17429 (goto-char (match-beginning 1))
17430 (let (org-clock-adjust-closest)
17431 (org-timestamp-change n org-ts-what updown))
17432 (message "Clock adjusted in %s for heading: %s"
17433 (file-name-nondirectory (buffer-file-name))
17434 (org-get-heading t t)))))))))
17435 ;; Try to recenter the calendar window, if any.
17436 (if (and org-calendar-follow-timestamp-change
17437 (get-buffer-window "*Calendar*" t)
17438 (memq org-ts-what '(day month year)))
17439 (org-recenter-calendar (time-to-days time))))))
17441 (defun org-modify-ts-extra (s pos n dm)
17442 "Change the different parts of the lead-time and repeat fields in timestamp."
17443 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17444 ng h m new rem)
17445 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17446 (cond
17447 ((or (org-pos-in-match-range pos 2)
17448 (org-pos-in-match-range pos 3))
17449 (setq m (string-to-number (match-string 3 s))
17450 h (string-to-number (match-string 2 s)))
17451 (if (org-pos-in-match-range pos 2)
17452 (setq h (+ h n))
17453 (setq n (* dm (org-no-warnings (signum n))))
17454 (when (not (= 0 (setq rem (% m dm))))
17455 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17456 (setq m (+ m n)))
17457 (if (< m 0) (setq m (+ m 60) h (1- h)))
17458 (if (> m 59) (setq m (- m 60) h (1+ h)))
17459 (setq h (min 24 (max 0 h)))
17460 (setq ng 1 new (format "-%02d:%02d" h m)))
17461 ((org-pos-in-match-range pos 6)
17462 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17463 ((org-pos-in-match-range pos 5)
17464 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17466 ((org-pos-in-match-range pos 9)
17467 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17468 ((org-pos-in-match-range pos 8)
17469 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17471 (when ng
17472 (setq s (concat
17473 (substring s 0 (match-beginning ng))
17475 (substring s (match-end ng))))))
17478 (defun org-recenter-calendar (date)
17479 "If the calendar is visible, recenter it to DATE."
17480 (let ((cwin (get-buffer-window "*Calendar*" t)))
17481 (when cwin
17482 (let ((calendar-move-hook nil))
17483 (with-selected-window cwin
17484 (calendar-goto-date (if (listp date) date
17485 (calendar-gregorian-from-absolute date))))))))
17487 (defun org-goto-calendar (&optional arg)
17488 "Go to the Emacs calendar at the current date.
17489 If there is a time stamp in the current line, go to that date.
17490 A prefix ARG can be used to force the current date."
17491 (interactive "P")
17492 (let ((tsr org-ts-regexp) diff
17493 (calendar-move-hook nil)
17494 (calendar-view-holidays-initially-flag nil)
17495 (calendar-view-diary-initially-flag nil))
17496 (if (or (org-at-timestamp-p)
17497 (save-excursion
17498 (beginning-of-line 1)
17499 (looking-at (concat ".*" tsr))))
17500 (let ((d1 (time-to-days (current-time)))
17501 (d2 (time-to-days
17502 (org-time-string-to-time (match-string 1)))))
17503 (setq diff (- d2 d1))))
17504 (calendar)
17505 (calendar-goto-today)
17506 (if (and diff (not arg)) (calendar-forward-day diff))))
17508 (defun org-get-date-from-calendar ()
17509 "Return a list (month day year) of date at point in calendar."
17510 (with-current-buffer "*Calendar*"
17511 (save-match-data
17512 (calendar-cursor-to-date))))
17514 (defun org-date-from-calendar ()
17515 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17516 If there is already a time stamp at the cursor position, update it."
17517 (interactive)
17518 (if (org-at-timestamp-p t)
17519 (org-timestamp-change 0 'calendar)
17520 (let ((cal-date (org-get-date-from-calendar)))
17521 (org-insert-time-stamp
17522 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17524 (defcustom org-effort-durations
17525 `(("h" . 60)
17526 ("d" . ,(* 60 8))
17527 ("w" . ,(* 60 8 5))
17528 ("m" . ,(* 60 8 5 4))
17529 ("y" . ,(* 60 8 5 40)))
17530 "Conversion factor to minutes for an effort modifier.
17532 Each entry has the form (MODIFIER . MINUTES).
17534 In an effort string, a number followed by MODIFIER is multiplied
17535 by the specified number of MINUTES to obtain an effort in
17536 minutes.
17538 For example, if the value of this variable is ((\"hours\" . 60)), then an
17539 effort string \"2hours\" is equivalent to 120 minutes."
17540 :group 'org-agenda
17541 :version "24.1"
17542 :type '(alist :key-type (string :tag "Modifier")
17543 :value-type (number :tag "Minutes")))
17545 (defun org-minutes-to-clocksum-string (m)
17546 "Format number of minutes as a clocksum string.
17547 The format is determined by `org-time-clocksum-format',
17548 `org-time-clocksum-use-fractional' and
17549 `org-time-clocksum-fractional-format' and
17550 `org-time-clocksum-use-effort-durations'."
17551 (let ((clocksum "")
17552 (m (round m)) ; Don't allow fractions of minutes
17553 h d w mo y fmt n)
17554 (setq h (if org-time-clocksum-use-effort-durations
17555 (cdr (assoc "h" org-effort-durations)) 60)
17556 d (if org-time-clocksum-use-effort-durations
17557 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17558 w (if org-time-clocksum-use-effort-durations
17559 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17560 mo (if org-time-clocksum-use-effort-durations
17561 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17562 y (if org-time-clocksum-use-effort-durations
17563 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17564 ;; fractional format
17565 (if org-time-clocksum-use-fractional
17566 (cond
17567 ;; single format string
17568 ((stringp org-time-clocksum-fractional-format)
17569 (format org-time-clocksum-fractional-format (/ m (float h))))
17570 ;; choice of fractional formats for different time units
17571 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17572 (> (/ (truncate m) (* y d h)) 0))
17573 (format fmt (/ m (* y d (float h)))))
17574 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17575 (> (/ (truncate m) (* mo d h)) 0))
17576 (format fmt (/ m (* mo d (float h)))))
17577 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17578 (> (/ (truncate m) (* w d h)) 0))
17579 (format fmt (/ m (* w d (float h)))))
17580 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17581 (> (/ (truncate m) (* d h)) 0))
17582 (format fmt (/ m (* d (float h)))))
17583 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17584 (> (/ (truncate m) h) 0))
17585 (format fmt (/ m (float h))))
17586 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17587 (format fmt m))
17588 ;; fall back to smallest time unit with a format
17589 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17590 (format fmt (/ m (float h))))
17591 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17592 (format fmt (/ m (* d (float h)))))
17593 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17594 (format fmt (/ m (* w d (float h)))))
17595 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17596 (format fmt (/ m (* mo d (float h)))))
17597 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17598 (format fmt (/ m (* y d (float h))))))
17599 ;; standard (non-fractional) format, with single format string
17600 (if (stringp org-time-clocksum-format)
17601 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17602 ;; separate formats components
17603 (and (setq fmt (plist-get org-time-clocksum-format :years))
17604 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17605 (plist-get org-time-clocksum-format :require-years))
17606 (setq clocksum (concat clocksum (format fmt n))
17607 m (- m (* n y d h))))
17608 (and (setq fmt (plist-get org-time-clocksum-format :months))
17609 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17610 (plist-get org-time-clocksum-format :require-months))
17611 (setq clocksum (concat clocksum (format fmt n))
17612 m (- m (* n mo d h))))
17613 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17614 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17615 (plist-get org-time-clocksum-format :require-weeks))
17616 (setq clocksum (concat clocksum (format fmt n))
17617 m (- m (* n w d h))))
17618 (and (setq fmt (plist-get org-time-clocksum-format :days))
17619 (or (> (setq n (/ (truncate m) (* d h))) 0)
17620 (plist-get org-time-clocksum-format :require-days))
17621 (setq clocksum (concat clocksum (format fmt n))
17622 m (- m (* n d h))))
17623 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17624 (or (> (setq n (/ (truncate m) h)) 0)
17625 (plist-get org-time-clocksum-format :require-hours))
17626 (setq clocksum (concat clocksum (format fmt n))
17627 m (- m (* n h))))
17628 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17629 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17630 (setq clocksum (concat clocksum (format fmt m))))
17631 ;; return formatted time duration
17632 clocksum))))
17634 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17635 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17636 "Org mode version 8.0")
17638 (defun org-hours-to-clocksum-string (n)
17639 (org-minutes-to-clocksum-string (* n 60)))
17641 (defun org-hh:mm-string-to-minutes (s)
17642 "Convert a string H:MM to a number of minutes.
17643 If the string is just a number, interpret it as minutes.
17644 In fact, the first hh:mm or number in the string will be taken,
17645 there can be extra stuff in the string.
17646 If no number is found, the return value is 0."
17647 (cond
17648 ((integerp s) s)
17649 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17650 (+ (* (string-to-number (match-string 1 s)) 60)
17651 (string-to-number (match-string 2 s))))
17652 ((string-match "\\([0-9]+\\)" s)
17653 (string-to-number (match-string 1 s)))
17654 (t 0)))
17656 (defcustom org-image-actual-width t
17657 "Should we use the actual width of images when inlining them?
17659 When set to `t', always use the image width.
17661 When set to a number, use imagemagick (when available) to set
17662 the image's width to this value.
17664 When set to a number in a list, try to get the width from any
17665 #+ATTR.* keyword if it matches a width specification like
17667 #+ATTR_HTML: :width 300px
17669 and fall back on that number if none is found.
17671 When set to nil, try to get the width from an #+ATTR.* keyword
17672 and fall back on the original width if none is found.
17674 This requires Emacs >= 24.1, build with imagemagick support."
17675 :group 'org-appearance
17676 :version "24.4"
17677 :package-version '(Org . "8.0")
17678 :type '(choice
17679 (const :tag "Use the image width" t)
17680 (integer :tag "Use a number of pixels")
17681 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17682 (const :tag "Use #+ATTR* or don't resize" nil)))
17684 (defcustom org-agenda-inhibit-startup nil
17685 "Inhibit startup when preparing agenda buffers.
17686 When this variable is `t' (the default), the initialization of
17687 the Org agenda buffers is inhibited: e.g. the visibility state
17688 is not set, the tables are not re-aligned, etc."
17689 :type 'boolean
17690 :version "24.3"
17691 :group 'org-agenda)
17693 (defcustom org-agenda-ignore-drawer-properties nil
17694 "Avoid updating text properties when building the agenda.
17695 Properties are used to prepare buffers for effort estimates, appointments,
17696 and subtree-local categories.
17697 If you don't use these in the agenda, you can add them to this list and
17698 agenda building will be a bit faster.
17699 The value is a list, with zero or more of the symbols `effort', `appt',
17700 or `category'."
17701 :type '(set :greedy t
17702 (const effort)
17703 (const appt)
17704 (const category))
17705 :version "24.3"
17706 :group 'org-agenda)
17708 (defun org-duration-string-to-minutes (s &optional output-to-string)
17709 "Convert a duration string S to minutes.
17711 A bare number is interpreted as minutes, modifiers can be set by
17712 customizing `org-effort-durations' (which see).
17714 Entries containing a colon are interpreted as H:MM by
17715 `org-hh:mm-string-to-minutes'."
17716 (let ((result 0)
17717 (re (concat "\\([0-9.]+\\) *\\("
17718 (regexp-opt (mapcar 'car org-effort-durations))
17719 "\\)")))
17720 (while (string-match re s)
17721 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17722 (string-to-number (match-string 1 s))))
17723 (setq s (replace-match "" nil t s)))
17724 (setq result (floor result))
17725 (incf result (org-hh:mm-string-to-minutes s))
17726 (if output-to-string (number-to-string result) result)))
17728 ;;;; Files
17730 (defun org-save-all-org-buffers ()
17731 "Save all Org-mode buffers without user confirmation."
17732 (interactive)
17733 (message "Saving all Org-mode buffers...")
17734 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17735 (when (featurep 'org-id) (org-id-locations-save))
17736 (message "Saving all Org-mode buffers... done"))
17738 (defun org-revert-all-org-buffers ()
17739 "Revert all Org-mode buffers.
17740 Prompt for confirmation when there are unsaved changes.
17741 Be sure you know what you are doing before letting this function
17742 overwrite your changes.
17744 This function is useful in a setup where one tracks org files
17745 with a version control system, to revert on one machine after pulling
17746 changes from another. I believe the procedure must be like this:
17748 1. M-x org-save-all-org-buffers
17749 2. Pull changes from the other machine, resolve conflicts
17750 3. M-x org-revert-all-org-buffers"
17751 (interactive)
17752 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17753 (user-error "Abort"))
17754 (save-excursion
17755 (save-window-excursion
17756 (mapc
17757 (lambda (b)
17758 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17759 (with-current-buffer b buffer-file-name))
17760 (org-pop-to-buffer-same-window b)
17761 (revert-buffer t 'no-confirm)))
17762 (buffer-list))
17763 (when (and (featurep 'org-id) org-id-track-globally)
17764 (org-id-locations-load)))))
17766 ;;;; Agenda files
17768 ;;;###autoload
17769 (defun org-switchb (&optional arg)
17770 "Switch between Org buffers.
17771 With one prefix argument, restrict available buffers to files.
17772 With two prefix arguments, restrict available buffers to agenda files.
17774 Defaults to `iswitchb' for buffer name completion.
17775 Set `org-completion-use-ido' to make it use ido instead."
17776 (interactive "P")
17777 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17778 ((equal arg '(16)) (org-buffer-list 'agenda))
17779 (t (org-buffer-list))))
17780 (org-completion-use-iswitchb org-completion-use-iswitchb)
17781 (org-completion-use-ido org-completion-use-ido))
17782 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17783 (setq org-completion-use-iswitchb t))
17784 (org-pop-to-buffer-same-window
17785 (org-icompleting-read "Org buffer: "
17786 (mapcar 'list (mapcar 'buffer-name blist))
17787 nil t))))
17789 ;;; Define some older names previously used for this functionality
17790 ;;;###autoload
17791 (defalias 'org-ido-switchb 'org-switchb)
17792 ;;;###autoload
17793 (defalias 'org-iswitchb 'org-switchb)
17795 (defun org-buffer-list (&optional predicate exclude-tmp)
17796 "Return a list of Org buffers.
17797 PREDICATE can be `export', `files' or `agenda'.
17799 export restrict the list to Export buffers.
17800 files restrict the list to buffers visiting Org files.
17801 agenda restrict the list to buffers visiting agenda files.
17803 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17804 (let* ((bfn nil)
17805 (agenda-files (and (eq predicate 'agenda)
17806 (mapcar 'file-truename (org-agenda-files t))))
17807 (filter
17808 (cond
17809 ((eq predicate 'files)
17810 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17811 ((eq predicate 'export)
17812 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17813 ((eq predicate 'agenda)
17814 (lambda (b)
17815 (with-current-buffer b
17816 (and (derived-mode-p 'org-mode)
17817 (setq bfn (buffer-file-name b))
17818 (member (file-truename bfn) agenda-files)))))
17819 (t (lambda (b) (with-current-buffer b
17820 (or (derived-mode-p 'org-mode)
17821 (string-match "\*Org .*Export"
17822 (buffer-name b)))))))))
17823 (delq nil
17824 (mapcar
17825 (lambda(b)
17826 (if (and (funcall filter b)
17827 (or (not exclude-tmp)
17828 (not (string-match "tmp" (buffer-name b)))))
17830 nil))
17831 (buffer-list)))))
17833 (defun org-agenda-files (&optional unrestricted archives)
17834 "Get the list of agenda files.
17835 Optional UNRESTRICTED means return the full list even if a restriction
17836 is currently in place.
17837 When ARCHIVES is t, include all archive files that are really being
17838 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17839 `org-agenda-archives-mode' is t."
17840 (let ((files
17841 (cond
17842 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17843 ((stringp org-agenda-files) (org-read-agenda-file-list))
17844 ((listp org-agenda-files) org-agenda-files)
17845 (t (error "Invalid value of `org-agenda-files'")))))
17846 (setq files (apply 'append
17847 (mapcar (lambda (f)
17848 (if (file-directory-p f)
17849 (directory-files
17850 f t org-agenda-file-regexp)
17851 (list f)))
17852 files)))
17853 (when org-agenda-skip-unavailable-files
17854 (setq files (delq nil
17855 (mapcar (function
17856 (lambda (file)
17857 (and (file-readable-p file) file)))
17858 files))))
17859 (when (or (eq archives t)
17860 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17861 (setq files (org-add-archive-files files)))
17862 files))
17864 (defun org-agenda-file-p (&optional file)
17865 "Return non-nil, if FILE is an agenda file.
17866 If FILE is omitted, use the file associated with the current
17867 buffer."
17868 (member (or file (buffer-file-name))
17869 (org-agenda-files t)))
17871 (defun org-edit-agenda-file-list ()
17872 "Edit the list of agenda files.
17873 Depending on setup, this either uses customize to edit the variable
17874 `org-agenda-files', or it visits the file that is holding the list. In the
17875 latter case, the buffer is set up in a way that saving it automatically kills
17876 the buffer and restores the previous window configuration."
17877 (interactive)
17878 (if (stringp org-agenda-files)
17879 (let ((cw (current-window-configuration)))
17880 (find-file org-agenda-files)
17881 (org-set-local 'org-window-configuration cw)
17882 (org-add-hook 'after-save-hook
17883 (lambda ()
17884 (set-window-configuration
17885 (prog1 org-window-configuration
17886 (kill-buffer (current-buffer))))
17887 (org-install-agenda-files-menu)
17888 (message "New agenda file list installed"))
17889 nil 'local)
17890 (message "%s" (substitute-command-keys
17891 "Edit list and finish with \\[save-buffer]")))
17892 (customize-variable 'org-agenda-files)))
17894 (defun org-store-new-agenda-file-list (list)
17895 "Set new value for the agenda file list and save it correctly."
17896 (if (stringp org-agenda-files)
17897 (let ((fe (org-read-agenda-file-list t)) b u)
17898 (while (setq b (find-buffer-visiting org-agenda-files))
17899 (kill-buffer b))
17900 (with-temp-file org-agenda-files
17901 (insert
17902 (mapconcat
17903 (lambda (f) ;; Keep un-expanded entries.
17904 (if (setq u (assoc f fe))
17905 (cdr u)
17907 list "\n")
17908 "\n")))
17909 (let ((org-mode-hook nil) (org-inhibit-startup t)
17910 (org-insert-mode-line-in-empty-file nil))
17911 (setq org-agenda-files list)
17912 (customize-save-variable 'org-agenda-files org-agenda-files))))
17914 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17915 "Read the list of agenda files from a file.
17916 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17917 filenames, used by `org-store-new-agenda-file-list' to write back
17918 un-expanded file names."
17919 (when (file-directory-p org-agenda-files)
17920 (error "`org-agenda-files' cannot be a single directory"))
17921 (when (stringp org-agenda-files)
17922 (with-temp-buffer
17923 (insert-file-contents org-agenda-files)
17924 (mapcar
17925 (lambda (f)
17926 (let ((e (expand-file-name (substitute-in-file-name f)
17927 org-directory)))
17928 (if pair-with-expansion
17929 (cons e f)
17930 e)))
17931 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17933 ;;;###autoload
17934 (defun org-cycle-agenda-files ()
17935 "Cycle through the files in `org-agenda-files'.
17936 If the current buffer visits an agenda file, find the next one in the list.
17937 If the current buffer does not, find the first agenda file."
17938 (interactive)
17939 (let* ((fs (org-agenda-files t))
17940 (files (append fs (list (car fs))))
17941 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17942 file)
17943 (unless files (user-error "No agenda files"))
17944 (catch 'exit
17945 (while (setq file (pop files))
17946 (if (equal (file-truename file) tcf)
17947 (when (car files)
17948 (find-file (car files))
17949 (throw 'exit t))))
17950 (find-file (car fs)))
17951 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17953 (defun org-agenda-file-to-front (&optional to-end)
17954 "Move/add the current file to the top of the agenda file list.
17955 If the file is not present in the list, it is added to the front. If it is
17956 present, it is moved there. With optional argument TO-END, add/move to the
17957 end of the list."
17958 (interactive "P")
17959 (let ((org-agenda-skip-unavailable-files nil)
17960 (file-alist (mapcar (lambda (x)
17961 (cons (file-truename x) x))
17962 (org-agenda-files t)))
17963 (ctf (file-truename
17964 (or buffer-file-name
17965 (user-error "Please save the current buffer to a file"))))
17966 x had)
17967 (setq x (assoc ctf file-alist) had x)
17969 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17970 (if to-end
17971 (setq file-alist (append (delq x file-alist) (list x)))
17972 (setq file-alist (cons x (delq x file-alist))))
17973 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17974 (org-install-agenda-files-menu)
17975 (message "File %s to %s of agenda file list"
17976 (if had "moved" "added") (if to-end "end" "front"))))
17978 (defun org-remove-file (&optional file)
17979 "Remove current file from the list of files in variable `org-agenda-files'.
17980 These are the files which are being checked for agenda entries.
17981 Optional argument FILE means use this file instead of the current."
17982 (interactive)
17983 (let* ((org-agenda-skip-unavailable-files nil)
17984 (file (or file buffer-file-name
17985 (user-error "Current buffer does not visit a file")))
17986 (true-file (file-truename file))
17987 (afile (abbreviate-file-name file))
17988 (files (delq nil (mapcar
17989 (lambda (x)
17990 (if (equal true-file
17991 (file-truename x))
17992 nil x))
17993 (org-agenda-files t)))))
17994 (if (not (= (length files) (length (org-agenda-files t))))
17995 (progn
17996 (org-store-new-agenda-file-list files)
17997 (org-install-agenda-files-menu)
17998 (message "Removed file: %s" afile))
17999 (message "File was not in list: %s (not removed)" afile))))
18001 (defun org-file-menu-entry (file)
18002 (vector file (list 'find-file file) t))
18004 (defun org-check-agenda-file (file)
18005 "Make sure FILE exists. If not, ask user what to do."
18006 (when (not (file-exists-p file))
18007 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18008 (abbreviate-file-name file))
18009 (let ((r (downcase (read-char-exclusive))))
18010 (cond
18011 ((equal r ?r)
18012 (org-remove-file file)
18013 (throw 'nextfile t))
18014 (t (error "Abort"))))))
18016 (defun org-get-agenda-file-buffer (file)
18017 "Get a buffer visiting FILE. If the buffer needs to be created, add
18018 it to the list of buffers which might be released later."
18019 (let ((buf (org-find-base-buffer-visiting file)))
18020 (if buf
18021 buf ; just return it
18022 ;; Make a new buffer and remember it
18023 (setq buf (find-file-noselect file))
18024 (if buf (push buf org-agenda-new-buffers))
18025 buf)))
18027 (defun org-release-buffers (blist)
18028 "Release all buffers in list, asking the user for confirmation when needed.
18029 When a buffer is unmodified, it is just killed. When modified, it is saved
18030 \(if the user agrees) and then killed."
18031 (let (buf file)
18032 (while (setq buf (pop blist))
18033 (setq file (buffer-file-name buf))
18034 (when (and (buffer-modified-p buf)
18035 file
18036 (y-or-n-p (format "Save file %s? " file)))
18037 (with-current-buffer buf (save-buffer)))
18038 (kill-buffer buf))))
18040 (defun org-agenda-prepare-buffers (files)
18041 "Create buffers for all agenda files, protect archived trees and comments."
18042 (interactive)
18043 (let ((pa '(:org-archived t))
18044 (pc '(:org-comment t))
18045 (pall '(:org-archived t :org-comment t))
18046 (inhibit-read-only t)
18047 (org-inhibit-startup org-agenda-inhibit-startup)
18048 (rea (concat ":" org-archive-tag ":"))
18049 file re)
18050 (setq org-tag-alist-for-agenda nil
18051 org-tag-groups-alist-for-agenda nil)
18052 (save-excursion
18053 (save-restriction
18054 (while (setq file (pop files))
18055 (catch 'nextfile
18056 (if (bufferp file)
18057 (set-buffer file)
18058 (org-check-agenda-file file)
18059 (set-buffer (org-get-agenda-file-buffer file)))
18060 (widen)
18061 (org-set-regexps-and-options-for-tags)
18062 (goto-char (point-min))
18063 (let ((case-fold-search t))
18064 (when (search-forward "#+setupfile" nil t)
18065 ;; Don't set all regexps and options systematically as
18066 ;; this is only run for setting agenda tags from setup
18067 ;; file
18068 (org-set-regexps-and-options)))
18069 (or (memq 'category org-agenda-ignore-drawer-properties)
18070 (org-refresh-category-properties))
18071 (or (memq 'effort org-agenda-ignore-drawer-properties)
18072 (org-refresh-properties org-effort-property 'org-effort))
18073 (or (memq 'appt org-agenda-ignore-drawer-properties)
18074 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18075 (setq org-todo-keywords-for-agenda
18076 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18077 (setq org-done-keywords-for-agenda
18078 (append org-done-keywords-for-agenda org-done-keywords))
18079 (setq org-todo-keyword-alist-for-agenda
18080 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18081 (setq org-drawers-for-agenda
18082 (append org-drawers-for-agenda org-drawers))
18083 (setq org-tag-alist-for-agenda
18084 (org-uniquify
18085 (append org-tag-alist-for-agenda
18086 org-tag-alist
18087 org-tag-persistent-alist)))
18088 (if org-group-tags
18089 (setq org-tag-groups-alist-for-agenda
18090 (org-uniquify-alist
18091 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18092 (org-with-silent-modifications
18093 (save-excursion
18094 (remove-text-properties (point-min) (point-max) pall)
18095 (when org-agenda-skip-archived-trees
18096 (goto-char (point-min))
18097 (while (re-search-forward rea nil t)
18098 (if (org-at-heading-p t)
18099 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18100 (goto-char (point-min))
18101 (setq re (format org-heading-keyword-regexp-format
18102 org-comment-string))
18103 (while (re-search-forward re nil t)
18104 (add-text-properties
18105 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18106 (setq org-todo-keywords-for-agenda
18107 (org-uniquify org-todo-keywords-for-agenda))
18108 (setq org-todo-keyword-alist-for-agenda
18109 (org-uniquify org-todo-keyword-alist-for-agenda))))
18112 ;;;; CDLaTeX minor mode
18114 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18115 "Keymap for the minor `org-cdlatex-mode'.")
18117 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18118 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18119 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18120 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18121 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18123 (defvar org-cdlatex-texmathp-advice-is-done nil
18124 "Flag remembering if we have applied the advice to texmathp already.")
18126 (define-minor-mode org-cdlatex-mode
18127 "Toggle the minor `org-cdlatex-mode'.
18128 This mode supports entering LaTeX environment and math in LaTeX fragments
18129 in Org-mode.
18130 \\{org-cdlatex-mode-map}"
18131 nil " OCDL" nil
18132 (when org-cdlatex-mode
18133 (require 'cdlatex)
18134 (run-hooks 'cdlatex-mode-hook)
18135 (cdlatex-compute-tables))
18136 (unless org-cdlatex-texmathp-advice-is-done
18137 (setq org-cdlatex-texmathp-advice-is-done t)
18138 (defadvice texmathp (around org-math-always-on activate)
18139 "Always return t in org-mode buffers.
18140 This is because we want to insert math symbols without dollars even outside
18141 the LaTeX math segments. If Orgmode thinks that point is actually inside
18142 an embedded LaTeX fragment, let texmathp do its job.
18143 \\[org-cdlatex-mode-map]"
18144 (interactive)
18145 (let (p)
18146 (cond
18147 ((not (derived-mode-p 'org-mode)) ad-do-it)
18148 ((eq this-command 'cdlatex-math-symbol)
18149 (setq ad-return-value t
18150 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18152 (let ((p (org-inside-LaTeX-fragment-p)))
18153 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18154 (setq ad-return-value t
18155 texmathp-why '("Org-mode embedded math" . 0))
18156 (if p ad-do-it)))))))))
18158 (defun turn-on-org-cdlatex ()
18159 "Unconditionally turn on `org-cdlatex-mode'."
18160 (org-cdlatex-mode 1))
18162 (defun org-try-cdlatex-tab ()
18163 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18164 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18165 - inside a LaTeX fragment, or
18166 - after the first word in a line, where an abbreviation expansion could
18167 insert a LaTeX environment."
18168 (when org-cdlatex-mode
18169 (cond
18170 ;; Before any word on the line: No expansion possible.
18171 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18172 ;; Just after first word on the line: Expand it. Make sure it
18173 ;; cannot happen on headlines, though.
18174 ((save-excursion
18175 (skip-chars-backward "a-zA-Z0-9*")
18176 (skip-chars-backward " \t")
18177 (and (bolp) (not (org-at-heading-p))))
18178 (cdlatex-tab) t)
18179 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18181 (defun org-cdlatex-underscore-caret (&optional arg)
18182 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18183 Revert to the normal definition outside of these fragments."
18184 (interactive "P")
18185 (if (org-inside-LaTeX-fragment-p)
18186 (call-interactively 'cdlatex-sub-superscript)
18187 (let (org-cdlatex-mode)
18188 (call-interactively (key-binding (vector last-input-event))))))
18190 (defun org-cdlatex-math-modify (&optional arg)
18191 "Execute `cdlatex-math-modify' in LaTeX fragments.
18192 Revert to the normal definition outside of these fragments."
18193 (interactive "P")
18194 (if (org-inside-LaTeX-fragment-p)
18195 (call-interactively 'cdlatex-math-modify)
18196 (let (org-cdlatex-mode)
18197 (call-interactively (key-binding (vector last-input-event))))))
18201 ;;;; LaTeX fragments
18203 (defvar org-latex-regexps
18204 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18205 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18206 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18207 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18208 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18209 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18210 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18211 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18212 "Regular expressions for matching embedded LaTeX.")
18214 (defun org-inside-LaTeX-fragment-p ()
18215 "Test if point is inside a LaTeX fragment.
18216 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18217 sequence appearing also before point.
18218 Even though the matchers for math are configurable, this function assumes
18219 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18220 delimiters are skipped when they have been removed by customization.
18221 The return value is nil, or a cons cell with the delimiter and the
18222 position of this delimiter.
18224 This function does a reasonably good job, but can locally be fooled by
18225 for example currency specifications. For example it will assume being in
18226 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18227 fragments that are properly closed, but during editing, we have to live
18228 with the uncertainty caused by missing closing delimiters. This function
18229 looks only before point, not after."
18230 (catch 'exit
18231 (let ((pos (point))
18232 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18233 (lim (progn
18234 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18235 (point)))
18236 dd-on str (start 0) m re)
18237 (goto-char pos)
18238 (when dodollar
18239 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18240 re (nth 1 (assoc "$" org-latex-regexps)))
18241 (while (string-match re str start)
18242 (cond
18243 ((= (match-end 0) (length str))
18244 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18245 ((= (match-end 0) (- (length str) 5))
18246 (throw 'exit nil))
18247 (t (setq start (match-end 0))))))
18248 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18249 (goto-char pos)
18250 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18251 (and (match-beginning 2) (throw 'exit nil))
18252 ;; count $$
18253 (while (re-search-backward "\\$\\$" lim t)
18254 (setq dd-on (not dd-on)))
18255 (goto-char pos)
18256 (if dd-on (cons "$$" m))))))
18258 (defun org-inside-latex-macro-p ()
18259 "Is point inside a LaTeX macro or its arguments?"
18260 (save-match-data
18261 (org-in-regexp
18262 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18264 (defvar org-latex-fragment-image-overlays nil
18265 "List of overlays carrying the images of latex fragments.")
18266 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18268 (defun org-remove-latex-fragment-image-overlays ()
18269 "Remove all overlays with LaTeX fragment images in current buffer."
18270 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18271 (setq org-latex-fragment-image-overlays nil))
18273 (defun org-preview-latex-fragment (&optional subtree)
18274 "Preview the LaTeX fragment at point, or all locally or globally.
18275 If the cursor is in a LaTeX fragment, create the image and overlay
18276 it over the source code. If there is no fragment at point, display
18277 all fragments in the current text, from one headline to the next. With
18278 prefix SUBTREE, display all fragments in the current subtree. With a
18279 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18280 the cursor is before the first headline,
18281 display all fragments in the buffer.
18282 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18283 (interactive "P")
18284 (unless buffer-file-name
18285 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18286 (when (display-graphic-p)
18287 (org-remove-latex-fragment-image-overlays)
18288 (save-excursion
18289 (save-restriction
18290 (let (beg end at msg)
18291 (cond
18292 ((or (equal subtree '(16))
18293 (not (save-excursion
18294 (re-search-backward org-outline-regexp-bol nil t))))
18295 (setq beg (point-min) end (point-max)
18296 msg "Creating images for buffer...%s"))
18297 ((equal subtree '(4))
18298 (org-back-to-heading)
18299 (setq beg (point) end (org-end-of-subtree t)
18300 msg "Creating images for subtree...%s"))
18302 (if (setq at (org-inside-LaTeX-fragment-p))
18303 (goto-char (max (point-min) (- (cdr at) 2)))
18304 (org-back-to-heading))
18305 (setq beg (point) end (progn (outline-next-heading) (point))
18306 msg (if at "Creating image...%s"
18307 "Creating images for entry...%s"))))
18308 (message msg "")
18309 (narrow-to-region beg end)
18310 (goto-char beg)
18311 (org-format-latex
18312 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18313 (file-name-nondirectory
18314 buffer-file-name)))
18315 default-directory 'overlays msg at 'forbuffer
18316 org-latex-create-formula-image-program)
18317 (message msg "done. Use `C-c C-c' to remove images."))))))
18319 (defun org-format-latex (prefix &optional dir overlays msg at
18320 forbuffer processing-type)
18321 "Replace LaTeX fragments with links to an image, and produce images.
18322 Some of the options can be changed using the variable
18323 `org-format-latex-options'."
18324 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18325 (let* ((prefixnodir (file-name-nondirectory prefix))
18326 (absprefix (expand-file-name prefix dir))
18327 (todir (file-name-directory absprefix))
18328 (opt org-format-latex-options)
18329 (optnew org-format-latex-options)
18330 (matchers (plist-get opt :matchers))
18331 (re-list org-latex-regexps)
18332 (cnt 0) txt hash link beg end re e checkdir
18333 string
18334 m n block-type block linkfile movefile ov)
18335 ;; Check the different regular expressions
18336 (while (setq e (pop re-list))
18337 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18338 block (if block-type "\n\n" ""))
18339 (when (member m matchers)
18340 (goto-char (point-min))
18341 (while (re-search-forward re nil t)
18342 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18343 (or (not overlays)
18344 (not (eq (get-char-property (match-beginning n)
18345 'org-overlay-type)
18346 'org-latex-overlay))))
18347 (cond
18348 ((eq processing-type 'verbatim))
18349 ((eq processing-type 'mathjax)
18350 ;; Prepare for MathJax processing.
18351 (setq string (match-string n))
18352 (when (member m '("$" "$1"))
18353 (save-excursion
18354 (delete-region (match-beginning n) (match-end n))
18355 (goto-char (match-beginning n))
18356 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18357 ((or (eq processing-type 'dvipng)
18358 (eq processing-type 'imagemagick))
18359 ;; Process to an image.
18360 (setq txt (match-string n)
18361 beg (match-beginning n) end (match-end n)
18362 cnt (1+ cnt))
18363 (let ((face (face-at-point))
18364 (fg (plist-get opt :foreground))
18365 (bg (plist-get opt :background))
18366 ;; Ensure full list is printed.
18367 print-length print-level)
18368 (when forbuffer
18369 ;; Get the colors from the face at point.
18370 (goto-char beg)
18371 (when (eq fg 'auto)
18372 (setq fg (face-attribute face :foreground nil 'default)))
18373 (when (eq bg 'auto)
18374 (setq bg (face-attribute face :background nil 'default)))
18375 (setq optnew (copy-sequence opt))
18376 (plist-put optnew :foreground fg)
18377 (plist-put optnew :background bg))
18378 (setq hash (sha1 (prin1-to-string
18379 (list org-format-latex-header
18380 org-latex-default-packages-alist
18381 org-latex-packages-alist
18382 org-format-latex-options
18383 forbuffer txt fg bg)))
18384 linkfile (format "%s_%s.png" prefix hash)
18385 movefile (format "%s_%s.png" absprefix hash)))
18386 (setq link (concat block "[[file:" linkfile "]]" block))
18387 (if msg (message msg cnt))
18388 (goto-char beg)
18389 (unless checkdir ; Ensure the directory exists.
18390 (setq checkdir t)
18391 (or (file-directory-p todir) (make-directory todir t)))
18392 (unless (file-exists-p movefile)
18393 (org-create-formula-image
18394 txt movefile optnew forbuffer processing-type))
18395 (if overlays
18396 (progn
18397 (mapc (lambda (o)
18398 (if (eq (overlay-get o 'org-overlay-type)
18399 'org-latex-overlay)
18400 (delete-overlay o)))
18401 (overlays-in beg end))
18402 (setq ov (make-overlay beg end))
18403 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18404 (if (featurep 'xemacs)
18405 (progn
18406 (overlay-put ov 'invisible t)
18407 (overlay-put
18408 ov 'end-glyph
18409 (make-glyph (vector 'png :file movefile))))
18410 (overlay-put
18411 ov 'display
18412 (list 'image :type 'png :file movefile :ascent 'center)))
18413 (push ov org-latex-fragment-image-overlays)
18414 (goto-char end))
18415 (delete-region beg end)
18416 (insert (org-add-props link
18417 (list 'org-latex-src
18418 (replace-regexp-in-string
18419 "\"" "" txt)
18420 'org-latex-src-embed-type
18421 (if block-type 'paragraph 'character))))))
18422 ((eq processing-type 'mathml)
18423 ;; Process to MathML
18424 (unless (save-match-data (org-format-latex-mathml-available-p))
18425 (user-error "LaTeX to MathML converter not configured"))
18426 (setq txt (match-string n)
18427 beg (match-beginning n) end (match-end n)
18428 cnt (1+ cnt))
18429 (if msg (message msg cnt))
18430 (goto-char beg)
18431 (delete-region beg end)
18432 (insert (org-format-latex-as-mathml
18433 txt block-type prefix dir)))
18435 (error "Unknown conversion type %s for LaTeX fragments"
18436 processing-type)))))))))
18438 (defun org-create-math-formula (latex-frag &optional mathml-file)
18439 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18440 Use `org-latex-to-mathml-convert-command'. If the conversion is
18441 sucessful, return the portion between \"<math...> </math>\"
18442 elements otherwise return nil. When MATHML-FILE is specified,
18443 write the results in to that file. When invoked as an
18444 interactive command, prompt for LATEX-FRAG, with initial value
18445 set to the current active region and echo the results for user
18446 inspection."
18447 (interactive (list (let ((frag (when (org-region-active-p)
18448 (buffer-substring-no-properties
18449 (region-beginning) (region-end)))))
18450 (read-string "LaTeX Fragment: " frag nil frag))))
18451 (unless latex-frag (error "Invalid LaTeX fragment"))
18452 (let* ((tmp-in-file (file-relative-name
18453 (make-temp-name (expand-file-name "ltxmathml-in"))))
18454 (ignore (write-region latex-frag nil tmp-in-file))
18455 (tmp-out-file (file-relative-name
18456 (make-temp-name (expand-file-name "ltxmathml-out"))))
18457 (cmd (format-spec
18458 org-latex-to-mathml-convert-command
18459 `((?j . ,(shell-quote-argument
18460 (expand-file-name org-latex-to-mathml-jar-file)))
18461 (?I . ,(shell-quote-argument tmp-in-file))
18462 (?o . ,(shell-quote-argument tmp-out-file)))))
18463 mathml shell-command-output)
18464 (when (org-called-interactively-p 'any)
18465 (unless (org-format-latex-mathml-available-p)
18466 (user-error "LaTeX to MathML converter not configured")))
18467 (message "Running %s" cmd)
18468 (setq shell-command-output (shell-command-to-string cmd))
18469 (setq mathml
18470 (when (file-readable-p tmp-out-file)
18471 (with-current-buffer (find-file-noselect tmp-out-file t)
18472 (goto-char (point-min))
18473 (when (re-search-forward
18474 (concat
18475 (regexp-quote
18476 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18477 "\\(.\\|\n\\)*"
18478 (regexp-quote "</math>")) nil t)
18479 (prog1 (match-string 0) (kill-buffer))))))
18480 (cond
18481 (mathml
18482 (setq mathml
18483 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18484 (when mathml-file
18485 (write-region mathml nil mathml-file))
18486 (when (org-called-interactively-p 'any)
18487 (message mathml)))
18488 ((message "LaTeX to MathML conversion failed")
18489 (message shell-command-output)))
18490 (delete-file tmp-in-file)
18491 (when (file-exists-p tmp-out-file)
18492 (delete-file tmp-out-file))
18493 mathml))
18495 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18496 prefix &optional dir)
18497 "Use `org-create-math-formula' but check local cache first."
18498 (let* ((absprefix (expand-file-name prefix dir))
18499 (print-length nil) (print-level nil)
18500 (formula-id (concat
18501 "formula-"
18502 (sha1
18503 (prin1-to-string
18504 (list latex-frag
18505 org-latex-to-mathml-convert-command)))))
18506 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18507 (formula-cache-dir (file-name-directory formula-cache)))
18509 (unless (file-directory-p formula-cache-dir)
18510 (make-directory formula-cache-dir t))
18512 (unless (file-exists-p formula-cache)
18513 (org-create-math-formula latex-frag formula-cache))
18515 (if (file-exists-p formula-cache)
18516 ;; Successful conversion. Return the link to MathML file.
18517 (org-add-props
18518 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18519 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18520 'org-latex-src-embed-type (if latex-frag-type
18521 'paragraph 'character)))
18522 ;; Failed conversion. Return the LaTeX fragment verbatim
18523 latex-frag)))
18525 (defun org-create-formula-image (string tofile options buffer &optional type)
18526 "Create an image from LaTeX source using dvipng or convert.
18527 This function calls either `org-create-formula-image-with-dvipng'
18528 or `org-create-formula-image-with-imagemagick' depending on the
18529 value of `org-latex-create-formula-image-program' or on the value
18530 of the optional TYPE variable.
18532 Note: ultimately these two function should be combined as they
18533 share a good deal of logic."
18534 (org-check-external-command
18535 "latex" "needed to convert LaTeX fragments to images")
18536 (funcall
18537 (case (or type org-latex-create-formula-image-program)
18538 ('dvipng
18539 (org-check-external-command
18540 "dvipng" "needed to convert LaTeX fragments to images")
18541 #'org-create-formula-image-with-dvipng)
18542 ('imagemagick
18543 (org-check-external-command
18544 "convert" "you need to install imagemagick")
18545 #'org-create-formula-image-with-imagemagick)
18546 (t (error
18547 "Invalid value of `org-latex-create-formula-image-program'")))
18548 string tofile options buffer))
18550 (declare-function org-export-get-backend "ox" (name))
18551 (declare-function org-export--get-global-options "ox" (&optional backend))
18552 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18553 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18554 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18555 (defun org-create-formula--latex-header ()
18556 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18557 (let ((info (org-combine-plists (org-export--get-global-options
18558 (org-export-get-backend 'latex))
18559 (org-export--get-inbuffer-options
18560 (org-export-get-backend 'latex)))))
18561 (org-latex-guess-babel-language
18562 (org-latex-guess-inputenc
18563 (org-splice-latex-header
18564 org-format-latex-header
18565 org-latex-default-packages-alist
18566 org-latex-packages-alist t
18567 (plist-get info :latex-header)))
18568 info)))
18570 ;; This function borrows from Ganesh Swami's latex2png.el
18571 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18572 "This calls dvipng."
18573 (require 'ox-latex)
18574 (let* ((tmpdir (if (featurep 'xemacs)
18575 (temp-directory)
18576 temporary-file-directory))
18577 (texfilebase (make-temp-name
18578 (expand-file-name "orgtex" tmpdir)))
18579 (texfile (concat texfilebase ".tex"))
18580 (dvifile (concat texfilebase ".dvi"))
18581 (pngfile (concat texfilebase ".png"))
18582 (fnh (if (featurep 'xemacs)
18583 (font-height (face-font 'default))
18584 (face-attribute 'default :height nil)))
18585 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18586 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18587 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18588 "Black"))
18589 (bg (or (plist-get options (if buffer :background :html-background))
18590 "Transparent")))
18591 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18592 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18593 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18594 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18595 (let ((latex-header (org-create-formula--latex-header)))
18596 (with-temp-file texfile
18597 (insert latex-header)
18598 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18599 (let ((dir default-directory))
18600 (condition-case nil
18601 (progn
18602 (cd tmpdir)
18603 (call-process "latex" nil nil nil texfile))
18604 (error nil))
18605 (cd dir))
18606 (if (not (file-exists-p dvifile))
18607 (progn (message "Failed to create dvi file from %s" texfile) nil)
18608 (condition-case nil
18609 (if (featurep 'xemacs)
18610 (call-process "dvipng" nil nil nil
18611 "-fg" fg "-bg" bg
18612 "-T" "tight"
18613 "-o" pngfile
18614 dvifile)
18615 (call-process "dvipng" nil nil nil
18616 "-fg" fg "-bg" bg
18617 "-D" dpi
18618 ;;"-x" scale "-y" scale
18619 "-T" "tight"
18620 "-o" pngfile
18621 dvifile))
18622 (error nil))
18623 (if (not (file-exists-p pngfile))
18624 (if org-format-latex-signal-error
18625 (error "Failed to create png file from %s" texfile)
18626 (message "Failed to create png file from %s" texfile)
18627 nil)
18628 ;; Use the requested file name and clean up
18629 (copy-file pngfile tofile 'replace)
18630 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18631 (if (file-exists-p (concat texfilebase e))
18632 (delete-file (concat texfilebase e))))
18633 pngfile))))
18635 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18636 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18637 "This calls convert, which is included into imagemagick."
18638 (require 'ox-latex)
18639 (let* ((tmpdir (if (featurep 'xemacs)
18640 (temp-directory)
18641 temporary-file-directory))
18642 (texfilebase (make-temp-name
18643 (expand-file-name "orgtex" tmpdir)))
18644 (texfile (concat texfilebase ".tex"))
18645 (pdffile (concat texfilebase ".pdf"))
18646 (pngfile (concat texfilebase ".png"))
18647 (fnh (if (featurep 'xemacs)
18648 (font-height (face-font 'default))
18649 (face-attribute 'default :height nil)))
18650 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18651 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18652 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18653 "black"))
18654 (bg (or (plist-get options (if buffer :background :html-background))
18655 "white")))
18656 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18657 (setq fg (org-latex-color-format fg)))
18658 (if (eq bg 'default) (setq bg (org-latex-color :background))
18659 (setq bg (org-latex-color-format
18660 (if (string= bg "Transparent") "white" bg))))
18661 (let ((latex-header (org-create-formula--latex-header)))
18662 (with-temp-file texfile
18663 (insert latex-header)
18664 (insert "\n\\begin{document}\n"
18665 "\\definecolor{fg}{rgb}{" fg "}\n"
18666 "\\definecolor{bg}{rgb}{" bg "}\n"
18667 "\n\\pagecolor{bg}\n"
18668 "\n{\\color{fg}\n"
18669 string
18670 "\n}\n"
18671 "\n\\end{document}\n")))
18672 (org-latex-compile texfile t)
18673 (if (not (file-exists-p pdffile))
18674 (progn (message "Failed to create pdf file from %s" texfile) nil)
18675 (condition-case nil
18676 (if (featurep 'xemacs)
18677 (call-process "convert" nil nil nil
18678 "-density" "96"
18679 "-trim"
18680 "-antialias"
18681 pdffile
18682 "-quality" "100"
18683 ;; "-sharpen" "0x1.0"
18684 pngfile)
18685 (call-process "convert" nil nil nil
18686 "-density" dpi
18687 "-trim"
18688 "-antialias"
18689 pdffile
18690 "-quality" "100"
18691 ;; "-sharpen" "0x1.0"
18692 pngfile))
18693 (error nil))
18694 (if (not (file-exists-p pngfile))
18695 (if org-format-latex-signal-error
18696 (error "Failed to create png file from %s" texfile)
18697 (message "Failed to create png file from %s" texfile)
18698 nil)
18699 ;; Use the requested file name and clean up
18700 (copy-file pngfile tofile 'replace)
18701 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18702 (if (file-exists-p (concat texfilebase e))
18703 (delete-file (concat texfilebase e))))
18704 pngfile))))
18706 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18707 "Fill a LaTeX header template TPL.
18708 In the template, the following place holders will be recognized:
18710 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18711 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18712 [PACKAGES] \\usepackage statements for PKG
18713 [NO-PACKAGES] do not include PKG
18714 [EXTRA] the string EXTRA
18715 [NO-EXTRA] do not include EXTRA
18717 For backward compatibility, if both the positive and the negative place
18718 holder is missing, the positive one (without the \"NO-\") will be
18719 assumed to be present at the end of the template.
18720 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18721 EXTRA is a string.
18722 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18723 (let (rpl (end ""))
18724 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18725 (setq rpl (if (or (match-end 1) (not def-pkg))
18726 "" (org-latex-packages-to-string def-pkg snippets-p t))
18727 tpl (replace-match rpl t t tpl))
18728 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18730 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18731 (setq rpl (if (or (match-end 1) (not pkg))
18732 "" (org-latex-packages-to-string pkg snippets-p t))
18733 tpl (replace-match rpl t t tpl))
18734 (if pkg (setq end
18735 (concat end "\n"
18736 (org-latex-packages-to-string pkg snippets-p)))))
18738 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18739 (setq rpl (if (or (match-end 1) (not extra))
18740 "" (concat extra "\n"))
18741 tpl (replace-match rpl t t tpl))
18742 (if (and extra (string-match "\\S-" extra))
18743 (setq end (concat end "\n" extra))))
18745 (if (string-match "\\S-" end)
18746 (concat tpl "\n" end)
18747 tpl)))
18749 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18750 "Turn an alist of packages into a string with the \\usepackage macros."
18751 (setq pkg (mapconcat (lambda(p)
18752 (cond
18753 ((stringp p) p)
18754 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18755 (format "%% Package %s omitted" (cadr p)))
18756 ((equal "" (car p))
18757 (format "\\usepackage{%s}" (cadr p)))
18759 (format "\\usepackage[%s]{%s}"
18760 (car p) (cadr p)))))
18762 "\n"))
18763 (if newline (concat pkg "\n") pkg))
18765 (defun org-dvipng-color (attr)
18766 "Return a RGB color specification for dvipng."
18767 (apply 'format "rgb %s %s %s"
18768 (mapcar 'org-normalize-color
18769 (if (featurep 'xemacs)
18770 (color-rgb-components
18771 (face-property 'default
18772 (cond ((eq attr :foreground) 'foreground)
18773 ((eq attr :background) 'background))))
18774 (color-values (face-attribute 'default attr nil))))))
18776 (defun org-dvipng-color-format (color-name)
18777 "Convert COLOR-NAME to a RGB color value for dvipng."
18778 (apply 'format "rgb %s %s %s"
18779 (mapcar 'org-normalize-color
18780 (color-values color-name))))
18782 (defun org-latex-color (attr)
18783 "Return a RGB color for the LaTeX color package."
18784 (apply 'format "%s,%s,%s"
18785 (mapcar 'org-normalize-color
18786 (if (featurep 'xemacs)
18787 (color-rgb-components
18788 (face-property 'default
18789 (cond ((eq attr :foreground) 'foreground)
18790 ((eq attr :background) 'background))))
18791 (color-values (face-attribute 'default attr nil))))))
18793 (defun org-latex-color-format (color-name)
18794 "Convert COLOR-NAME to a RGB color value."
18795 (apply 'format "%s,%s,%s"
18796 (mapcar 'org-normalize-color
18797 (color-values color-name))))
18799 (defun org-normalize-color (value)
18800 "Return string to be used as color value for an RGB component."
18801 (format "%g" (/ value 65535.0)))
18805 ;; Image display
18807 (defvar org-inline-image-overlays nil)
18808 (make-variable-buffer-local 'org-inline-image-overlays)
18810 (defun org-toggle-inline-images (&optional include-linked)
18811 "Toggle the display of inline images.
18812 INCLUDE-LINKED is passed to `org-display-inline-images'."
18813 (interactive "P")
18814 (if org-inline-image-overlays
18815 (progn
18816 (org-remove-inline-images)
18817 (message "Inline image display turned off"))
18818 (org-display-inline-images include-linked)
18819 (if (and (org-called-interactively-p)
18820 org-inline-image-overlays)
18821 (message "%d images displayed inline"
18822 (length org-inline-image-overlays))
18823 (message "No images to display inline"))))
18825 (defun org-redisplay-inline-images ()
18826 "Refresh the display of inline images."
18827 (interactive)
18828 (if (not org-inline-image-overlays)
18829 (org-toggle-inline-images)
18830 (org-toggle-inline-images)
18831 (org-toggle-inline-images)))
18833 (defun org-display-inline-images (&optional include-linked refresh beg end)
18834 "Display inline images.
18835 Normally only links without a description part are inlined, because this
18836 is how it will work for export. When INCLUDE-LINKED is set, also links
18837 with a description part will be inlined. This can be nice for a quick
18838 look at those images, but it does not reflect what exported files will look
18839 like.
18840 When REFRESH is set, refresh existing images between BEG and END.
18841 This will create new image displays only if necessary.
18842 BEG and END default to the buffer boundaries."
18843 (interactive "P")
18844 (when (display-graphic-p)
18845 (unless refresh
18846 (org-remove-inline-images)
18847 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18848 (save-excursion
18849 (save-restriction
18850 (widen)
18851 (setq beg (or beg (point-min)) end (or end (point-max)))
18852 (goto-char beg)
18853 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18854 (substring (org-image-file-name-regexp) 0 -2)
18855 "\\)\\]" (if include-linked "" "\\]")))
18856 (case-fold-search t)
18857 old file ov img type attrwidth width)
18858 (while (re-search-forward re end t)
18859 (setq old (get-char-property-and-overlay (match-beginning 1)
18860 'org-image-overlay)
18861 file (expand-file-name
18862 (concat (or (match-string 3) "") (match-string 4))))
18863 (when (image-type-available-p 'imagemagick)
18864 (setq attrwidth (if (or (listp org-image-actual-width)
18865 (null org-image-actual-width))
18866 (save-excursion
18867 (save-match-data
18868 (when (re-search-backward
18869 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18870 (save-excursion
18871 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18872 (string-to-number (match-string 1))))))
18873 width (cond ((eq org-image-actual-width t) nil)
18874 ((null org-image-actual-width) attrwidth)
18875 ((numberp org-image-actual-width)
18876 org-image-actual-width)
18877 ((listp org-image-actual-width)
18878 (or attrwidth (car org-image-actual-width))))
18879 type (if width 'imagemagick)))
18880 (when (file-exists-p file)
18881 (if (and (car-safe old) refresh)
18882 (image-refresh (overlay-get (cdr old) 'display))
18883 (setq img (save-match-data (create-image file type nil :width width)))
18884 (when img
18885 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18886 (overlay-put ov 'display img)
18887 (overlay-put ov 'face 'default)
18888 (overlay-put ov 'org-image-overlay t)
18889 (overlay-put ov 'modification-hooks
18890 (list 'org-display-inline-remove-overlay))
18891 (push ov org-inline-image-overlays))))))))))
18893 (define-obsolete-function-alias
18894 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18896 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18897 "Remove inline-display overlay if a corresponding region is modified."
18898 (let ((inhibit-modification-hooks t))
18899 (when (and ov after)
18900 (delete ov org-inline-image-overlays)
18901 (delete-overlay ov))))
18903 (defun org-remove-inline-images ()
18904 "Remove inline display of images."
18905 (interactive)
18906 (mapc 'delete-overlay org-inline-image-overlays)
18907 (setq org-inline-image-overlays nil))
18909 ;;;; Key bindings
18911 ;; Outline functions from `outline-mode-prefix-map'
18912 ;; that can be remapped in Org:
18913 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18914 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18915 (define-key org-mode-map [remap outline-forward-same-level]
18916 'org-forward-heading-same-level)
18917 (define-key org-mode-map [remap outline-backward-same-level]
18918 'org-backward-heading-same-level)
18919 (define-key org-mode-map [remap show-branches]
18920 'org-kill-note-or-show-branches)
18921 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18922 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18923 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18925 ;; Outline functions from `outline-mode-prefix-map' that can not
18926 ;; be remapped in Org:
18928 ;; - the column "key binding" shows whether the Outline function is still
18929 ;; available in Org mode on the same key that it has been bound to in
18930 ;; Outline mode:
18931 ;; - "overridden": key used for a different functionality in Org mode
18932 ;; - else: key still bound to the same Outline function in Org mode
18934 ;; | Outline function | key binding | Org replacement |
18935 ;; |------------------------------------+-------------+-----------------------|
18936 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18937 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18938 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18939 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18940 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18941 ;; | `show-entry' | overridden | no replacement |
18942 ;; | `show-children' | `C-c C-i' | visibility cycling |
18943 ;; | `show-branches' | `C-c C-k' | still same function |
18944 ;; | `show-subtree' | overridden | visibility cycling |
18945 ;; | `show-all' | overridden | no replacement |
18946 ;; | `hide-subtree' | overridden | visibility cycling |
18947 ;; | `hide-body' | overridden | no replacement |
18948 ;; | `hide-entry' | overridden | visibility cycling |
18949 ;; | `hide-leaves' | overridden | no replacement |
18950 ;; | `hide-sublevels' | overridden | no replacement |
18951 ;; | `hide-other' | overridden | no replacement |
18953 ;; Make `C-c C-x' a prefix key
18954 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18956 ;; TAB key with modifiers
18957 (org-defkey org-mode-map "\C-i" 'org-cycle)
18958 (org-defkey org-mode-map [(tab)] 'org-cycle)
18959 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18960 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18961 ;; The following line is necessary under Suse GNU/Linux
18962 (unless (featurep 'xemacs)
18963 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18964 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18965 (define-key org-mode-map [backtab] 'org-shifttab)
18967 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18968 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18969 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18971 ;; Cursor keys with modifiers
18972 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18973 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18974 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18975 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18977 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18978 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18979 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18980 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18982 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18983 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18984 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18985 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18987 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18988 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18989 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18990 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18992 ;; Babel keys
18993 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18994 (mapc (lambda (pair)
18995 (define-key org-babel-map (car pair) (cdr pair)))
18996 org-babel-key-bindings)
18998 ;;; Extra keys for tty access.
18999 ;; We only set them when really needed because otherwise the
19000 ;; menus don't show the simple keys
19002 (when (or org-use-extra-keys
19003 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19004 (not window-system))
19005 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19006 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19007 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19008 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19009 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19010 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19011 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19012 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19013 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19014 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19015 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19016 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19017 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19018 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19019 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19020 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19021 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19022 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19023 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19024 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19025 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19026 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19027 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19028 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19029 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19030 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19031 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19032 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19034 ;; All the other keys
19036 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19037 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19038 (if (boundp 'narrow-map)
19039 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19040 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19041 (if (boundp 'narrow-map)
19042 (org-defkey narrow-map "b" 'org-narrow-to-block)
19043 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19044 (if (boundp 'narrow-map)
19045 (org-defkey narrow-map "e" 'org-narrow-to-element)
19046 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19047 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19048 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19049 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19050 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19051 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19052 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19053 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19054 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19055 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19056 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19057 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19058 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19059 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19060 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19061 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19062 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19063 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19064 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19065 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19066 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19067 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19068 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19069 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19070 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19071 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19072 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19073 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19074 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19075 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19076 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19077 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19078 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19079 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19080 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19081 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19082 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19083 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19084 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19085 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19086 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19087 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19088 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19089 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19090 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19091 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19092 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19093 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19094 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19095 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19096 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19097 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19098 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19099 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19100 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19101 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19102 (org-defkey org-mode-map "\C-c^" 'org-sort)
19103 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19104 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19105 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19106 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19107 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19108 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19109 (org-defkey org-mode-map "\C-m" 'org-return)
19110 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19111 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19112 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19113 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19114 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19115 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19116 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19117 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19118 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19119 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19120 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19121 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19122 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19123 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19124 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19125 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19126 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19127 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19128 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19129 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19130 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19131 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19132 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19134 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19135 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19136 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19138 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19139 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19140 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19141 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19142 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19143 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19144 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19145 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19146 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19147 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19148 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19149 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19150 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19151 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19152 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19153 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19154 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19155 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19156 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19157 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19158 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19159 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19160 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19162 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19163 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19164 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19165 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19166 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19168 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19170 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19172 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19173 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19175 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19178 (when (featurep 'xemacs)
19179 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19182 (defconst org-speed-commands-default
19184 ("Outline Navigation")
19185 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19186 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19187 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19188 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19189 ("F" . org-next-block)
19190 ("B" . org-previous-block)
19191 ("u" . (org-speed-move-safe 'outline-up-heading))
19192 ("j" . org-goto)
19193 ("g" . (org-refile t))
19194 ("Outline Visibility")
19195 ("c" . org-cycle)
19196 ("C" . org-shifttab)
19197 (" " . org-display-outline-path)
19198 ("s" . org-narrow-to-subtree)
19199 ("=" . org-columns)
19200 ("Outline Structure Editing")
19201 ("U" . org-shiftmetaup)
19202 ("D" . org-shiftmetadown)
19203 ("r" . org-metaright)
19204 ("l" . org-metaleft)
19205 ("R" . org-shiftmetaright)
19206 ("L" . org-shiftmetaleft)
19207 ("i" . (progn (forward-char 1) (call-interactively
19208 'org-insert-heading-respect-content)))
19209 ("^" . org-sort)
19210 ("w" . org-refile)
19211 ("a" . org-archive-subtree-default-with-confirmation)
19212 ("@" . org-mark-subtree)
19213 ("#" . org-toggle-comment)
19214 ("Clock Commands")
19215 ("I" . org-clock-in)
19216 ("O" . org-clock-out)
19217 ("Meta Data Editing")
19218 ("t" . org-todo)
19219 ("," . (org-priority))
19220 ("0" . (org-priority ?\ ))
19221 ("1" . (org-priority ?A))
19222 ("2" . (org-priority ?B))
19223 ("3" . (org-priority ?C))
19224 (":" . org-set-tags-command)
19225 ("e" . org-set-effort)
19226 ("E" . org-inc-effort)
19227 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19228 (org-entry-put (point) "APPT_WARNTIME" m)))
19229 ("Agenda Views etc")
19230 ("v" . org-agenda)
19231 ("/" . org-sparse-tree)
19232 ("Misc")
19233 ("o" . org-open-at-point)
19234 ("?" . org-speed-command-help)
19235 ("<" . (org-agenda-set-restriction-lock 'subtree))
19236 (">" . (org-agenda-remove-restriction-lock))
19238 "The default speed commands.")
19240 (defun org-print-speed-command (e)
19241 (if (> (length (car e)) 1)
19242 (progn
19243 (princ "\n")
19244 (princ (car e))
19245 (princ "\n")
19246 (princ (make-string (length (car e)) ?-))
19247 (princ "\n"))
19248 (princ (car e))
19249 (princ " ")
19250 (if (symbolp (cdr e))
19251 (princ (symbol-name (cdr e)))
19252 (prin1 (cdr e)))
19253 (princ "\n")))
19255 (defun org-speed-command-help ()
19256 "Show the available speed commands."
19257 (interactive)
19258 (if (not org-use-speed-commands)
19259 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19260 (with-output-to-temp-buffer "*Help*"
19261 (princ "User-defined Speed commands\n===========================\n")
19262 (mapc 'org-print-speed-command org-speed-commands-user)
19263 (princ "\n")
19264 (princ "Built-in Speed commands\n=======================\n")
19265 (mapc 'org-print-speed-command org-speed-commands-default))
19266 (with-current-buffer "*Help*"
19267 (setq truncate-lines t))))
19269 (defun org-speed-move-safe (cmd)
19270 "Execute CMD, but make sure that the cursor always ends up in a headline.
19271 If not, return to the original position and throw an error."
19272 (interactive)
19273 (let ((pos (point)))
19274 (call-interactively cmd)
19275 (unless (and (bolp) (org-at-heading-p))
19276 (goto-char pos)
19277 (error "Boundary reached while executing %s" cmd))))
19279 (defvar org-self-insert-command-undo-counter 0)
19281 (defvar org-table-auto-blank-field) ; defined in org-table.el
19282 (defvar org-speed-command nil)
19284 (define-obsolete-function-alias
19285 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19287 (defun org-speed-command-activate (keys)
19288 "Hook for activating single-letter speed commands.
19289 `org-speed-commands-default' specifies a minimal command set.
19290 Use `org-speed-commands-user' for further customization."
19291 (when (or (and (bolp) (looking-at org-outline-regexp))
19292 (and (functionp org-use-speed-commands)
19293 (funcall org-use-speed-commands)))
19294 (cdr (assoc keys (append org-speed-commands-user
19295 org-speed-commands-default)))))
19297 (define-obsolete-function-alias
19298 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19300 (defun org-babel-speed-command-activate (keys)
19301 "Hook for activating single-letter code block commands."
19302 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19303 (cdr (assoc keys org-babel-key-bindings))))
19305 (defcustom org-speed-command-hook
19306 '(org-speed-command-default-hook org-babel-speed-command-hook)
19307 "Hook for activating speed commands at strategic locations.
19308 Hook functions are called in sequence until a valid handler is
19309 found.
19311 Each hook takes a single argument, a user-pressed command key
19312 which is also a `self-insert-command' from the global map.
19314 Within the hook, examine the cursor position and the command key
19315 and return nil or a valid handler as appropriate. Handler could
19316 be one of an interactive command, a function, or a form.
19318 Set `org-use-speed-commands' to non-nil value to enable this
19319 hook. The default setting is `org-speed-command-activate'."
19320 :group 'org-structure
19321 :version "24.1"
19322 :type 'hook)
19324 (defun org-self-insert-command (N)
19325 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19326 If the cursor is in a table looking at whitespace, the whitespace is
19327 overwritten, and the table is not marked as requiring realignment."
19328 (interactive "p")
19329 (org-check-before-invisible-edit 'insert)
19330 (cond
19331 ((and org-use-speed-commands
19332 (setq org-speed-command
19333 (run-hook-with-args-until-success
19334 'org-speed-command-hook (this-command-keys))))
19335 (cond
19336 ((commandp org-speed-command)
19337 (setq this-command org-speed-command)
19338 (call-interactively org-speed-command))
19339 ((functionp org-speed-command)
19340 (funcall org-speed-command))
19341 ((and org-speed-command (listp org-speed-command))
19342 (eval org-speed-command))
19343 (t (let (org-use-speed-commands)
19344 (call-interactively 'org-self-insert-command)))))
19345 ((and
19346 (org-table-p)
19347 (progn
19348 ;; check if we blank the field, and if that triggers align
19349 (and (featurep 'org-table) org-table-auto-blank-field
19350 (member last-command
19351 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19352 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19353 ;; got extra space, this field does not determine column width
19354 (let (org-table-may-need-update) (org-table-blank-field))
19355 ;; no extra space, this field may determine column width
19356 (org-table-blank-field)))
19358 (eq N 1)
19359 (looking-at "[^|\n]* |"))
19360 (let (org-table-may-need-update)
19361 (goto-char (1- (match-end 0)))
19362 (backward-delete-char 1)
19363 (goto-char (match-beginning 0))
19364 (self-insert-command N)))
19366 (setq org-table-may-need-update t)
19367 (self-insert-command N)
19368 (org-fix-tags-on-the-fly)
19369 (if org-self-insert-cluster-for-undo
19370 (if (not (eq last-command 'org-self-insert-command))
19371 (setq org-self-insert-command-undo-counter 1)
19372 (if (>= org-self-insert-command-undo-counter 20)
19373 (setq org-self-insert-command-undo-counter 1)
19374 (and (> org-self-insert-command-undo-counter 0)
19375 buffer-undo-list (listp buffer-undo-list)
19376 (not (cadr buffer-undo-list)) ; remove nil entry
19377 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19378 (setq org-self-insert-command-undo-counter
19379 (1+ org-self-insert-command-undo-counter))))))))
19381 (defun org-check-before-invisible-edit (kind)
19382 "Check is editing if kind KIND would be dangerous with invisible text around.
19383 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19384 ;; First, try to get out of here as quickly as possible, to reduce overhead
19385 (if (and org-catch-invisible-edits
19386 (or (not (boundp 'visible-mode)) (not visible-mode))
19387 (or (get-char-property (point) 'invisible)
19388 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19389 ;; OK, we need to take a closer look
19390 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19391 (invisible-before-point (if (bobp) nil (get-char-property
19392 (1- (point)) 'invisible)))
19393 (border-and-ok-direction
19395 ;; Check if we are acting predictably before invisible text
19396 (and invisible-at-point (not invisible-before-point)
19397 (memq kind '(insert delete-backward)))
19398 ;; Check if we are acting predictably after invisible text
19399 ;; This works not well, and I have turned it off. It seems
19400 ;; better to always show and stop after invisible text.
19401 ;; (and (not invisible-at-point) invisible-before-point
19402 ;; (memq kind '(insert delete)))
19404 (when (or (memq invisible-at-point '(outline org-hide-block t))
19405 (memq invisible-before-point '(outline org-hide-block t)))
19406 (if (eq org-catch-invisible-edits 'error)
19407 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19408 (if (and org-custom-properties-overlays
19409 (y-or-n-p "Display invisible properties in this buffer? "))
19410 (org-toggle-custom-properties-visibility)
19411 ;; Make the area visible
19412 (save-excursion
19413 (if invisible-before-point
19414 (goto-char (previous-single-char-property-change
19415 (point) 'invisible)))
19416 (org-cycle))
19417 (cond
19418 ((eq org-catch-invisible-edits 'show)
19419 ;; That's it, we do the edit after showing
19420 (message
19421 "Unfolding invisible region around point before editing")
19422 (sit-for 1))
19423 ((and (eq org-catch-invisible-edits 'smart)
19424 border-and-ok-direction)
19425 (message "Unfolding invisible region around point before editing"))
19427 ;; Don't do the edit, make the user repeat it in full visibility
19428 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19430 (defun org-fix-tags-on-the-fly ()
19431 (when (and (equal (char-after (point-at-bol)) ?*)
19432 (org-at-heading-p))
19433 (org-align-tags-here org-tags-column)))
19435 (defun org-delete-backward-char (N)
19436 "Like `delete-backward-char', insert whitespace at field end in tables.
19437 When deleting backwards, in tables this function will insert whitespace in
19438 front of the next \"|\" separator, to keep the table aligned. The table will
19439 still be marked for re-alignment if the field did fill the entire column,
19440 because, in this case the deletion might narrow the column."
19441 (interactive "p")
19442 (save-match-data
19443 (org-check-before-invisible-edit 'delete-backward)
19444 (if (and (org-table-p)
19445 (eq N 1)
19446 (string-match "|" (buffer-substring (point-at-bol) (point)))
19447 (looking-at ".*?|"))
19448 (let ((pos (point))
19449 (noalign (looking-at "[^|\n\r]* |"))
19450 (c org-table-may-need-update))
19451 (backward-delete-char N)
19452 (if (not overwrite-mode)
19453 (progn
19454 (skip-chars-forward "^|")
19455 (insert " ")
19456 (goto-char (1- pos))))
19457 ;; noalign: if there were two spaces at the end, this field
19458 ;; does not determine the width of the column.
19459 (if noalign (setq org-table-may-need-update c)))
19460 (backward-delete-char N)
19461 (org-fix-tags-on-the-fly))))
19463 (defun org-delete-char (N)
19464 "Like `delete-char', but insert whitespace at field end in tables.
19465 When deleting characters, in tables this function will insert whitespace in
19466 front of the next \"|\" separator, to keep the table aligned. The table will
19467 still be marked for re-alignment if the field did fill the entire column,
19468 because, in this case the deletion might narrow the column."
19469 (interactive "p")
19470 (save-match-data
19471 (org-check-before-invisible-edit 'delete)
19472 (if (and (org-table-p)
19473 (not (bolp))
19474 (not (= (char-after) ?|))
19475 (eq N 1))
19476 (if (looking-at ".*?|")
19477 (let ((pos (point))
19478 (noalign (looking-at "[^|\n\r]* |"))
19479 (c org-table-may-need-update))
19480 (replace-match
19481 (concat (substring (match-string 0) 1 -1) " |") nil t)
19482 (goto-char pos)
19483 ;; noalign: if there were two spaces at the end, this field
19484 ;; does not determine the width of the column.
19485 (if noalign (setq org-table-may-need-update c)))
19486 (delete-char N))
19487 (delete-char N)
19488 (org-fix-tags-on-the-fly))))
19490 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19491 (put 'org-self-insert-command 'delete-selection t)
19492 (put 'orgtbl-self-insert-command 'delete-selection t)
19493 (put 'org-delete-char 'delete-selection 'supersede)
19494 (put 'org-delete-backward-char 'delete-selection 'supersede)
19495 (put 'org-yank 'delete-selection 'yank)
19497 ;; Make `flyspell-mode' delay after some commands
19498 (put 'org-self-insert-command 'flyspell-delayed t)
19499 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19500 (put 'org-delete-char 'flyspell-delayed t)
19501 (put 'org-delete-backward-char 'flyspell-delayed t)
19503 ;; Make pabbrev-mode expand after org-mode commands
19504 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19505 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19507 ;; How to do this: Measure non-white length of current string
19508 ;; If equal to column width, we should realign.
19510 (defun org-remap (map &rest commands)
19511 "In MAP, remap the functions given in COMMANDS.
19512 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19513 (let (new old)
19514 (while commands
19515 (setq old (pop commands) new (pop commands))
19516 (if (fboundp 'command-remapping)
19517 (org-defkey map (vector 'remap old) new)
19518 (substitute-key-definition old new map global-map)))))
19520 (defun org-transpose-words ()
19521 "Transpose words for Org.
19522 This uses the `org-mode-transpose-word-syntax-table' syntax
19523 table, which interprets characters in `org-emphasis-alist' as
19524 word constituants."
19525 (interactive)
19526 (with-syntax-table org-mode-transpose-word-syntax-table
19527 (call-interactively 'transpose-words)))
19528 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19530 (when (eq org-enable-table-editor 'optimized)
19531 ;; If the user wants maximum table support, we need to hijack
19532 ;; some standard editing functions
19533 (org-remap org-mode-map
19534 'self-insert-command 'org-self-insert-command
19535 'delete-char 'org-delete-char
19536 'delete-backward-char 'org-delete-backward-char)
19537 (org-defkey org-mode-map "|" 'org-force-self-insert))
19539 (defvar org-ctrl-c-ctrl-c-hook nil
19540 "Hook for functions attaching themselves to `C-c C-c'.
19542 This can be used to add additional functionality to the C-c C-c
19543 key which executes context-dependent commands. This hook is run
19544 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19545 run after the last test.
19547 Each function will be called with no arguments. The function
19548 must check if the context is appropriate for it to act. If yes,
19549 it should do its thing and then return a non-nil value. If the
19550 context is wrong, just do nothing and return nil.")
19552 (defvar org-ctrl-c-ctrl-c-final-hook nil
19553 "Hook for functions attaching themselves to `C-c C-c'.
19555 This can be used to add additional functionality to the C-c C-c
19556 key which executes context-dependent commands. This hook is run
19557 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19558 before the first test.
19560 Each function will be called with no arguments. The function
19561 must check if the context is appropriate for it to act. If yes,
19562 it should do its thing and then return a non-nil value. If the
19563 context is wrong, just do nothing and return nil.")
19565 (defvar org-tab-first-hook nil
19566 "Hook for functions to attach themselves to TAB.
19567 See `org-ctrl-c-ctrl-c-hook' for more information.
19568 This hook runs as the first action when TAB is pressed, even before
19569 `org-cycle' messes around with the `outline-regexp' to cater for
19570 inline tasks and plain list item folding.
19571 If any function in this hook returns t, any other actions that
19572 would have been caused by TAB (such as table field motion or visibility
19573 cycling) will not occur.")
19575 (defvar org-tab-after-check-for-table-hook nil
19576 "Hook for functions to attach themselves to TAB.
19577 See `org-ctrl-c-ctrl-c-hook' for more information.
19578 This hook runs after it has been established that the cursor is not in a
19579 table, but before checking if the cursor is in a headline or if global cycling
19580 should be done.
19581 If any function in this hook returns t, not other actions like visibility
19582 cycling will be done.")
19584 (defvar org-tab-after-check-for-cycling-hook nil
19585 "Hook for functions to attach themselves to TAB.
19586 See `org-ctrl-c-ctrl-c-hook' for more information.
19587 This hook runs after it has been established that not table field motion and
19588 not visibility should be done because of current context. This is probably
19589 the place where a package like yasnippets can hook in.")
19591 (defvar org-tab-before-tab-emulation-hook nil
19592 "Hook for functions to attach themselves to TAB.
19593 See `org-ctrl-c-ctrl-c-hook' for more information.
19594 This hook runs after every other options for TAB have been exhausted, but
19595 before indentation and \t insertion takes place.")
19597 (defvar org-metaleft-hook nil
19598 "Hook for functions attaching themselves to `M-left'.
19599 See `org-ctrl-c-ctrl-c-hook' for more information.")
19600 (defvar org-metaright-hook nil
19601 "Hook for functions attaching themselves to `M-right'.
19602 See `org-ctrl-c-ctrl-c-hook' for more information.")
19603 (defvar org-metaup-hook nil
19604 "Hook for functions attaching themselves to `M-up'.
19605 See `org-ctrl-c-ctrl-c-hook' for more information.")
19606 (defvar org-metadown-hook nil
19607 "Hook for functions attaching themselves to `M-down'.
19608 See `org-ctrl-c-ctrl-c-hook' for more information.")
19609 (defvar org-shiftmetaleft-hook nil
19610 "Hook for functions attaching themselves to `M-S-left'.
19611 See `org-ctrl-c-ctrl-c-hook' for more information.")
19612 (defvar org-shiftmetaright-hook nil
19613 "Hook for functions attaching themselves to `M-S-right'.
19614 See `org-ctrl-c-ctrl-c-hook' for more information.")
19615 (defvar org-shiftmetaup-hook nil
19616 "Hook for functions attaching themselves to `M-S-up'.
19617 See `org-ctrl-c-ctrl-c-hook' for more information.")
19618 (defvar org-shiftmetadown-hook nil
19619 "Hook for functions attaching themselves to `M-S-down'.
19620 See `org-ctrl-c-ctrl-c-hook' for more information.")
19621 (defvar org-metareturn-hook nil
19622 "Hook for functions attaching themselves to `M-RET'.
19623 See `org-ctrl-c-ctrl-c-hook' for more information.")
19624 (defvar org-shiftup-hook nil
19625 "Hook for functions attaching themselves to `S-up'.
19626 See `org-ctrl-c-ctrl-c-hook' for more information.")
19627 (defvar org-shiftup-final-hook nil
19628 "Hook for functions attaching themselves to `S-up'.
19629 This one runs after all other options except shift-select have been excluded.
19630 See `org-ctrl-c-ctrl-c-hook' for more information.")
19631 (defvar org-shiftdown-hook nil
19632 "Hook for functions attaching themselves to `S-down'.
19633 See `org-ctrl-c-ctrl-c-hook' for more information.")
19634 (defvar org-shiftdown-final-hook nil
19635 "Hook for functions attaching themselves to `S-down'.
19636 This one runs after all other options except shift-select have been excluded.
19637 See `org-ctrl-c-ctrl-c-hook' for more information.")
19638 (defvar org-shiftleft-hook nil
19639 "Hook for functions attaching themselves to `S-left'.
19640 See `org-ctrl-c-ctrl-c-hook' for more information.")
19641 (defvar org-shiftleft-final-hook nil
19642 "Hook for functions attaching themselves to `S-left'.
19643 This one runs after all other options except shift-select have been excluded.
19644 See `org-ctrl-c-ctrl-c-hook' for more information.")
19645 (defvar org-shiftright-hook nil
19646 "Hook for functions attaching themselves to `S-right'.
19647 See `org-ctrl-c-ctrl-c-hook' for more information.")
19648 (defvar org-shiftright-final-hook nil
19649 "Hook for functions attaching themselves to `S-right'.
19650 This one runs after all other options except shift-select have been excluded.
19651 See `org-ctrl-c-ctrl-c-hook' for more information.")
19653 (defun org-modifier-cursor-error ()
19654 "Throw an error, a modified cursor command was applied in wrong context."
19655 (user-error "This command is active in special context like tables, headlines or items"))
19657 (defun org-shiftselect-error ()
19658 "Throw an error because Shift-Cursor command was applied in wrong context."
19659 (if (and (boundp 'shift-select-mode) shift-select-mode)
19660 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19661 (user-error "This command works only in special context like headlines or timestamps")))
19663 (defun org-call-for-shift-select (cmd)
19664 (let ((this-command-keys-shift-translated t))
19665 (call-interactively cmd)))
19667 (defun org-shifttab (&optional arg)
19668 "Global visibility cycling or move to previous table field.
19669 Call `org-table-previous-field' within a table.
19670 When ARG is nil, cycle globally through visibility states.
19671 When ARG is a numeric prefix, show contents of this level."
19672 (interactive "P")
19673 (cond
19674 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19675 ((integerp arg)
19676 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19677 (message "Content view to level: %d" arg)
19678 (org-content (prefix-numeric-value arg2))
19679 (org-cycle-show-empty-lines t)
19680 (setq org-cycle-global-status 'overview)))
19681 (t (call-interactively 'org-global-cycle))))
19683 (defun org-shiftmetaleft ()
19684 "Promote subtree or delete table column.
19685 Calls `org-promote-subtree', `org-outdent-item-tree', or
19686 `org-table-delete-column', depending on context. See the
19687 individual commands for more information."
19688 (interactive)
19689 (cond
19690 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19691 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19692 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19693 ((if (not (org-region-active-p)) (org-at-item-p)
19694 (save-excursion (goto-char (region-beginning))
19695 (org-at-item-p)))
19696 (call-interactively 'org-outdent-item-tree))
19697 (t (org-modifier-cursor-error))))
19699 (defun org-shiftmetaright ()
19700 "Demote subtree or insert table column.
19701 Calls `org-demote-subtree', `org-indent-item-tree', or
19702 `org-table-insert-column', depending on context. See the
19703 individual commands for more information."
19704 (interactive)
19705 (cond
19706 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19707 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19708 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19709 ((if (not (org-region-active-p)) (org-at-item-p)
19710 (save-excursion (goto-char (region-beginning))
19711 (org-at-item-p)))
19712 (call-interactively 'org-indent-item-tree))
19713 (t (org-modifier-cursor-error))))
19715 (defun org-shiftmetaup (&optional arg)
19716 "Move subtree up or kill table row.
19717 Calls `org-move-subtree-up' or `org-table-kill-row' or
19718 `org-move-item-up' or `org-timestamp-up', depending on context.
19719 See the individual commands for more information."
19720 (interactive "P")
19721 (cond
19722 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19723 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19724 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19725 ((org-at-item-p) (call-interactively 'org-move-item-up))
19726 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19727 (call-interactively 'org-timestamp-up)))
19728 (t (call-interactively 'org-drag-line-backward))))
19730 (defun org-shiftmetadown (&optional arg)
19731 "Move subtree down or insert table row.
19732 Calls `org-move-subtree-down' or `org-table-insert-row' or
19733 `org-move-item-down' or `org-timestamp-up', depending on context.
19734 See the individual commands for more information."
19735 (interactive "P")
19736 (cond
19737 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19738 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19739 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19740 ((org-at-item-p) (call-interactively 'org-move-item-down))
19741 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19742 (call-interactively 'org-timestamp-down)))
19743 (t (call-interactively 'org-drag-line-forward))))
19745 (defsubst org-hidden-tree-error ()
19746 (user-error
19747 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19749 (defun org-metaleft (&optional arg)
19750 "Promote heading or move table column to left.
19751 Calls `org-do-promote' or `org-table-move-column', depending on context.
19752 With no specific context, calls the Emacs default `backward-word'.
19753 See the individual commands for more information."
19754 (interactive "P")
19755 (cond
19756 ((run-hook-with-args-until-success 'org-metaleft-hook))
19757 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19758 ((org-with-limited-levels
19759 (or (org-at-heading-p)
19760 (and (org-region-active-p)
19761 (save-excursion
19762 (goto-char (region-beginning))
19763 (org-at-heading-p)))))
19764 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19765 (call-interactively 'org-do-promote))
19766 ;; At an inline task.
19767 ((org-at-heading-p)
19768 (call-interactively 'org-inlinetask-promote))
19769 ((or (org-at-item-p)
19770 (and (org-region-active-p)
19771 (save-excursion
19772 (goto-char (region-beginning))
19773 (org-at-item-p))))
19774 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19775 (call-interactively 'org-outdent-item))
19776 (t (call-interactively 'backward-word))))
19778 (defun org-metaright (&optional arg)
19779 "Demote a subtree, a list item or move table column to right.
19780 In front of a drawer or a block keyword, indent it correctly.
19781 With no specific context, calls the Emacs default `forward-word'.
19782 See the individual commands for more information."
19783 (interactive "P")
19784 (cond
19785 ((run-hook-with-args-until-success 'org-metaright-hook))
19786 ((org-at-table-p) (call-interactively 'org-table-move-column))
19787 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19788 ((org-at-block-p) (call-interactively 'org-indent-block))
19789 ((org-with-limited-levels
19790 (or (org-at-heading-p)
19791 (and (org-region-active-p)
19792 (save-excursion
19793 (goto-char (region-beginning))
19794 (org-at-heading-p)))))
19795 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19796 (call-interactively 'org-do-demote))
19797 ;; At an inline task.
19798 ((org-at-heading-p)
19799 (call-interactively 'org-inlinetask-demote))
19800 ((or (org-at-item-p)
19801 (and (org-region-active-p)
19802 (save-excursion
19803 (goto-char (region-beginning))
19804 (org-at-item-p))))
19805 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19806 (call-interactively 'org-indent-item))
19807 (t (call-interactively 'forward-word))))
19809 (defun org-check-for-hidden (what)
19810 "Check if there are hidden headlines/items in the current visual line.
19811 WHAT can be either `headlines' or `items'. If the current line is
19812 an outline or item heading and it has a folded subtree below it,
19813 this function returns t, nil otherwise."
19814 (let ((re (cond
19815 ((eq what 'headlines) org-outline-regexp-bol)
19816 ((eq what 'items) (org-item-beginning-re))
19817 (t (error "This should not happen"))))
19818 beg end)
19819 (save-excursion
19820 (catch 'exit
19821 (unless (org-region-active-p)
19822 (setq beg (point-at-bol))
19823 (beginning-of-line 2)
19824 (while (and (not (eobp)) ;; this is like `next-line'
19825 (get-char-property (1- (point)) 'invisible))
19826 (beginning-of-line 2))
19827 (setq end (point))
19828 (goto-char beg)
19829 (goto-char (point-at-eol))
19830 (setq end (max end (point)))
19831 (while (re-search-forward re end t)
19832 (if (get-char-property (match-beginning 0) 'invisible)
19833 (throw 'exit t))))
19834 nil))))
19836 (defun org-metaup (&optional arg)
19837 "Move subtree up or move table row up.
19838 Calls `org-move-subtree-up' or `org-table-move-row' or
19839 `org-move-item-up', depending on context. See the individual commands
19840 for more information."
19841 (interactive "P")
19842 (cond
19843 ((run-hook-with-args-until-success 'org-metaup-hook))
19844 ((org-region-active-p)
19845 (let* ((a (min (region-beginning) (region-end)))
19846 (b (1- (max (region-beginning) (region-end))))
19847 (c (save-excursion (goto-char a)
19848 (move-beginning-of-line 0)))
19849 (d (save-excursion (goto-char a)
19850 (move-end-of-line 0) (point))))
19851 (transpose-regions a b c d)
19852 (goto-char c)))
19853 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19854 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19855 ((org-at-item-p) (call-interactively 'org-move-item-up))
19856 (t (org-drag-element-backward))))
19858 (defun org-metadown (&optional arg)
19859 "Move subtree down or move table row down.
19860 Calls `org-move-subtree-down' or `org-table-move-row' or
19861 `org-move-item-down', depending on context. See the individual
19862 commands for more information."
19863 (interactive "P")
19864 (cond
19865 ((run-hook-with-args-until-success 'org-metadown-hook))
19866 ((org-region-active-p)
19867 (let* ((a (min (region-beginning) (region-end)))
19868 (b (max (region-beginning) (region-end)))
19869 (c (save-excursion (goto-char b)
19870 (move-beginning-of-line 1)))
19871 (d (save-excursion (goto-char b)
19872 (move-end-of-line 1) (1+ (point)))))
19873 (transpose-regions a b c d)
19874 (goto-char d)))
19875 ((org-at-table-p) (call-interactively 'org-table-move-row))
19876 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19877 ((org-at-item-p) (call-interactively 'org-move-item-down))
19878 (t (org-drag-element-forward))))
19880 (defun org-shiftup (&optional arg)
19881 "Increase item in timestamp or increase priority of current headline.
19882 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19883 depending on context. See the individual commands for more information."
19884 (interactive "P")
19885 (cond
19886 ((run-hook-with-args-until-success 'org-shiftup-hook))
19887 ((and org-support-shift-select (org-region-active-p))
19888 (org-call-for-shift-select 'previous-line))
19889 ((org-at-timestamp-p t)
19890 (call-interactively (if org-edit-timestamp-down-means-later
19891 'org-timestamp-down 'org-timestamp-up)))
19892 ((and (not (eq org-support-shift-select 'always))
19893 org-enable-priority-commands
19894 (org-at-heading-p))
19895 (call-interactively 'org-priority-up))
19896 ((and (not org-support-shift-select) (org-at-item-p))
19897 (call-interactively 'org-previous-item))
19898 ((org-clocktable-try-shift 'up arg))
19899 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19900 (org-support-shift-select
19901 (org-call-for-shift-select 'previous-line))
19902 (t (org-shiftselect-error))))
19904 (defun org-shiftdown (&optional arg)
19905 "Decrease item in timestamp or decrease priority of current headline.
19906 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19907 depending on context. See the individual commands for more information."
19908 (interactive "P")
19909 (cond
19910 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19911 ((and org-support-shift-select (org-region-active-p))
19912 (org-call-for-shift-select 'next-line))
19913 ((org-at-timestamp-p t)
19914 (call-interactively (if org-edit-timestamp-down-means-later
19915 'org-timestamp-up 'org-timestamp-down)))
19916 ((and (not (eq org-support-shift-select 'always))
19917 org-enable-priority-commands
19918 (org-at-heading-p))
19919 (call-interactively 'org-priority-down))
19920 ((and (not org-support-shift-select) (org-at-item-p))
19921 (call-interactively 'org-next-item))
19922 ((org-clocktable-try-shift 'down arg))
19923 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19924 (org-support-shift-select
19925 (org-call-for-shift-select 'next-line))
19926 (t (org-shiftselect-error))))
19928 (defun org-shiftright (&optional arg)
19929 "Cycle the thing at point or in the current line, depending on context.
19930 Depending on context, this does one of the following:
19932 - switch a timestamp at point one day into the future
19933 - on a headline, switch to the next TODO keyword.
19934 - on an item, switch entire list to the next bullet type
19935 - on a property line, switch to the next allowed value
19936 - on a clocktable definition line, move time block into the future"
19937 (interactive "P")
19938 (cond
19939 ((run-hook-with-args-until-success 'org-shiftright-hook))
19940 ((and org-support-shift-select (org-region-active-p))
19941 (org-call-for-shift-select 'forward-char))
19942 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19943 ((and (not (eq org-support-shift-select 'always))
19944 (org-at-heading-p))
19945 (let ((org-inhibit-logging
19946 (not org-treat-S-cursor-todo-selection-as-state-change))
19947 (org-inhibit-blocking
19948 (not org-treat-S-cursor-todo-selection-as-state-change)))
19949 (org-call-with-arg 'org-todo 'right)))
19950 ((or (and org-support-shift-select
19951 (not (eq org-support-shift-select 'always))
19952 (org-at-item-bullet-p))
19953 (and (not org-support-shift-select) (org-at-item-p)))
19954 (org-call-with-arg 'org-cycle-list-bullet nil))
19955 ((and (not (eq org-support-shift-select 'always))
19956 (org-at-property-p))
19957 (call-interactively 'org-property-next-allowed-value))
19958 ((org-clocktable-try-shift 'right arg))
19959 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19960 (org-support-shift-select
19961 (org-call-for-shift-select 'forward-char))
19962 (t (org-shiftselect-error))))
19964 (defun org-shiftleft (&optional arg)
19965 "Cycle the thing at point or in the current line, depending on context.
19966 Depending on context, this does one of the following:
19968 - switch a timestamp at point one day into the past
19969 - on a headline, switch to the previous TODO keyword.
19970 - on an item, switch entire list to the previous bullet type
19971 - on a property line, switch to the previous allowed value
19972 - on a clocktable definition line, move time block into the past"
19973 (interactive "P")
19974 (cond
19975 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19976 ((and org-support-shift-select (org-region-active-p))
19977 (org-call-for-shift-select 'backward-char))
19978 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19979 ((and (not (eq org-support-shift-select 'always))
19980 (org-at-heading-p))
19981 (let ((org-inhibit-logging
19982 (not org-treat-S-cursor-todo-selection-as-state-change))
19983 (org-inhibit-blocking
19984 (not org-treat-S-cursor-todo-selection-as-state-change)))
19985 (org-call-with-arg 'org-todo 'left)))
19986 ((or (and org-support-shift-select
19987 (not (eq org-support-shift-select 'always))
19988 (org-at-item-bullet-p))
19989 (and (not org-support-shift-select) (org-at-item-p)))
19990 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19991 ((and (not (eq org-support-shift-select 'always))
19992 (org-at-property-p))
19993 (call-interactively 'org-property-previous-allowed-value))
19994 ((org-clocktable-try-shift 'left arg))
19995 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19996 (org-support-shift-select
19997 (org-call-for-shift-select 'backward-char))
19998 (t (org-shiftselect-error))))
20000 (defun org-shiftcontrolright ()
20001 "Switch to next TODO set."
20002 (interactive)
20003 (cond
20004 ((and org-support-shift-select (org-region-active-p))
20005 (org-call-for-shift-select 'forward-word))
20006 ((and (not (eq org-support-shift-select 'always))
20007 (org-at-heading-p))
20008 (org-call-with-arg 'org-todo 'nextset))
20009 (org-support-shift-select
20010 (org-call-for-shift-select 'forward-word))
20011 (t (org-shiftselect-error))))
20013 (defun org-shiftcontrolleft ()
20014 "Switch to previous TODO set."
20015 (interactive)
20016 (cond
20017 ((and org-support-shift-select (org-region-active-p))
20018 (org-call-for-shift-select 'backward-word))
20019 ((and (not (eq org-support-shift-select 'always))
20020 (org-at-heading-p))
20021 (org-call-with-arg 'org-todo 'previousset))
20022 (org-support-shift-select
20023 (org-call-for-shift-select 'backward-word))
20024 (t (org-shiftselect-error))))
20026 (defun org-shiftcontrolup (&optional n)
20027 "Change timestamps synchronously up in CLOCK log lines.
20028 Optional argument N tells to change by that many units."
20029 (interactive "P")
20030 (cond ((and (not org-support-shift-select)
20031 (org-at-clock-log-p)
20032 (org-at-timestamp-p t))
20033 (org-clock-timestamps-up n))
20034 (t (org-shiftselect-error))))
20036 (defun org-shiftcontroldown (&optional n)
20037 "Change timestamps synchronously down in CLOCK log lines.
20038 Optional argument N tells to change by that many units."
20039 (interactive "P")
20040 (cond ((and (not org-support-shift-select)
20041 (org-at-clock-log-p)
20042 (org-at-timestamp-p t))
20043 (org-clock-timestamps-down n))
20044 (t (org-shiftselect-error))))
20046 (defun org-ctrl-c-ret ()
20047 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20048 (interactive)
20049 (cond
20050 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20051 (t (call-interactively 'org-insert-heading))))
20053 (defun org-find-visible ()
20054 (let ((s (point)))
20055 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20056 (get-char-property s 'invisible)))
20058 (defun org-find-invisible ()
20059 (let ((s (point)))
20060 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20061 (not (get-char-property s 'invisible))))
20064 (defun org-copy-visible (beg end)
20065 "Copy the visible parts of the region."
20066 (interactive "r")
20067 (let (snippets s)
20068 (save-excursion
20069 (save-restriction
20070 (narrow-to-region beg end)
20071 (setq s (goto-char (point-min)))
20072 (while (not (= (point) (point-max)))
20073 (goto-char (org-find-invisible))
20074 (push (buffer-substring s (point)) snippets)
20075 (setq s (goto-char (org-find-visible))))))
20076 (kill-new (apply 'concat (nreverse snippets)))))
20078 (defun org-copy-special ()
20079 "Copy region in table or copy current subtree.
20080 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20081 See the individual commands for more information."
20082 (interactive)
20083 (call-interactively
20084 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20086 (defun org-cut-special ()
20087 "Cut region in table or cut current subtree.
20088 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20089 See the individual commands for more information."
20090 (interactive)
20091 (call-interactively
20092 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20094 (defun org-paste-special (arg)
20095 "Paste rectangular region into table, or past subtree relative to level.
20096 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20097 See the individual commands for more information."
20098 (interactive "P")
20099 (if (org-at-table-p)
20100 (org-table-paste-rectangle)
20101 (org-paste-subtree arg)))
20103 (defsubst org-in-fixed-width-region-p ()
20104 "Is point in a fixed-width region?"
20105 (save-match-data
20106 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20108 (defun org-edit-special (&optional arg)
20109 "Call a special editor for the element at point.
20110 When at a table, call the formula editor with `org-table-edit-formulas'.
20111 When in a source code block, call `org-edit-src-code'.
20112 When in a fixed-width region, call `org-edit-fixed-width-region'.
20113 When at an #+INCLUDE keyword, visit the included file.
20114 On a link, call `ffap' to visit the link at point.
20115 Otherwise, return a user error."
20116 (interactive "P")
20117 (let ((element (org-element-at-point)))
20118 (assert (not buffer-read-only) nil
20119 "Buffer is read-only: %s" (buffer-name))
20120 (case (org-element-type element)
20121 (src-block
20122 (if (not arg) (org-edit-src-code)
20123 (let* ((info (org-babel-get-src-block-info))
20124 (lang (nth 0 info))
20125 (params (nth 2 info))
20126 (session (cdr (assq :session params))))
20127 (if (not session) (org-edit-src-code)
20128 ;; At a src-block with a session and function called with
20129 ;; an ARG: switch to the buffer related to the inferior
20130 ;; process.
20131 (switch-to-buffer
20132 (funcall (intern (concat "org-babel-prep-session:" lang))
20133 session params))))))
20134 (keyword
20135 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20136 (find-file
20137 (org-remove-double-quotes
20138 (car (org-split-string (org-element-property :value element)))))
20139 (user-error "No special environment to edit here")))
20140 (table
20141 (if (eq (org-element-property :type element) 'table.el)
20142 (org-edit-src-code)
20143 (call-interactively 'org-table-edit-formulas)))
20144 ;; Only Org tables contain `table-row' type elements.
20145 (table-row (call-interactively 'org-table-edit-formulas))
20146 ((example-block export-block) (org-edit-src-code))
20147 (fixed-width (org-edit-fixed-width-region))
20148 (otherwise
20149 ;; No notable element at point. Though, we may be at a link,
20150 ;; which is an object. Thus, scan deeper.
20151 (if (eq (org-element-type (org-element-context element)) 'link)
20152 (call-interactively 'ffap)
20153 (user-error "No special environment to edit here"))))))
20155 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20156 (defun org-ctrl-c-ctrl-c (&optional arg)
20157 "Set tags in headline, or update according to changed information at point.
20159 This command does many different things, depending on context:
20161 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20162 this is what we do.
20164 - If the cursor is on a statistics cookie, update it.
20166 - If the cursor is in a headline, prompt for tags and insert them
20167 into the current line, aligned to `org-tags-column'. When called
20168 with prefix arg, realign all tags in the current buffer.
20170 - If the cursor is in one of the special #+KEYWORD lines, this
20171 triggers scanning the buffer for these lines and updating the
20172 information.
20174 - If the cursor is inside a table, realign the table. This command
20175 works even if the automatic table editor has been turned off.
20177 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20178 the entire table.
20180 - If the cursor is at a footnote reference or definition, jump to
20181 the corresponding definition or references, respectively.
20183 - If the cursor is a the beginning of a dynamic block, update it.
20185 - If the current buffer is a capture buffer, close note and file it.
20187 - If the cursor is on a <<<target>>>, update radio targets and
20188 corresponding links in this buffer.
20190 - If the cursor is on a numbered item in a plain list, renumber the
20191 ordered list.
20193 - If the cursor is on a checkbox, toggle it.
20195 - If the cursor is on a code block, evaluate it. The variable
20196 `org-confirm-babel-evaluate' can be used to control prompting
20197 before code block evaluation, by default every code block
20198 evaluation requires confirmation. Code block evaluation can be
20199 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20200 (interactive "P")
20201 (cond
20202 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20203 org-occur-highlights
20204 org-latex-fragment-image-overlays)
20205 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20206 (org-remove-occur-highlights)
20207 (org-remove-latex-fragment-image-overlays)
20208 (message "Temporary highlights/overlays removed from current buffer"))
20209 ((and (local-variable-p 'org-finish-function (current-buffer))
20210 (fboundp org-finish-function))
20211 (funcall org-finish-function))
20212 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20214 (let* ((context (org-element-context)) (type (org-element-type context)))
20215 ;; Test if point is within a blank line.
20216 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20217 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20218 (user-error "C-c C-c can do nothing useful at this location"))
20219 ;; For convenience: at the first line of a paragraph on the
20220 ;; same line as an item, apply function on that item instead.
20221 (when (eq type 'paragraph)
20222 (let ((parent (org-element-property :parent context)))
20223 (when (and (eq (org-element-type parent) 'item)
20224 (= (point-at-bol) (org-element-property :begin parent)))
20225 (setq context parent type 'item))))
20226 ;; When heading text is a link, treat the heading, not the link,
20227 ;; as the current element
20228 (when (eq type 'link)
20229 (let ((parent (org-element-property :parent context)))
20230 (when (and (eq (org-element-type parent) 'headline))
20231 (setq context parent type 'headline))))
20232 ;; Act according to type of element or object at point.
20233 (case type
20234 (clock (org-clock-update-time-maybe))
20235 (dynamic-block
20236 (save-excursion
20237 (goto-char (org-element-property :post-affiliated context))
20238 (org-update-dblock)))
20239 (footnote-definition
20240 (goto-char (org-element-property :post-affiliated context))
20241 (call-interactively 'org-footnote-action))
20242 (footnote-reference (call-interactively 'org-footnote-action))
20243 ((headline inlinetask)
20244 (save-excursion (goto-char (org-element-property :begin context))
20245 (call-interactively 'org-set-tags)))
20246 (item
20247 ;; At an item: a double C-u set checkbox to "[-]"
20248 ;; unconditionally, whereas a single one will toggle its
20249 ;; presence. Without an universal argument, if the item
20250 ;; has a checkbox, toggle it. Otherwise repair the list.
20251 (let* ((box (org-element-property :checkbox context))
20252 (struct (org-element-property :structure context))
20253 (old-struct (copy-tree struct))
20254 (parents (org-list-parents-alist struct))
20255 (prevs (org-list-prevs-alist struct))
20256 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20257 (org-list-set-checkbox
20258 (org-element-property :begin context) struct
20259 (cond ((equal arg '(16)) "[-]")
20260 ((and (not box) (equal arg '(4))) "[ ]")
20261 ((or (not box) (equal arg '(4))) nil)
20262 ((eq box 'on) "[ ]")
20263 (t "[X]")))
20264 ;; Mimic `org-list-write-struct' but with grabbing
20265 ;; a return value from `org-list-struct-fix-box'.
20266 (org-list-struct-fix-ind struct parents 2)
20267 (org-list-struct-fix-item-end struct)
20268 (org-list-struct-fix-bul struct prevs)
20269 (org-list-struct-fix-ind struct parents)
20270 (let ((block-item
20271 (org-list-struct-fix-box struct parents prevs orderedp)))
20272 (if (and box (equal struct old-struct))
20273 (if (equal arg '(16))
20274 (message "Checkboxes already reset")
20275 (user-error "Cannot toggle this checkbox: %s"
20276 (if (eq box 'on)
20277 "all subitems checked"
20278 "unchecked subitems")))
20279 (org-list-struct-apply-struct struct old-struct)
20280 (org-update-checkbox-count-maybe))
20281 (when block-item
20282 (message "Checkboxes were removed due to empty box at line %d"
20283 (org-current-line block-item))))))
20284 (keyword
20285 (let ((org-inhibit-startup-visibility-stuff t)
20286 (org-startup-align-all-tables nil))
20287 (when (boundp 'org-table-coordinate-overlays)
20288 (mapc 'delete-overlay org-table-coordinate-overlays)
20289 (setq org-table-coordinate-overlays nil))
20290 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20291 (message "Local setup has been refreshed"))
20292 (plain-list
20293 ;; At a plain list, with a double C-u argument, set
20294 ;; checkboxes of each item to "[-]", whereas a single one
20295 ;; will toggle their presence according to the state of the
20296 ;; first item in the list. Without an argument, repair the
20297 ;; list.
20298 (let* ((begin (org-element-property :contents-begin context))
20299 (beginm (move-marker (make-marker) begin))
20300 (struct (org-element-property :structure context))
20301 (old-struct (copy-tree struct))
20302 (first-box (save-excursion
20303 (goto-char begin)
20304 (looking-at org-list-full-item-re)
20305 (match-string-no-properties 3)))
20306 (new-box (cond ((equal arg '(16)) "[-]")
20307 ((equal arg '(4)) (unless first-box "[ ]"))
20308 ((equal first-box "[X]") "[ ]")
20309 (t "[X]"))))
20310 (cond
20311 (arg
20312 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20313 (org-list-get-all-items
20314 begin struct (org-list-prevs-alist struct))))
20315 ((and first-box (eq (point) begin))
20316 ;; For convenience, when point is at bol on the first
20317 ;; item of the list and no argument is provided, simply
20318 ;; toggle checkbox of that item, if any.
20319 (org-list-set-checkbox begin struct new-box)))
20320 (org-list-write-struct
20321 struct (org-list-parents-alist struct) old-struct)
20322 (org-update-checkbox-count-maybe)
20323 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20324 ((property-drawer node-property)
20325 (call-interactively 'org-property-action))
20326 ((radio-target target)
20327 (call-interactively 'org-update-radio-target-regexp))
20328 (statistics-cookie
20329 (call-interactively 'org-update-statistics-cookies))
20330 ((table table-cell table-row)
20331 ;; At a table, recalculate every field and align it. Also
20332 ;; send the table if necessary. If the table has
20333 ;; a `table.el' type, just give up. At a table row or
20334 ;; cell, maybe recalculate line but always align table.
20335 (if (eq (org-element-property :type context) 'table.el)
20336 (message "Use C-c ' to edit table.el tables")
20337 (let ((org-enable-table-editor t))
20338 (if (or (eq type 'table)
20339 ;; Check if point is at a TBLFM line.
20340 (and (eq type 'table-row)
20341 (= (point) (org-element-property :end context))))
20342 (save-excursion
20343 (if (org-at-TBLFM-p)
20344 (progn (require 'org-table)
20345 (org-table-calc-current-TBLFM))
20346 (goto-char (org-element-property :contents-begin context))
20347 (org-call-with-arg 'org-table-recalculate (or arg t))
20348 (orgtbl-send-table 'maybe)))
20349 (org-table-maybe-eval-formula)
20350 (cond (arg (call-interactively 'org-table-recalculate))
20351 ((org-table-maybe-recalculate-line))
20352 (t (org-table-align)))))))
20353 (timestamp (org-timestamp-change 0 'day))
20354 (otherwise
20355 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20356 (user-error
20357 "C-c C-c can do nothing useful at this location")))))))))
20359 (defun org-mode-restart ()
20360 "Restart Org-mode, to scan again for special lines.
20361 Also updates the keyword regular expressions."
20362 (interactive)
20363 (org-mode)
20364 (message "Org-mode restarted"))
20366 (defun org-kill-note-or-show-branches ()
20367 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20368 (interactive)
20369 (if (not org-finish-function)
20370 (progn
20371 (hide-subtree)
20372 (call-interactively 'show-branches))
20373 (let ((org-note-abort t))
20374 (funcall org-finish-function))))
20376 (defun org-open-line (n)
20377 "Insert a new row in tables, call `open-line' elsewhere.
20378 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20379 (interactive "*p")
20380 (cond
20381 ((not org-special-ctrl-o)
20382 (open-line n))
20383 ((org-at-table-p)
20384 (org-table-insert-row))
20386 (open-line n))))
20388 (defun org-return (&optional indent)
20389 "Goto next table row or insert a newline.
20390 Calls `org-table-next-row' or `newline', depending on context.
20391 See the individual commands for more information."
20392 (interactive)
20393 (let (org-ts-what)
20394 (cond
20395 ((or (bobp) (org-in-src-block-p))
20396 (if indent (newline-and-indent) (newline)))
20397 ((org-at-table-p)
20398 (org-table-justify-field-maybe)
20399 (call-interactively 'org-table-next-row))
20400 ;; when `newline-and-indent' is called within a list, make sure
20401 ;; text moved stays inside the item.
20402 ((and (org-in-item-p) indent)
20403 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20404 (progn
20405 (save-match-data (newline))
20406 (org-indent-line-to (length (match-string 0))))
20407 (let ((ind (org-get-indentation)))
20408 (newline)
20409 (if (org-looking-back org-list-end-re)
20410 (org-indent-line)
20411 (org-indent-line-to ind)))))
20412 ((and org-return-follows-link
20413 (org-at-timestamp-p t)
20414 (not (eq org-ts-what 'after)))
20415 (org-follow-timestamp-link))
20416 ((and org-return-follows-link
20417 (let ((tprop (get-text-property (point) 'face)))
20418 (or (eq tprop 'org-link)
20419 (and (listp tprop) (memq 'org-link tprop)))))
20420 (call-interactively 'org-open-at-point))
20421 ((and (org-at-heading-p)
20422 (looking-at
20423 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20424 (org-show-entry)
20425 (end-of-line 1)
20426 (newline))
20427 (t (if indent (newline-and-indent) (newline))))))
20429 (defun org-return-indent ()
20430 "Goto next table row or insert a newline and indent.
20431 Calls `org-table-next-row' or `newline-and-indent', depending on
20432 context. See the individual commands for more information."
20433 (interactive)
20434 (org-return t))
20436 (defun org-ctrl-c-star ()
20437 "Compute table, or change heading status of lines.
20438 Calls `org-table-recalculate' or `org-toggle-heading',
20439 depending on context."
20440 (interactive)
20441 (cond
20442 ((org-at-table-p)
20443 (call-interactively 'org-table-recalculate))
20445 ;; Convert all lines in region to list items
20446 (call-interactively 'org-toggle-heading))))
20448 (defun org-ctrl-c-minus ()
20449 "Insert separator line in table or modify bullet status of line.
20450 Also turns a plain line or a region of lines into list items.
20451 Calls `org-table-insert-hline', `org-toggle-item', or
20452 `org-cycle-list-bullet', depending on context."
20453 (interactive)
20454 (cond
20455 ((org-at-table-p)
20456 (call-interactively 'org-table-insert-hline))
20457 ((org-region-active-p)
20458 (call-interactively 'org-toggle-item))
20459 ((org-in-item-p)
20460 (call-interactively 'org-cycle-list-bullet))
20462 (call-interactively 'org-toggle-item))))
20464 (defun org-toggle-item (arg)
20465 "Convert headings or normal lines to items, items to normal lines.
20466 If there is no active region, only the current line is considered.
20468 If the first non blank line in the region is a headline, convert
20469 all headlines to items, shifting text accordingly.
20471 If it is an item, convert all items to normal lines.
20473 If it is normal text, change region into a list of items.
20474 With a prefix argument ARG, change the region in a single item."
20475 (interactive "P")
20476 (let ((shift-text
20477 (function
20478 ;; Shift text in current section to IND, from point to END.
20479 ;; The function leaves point to END line.
20480 (lambda (ind end)
20481 (let ((min-i 1000) (end (copy-marker end)))
20482 ;; First determine the minimum indentation (MIN-I) of
20483 ;; the text.
20484 (save-excursion
20485 (catch 'exit
20486 (while (< (point) end)
20487 (let ((i (org-get-indentation)))
20488 (cond
20489 ;; Skip blank lines and inline tasks.
20490 ((looking-at "^[ \t]*$"))
20491 ((looking-at org-outline-regexp-bol))
20492 ;; We can't find less than 0 indentation.
20493 ((zerop i) (throw 'exit (setq min-i 0)))
20494 ((< i min-i) (setq min-i i))))
20495 (forward-line))))
20496 ;; Then indent each line so that a line indented to
20497 ;; MIN-I becomes indented to IND. Ignore blank lines
20498 ;; and inline tasks in the process.
20499 (let ((delta (- ind min-i)))
20500 (while (< (point) end)
20501 (unless (or (looking-at "^[ \t]*$")
20502 (looking-at org-outline-regexp-bol))
20503 (org-indent-line-to (+ (org-get-indentation) delta)))
20504 (forward-line)))))))
20505 (skip-blanks
20506 (function
20507 ;; Return beginning of first non-blank line, starting from
20508 ;; line at POS.
20509 (lambda (pos)
20510 (save-excursion
20511 (goto-char pos)
20512 (skip-chars-forward " \r\t\n")
20513 (point-at-bol)))))
20514 beg end)
20515 ;; Determine boundaries of changes.
20516 (if (org-region-active-p)
20517 (setq beg (funcall skip-blanks (region-beginning))
20518 end (copy-marker (region-end)))
20519 (setq beg (funcall skip-blanks (point-at-bol))
20520 end (copy-marker (point-at-eol))))
20521 ;; Depending on the starting line, choose an action on the text
20522 ;; between BEG and END.
20523 (org-with-limited-levels
20524 (save-excursion
20525 (goto-char beg)
20526 (cond
20527 ;; Case 1. Start at an item: de-itemize. Note that it only
20528 ;; happens when a region is active: `org-ctrl-c-minus'
20529 ;; would call `org-cycle-list-bullet' otherwise.
20530 ((org-at-item-p)
20531 (while (< (point) end)
20532 (when (org-at-item-p)
20533 (skip-chars-forward " \t")
20534 (delete-region (point) (match-end 0)))
20535 (forward-line)))
20536 ;; Case 2. Start at an heading: convert to items.
20537 ((org-at-heading-p)
20538 (let* ((bul (org-list-bullet-string "-"))
20539 (bul-len (length bul))
20540 ;; Indentation of the first heading. It should be
20541 ;; relative to the indentation of its parent, if any.
20542 (start-ind (save-excursion
20543 (cond
20544 ((not org-adapt-indentation) 0)
20545 ((not (outline-previous-heading)) 0)
20546 (t (length (match-string 0))))))
20547 ;; Level of first heading. Further headings will be
20548 ;; compared to it to determine hierarchy in the list.
20549 (ref-level (org-reduced-level (org-outline-level))))
20550 (while (< (point) end)
20551 (let* ((level (org-reduced-level (org-outline-level)))
20552 (delta (max 0 (- level ref-level))))
20553 ;; If current headline is less indented than the first
20554 ;; one, set it as reference, in order to preserve
20555 ;; subtrees.
20556 (when (< level ref-level) (setq ref-level level))
20557 (replace-match bul t t)
20558 (org-indent-line-to (+ start-ind (* delta bul-len)))
20559 ;; Ensure all text down to END (or SECTION-END) belongs
20560 ;; to the newly created item.
20561 (let ((section-end (save-excursion
20562 (or (outline-next-heading) (point)))))
20563 (forward-line)
20564 (funcall shift-text
20565 (+ start-ind (* (1+ delta) bul-len))
20566 (min end section-end)))))))
20567 ;; Case 3. Normal line with ARG: make the first line of region
20568 ;; an item, and shift indentation of others lines to
20569 ;; set them as item's body.
20570 (arg (let* ((bul (org-list-bullet-string "-"))
20571 (bul-len (length bul))
20572 (ref-ind (org-get-indentation)))
20573 (skip-chars-forward " \t")
20574 (insert bul)
20575 (forward-line)
20576 (while (< (point) end)
20577 ;; Ensure that lines less indented than first one
20578 ;; still get included in item body.
20579 (funcall shift-text
20580 (+ ref-ind bul-len)
20581 (min end (save-excursion (or (outline-next-heading)
20582 (point)))))
20583 (forward-line))))
20584 ;; Case 4. Normal line without ARG: turn each non-item line
20585 ;; into an item.
20587 (while (< (point) end)
20588 (unless (or (org-at-heading-p) (org-at-item-p))
20589 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20590 (replace-match
20591 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20592 (forward-line))))))))
20594 (defun org-toggle-heading (&optional nstars)
20595 "Convert headings to normal text, or items or text to headings.
20596 If there is no active region, only convert the current line.
20598 With a \\[universal-argument] prefix, convert the whole list at
20599 point into heading.
20601 In a region:
20603 - If the first non blank line is a headline, remove the stars
20604 from all headlines in the region.
20606 - If it is a normal line, turn each and every normal line (i.e.,
20607 not an heading or an item) in the region into headings. If you
20608 want to convert only the first line of this region, use one
20609 universal prefix argument.
20611 - If it is a plain list item, turn all plain list items into headings.
20613 When converting a line into a heading, the number of stars is chosen
20614 such that the lines become children of the current entry. However,
20615 when a numeric prefix argument is given, its value determines the
20616 number of stars to add."
20617 (interactive "P")
20618 (let ((skip-blanks
20619 (function
20620 ;; Return beginning of first non-blank line, starting from
20621 ;; line at POS.
20622 (lambda (pos)
20623 (save-excursion
20624 (goto-char pos)
20625 (while (org-at-comment-p) (forward-line))
20626 (skip-chars-forward " \r\t\n")
20627 (point-at-bol)))))
20628 beg end toggled)
20629 ;; Determine boundaries of changes. If a universal prefix has
20630 ;; been given, put the list in a region. If region ends at a bol,
20631 ;; do not consider the last line to be in the region.
20633 (when (and current-prefix-arg (org-at-item-p))
20634 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20635 (org-mark-element))
20637 (if (org-region-active-p)
20638 (setq beg (funcall skip-blanks (region-beginning))
20639 end (copy-marker (save-excursion
20640 (goto-char (region-end))
20641 (if (bolp) (point) (point-at-eol)))))
20642 (setq beg (funcall skip-blanks (point-at-bol))
20643 end (copy-marker (point-at-eol))))
20644 ;; Ensure inline tasks don't count as headings.
20645 (org-with-limited-levels
20646 (save-excursion
20647 (goto-char beg)
20648 (cond
20649 ;; Case 1. Started at an heading: de-star headings.
20650 ((org-at-heading-p)
20651 (while (< (point) end)
20652 (when (org-at-heading-p t)
20653 (looking-at org-outline-regexp) (replace-match "")
20654 (setq toggled t))
20655 (forward-line)))
20656 ;; Case 2. Started at an item: change items into headlines.
20657 ;; One star will be added by `org-list-to-subtree'.
20658 ((org-at-item-p)
20659 (let* ((stars (make-string
20660 ;; subtract the star that will be added again by
20661 ;; `org-list-to-subtree'
20662 (if (numberp nstars) (1- nstars)
20663 (or (org-current-level) 0))
20664 ?*))
20665 (add-stars
20666 (cond (nstars "") ; stars from prefix only
20667 ((equal stars "") "") ; before first heading
20668 (org-odd-levels-only "*") ; inside heading, odd
20669 (t "")))) ; inside heading, oddeven
20670 (while (< (point) end)
20671 (when (org-at-item-p)
20672 ;; Pay attention to cases when region ends before list.
20673 (let* ((struct (org-list-struct))
20674 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20675 (save-restriction
20676 (narrow-to-region (point) list-end)
20677 (insert
20678 (org-list-to-subtree
20679 (org-list-parse-list t)
20680 '(:istart (concat stars add-stars (funcall get-stars depth))
20681 :icount (concat stars add-stars (funcall get-stars depth)))))))
20682 (setq toggled t))
20683 (forward-line))))
20684 ;; Case 3. Started at normal text: make every line an heading,
20685 ;; skipping headlines and items.
20686 (t (let* ((stars
20687 (make-string
20688 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20689 (add-stars
20690 (cond (nstars "") ; stars from prefix only
20691 ((equal stars "") "*") ; before first heading
20692 (org-odd-levels-only "**") ; inside heading, odd
20693 (t "*"))) ; inside heading, oddeven
20694 (rpl (concat stars add-stars " "))
20695 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20696 (while (< (point) (if (equal nstars '(4)) lend end))
20697 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20698 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20699 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20700 (forward-line)))))))
20701 (unless toggled (message "Cannot toggle heading from here"))))
20703 (defun org-meta-return (&optional arg)
20704 "Insert a new heading or wrap a region in a table.
20705 Calls `org-insert-heading' or `org-table-wrap-region', depending
20706 on context. See the individual commands for more information."
20707 (interactive "P")
20708 (org-check-before-invisible-edit 'insert)
20709 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20710 (let* ((element (org-element-at-point))
20711 (type (org-element-type element)))
20712 (when (eq type 'table-row)
20713 (setq element (org-element-property :parent element))
20714 (setq type 'table))
20715 (if (and (eq type 'table)
20716 (eq (org-element-property :type element) 'org)
20717 (>= (point) (org-element-property :contents-begin element))
20718 (< (point) (org-element-property :contents-end element)))
20719 (call-interactively 'org-table-wrap-region)
20720 (call-interactively 'org-insert-heading)))))
20722 ;;; Menu entries
20724 (defsubst org-in-subtree-not-table-p ()
20725 "Are we in a subtree and not in a table?"
20726 (and (not (org-before-first-heading-p))
20727 (not (org-at-table-p))))
20729 ;; Define the Org-mode menus
20730 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20731 '("Tbl"
20732 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20733 ["Next Field" org-cycle (org-at-table-p)]
20734 ["Previous Field" org-shifttab (org-at-table-p)]
20735 ["Next Row" org-return (org-at-table-p)]
20736 "--"
20737 ["Blank Field" org-table-blank-field (org-at-table-p)]
20738 ["Edit Field" org-table-edit-field (org-at-table-p)]
20739 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20740 "--"
20741 ("Column"
20742 ["Move Column Left" org-metaleft (org-at-table-p)]
20743 ["Move Column Right" org-metaright (org-at-table-p)]
20744 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20745 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20746 ("Row"
20747 ["Move Row Up" org-metaup (org-at-table-p)]
20748 ["Move Row Down" org-metadown (org-at-table-p)]
20749 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20750 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20751 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20752 "--"
20753 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20754 ("Rectangle"
20755 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20756 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20757 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20758 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20759 "--"
20760 ("Calculate"
20761 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20762 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20763 ["Edit Formulas" org-edit-special (org-at-table-p)]
20764 "--"
20765 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20766 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20767 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20768 "--"
20769 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20770 "--"
20771 ["Sum Column/Rectangle" org-table-sum
20772 (or (org-at-table-p) (org-region-active-p))]
20773 ["Which Column?" org-table-current-column (org-at-table-p)])
20774 ["Debug Formulas"
20775 org-table-toggle-formula-debugger
20776 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20777 ["Show Col/Row Numbers"
20778 org-table-toggle-coordinate-overlays
20779 :style toggle
20780 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20781 "--"
20782 ["Create" org-table-create (and (not (org-at-table-p))
20783 org-enable-table-editor)]
20784 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20785 ["Import from File" org-table-import (not (org-at-table-p))]
20786 ["Export to File" org-table-export (org-at-table-p)]
20787 "--"
20788 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20790 (easy-menu-define org-org-menu org-mode-map "Org menu"
20791 '("Org"
20792 ("Show/Hide"
20793 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20794 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20795 ["Sparse Tree..." org-sparse-tree t]
20796 ["Reveal Context" org-reveal t]
20797 ["Show All" show-all t]
20798 "--"
20799 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20800 "--"
20801 ["New Heading" org-insert-heading t]
20802 ("Navigate Headings"
20803 ["Up" outline-up-heading t]
20804 ["Next" outline-next-visible-heading t]
20805 ["Previous" outline-previous-visible-heading t]
20806 ["Next Same Level" outline-forward-same-level t]
20807 ["Previous Same Level" outline-backward-same-level t]
20808 "--"
20809 ["Jump" org-goto t])
20810 ("Edit Structure"
20811 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20812 "--"
20813 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20814 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20815 "--"
20816 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20817 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20818 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20819 "--"
20820 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20821 "--"
20822 ["Copy visible text" org-copy-visible t]
20823 "--"
20824 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20825 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20826 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20827 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20828 "--"
20829 ["Sort Region/Children" org-sort t]
20830 "--"
20831 ["Convert to odd levels" org-convert-to-odd-levels t]
20832 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20833 ("Editing"
20834 ["Emphasis..." org-emphasize t]
20835 ["Edit Source Example" org-edit-special t]
20836 "--"
20837 ["Footnote new/jump" org-footnote-action t]
20838 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20839 ("Archive"
20840 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20841 "--"
20842 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20843 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20844 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20846 "--"
20847 ("Hyperlinks"
20848 ["Store Link (Global)" org-store-link t]
20849 ["Find existing link to here" org-occur-link-in-agenda-files t]
20850 ["Insert Link" org-insert-link t]
20851 ["Follow Link" org-open-at-point t]
20852 "--"
20853 ["Next link" org-next-link t]
20854 ["Previous link" org-previous-link t]
20855 "--"
20856 ["Descriptive Links"
20857 org-toggle-link-display
20858 :style radio
20859 :selected org-descriptive-links
20861 ["Literal Links"
20862 org-toggle-link-display
20863 :style radio
20864 :selected (not org-descriptive-links)])
20865 "--"
20866 ("TODO Lists"
20867 ["TODO/DONE/-" org-todo t]
20868 ("Select keyword"
20869 ["Next keyword" org-shiftright (org-at-heading-p)]
20870 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20871 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20872 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20873 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20874 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20875 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20876 "--"
20877 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20878 :selected org-enforce-todo-dependencies :style toggle :active t]
20879 "Settings for tree at point"
20880 ["Do Children sequentially" org-toggle-ordered-property :style radio
20881 :selected (org-entry-get nil "ORDERED")
20882 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20883 ["Do Children parallel" org-toggle-ordered-property :style radio
20884 :selected (not (org-entry-get nil "ORDERED"))
20885 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20886 "--"
20887 ["Set Priority" org-priority t]
20888 ["Priority Up" org-shiftup t]
20889 ["Priority Down" org-shiftdown t]
20890 "--"
20891 ["Get news from all feeds" org-feed-update-all t]
20892 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20893 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20894 ("TAGS and Properties"
20895 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20896 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20897 "--"
20898 ["Set property" org-set-property (not (org-before-first-heading-p))]
20899 ["Column view of properties" org-columns t]
20900 ["Insert Column View DBlock" org-insert-columns-dblock t])
20901 ("Dates and Scheduling"
20902 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20903 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20904 ("Change Date"
20905 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20906 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20907 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20908 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20909 ["Compute Time Range" org-evaluate-time-range t]
20910 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20911 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20912 "--"
20913 ["Custom time format" org-toggle-time-stamp-overlays
20914 :style radio :selected org-display-custom-times]
20915 "--"
20916 ["Goto Calendar" org-goto-calendar t]
20917 ["Date from Calendar" org-date-from-calendar t]
20918 "--"
20919 ["Start/Restart Timer" org-timer-start t]
20920 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20921 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20922 ["Insert Timer String" org-timer t]
20923 ["Insert Timer Item" org-timer-item t])
20924 ("Logging work"
20925 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20926 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20927 ["Clock out" org-clock-out t]
20928 ["Clock cancel" org-clock-cancel t]
20929 "--"
20930 ["Mark as default task" org-clock-mark-default-task t]
20931 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20932 ["Goto running clock" org-clock-goto t]
20933 "--"
20934 ["Display times" org-clock-display t]
20935 ["Create clock table" org-clock-report t]
20936 "--"
20937 ["Record DONE time"
20938 (progn (setq org-log-done (not org-log-done))
20939 (message "Switching to %s will %s record a timestamp"
20940 (car org-done-keywords)
20941 (if org-log-done "automatically" "not")))
20942 :style toggle :selected org-log-done])
20943 "--"
20944 ["Agenda Command..." org-agenda t]
20945 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20946 ("File List for Agenda")
20947 ("Special views current file"
20948 ["TODO Tree" org-show-todo-tree t]
20949 ["Check Deadlines" org-check-deadlines t]
20950 ["Timeline" org-timeline t]
20951 ["Tags/Property tree" org-match-sparse-tree t])
20952 "--"
20953 ["Export/Publish..." org-export-dispatch t]
20954 ("LaTeX"
20955 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20956 :selected org-cdlatex-mode]
20957 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20958 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20959 ["Modify math symbol" org-cdlatex-math-modify
20960 (org-inside-LaTeX-fragment-p)]
20961 ["Insert citation" org-reftex-citation t]
20962 "--"
20963 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20964 "--"
20965 ("MobileOrg"
20966 ["Push Files and Views" org-mobile-push t]
20967 ["Get Captured and Flagged" org-mobile-pull t]
20968 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20969 "--"
20970 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20971 "--"
20972 ("Documentation"
20973 ["Show Version" org-version t]
20974 ["Info Documentation" org-info t])
20975 ("Customize"
20976 ["Browse Org Group" org-customize t]
20977 "--"
20978 ["Expand This Menu" org-create-customize-menu
20979 (fboundp 'customize-menu-create)])
20980 ["Send bug report" org-submit-bug-report t]
20981 "--"
20982 ("Refresh/Reload"
20983 ["Refresh setup current buffer" org-mode-restart t]
20984 ["Reload Org (after update)" org-reload t]
20985 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20988 (defun org-info (&optional node)
20989 "Read documentation for Org-mode in the info system.
20990 With optional NODE, go directly to that node."
20991 (interactive)
20992 (info (format "(org)%s" (or node ""))))
20994 ;;;###autoload
20995 (defun org-submit-bug-report ()
20996 "Submit a bug report on Org-mode via mail.
20998 Don't hesitate to report any problems or inaccurate documentation.
21000 If you don't have setup sending mail from (X)Emacs, please copy the
21001 output buffer into your mail program, as it gives us important
21002 information about your Org-mode version and configuration."
21003 (interactive)
21004 (require 'reporter)
21005 (org-load-modules-maybe)
21006 (org-require-autoloaded-modules)
21007 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21008 (reporter-submit-bug-report
21009 "emacs-orgmode@gnu.org"
21010 (org-version nil 'full)
21011 (let (list)
21012 (save-window-excursion
21013 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21014 (delete-other-windows)
21015 (erase-buffer)
21016 (insert "You are about to submit a bug report to the Org-mode mailing list.
21018 We would like to add your full Org-mode and Outline configuration to the
21019 bug report. This greatly simplifies the work of the maintainer and
21020 other experts on the mailing list.
21022 HOWEVER, some variables you have customized may contain private
21023 information. The names of customers, colleagues, or friends, might
21024 appear in the form of file names, tags, todo states, or search strings.
21025 If you answer yes to the prompt, you might want to check and remove
21026 such private information before sending the email.")
21027 (add-text-properties (point-min) (point-max) '(face org-warning))
21028 (when (yes-or-no-p "Include your Org-mode configuration ")
21029 (mapatoms
21030 (lambda (v)
21031 (and (boundp v)
21032 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21033 (or (and (symbol-value v)
21034 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21035 (and
21036 (get v 'custom-type) (get v 'standard-value)
21037 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21038 (push v list)))))
21039 (kill-buffer (get-buffer "*Warn about privacy*"))
21040 list))
21041 nil nil
21042 "Remember to cover the basics, that is, what you expected to happen and
21043 what in fact did happen. You don't know how to make a good report? See
21045 http://orgmode.org/manual/Feedback.html#Feedback
21047 Your bug report will be posted to the Org-mode mailing list.
21048 ------------------------------------------------------------------------")
21049 (save-excursion
21050 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21051 (replace-match "\\1Bug: \\3 [\\2]")))))
21054 (defun org-install-agenda-files-menu ()
21055 (let ((bl (buffer-list)))
21056 (save-excursion
21057 (while bl
21058 (set-buffer (pop bl))
21059 (if (derived-mode-p 'org-mode) (setq bl nil)))
21060 (when (derived-mode-p 'org-mode)
21061 (easy-menu-change
21062 '("Org") "File List for Agenda"
21063 (append
21064 (list
21065 ["Edit File List" (org-edit-agenda-file-list) t]
21066 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21067 ["Remove Current File from List" org-remove-file t]
21068 ["Cycle through agenda files" org-cycle-agenda-files t]
21069 ["Occur in all agenda files" org-occur-in-agenda-files t]
21070 "--")
21071 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21073 ;;;; Documentation
21075 (defun org-require-autoloaded-modules ()
21076 (interactive)
21077 (mapc 'require
21078 '(org-agenda org-archive org-attach org-clock org-colview org-id
21079 org-remember org-table org-timer)))
21081 ;;;###autoload
21082 (defun org-reload (&optional uncompiled)
21083 "Reload all org lisp files.
21084 With prefix arg UNCOMPILED, load the uncompiled versions."
21085 (interactive "P")
21086 (require 'loadhist)
21087 (let* ((org-dir (org-find-library-dir "org"))
21088 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21089 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21090 (remove-re (mapconcat 'identity
21091 (mapcar (lambda (f) (concat "^" f "$"))
21092 (list (if (featurep 'xemacs)
21093 "org-colview"
21094 "org-colview-xemacs")
21095 "org" "org-loaddefs" "org-version"))
21096 "\\|"))
21097 (feats (delete-dups
21098 (mapcar 'file-name-sans-extension
21099 (mapcar 'file-name-nondirectory
21100 (delq nil
21101 (mapcar 'feature-file
21102 features))))))
21103 (lfeat (append
21104 (sort
21105 (setq feats
21106 (delq nil (mapcar
21107 (lambda (f)
21108 (if (and (string-match feature-re f)
21109 (not (string-match remove-re f)))
21110 f nil))
21111 feats)))
21112 'string-lessp)
21113 (list "org-version" "org")))
21114 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21115 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21116 load-uncore load-misses)
21117 (setq load-misses
21118 (delq 't
21119 (mapcar (lambda (f)
21120 (or (org-load-noerror-mustsuffix (concat org-dir f))
21121 (and (string= org-dir contrib-dir)
21122 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21123 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21124 (add-to-list 'load-uncore f 'append)
21127 lfeat)))
21128 (if load-uncore
21129 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21130 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21131 (if load-misses
21132 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21133 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21134 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21136 ;;;###autoload
21137 (defun org-customize ()
21138 "Call the customize function with org as argument."
21139 (interactive)
21140 (org-load-modules-maybe)
21141 (org-require-autoloaded-modules)
21142 (customize-browse 'org))
21144 (defun org-create-customize-menu ()
21145 "Create a full customization menu for Org-mode, insert it into the menu."
21146 (interactive)
21147 (org-load-modules-maybe)
21148 (org-require-autoloaded-modules)
21149 (if (fboundp 'customize-menu-create)
21150 (progn
21151 (easy-menu-change
21152 '("Org") "Customize"
21153 `(["Browse Org group" org-customize t]
21154 "--"
21155 ,(customize-menu-create 'org)
21156 ["Set" Custom-set t]
21157 ["Save" Custom-save t]
21158 ["Reset to Current" Custom-reset-current t]
21159 ["Reset to Saved" Custom-reset-saved t]
21160 ["Reset to Standard Settings" Custom-reset-standard t]))
21161 (message "\"Org\"-menu now contains full customization menu"))
21162 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21164 ;;;; Miscellaneous stuff
21166 ;;; Generally useful functions
21168 (defun org-get-at-bol (property)
21169 "Get text property PROPERTY at beginning of line."
21170 (get-text-property (point-at-bol) property))
21172 (defun org-find-text-property-in-string (prop s)
21173 "Return the first non-nil value of property PROP in string S."
21174 (or (get-text-property 0 prop s)
21175 (get-text-property (or (next-single-property-change 0 prop s) 0)
21176 prop s)))
21178 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21179 "Display the given MESSAGE as a warning."
21180 (if (fboundp 'display-warning)
21181 (display-warning 'org message
21182 (if (featurep 'xemacs) 'warning :warning))
21183 (let ((buf (get-buffer-create "*Org warnings*")))
21184 (with-current-buffer buf
21185 (goto-char (point-max))
21186 (insert "Warning (Org): " message)
21187 (unless (bolp)
21188 (newline)))
21189 (display-buffer buf)
21190 (sit-for 0))))
21192 (defun org-eval (form)
21193 "Eval FORM and return result."
21194 (condition-case error
21195 (eval form)
21196 (error (format "%%![Error: %s]" error))))
21198 (defun org-in-clocktable-p ()
21199 "Check if the cursor is in a clocktable."
21200 (let ((pos (point)) start)
21201 (save-excursion
21202 (end-of-line 1)
21203 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21204 (setq start (match-beginning 0))
21205 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21206 (>= (match-end 0) pos)
21207 start))))
21209 (defun org-in-commented-line ()
21210 "Is point in a line starting with `#'?"
21211 (equal (char-after (point-at-bol)) ?#))
21213 (defun org-in-indented-comment-line ()
21214 "Is point in a line starting with `#' after some white space?"
21215 (save-excursion
21216 (save-match-data
21217 (goto-char (point-at-bol))
21218 (looking-at "[ \t]*#"))))
21220 (defun org-in-verbatim-emphasis ()
21221 (save-match-data
21222 (and (org-in-regexp org-emph-re 2)
21223 (>= (point) (match-beginning 3))
21224 (<= (point) (match-end 4))
21225 (member (match-string 3) '("=" "~")))))
21227 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21228 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21229 (if (and marker (marker-buffer marker)
21230 (buffer-live-p (marker-buffer marker)))
21231 (progn
21232 (org-pop-to-buffer-same-window (marker-buffer marker))
21233 (if (or (> marker (point-max)) (< marker (point-min)))
21234 (widen))
21235 (goto-char marker)
21236 (org-show-context 'org-goto))
21237 (if bookmark
21238 (bookmark-jump bookmark)
21239 (error "Cannot find location"))))
21241 (defun org-quote-csv-field (s)
21242 "Quote field for inclusion in CSV material."
21243 (if (string-match "[\",]" s)
21244 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21247 (defun org-force-self-insert (N)
21248 "Needed to enforce self-insert under remapping."
21249 (interactive "p")
21250 (self-insert-command N))
21252 (defun org-string-width (s)
21253 "Compute width of string, ignoring invisible characters.
21254 This ignores character with invisibility property `org-link', and also
21255 characters with property `org-cwidth', because these will become invisible
21256 upon the next fontification round."
21257 (let (b l)
21258 (when (or (eq t buffer-invisibility-spec)
21259 (assq 'org-link buffer-invisibility-spec))
21260 (while (setq b (text-property-any 0 (length s)
21261 'invisible 'org-link s))
21262 (setq s (concat (substring s 0 b)
21263 (substring s (or (next-single-property-change
21264 b 'invisible s) (length s)))))))
21265 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21266 (setq s (concat (substring s 0 b)
21267 (substring s (or (next-single-property-change
21268 b 'org-cwidth s) (length s))))))
21269 (setq l (string-width s) b -1)
21270 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21271 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21274 (defun org-shorten-string (s maxlength)
21275 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21276 If the string is shorter or has length MAXLENGTH, just return the
21277 original string. If it is longer, the functions finds a space in the
21278 string, breaks this string off at that locations and adds three dots
21279 as ellipsis. Including the ellipsis, the string will not be longer
21280 than MAXLENGTH. If finding a good breaking point in the string does
21281 not work, the string is just chopped off in the middle of a word
21282 if necessary."
21283 (if (<= (length s) maxlength)
21285 (let* ((n (max (- maxlength 4) 1))
21286 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21287 (if (string-match re s)
21288 (concat (match-string 1 s) "...")
21289 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21291 (defun org-get-indentation (&optional line)
21292 "Get the indentation of the current line, interpreting tabs.
21293 When LINE is given, assume it represents a line and compute its indentation."
21294 (if line
21295 (if (string-match "^ *" (org-remove-tabs line))
21296 (match-end 0))
21297 (save-excursion
21298 (beginning-of-line 1)
21299 (skip-chars-forward " \t")
21300 (current-column))))
21302 (defun org-get-string-indentation (s)
21303 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21304 (let ((n -1) (i 0) (w tab-width) c)
21305 (catch 'exit
21306 (while (< (setq n (1+ n)) (length s))
21307 (setq c (aref s n))
21308 (cond ((= c ?\ ) (setq i (1+ i)))
21309 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21310 (t (throw 'exit t)))))
21313 (defun org-remove-tabs (s &optional width)
21314 "Replace tabulators in S with spaces.
21315 Assumes that s is a single line, starting in column 0."
21316 (setq width (or width tab-width))
21317 (while (string-match "\t" s)
21318 (setq s (replace-match
21319 (make-string
21320 (- (* width (/ (+ (match-beginning 0) width) width))
21321 (match-beginning 0)) ?\ )
21322 t t s)))
21325 (defun org-fix-indentation (line ind)
21326 "Fix indentation in LINE.
21327 IND is a cons cell with target and minimum indentation.
21328 If the current indentation in LINE is smaller than the minimum,
21329 leave it alone. If it is larger than ind, set it to the target."
21330 (let* ((l (org-remove-tabs line))
21331 (i (org-get-indentation l))
21332 (i1 (car ind)) (i2 (cdr ind)))
21333 (if (>= i i2) (setq l (substring line i2)))
21334 (if (> i1 0)
21335 (concat (make-string i1 ?\ ) l)
21336 l)))
21338 (defun org-remove-indentation (code &optional n)
21339 "Remove the maximum common indentation from the lines in CODE.
21340 N may optionally be the number of spaces to remove."
21341 (with-temp-buffer
21342 (insert code)
21343 (org-do-remove-indentation n)
21344 (buffer-string)))
21346 (defun org-do-remove-indentation (&optional n)
21347 "Remove the maximum common indentation from the buffer."
21348 (untabify (point-min) (point-max))
21349 (let ((min 10000) re)
21350 (if n
21351 (setq min n)
21352 (goto-char (point-min))
21353 (while (re-search-forward "^ *[^ \n]" nil t)
21354 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21355 (unless (or (= min 0) (= min 10000))
21356 (setq re (format "^ \\{%d\\}" min))
21357 (goto-char (point-min))
21358 (while (re-search-forward re nil t)
21359 (replace-match "")
21360 (end-of-line 1))
21361 min)))
21363 (defun org-fill-template (template alist)
21364 "Find each %key of ALIST in TEMPLATE and replace it."
21365 (let ((case-fold-search nil)
21366 entry key value)
21367 (setq alist (sort (copy-sequence alist)
21368 (lambda (a b) (< (length (car a)) (length (car b))))))
21369 (while (setq entry (pop alist))
21370 (setq template
21371 (replace-regexp-in-string
21372 (concat "%" (regexp-quote (car entry)))
21373 (or (cdr entry) "") template t t)))
21374 template))
21376 (defun org-base-buffer (buffer)
21377 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21378 (if (not buffer)
21379 buffer
21380 (or (buffer-base-buffer buffer)
21381 buffer)))
21383 (defun org-trim (s)
21384 "Remove whitespace at beginning and end of string."
21385 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21386 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21389 (defun org-wrap (string &optional width lines)
21390 "Wrap string to either a number of lines, or a width in characters.
21391 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21392 that costs. If there is a word longer than WIDTH, the text is actually
21393 wrapped to the length of that word.
21394 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21395 many lines, whatever width that takes.
21396 The return value is a list of lines, without newlines at the end."
21397 (let* ((words (org-split-string string "[ \t\n]+"))
21398 (maxword (apply 'max (mapcar 'org-string-width words)))
21399 w ll)
21400 (cond (width
21401 (org-do-wrap words (max maxword width)))
21402 (lines
21403 (setq w maxword)
21404 (setq ll (org-do-wrap words maxword))
21405 (if (<= (length ll) lines)
21407 (setq ll words)
21408 (while (> (length ll) lines)
21409 (setq w (1+ w))
21410 (setq ll (org-do-wrap words w)))
21411 ll))
21412 (t (error "Cannot wrap this")))))
21414 (defun org-do-wrap (words width)
21415 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21416 (let (lines line)
21417 (while words
21418 (setq line (pop words))
21419 (while (and words (< (+ (length line) (length (car words))) width))
21420 (setq line (concat line " " (pop words))))
21421 (setq lines (push line lines)))
21422 (nreverse lines)))
21424 (defun org-split-string (string &optional separators)
21425 "Splits STRING into substrings at SEPARATORS.
21426 No empty strings are returned if there are matches at the beginning
21427 and end of string."
21428 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21429 (start 0)
21430 notfirst
21431 (list nil))
21432 (while (and (string-match rexp string
21433 (if (and notfirst
21434 (= start (match-beginning 0))
21435 (< start (length string)))
21436 (1+ start) start))
21437 (< (match-beginning 0) (length string)))
21438 (setq notfirst t)
21439 (or (eq (match-beginning 0) 0)
21440 (and (eq (match-beginning 0) (match-end 0))
21441 (eq (match-beginning 0) start))
21442 (setq list
21443 (cons (substring string start (match-beginning 0))
21444 list)))
21445 (setq start (match-end 0)))
21446 (or (eq start (length string))
21447 (setq list
21448 (cons (substring string start)
21449 list)))
21450 (nreverse list)))
21452 (defun org-quote-vert (s)
21453 "Replace \"|\" with \"\\vert\"."
21454 (while (string-match "|" s)
21455 (setq s (replace-match "\\vert" t t s)))
21458 (defun org-uuidgen-p (s)
21459 "Is S an ID created by UUIDGEN?"
21460 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21462 (defun org-in-src-block-p (&optional inside)
21463 "Whether point is in a code source block.
21464 When INSIDE is non-nil, don't consider we are within a src block
21465 when point is at #+BEGIN_SRC or #+END_SRC."
21466 (let ((case-fold-search t) ov)
21467 (or (and (setq ov (overlays-at (point)))
21468 (memq 'org-block-background
21469 (overlay-properties (car ov))))
21470 (and (not inside)
21471 (save-match-data
21472 (save-excursion
21473 (beginning-of-line)
21474 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21476 (defun org-context ()
21477 "Return a list of contexts of the current cursor position.
21478 If several contexts apply, all are returned.
21479 Each context entry is a list with a symbol naming the context, and
21480 two positions indicating start and end of the context. Possible
21481 contexts are:
21483 :headline anywhere in a headline
21484 :headline-stars on the leading stars in a headline
21485 :todo-keyword on a TODO keyword (including DONE) in a headline
21486 :tags on the TAGS in a headline
21487 :priority on the priority cookie in a headline
21488 :item on the first line of a plain list item
21489 :item-bullet on the bullet/number of a plain list item
21490 :checkbox on the checkbox in a plain list item
21491 :table in an org-mode table
21492 :table-special on a special filed in a table
21493 :table-table in a table.el table
21494 :clocktable in a clocktable
21495 :src-block in a source block
21496 :link on a hyperlink
21497 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21498 :target on a <<target>>
21499 :radio-target on a <<<radio-target>>>
21500 :latex-fragment on a LaTeX fragment
21501 :latex-preview on a LaTeX fragment with overlaid preview image
21503 This function expects the position to be visible because it uses font-lock
21504 faces as a help to recognize the following contexts: :table-special, :link,
21505 and :keyword."
21506 (let* ((f (get-text-property (point) 'face))
21507 (faces (if (listp f) f (list f)))
21508 (case-fold-search t)
21509 (p (point)) clist o)
21510 ;; First the large context
21511 (cond
21512 ((org-at-heading-p t)
21513 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21514 (when (progn
21515 (beginning-of-line 1)
21516 (looking-at org-todo-line-tags-regexp))
21517 (push (org-point-in-group p 1 :headline-stars) clist)
21518 (push (org-point-in-group p 2 :todo-keyword) clist)
21519 (push (org-point-in-group p 4 :tags) clist))
21520 (goto-char p)
21521 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21522 (if (looking-at "\\[#[A-Z0-9]\\]")
21523 (push (org-point-in-group p 0 :priority) clist)))
21525 ((org-at-item-p)
21526 (push (org-point-in-group p 2 :item-bullet) clist)
21527 (push (list :item (point-at-bol)
21528 (save-excursion (org-end-of-item) (point)))
21529 clist)
21530 (and (org-at-item-checkbox-p)
21531 (push (org-point-in-group p 0 :checkbox) clist)))
21533 ((org-at-table-p)
21534 (push (list :table (org-table-begin) (org-table-end)) clist)
21535 (if (memq 'org-formula faces)
21536 (push (list :table-special
21537 (previous-single-property-change p 'face)
21538 (next-single-property-change p 'face)) clist)))
21539 ((org-at-table-p 'any)
21540 (push (list :table-table) clist)))
21541 (goto-char p)
21543 (let ((case-fold-search t))
21544 ;; New the "medium" contexts: clocktables, source blocks
21545 (cond ((org-in-clocktable-p)
21546 (push (list :clocktable
21547 (and (or (looking-at "#\\+BEGIN: clocktable")
21548 (search-backward "#+BEGIN: clocktable" nil t))
21549 (match-beginning 0))
21550 (and (re-search-forward "#\\+END:?" nil t)
21551 (match-end 0))) clist))
21552 ((org-in-src-block-p)
21553 (push (list :src-block
21554 (and (or (looking-at "#\\+BEGIN_SRC")
21555 (search-backward "#+BEGIN_SRC" nil t))
21556 (match-beginning 0))
21557 (and (search-forward "#+END_SRC" nil t)
21558 (match-beginning 0))) clist))))
21559 (goto-char p)
21561 ;; Now the small context
21562 (cond
21563 ((org-at-timestamp-p)
21564 (push (org-point-in-group p 0 :timestamp) clist))
21565 ((memq 'org-link faces)
21566 (push (list :link
21567 (previous-single-property-change p 'face)
21568 (next-single-property-change p 'face)) clist))
21569 ((memq 'org-special-keyword faces)
21570 (push (list :keyword
21571 (previous-single-property-change p 'face)
21572 (next-single-property-change p 'face)) clist))
21573 ((org-at-target-p)
21574 (push (org-point-in-group p 0 :target) clist)
21575 (goto-char (1- (match-beginning 0)))
21576 (if (looking-at org-radio-target-regexp)
21577 (push (org-point-in-group p 0 :radio-target) clist))
21578 (goto-char p))
21579 ((setq o (car (delq nil
21580 (mapcar
21581 (lambda (x)
21582 (if (memq x org-latex-fragment-image-overlays) x))
21583 (overlays-at (point))))))
21584 (push (list :latex-fragment
21585 (overlay-start o) (overlay-end o)) clist)
21586 (push (list :latex-preview
21587 (overlay-start o) (overlay-end o)) clist))
21588 ((org-inside-LaTeX-fragment-p)
21589 ;; FIXME: positions wrong.
21590 (push (list :latex-fragment (point) (point)) clist)))
21592 (setq clist (nreverse (delq nil clist)))
21593 clist))
21595 ;; FIXME: Compare with at-regexp-p Do we need both?
21596 (defun org-in-regexp (re &optional nlines visually)
21597 "Check if point is inside a match of regexp.
21598 Normally only the current line is checked, but you can include NLINES extra
21599 lines both before and after point into the search.
21600 If VISUALLY is set, require that the cursor is not after the match but
21601 really on, so that the block visually is on the match."
21602 (catch 'exit
21603 (let ((pos (point))
21604 (eol (point-at-eol (+ 1 (or nlines 0))))
21605 (inc (if visually 1 0)))
21606 (save-excursion
21607 (beginning-of-line (- 1 (or nlines 0)))
21608 (while (re-search-forward re eol t)
21609 (if (and (<= (match-beginning 0) pos)
21610 (>= (+ inc (match-end 0)) pos))
21611 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21613 (defun org-at-regexp-p (regexp)
21614 "Is point inside a match of REGEXP in the current line?"
21615 (catch 'exit
21616 (save-excursion
21617 (let ((pos (point)) (end (point-at-eol)))
21618 (beginning-of-line 1)
21619 (while (re-search-forward regexp end t)
21620 (if (and (<= (match-beginning 0) pos)
21621 (>= (match-end 0) pos))
21622 (throw 'exit t)))
21623 nil))))
21625 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21626 "Non-nil when point is between matches of START-RE and END-RE.
21628 Also return a non-nil value when point is on one of the matches.
21630 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21631 buffer positions. Default values are the positions of headlines
21632 surrounding the point.
21634 The functions returns a cons cell whose car (resp. cdr) is the
21635 position before START-RE (resp. after END-RE)."
21636 (save-match-data
21637 (let ((pos (point))
21638 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21639 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21640 beg end)
21641 (save-excursion
21642 ;; Point is on a block when on START-RE or if START-RE can be
21643 ;; found before it...
21644 (and (or (org-at-regexp-p start-re)
21645 (re-search-backward start-re limit-up t))
21646 (setq beg (match-beginning 0))
21647 ;; ... and END-RE after it...
21648 (goto-char (match-end 0))
21649 (re-search-forward end-re limit-down t)
21650 (> (setq end (match-end 0)) pos)
21651 ;; ... without another START-RE in-between.
21652 (goto-char (match-beginning 0))
21653 (not (re-search-backward start-re (1+ beg) t))
21654 ;; Return value.
21655 (cons beg end))))))
21657 (defun org-in-block-p (names)
21658 "Non-nil when point belongs to a block whose name belongs to NAMES.
21660 NAMES is a list of strings containing names of blocks.
21662 Return first block name matched, or nil. Beware that in case of
21663 nested blocks, the returned name may not belong to the closest
21664 block from point."
21665 (save-match-data
21666 (catch 'exit
21667 (let ((case-fold-search t)
21668 (lim-up (save-excursion (outline-previous-heading)))
21669 (lim-down (save-excursion (outline-next-heading))))
21670 (mapc (lambda (name)
21671 (let ((n (regexp-quote name)))
21672 (when (org-between-regexps-p
21673 (concat "^[ \t]*#\\+begin_" n)
21674 (concat "^[ \t]*#\\+end_" n)
21675 lim-up lim-down)
21676 (throw 'exit n))))
21677 names))
21678 nil)))
21680 (defun org-in-drawer-p ()
21681 "Is point within a drawer?"
21682 (save-match-data
21683 (let ((case-fold-search t)
21684 (lim-up (save-excursion (outline-previous-heading)))
21685 (lim-down (save-excursion (outline-next-heading))))
21686 (org-between-regexps-p
21687 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21688 "^[ \t]*:end:.*$"
21689 lim-up lim-down))))
21691 (defun org-occur-in-agenda-files (regexp &optional nlines)
21692 "Call `multi-occur' with buffers for all agenda files."
21693 (interactive "sOrg-files matching: \np")
21694 (let* ((files (org-agenda-files))
21695 (tnames (mapcar 'file-truename files))
21696 (extra org-agenda-text-search-extra-files)
21698 (when (eq (car extra) 'agenda-archives)
21699 (setq extra (cdr extra))
21700 (setq files (org-add-archive-files files)))
21701 (while (setq f (pop extra))
21702 (unless (member (file-truename f) tnames)
21703 (add-to-list 'files f 'append)
21704 (add-to-list 'tnames (file-truename f) 'append)))
21705 (multi-occur
21706 (mapcar (lambda (x)
21707 (with-current-buffer
21708 (or (get-file-buffer x) (find-file-noselect x))
21709 (widen)
21710 (current-buffer)))
21711 files)
21712 regexp)))
21714 (if (boundp 'occur-mode-find-occurrence-hook)
21715 ;; Emacs 23
21716 (add-hook 'occur-mode-find-occurrence-hook
21717 (lambda ()
21718 (when (derived-mode-p 'org-mode)
21719 (org-reveal))))
21720 ;; Emacs 22
21721 (defadvice occur-mode-goto-occurrence
21722 (after org-occur-reveal activate)
21723 (and (derived-mode-p 'org-mode) (org-reveal)))
21724 (defadvice occur-mode-goto-occurrence-other-window
21725 (after org-occur-reveal activate)
21726 (and (derived-mode-p 'org-mode) (org-reveal)))
21727 (defadvice occur-mode-display-occurrence
21728 (after org-occur-reveal activate)
21729 (when (derived-mode-p 'org-mode)
21730 (let ((pos (occur-mode-find-occurrence)))
21731 (with-current-buffer (marker-buffer pos)
21732 (save-excursion
21733 (goto-char pos)
21734 (org-reveal)))))))
21736 (defun org-occur-link-in-agenda-files ()
21737 "Create a link and search for it in the agendas.
21738 The link is not stored in `org-stored-links', it is just created
21739 for the search purpose."
21740 (interactive)
21741 (let ((link (condition-case nil
21742 (org-store-link nil)
21743 (error "Unable to create a link to here"))))
21744 (org-occur-in-agenda-files (regexp-quote link))))
21746 (defun org-reverse-string (string)
21747 "Return the reverse of STRING."
21748 (apply 'string (reverse (string-to-list string))))
21750 (defsubst org-uniquify (list)
21751 "Non-destructively remove duplicate elements from LIST."
21752 (let ((res (copy-sequence list))) (delete-dups res)))
21754 (defun org-uniquify-alist (alist)
21755 "Merge elements of ALIST with the same key.
21757 For example, in this alist:
21759 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21760 => '((a 1 3) (b 2))
21762 merge (a 1) and (a 3) into (a 1 3).
21764 The function returns the new ALIST."
21765 (let (rtn)
21766 (mapc
21767 (lambda (e)
21768 (let (n)
21769 (if (not (assoc (car e) rtn))
21770 (push e rtn)
21771 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21772 (setq rtn (assq-delete-all (car e) rtn))
21773 (push n rtn))))
21774 alist)
21775 rtn))
21777 (defun org-delete-all (elts list)
21778 "Remove all elements in ELTS from LIST."
21779 (while elts
21780 (setq list (delete (pop elts) list)))
21781 list)
21783 (defun org-count (cl-item cl-seq)
21784 "Count the number of occurrences of ITEM in SEQ.
21785 Taken from `count' in cl-seq.el with all keyword arguments removed."
21786 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21787 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21788 (while (< cl-start cl-end)
21789 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21790 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21791 (setq cl-start (1+ cl-start)))
21792 cl-count))
21794 (defun org-remove-if (predicate seq)
21795 "Remove everything from SEQ that fulfills PREDICATE."
21796 (let (res e)
21797 (while seq
21798 (setq e (pop seq))
21799 (if (not (funcall predicate e)) (push e res)))
21800 (nreverse res)))
21802 (defun org-remove-if-not (predicate seq)
21803 "Remove everything from SEQ that does not fulfill PREDICATE."
21804 (let (res e)
21805 (while seq
21806 (setq e (pop seq))
21807 (if (funcall predicate e) (push e res)))
21808 (nreverse res)))
21810 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21811 "Reduce two-argument FUNCTION across SEQ.
21812 Taken from `reduce' in cl-seq.el with all keyword arguments but
21813 \":initial-value\" removed."
21814 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21815 (cadr (memq :initial-value cl-keys)))
21816 (cl-seq (pop cl-seq))
21817 (t (funcall cl-func)))))
21818 (while cl-seq
21819 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21820 cl-accum))
21822 (defun org-every (pred seq)
21823 "Return true if PREDICATE is true of every element of SEQ.
21824 Adapted from `every' in cl.el."
21825 (catch 'org-every
21826 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21829 (defun org-some (pred seq)
21830 "Return true if PREDICATE is true of any element of SEQ.
21831 Adapted from `some' in cl.el."
21832 (catch 'org-some
21833 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21834 nil))
21836 (defun org-back-over-empty-lines ()
21837 "Move backwards over whitespace, to the beginning of the first empty line.
21838 Returns the number of empty lines passed."
21839 (let ((pos (point)))
21840 (if (cdr (assoc 'heading org-blank-before-new-entry))
21841 (skip-chars-backward " \t\n\r")
21842 (unless (eobp)
21843 (forward-line -1)))
21844 (beginning-of-line 2)
21845 (goto-char (min (point) pos))
21846 (count-lines (point) pos)))
21848 (defun org-skip-whitespace ()
21849 (skip-chars-forward " \t\n\r"))
21851 (defun org-point-in-group (point group &optional context)
21852 "Check if POINT is in match-group GROUP.
21853 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21854 match. If the match group does not exist or point is not inside it,
21855 return nil."
21856 (and (match-beginning group)
21857 (>= point (match-beginning group))
21858 (<= point (match-end group))
21859 (if context
21860 (list context (match-beginning group) (match-end group))
21861 t)))
21863 (defun org-switch-to-buffer-other-window (&rest args)
21864 "Switch to buffer in a second window on the current frame.
21865 In particular, do not allow pop-up frames.
21866 Returns the newly created buffer."
21867 (org-no-popups
21868 (apply 'switch-to-buffer-other-window args)))
21870 (defun org-combine-plists (&rest plists)
21871 "Create a single property list from all plists in PLISTS.
21872 The process starts by copying the first list, and then setting properties
21873 from the other lists. Settings in the last list are the most significant
21874 ones and overrule settings in the other lists."
21875 (let ((rtn (copy-sequence (pop plists)))
21876 p v ls)
21877 (while plists
21878 (setq ls (pop plists))
21879 (while ls
21880 (setq p (pop ls) v (pop ls))
21881 (setq rtn (plist-put rtn p v))))
21882 rtn))
21884 (defun org-replace-escapes (string table)
21885 "Replace %-escapes in STRING with values in TABLE.
21886 TABLE is an association list with keys like \"%a\" and string values.
21887 The sequences in STRING may contain normal field width and padding information,
21888 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21889 so values can contain further %-escapes if they are define later in TABLE."
21890 (let ((tbl (copy-alist table))
21891 (case-fold-search nil)
21892 (pchg 0)
21893 e re rpl)
21894 (while (setq e (pop tbl))
21895 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21896 (when (and (cdr e) (string-match re (cdr e)))
21897 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21898 (safe "SREF"))
21899 (add-text-properties 0 3 (list 'sref sref) safe)
21900 (setcdr e (replace-match safe t t (cdr e)))))
21901 (while (string-match re string)
21902 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21903 (cdr e)))
21904 (setq string (replace-match rpl t t string))))
21905 (while (setq pchg (next-property-change pchg string))
21906 (let ((sref (get-text-property pchg 'sref string)))
21907 (when (and sref (string-match "SREF" string pchg))
21908 (setq string (replace-match sref t t string)))))
21909 string))
21911 (defun org-sublist (list start end)
21912 "Return a section of LIST, from START to END.
21913 Counting starts at 1."
21914 (let (rtn (c start))
21915 (setq list (nthcdr (1- start) list))
21916 (while (and list (<= c end))
21917 (push (pop list) rtn)
21918 (setq c (1+ c)))
21919 (nreverse rtn)))
21921 (defun org-find-base-buffer-visiting (file)
21922 "Like `find-buffer-visiting' but always return the base buffer and
21923 not an indirect buffer."
21924 (let ((buf (or (get-file-buffer file)
21925 (find-buffer-visiting file))))
21926 (if buf
21927 (or (buffer-base-buffer buf) buf)
21928 nil)))
21930 (defun org-image-file-name-regexp (&optional extensions)
21931 "Return regexp matching the file names of images.
21932 If EXTENSIONS is given, only match these."
21933 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21934 (image-file-name-regexp)
21935 (let ((image-file-name-extensions
21936 (or extensions
21937 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21938 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21939 (concat "\\."
21940 (regexp-opt (nconc (mapcar 'upcase
21941 image-file-name-extensions)
21942 image-file-name-extensions)
21944 "\\'"))))
21946 (defun org-file-image-p (file &optional extensions)
21947 "Return non-nil if FILE is an image."
21948 (save-match-data
21949 (string-match (org-image-file-name-regexp extensions) file)))
21951 (defun org-get-cursor-date (&optional with-time)
21952 "Return the date at cursor in as a time.
21953 This works in the calendar and in the agenda, anywhere else it just
21954 returns the current time.
21955 If WITH-TIME is non-nil, returns the time of the event at point (in
21956 the agenda) or the current time of the day."
21957 (let (date day defd tp tm hod mod)
21958 (when with-time
21959 (setq tp (get-text-property (point) 'time))
21960 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21961 (setq hod (string-to-number (match-string 1 tp))
21962 mod (string-to-number (match-string 2 tp))))
21963 (or tp (setq hod (nth 2 (decode-time (current-time)))
21964 mod (nth 1 (decode-time (current-time))))))
21965 (cond
21966 ((eq major-mode 'calendar-mode)
21967 (setq date (calendar-cursor-to-date)
21968 defd (encode-time 0 (or mod 0) (or hod 0)
21969 (nth 1 date) (nth 0 date) (nth 2 date))))
21970 ((eq major-mode 'org-agenda-mode)
21971 (setq day (get-text-property (point) 'day))
21972 (if day
21973 (setq date (calendar-gregorian-from-absolute day)
21974 defd (encode-time 0 (or mod 0) (or hod 0)
21975 (nth 1 date) (nth 0 date) (nth 2 date))))))
21976 (or defd (current-time))))
21978 (defun org-mark-subtree (&optional up)
21979 "Mark the current subtree.
21980 This puts point at the start of the current subtree, and mark at
21981 the end. If a numeric prefix UP is given, move up into the
21982 hierarchy of headlines by UP levels before marking the subtree."
21983 (interactive "P")
21984 (org-with-limited-levels
21985 (cond ((org-at-heading-p) (beginning-of-line))
21986 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21987 (t (outline-previous-visible-heading 1))))
21988 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21989 (if (org-called-interactively-p 'any)
21990 (call-interactively 'org-mark-element)
21991 (org-mark-element)))
21994 ;;; Indentation
21996 (defun org-indent-line ()
21997 "Indent line depending on context."
21998 (interactive)
21999 (let* ((pos (point))
22000 (itemp (org-at-item-p))
22001 (case-fold-search t)
22002 (org-drawer-regexp (or org-drawer-regexp "\000"))
22003 (inline-task-p (and (featurep 'org-inlinetask)
22004 (org-inlinetask-in-task-p)))
22005 (inline-re (and inline-task-p
22006 (org-inlinetask-outline-regexp)))
22007 column)
22008 (if (and orgstruct-is-++ (eq pos (point)))
22009 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22010 (indent-according-to-mode))
22011 (beginning-of-line 1)
22012 (cond
22013 ;; Headings
22014 ((looking-at org-outline-regexp) (setq column 0))
22015 ;; Footnote definition
22016 ((looking-at org-footnote-definition-re) (setq column 0))
22017 ;; Literal examples
22018 ((looking-at "[ \t]*:\\( \\|$\\)")
22019 (setq column (org-get-indentation))) ; do nothing
22020 ;; Lists
22021 ((ignore-errors (goto-char (org-in-item-p)))
22022 (setq column (if itemp
22023 (org-get-indentation)
22024 (org-list-item-body-column (point))))
22025 (goto-char pos))
22026 ;; Drawers
22027 ((and (looking-at "[ \t]*:END:")
22028 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22029 (save-excursion
22030 (goto-char (1- (match-beginning 1)))
22031 (setq column (current-column))))
22032 ;; Special blocks
22033 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22034 (save-excursion
22035 (re-search-backward
22036 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22037 (setq column (org-get-indentation (match-string 0))))
22038 ((and (not (looking-at "[ \t]*#\\+begin_"))
22039 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22040 (save-excursion
22041 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22042 (setq column
22043 (cond ((equal (downcase (match-string 1)) "src")
22044 ;; src blocks: let `org-edit-src-exit' handle them
22045 (org-get-indentation))
22046 ((equal (downcase (match-string 1)) "example")
22047 (max (org-get-indentation)
22048 (org-get-indentation (match-string 0))))
22050 (org-get-indentation (match-string 0))))))
22051 ;; This line has nothing special, look at the previous relevant
22052 ;; line to compute indentation
22054 (beginning-of-line 0)
22055 (while (and (not (bobp))
22056 (not (looking-at org-table-line-regexp))
22057 (not (looking-at org-drawer-regexp))
22058 ;; When point started in an inline task, do not move
22059 ;; above task starting line.
22060 (not (and inline-task-p (looking-at inline-re)))
22061 ;; Skip drawers, blocks, empty lines, verbatim,
22062 ;; comments, tables, footnotes definitions, lists,
22063 ;; inline tasks.
22064 (or (and (looking-at "[ \t]*:END:")
22065 (re-search-backward org-drawer-regexp nil t))
22066 (and (looking-at "[ \t]*#\\+end_")
22067 (re-search-backward "[ \t]*#\\+begin_"nil t))
22068 (looking-at "[ \t]*[\n:#|]")
22069 (looking-at org-footnote-definition-re)
22070 (and (not inline-task-p)
22071 (featurep 'org-inlinetask)
22072 (org-inlinetask-in-task-p)
22073 (or (org-inlinetask-goto-beginning) t))))
22074 (beginning-of-line 0))
22075 (cond
22076 ;; There was a list item above.
22077 ((ignore-errors (goto-char (org-in-item-p)))
22078 (goto-char (org-list-get-top-point (org-list-struct)))
22079 (setq column (org-get-indentation)))
22080 ;; There was an heading above.
22081 ((looking-at "\\*+[ \t]+")
22082 (if (not org-adapt-indentation)
22083 (setq column 0)
22084 (goto-char (match-end 0))
22085 (setq column (current-column))))
22086 ;; A drawer had started and is unfinished
22087 ((looking-at org-drawer-regexp)
22088 (goto-char (1- (match-beginning 1)))
22089 (setq column (current-column)))
22090 ;; Else, nothing noticeable found: get indentation and go on.
22091 (t (setq column (org-get-indentation))))))
22092 ;; Now apply indentation and move cursor accordingly
22093 (goto-char pos)
22094 (if (<= (current-column) (current-indentation))
22095 (org-indent-line-to column)
22096 (save-excursion (org-indent-line-to column)))
22097 ;; Special polishing for properties, see `org-property-format'
22098 (setq column (current-column))
22099 (beginning-of-line 1)
22100 (if (looking-at org-property-re)
22101 (replace-match (concat (match-string 4)
22102 (format org-property-format
22103 (match-string 1) (match-string 3)))
22104 t t))
22105 (org-move-to-column column))))
22107 (defun org-indent-drawer ()
22108 "Indent the drawer at point."
22109 (interactive)
22110 (let ((p (point))
22111 (e (and (save-excursion (re-search-forward ":END:" nil t))
22112 (match-end 0)))
22113 (folded
22114 (save-excursion
22115 (end-of-line)
22116 (when (overlays-at (point))
22117 (member 'invisible (overlay-properties
22118 (car (overlays-at (point)))))))))
22119 (when folded (org-cycle))
22120 (indent-for-tab-command)
22121 (while (and (move-beginning-of-line 2) (< (point) e))
22122 (indent-for-tab-command))
22123 (goto-char p)
22124 (when folded (org-cycle)))
22125 (message "Drawer at point indented"))
22127 (defun org-indent-block ()
22128 "Indent the block at point."
22129 (interactive)
22130 (let ((p (point))
22131 (case-fold-search t)
22132 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22133 (match-end 0)))
22134 (folded
22135 (save-excursion
22136 (end-of-line)
22137 (when (overlays-at (point))
22138 (member 'invisible (overlay-properties
22139 (car (overlays-at (point)))))))))
22140 (when folded (org-cycle))
22141 (indent-for-tab-command)
22142 (while (and (move-beginning-of-line 2) (< (point) e))
22143 (indent-for-tab-command))
22144 (goto-char p)
22145 (when folded (org-cycle)))
22146 (message "Block at point indented"))
22148 (defun org-indent-region (start end)
22149 "Indent region."
22150 (interactive "r")
22151 (save-excursion
22152 (let ((line-end (org-current-line end)))
22153 (goto-char start)
22154 (while (< (org-current-line) line-end)
22155 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22156 (t (call-interactively 'org-indent-line)))
22157 (move-beginning-of-line 2)))))
22160 ;;; Filling
22162 ;; We use our own fill-paragraph and auto-fill functions.
22164 ;; `org-fill-paragraph' relies on adaptive filling and context
22165 ;; checking. Appropriate `fill-prefix' is computed with
22166 ;; `org-adaptive-fill-function'.
22168 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22169 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22170 ;; `org-adaptive-fill-function' value. Internally,
22171 ;; `org-comment-line-break-function' breaks the line.
22173 ;; `org-setup-filling' installs filling and auto-filling related
22174 ;; variables during `org-mode' initialization.
22176 (defvar org-element-paragraph-separate) ; org-element.el
22177 (defun org-setup-filling ()
22178 (require 'org-element)
22179 ;; Prevent auto-fill from inserting unwanted new items.
22180 (when (boundp 'fill-nobreak-predicate)
22181 (org-set-local
22182 'fill-nobreak-predicate
22183 (org-uniquify
22184 (append fill-nobreak-predicate
22185 '(org-fill-line-break-nobreak-p
22186 org-fill-paragraph-with-timestamp-nobreak-p)))))
22187 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22188 (org-set-local 'paragraph-start paragraph-ending)
22189 (org-set-local 'paragraph-separate paragraph-ending))
22190 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22191 (org-set-local 'auto-fill-inhibit-regexp nil)
22192 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22193 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22194 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22196 (defun org-fill-line-break-nobreak-p ()
22197 "Non-nil when a new line at point would create an Org line break."
22198 (save-excursion
22199 (skip-chars-backward "[ \t]")
22200 (skip-chars-backward "\\\\")
22201 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22203 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22204 "Non-nil when a new line at point would split a timestamp."
22205 (and (org-at-timestamp-p t)
22206 (not (looking-at org-ts-regexp-both))))
22208 (declare-function message-in-body-p "message" ())
22209 (defvar orgtbl-line-start-regexp) ; From org-table.el
22210 (defun org-adaptive-fill-function ()
22211 "Compute a fill prefix for the current line.
22212 Return fill prefix, as a string, or nil if current line isn't
22213 meant to be filled. For convenience, if `adaptive-fill-regexp'
22214 matches in paragraphs or comments, use it."
22215 (catch 'exit
22216 (when (derived-mode-p 'message-mode)
22217 (save-excursion
22218 (beginning-of-line)
22219 (cond ((or (not (message-in-body-p))
22220 (looking-at orgtbl-line-start-regexp))
22221 (throw 'exit nil))
22222 ((looking-at message-cite-prefix-regexp)
22223 (throw 'exit (match-string-no-properties 0)))
22224 ((looking-at org-outline-regexp)
22225 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22226 (org-with-wide-buffer
22227 (let* ((p (line-beginning-position))
22228 (element (save-excursion
22229 (beginning-of-line)
22230 (or (ignore-errors (org-element-at-point))
22231 (user-error "An element cannot be parsed line %d"
22232 (line-number-at-pos (point))))))
22233 (type (org-element-type element))
22234 (post-affiliated (org-element-property :post-affiliated element)))
22235 (unless (and post-affiliated (< p post-affiliated))
22236 (case type
22237 (comment
22238 (save-excursion
22239 (beginning-of-line)
22240 (looking-at "[ \t]*")
22241 (concat (match-string 0) "# ")))
22242 (footnote-definition "")
22243 ((item plain-list)
22244 (make-string (org-list-item-body-column
22245 (or post-affiliated
22246 (org-element-property :begin element)))
22247 ? ))
22248 (paragraph
22249 ;; Fill prefix is usually the same as the current line,
22250 ;; unless the paragraph is at the beginning of an item.
22251 (let ((parent (org-element-property :parent element)))
22252 (save-excursion
22253 (beginning-of-line)
22254 (cond ((eq (org-element-type parent) 'item)
22255 (make-string (org-list-item-body-column
22256 (org-element-property :begin parent))
22257 ? ))
22258 ((and adaptive-fill-regexp
22259 ;; Locally disable
22260 ;; `adaptive-fill-function' to let
22261 ;; `fill-context-prefix' handle
22262 ;; `adaptive-fill-regexp' variable.
22263 (let (adaptive-fill-function)
22264 (fill-context-prefix
22265 post-affiliated
22266 (org-element-property :end element)))))
22267 ((looking-at "[ \t]+") (match-string 0))
22268 (t "")))))
22269 (comment-block
22270 ;; Only fill contents if P is within block boundaries.
22271 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22272 (forward-line)
22273 (point)))
22274 (cend (save-excursion
22275 (goto-char (org-element-property :end element))
22276 (skip-chars-backward " \r\t\n")
22277 (line-beginning-position))))
22278 (when (and (>= p cbeg) (< p cend))
22279 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22280 (match-string 0)
22281 ""))))))))))
22283 (declare-function message-goto-body "message" ())
22284 (defvar message-cite-prefix-regexp) ; From message.el
22285 (defun org-fill-paragraph (&optional justify)
22286 "Fill element at point, when applicable.
22288 This function only applies to comment blocks, comments, example
22289 blocks and paragraphs. Also, as a special case, re-align table
22290 when point is at one.
22292 If JUSTIFY is non-nil (interactively, with prefix argument),
22293 justify as well. If `sentence-end-double-space' is non-nil, then
22294 period followed by one space does not end a sentence, so don't
22295 break a line there. The variable `fill-column' controls the
22296 width for filling.
22298 For convenience, when point is at a plain list, an item or
22299 a footnote definition, try to fill the first paragraph within."
22300 (interactive)
22301 (if (and (derived-mode-p 'message-mode)
22302 (or (not (message-in-body-p))
22303 (save-excursion (move-beginning-of-line 1)
22304 (looking-at message-cite-prefix-regexp))))
22305 ;; First ensure filling is correct in message-mode.
22306 (let ((fill-paragraph-function
22307 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22308 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22309 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22310 (paragraph-separate
22311 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22312 (fill-paragraph nil))
22313 (with-syntax-table org-mode-transpose-word-syntax-table
22314 ;; Move to end of line in order to get the first paragraph
22315 ;; within a plain list or a footnote definition.
22316 (let ((element (save-excursion
22317 (end-of-line)
22318 (or (ignore-errors (org-element-at-point))
22319 (user-error "An element cannot be parsed line %d"
22320 (line-number-at-pos (point)))))))
22321 ;; First check if point is in a blank line at the beginning of
22322 ;; the buffer. In that case, ignore filling.
22323 (case (org-element-type element)
22324 ;; Use major mode filling function is src blocks.
22325 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22326 ;; Align Org tables, leave table.el tables as-is.
22327 (table-row (org-table-align) t)
22328 (table
22329 (when (eq (org-element-property :type element) 'org)
22330 (save-excursion
22331 (goto-char (org-element-property :post-affiliated element))
22332 (org-table-align)))
22334 (paragraph
22335 ;; Paragraphs may contain `line-break' type objects.
22336 (let ((beg (max (point-min)
22337 (org-element-property :contents-begin element)))
22338 (end (min (point-max)
22339 (org-element-property :contents-end element))))
22340 ;; Do nothing if point is at an affiliated keyword.
22341 (if (< (line-end-position) beg) t
22342 (when (derived-mode-p 'message-mode)
22343 ;; In `message-mode', do not fill following citation
22344 ;; in current paragraph nor text before message body.
22345 (let ((body-start (save-excursion (message-goto-body))))
22346 (when body-start (setq beg (max body-start beg))))
22347 (when (save-excursion
22348 (re-search-forward
22349 (concat "^" message-cite-prefix-regexp) end t))
22350 (setq end (match-beginning 0))))
22351 ;; Fill paragraph, taking line breaks into account.
22352 ;; For that, slice the paragraph using line breaks as
22353 ;; separators, and fill the parts in reverse order to
22354 ;; avoid messing with markers.
22355 (save-excursion
22356 (goto-char end)
22357 (mapc
22358 (lambda (pos)
22359 (fill-region-as-paragraph pos (point) justify)
22360 (goto-char pos))
22361 ;; Find the list of ending positions for line breaks
22362 ;; in the current paragraph. Add paragraph
22363 ;; beginning to include first slice.
22364 (nreverse
22365 (cons beg
22366 (org-element-map
22367 (org-element--parse-objects
22368 beg end nil (org-element-restriction 'paragraph))
22369 'line-break
22370 (lambda (lb) (org-element-property :end lb)))))))
22371 t)))
22372 ;; Contents of `comment-block' type elements should be
22373 ;; filled as plain text, but only if point is within block
22374 ;; markers.
22375 (comment-block
22376 (let* ((case-fold-search t)
22377 (beg (save-excursion
22378 (goto-char (org-element-property :begin element))
22379 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22380 (forward-line)
22381 (point)))
22382 (end (save-excursion
22383 (goto-char (org-element-property :end element))
22384 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22385 (line-beginning-position))))
22386 (if (or (< (point) beg) (> (point) end)) t
22387 (fill-region-as-paragraph
22388 (save-excursion (end-of-line)
22389 (re-search-backward "^[ \t]*$" beg 'move)
22390 (line-beginning-position))
22391 (save-excursion (beginning-of-line)
22392 (re-search-forward "^[ \t]*$" end 'move)
22393 (line-beginning-position))
22394 justify))))
22395 ;; Fill comments.
22396 (comment
22397 (let ((begin (org-element-property :post-affiliated element))
22398 (end (org-element-property :end element)))
22399 (when (and (>= (point) begin) (<= (point) end))
22400 (let ((begin (save-excursion
22401 (end-of-line)
22402 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22403 (progn (forward-line) (point))
22404 begin)))
22405 (end (save-excursion
22406 (end-of-line)
22407 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22408 (1- (line-beginning-position))
22409 (skip-chars-backward " \r\t\n")
22410 (line-end-position)))))
22411 ;; Do not fill comments when at a blank line.
22412 (when (> end begin)
22413 (let ((fill-prefix
22414 (save-excursion
22415 (beginning-of-line)
22416 (looking-at "[ \t]*#")
22417 (let ((comment-prefix (match-string 0)))
22418 (goto-char (match-end 0))
22419 (if (looking-at adaptive-fill-regexp)
22420 (concat comment-prefix (match-string 0))
22421 (concat comment-prefix " "))))))
22422 (save-excursion
22423 (fill-region-as-paragraph begin end justify))))))
22425 ;; Ignore every other element.
22426 (otherwise t))))))
22428 (defun org-auto-fill-function ()
22429 "Auto-fill function."
22430 ;; Check if auto-filling is meaningful.
22431 (let ((fc (current-fill-column)))
22432 (when (and fc (> (current-column) fc))
22433 (let* ((fill-prefix (org-adaptive-fill-function))
22434 ;; Enforce empty fill prefix, if required. Otherwise, it
22435 ;; will be computed again.
22436 (adaptive-fill-mode (not (equal fill-prefix ""))))
22437 (when fill-prefix (do-auto-fill))))))
22439 (defun org-comment-line-break-function (&optional soft)
22440 "Break line at point and indent, continuing comment if within one.
22441 The inserted newline is marked hard if variable
22442 `use-hard-newlines' is true, unless optional argument SOFT is
22443 non-nil."
22444 (if soft (insert-and-inherit ?\n) (newline 1))
22445 (save-excursion (forward-char -1) (delete-horizontal-space))
22446 (delete-horizontal-space)
22447 (indent-to-left-margin)
22448 (insert-before-markers-and-inherit fill-prefix))
22451 ;;; Comments
22453 ;; Org comments syntax is quite complex. It requires the entire line
22454 ;; to be just a comment. Also, even with the right syntax at the
22455 ;; beginning of line, some some elements (i.e. verse-block or
22456 ;; example-block) don't accept comments. Usual Emacs comment commands
22457 ;; cannot cope with those requirements. Therefore, Org replaces them.
22459 ;; Org still relies on `comment-dwim', but cannot trust
22460 ;; `comment-only-p'. So, `comment-region-function' and
22461 ;; `uncomment-region-function' both point
22462 ;; to`org-comment-or-uncomment-region'. Eventually,
22463 ;; `org-insert-comment' takes care of insertion of comments at the
22464 ;; beginning of line.
22466 ;; `org-setup-comments-handling' install comments related variables
22467 ;; during `org-mode' initialization.
22469 (defun org-setup-comments-handling ()
22470 (interactive)
22471 (org-set-local 'comment-use-syntax nil)
22472 (org-set-local 'comment-start "# ")
22473 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22474 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22475 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22476 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22478 (defun org-insert-comment ()
22479 "Insert an empty comment above current line.
22480 If the line is empty, insert comment at its beginning."
22481 (beginning-of-line)
22482 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22483 (org-indent-line)
22484 (insert "# "))
22486 (defvar comment-empty-lines) ; From newcomment.el.
22487 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22488 "Comment or uncomment each non-blank line in the region.
22489 Uncomment each non-blank line between BEG and END if it only
22490 contains commented lines. Otherwise, comment them."
22491 (save-restriction
22492 ;; Restrict region
22493 (narrow-to-region (save-excursion (goto-char beg)
22494 (skip-chars-forward " \r\t\n" end)
22495 (line-beginning-position))
22496 (save-excursion (goto-char end)
22497 (skip-chars-backward " \r\t\n" beg)
22498 (line-end-position)))
22499 (let ((uncommentp
22500 ;; UNCOMMENTP is non-nil when every non blank line between
22501 ;; BEG and END is a comment.
22502 (save-excursion
22503 (goto-char (point-min))
22504 (while (and (not (eobp))
22505 (let ((element (org-element-at-point)))
22506 (and (eq (org-element-type element) 'comment)
22507 (goto-char (min (point-max)
22508 (org-element-property
22509 :end element)))))))
22510 (eobp))))
22511 (if uncommentp
22512 ;; Only blank lines and comments in region: uncomment it.
22513 (save-excursion
22514 (goto-char (point-min))
22515 (while (not (eobp))
22516 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22517 (replace-match "" nil nil nil 1))
22518 (forward-line)))
22519 ;; Comment each line in region.
22520 (let ((min-indent (point-max)))
22521 ;; First find the minimum indentation across all lines.
22522 (save-excursion
22523 (goto-char (point-min))
22524 (while (and (not (eobp)) (not (zerop min-indent)))
22525 (unless (looking-at "[ \t]*$")
22526 (setq min-indent (min min-indent (current-indentation))))
22527 (forward-line)))
22528 ;; Then loop over all lines.
22529 (save-excursion
22530 (goto-char (point-min))
22531 (while (not (eobp))
22532 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22533 ;; Don't get fooled by invisible text (e.g. link path)
22534 ;; when moving to column MIN-INDENT.
22535 (let ((buffer-invisibility-spec nil))
22536 (org-move-to-column min-indent t))
22537 (insert comment-start))
22538 (forward-line))))))))
22541 ;;; Planning
22543 ;; This section contains tools to operate on timestamp objects, as
22544 ;; returned by, e.g. `org-element-context'.
22546 (defun org-timestamp-has-time-p (timestamp)
22547 "Non-nil when TIMESTAMP has a time specified."
22548 (org-element-property :hour-start timestamp))
22550 (defun org-timestamp-format (timestamp format &optional end utc)
22551 "Format a TIMESTAMP element into a string.
22553 FORMAT is a format specifier to be passed to
22554 `format-time-string'.
22556 When optional argument END is non-nil, use end of date-range or
22557 time-range, if possible.
22559 When optional argument UTC is non-nil, time will be expressed as
22560 Universal Time."
22561 (format-time-string
22562 format
22563 (apply 'encode-time
22564 (cons 0
22565 (mapcar
22566 (lambda (prop) (or (org-element-property prop timestamp) 0))
22567 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22568 '(:minute-start :hour-start :day-start :month-start
22569 :year-start)))))
22570 utc))
22572 (defun org-timestamp-split-range (timestamp &optional end)
22573 "Extract a timestamp object from a date or time range.
22575 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22576 the end of the range. Otherwise, extract its start.
22578 Return a new timestamp object sharing the same parent as
22579 TIMESTAMP."
22580 (let ((type (org-element-property :type timestamp)))
22581 (if (memq type '(active inactive diary)) timestamp
22582 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22583 ;; Set new type.
22584 (org-element-put-property
22585 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22586 ;; Copy start properties over end properties if END is
22587 ;; non-nil. Otherwise, copy end properties over `start' ones.
22588 (let ((p-alist '((:minute-start . :minute-end)
22589 (:hour-start . :hour-end)
22590 (:day-start . :day-end)
22591 (:month-start . :month-end)
22592 (:year-start . :year-end))))
22593 (dolist (p-cell p-alist)
22594 (org-element-put-property
22595 split-ts
22596 (funcall (if end 'car 'cdr) p-cell)
22597 (org-element-property
22598 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22599 ;; Eventually refresh `:raw-value'.
22600 (org-element-put-property split-ts :raw-value nil)
22601 (org-element-put-property
22602 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22604 (defun org-timestamp-translate (timestamp &optional boundary)
22605 "Apply `org-translate-time' on a TIMESTAMP object.
22606 When optional argument BOUNDARY is non-nil, it is either the
22607 symbol `start' or `end'. In this case, only translate the
22608 starting or ending part of TIMESTAMP if it is a date or time
22609 range. Otherwise, translate both parts."
22610 (if (and (not boundary)
22611 (memq (org-element-property :type timestamp)
22612 '(active-range inactive-range)))
22613 (concat
22614 (org-translate-time
22615 (org-element-property :raw-value
22616 (org-timestamp-split-range timestamp)))
22617 "--"
22618 (org-translate-time
22619 (org-element-property :raw-value
22620 (org-timestamp-split-range timestamp t))))
22621 (org-translate-time
22622 (org-element-property
22623 :raw-value
22624 (if (not boundary) timestamp
22625 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22629 ;;; Other stuff.
22631 (defun org-toggle-fixed-width-section (arg)
22632 "Toggle the fixed-width export.
22633 If there is no active region, the QUOTE keyword at the current headline is
22634 inserted or removed. When present, it causes the text between this headline
22635 and the next to be exported as fixed-width text, and unmodified.
22636 If there is an active region, this command adds or removes a colon as the
22637 first character of this line. If the first character of a line is a colon,
22638 this line is also exported in fixed-width font."
22639 (interactive "P")
22640 (let* ((cc 0)
22641 (regionp (org-region-active-p))
22642 (beg (if regionp (region-beginning) (point)))
22643 (end (if regionp (region-end)))
22644 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22645 (case-fold-search nil)
22646 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22647 off)
22648 (if regionp
22649 (save-excursion
22650 (goto-char beg)
22651 (setq cc (current-column))
22652 (beginning-of-line 1)
22653 (setq off (looking-at re))
22654 (while (> nlines 0)
22655 (setq nlines (1- nlines))
22656 (beginning-of-line 1)
22657 (cond
22658 (arg
22659 (org-move-to-column cc t)
22660 (insert ": \n")
22661 (forward-line -1))
22662 ((and off (looking-at re))
22663 (replace-match "" t t nil 1))
22664 ((not off) (org-move-to-column cc t) (insert ": ")))
22665 (forward-line 1)))
22666 (save-excursion
22667 (org-back-to-heading)
22668 (cond
22669 ((looking-at (format org-heading-keyword-regexp-format
22670 org-quote-string))
22671 (goto-char (match-end 1))
22672 (looking-at (concat " +" org-quote-string))
22673 (replace-match "" t t)
22674 (when (eolp) (insert " ")))
22675 ((looking-at org-outline-regexp)
22676 (goto-char (match-end 0))
22677 (insert org-quote-string " ")))))))
22679 (defun org-reftex-citation ()
22680 "Use reftex-citation to insert a citation into the buffer.
22681 This looks for a line like
22683 #+BIBLIOGRAPHY: foo plain option:-d
22685 and derives from it that foo.bib is the bibliography file relevant
22686 for this document. It then installs the necessary environment for RefTeX
22687 to work in this buffer and calls `reftex-citation' to insert a citation
22688 into the buffer.
22690 Export of such citations to both LaTeX and HTML is handled by the contributed
22691 package ox-bibtex by Taru Karttunen."
22692 (interactive)
22693 (let ((reftex-docstruct-symbol 'rds)
22694 (reftex-cite-format "\\cite{%l}")
22695 rds bib)
22696 (save-excursion
22697 (save-restriction
22698 (widen)
22699 (let ((case-fold-search t)
22700 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22701 (if (not (save-excursion
22702 (or (re-search-forward re nil t)
22703 (re-search-backward re nil t))))
22704 (error "No bibliography defined in file")
22705 (setq bib (concat (match-string 1) ".bib")
22706 rds (list (list 'bib bib)))))))
22707 (call-interactively 'reftex-citation)))
22709 ;;;; Functions extending outline functionality
22711 (defun org-beginning-of-line (&optional arg)
22712 "Go to the beginning of the current line. If that is invisible, continue
22713 to a visible line beginning. This makes the function of C-a more intuitive.
22714 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22715 first attempt, and only move to after the tags when the cursor is already
22716 beyond the end of the headline."
22717 (interactive "P")
22718 (let ((pos (point))
22719 (special (if (consp org-special-ctrl-a/e)
22720 (car org-special-ctrl-a/e)
22721 org-special-ctrl-a/e))
22722 deactivate-mark refpos)
22723 (if (org-bound-and-true-p visual-line-mode)
22724 (beginning-of-visual-line 1)
22725 (beginning-of-line 1))
22726 (if (and arg (fboundp 'move-beginning-of-line))
22727 (call-interactively 'move-beginning-of-line)
22728 (if (bobp)
22730 (backward-char 1)
22731 (if (org-truely-invisible-p)
22732 (while (and (not (bobp)) (org-truely-invisible-p))
22733 (backward-char 1)
22734 (beginning-of-line 1))
22735 (forward-char 1))))
22736 (when special
22737 (cond
22738 ((and (looking-at org-complex-heading-regexp)
22739 (= (char-after (match-end 1)) ?\ ))
22740 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22741 (point-at-eol)))
22742 (goto-char
22743 (if (eq special t)
22744 (cond ((> pos refpos) refpos)
22745 ((= pos (point)) refpos)
22746 (t (point)))
22747 (cond ((> pos (point)) (point))
22748 ((not (eq last-command this-command)) (point))
22749 (t refpos)))))
22750 ((org-at-item-p)
22751 ;; Being at an item and not looking at an the item means point
22752 ;; was previously moved to beginning of a visual line, which
22753 ;; doesn't contain the item. Therefore, do nothing special,
22754 ;; just stay here.
22755 (when (looking-at org-list-full-item-re)
22756 ;; Set special position at first white space character after
22757 ;; bullet, and check-box, if any.
22758 (let ((after-bullet
22759 (let ((box (match-end 3)))
22760 (if (not box) (match-end 1)
22761 (let ((after (char-after box)))
22762 (if (and after (= after ? )) (1+ box) box))))))
22763 ;; Special case: Move point to special position when
22764 ;; currently after it or at beginning of line.
22765 (if (eq special t)
22766 (when (or (> pos after-bullet) (= (point) pos))
22767 (goto-char after-bullet))
22768 ;; Reversed case: Move point to special position when
22769 ;; point was already at beginning of line and command is
22770 ;; repeated.
22771 (when (and (= (point) pos) (eq last-command this-command))
22772 (goto-char after-bullet))))))))
22773 (org-no-warnings
22774 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22775 (setq disable-point-adjustment
22776 (or (not (invisible-p (point)))
22777 (not (invisible-p (max (point-min) (1- (point))))))))
22779 (defun org-end-of-line (&optional arg)
22780 "Go to the end of the line.
22781 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22782 tags on the first attempt, and only move to after the tags when
22783 the cursor is already beyond the end of the headline."
22784 (interactive "P")
22785 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22786 org-special-ctrl-a/e))
22787 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22788 'end-of-visual-line)
22789 ((fboundp 'move-end-of-line) 'move-end-of-line)
22790 (t 'end-of-line)))
22791 deactivate-mark)
22792 (if (or (not special) arg) (call-interactively move-fun)
22793 (let* ((element (save-excursion (beginning-of-line)
22794 (org-element-at-point)))
22795 (type (org-element-type element)))
22796 (cond
22797 ((memq type '(headline inlinetask))
22798 (let ((pos (point)))
22799 (beginning-of-line 1)
22800 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22801 (if (eq special t)
22802 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22803 (goto-char (match-beginning 1))
22804 (goto-char (match-end 0)))
22805 (if (or (< pos (match-end 0))
22806 (not (eq this-command last-command)))
22807 (goto-char (match-end 0))
22808 (goto-char (match-beginning 1))))
22809 (call-interactively move-fun))))
22810 ((org-element-property :hiddenp element)
22811 ;; If element is hidden, `move-end-of-line' would put point
22812 ;; after it. Use `end-of-line' to stay on current line.
22813 (call-interactively 'end-of-line))
22814 (t (call-interactively move-fun)))))
22815 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22816 (setq disable-point-adjustment
22817 (or (not (invisible-p (point)))
22818 (not (invisible-p (max (point-min) (1- (point))))))))
22820 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22821 (define-key org-mode-map "\C-e" 'org-end-of-line)
22823 (defun org-backward-sentence (&optional arg)
22824 "Go to beginning of sentence, or beginning of table field.
22825 This will call `backward-sentence' or `org-table-beginning-of-field',
22826 depending on context."
22827 (interactive "P")
22828 (cond
22829 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22830 (t (call-interactively 'backward-sentence))))
22832 (defun org-forward-sentence (&optional arg)
22833 "Go to end of sentence, or end of table field.
22834 This will call `forward-sentence' or `org-table-end-of-field',
22835 depending on context."
22836 (interactive "P")
22837 (cond
22838 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22839 (t (call-interactively 'forward-sentence))))
22841 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22842 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22844 (defun org-kill-line (&optional arg)
22845 "Kill line, to tags or end of line."
22846 (interactive "P")
22847 (cond
22848 ((or (not org-special-ctrl-k)
22849 (bolp)
22850 (not (org-at-heading-p)))
22851 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22852 org-ctrl-k-protect-subtree)
22853 (if (or (eq org-ctrl-k-protect-subtree 'error)
22854 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22855 (user-error "C-k aborted as it would kill a hidden subtree")))
22856 (call-interactively
22857 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22858 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22859 (kill-region (point) (match-beginning 1))
22860 (org-set-tags nil t))
22861 (t (kill-region (point) (point-at-eol)))))
22863 (define-key org-mode-map "\C-k" 'org-kill-line)
22865 (defun org-yank (&optional arg)
22866 "Yank. If the kill is a subtree, treat it specially.
22867 This command will look at the current kill and check if is a single
22868 subtree, or a series of subtrees[1]. If it passes the test, and if the
22869 cursor is at the beginning of a line or after the stars of a currently
22870 empty headline, then the yank is handled specially. How exactly depends
22871 on the value of the following variables, both set by default.
22873 org-yank-folded-subtrees
22874 When set, the subtree(s) will be folded after insertion, but only
22875 if doing so would now swallow text after the yanked text.
22877 org-yank-adjusted-subtrees
22878 When set, the subtree will be promoted or demoted in order to
22879 fit into the local outline tree structure, which means that the level
22880 will be adjusted so that it becomes the smaller one of the two
22881 *visible* surrounding headings.
22883 Any prefix to this command will cause `yank' to be called directly with
22884 no special treatment. In particular, a simple \\[universal-argument] prefix \
22885 will just
22886 plainly yank the text as it is.
22888 \[1] The test checks if the first non-white line is a heading
22889 and if there are no other headings with fewer stars."
22890 (interactive "P")
22891 (org-yank-generic 'yank arg))
22893 (defun org-yank-generic (command arg)
22894 "Perform some yank-like command.
22896 This function implements the behavior described in the `org-yank'
22897 documentation. However, it has been generalized to work for any
22898 interactive command with similar behavior."
22900 ;; pretend to be command COMMAND
22901 (setq this-command command)
22903 (if arg
22904 (call-interactively command)
22906 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22907 (and (org-kill-is-subtree-p)
22908 (or (bolp)
22909 (and (looking-at "[ \t]*$")
22910 (string-match
22911 "\\`\\*+\\'"
22912 (buffer-substring (point-at-bol) (point)))))))
22913 swallowp)
22914 (cond
22915 ((and subtreep org-yank-folded-subtrees)
22916 (let ((beg (point))
22917 end)
22918 (if (and subtreep org-yank-adjusted-subtrees)
22919 (org-paste-subtree nil nil 'for-yank)
22920 (call-interactively command))
22922 (setq end (point))
22923 (goto-char beg)
22924 (when (and (bolp) subtreep
22925 (not (setq swallowp
22926 (org-yank-folding-would-swallow-text beg end))))
22927 (org-with-limited-levels
22928 (or (looking-at org-outline-regexp)
22929 (re-search-forward org-outline-regexp-bol end t))
22930 (while (and (< (point) end) (looking-at org-outline-regexp))
22931 (hide-subtree)
22932 (org-cycle-show-empty-lines 'folded)
22933 (condition-case nil
22934 (outline-forward-same-level 1)
22935 (error (goto-char end))))))
22936 (when swallowp
22937 (message
22938 "Inserted text not folded because that would swallow text"))
22940 (goto-char end)
22941 (skip-chars-forward " \t\n\r")
22942 (beginning-of-line 1)
22943 (push-mark beg 'nomsg)))
22944 ((and subtreep org-yank-adjusted-subtrees)
22945 (let ((beg (point-at-bol)))
22946 (org-paste-subtree nil nil 'for-yank)
22947 (push-mark beg 'nomsg)))
22949 (call-interactively command))))))
22951 (defun org-yank-folding-would-swallow-text (beg end)
22952 "Would hide-subtree at BEG swallow any text after END?"
22953 (let (level)
22954 (org-with-limited-levels
22955 (save-excursion
22956 (goto-char beg)
22957 (when (or (looking-at org-outline-regexp)
22958 (re-search-forward org-outline-regexp-bol end t))
22959 (setq level (org-outline-level)))
22960 (goto-char end)
22961 (skip-chars-forward " \t\r\n\v\f")
22962 (if (or (eobp)
22963 (and (bolp) (looking-at org-outline-regexp)
22964 (<= (org-outline-level) level)))
22965 nil ; Nothing would be swallowed
22966 t))))) ; something would swallow
22968 (define-key org-mode-map "\C-y" 'org-yank)
22970 (defun org-truely-invisible-p ()
22971 "Check if point is at a character currently not visible.
22972 This version does not only check the character property, but also
22973 `visible-mode'."
22974 ;; Early versions of noutline don't have `outline-invisible-p'.
22975 (if (org-bound-and-true-p visible-mode)
22977 (outline-invisible-p)))
22979 (defun org-invisible-p2 ()
22980 "Check if point is at a character currently not visible."
22981 (save-excursion
22982 (if (and (eolp) (not (bobp))) (backward-char 1))
22983 ;; Early versions of noutline don't have `outline-invisible-p'.
22984 (outline-invisible-p)))
22986 (defun org-back-to-heading (&optional invisible-ok)
22987 "Call `outline-back-to-heading', but provide a better error message."
22988 (condition-case nil
22989 (outline-back-to-heading invisible-ok)
22990 (error (error "Before first headline at position %d in buffer %s"
22991 (point) (current-buffer)))))
22993 (defun org-before-first-heading-p ()
22994 "Before first heading?"
22995 (save-excursion
22996 (end-of-line)
22997 (null (re-search-backward org-outline-regexp-bol nil t))))
22999 (defun org-at-heading-p (&optional ignored)
23000 (outline-on-heading-p t))
23001 ;; Compatibility alias with Org versions < 7.8.03
23002 (defalias 'org-on-heading-p 'org-at-heading-p)
23004 (defun org-at-comment-p nil
23005 "Is cursor in a line starting with a # character?"
23006 (save-excursion
23007 (beginning-of-line)
23008 (looking-at "^#")))
23010 (defun org-at-drawer-p nil
23011 "Is cursor at a drawer keyword?"
23012 (save-excursion
23013 (move-beginning-of-line 1)
23014 (looking-at org-drawer-regexp)))
23016 (defun org-at-block-p nil
23017 "Is cursor at a block keyword?"
23018 (save-excursion
23019 (move-beginning-of-line 1)
23020 (looking-at org-block-regexp)))
23022 (defun org-point-at-end-of-empty-headline ()
23023 "If point is at the end of an empty headline, return t, else nil.
23024 If the heading only contains a TODO keyword, it is still still considered
23025 empty."
23026 (and (looking-at "[ \t]*$")
23027 (when org-todo-line-regexp
23028 (save-excursion
23029 (beginning-of-line 1)
23030 (let ((case-fold-search nil))
23031 (looking-at org-todo-line-regexp)
23032 (string= (match-string 3) ""))))))
23034 (defun org-at-heading-or-item-p ()
23035 (or (org-at-heading-p) (org-at-item-p)))
23037 (defun org-at-target-p ()
23038 (or (org-in-regexp org-radio-target-regexp)
23039 (org-in-regexp org-target-regexp)))
23040 ;; Compatibility alias with Org versions < 7.8.03
23041 (defalias 'org-on-target-p 'org-at-target-p)
23043 (defun org-up-heading-all (arg)
23044 "Move to the heading line of which the present line is a subheading.
23045 This function considers both visible and invisible heading lines.
23046 With argument, move up ARG levels."
23047 (if (fboundp 'outline-up-heading-all)
23048 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23049 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23051 (defun org-up-heading-safe ()
23052 "Move to the heading line of which the present line is a subheading.
23053 This version will not throw an error. It will return the level of the
23054 headline found, or nil if no higher level is found.
23056 Also, this function will be a lot faster than `outline-up-heading',
23057 because it relies on stars being the outline starters. This can really
23058 make a significant difference in outlines with very many siblings."
23059 (let (start-level re)
23060 (org-back-to-heading t)
23061 (setq start-level (funcall outline-level))
23062 (if (equal start-level 1)
23064 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23065 (if (re-search-backward re nil t)
23066 (funcall outline-level)))))
23068 (defun org-first-sibling-p ()
23069 "Is this heading the first child of its parents?"
23070 (interactive)
23071 (let ((re org-outline-regexp-bol)
23072 level l)
23073 (unless (org-at-heading-p t)
23074 (user-error "Not at a heading"))
23075 (setq level (funcall outline-level))
23076 (save-excursion
23077 (if (not (re-search-backward re nil t))
23079 (setq l (funcall outline-level))
23080 (< l level)))))
23082 (defun org-goto-sibling (&optional previous)
23083 "Goto the next sibling, even if it is invisible.
23084 When PREVIOUS is set, go to the previous sibling instead. Returns t
23085 when a sibling was found. When none is found, return nil and don't
23086 move point."
23087 (let ((fun (if previous 're-search-backward 're-search-forward))
23088 (pos (point))
23089 (re org-outline-regexp-bol)
23090 level l)
23091 (when (condition-case nil (org-back-to-heading t) (error nil))
23092 (setq level (funcall outline-level))
23093 (catch 'exit
23094 (or previous (forward-char 1))
23095 (while (funcall fun re nil t)
23096 (setq l (funcall outline-level))
23097 (when (< l level) (goto-char pos) (throw 'exit nil))
23098 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23099 (goto-char pos)
23100 nil))))
23102 (defun org-show-siblings ()
23103 "Show all siblings of the current headline."
23104 (save-excursion
23105 (while (org-goto-sibling) (org-flag-heading nil)))
23106 (save-excursion
23107 (while (org-goto-sibling 'previous)
23108 (org-flag-heading nil))))
23110 (defun org-goto-first-child ()
23111 "Goto the first child, even if it is invisible.
23112 Return t when a child was found. Otherwise don't move point and
23113 return nil."
23114 (let (level (pos (point)) (re org-outline-regexp-bol))
23115 (when (condition-case nil (org-back-to-heading t) (error nil))
23116 (setq level (outline-level))
23117 (forward-char 1)
23118 (if (and (re-search-forward re nil t) (> (outline-level) level))
23119 (progn (goto-char (match-beginning 0)) t)
23120 (goto-char pos) nil))))
23122 (defun org-show-hidden-entry ()
23123 "Show an entry where even the heading is hidden."
23124 (save-excursion
23125 (org-show-entry)))
23127 (defun org-flag-heading (flag &optional entry)
23128 "Flag the current heading. FLAG non-nil means make invisible.
23129 When ENTRY is non-nil, show the entire entry."
23130 (save-excursion
23131 (org-back-to-heading t)
23132 ;; Check if we should show the entire entry
23133 (if entry
23134 (progn
23135 (org-show-entry)
23136 (save-excursion
23137 (and (outline-next-heading)
23138 (org-flag-heading nil))))
23139 (outline-flag-region (max (point-min) (1- (point)))
23140 (save-excursion (outline-end-of-heading) (point))
23141 flag))))
23143 (defun org-get-next-sibling ()
23144 "Move to next heading of the same level, and return point.
23145 If there is no such heading, return nil.
23146 This is like outline-next-sibling, but invisible headings are ok."
23147 (let ((level (funcall outline-level)))
23148 (outline-next-heading)
23149 (while (and (not (eobp)) (> (funcall outline-level) level))
23150 (outline-next-heading))
23151 (if (or (eobp) (< (funcall outline-level) level))
23153 (point))))
23155 (defun org-get-last-sibling ()
23156 "Move to previous heading of the same level, and return point.
23157 If there is no such heading, return nil."
23158 (let ((opoint (point))
23159 (level (funcall outline-level)))
23160 (outline-previous-heading)
23161 (when (and (/= (point) opoint) (outline-on-heading-p t))
23162 (while (and (> (funcall outline-level) level)
23163 (not (bobp)))
23164 (outline-previous-heading))
23165 (if (< (funcall outline-level) level)
23167 (point)))))
23169 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23170 "Goto to the end of a subtree."
23171 ;; This contains an exact copy of the original function, but it uses
23172 ;; `org-back-to-heading', to make it work also in invisible
23173 ;; trees. And is uses an invisible-ok argument.
23174 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23175 ;; Furthermore, when used inside Org, finding the end of a large subtree
23176 ;; with many children and grandchildren etc, this can be much faster
23177 ;; than the outline version.
23178 (org-back-to-heading invisible-ok)
23179 (let ((first t)
23180 (level (funcall outline-level)))
23181 (if (and (derived-mode-p 'org-mode) (< level 1000))
23182 ;; A true heading (not a plain list item), in Org-mode
23183 ;; This means we can easily find the end by looking
23184 ;; only for the right number of stars. Using a regexp to do
23185 ;; this is so much faster than using a Lisp loop.
23186 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23187 (forward-char 1)
23188 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23189 ;; something else, do it the slow way
23190 (while (and (not (eobp))
23191 (or first (> (funcall outline-level) level)))
23192 (setq first nil)
23193 (outline-next-heading)))
23194 (unless to-heading
23195 (if (memq (preceding-char) '(?\n ?\^M))
23196 (progn
23197 ;; Go to end of line before heading
23198 (forward-char -1)
23199 (if (memq (preceding-char) '(?\n ?\^M))
23200 ;; leave blank line before heading
23201 (forward-char -1))))))
23202 (point))
23204 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23205 "Use Org version in org-mode, for dramatic speed-up."
23206 (if (derived-mode-p 'org-mode)
23207 (progn
23208 (org-end-of-subtree nil t)
23209 (unless (eobp) (backward-char 1)))
23210 ad-do-it))
23212 (defun org-end-of-meta-data-and-drawers ()
23213 "Jump to the first text after meta data and drawers in the current entry.
23214 This will move over empty lines, lines with planning time stamps,
23215 clocking lines, and drawers."
23216 (org-back-to-heading t)
23217 (let ((end (save-excursion (outline-next-heading) (point)))
23218 (re (concat "\\(" org-drawer-regexp "\\)"
23219 "\\|" "[ \t]*" org-keyword-time-regexp)))
23220 (forward-line 1)
23221 (while (re-search-forward re end t)
23222 (if (not (match-end 1))
23223 ;; empty or planning line
23224 (forward-line 1)
23225 ;; a drawer, find the end
23226 (re-search-forward "^[ \t]*:END:" end 'move)
23227 (forward-line 1)))
23228 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23229 (point)))
23231 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23232 "Move forward to the ARG'th subheading at same level as this one.
23233 Stop at the first and last subheadings of a superior heading.
23234 Normally this only looks at visible headings, but when INVISIBLE-OK is
23235 non-nil it will also look at invisible ones."
23236 (interactive "p")
23237 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23238 (if (and arg (< arg 0))
23239 (goto-char (point-min))
23240 (outline-next-heading))
23241 (org-at-heading-p)
23242 (let ((level (- (match-end 0) (match-beginning 0) 1))
23243 (f (if (and arg (< arg 0))
23244 're-search-backward
23245 're-search-forward))
23246 (count (if arg (abs arg) 1))
23247 (result (point)))
23248 (while (and (prog1 (> count 0)
23249 (forward-char (if (and arg (< arg 0)) -1 1)))
23250 (funcall f org-outline-regexp-bol nil 'move))
23251 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23252 (cond ((< l level) (setq count 0))
23253 ((and (= l level)
23254 (or invisible-ok
23255 (progn
23256 (goto-char (line-beginning-position))
23257 (not (outline-invisible-p)))))
23258 (setq count (1- count))
23259 (when (eq l level)
23260 (setq result (point)))))))
23261 (goto-char result))
23262 (beginning-of-line 1)))
23264 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23265 "Move backward to the ARG'th subheading at same level as this one.
23266 Stop at the first and last subheadings of a superior heading."
23267 (interactive "p")
23268 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23270 (defun org-next-block (arg &optional backward block-regexp)
23271 "Jump to the next block.
23272 With a prefix argument ARG, jump forward ARG many source blocks.
23273 When BACKWARD is non-nil, jump to the previous block.
23274 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23275 (interactive "p")
23276 (let ((re (or block-regexp org-block-regexp))
23277 (re-search-fn (or (and backward 're-search-backward)
23278 're-search-forward)))
23279 (if (looking-at re) (forward-char 1))
23280 (condition-case nil
23281 (funcall re-search-fn re nil nil arg)
23282 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23283 (goto-char (match-beginning 0)) (org-show-context)))
23285 (defun org-previous-block (arg &optional block-regexp)
23286 "Jump to the previous block.
23287 With a prefix argument ARG, jump backward ARG many source blocks.
23288 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23289 (interactive "p")
23290 (org-next-block arg t block-regexp))
23292 (defun org-forward-paragraph ()
23293 "Move forward to beginning of next paragraph or equivalent.
23295 The function moves point to the beginning of the next visible
23296 structural element, which can be a paragraph, a table, a list
23297 item, etc. It also provides some special moves for convenience:
23299 - On an affiliated keyword, jump to the beginning of the
23300 relative element.
23301 - On an item or a footnote definition, move to the second
23302 element inside, if any.
23303 - On a table or a property drawer, jump after it.
23304 - On a verse or source block, stop after blank lines."
23305 (interactive)
23306 (when (eobp) (user-error "Cannot move further down"))
23307 (let* ((deactivate-mark nil)
23308 (element (org-element-at-point))
23309 (type (org-element-type element))
23310 (post-affiliated (org-element-property :post-affiliated element))
23311 (contents-begin (org-element-property :contents-begin element))
23312 (contents-end (org-element-property :contents-end element))
23313 (end (let ((end (org-element-property :end element)) (parent element))
23314 (while (and (setq parent (org-element-property :parent parent))
23315 (= (org-element-property :contents-end parent) end))
23316 (setq end (org-element-property :end parent)))
23317 end)))
23318 (cond ((not element)
23319 (skip-chars-forward " \r\t\n")
23320 (or (eobp) (beginning-of-line)))
23321 ;; On affiliated keywords, move to element's beginning.
23322 ((and post-affiliated (< (point) post-affiliated))
23323 (goto-char post-affiliated))
23324 ;; At a table row, move to the end of the table. Similarly,
23325 ;; at a node property, move to the end of the property
23326 ;; drawer.
23327 ((memq type '(node-property table-row))
23328 (goto-char (org-element-property
23329 :end (org-element-property :parent element))))
23330 ((memq type '(property-drawer table)) (goto-char end))
23331 ;; Consider blank lines as separators in verse and source
23332 ;; blocks to ease editing.
23333 ((memq type '(src-block verse-block))
23334 (when (eq type 'src-block)
23335 (setq contents-end
23336 (save-excursion (goto-char end)
23337 (skip-chars-backward " \r\t\n")
23338 (line-beginning-position))))
23339 (beginning-of-line)
23340 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23341 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23342 (goto-char end)
23343 (skip-chars-forward " \r\t\n")
23344 (if (= (point) contents-end) (goto-char end)
23345 (beginning-of-line))))
23346 ;; With no contents, just skip element.
23347 ((not contents-begin) (goto-char end))
23348 ;; If contents are invisible, skip the element altogether.
23349 ((outline-invisible-p (line-end-position))
23350 (case type
23351 (headline
23352 (org-with-limited-levels (outline-next-visible-heading 1)))
23353 ;; At a plain list, make sure we move to the next item
23354 ;; instead of skipping the whole list.
23355 (plain-list (forward-char)
23356 (org-forward-paragraph))
23357 (otherwise (goto-char end))))
23358 ((>= (point) contents-end) (goto-char end))
23359 ((>= (point) contents-begin)
23360 ;; This can only happen on paragraphs and plain lists.
23361 (case type
23362 (paragraph (goto-char end))
23363 ;; At a plain list, try to move to second element in
23364 ;; first item, if possible.
23365 (plain-list (end-of-line)
23366 (org-forward-paragraph))))
23367 ;; When contents start on the middle of a line (e.g. in
23368 ;; items and footnote definitions), try to reach first
23369 ;; element starting after current line.
23370 ((> (line-end-position) contents-begin)
23371 (end-of-line)
23372 (org-forward-paragraph))
23373 (t (goto-char contents-begin)))))
23375 (defun org-backward-paragraph ()
23376 "Move backward to start of previous paragraph or equivalent.
23378 The function moves point to the beginning of the current
23379 structural element, which can be a paragraph, a table, a list
23380 item, etc., or to the beginning of the previous visible one if
23381 point is already there. It also provides some special moves for
23382 convenience:
23384 - On an affiliated keyword, jump to the first one.
23385 - On a table or a property drawer, move to its beginning.
23386 - On a verse or source block, stop before blank lines."
23387 (interactive)
23388 (when (bobp) (user-error "Cannot move further up"))
23389 (let* ((deactivate-mark nil)
23390 (element (org-element-at-point))
23391 (type (org-element-type element))
23392 (contents-begin (org-element-property :contents-begin element))
23393 (contents-end (org-element-property :contents-end element))
23394 (post-affiliated (org-element-property :post-affiliated element))
23395 (begin (org-element-property :begin element)))
23396 (cond
23397 ((not element) (goto-char (point-min)))
23398 ((= (point) begin)
23399 (backward-char)
23400 (org-backward-paragraph))
23401 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23402 ((memq type '(node-property table-row))
23403 (goto-char (org-element-property
23404 :post-affiliated (org-element-property :parent element))))
23405 ((memq type '(property-drawer table)) (goto-char begin))
23406 ((memq type '(src-block verse-block))
23407 (when (eq type 'src-block)
23408 (setq contents-begin
23409 (save-excursion (goto-char begin) (forward-line) (point))))
23410 (if (= (point) contents-begin) (goto-char post-affiliated)
23411 ;; Inside a verse block, see blank lines as paragraph
23412 ;; separators.
23413 (let ((origin (point)))
23414 (skip-chars-backward " \r\t\n" contents-begin)
23415 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23416 (skip-chars-forward " \r\t\n" origin)
23417 (if (= (point) origin) (goto-char contents-begin)
23418 (beginning-of-line))))))
23419 ((not contents-begin) (goto-char (or post-affiliated begin)))
23420 ((eq type 'paragraph)
23421 (goto-char contents-begin)
23422 ;; When at first paragraph in an item or a footnote definition,
23423 ;; move directly to beginning of line.
23424 (let ((parent-contents
23425 (org-element-property
23426 :contents-begin (org-element-property :parent element))))
23427 (when (and parent-contents (= parent-contents contents-begin))
23428 (beginning-of-line))))
23429 ;; At the end of a greater element, move to the beginning of the
23430 ;; last element within.
23431 ((>= (point) contents-end)
23432 (goto-char (1- contents-end))
23433 (org-backward-paragraph))
23434 (t (goto-char (or post-affiliated begin))))
23435 ;; Ensure we never leave point invisible.
23436 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23438 (defun org-forward-element ()
23439 "Move forward by one element.
23440 Move to the next element at the same level, when possible."
23441 (interactive)
23442 (cond ((eobp) (user-error "Cannot move further down"))
23443 ((org-with-limited-levels (org-at-heading-p))
23444 (let ((origin (point)))
23445 (goto-char (org-end-of-subtree nil t))
23446 (unless (org-with-limited-levels (org-at-heading-p))
23447 (goto-char origin)
23448 (user-error "Cannot move further down"))))
23450 (let* ((elem (org-element-at-point))
23451 (end (org-element-property :end elem))
23452 (parent (org-element-property :parent elem)))
23453 (cond ((and parent (= (org-element-property :contents-end parent) end))
23454 (goto-char (org-element-property :end parent)))
23455 ((integer-or-marker-p end) (goto-char end))
23456 (t (message "No element at point")))))))
23458 (defun org-backward-element ()
23459 "Move backward by one element.
23460 Move to the previous element at the same level, when possible."
23461 (interactive)
23462 (cond ((bobp) (user-error "Cannot move further up"))
23463 ((org-with-limited-levels (org-at-heading-p))
23464 ;; At a headline, move to the previous one, if any, or stay
23465 ;; here.
23466 (let ((origin (point)))
23467 (org-with-limited-levels (org-backward-heading-same-level 1))
23468 ;; When current headline has no sibling above, move to its
23469 ;; parent.
23470 (when (= (point) origin)
23471 (or (org-with-limited-levels (org-up-heading-safe))
23472 (progn (goto-char origin)
23473 (user-error "Cannot move further up"))))))
23475 (let* ((trail (org-element-at-point 'keep-trail))
23476 (elem (car trail))
23477 (prev-elem (nth 1 trail))
23478 (beg (org-element-property :begin elem)))
23479 (cond
23480 ;; Move to beginning of current element if point isn't
23481 ;; there already.
23482 ((null beg) (message "No element at point"))
23483 ((/= (point) beg) (goto-char beg))
23484 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23485 ((org-before-first-heading-p) (goto-char (point-min)))
23486 (t (org-back-to-heading)))))))
23488 (defun org-up-element ()
23489 "Move to upper element."
23490 (interactive)
23491 (if (org-with-limited-levels (org-at-heading-p))
23492 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23493 (let* ((elem (org-element-at-point))
23494 (parent (org-element-property :parent elem)))
23495 (if parent (goto-char (org-element-property :begin parent))
23496 (if (org-with-limited-levels (org-before-first-heading-p))
23497 (user-error "No surrounding element")
23498 (org-with-limited-levels (org-back-to-heading)))))))
23500 (defvar org-element-greater-elements)
23501 (defun org-down-element ()
23502 "Move to inner element."
23503 (interactive)
23504 (let ((element (org-element-at-point)))
23505 (cond
23506 ((memq (org-element-type element) '(plain-list table))
23507 (goto-char (org-element-property :contents-begin element))
23508 (forward-char))
23509 ((memq (org-element-type element) org-element-greater-elements)
23510 ;; If contents are hidden, first disclose them.
23511 (when (org-element-property :hiddenp element) (org-cycle))
23512 (goto-char (or (org-element-property :contents-begin element)
23513 (user-error "No content for this element"))))
23514 (t (user-error "No inner element")))))
23516 (defun org-drag-element-backward ()
23517 "Move backward element at point."
23518 (interactive)
23519 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23520 (let* ((trail (org-element-at-point 'keep-trail))
23521 (elem (car trail))
23522 (prev-elem (nth 1 trail)))
23523 ;; Error out if no previous element or previous element is
23524 ;; a parent of the current one.
23525 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23526 (user-error "Cannot drag element backward")
23527 (let ((pos (point)))
23528 (org-element-swap-A-B prev-elem elem)
23529 (goto-char (+ (org-element-property :begin prev-elem)
23530 (- pos (org-element-property :begin elem)))))))))
23532 (defun org-drag-element-forward ()
23533 "Move forward element at point."
23534 (interactive)
23535 (let* ((pos (point))
23536 (elem (org-element-at-point)))
23537 (when (= (point-max) (org-element-property :end elem))
23538 (user-error "Cannot drag element forward"))
23539 (goto-char (org-element-property :end elem))
23540 (let ((next-elem (org-element-at-point)))
23541 (when (or (org-element-nested-p elem next-elem)
23542 (and (eq (org-element-type next-elem) 'headline)
23543 (not (eq (org-element-type elem) 'headline))))
23544 (goto-char pos)
23545 (user-error "Cannot drag element forward"))
23546 ;; Compute new position of point: it's shifted by NEXT-ELEM
23547 ;; body's length (without final blanks) and by the length of
23548 ;; blanks between ELEM and NEXT-ELEM.
23549 (let ((size-next (- (save-excursion
23550 (goto-char (org-element-property :end next-elem))
23551 (skip-chars-backward " \r\t\n")
23552 (forward-line)
23553 ;; Small correction if buffer doesn't end
23554 ;; with a newline character.
23555 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23556 (org-element-property :begin next-elem)))
23557 (size-blank (- (org-element-property :end elem)
23558 (save-excursion
23559 (goto-char (org-element-property :end elem))
23560 (skip-chars-backward " \r\t\n")
23561 (forward-line)
23562 (point)))))
23563 (org-element-swap-A-B elem next-elem)
23564 (goto-char (+ pos size-next size-blank))))))
23566 (defun org-drag-line-forward (arg)
23567 "Drag the line at point ARG lines forward."
23568 (interactive "p")
23569 (dotimes (n (abs arg))
23570 (let ((c (current-column)))
23571 (if (< 0 arg)
23572 (progn
23573 (beginning-of-line 2)
23574 (transpose-lines 1)
23575 (beginning-of-line 0))
23576 (transpose-lines 1)
23577 (beginning-of-line -1))
23578 (org-move-to-column c))))
23580 (defun org-drag-line-backward (arg)
23581 "Drag the line at point ARG lines backward."
23582 (interactive "p")
23583 (org-drag-line-forward (- arg)))
23585 (defun org-mark-element ()
23586 "Put point at beginning of this element, mark at end.
23588 Interactively, if this command is repeated or (in Transient Mark
23589 mode) if the mark is active, it marks the next element after the
23590 ones already marked."
23591 (interactive)
23592 (let (deactivate-mark)
23593 (if (and (org-called-interactively-p 'any)
23594 (or (and (eq last-command this-command) (mark t))
23595 (and transient-mark-mode mark-active)))
23596 (set-mark
23597 (save-excursion
23598 (goto-char (mark))
23599 (goto-char (org-element-property :end (org-element-at-point)))))
23600 (let ((element (org-element-at-point)))
23601 (end-of-line)
23602 (push-mark (org-element-property :end element) t t)
23603 (goto-char (org-element-property :begin element))))))
23605 (defun org-narrow-to-element ()
23606 "Narrow buffer to current element."
23607 (interactive)
23608 (let ((elem (org-element-at-point)))
23609 (cond
23610 ((eq (car elem) 'headline)
23611 (narrow-to-region
23612 (org-element-property :begin elem)
23613 (org-element-property :end elem)))
23614 ((memq (car elem) org-element-greater-elements)
23615 (narrow-to-region
23616 (org-element-property :contents-begin elem)
23617 (org-element-property :contents-end elem)))
23619 (narrow-to-region
23620 (org-element-property :begin elem)
23621 (org-element-property :end elem))))))
23623 (defun org-transpose-element ()
23624 "Transpose current and previous elements, keeping blank lines between.
23625 Point is moved after both elements."
23626 (interactive)
23627 (org-skip-whitespace)
23628 (let ((end (org-element-property :end (org-element-at-point))))
23629 (org-drag-element-backward)
23630 (goto-char end)))
23632 (defun org-unindent-buffer ()
23633 "Un-indent the visible part of the buffer.
23634 Relative indentation (between items, inside blocks, etc.) isn't
23635 modified."
23636 (interactive)
23637 (unless (eq major-mode 'org-mode)
23638 (user-error "Cannot un-indent a buffer not in Org mode"))
23639 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23640 unindent-tree ; For byte-compiler.
23641 (unindent-tree
23642 (function
23643 (lambda (contents)
23644 (mapc
23645 (lambda (element)
23646 (if (memq (org-element-type element) '(headline section))
23647 (funcall unindent-tree (org-element-contents element))
23648 (save-excursion
23649 (save-restriction
23650 (narrow-to-region
23651 (org-element-property :begin element)
23652 (org-element-property :end element))
23653 (org-do-remove-indentation)))))
23654 (reverse contents))))))
23655 (funcall unindent-tree (org-element-contents parse-tree))))
23657 (defun org-show-subtree ()
23658 "Show everything after this heading at deeper levels."
23659 (interactive)
23660 (outline-flag-region
23661 (point)
23662 (save-excursion
23663 (org-end-of-subtree t t))
23664 nil))
23666 (defun org-show-entry ()
23667 "Show the body directly following this heading.
23668 Show the heading too, if it is currently invisible."
23669 (interactive)
23670 (save-excursion
23671 (condition-case nil
23672 (progn
23673 (org-back-to-heading t)
23674 (outline-flag-region
23675 (max (point-min) (1- (point)))
23676 (save-excursion
23677 (if (re-search-forward
23678 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23679 (match-beginning 1)
23680 (point-max)))
23681 nil)
23682 (org-cycle-hide-drawers 'children))
23683 (error nil))))
23685 (defun org-make-options-regexp (kwds &optional extra)
23686 "Make a regular expression for keyword lines."
23687 (concat
23688 "^#\\+\\("
23689 (mapconcat 'regexp-quote kwds "\\|")
23690 (if extra (concat "\\|" extra))
23691 "\\):[ \t]*\\(.*\\)"))
23693 ;; Make isearch reveal the necessary context
23694 (defun org-isearch-end ()
23695 "Reveal context after isearch exits."
23696 (when isearch-success ; only if search was successful
23697 (if (featurep 'xemacs)
23698 ;; Under XEmacs, the hook is run in the correct place,
23699 ;; we directly show the context.
23700 (org-show-context 'isearch)
23701 ;; In Emacs the hook runs *before* restoring the overlays.
23702 ;; So we have to use a one-time post-command-hook to do this.
23703 ;; (Emacs 22 has a special variable, see function `org-mode')
23704 (unless (and (boundp 'isearch-mode-end-hook-quit)
23705 isearch-mode-end-hook-quit)
23706 ;; Only when the isearch was not quitted.
23707 (org-add-hook 'post-command-hook 'org-isearch-post-command
23708 'append 'local)))
23709 (org-fix-ellipsis-at-bol)))
23711 (defun org-isearch-post-command ()
23712 "Remove self from hook, and show context."
23713 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23714 (org-show-context 'isearch))
23717 ;;;; Integration with and fixes for other packages
23719 ;;; Imenu support
23721 (defvar org-imenu-markers nil
23722 "All markers currently used by Imenu.")
23723 (make-variable-buffer-local 'org-imenu-markers)
23725 (defun org-imenu-new-marker (&optional pos)
23726 "Return a new marker for use by Imenu, and remember the marker."
23727 (let ((m (make-marker)))
23728 (move-marker m (or pos (point)))
23729 (push m org-imenu-markers)
23732 (defun org-imenu-get-tree ()
23733 "Produce the index for Imenu."
23734 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23735 (setq org-imenu-markers nil)
23736 (let* ((n org-imenu-depth)
23737 (re (concat "^" (org-get-limited-outline-regexp)))
23738 (subs (make-vector (1+ n) nil))
23739 (last-level 0)
23740 m level head0 head)
23741 (save-excursion
23742 (save-restriction
23743 (widen)
23744 (goto-char (point-max))
23745 (while (re-search-backward re nil t)
23746 (setq level (org-reduced-level (funcall outline-level)))
23747 (when (and (<= level n)
23748 (looking-at org-complex-heading-regexp)
23749 (setq head0 (org-match-string-no-properties 4)))
23750 (setq head (org-link-display-format head0)
23751 m (org-imenu-new-marker))
23752 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23753 (if (>= level last-level)
23754 (push (cons head m) (aref subs level))
23755 (push (cons head (aref subs (1+ level))) (aref subs level))
23756 (loop for i from (1+ level) to n do (aset subs i nil)))
23757 (setq last-level level)))))
23758 (aref subs 1)))
23760 (eval-after-load "imenu"
23761 '(progn
23762 (add-hook 'imenu-after-jump-hook
23763 (lambda ()
23764 (if (derived-mode-p 'org-mode)
23765 (org-show-context 'org-goto))))))
23767 (defun org-link-display-format (link)
23768 "Replace a link with its the description.
23769 If there is no description, use the link target."
23770 (save-match-data
23771 (if (string-match org-bracket-link-analytic-regexp link)
23772 (replace-match (if (match-end 5)
23773 (match-string 5 link)
23774 (concat (match-string 1 link)
23775 (match-string 3 link)))
23776 nil t link)
23777 link)))
23779 (defun org-toggle-link-display ()
23780 "Toggle the literal or descriptive display of links."
23781 (interactive)
23782 (if org-descriptive-links
23783 (progn (org-remove-from-invisibility-spec '(org-link))
23784 (org-restart-font-lock)
23785 (setq org-descriptive-links nil))
23786 (progn (add-to-invisibility-spec '(org-link))
23787 (org-restart-font-lock)
23788 (setq org-descriptive-links t))))
23790 ;; Speedbar support
23792 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23793 "Overlay marking the agenda restriction line in speedbar.")
23794 (overlay-put org-speedbar-restriction-lock-overlay
23795 'face 'org-agenda-restriction-lock)
23796 (overlay-put org-speedbar-restriction-lock-overlay
23797 'help-echo "Agendas are currently limited to this item.")
23798 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23800 (defun org-speedbar-set-agenda-restriction ()
23801 "Restrict future agenda commands to the location at point in speedbar.
23802 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23803 (interactive)
23804 (require 'org-agenda)
23805 (let (p m tp np dir txt)
23806 (cond
23807 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23808 'org-imenu t))
23809 (setq m (get-text-property p 'org-imenu-marker))
23810 (with-current-buffer (marker-buffer m)
23811 (goto-char m)
23812 (org-agenda-set-restriction-lock 'subtree)))
23813 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23814 'speedbar-function 'speedbar-find-file))
23815 (setq tp (previous-single-property-change
23816 (1+ p) 'speedbar-function)
23817 np (next-single-property-change
23818 tp 'speedbar-function)
23819 dir (speedbar-line-directory)
23820 txt (buffer-substring-no-properties (or tp (point-min))
23821 (or np (point-max))))
23822 (with-current-buffer (find-file-noselect
23823 (let ((default-directory dir))
23824 (expand-file-name txt)))
23825 (unless (derived-mode-p 'org-mode)
23826 (user-error "Cannot restrict to non-Org-mode file"))
23827 (org-agenda-set-restriction-lock 'file)))
23828 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23829 (move-overlay org-speedbar-restriction-lock-overlay
23830 (point-at-bol) (point-at-eol))
23831 (setq current-prefix-arg nil)
23832 (org-agenda-maybe-redo)))
23834 (defvar speedbar-file-key-map)
23835 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23836 (eval-after-load "speedbar"
23837 '(progn
23838 (speedbar-add-supported-extension ".org")
23839 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23840 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23841 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23842 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23843 (add-hook 'speedbar-visiting-tag-hook
23844 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23846 ;;; Fixes and Hacks for problems with other packages
23848 ;; Make flyspell not check words in links, to not mess up our keymap
23849 (defvar org-element-affiliated-keywords) ; From org-element.el
23850 (defvar org-element-block-name-alist) ; From org-element.el
23851 (defun org-mode-flyspell-verify ()
23852 "Don't let flyspell put overlays at active buttons, or on
23853 {todo,all-time,additional-option-like}-keywords."
23854 (require 'org-element) ; For `org-element-affiliated-keywords'
23855 (let ((pos (max (1- (point)) (point-min)))
23856 (word (thing-at-point 'word)))
23857 (and (not (get-text-property pos 'keymap))
23858 (not (get-text-property pos 'org-no-flyspell))
23859 (not (member word org-todo-keywords-1))
23860 (not (member word org-all-time-keywords))
23861 (not (member word org-options-keywords))
23862 (not (member word (mapcar 'car org-startup-options)))
23863 (not (member-ignore-case word org-element-affiliated-keywords))
23864 (not (member-ignore-case word (org-get-export-keywords)))
23865 (not (member-ignore-case
23866 word (mapcar 'car org-element-block-name-alist)))
23867 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23868 (not (org-in-src-block-p)))))
23870 (defun org-remove-flyspell-overlays-in (beg end)
23871 "Remove flyspell overlays in region."
23872 (and (org-bound-and-true-p flyspell-mode)
23873 (fboundp 'flyspell-delete-region-overlays)
23874 (flyspell-delete-region-overlays beg end))
23875 (add-text-properties beg end '(org-no-flyspell t)))
23877 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23878 (eval-after-load "bookmark"
23879 '(if (boundp 'bookmark-after-jump-hook)
23880 ;; We can use the hook
23881 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23882 ;; Hook not available, use advice
23883 (defadvice bookmark-jump (after org-make-visible activate)
23884 "Make the position visible."
23885 (org-bookmark-jump-unhide))))
23887 ;; Make sure saveplace shows the location if it was hidden
23888 (eval-after-load "saveplace"
23889 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23890 "Make the position visible."
23891 (org-bookmark-jump-unhide)))
23893 ;; Make sure ecb shows the location if it was hidden
23894 (eval-after-load "ecb"
23895 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23896 "Make hierarchy visible when jumping into location from ECB tree buffer."
23897 (if (derived-mode-p 'org-mode)
23898 (org-show-context))))
23900 (defun org-bookmark-jump-unhide ()
23901 "Unhide the current position, to show the bookmark location."
23902 (and (derived-mode-p 'org-mode)
23903 (or (outline-invisible-p)
23904 (save-excursion (goto-char (max (point-min) (1- (point))))
23905 (outline-invisible-p)))
23906 (org-show-context 'bookmark-jump)))
23908 ;; Make session.el ignore our circular variable
23909 (defvar session-globals-exclude)
23910 (eval-after-load "session"
23911 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23913 ;;;; Finish up
23915 (provide 'org)
23917 (run-hooks 'org-load-hook)
23919 ;;; org.el ends here