org.el (org-deadline, org-schedule): Fix bug
[org-mode.git] / lisp / org.el
blob4a74d44fe1de99e24a9269c89dc8242432da303a
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 (setq exported-file
202 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
203 (message "%s %s"
204 (if compile
205 (progn (byte-compile-file exported-file 'load)
206 "Compiled and loaded")
207 (progn (load-file exported-file) "Loaded"))
208 exported-file)))
210 (defcustom org-babel-load-languages '((emacs-lisp . t))
211 "Languages which can be evaluated in Org-mode buffers.
212 This list can be used to load support for any of the languages
213 below, note that each language will depend on a different set of
214 system executables and/or Emacs modes. When a language is
215 \"loaded\", then code blocks in that language can be evaluated
216 with `org-babel-execute-src-block' bound by default to C-c
217 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
218 be set to remove code block evaluation from the C-c C-c
219 keybinding. By default only Emacs Lisp (which has no
220 requirements) is loaded."
221 :group 'org-babel
222 :set 'org-babel-do-load-languages
223 :version "24.1"
224 :type '(alist :tag "Babel Languages"
225 :key-type
226 (choice
227 (const :tag "Awk" awk)
228 (const :tag "C" C)
229 (const :tag "R" R)
230 (const :tag "Asymptote" asymptote)
231 (const :tag "Calc" calc)
232 (const :tag "Clojure" clojure)
233 (const :tag "CSS" css)
234 (const :tag "Ditaa" ditaa)
235 (const :tag "Dot" dot)
236 (const :tag "Emacs Lisp" emacs-lisp)
237 (const :tag "Fortran" fortran)
238 (const :tag "Gnuplot" gnuplot)
239 (const :tag "Haskell" haskell)
240 (const :tag "IO" io)
241 (const :tag "Java" java)
242 (const :tag "Javascript" js)
243 (const :tag "LaTeX" latex)
244 (const :tag "Ledger" ledger)
245 (const :tag "Lilypond" lilypond)
246 (const :tag "Lisp" lisp)
247 (const :tag "Makefile" makefile)
248 (const :tag "Maxima" maxima)
249 (const :tag "Matlab" matlab)
250 (const :tag "Mscgen" mscgen)
251 (const :tag "Ocaml" ocaml)
252 (const :tag "Octave" octave)
253 (const :tag "Org" org)
254 (const :tag "Perl" perl)
255 (const :tag "Pico Lisp" picolisp)
256 (const :tag "PlantUML" plantuml)
257 (const :tag "Python" python)
258 (const :tag "Ruby" ruby)
259 (const :tag "Sass" sass)
260 (const :tag "Scala" scala)
261 (const :tag "Scheme" scheme)
262 (const :tag "Screen" screen)
263 (const :tag "Shell Script" sh)
264 (const :tag "Shen" shen)
265 (const :tag "Sql" sql)
266 (const :tag "Sqlite" sqlite))
267 :value-type (boolean :tag "Activate" :value t)))
269 ;;;; Customization variables
270 (defcustom org-clone-delete-id nil
271 "Remove ID property of clones of a subtree.
272 When non-nil, clones of a subtree don't inherit the ID property.
273 Otherwise they inherit the ID property with a new unique
274 identifier."
275 :type 'boolean
276 :version "24.1"
277 :group 'org-id)
279 ;;; Version
280 (org-check-version)
282 ;;;###autoload
283 (defun org-version (&optional here full message)
284 "Show the org-mode version in the echo area.
285 With prefix argument HERE, insert it at point.
286 When FULL is non-nil, use a verbose version string.
287 When MESSAGE is non-nil, display a message with the version."
288 (interactive "P")
289 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
290 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
291 (load-suffixes (list ".el"))
292 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
293 (org-trash (or
294 (and (fboundp 'org-release) (fboundp 'org-git-version))
295 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
296 (load-suffixes save-load-suffixes)
297 (org-version (org-release))
298 (git-version (org-git-version))
299 (version (format "Org-mode version %s (%s @ %s)"
300 org-version
301 git-version
302 (if org-install-dir
303 (if (string= org-dir org-install-dir)
304 org-install-dir
305 (concat "mixed installation! " org-install-dir " and " org-dir))
306 "org-loaddefs.el can not be found!")))
307 (_version (if full version org-version)))
308 (if (org-called-interactively-p 'interactive)
309 (if here
310 (insert version)
311 (message version))
312 (if message (message _version))
313 _version)))
315 (defconst org-version (org-version))
317 ;;; Compatibility constants
319 ;;; The custom variables
321 (defgroup org nil
322 "Outline-based notes management and organizer."
323 :tag "Org"
324 :group 'outlines
325 :group 'calendar)
327 (defcustom org-mode-hook nil
328 "Mode hook for Org-mode, run after the mode was turned on."
329 :group 'org
330 :type 'hook)
332 (defcustom org-load-hook nil
333 "Hook that is run after org.el has been loaded."
334 :group 'org
335 :type 'hook)
337 (defcustom org-log-buffer-setup-hook nil
338 "Hook that is run after an Org log buffer is created."
339 :group 'org
340 :version "24.1"
341 :type 'hook)
343 (defvar org-modules) ; defined below
344 (defvar org-modules-loaded nil
345 "Have the modules been loaded already?")
347 (defun org-load-modules-maybe (&optional force)
348 "Load all extensions listed in `org-modules'."
349 (when (or force (not org-modules-loaded))
350 (mapc (lambda (ext)
351 (condition-case nil (require ext)
352 (error (message "Problems while trying to load feature `%s'" ext))))
353 org-modules)
354 (setq org-modules-loaded t)))
356 (defun org-set-modules (var value)
357 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
358 (set var value)
359 (when (featurep 'org)
360 (org-load-modules-maybe 'force)))
362 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
363 "Modules that should always be loaded together with org.el.
365 If a description starts with <C>, the file is not part of Emacs
366 and loading it will require that you have downloaded and properly
367 installed the Org mode distribution.
369 You can also use this system to load external packages (i.e. neither Org
370 core modules, nor modules from the CONTRIB directory). Just add symbols
371 to the end of the list. If the package is called org-xyz.el, then you need
372 to add the symbol `xyz', and the package must have a call to:
374 \(provide 'org-xyz)
376 For export specific modules, see also `org-export-backends'."
377 :group 'org
378 :set 'org-set-modules
379 :version "24.4"
380 :package-version '(Org . "8.0")
381 :type
382 '(set :greedy t
383 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
384 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
385 (const :tag " crypt: Encryption of subtrees" org-crypt)
386 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
387 (const :tag " docview: Links to doc-view buffers" org-docview)
388 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
389 (const :tag " habit: Track your consistency with habits" org-habit)
390 (const :tag " id: Global IDs for identifying entries" org-id)
391 (const :tag " info: Links to Info nodes" org-info)
392 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
393 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
394 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
395 (const :tag " mouse: Additional mouse support" org-mouse)
396 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
397 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
398 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
400 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
401 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
402 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
403 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
404 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
405 (const :tag "C collector: Collect properties into tables" org-collector)
406 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
407 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
408 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
409 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
410 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
411 (const :tag "C eval: Include command output as text" org-eval)
412 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
413 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
414 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
415 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
416 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
417 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
418 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
419 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
420 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export--registered-backends) ; From ox.el.
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (declare-function org-export-backend-name "ox" (backend))
442 (defcustom org-export-backends '(ascii html icalendar latex)
443 "List of export back-ends that should be always available.
445 If a description starts with <C>, the file is not part of Emacs
446 and loading it will require that you have downloaded and properly
447 installed the Org mode distribution.
449 Unlike to `org-modules', libraries in this list will not be
450 loaded along with Org, but only once the export framework is
451 needed.
453 This variable needs to be set before org.el is loaded. If you
454 need to make a change while Emacs is running, use the customize
455 interface or run the following code, where VAL stands for the new
456 value of the variable, after updating it:
458 \(progn
459 \(setq org-export--registered-backends
460 \(org-remove-if-not
461 \(lambda (backend)
462 \(let ((name (org-export-backend-name backend)))
463 \(or (memq name val)
464 \(catch 'parentp
465 \(dolist (b val)
466 \(and (org-export-derived-backend-p b name)
467 \(throw 'parentp t)))))))
468 org-export--registered-backends))
469 \(let ((new-list (mapcar 'org-export-backend-name
470 org-export--registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default 'org-export-backends new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export--registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (let ((name (org-export-backend-name backend)))
495 (or (memq name val)
496 (catch 'parentp
497 (dolist (b val)
498 (and (org-export-derived-backend-p b name)
499 (throw 'parentp t)))))))
500 org-export--registered-backends))
501 ;; Now build NEW-LIST of both new back-ends and required
502 ;; parents.
503 (let ((new-list (mapcar 'org-export-backend-name
504 org-export--registered-backends)))
505 (dolist (backend val)
506 (cond
507 ((not (load (format "ox-%s" backend) t t))
508 (message "Problems while trying to load export back-end `%s'"
509 backend))
510 ((not (memq backend new-list)) (push backend new-list))))
511 ;; Set VAR to that list with fixed dependencies.
512 (set-default var new-list))))
513 :type '(set :greedy t
514 (const :tag " ascii Export buffer to ASCII format" ascii)
515 (const :tag " beamer Export buffer to Beamer presentation" beamer)
516 (const :tag " html Export buffer to HTML format" html)
517 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
518 (const :tag " latex Export buffer to LaTeX format" latex)
519 (const :tag " man Export buffer to MAN format" man)
520 (const :tag " md Export buffer to Markdown format" md)
521 (const :tag " odt Export buffer to ODT format" odt)
522 (const :tag " org Export buffer to Org format" org)
523 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
524 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
525 (const :tag "C deck Export buffer to deck.js presentations" deck)
526 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
527 (const :tag "C groff Export buffer to Groff format" groff)
528 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
529 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
530 (const :tag "C s5 Export buffer to s5 presentations" s5)
531 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
533 (eval-after-load 'ox
534 '(mapc
535 (lambda (backend)
536 (condition-case nil (require (intern (format "ox-%s" backend)))
537 (error (message "Problems while trying to load export back-end `%s'"
538 backend))))
539 org-export-backends))
541 (defcustom org-support-shift-select nil
542 "Non-nil means make shift-cursor commands select text when possible.
544 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
545 start selecting a region, or enlarge regions started in this way.
546 In Org-mode, in special contexts, these same keys are used for
547 other purposes, important enough to compete with shift selection.
548 Org tries to balance these needs by supporting `shift-select-mode'
549 outside these special contexts, under control of this variable.
551 The default of this variable is nil, to avoid confusing behavior. Shifted
552 cursor keys will then execute Org commands in the following contexts:
553 - on a headline, changing TODO state (left/right) and priority (up/down)
554 - on a time stamp, changing the time
555 - in a plain list item, changing the bullet type
556 - in a property definition line, switching between allowed values
557 - in the BEGIN line of a clock table (changing the time block).
558 Outside these contexts, the commands will throw an error.
560 When this variable is t and the cursor is not in a special
561 context, Org-mode will support shift-selection for making and
562 enlarging regions. To make this more effective, the bullet
563 cycling will no longer happen anywhere in an item line, but only
564 if the cursor is exactly on the bullet.
566 If you set this variable to the symbol `always', then the keys
567 will not be special in headlines, property lines, and item lines,
568 to make shift selection work there as well. If this is what you
569 want, you can use the following alternative commands: `C-c C-t'
570 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
571 can be used to switch TODO sets, `C-c -' to cycle item bullet
572 types, and properties can be edited by hand or in column view.
574 However, when the cursor is on a timestamp, shift-cursor commands
575 will still edit the time stamp - this is just too good to give up.
577 XEmacs user should have this variable set to nil, because
578 `shift-select-mode' is in Emacs 23 or later only."
579 :group 'org
580 :type '(choice
581 (const :tag "Never" nil)
582 (const :tag "When outside special context" t)
583 (const :tag "Everywhere except timestamps" always)))
585 (defcustom org-loop-over-headlines-in-active-region nil
586 "Shall some commands act upon headlines in the active region?
588 When set to `t', some commands will be performed in all headlines
589 within the active region.
591 When set to `start-level', some commands will be performed in all
592 headlines within the active region, provided that these headlines
593 are of the same level than the first one.
595 When set to a string, those commands will be performed on the
596 matching headlines within the active region. Such string must be
597 a tags/property/todo match as it is used in the agenda tags view.
599 The list of commands is: `org-schedule', `org-deadline',
600 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
601 `org-archive-to-archive-sibling'. The archiving commands skip
602 already archived entries."
603 :type '(choice (const :tag "Don't loop" nil)
604 (const :tag "All headlines in active region" t)
605 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
606 (string :tag "Tags/Property/Todo matcher"))
607 :version "24.1"
608 :group 'org-todo
609 :group 'org-archive)
611 (defgroup org-startup nil
612 "Options concerning startup of Org-mode."
613 :tag "Org Startup"
614 :group 'org)
616 (defcustom org-startup-folded t
617 "Non-nil means entering Org-mode will switch to OVERVIEW.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: fold (or `overview', this is equivalent)
622 #+STARTUP: nofold (or `showall', this is equivalent)
623 #+STARTUP: content
624 #+STARTUP: showeverything
626 By default, this option is ignored when Org opens agenda files
627 for the first time. If you want the agenda to honor the startup
628 option, set `org-agenda-inhibit-startup' to nil."
629 :group 'org-startup
630 :type '(choice
631 (const :tag "nofold: show all" nil)
632 (const :tag "fold: overview" t)
633 (const :tag "content: all headlines" content)
634 (const :tag "show everything, even drawers" showeverything)))
636 (defcustom org-startup-truncated t
637 "Non-nil means entering Org-mode will set `truncate-lines'.
638 This is useful since some lines containing links can be very long and
639 uninteresting. Also tables look terrible when wrapped."
640 :group 'org-startup
641 :type 'boolean)
643 (defcustom org-startup-indented nil
644 "Non-nil means turn on `org-indent-mode' on startup.
645 This can also be configured on a per-file basis by adding one of
646 the following lines anywhere in the buffer:
648 #+STARTUP: indent
649 #+STARTUP: noindent"
650 :group 'org-structure
651 :type '(choice
652 (const :tag "Not" nil)
653 (const :tag "Globally (slow on startup in large files)" t)))
655 (defcustom org-use-sub-superscripts t
656 "Non-nil means interpret \"_\" and \"^\" for display.
657 When this option is turned on, you can use TeX-like syntax for sub- and
658 superscripts. Several characters after \"_\" or \"^\" will be
659 considered as a single item - so grouping with {} is normally not
660 needed. For example, the following things will be parsed as single
661 sub- or superscripts.
663 10^24 or 10^tau several digits will be considered 1 item.
664 10^-12 or 10^-tau a leading sign with digits or a word
665 x^2-y^3 will be read as x^2 - y^3, because items are
666 terminated by almost any nonword/nondigit char.
667 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
669 Still, ambiguity is possible - so when in doubt use {} to enclose
670 the sub/superscript. If you set this variable to the symbol
671 `{}', the braces are *required* in order to trigger
672 interpretations as sub/superscript. This can be helpful in
673 documents that need \"_\" frequently in plain text."
674 :group 'org-startup
675 :version "24.1"
676 :type '(choice
677 (const :tag "Always interpret" t)
678 (const :tag "Only with braces" {})
679 (const :tag "Never interpret" nil)))
681 (defcustom org-startup-with-beamer-mode nil
682 "Non-nil means turn on `org-beamer-mode' on startup.
683 This can also be configured on a per-file basis by adding one of
684 the following lines anywhere in the buffer:
686 #+STARTUP: beamer"
687 :group 'org-startup
688 :version "24.1"
689 :type 'boolean)
691 (defcustom org-startup-align-all-tables nil
692 "Non-nil means align all tables when visiting a file.
693 This is useful when the column width in tables is forced with <N> cookies
694 in table fields. Such tables will look correct only after the first re-align.
695 This can also be configured on a per-file basis by adding one of
696 the following lines anywhere in the buffer:
697 #+STARTUP: align
698 #+STARTUP: noalign"
699 :group 'org-startup
700 :type 'boolean)
702 (defcustom org-startup-with-inline-images nil
703 "Non-nil means show inline images when loading a new Org file.
704 This can also be configured on a per-file basis by adding one of
705 the following lines anywhere in the buffer:
706 #+STARTUP: inlineimages
707 #+STARTUP: noinlineimages"
708 :group 'org-startup
709 :version "24.1"
710 :type 'boolean)
712 (defcustom org-startup-with-latex-preview nil
713 "Non-nil means preview LaTeX fragments when loading a new Org file.
715 This can also be configured on a per-file basis by adding one of
716 the followinglines anywhere in the buffer:
717 #+STARTUP: latexpreview
718 #+STARTUP: nolatexpreview"
719 :group 'org-startup
720 :version "24.4"
721 :package-version '(Org . "8.0")
722 :type 'boolean)
724 (defcustom org-insert-mode-line-in-empty-file nil
725 "Non-nil means insert the first line setting Org-mode in empty files.
726 When the function `org-mode' is called interactively in an empty file, this
727 normally means that the file name does not automatically trigger Org-mode.
728 To ensure that the file will always be in Org-mode in the future, a
729 line enforcing Org-mode will be inserted into the buffer, if this option
730 has been set."
731 :group 'org-startup
732 :type 'boolean)
734 (defcustom org-replace-disputed-keys nil
735 "Non-nil means use alternative key bindings for some keys.
736 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
737 These keys are also used by other packages like shift-selection-mode'
738 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
739 If you want to use Org-mode together with one of these other modes,
740 or more generally if you would like to move some Org-mode commands to
741 other keys, set this variable and configure the keys with the variable
742 `org-disputed-keys'.
744 This option is only relevant at load-time of Org-mode, and must be set
745 *before* org.el is loaded. Changing it requires a restart of Emacs to
746 become effective."
747 :group 'org-startup
748 :type 'boolean)
750 (defcustom org-use-extra-keys nil
751 "Non-nil means use extra key sequence definitions for certain commands.
752 This happens automatically if you run XEmacs or if `window-system'
753 is nil. This variable lets you do the same manually. You must
754 set it before loading org.
756 Example: on Carbon Emacs 22 running graphically, with an external
757 keyboard on a Powerbook, the default way of setting M-left might
758 not work for either Alt or ESC. Setting this variable will make
759 it work for ESC."
760 :group 'org-startup
761 :type 'boolean)
763 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
765 (defcustom org-disputed-keys
766 '(([(shift up)] . [(meta p)])
767 ([(shift down)] . [(meta n)])
768 ([(shift left)] . [(meta -)])
769 ([(shift right)] . [(meta +)])
770 ([(control shift right)] . [(meta shift +)])
771 ([(control shift left)] . [(meta shift -)]))
772 "Keys for which Org-mode and other modes compete.
773 This is an alist, cars are the default keys, second element specifies
774 the alternative to use when `org-replace-disputed-keys' is t.
776 Keys can be specified in any syntax supported by `define-key'.
777 The value of this option takes effect only at Org-mode's startup,
778 therefore you'll have to restart Emacs to apply it after changing."
779 :group 'org-startup
780 :type 'alist)
782 (defun org-key (key)
783 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
784 Or return the original if not disputed.
785 Also apply the translations defined in `org-xemacs-key-equivalents'."
786 (when org-replace-disputed-keys
787 (let* ((nkey (key-description key))
788 (x (org-find-if (lambda (x)
789 (equal (key-description (car x)) nkey))
790 org-disputed-keys)))
791 (setq key (if x (cdr x) key))))
792 (when (featurep 'xemacs)
793 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
794 key)
796 (defun org-find-if (predicate seq)
797 (catch 'exit
798 (while seq
799 (if (funcall predicate (car seq))
800 (throw 'exit (car seq))
801 (pop seq)))))
803 (defun org-defkey (keymap key def)
804 "Define a key, possibly translated, as returned by `org-key'."
805 (define-key keymap (org-key key) def))
807 (defcustom org-ellipsis nil
808 "The ellipsis to use in the Org-mode outline.
809 When nil, just use the standard three dots. When a string, use that instead,
810 When a face, use the standard 3 dots, but with the specified face.
811 The change affects only Org-mode (which will then use its own display table).
812 Changing this requires executing `M-x org-mode' in a buffer to become
813 effective."
814 :group 'org-startup
815 :type '(choice (const :tag "Default" nil)
816 (face :tag "Face" :value org-warning)
817 (string :tag "String" :value "...#")))
819 (defvar org-display-table nil
820 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
822 (defgroup org-keywords nil
823 "Keywords in Org-mode."
824 :tag "Org Keywords"
825 :group 'org)
827 (defcustom org-deadline-string "DEADLINE:"
828 "String to mark deadline entries.
829 A deadline is this string, followed by a time stamp. Should be a word,
830 terminated by a colon. You can insert a schedule keyword and
831 a timestamp with \\[org-deadline].
832 Changes become only effective after restarting Emacs."
833 :group 'org-keywords
834 :type 'string)
836 (defcustom org-scheduled-string "SCHEDULED:"
837 "String to mark scheduled TODO entries.
838 A schedule is this string, followed by a time stamp. Should be a word,
839 terminated by a colon. You can insert a schedule keyword and
840 a timestamp with \\[org-schedule].
841 Changes become only effective after restarting Emacs."
842 :group 'org-keywords
843 :type 'string)
845 (defcustom org-closed-string "CLOSED:"
846 "String used as the prefix for timestamps logging closing a TODO entry."
847 :group 'org-keywords
848 :type 'string)
850 (defcustom org-clock-string "CLOCK:"
851 "String used as prefix for timestamps clocking work hours on an item."
852 :group 'org-keywords
853 :type 'string)
855 (defcustom org-closed-keep-when-no-todo nil
856 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
857 :group 'org-todo
858 :group 'org-keywords
859 :version "24.4"
860 :package-version '(Org . "8.0")
861 :type 'boolean)
863 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
864 org-scheduled-string "\\|"
865 org-deadline-string "\\|"
866 org-closed-string "\\|"
867 org-clock-string "\\)")
868 "Matches a line with planning or clock info.")
870 (defcustom org-comment-string "COMMENT"
871 "Entries starting with this keyword will never be exported.
872 An entry can be toggled between COMMENT and normal with
873 \\[org-toggle-comment].
874 Changes become only effective after restarting Emacs."
875 :group 'org-keywords
876 :type 'string)
878 (defcustom org-quote-string "QUOTE"
879 "Entries starting with this keyword will be exported in fixed-width font.
880 Quoting applies only to the text in the entry following the headline, and does
881 not extend beyond the next headline, even if that is lower level.
882 An entry can be toggled between QUOTE and normal with
883 \\[org-toggle-fixed-width-section]."
884 :group 'org-keywords
885 :type 'string)
887 (defconst org-repeat-re
888 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
889 "Regular expression for specifying repeated events.
890 After a match, group 1 contains the repeat expression.")
892 (defgroup org-structure nil
893 "Options concerning the general structure of Org-mode files."
894 :tag "Org Structure"
895 :group 'org)
897 (defgroup org-reveal-location nil
898 "Options about how to make context of a location visible."
899 :tag "Org Reveal Location"
900 :group 'org-structure)
902 (defconst org-context-choice
903 '(choice
904 (const :tag "Always" t)
905 (const :tag "Never" nil)
906 (repeat :greedy t :tag "Individual contexts"
907 (cons
908 (choice :tag "Context"
909 (const agenda)
910 (const org-goto)
911 (const occur-tree)
912 (const tags-tree)
913 (const link-search)
914 (const mark-goto)
915 (const bookmark-jump)
916 (const isearch)
917 (const default))
918 (boolean))))
919 "Contexts for the reveal options.")
921 (defcustom org-show-hierarchy-above '((default . t))
922 "Non-nil means show full hierarchy when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the hierarchy of headings
925 above the exposed location is shown.
926 Turning this off for example for sparse trees makes them very compact.
927 Instead of t, this can also be an alist specifying this option for different
928 contexts. Valid contexts are
929 agenda when exposing an entry from the agenda
930 org-goto when using the command `org-goto' on key C-c C-j
931 occur-tree when using the command `org-occur' on key C-c /
932 tags-tree when constructing a sparse tree based on tags matches
933 link-search when exposing search matches associated with a link
934 mark-goto when exposing the jump goal of a mark
935 bookmark-jump when exposing a bookmark location
936 isearch when exiting from an incremental search
937 default default for all contexts not set explicitly"
938 :group 'org-reveal-location
939 :type org-context-choice)
941 (defcustom org-show-following-heading '((default . nil))
942 "Non-nil means show following heading when revealing a location.
943 Org-mode often shows locations in an org-mode file which might have
944 been invisible before. When this is set, the heading following the
945 match is shown.
946 Turning this off for example for sparse trees makes them very compact,
947 but makes it harder to edit the location of the match. In such a case,
948 use the command \\[org-reveal] to show more context.
949 Instead of t, this can also be an alist specifying this option for different
950 contexts. See `org-show-hierarchy-above' for valid contexts."
951 :group 'org-reveal-location
952 :type org-context-choice)
954 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
955 "Non-nil means show all sibling heading when revealing a location.
956 Org-mode often shows locations in an org-mode file which might have
957 been invisible before. When this is set, the sibling of the current entry
958 heading are all made visible. If `org-show-hierarchy-above' is t,
959 the same happens on each level of the hierarchy above the current entry.
961 By default this is on for the isearch context, off for all other contexts.
962 Turning this off for example for sparse trees makes them very compact,
963 but makes it harder to edit the location of the match. In such a case,
964 use the command \\[org-reveal] to show more context.
965 Instead of t, this can also be an alist specifying this option for different
966 contexts. See `org-show-hierarchy-above' for valid contexts."
967 :group 'org-reveal-location
968 :type org-context-choice
969 :version "24.4"
970 :package-version '(Org . "8.0"))
972 (defcustom org-show-entry-below '((default . nil))
973 "Non-nil means show the entry below a headline when revealing a location.
974 Org-mode often shows locations in an org-mode file which might have
975 been invisible before. When this is set, the text below the headline that is
976 exposed is also shown.
978 By default this is off for all contexts.
979 Instead of t, this can also be an alist specifying this option for different
980 contexts. See `org-show-hierarchy-above' for valid contexts."
981 :group 'org-reveal-location
982 :type org-context-choice)
984 (defcustom org-indirect-buffer-display 'other-window
985 "How should indirect tree buffers be displayed?
986 This applies to indirect buffers created with the commands
987 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
988 Valid values are:
989 current-window Display in the current window
990 other-window Just display in another window.
991 dedicated-frame Create one new frame, and re-use it each time.
992 new-frame Make a new frame each time. Note that in this case
993 previously-made indirect buffers are kept, and you need to
994 kill these buffers yourself."
995 :group 'org-structure
996 :group 'org-agenda-windows
997 :type '(choice
998 (const :tag "In current window" current-window)
999 (const :tag "In current frame, other window" other-window)
1000 (const :tag "Each time a new frame" new-frame)
1001 (const :tag "One dedicated frame" dedicated-frame)))
1003 (defcustom org-use-speed-commands nil
1004 "Non-nil means activate single letter commands at beginning of a headline.
1005 This may also be a function to test for appropriate locations where speed
1006 commands should be active."
1007 :group 'org-structure
1008 :type '(choice
1009 (const :tag "Never" nil)
1010 (const :tag "At beginning of headline stars" t)
1011 (function)))
1013 (defcustom org-speed-commands-user nil
1014 "Alist of additional speed commands.
1015 This list will be checked before `org-speed-commands-default'
1016 when the variable `org-use-speed-commands' is non-nil
1017 and when the cursor is at the beginning of a headline.
1018 The car if each entry is a string with a single letter, which must
1019 be assigned to `self-insert-command' in the global map.
1020 The cdr is either a command to be called interactively, a function
1021 to be called, or a form to be evaluated.
1022 An entry that is just a list with a single string will be interpreted
1023 as a descriptive headline that will be added when listing the speed
1024 commands in the Help buffer using the `?' speed command."
1025 :group 'org-structure
1026 :type '(repeat :value ("k" . ignore)
1027 (choice :value ("k" . ignore)
1028 (list :tag "Descriptive Headline" (string :tag "Headline"))
1029 (cons :tag "Letter and Command"
1030 (string :tag "Command letter")
1031 (choice
1032 (function)
1033 (sexp))))))
1035 (defcustom org-bookmark-names-plist
1036 '(:last-capture "org-capture-last-stored"
1037 :last-refile "org-refile-last-stored"
1038 :last-capture-marker "org-capture-last-stored-marker")
1039 "Names for bookmarks automatically set by some Org commands.
1040 This can provide strings as names for a number of bookmakrs Org sets
1041 automatically. The following keys are currently implemented:
1042 :last-capture
1043 :last-capture-marker
1044 :last-refile
1045 When a key does not show up in the property list, the corresponding bookmark
1046 is not set."
1047 :group 'org-structure
1048 :type 'plist)
1050 (defgroup org-cycle nil
1051 "Options concerning visibility cycling in Org-mode."
1052 :tag "Org Cycle"
1053 :group 'org-structure)
1055 (defcustom org-cycle-skip-children-state-if-no-children t
1056 "Non-nil means skip CHILDREN state in entries that don't have any."
1057 :group 'org-cycle
1058 :type 'boolean)
1060 (defcustom org-cycle-max-level nil
1061 "Maximum level which should still be subject to visibility cycling.
1062 Levels higher than this will, for cycling, be treated as text, not a headline.
1063 When `org-odd-levels-only' is set, a value of N in this variable actually
1064 means 2N-1 stars as the limiting headline.
1065 When nil, cycle all levels.
1066 Note that the limiting level of cycling is also influenced by
1067 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1068 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1069 than its value."
1070 :group 'org-cycle
1071 :type '(choice
1072 (const :tag "No limit" nil)
1073 (integer :tag "Maximum level")))
1075 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1076 "Names of drawers. Drawers are not opened by cycling on the headline above.
1077 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1078 this:
1079 :DRAWERNAME:
1080 .....
1081 :END:
1082 The drawer \"PROPERTIES\" is special for capturing properties through
1083 the property API.
1085 Drawers can be defined on the per-file basis with a line like:
1087 #+DRAWERS: HIDDEN STATE PROPERTIES"
1088 :group 'org-structure
1089 :group 'org-cycle
1090 :type '(repeat (string :tag "Drawer Name")))
1092 (defcustom org-hide-block-startup nil
1093 "Non-nil means entering Org-mode will fold all blocks.
1094 This can also be set in on a per-file basis with
1096 #+STARTUP: hideblocks
1097 #+STARTUP: showblocks"
1098 :group 'org-startup
1099 :group 'org-cycle
1100 :type 'boolean)
1102 (defcustom org-cycle-global-at-bob nil
1103 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1104 This makes it possible to do global cycling without having to use S-TAB or
1105 \\[universal-argument] TAB. For this special case to work, the first line
1106 of the buffer must not be a headline -- it may be empty or some other text.
1107 When used in this way, `org-cycle-hook' is disabled temporarily to make
1108 sure the cursor stays at the beginning of the buffer. When this option is
1109 nil, don't do anything special at the beginning of the buffer."
1110 :group 'org-cycle
1111 :type 'boolean)
1113 (defcustom org-cycle-level-after-item/entry-creation t
1114 "Non-nil means cycle entry level or item indentation in new empty entries.
1116 When the cursor is at the end of an empty headline, i.e., with only stars
1117 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1118 and then all possible ancestor states, before returning to the original state.
1119 This makes data entry extremely fast: M-RET to create a new headline,
1120 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1122 When the cursor is at the end of an empty plain list item, one TAB will
1123 make it a subitem, two or more tabs will back up to make this an item
1124 higher up in the item hierarchy."
1125 :group 'org-cycle
1126 :type 'boolean)
1128 (defcustom org-cycle-emulate-tab t
1129 "Where should `org-cycle' emulate TAB.
1130 nil Never
1131 white Only in completely white lines
1132 whitestart Only at the beginning of lines, before the first non-white char
1133 t Everywhere except in headlines
1134 exc-hl-bol Everywhere except at the start of a headline
1135 If TAB is used in a place where it does not emulate TAB, the current subtree
1136 visibility is cycled."
1137 :group 'org-cycle
1138 :type '(choice (const :tag "Never" nil)
1139 (const :tag "Only in completely white lines" white)
1140 (const :tag "Before first char in a line" whitestart)
1141 (const :tag "Everywhere except in headlines" t)
1142 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1144 (defcustom org-cycle-separator-lines 2
1145 "Number of empty lines needed to keep an empty line between collapsed trees.
1146 If you leave an empty line between the end of a subtree and the following
1147 headline, this empty line is hidden when the subtree is folded.
1148 Org-mode will leave (exactly) one empty line visible if the number of
1149 empty lines is equal or larger to the number given in this variable.
1150 So the default 2 means at least 2 empty lines after the end of a subtree
1151 are needed to produce free space between a collapsed subtree and the
1152 following headline.
1154 If the number is negative, and the number of empty lines is at least -N,
1155 all empty lines are shown.
1157 Special case: when 0, never leave empty lines in collapsed view."
1158 :group 'org-cycle
1159 :type 'integer)
1160 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1162 (defcustom org-pre-cycle-hook nil
1163 "Hook that is run before visibility cycling is happening.
1164 The function(s) in this hook must accept a single argument which indicates
1165 the new state that will be set right after running this hook. The
1166 argument is a symbol. Before a global state change, it can have the values
1167 `overview', `content', or `all'. Before a local state change, it can have
1168 the values `folded', `children', or `subtree'."
1169 :group 'org-cycle
1170 :type 'hook)
1172 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1173 org-cycle-hide-drawers
1174 org-cycle-hide-inline-tasks
1175 org-cycle-show-empty-lines
1176 org-optimize-window-after-visibility-change)
1177 "Hook that is run after `org-cycle' has changed the buffer visibility.
1178 The function(s) in this hook must accept a single argument which indicates
1179 the new state that was set by the most recent `org-cycle' command. The
1180 argument is a symbol. After a global state change, it can have the values
1181 `overview', `contents', or `all'. After a local state change, it can have
1182 the values `folded', `children', or `subtree'."
1183 :group 'org-cycle
1184 :type 'hook)
1186 (defgroup org-edit-structure nil
1187 "Options concerning structure editing in Org-mode."
1188 :tag "Org Edit Structure"
1189 :group 'org-structure)
1191 (defcustom org-odd-levels-only nil
1192 "Non-nil means skip even levels and only use odd levels for the outline.
1193 This has the effect that two stars are being added/taken away in
1194 promotion/demotion commands. It also influences how levels are
1195 handled by the exporters.
1196 Changing it requires restart of `font-lock-mode' to become effective
1197 for fontification also in regions already fontified.
1198 You may also set this on a per-file basis by adding one of the following
1199 lines to the buffer:
1201 #+STARTUP: odd
1202 #+STARTUP: oddeven"
1203 :group 'org-edit-structure
1204 :group 'org-appearance
1205 :type 'boolean)
1207 (defcustom org-adapt-indentation t
1208 "Non-nil means adapt indentation to outline node level.
1210 When this variable is set, Org assumes that you write outlines by
1211 indenting text in each node to align with the headline (after the stars).
1212 The following issues are influenced by this variable:
1214 - When this is set and the *entire* text in an entry is indented, the
1215 indentation is increased by one space in a demotion command, and
1216 decreased by one in a promotion command. If any line in the entry
1217 body starts with text at column 0, indentation is not changed at all.
1219 - Property drawers and planning information is inserted indented when
1220 this variable s set. When nil, they will not be indented.
1222 - TAB indents a line relative to context. The lines below a headline
1223 will be indented when this variable is set.
1225 Note that this is all about true indentation, by adding and removing
1226 space characters. See also `org-indent.el' which does level-dependent
1227 indentation in a virtual way, i.e. at display time in Emacs."
1228 :group 'org-edit-structure
1229 :type 'boolean)
1231 (defcustom org-special-ctrl-a/e nil
1232 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1234 When t, `C-a' will bring back the cursor to the beginning of the
1235 headline text, i.e. after the stars and after a possible TODO
1236 keyword. In an item, this will be the position after bullet and
1237 check-box, if any. When the cursor is already at that position,
1238 another `C-a' will bring it to the beginning of the line.
1240 `C-e' will jump to the end of the headline, ignoring the presence
1241 of tags in the headline. A second `C-e' will then jump to the
1242 true end of the line, after any tags. This also means that, when
1243 this variable is non-nil, `C-e' also will never jump beyond the
1244 end of the heading of a folded section, i.e. not after the
1245 ellipses.
1247 When set to the symbol `reversed', the first `C-a' or `C-e' works
1248 normally, going to the true line boundary first. Only a directly
1249 following, identical keypress will bring the cursor to the
1250 special positions.
1252 This may also be a cons cell where the behavior for `C-a' and
1253 `C-e' is set separately."
1254 :group 'org-edit-structure
1255 :type '(choice
1256 (const :tag "off" nil)
1257 (const :tag "on: after stars/bullet and before tags first" t)
1258 (const :tag "reversed: true line boundary first" reversed)
1259 (cons :tag "Set C-a and C-e separately"
1260 (choice :tag "Special C-a"
1261 (const :tag "off" nil)
1262 (const :tag "on: after stars/bullet first" t)
1263 (const :tag "reversed: before stars/bullet first" reversed))
1264 (choice :tag "Special C-e"
1265 (const :tag "off" nil)
1266 (const :tag "on: before tags first" t)
1267 (const :tag "reversed: after tags first" reversed)))))
1268 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1270 (defcustom org-special-ctrl-k nil
1271 "Non-nil means `C-k' will behave specially in headlines.
1272 When nil, `C-k' will call the default `kill-line' command.
1273 When t, the following will happen while the cursor is in the headline:
1275 - When the cursor is at the beginning of a headline, kill the entire
1276 line and possible the folded subtree below the line.
1277 - When in the middle of the headline text, kill the headline up to the tags.
1278 - When after the headline text, kill the tags."
1279 :group 'org-edit-structure
1280 :type 'boolean)
1282 (defcustom org-ctrl-k-protect-subtree nil
1283 "Non-nil means, do not delete a hidden subtree with C-k.
1284 When set to the symbol `error', simply throw an error when C-k is
1285 used to kill (part-of) a headline that has hidden text behind it.
1286 Any other non-nil value will result in a query to the user, if it is
1287 OK to kill that hidden subtree. When nil, kill without remorse."
1288 :group 'org-edit-structure
1289 :version "24.1"
1290 :type '(choice
1291 (const :tag "Do not protect hidden subtrees" nil)
1292 (const :tag "Protect hidden subtrees with a security query" t)
1293 (const :tag "Never kill a hidden subtree with C-k" error)))
1295 (defcustom org-special-ctrl-o t
1296 "Non-nil means, make `C-o' insert a row in tables."
1297 :group 'org-edit-structure
1298 :type 'boolean)
1300 (defcustom org-catch-invisible-edits nil
1301 "Check if in invisible region before inserting or deleting a character.
1302 Valid values are:
1304 nil Do not check, so just do invisible edits.
1305 error Throw an error and do nothing.
1306 show Make point visible, and do the requested edit.
1307 show-and-error Make point visible, then throw an error and abort the edit.
1308 smart Make point visible, and do insertion/deletion if it is
1309 adjacent to visible text and the change feels predictable.
1310 Never delete a previously invisible character or add in the
1311 middle or right after an invisible region. Basically, this
1312 allows insertion and backward-delete right before ellipses.
1313 FIXME: maybe in this case we should not even show?"
1314 :group 'org-edit-structure
1315 :version "24.1"
1316 :type '(choice
1317 (const :tag "Do not check" nil)
1318 (const :tag "Throw error when trying to edit" error)
1319 (const :tag "Unhide, but do not do the edit" show-and-error)
1320 (const :tag "Show invisible part and do the edit" show)
1321 (const :tag "Be smart and do the right thing" smart)))
1323 (defcustom org-yank-folded-subtrees t
1324 "Non-nil means when yanking subtrees, fold them.
1325 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1326 it starts with a heading and all other headings in it are either children
1327 or siblings, then fold all the subtrees. However, do this only if no
1328 text after the yank would be swallowed into a folded tree by this action."
1329 :group 'org-edit-structure
1330 :type 'boolean)
1332 (defcustom org-yank-adjusted-subtrees nil
1333 "Non-nil means when yanking subtrees, adjust the level.
1334 With this setting, `org-paste-subtree' is used to insert the subtree, see
1335 this function for details."
1336 :group 'org-edit-structure
1337 :type 'boolean)
1339 (defcustom org-M-RET-may-split-line '((default . t))
1340 "Non-nil means M-RET will split the line at the cursor position.
1341 When nil, it will go to the end of the line before making a
1342 new line.
1343 You may also set this option in a different way for different
1344 contexts. Valid contexts are:
1346 headline when creating a new headline
1347 item when creating a new item
1348 table in a table field
1349 default the value to be used for all contexts not explicitly
1350 customized"
1351 :group 'org-structure
1352 :group 'org-table
1353 :type '(choice
1354 (const :tag "Always" t)
1355 (const :tag "Never" nil)
1356 (repeat :greedy t :tag "Individual contexts"
1357 (cons
1358 (choice :tag "Context"
1359 (const headline)
1360 (const item)
1361 (const table)
1362 (const default))
1363 (boolean)))))
1366 (defcustom org-insert-heading-respect-content nil
1367 "Non-nil means insert new headings after the current subtree.
1368 When nil, the new heading is created directly after the current line.
1369 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1370 this variable on for the duration of the command."
1371 :group 'org-structure
1372 :type 'boolean)
1374 (defcustom org-blank-before-new-entry '((heading . auto)
1375 (plain-list-item . auto))
1376 "Should `org-insert-heading' leave a blank line before new heading/item?
1377 The value is an alist, with `heading' and `plain-list-item' as CAR,
1378 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1379 which case Org will look at the surrounding headings/items and try to
1380 make an intelligent decision whether to insert a blank line or not.
1382 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1383 the setting here is ignored and no empty line is inserted to avoid breaking
1384 the list structure."
1385 :group 'org-edit-structure
1386 :type '(list
1387 (cons (const heading)
1388 (choice (const :tag "Never" nil)
1389 (const :tag "Always" t)
1390 (const :tag "Auto" auto)))
1391 (cons (const plain-list-item)
1392 (choice (const :tag "Never" nil)
1393 (const :tag "Always" t)
1394 (const :tag "Auto" auto)))))
1396 (defcustom org-insert-heading-hook nil
1397 "Hook being run after inserting a new heading."
1398 :group 'org-edit-structure
1399 :type 'hook)
1401 (defcustom org-enable-fixed-width-editor t
1402 "Non-nil means lines starting with \":\" are treated as fixed-width.
1403 This currently only means they are never auto-wrapped.
1404 When nil, such lines will be treated like ordinary lines.
1405 See also the QUOTE keyword."
1406 :group 'org-edit-structure
1407 :type 'boolean)
1409 (defcustom org-goto-auto-isearch t
1410 "Non-nil means typing characters in `org-goto' starts incremental search.
1411 When nil, you can use these keybindings to navigate the buffer:
1413 q Quit the org-goto interface
1414 n Go to the next visible heading
1415 p Go to the previous visible heading
1416 f Go one heading forward on same level
1417 b Go one heading backward on same level
1418 u Go one heading up"
1419 :group 'org-edit-structure
1420 :type 'boolean)
1422 (defgroup org-sparse-trees nil
1423 "Options concerning sparse trees in Org-mode."
1424 :tag "Org Sparse Trees"
1425 :group 'org-structure)
1427 (defcustom org-highlight-sparse-tree-matches t
1428 "Non-nil means highlight all matches that define a sparse tree.
1429 The highlights will automatically disappear the next time the buffer is
1430 changed by an edit command."
1431 :group 'org-sparse-trees
1432 :type 'boolean)
1434 (defcustom org-remove-highlights-with-change t
1435 "Non-nil means any change to the buffer will remove temporary highlights.
1436 Such highlights are created by `org-occur' and `org-clock-display'.
1437 When nil, `C-c C-c needs to be used to get rid of the highlights.
1438 The highlights created by `org-preview-latex-fragment' always need
1439 `C-c C-c' to be removed."
1440 :group 'org-sparse-trees
1441 :group 'org-time
1442 :type 'boolean)
1445 (defcustom org-occur-hook '(org-first-headline-recenter)
1446 "Hook that is run after `org-occur' has constructed a sparse tree.
1447 This can be used to recenter the window to show as much of the structure
1448 as possible."
1449 :group 'org-sparse-trees
1450 :type 'hook)
1452 (defgroup org-imenu-and-speedbar nil
1453 "Options concerning imenu and speedbar in Org-mode."
1454 :tag "Org Imenu and Speedbar"
1455 :group 'org-structure)
1457 (defcustom org-imenu-depth 2
1458 "The maximum level for Imenu access to Org-mode headlines.
1459 This also applied for speedbar access."
1460 :group 'org-imenu-and-speedbar
1461 :type 'integer)
1463 (defgroup org-table nil
1464 "Options concerning tables in Org-mode."
1465 :tag "Org Table"
1466 :group 'org)
1468 (defcustom org-enable-table-editor 'optimized
1469 "Non-nil means lines starting with \"|\" are handled by the table editor.
1470 When nil, such lines will be treated like ordinary lines.
1472 When equal to the symbol `optimized', the table editor will be optimized to
1473 do the following:
1474 - Automatic overwrite mode in front of whitespace in table fields.
1475 This makes the structure of the table stay in tact as long as the edited
1476 field does not exceed the column width.
1477 - Minimize the number of realigns. Normally, the table is aligned each time
1478 TAB or RET are pressed to move to another field. With optimization this
1479 happens only if changes to a field might have changed the column width.
1480 Optimization requires replacing the functions `self-insert-command',
1481 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1482 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1483 very good at guessing when a re-align will be necessary, but you can always
1484 force one with \\[org-ctrl-c-ctrl-c].
1486 If you would like to use the optimized version in Org-mode, but the
1487 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1489 This variable can be used to turn on and off the table editor during a session,
1490 but in order to toggle optimization, a restart is required.
1492 See also the variable `org-table-auto-blank-field'."
1493 :group 'org-table
1494 :type '(choice
1495 (const :tag "off" nil)
1496 (const :tag "on" t)
1497 (const :tag "on, optimized" optimized)))
1499 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1500 (version<= emacs-version "24.1"))
1501 "Non-nil means cluster self-insert commands for undo when possible.
1502 If this is set, then, like in the Emacs command loop, 20 consecutive
1503 characters will be undone together.
1504 This is configurable, because there is some impact on typing performance."
1505 :group 'org-table
1506 :type 'boolean)
1508 (defcustom org-table-tab-recognizes-table.el t
1509 "Non-nil means TAB will automatically notice a table.el table.
1510 When it sees such a table, it moves point into it and - if necessary -
1511 calls `table-recognize-table'."
1512 :group 'org-table-editing
1513 :type 'boolean)
1515 (defgroup org-link nil
1516 "Options concerning links in Org-mode."
1517 :tag "Org Link"
1518 :group 'org)
1520 (defvar org-link-abbrev-alist-local nil
1521 "Buffer-local version of `org-link-abbrev-alist', which see.
1522 The value of this is taken from the #+LINK lines.")
1523 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1525 (defcustom org-link-abbrev-alist nil
1526 "Alist of link abbreviations.
1527 The car of each element is a string, to be replaced at the start of a link.
1528 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1529 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1531 [[linkkey:tag][description]]
1533 The 'linkkey' must be a word word, starting with a letter, followed
1534 by letters, numbers, '-' or '_'.
1536 If REPLACE is a string, the tag will simply be appended to create the link.
1537 If the string contains \"%s\", the tag will be inserted there. If the string
1538 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1539 at that point (see the function `url-hexify-string'). If the string contains
1540 the specifier \"%(my-function)\", then the custom function `my-function' will
1541 be invoked: this function takes the tag as its only argument and must return
1542 a string.
1544 REPLACE may also be a function that will be called with the tag as the
1545 only argument to create the link, which should be returned as a string.
1547 See the manual for examples."
1548 :group 'org-link
1549 :type '(repeat
1550 (cons
1551 (string :tag "Protocol")
1552 (choice
1553 (string :tag "Format")
1554 (function)))))
1556 (defcustom org-descriptive-links t
1557 "Non-nil means Org will display descriptive links.
1558 E.g. [[http://orgmode.org][Org website]] will be displayed as
1559 \"Org Website\", hiding the link itself and just displaying its
1560 description. When set to `nil', Org will display the full links
1561 literally.
1563 You can interactively set the value of this variable by calling
1564 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1565 :group 'org-link
1566 :type 'boolean)
1568 (defcustom org-link-file-path-type 'adaptive
1569 "How the path name in file links should be stored.
1570 Valid values are:
1572 relative Relative to the current directory, i.e. the directory of the file
1573 into which the link is being inserted.
1574 absolute Absolute path, if possible with ~ for home directory.
1575 noabbrev Absolute path, no abbreviation of home directory.
1576 adaptive Use relative path for files in the current directory and sub-
1577 directories of it. For other files, use an absolute path."
1578 :group 'org-link
1579 :type '(choice
1580 (const relative)
1581 (const absolute)
1582 (const noabbrev)
1583 (const adaptive)))
1585 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1586 "Types of links that should be activated in Org-mode files.
1587 This is a list of symbols, each leading to the activation of a certain link
1588 type. In principle, it does not hurt to turn on most link types - there may
1589 be a small gain when turning off unused link types. The types are:
1591 bracket The recommended [[link][description]] or [[link]] links with hiding.
1592 angle Links in angular brackets that may contain whitespace like
1593 <bbdb:Carsten Dominik>.
1594 plain Plain links in normal text, no whitespace, like http://google.com.
1595 radio Text that is matched by a radio target, see manual for details.
1596 tag Tag settings in a headline (link to tag search).
1597 date Time stamps (link to calendar).
1598 footnote Footnote labels.
1600 Changing this variable requires a restart of Emacs to become effective."
1601 :group 'org-link
1602 :type '(set :greedy t
1603 (const :tag "Double bracket links" bracket)
1604 (const :tag "Angular bracket links" angle)
1605 (const :tag "Plain text links" plain)
1606 (const :tag "Radio target matches" radio)
1607 (const :tag "Tags" tag)
1608 (const :tag "Timestamps" date)
1609 (const :tag "Footnotes" footnote)))
1611 (defcustom org-make-link-description-function nil
1612 "Function to use for generating link descriptions from links.
1613 When nil, the link location will be used. This function must take
1614 two parameters: the first one is the link, the second one is the
1615 description generated by `org-insert-link'. The function should
1616 return the description to use."
1617 :group 'org-link
1618 :type '(choice (const nil) (function)))
1620 (defgroup org-link-store nil
1621 "Options concerning storing links in Org-mode."
1622 :tag "Org Store Link"
1623 :group 'org-link)
1625 (defcustom org-url-hexify-p t
1626 "When non-nil, hexify URL when creating a link."
1627 :type 'boolean
1628 :version "24.3"
1629 :group 'org-link-store)
1631 (defcustom org-email-link-description-format "Email %c: %.30s"
1632 "Format of the description part of a link to an email or usenet message.
1633 The following %-escapes will be replaced by corresponding information:
1635 %F full \"From\" field
1636 %f name, taken from \"From\" field, address if no name
1637 %T full \"To\" field
1638 %t first name in \"To\" field, address if no name
1639 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1640 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1641 %s subject
1642 %d date
1643 %m message-id.
1645 You may use normal field width specification between the % and the letter.
1646 This is for example useful to limit the length of the subject.
1648 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1649 :group 'org-link-store
1650 :type 'string)
1652 (defcustom org-from-is-user-regexp
1653 (let (r1 r2)
1654 (when (and user-mail-address (not (string= user-mail-address "")))
1655 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1656 (when (and user-full-name (not (string= user-full-name "")))
1657 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1658 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1659 "Regexp matched against the \"From:\" header of an email or usenet message.
1660 It should match if the message is from the user him/herself."
1661 :group 'org-link-store
1662 :type 'regexp)
1664 (defcustom org-context-in-file-links t
1665 "Non-nil means file links from `org-store-link' contain context.
1666 A search string will be added to the file name with :: as separator and
1667 used to find the context when the link is activated by the command
1668 `org-open-at-point'. When this option is t, the entire active region
1669 will be placed in the search string of the file link. If set to a
1670 positive integer, only the first n lines of context will be stored.
1672 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1673 negates this setting for the duration of the command."
1674 :group 'org-link-store
1675 :type '(choice boolean integer))
1677 (defcustom org-keep-stored-link-after-insertion nil
1678 "Non-nil means keep link in list for entire session.
1680 The command `org-store-link' adds a link pointing to the current
1681 location to an internal list. These links accumulate during a session.
1682 The command `org-insert-link' can be used to insert links into any
1683 Org-mode file (offering completion for all stored links). When this
1684 option is nil, every link which has been inserted once using \\[org-insert-link]
1685 will be removed from the list, to make completing the unused links
1686 more efficient."
1687 :group 'org-link-store
1688 :type 'boolean)
1690 (defgroup org-link-follow nil
1691 "Options concerning following links in Org-mode."
1692 :tag "Org Follow Link"
1693 :group 'org-link)
1695 (defcustom org-link-translation-function nil
1696 "Function to translate links with different syntax to Org syntax.
1697 This can be used to translate links created for example by the Planner
1698 or emacs-wiki packages to Org syntax.
1699 The function must accept two parameters, a TYPE containing the link
1700 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1701 which is everything after the link protocol. It should return a cons
1702 with possibly modified values of type and path.
1703 Org contains a function for this, so if you set this variable to
1704 `org-translate-link-from-planner', you should be able follow many
1705 links created by planner."
1706 :group 'org-link-follow
1707 :type '(choice (const nil) (function)))
1709 (defcustom org-follow-link-hook nil
1710 "Hook that is run after a link has been followed."
1711 :group 'org-link-follow
1712 :type 'hook)
1714 (defcustom org-tab-follows-link nil
1715 "Non-nil means on links TAB will follow the link.
1716 Needs to be set before org.el is loaded.
1717 This really should not be used, it does not make sense, and the
1718 implementation is bad."
1719 :group 'org-link-follow
1720 :type 'boolean)
1722 (defcustom org-return-follows-link nil
1723 "Non-nil means on links RET will follow the link.
1724 In tables, the special behavior of RET has precedence."
1725 :group 'org-link-follow
1726 :type 'boolean)
1728 (defcustom org-mouse-1-follows-link
1729 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1730 "Non-nil means mouse-1 on a link will follow the link.
1731 A longer mouse click will still set point. Does not work on XEmacs.
1732 Needs to be set before org.el is loaded."
1733 :group 'org-link-follow
1734 :type 'boolean)
1736 (defcustom org-mark-ring-length 4
1737 "Number of different positions to be recorded in the ring.
1738 Changing this requires a restart of Emacs to work correctly."
1739 :group 'org-link-follow
1740 :type 'integer)
1742 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1743 "Non-nil means internal links in Org files must exactly match a headline.
1744 When nil, the link search tries to match a phrase with all words
1745 in the search text."
1746 :group 'org-link-follow
1747 :version "24.1"
1748 :type '(choice
1749 (const :tag "Use fuzzy text search" nil)
1750 (const :tag "Match only exact headline" t)
1751 (const :tag "Match exact headline or query to create it"
1752 query-to-create)))
1754 (defcustom org-link-frame-setup
1755 '((vm . vm-visit-folder-other-frame)
1756 (vm-imap . vm-visit-imap-folder-other-frame)
1757 (gnus . org-gnus-no-new-news)
1758 (file . find-file-other-window)
1759 (wl . wl-other-frame))
1760 "Setup the frame configuration for following links.
1761 When following a link with Emacs, it may often be useful to display
1762 this link in another window or frame. This variable can be used to
1763 set this up for the different types of links.
1764 For VM, use any of
1765 `vm-visit-folder'
1766 `vm-visit-folder-other-window'
1767 `vm-visit-folder-other-frame'
1768 For Gnus, use any of
1769 `gnus'
1770 `gnus-other-frame'
1771 `org-gnus-no-new-news'
1772 For FILE, use any of
1773 `find-file'
1774 `find-file-other-window'
1775 `find-file-other-frame'
1776 For Wanderlust use any of
1777 `wl'
1778 `wl-other-frame'
1779 For the calendar, use the variable `calendar-setup'.
1780 For BBDB, it is currently only possible to display the matches in
1781 another window."
1782 :group 'org-link-follow
1783 :type '(list
1784 (cons (const vm)
1785 (choice
1786 (const vm-visit-folder)
1787 (const vm-visit-folder-other-window)
1788 (const vm-visit-folder-other-frame)))
1789 (cons (const vm-imap)
1790 (choice
1791 (const vm-visit-imap-folder)
1792 (const vm-visit-imap-folder-other-window)
1793 (const vm-visit-imap-folder-other-frame)))
1794 (cons (const gnus)
1795 (choice
1796 (const gnus)
1797 (const gnus-other-frame)
1798 (const org-gnus-no-new-news)))
1799 (cons (const file)
1800 (choice
1801 (const find-file)
1802 (const find-file-other-window)
1803 (const find-file-other-frame)))
1804 (cons (const wl)
1805 (choice
1806 (const wl)
1807 (const wl-other-frame)))))
1809 (defcustom org-display-internal-link-with-indirect-buffer nil
1810 "Non-nil means use indirect buffer to display infile links.
1811 Activating internal links (from one location in a file to another location
1812 in the same file) normally just jumps to the location. When the link is
1813 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1814 is displayed in
1815 another window. When this option is set, the other window actually displays
1816 an indirect buffer clone of the current buffer, to avoid any visibility
1817 changes to the current buffer."
1818 :group 'org-link-follow
1819 :type 'boolean)
1821 (defcustom org-open-non-existing-files nil
1822 "Non-nil means `org-open-file' will open non-existing files.
1823 When nil, an error will be generated.
1824 This variable applies only to external applications because they
1825 might choke on non-existing files. If the link is to a file that
1826 will be opened in Emacs, the variable is ignored."
1827 :group 'org-link-follow
1828 :type 'boolean)
1830 (defcustom org-open-directory-means-index-dot-org nil
1831 "Non-nil means a link to a directory really means to index.org.
1832 When nil, following a directory link will run dired or open a finder/explorer
1833 window on that directory."
1834 :group 'org-link-follow
1835 :type 'boolean)
1837 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1838 "Function and arguments to call for following mailto links.
1839 This is a list with the first element being a Lisp function, and the
1840 remaining elements being arguments to the function. In string arguments,
1841 %a will be replaced by the address, and %s will be replaced by the subject
1842 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1843 :group 'org-link-follow
1844 :type '(choice
1845 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1846 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1847 (const :tag "message-mail" (message-mail "%a" "%s"))
1848 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1850 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1851 "Non-nil means ask for confirmation before executing shell links.
1852 Shell links can be dangerous: just think about a link
1854 [[shell:rm -rf ~/*][Google Search]]
1856 This link would show up in your Org-mode document as \"Google Search\",
1857 but really it would remove your entire home directory.
1858 Therefore we advise against setting this variable to nil.
1859 Just change it to `y-or-n-p' if you want to confirm with a
1860 single keystroke rather than having to type \"yes\"."
1861 :group 'org-link-follow
1862 :type '(choice
1863 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1864 (const :tag "with y-or-n (faster)" y-or-n-p)
1865 (const :tag "no confirmation (dangerous)" nil)))
1866 (put 'org-confirm-shell-link-function
1867 'safe-local-variable
1868 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1870 (defcustom org-confirm-shell-link-not-regexp ""
1871 "A regexp to skip confirmation for shell links."
1872 :group 'org-link-follow
1873 :version "24.1"
1874 :type 'regexp)
1876 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1877 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1878 Elisp links can be dangerous: just think about a link
1880 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1882 This link would show up in your Org-mode document as \"Google Search\",
1883 but really it would remove your entire home directory.
1884 Therefore we advise against setting this variable to nil.
1885 Just change it to `y-or-n-p' if you want to confirm with a
1886 single keystroke rather than having to type \"yes\"."
1887 :group 'org-link-follow
1888 :type '(choice
1889 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1890 (const :tag "with y-or-n (faster)" y-or-n-p)
1891 (const :tag "no confirmation (dangerous)" nil)))
1892 (put 'org-confirm-shell-link-function
1893 'safe-local-variable
1894 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1896 (defcustom org-confirm-elisp-link-not-regexp ""
1897 "A regexp to skip confirmation for Elisp links."
1898 :group 'org-link-follow
1899 :version "24.1"
1900 :type 'regexp)
1902 (defconst org-file-apps-defaults-gnu
1903 '((remote . emacs)
1904 (system . mailcap)
1905 (t . mailcap))
1906 "Default file applications on a UNIX or GNU/Linux system.
1907 See `org-file-apps'.")
1909 (defconst org-file-apps-defaults-macosx
1910 '((remote . emacs)
1911 (t . "open %s")
1912 (system . "open %s")
1913 ("ps.gz" . "gv %s")
1914 ("eps.gz" . "gv %s")
1915 ("dvi" . "xdvi %s")
1916 ("fig" . "xfig %s"))
1917 "Default file applications on a MacOS X system.
1918 The system \"open\" is known as a default, but we use X11 applications
1919 for some files for which the OS does not have a good default.
1920 See `org-file-apps'.")
1922 (defconst org-file-apps-defaults-windowsnt
1923 (list
1924 '(remote . emacs)
1925 (cons t
1926 (list (if (featurep 'xemacs)
1927 'mswindows-shell-execute
1928 'w32-shell-execute)
1929 "open" 'file))
1930 (cons 'system
1931 (list (if (featurep 'xemacs)
1932 'mswindows-shell-execute
1933 'w32-shell-execute)
1934 "open" 'file)))
1935 "Default file applications on a Windows NT system.
1936 The system \"open\" is used for most files.
1937 See `org-file-apps'.")
1939 (defcustom org-file-apps
1940 '((auto-mode . emacs)
1941 ("\\.mm\\'" . default)
1942 ("\\.x?html?\\'" . default)
1943 ("\\.pdf\\'" . default))
1944 "External applications for opening `file:path' items in a document.
1945 Org-mode uses system defaults for different file types, but
1946 you can use this variable to set the application for a given file
1947 extension. The entries in this list are cons cells where the car identifies
1948 files and the cdr the corresponding command. Possible values for the
1949 file identifier are
1950 \"string\" A string as a file identifier can be interpreted in different
1951 ways, depending on its contents:
1953 - Alphanumeric characters only:
1954 Match links with this file extension.
1955 Example: (\"pdf\" . \"evince %s\")
1956 to open PDFs with evince.
1958 - Regular expression: Match links where the
1959 filename matches the regexp. If you want to
1960 use groups here, use shy groups.
1962 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1963 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1964 to open *.html and *.xhtml with firefox.
1966 - Regular expression which contains (non-shy) groups:
1967 Match links where the whole link, including \"::\", and
1968 anything after that, matches the regexp.
1969 In a custom command string, %1, %2, etc. are replaced with
1970 the parts of the link that were matched by the groups.
1971 For backwards compatibility, if a command string is given
1972 that does not use any of the group matches, this case is
1973 handled identically to the second one (i.e. match against
1974 file name only).
1975 In a custom lisp form, you can access the group matches with
1976 (match-string n link).
1978 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1979 to open [[file:document.pdf::5]] with evince at page 5.
1981 `directory' Matches a directory
1982 `remote' Matches a remote file, accessible through tramp or efs.
1983 Remote files most likely should be visited through Emacs
1984 because external applications cannot handle such paths.
1985 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1986 so all files Emacs knows how to handle. Using this with
1987 command `emacs' will open most files in Emacs. Beware that this
1988 will also open html files inside Emacs, unless you add
1989 (\"html\" . default) to the list as well.
1990 t Default for files not matched by any of the other options.
1991 `system' The system command to open files, like `open' on Windows
1992 and Mac OS X, and mailcap under GNU/Linux. This is the command
1993 that will be selected if you call `C-c C-o' with a double
1994 \\[universal-argument] \\[universal-argument] prefix.
1996 Possible values for the command are:
1997 `emacs' The file will be visited by the current Emacs process.
1998 `default' Use the default application for this file type, which is the
1999 association for t in the list, most likely in the system-specific
2000 part.
2001 This can be used to overrule an unwanted setting in the
2002 system-specific variable.
2003 `system' Use the system command for opening files, like \"open\".
2004 This command is specified by the entry whose car is `system'.
2005 Most likely, the system-specific version of this variable
2006 does define this command, but you can overrule/replace it
2007 here.
2008 string A command to be executed by a shell; %s will be replaced
2009 by the path to the file.
2010 sexp A Lisp form which will be evaluated. The file path will
2011 be available in the Lisp variable `file'.
2012 For more examples, see the system specific constants
2013 `org-file-apps-defaults-macosx'
2014 `org-file-apps-defaults-windowsnt'
2015 `org-file-apps-defaults-gnu'."
2016 :group 'org-link-follow
2017 :type '(repeat
2018 (cons (choice :value ""
2019 (string :tag "Extension")
2020 (const :tag "System command to open files" system)
2021 (const :tag "Default for unrecognized files" t)
2022 (const :tag "Remote file" remote)
2023 (const :tag "Links to a directory" directory)
2024 (const :tag "Any files that have Emacs modes"
2025 auto-mode))
2026 (choice :value ""
2027 (const :tag "Visit with Emacs" emacs)
2028 (const :tag "Use default" default)
2029 (const :tag "Use the system command" system)
2030 (string :tag "Command")
2031 (sexp :tag "Lisp form")))))
2033 (defcustom org-doi-server-url "http://dx.doi.org/"
2034 "The URL of the DOI server."
2035 :type 'string
2036 :version "24.3"
2037 :group 'org-link-follow)
2039 (defgroup org-refile nil
2040 "Options concerning refiling entries in Org-mode."
2041 :tag "Org Refile"
2042 :group 'org)
2044 (defcustom org-directory "~/org"
2045 "Directory with org files.
2046 This is just a default location to look for Org files. There is no need
2047 at all to put your files into this directory. It is only used in the
2048 following situations:
2050 1. When a capture template specifies a target file that is not an
2051 absolute path. The path will then be interpreted relative to
2052 `org-directory'
2053 2. When a capture note is filed away in an interactive way (when exiting the
2054 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2055 with `org-directory' as the default path."
2056 :group 'org-refile
2057 :group 'org-capture
2058 :type 'directory)
2060 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2061 "Default target for storing notes.
2062 Used as a fall back file for org-capture.el, for templates that
2063 do not specify a target file."
2064 :group 'org-refile
2065 :group 'org-capture
2066 :type '(choice
2067 (const :tag "Default from remember-data-file" nil)
2068 file))
2070 (defcustom org-goto-interface 'outline
2071 "The default interface to be used for `org-goto'.
2072 Allowed values are:
2073 outline The interface shows an outline of the relevant file
2074 and the correct heading is found by moving through
2075 the outline or by searching with incremental search.
2076 outline-path-completion Headlines in the current buffer are offered via
2077 completion. This is the interface also used by
2078 the refile command."
2079 :group 'org-refile
2080 :type '(choice
2081 (const :tag "Outline" outline)
2082 (const :tag "Outline-path-completion" outline-path-completion)))
2084 (defcustom org-goto-max-level 5
2085 "Maximum target level when running `org-goto' with refile interface."
2086 :group 'org-refile
2087 :type 'integer)
2089 (defcustom org-reverse-note-order nil
2090 "Non-nil means store new notes at the beginning of a file or entry.
2091 When nil, new notes will be filed to the end of a file or entry.
2092 This can also be a list with cons cells of regular expressions that
2093 are matched against file names, and values."
2094 :group 'org-capture
2095 :group 'org-refile
2096 :type '(choice
2097 (const :tag "Reverse always" t)
2098 (const :tag "Reverse never" nil)
2099 (repeat :tag "By file name regexp"
2100 (cons regexp boolean))))
2102 (defcustom org-log-refile nil
2103 "Information to record when a task is refiled.
2105 Possible values are:
2107 nil Don't add anything
2108 time Add a time stamp to the task
2109 note Prompt for a note and add it with template `org-log-note-headings'
2111 This option can also be set with on a per-file-basis with
2113 #+STARTUP: nologrefile
2114 #+STARTUP: logrefile
2115 #+STARTUP: lognoterefile
2117 You can have local logging settings for a subtree by setting the LOGGING
2118 property to one or more of these keywords.
2120 When bulk-refiling from the agenda, the value `note' is forbidden and
2121 will temporarily be changed to `time'."
2122 :group 'org-refile
2123 :group 'org-progress
2124 :version "24.1"
2125 :type '(choice
2126 (const :tag "No logging" nil)
2127 (const :tag "Record timestamp" time)
2128 (const :tag "Record timestamp with note." note)))
2130 (defcustom org-refile-targets nil
2131 "Targets for refiling entries with \\[org-refile].
2132 This is a list of cons cells. Each cell contains:
2133 - a specification of the files to be considered, either a list of files,
2134 or a symbol whose function or variable value will be used to retrieve
2135 a file name or a list of file names. If you use `org-agenda-files' for
2136 that, all agenda files will be scanned for targets. Nil means consider
2137 headings in the current buffer.
2138 - A specification of how to find candidate refile targets. This may be
2139 any of:
2140 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2141 This tag has to be present in all target headlines, inheritance will
2142 not be considered.
2143 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2144 todo keyword.
2145 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2146 headlines that are refiling targets.
2147 - a cons cell (:level . N). Any headline of level N is considered a target.
2148 Note that, when `org-odd-levels-only' is set, level corresponds to
2149 order in hierarchy, not to the number of stars.
2150 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2151 Note that, when `org-odd-levels-only' is set, level corresponds to
2152 order in hierarchy, not to the number of stars.
2154 Each element of this list generates a set of possible targets.
2155 The union of these sets is presented (with completion) to
2156 the user by `org-refile'.
2158 You can set the variable `org-refile-target-verify-function' to a function
2159 to verify each headline found by the simple criteria above.
2161 When this variable is nil, all top-level headlines in the current buffer
2162 are used, equivalent to the value `((nil . (:level . 1))'."
2163 :group 'org-refile
2164 :type '(repeat
2165 (cons
2166 (choice :value org-agenda-files
2167 (const :tag "All agenda files" org-agenda-files)
2168 (const :tag "Current buffer" nil)
2169 (function) (variable) (file))
2170 (choice :tag "Identify target headline by"
2171 (cons :tag "Specific tag" (const :value :tag) (string))
2172 (cons :tag "TODO keyword" (const :value :todo) (string))
2173 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2174 (cons :tag "Level number" (const :value :level) (integer))
2175 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2177 (defcustom org-refile-target-verify-function nil
2178 "Function to verify if the headline at point should be a refile target.
2179 The function will be called without arguments, with point at the
2180 beginning of the headline. It should return t and leave point
2181 where it is if the headline is a valid target for refiling.
2183 If the target should not be selected, the function must return nil.
2184 In addition to this, it may move point to a place from where the search
2185 should be continued. For example, the function may decide that the entire
2186 subtree of the current entry should be excluded and move point to the end
2187 of the subtree."
2188 :group 'org-refile
2189 :type '(choice
2190 (const nil)
2191 (function)))
2193 (defcustom org-refile-use-cache nil
2194 "Non-nil means cache refile targets to speed up the process.
2195 The cache for a particular file will be updated automatically when
2196 the buffer has been killed, or when any of the marker used for flagging
2197 refile targets no longer points at a live buffer.
2198 If you have added new entries to a buffer that might themselves be targets,
2199 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2200 find that easier, `C-u C-u C-u C-c C-w'."
2201 :group 'org-refile
2202 :version "24.1"
2203 :type 'boolean)
2205 (defcustom org-refile-use-outline-path nil
2206 "Non-nil means provide refile targets as paths.
2207 So a level 3 headline will be available as level1/level2/level3.
2209 When the value is `file', also include the file name (without directory)
2210 into the path. In this case, you can also stop the completion after
2211 the file name, to get entries inserted as top level in the file.
2213 When `full-file-path', include the full file path."
2214 :group 'org-refile
2215 :type '(choice
2216 (const :tag "Not" nil)
2217 (const :tag "Yes" t)
2218 (const :tag "Start with file name" file)
2219 (const :tag "Start with full file path" full-file-path)))
2221 (defcustom org-outline-path-complete-in-steps t
2222 "Non-nil means complete the outline path in hierarchical steps.
2223 When Org-mode uses the refile interface to select an outline path
2224 \(see variable `org-refile-use-outline-path'), the completion of
2225 the path can be done is a single go, or if can be done in steps down
2226 the headline hierarchy. Going in steps is probably the best if you
2227 do not use a special completion package like `ido' or `icicles'.
2228 However, when using these packages, going in one step can be very
2229 fast, while still showing the whole path to the entry."
2230 :group 'org-refile
2231 :type 'boolean)
2233 (defcustom org-refile-allow-creating-parent-nodes nil
2234 "Non-nil means allow to create new nodes as refile targets.
2235 New nodes are then created by adding \"/new node name\" to the completion
2236 of an existing node. When the value of this variable is `confirm',
2237 new node creation must be confirmed by the user (recommended)
2238 When nil, the completion must match an existing entry.
2240 Note that, if the new heading is not seen by the criteria
2241 listed in `org-refile-targets', multiple instances of the same
2242 heading would be created by trying again to file under the new
2243 heading."
2244 :group 'org-refile
2245 :type '(choice
2246 (const :tag "Never" nil)
2247 (const :tag "Always" t)
2248 (const :tag "Prompt for confirmation" confirm)))
2250 (defcustom org-refile-active-region-within-subtree nil
2251 "Non-nil means also refile active region within a subtree.
2253 By default `org-refile' doesn't allow refiling regions if they
2254 don't contain a set of subtrees, but it might be convenient to
2255 do so sometimes: in that case, the first line of the region is
2256 converted to a headline before refiling."
2257 :group 'org-refile
2258 :version "24.1"
2259 :type 'boolean)
2261 (defgroup org-todo nil
2262 "Options concerning TODO items in Org-mode."
2263 :tag "Org TODO"
2264 :group 'org)
2266 (defgroup org-progress nil
2267 "Options concerning Progress logging in Org-mode."
2268 :tag "Org Progress"
2269 :group 'org-time)
2271 (defvar org-todo-interpretation-widgets
2272 '((:tag "Sequence (cycling hits every state)" sequence)
2273 (:tag "Type (cycling directly to DONE)" type))
2274 "The available interpretation symbols for customizing `org-todo-keywords'.
2275 Interested libraries should add to this list.")
2277 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2278 "List of TODO entry keyword sequences and their interpretation.
2279 \\<org-mode-map>This is a list of sequences.
2281 Each sequence starts with a symbol, either `sequence' or `type',
2282 indicating if the keywords should be interpreted as a sequence of
2283 action steps, or as different types of TODO items. The first
2284 keywords are states requiring action - these states will select a headline
2285 for inclusion into the global TODO list Org-mode produces. If one of
2286 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2287 signify that no further action is necessary. If \"|\" is not found,
2288 the last keyword is treated as the only DONE state of the sequence.
2290 The command \\[org-todo] cycles an entry through these states, and one
2291 additional state where no keyword is present. For details about this
2292 cycling, see the manual.
2294 TODO keywords and interpretation can also be set on a per-file basis with
2295 the special #+SEQ_TODO and #+TYP_TODO lines.
2297 Each keyword can optionally specify a character for fast state selection
2298 \(in combination with the variable `org-use-fast-todo-selection')
2299 and specifiers for state change logging, using the same syntax that
2300 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2301 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2302 indicates to record a time stamp each time this state is selected.
2304 Each keyword may also specify if a timestamp or a note should be
2305 recorded when entering or leaving the state, by adding additional
2306 characters in the parenthesis after the keyword. This looks like this:
2307 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2308 record only the time of the state change. With X and Y being either
2309 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2310 Y when leaving the state if and only if the *target* state does not
2311 define X. You may omit any of the fast-selection key or X or /Y,
2312 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2314 For backward compatibility, this variable may also be just a list
2315 of keywords. In this case the interpretation (sequence or type) will be
2316 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2317 :group 'org-todo
2318 :group 'org-keywords
2319 :type '(choice
2320 (repeat :tag "Old syntax, just keywords"
2321 (string :tag "Keyword"))
2322 (repeat :tag "New syntax"
2323 (cons
2324 (choice
2325 :tag "Interpretation"
2326 ;;Quick and dirty way to see
2327 ;;`org-todo-interpretations'. This takes the
2328 ;;place of item arguments
2329 :convert-widget
2330 (lambda (widget)
2331 (widget-put widget
2332 :args (mapcar
2333 #'(lambda (x)
2334 (widget-convert
2335 (cons 'const x)))
2336 org-todo-interpretation-widgets))
2337 widget))
2338 (repeat
2339 (string :tag "Keyword"))))))
2341 (defvar org-todo-keywords-1 nil
2342 "All TODO and DONE keywords active in a buffer.")
2343 (make-variable-buffer-local 'org-todo-keywords-1)
2344 (defvar org-todo-keywords-for-agenda nil)
2345 (defvar org-done-keywords-for-agenda nil)
2346 (defvar org-drawers-for-agenda nil)
2347 (defvar org-todo-keyword-alist-for-agenda nil)
2348 (defvar org-tag-alist-for-agenda nil
2349 "Alist of all tags from all agenda files.")
2350 (defvar org-tag-groups-alist-for-agenda nil
2351 "Alist of all groups tags from all current agenda files.")
2352 (defvar org-tag-groups-alist nil)
2353 (make-variable-buffer-local 'org-tag-groups-alist)
2354 (defvar org-agenda-contributing-files nil)
2355 (defvar org-not-done-keywords nil)
2356 (make-variable-buffer-local 'org-not-done-keywords)
2357 (defvar org-done-keywords nil)
2358 (make-variable-buffer-local 'org-done-keywords)
2359 (defvar org-todo-heads nil)
2360 (make-variable-buffer-local 'org-todo-heads)
2361 (defvar org-todo-sets nil)
2362 (make-variable-buffer-local 'org-todo-sets)
2363 (defvar org-todo-log-states nil)
2364 (make-variable-buffer-local 'org-todo-log-states)
2365 (defvar org-todo-kwd-alist nil)
2366 (make-variable-buffer-local 'org-todo-kwd-alist)
2367 (defvar org-todo-key-alist nil)
2368 (make-variable-buffer-local 'org-todo-key-alist)
2369 (defvar org-todo-key-trigger nil)
2370 (make-variable-buffer-local 'org-todo-key-trigger)
2372 (defcustom org-todo-interpretation 'sequence
2373 "Controls how TODO keywords are interpreted.
2374 This variable is in principle obsolete and is only used for
2375 backward compatibility, if the interpretation of todo keywords is
2376 not given already in `org-todo-keywords'. See that variable for
2377 more information."
2378 :group 'org-todo
2379 :group 'org-keywords
2380 :type '(choice (const sequence)
2381 (const type)))
2383 (defcustom org-use-fast-todo-selection t
2384 "Non-nil means use the fast todo selection scheme with C-c C-t.
2385 This variable describes if and under what circumstances the cycling
2386 mechanism for TODO keywords will be replaced by a single-key, direct
2387 selection scheme.
2389 When nil, fast selection is never used.
2391 When the symbol `prefix', it will be used when `org-todo' is called
2392 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2393 `C-u t' in an agenda buffer.
2395 When t, fast selection is used by default. In this case, the prefix
2396 argument forces cycling instead.
2398 In all cases, the special interface is only used if access keys have
2399 actually been assigned by the user, i.e. if keywords in the configuration
2400 are followed by a letter in parenthesis, like TODO(t)."
2401 :group 'org-todo
2402 :type '(choice
2403 (const :tag "Never" nil)
2404 (const :tag "By default" t)
2405 (const :tag "Only with C-u C-c C-t" prefix)))
2407 (defcustom org-provide-todo-statistics t
2408 "Non-nil means update todo statistics after insert and toggle.
2409 ALL-HEADLINES means update todo statistics by including headlines
2410 with no TODO keyword as well, counting them as not done.
2411 A list of TODO keywords means the same, but skip keywords that are
2412 not in this list.
2414 When this is set, todo statistics is updated in the parent of the
2415 current entry each time a todo state is changed."
2416 :group 'org-todo
2417 :type '(choice
2418 (const :tag "Yes, only for TODO entries" t)
2419 (const :tag "Yes, including all entries" 'all-headlines)
2420 (repeat :tag "Yes, for TODOs in this list"
2421 (string :tag "TODO keyword"))
2422 (other :tag "No TODO statistics" nil)))
2424 (defcustom org-hierarchical-todo-statistics t
2425 "Non-nil means TODO statistics covers just direct children.
2426 When nil, all entries in the subtree are considered.
2427 This has only an effect if `org-provide-todo-statistics' is set.
2428 To set this to nil for only a single subtree, use a COOKIE_DATA
2429 property and include the word \"recursive\" into the value."
2430 :group 'org-todo
2431 :type 'boolean)
2433 (defcustom org-after-todo-state-change-hook nil
2434 "Hook which is run after the state of a TODO item was changed.
2435 The new state (a string with a TODO keyword, or nil) is available in the
2436 Lisp variable `org-state'."
2437 :group 'org-todo
2438 :type 'hook)
2440 (defvar org-blocker-hook nil
2441 "Hook for functions that are allowed to block a state change.
2443 Functions in this hook should not modify the buffer.
2444 Each function gets as its single argument a property list,
2445 see `org-trigger-hook' for more information about this list.
2447 If any of the functions in this hook returns nil, the state change
2448 is blocked.")
2450 (defvar org-trigger-hook nil
2451 "Hook for functions that are triggered by a state change.
2453 Each function gets as its single argument a property list with at
2454 least the following elements:
2456 (:type type-of-change :position pos-at-entry-start
2457 :from old-state :to new-state)
2459 Depending on the type, more properties may be present.
2461 This mechanism is currently implemented for:
2463 TODO state changes
2464 ------------------
2465 :type todo-state-change
2466 :from previous state (keyword as a string), or nil, or a symbol
2467 'todo' or 'done', to indicate the general type of state.
2468 :to new state, like in :from")
2470 (defcustom org-enforce-todo-dependencies nil
2471 "Non-nil means undone TODO entries will block switching the parent to DONE.
2472 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2473 be blocked if any prior sibling is not yet done.
2474 Finally, if the parent is blocked because of ordered siblings of its own,
2475 the child will also be blocked."
2476 :set (lambda (var val)
2477 (set var val)
2478 (if val
2479 (add-hook 'org-blocker-hook
2480 'org-block-todo-from-children-or-siblings-or-parent)
2481 (remove-hook 'org-blocker-hook
2482 'org-block-todo-from-children-or-siblings-or-parent)))
2483 :group 'org-todo
2484 :type 'boolean)
2486 (defcustom org-enforce-todo-checkbox-dependencies nil
2487 "Non-nil means unchecked boxes will block switching the parent to DONE.
2488 When this is nil, checkboxes have no influence on switching TODO states.
2489 When non-nil, you first need to check off all check boxes before the TODO
2490 entry can be switched to DONE.
2491 This variable needs to be set before org.el is loaded, and you need to
2492 restart Emacs after a change to make the change effective. The only way
2493 to change is while Emacs is running is through the customize interface."
2494 :set (lambda (var val)
2495 (set var val)
2496 (if val
2497 (add-hook 'org-blocker-hook
2498 'org-block-todo-from-checkboxes)
2499 (remove-hook 'org-blocker-hook
2500 'org-block-todo-from-checkboxes)))
2501 :group 'org-todo
2502 :type 'boolean)
2504 (defcustom org-treat-insert-todo-heading-as-state-change nil
2505 "Non-nil means inserting a TODO heading is treated as state change.
2506 So when the command \\[org-insert-todo-heading] is used, state change
2507 logging will apply if appropriate. When nil, the new TODO item will
2508 be inserted directly, and no logging will take place."
2509 :group 'org-todo
2510 :type 'boolean)
2512 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2513 "Non-nil means switching TODO states with S-cursor counts as state change.
2514 This is the default behavior. However, setting this to nil allows a
2515 convenient way to select a TODO state and bypass any logging associated
2516 with that."
2517 :group 'org-todo
2518 :type 'boolean)
2520 (defcustom org-todo-state-tags-triggers nil
2521 "Tag changes that should be triggered by TODO state changes.
2522 This is a list. Each entry is
2524 (state-change (tag . flag) .......)
2526 State-change can be a string with a state, and empty string to indicate the
2527 state that has no TODO keyword, or it can be one of the symbols `todo'
2528 or `done', meaning any not-done or done state, respectively."
2529 :group 'org-todo
2530 :group 'org-tags
2531 :type '(repeat
2532 (cons (choice :tag "When changing to"
2533 (const :tag "Not-done state" todo)
2534 (const :tag "Done state" done)
2535 (string :tag "State"))
2536 (repeat
2537 (cons :tag "Tag action"
2538 (string :tag "Tag")
2539 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2541 (defcustom org-log-done nil
2542 "Information to record when a task moves to the DONE state.
2544 Possible values are:
2546 nil Don't add anything, just change the keyword
2547 time Add a time stamp to the task
2548 note Prompt for a note and add it with template `org-log-note-headings'
2550 This option can also be set with on a per-file-basis with
2552 #+STARTUP: nologdone
2553 #+STARTUP: logdone
2554 #+STARTUP: lognotedone
2556 You can have local logging settings for a subtree by setting the LOGGING
2557 property to one or more of these keywords."
2558 :group 'org-todo
2559 :group 'org-progress
2560 :type '(choice
2561 (const :tag "No logging" nil)
2562 (const :tag "Record CLOSED timestamp" time)
2563 (const :tag "Record CLOSED timestamp with note." note)))
2565 ;; Normalize old uses of org-log-done.
2566 (cond
2567 ((eq org-log-done t) (setq org-log-done 'time))
2568 ((and (listp org-log-done) (memq 'done org-log-done))
2569 (setq org-log-done 'note)))
2571 (defcustom org-log-reschedule nil
2572 "Information to record when the scheduling date of a tasks is modified.
2574 Possible values are:
2576 nil Don't add anything, just change the date
2577 time Add a time stamp to the task
2578 note Prompt for a note and add it with template `org-log-note-headings'
2580 This option can also be set with on a per-file-basis with
2582 #+STARTUP: nologreschedule
2583 #+STARTUP: logreschedule
2584 #+STARTUP: lognotereschedule"
2585 :group 'org-todo
2586 :group 'org-progress
2587 :type '(choice
2588 (const :tag "No logging" nil)
2589 (const :tag "Record timestamp" time)
2590 (const :tag "Record timestamp with note." note)))
2592 (defcustom org-log-redeadline nil
2593 "Information to record when the deadline date of a tasks is modified.
2595 Possible values are:
2597 nil Don't add anything, just change the date
2598 time Add a time stamp to the task
2599 note Prompt for a note and add it with template `org-log-note-headings'
2601 This option can also be set with on a per-file-basis with
2603 #+STARTUP: nologredeadline
2604 #+STARTUP: logredeadline
2605 #+STARTUP: lognoteredeadline
2607 You can have local logging settings for a subtree by setting the LOGGING
2608 property to one or more of these keywords."
2609 :group 'org-todo
2610 :group 'org-progress
2611 :type '(choice
2612 (const :tag "No logging" nil)
2613 (const :tag "Record timestamp" time)
2614 (const :tag "Record timestamp with note." note)))
2616 (defcustom org-log-note-clock-out nil
2617 "Non-nil means record a note when clocking out of an item.
2618 This can also be configured on a per-file basis by adding one of
2619 the following lines anywhere in the buffer:
2621 #+STARTUP: lognoteclock-out
2622 #+STARTUP: nolognoteclock-out"
2623 :group 'org-todo
2624 :group 'org-progress
2625 :type 'boolean)
2627 (defcustom org-log-done-with-time t
2628 "Non-nil means the CLOSED time stamp will contain date and time.
2629 When nil, only the date will be recorded."
2630 :group 'org-progress
2631 :type 'boolean)
2633 (defcustom org-log-note-headings
2634 '((done . "CLOSING NOTE %t")
2635 (state . "State %-12s from %-12S %t")
2636 (note . "Note taken on %t")
2637 (reschedule . "Rescheduled from %S on %t")
2638 (delschedule . "Not scheduled, was %S on %t")
2639 (redeadline . "New deadline from %S on %t")
2640 (deldeadline . "Removed deadline, was %S on %t")
2641 (refile . "Refiled on %t")
2642 (clock-out . ""))
2643 "Headings for notes added to entries.
2644 The value is an alist, with the car being a symbol indicating the note
2645 context, and the cdr is the heading to be used. The heading may also be the
2646 empty string.
2647 %t in the heading will be replaced by a time stamp.
2648 %T will be an active time stamp instead the default inactive one
2649 %d will be replaced by a short-format time stamp.
2650 %D will be replaced by an active short-format time stamp.
2651 %s will be replaced by the new TODO state, in double quotes.
2652 %S will be replaced by the old TODO state, in double quotes.
2653 %u will be replaced by the user name.
2654 %U will be replaced by the full user name.
2656 In fact, it is not a good idea to change the `state' entry, because
2657 agenda log mode depends on the format of these entries."
2658 :group 'org-todo
2659 :group 'org-progress
2660 :type '(list :greedy t
2661 (cons (const :tag "Heading when closing an item" done) string)
2662 (cons (const :tag
2663 "Heading when changing todo state (todo sequence only)"
2664 state) string)
2665 (cons (const :tag "Heading when just taking a note" note) string)
2666 (cons (const :tag "Heading when clocking out" clock-out) string)
2667 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2668 (cons (const :tag "Heading when rescheduling" reschedule) string)
2669 (cons (const :tag "Heading when changing deadline" redeadline) string)
2670 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2671 (cons (const :tag "Heading when refiling" refile) string)))
2673 (unless (assq 'note org-log-note-headings)
2674 (push '(note . "%t") org-log-note-headings))
2676 (defcustom org-log-into-drawer nil
2677 "Non-nil means insert state change notes and time stamps into a drawer.
2678 When nil, state changes notes will be inserted after the headline and
2679 any scheduling and clock lines, but not inside a drawer.
2681 The value of this variable should be the name of the drawer to use.
2682 LOGBOOK is proposed as the default drawer for this purpose, you can
2683 also set this to a string to define the drawer of your choice.
2685 A value of t is also allowed, representing \"LOGBOOK\".
2687 A value of t or nil can also be set with on a per-file-basis with
2689 #+STARTUP: logdrawer
2690 #+STARTUP: nologdrawer
2692 If this variable is set, `org-log-state-notes-insert-after-drawers'
2693 will be ignored.
2695 You can set the property LOG_INTO_DRAWER to overrule this setting for
2696 a subtree."
2697 :group 'org-todo
2698 :group 'org-progress
2699 :type '(choice
2700 (const :tag "Not into a drawer" nil)
2701 (const :tag "LOGBOOK" t)
2702 (string :tag "Other")))
2704 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2706 (defun org-log-into-drawer ()
2707 "Return the value of `org-log-into-drawer', but let properties overrule.
2708 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2709 used instead of the default value."
2710 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2711 (cond
2712 ((not p) org-log-into-drawer)
2713 ((equal p "nil") nil)
2714 ((equal p "t") "LOGBOOK")
2715 (t p))))
2717 (defcustom org-log-state-notes-insert-after-drawers nil
2718 "Non-nil means insert state change notes after any drawers in entry.
2719 Only the drawers that *immediately* follow the headline and the
2720 deadline/scheduled line are skipped.
2721 When nil, insert notes right after the heading and perhaps the line
2722 with deadline/scheduling if present.
2724 This variable will have no effect if `org-log-into-drawer' is
2725 set."
2726 :group 'org-todo
2727 :group 'org-progress
2728 :type 'boolean)
2730 (defcustom org-log-states-order-reversed t
2731 "Non-nil means the latest state note will be directly after heading.
2732 When nil, the state change notes will be ordered according to time.
2734 This option can also be set with on a per-file-basis with
2736 #+STARTUP: logstatesreversed
2737 #+STARTUP: nologstatesreversed"
2738 :group 'org-todo
2739 :group 'org-progress
2740 :type 'boolean)
2742 (defcustom org-todo-repeat-to-state nil
2743 "The TODO state to which a repeater should return the repeating task.
2744 By default this is the first task in a TODO sequence, or the previous state
2745 in a TODO_TYP set. But you can specify another task here.
2746 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2747 :group 'org-todo
2748 :version "24.1"
2749 :type '(choice (const :tag "Head of sequence" nil)
2750 (string :tag "Specific state")))
2752 (defcustom org-log-repeat 'time
2753 "Non-nil means record moving through the DONE state when triggering repeat.
2754 An auto-repeating task is immediately switched back to TODO when
2755 marked DONE. If you are not logging state changes (by adding \"@\"
2756 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2757 record a closing note, there will be no record of the task moving
2758 through DONE. This variable forces taking a note anyway.
2760 nil Don't force a record
2761 time Record a time stamp
2762 note Prompt for a note and add it with template `org-log-note-headings'
2764 This option can also be set with on a per-file-basis with
2766 #+STARTUP: nologrepeat
2767 #+STARTUP: logrepeat
2768 #+STARTUP: lognoterepeat
2770 You can have local logging settings for a subtree by setting the LOGGING
2771 property to one or more of these keywords."
2772 :group 'org-todo
2773 :group 'org-progress
2774 :type '(choice
2775 (const :tag "Don't force a record" nil)
2776 (const :tag "Force recording the DONE state" time)
2777 (const :tag "Force recording a note with the DONE state" note)))
2780 (defgroup org-priorities nil
2781 "Priorities in Org-mode."
2782 :tag "Org Priorities"
2783 :group 'org-todo)
2785 (defcustom org-enable-priority-commands t
2786 "Non-nil means priority commands are active.
2787 When nil, these commands will be disabled, so that you never accidentally
2788 set a priority."
2789 :group 'org-priorities
2790 :type 'boolean)
2792 (defcustom org-highest-priority ?A
2793 "The highest priority of TODO items. A character like ?A, ?B etc.
2794 Must have a smaller ASCII number than `org-lowest-priority'."
2795 :group 'org-priorities
2796 :type 'character)
2798 (defcustom org-lowest-priority ?C
2799 "The lowest priority of TODO items. A character like ?A, ?B etc.
2800 Must have a larger ASCII number than `org-highest-priority'."
2801 :group 'org-priorities
2802 :type 'character)
2804 (defcustom org-default-priority ?B
2805 "The default priority of TODO items.
2806 This is the priority an item gets if no explicit priority is given.
2807 When starting to cycle on an empty priority the first step in the cycle
2808 depends on `org-priority-start-cycle-with-default'. The resulting first
2809 step priority must not exceed the range from `org-highest-priority' to
2810 `org-lowest-priority' which means that `org-default-priority' has to be
2811 in this range exclusive or inclusive the range boundaries. Else the
2812 first step refuses to set the default and the second will fall back
2813 to (depending on the command used) the highest or lowest priority."
2814 :group 'org-priorities
2815 :type 'character)
2817 (defcustom org-priority-start-cycle-with-default t
2818 "Non-nil means start with default priority when starting to cycle.
2819 When this is nil, the first step in the cycle will be (depending on the
2820 command used) one higher or lower than the default priority.
2821 See also `org-default-priority'."
2822 :group 'org-priorities
2823 :type 'boolean)
2825 (defcustom org-get-priority-function nil
2826 "Function to extract the priority from a string.
2827 The string is normally the headline. If this is nil Org computes the
2828 priority from the priority cookie like [#A] in the headline. It returns
2829 an integer, increasing by 1000 for each priority level.
2830 The user can set a different function here, which should take a string
2831 as an argument and return the numeric priority."
2832 :group 'org-priorities
2833 :version "24.1"
2834 :type '(choice
2835 (const nil)
2836 (function)))
2838 (defgroup org-time nil
2839 "Options concerning time stamps and deadlines in Org-mode."
2840 :tag "Org Time"
2841 :group 'org)
2843 (defcustom org-insert-labeled-timestamps-at-point nil
2844 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2845 When nil, these labeled time stamps are forces into the second line of an
2846 entry, just after the headline. When scheduling from the global TODO list,
2847 the time stamp will always be forced into the second line."
2848 :group 'org-time
2849 :type 'boolean)
2851 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2852 "Formats for `format-time-string' which are used for time stamps.
2853 It is not recommended to change this constant.")
2855 (defcustom org-time-stamp-rounding-minutes '(0 5)
2856 "Number of minutes to round time stamps to.
2857 These are two values, the first applies when first creating a time stamp.
2858 The second applies when changing it with the commands `S-up' and `S-down'.
2859 When changing the time stamp, this means that it will change in steps
2860 of N minutes, as given by the second value.
2862 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2863 numbers should be factors of 60, so for example 5, 10, 15.
2865 When this is larger than 1, you can still force an exact time stamp by using
2866 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2867 and by using a prefix arg to `S-up/down' to specify the exact number
2868 of minutes to shift."
2869 :group 'org-time
2870 :get #'(lambda (var) ; Make sure both elements are there
2871 (if (integerp (default-value var))
2872 (list (default-value var) 5)
2873 (default-value var)))
2874 :type '(list
2875 (integer :tag "when inserting times")
2876 (integer :tag "when modifying times")))
2878 ;; Normalize old customizations of this variable.
2879 (when (integerp org-time-stamp-rounding-minutes)
2880 (setq org-time-stamp-rounding-minutes
2881 (list org-time-stamp-rounding-minutes
2882 org-time-stamp-rounding-minutes)))
2884 (defcustom org-display-custom-times nil
2885 "Non-nil means overlay custom formats over all time stamps.
2886 The formats are defined through the variable `org-time-stamp-custom-formats'.
2887 To turn this on on a per-file basis, insert anywhere in the file:
2888 #+STARTUP: customtime"
2889 :group 'org-time
2890 :set 'set-default
2891 :type 'sexp)
2892 (make-variable-buffer-local 'org-display-custom-times)
2894 (defcustom org-time-stamp-custom-formats
2895 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2896 "Custom formats for time stamps. See `format-time-string' for the syntax.
2897 These are overlaid over the default ISO format if the variable
2898 `org-display-custom-times' is set. Time like %H:%M should be at the
2899 end of the second format. The custom formats are also honored by export
2900 commands, if custom time display is turned on at the time of export."
2901 :group 'org-time
2902 :type 'sexp)
2904 (defun org-time-stamp-format (&optional long inactive)
2905 "Get the right format for a time string."
2906 (let ((f (if long (cdr org-time-stamp-formats)
2907 (car org-time-stamp-formats))))
2908 (if inactive
2909 (concat "[" (substring f 1 -1) "]")
2910 f)))
2912 (defcustom org-time-clocksum-format
2913 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2914 "The format string used when creating CLOCKSUM lines.
2915 This is also used when Org mode generates a time duration.
2917 The value can be a single format string containing two
2918 %-sequences, which will be filled with the number of hours and
2919 minutes in that order.
2921 Alternatively, the value can be a plist associating any of the
2922 keys :years, :months, :weeks, :days, :hours or :minutes with
2923 format strings. The time duration is formatted using only the
2924 time components that are needed and concatenating the results.
2925 If a time unit in absent, it falls back to the next smallest
2926 unit.
2928 The keys :require-years, :require-months, :require-days,
2929 :require-weeks, :require-hours, :require-minutes are also
2930 meaningful. A non-nil value for these keys indicates that the
2931 corresponding time component should always be included, even if
2932 its value is 0.
2935 For example,
2937 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2938 :require-minutes t)
2940 means durations longer than a day will be expressed in days,
2941 hours and minutes, and durations less than a day will always be
2942 expressed in hours and minutes (even for durations less than an
2943 hour).
2945 The value
2947 \(:days \"%dd\" :minutes \"%dm\")
2949 means durations longer than a day will be expressed in days and
2950 minutes, and durations less than a day will be expressed entirely
2951 in minutes (even for durations longer than an hour)."
2952 :group 'org-time
2953 :group 'org-clock
2954 :version "24.4"
2955 :package-version '(Org . "8.0")
2956 :type '(choice (string :tag "Format string")
2957 (set :tag "Plist"
2958 (group :inline t (const :tag "Years" :years)
2959 (string :tag "Format string"))
2960 (group :inline t
2961 (const :tag "Always show years" :require-years)
2962 (const t))
2963 (group :inline t (const :tag "Months" :months)
2964 (string :tag "Format string"))
2965 (group :inline t
2966 (const :tag "Always show months" :require-months)
2967 (const t))
2968 (group :inline t (const :tag "Weeks" :weeks)
2969 (string :tag "Format string"))
2970 (group :inline t
2971 (const :tag "Always show weeks" :require-weeks)
2972 (const t))
2973 (group :inline t (const :tag "Days" :days)
2974 (string :tag "Format string"))
2975 (group :inline t
2976 (const :tag "Always show days" :require-days)
2977 (const t))
2978 (group :inline t (const :tag "Hours" :hours)
2979 (string :tag "Format string"))
2980 (group :inline t
2981 (const :tag "Always show hours" :require-hours)
2982 (const t))
2983 (group :inline t (const :tag "Minutes" :minutes)
2984 (string :tag "Format string"))
2985 (group :inline t
2986 (const :tag "Always show minutes" :require-minutes)
2987 (const t)))))
2989 (defcustom org-time-clocksum-use-fractional nil
2990 "When non-nil, \\[org-clock-display] uses fractional times.
2991 See `org-time-clocksum-format' for more on time clock formats."
2992 :group 'org-time
2993 :group 'org-clock
2994 :version "24.3"
2995 :type 'boolean)
2997 (defcustom org-time-clocksum-use-effort-durations nil
2998 "When non-nil, \\[org-clock-display] uses effort durations.
2999 E.g. by default, one day is considered to be a 8 hours effort,
3000 so a task that has been clocked for 16 hours will be displayed
3001 as during 2 days in the clock display or in the clocktable.
3003 See `org-effort-durations' on how to set effort durations
3004 and `org-time-clocksum-format' for more on time clock formats."
3005 :group 'org-time
3006 :group 'org-clock
3007 :version "24.4"
3008 :package-version '(Org . "8.0")
3009 :type 'boolean)
3011 (defcustom org-time-clocksum-fractional-format "%.2f"
3012 "The format string used when creating CLOCKSUM lines,
3013 or when Org mode generates a time duration, if
3014 `org-time-clocksum-use-fractional' is enabled.
3016 The value can be a single format string containing one
3017 %-sequence, which will be filled with the number of hours as
3018 a float.
3020 Alternatively, the value can be a plist associating any of the
3021 keys :years, :months, :weeks, :days, :hours or :minutes with
3022 a format string. The time duration is formatted using the
3023 largest time unit which gives a non-zero integer part. If all
3024 specified formats have zero integer part, the smallest time unit
3025 is used."
3026 :group 'org-time
3027 :type '(choice (string :tag "Format string")
3028 (set (group :inline t (const :tag "Years" :years)
3029 (string :tag "Format string"))
3030 (group :inline t (const :tag "Months" :months)
3031 (string :tag "Format string"))
3032 (group :inline t (const :tag "Weeks" :weeks)
3033 (string :tag "Format string"))
3034 (group :inline t (const :tag "Days" :days)
3035 (string :tag "Format string"))
3036 (group :inline t (const :tag "Hours" :hours)
3037 (string :tag "Format string"))
3038 (group :inline t (const :tag "Minutes" :minutes)
3039 (string :tag "Format string")))))
3041 (defcustom org-deadline-warning-days 14
3042 "Number of days before expiration during which a deadline becomes active.
3043 This variable governs the display in sparse trees and in the agenda.
3044 When 0 or negative, it means use this number (the absolute value of it)
3045 even if a deadline has a different individual lead time specified.
3047 Custom commands can set this variable in the options section."
3048 :group 'org-time
3049 :group 'org-agenda-daily/weekly
3050 :type 'integer)
3052 (defcustom org-scheduled-delay-days 0
3053 "Number of days before a scheduled item becomes active.
3054 This variable governs the display in sparse trees and in the agenda.
3055 The default value (i.e. 0) means: don't delay scheduled item.
3056 When negative, it means use this number (the absolute value of it)
3057 even if a scheduled item has a different individual delay time
3058 specified.
3060 Custom commands can set this variable in the options section."
3061 :group 'org-time
3062 :group 'org-agenda-daily/weekly
3063 :version "24.4"
3064 :package-version '(Org . "8.0")
3065 :type 'integer)
3067 (defcustom org-read-date-prefer-future t
3068 "Non-nil means assume future for incomplete date input from user.
3069 This affects the following situations:
3070 1. The user gives a month but not a year.
3071 For example, if it is April and you enter \"feb 2\", this will be read
3072 as Feb 2, *next* year. \"May 5\", however, will be this year.
3073 2. The user gives a day, but no month.
3074 For example, if today is the 15th, and you enter \"3\", Org-mode will
3075 read this as the third of *next* month. However, if you enter \"17\",
3076 it will be considered as *this* month.
3078 If you set this variable to the symbol `time', then also the following
3079 will work:
3081 3. If the user gives a time.
3082 If the time is before now, it will be interpreted as tomorrow.
3084 Currently none of this works for ISO week specifications.
3086 When this option is nil, the current day, month and year will always be
3087 used as defaults.
3089 See also `org-agenda-jump-prefer-future'."
3090 :group 'org-time
3091 :type '(choice
3092 (const :tag "Never" nil)
3093 (const :tag "Check month and day" t)
3094 (const :tag "Check month, day, and time" time)))
3096 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3097 "Should the agenda jump command prefer the future for incomplete dates?
3098 The default is to do the same as configured in `org-read-date-prefer-future'.
3099 But you can also set a deviating value here.
3100 This may t or nil, or the symbol `org-read-date-prefer-future'."
3101 :group 'org-agenda
3102 :group 'org-time
3103 :version "24.1"
3104 :type '(choice
3105 (const :tag "Use org-read-date-prefer-future"
3106 org-read-date-prefer-future)
3107 (const :tag "Never" nil)
3108 (const :tag "Always" t)))
3110 (defcustom org-read-date-force-compatible-dates t
3111 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3113 Depending on the system Emacs is running on, certain dates cannot
3114 be represented with the type used internally to represent time.
3115 Dates between 1970-1-1 and 2038-1-1 can always be represented
3116 correctly. Some systems allow for earlier dates, some for later,
3117 some for both. One way to find out it to insert any date into an
3118 Org buffer, putting the cursor on the year and hitting S-up and
3119 S-down to test the range.
3121 When this variable is set to t, the date/time prompt will not let
3122 you specify dates outside the 1970-2037 range, so it is certain that
3123 these dates will work in whatever version of Emacs you are
3124 running, and also that you can move a file from one Emacs implementation
3125 to another. WHenever Org is forcing the year for you, it will display
3126 a message and beep.
3128 When this variable is nil, Org will check if the date is
3129 representable in the specific Emacs implementation you are using.
3130 If not, it will force a year, usually the current year, and beep
3131 to remind you. Currently this setting is not recommended because
3132 the likelihood that you will open your Org files in an Emacs that
3133 has limited date range is not negligible.
3135 A workaround for this problem is to use diary sexp dates for time
3136 stamps outside of this range."
3137 :group 'org-time
3138 :version "24.1"
3139 :type 'boolean)
3141 (defcustom org-read-date-display-live t
3142 "Non-nil means display current interpretation of date prompt live.
3143 This display will be in an overlay, in the minibuffer."
3144 :group 'org-time
3145 :type 'boolean)
3147 (defcustom org-read-date-popup-calendar t
3148 "Non-nil means pop up a calendar when prompting for a date.
3149 In the calendar, the date can be selected with mouse-1. However, the
3150 minibuffer will also be active, and you can simply enter the date as well.
3151 When nil, only the minibuffer will be available."
3152 :group 'org-time
3153 :type 'boolean)
3154 (org-defvaralias 'org-popup-calendar-for-date-prompt
3155 'org-read-date-popup-calendar)
3157 (make-obsolete-variable
3158 'org-read-date-minibuffer-setup-hook
3159 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3160 (defcustom org-read-date-minibuffer-setup-hook nil
3161 "Hook to be used to set up keys for the date/time interface.
3162 Add key definitions to `minibuffer-local-map', which will be a
3163 temporary copy.
3165 WARNING: This option is obsolete, you should use
3166 `org-read-date-minibuffer-local-map' to set up keys."
3167 :group 'org-time
3168 :type 'hook)
3170 (defcustom org-extend-today-until 0
3171 "The hour when your day really ends. Must be an integer.
3172 This has influence for the following applications:
3173 - When switching the agenda to \"today\". It it is still earlier than
3174 the time given here, the day recognized as TODAY is actually yesterday.
3175 - When a date is read from the user and it is still before the time given
3176 here, the current date and time will be assumed to be yesterday, 23:59.
3177 Also, timestamps inserted in capture templates follow this rule.
3179 IMPORTANT: This is a feature whose implementation is and likely will
3180 remain incomplete. Really, it is only here because past midnight seems to
3181 be the favorite working time of John Wiegley :-)"
3182 :group 'org-time
3183 :type 'integer)
3185 (defcustom org-use-effective-time nil
3186 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3187 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3188 \"effective time\" of any timestamps between midnight and 8am will be
3189 23:59 of the previous day."
3190 :group 'org-time
3191 :version "24.1"
3192 :type 'boolean)
3194 (defcustom org-use-last-clock-out-time-as-effective-time nil
3195 "When non-nil, use the last clock out time for `org-todo'.
3196 Note that this option has precedence over the combined use of
3197 `org-use-effective-time' and `org-extend-today-until'."
3198 :group 'org-time
3199 :version "24.4"
3200 :package-version '(Org . "8.0")
3201 :type 'boolean)
3203 (defcustom org-edit-timestamp-down-means-later nil
3204 "Non-nil means S-down will increase the time in a time stamp.
3205 When nil, S-up will increase."
3206 :group 'org-time
3207 :type 'boolean)
3209 (defcustom org-calendar-follow-timestamp-change t
3210 "Non-nil means make the calendar window follow timestamp changes.
3211 When a timestamp is modified and the calendar window is visible, it will be
3212 moved to the new date."
3213 :group 'org-time
3214 :type 'boolean)
3216 (defgroup org-tags nil
3217 "Options concerning tags in Org-mode."
3218 :tag "Org Tags"
3219 :group 'org)
3221 (defcustom org-tag-alist nil
3222 "List of tags allowed in Org-mode files.
3223 When this list is nil, Org-mode will base TAG input on what is already in the
3224 buffer.
3225 The value of this variable is an alist, the car of each entry must be a
3226 keyword as a string, the cdr may be a character that is used to select
3227 that tag through the fast-tag-selection interface.
3228 See the manual for details."
3229 :group 'org-tags
3230 :type '(repeat
3231 (choice
3232 (cons (string :tag "Tag name")
3233 (character :tag "Access char"))
3234 (list :tag "Start radio group"
3235 (const :startgroup)
3236 (option (string :tag "Group description")))
3237 (list :tag "Group tags delimiter"
3238 (const :grouptags))
3239 (list :tag "End radio group"
3240 (const :endgroup)
3241 (option (string :tag "Group description")))
3242 (const :tag "New line" (:newline)))))
3244 (defcustom org-tag-persistent-alist nil
3245 "List of tags that will always appear in all Org-mode files.
3246 This is in addition to any in buffer settings or customizations
3247 of `org-tag-alist'.
3248 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3249 The value of this variable is an alist, the car of each entry must be a
3250 keyword as a string, the cdr may be a character that is used to select
3251 that tag through the fast-tag-selection interface.
3252 See the manual for details.
3253 To disable these tags on a per-file basis, insert anywhere in the file:
3254 #+STARTUP: noptag"
3255 :group 'org-tags
3256 :type '(repeat
3257 (choice
3258 (cons (string :tag "Tag name")
3259 (character :tag "Access char"))
3260 (const :tag "Start radio group" (:startgroup))
3261 (const :tag "Group tags delimiter" (:grouptags))
3262 (const :tag "End radio group" (:endgroup))
3263 (const :tag "New line" (:newline)))))
3265 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3266 "If non-nil, always offer completion for all tags of all agenda files.
3267 Instead of customizing this variable directly, you might want to
3268 set it locally for capture buffers, because there no list of
3269 tags in that file can be created dynamically (there are none).
3271 (add-hook 'org-capture-mode-hook
3272 (lambda ()
3273 (set (make-local-variable
3274 'org-complete-tags-always-offer-all-agenda-tags)
3275 t)))"
3276 :group 'org-tags
3277 :version "24.1"
3278 :type 'boolean)
3280 (defvar org-file-tags nil
3281 "List of tags that can be inherited by all entries in the file.
3282 The tags will be inherited if the variable `org-use-tag-inheritance'
3283 says they should be.
3284 This variable is populated from #+FILETAGS lines.")
3286 (defcustom org-use-fast-tag-selection 'auto
3287 "Non-nil means use fast tag selection scheme.
3288 This is a special interface to select and deselect tags with single keys.
3289 When nil, fast selection is never used.
3290 When the symbol `auto', fast selection is used if and only if selection
3291 characters for tags have been configured, either through the variable
3292 `org-tag-alist' or through a #+TAGS line in the buffer.
3293 When t, fast selection is always used and selection keys are assigned
3294 automatically if necessary."
3295 :group 'org-tags
3296 :type '(choice
3297 (const :tag "Always" t)
3298 (const :tag "Never" nil)
3299 (const :tag "When selection characters are configured" auto)))
3301 (defcustom org-fast-tag-selection-single-key nil
3302 "Non-nil means fast tag selection exits after first change.
3303 When nil, you have to press RET to exit it.
3304 During fast tag selection, you can toggle this flag with `C-c'.
3305 This variable can also have the value `expert'. In this case, the window
3306 displaying the tags menu is not even shown, until you press C-c again."
3307 :group 'org-tags
3308 :type '(choice
3309 (const :tag "No" nil)
3310 (const :tag "Yes" t)
3311 (const :tag "Expert" expert)))
3313 (defvar org-fast-tag-selection-include-todo nil
3314 "Non-nil means fast tags selection interface will also offer TODO states.
3315 This is an undocumented feature, you should not rely on it.")
3317 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3318 "The column to which tags should be indented in a headline.
3319 If this number is positive, it specifies the column. If it is negative,
3320 it means that the tags should be flushright to that column. For example,
3321 -80 works well for a normal 80 character screen.
3322 When 0, place tags directly after headline text, with only one space in
3323 between."
3324 :group 'org-tags
3325 :type 'integer)
3327 (defcustom org-auto-align-tags t
3328 "Non-nil keeps tags aligned when modifying headlines.
3329 Some operations (i.e. demoting) change the length of a headline and
3330 therefore shift the tags around. With this option turned on, after
3331 each such operation the tags are again aligned to `org-tags-column'."
3332 :group 'org-tags
3333 :type 'boolean)
3335 (defcustom org-use-tag-inheritance t
3336 "Non-nil means tags in levels apply also for sublevels.
3337 When nil, only the tags directly given in a specific line apply there.
3338 This may also be a list of tags that should be inherited, or a regexp that
3339 matches tags that should be inherited. Additional control is possible
3340 with the variable `org-tags-exclude-from-inheritance' which gives an
3341 explicit list of tags to be excluded from inheritance, even if the value of
3342 `org-use-tag-inheritance' would select it for inheritance.
3344 If this option is t, a match early-on in a tree can lead to a large
3345 number of matches in the subtree when constructing the agenda or creating
3346 a sparse tree. If you only want to see the first match in a tree during
3347 a search, check out the variable `org-tags-match-list-sublevels'."
3348 :group 'org-tags
3349 :type '(choice
3350 (const :tag "Not" nil)
3351 (const :tag "Always" t)
3352 (repeat :tag "Specific tags" (string :tag "Tag"))
3353 (regexp :tag "Tags matched by regexp")))
3355 (defcustom org-tags-exclude-from-inheritance nil
3356 "List of tags that should never be inherited.
3357 This is a way to exclude a few tags from inheritance. For way to do
3358 the opposite, to actively allow inheritance for selected tags,
3359 see the variable `org-use-tag-inheritance'."
3360 :group 'org-tags
3361 :type '(repeat (string :tag "Tag")))
3363 (defun org-tag-inherit-p (tag)
3364 "Check if TAG is one that should be inherited."
3365 (cond
3366 ((member tag org-tags-exclude-from-inheritance) nil)
3367 ((eq org-use-tag-inheritance t) t)
3368 ((not org-use-tag-inheritance) nil)
3369 ((stringp org-use-tag-inheritance)
3370 (string-match org-use-tag-inheritance tag))
3371 ((listp org-use-tag-inheritance)
3372 (member tag org-use-tag-inheritance))
3373 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3375 (defcustom org-tags-match-list-sublevels t
3376 "Non-nil means list also sublevels of headlines matching a search.
3377 This variable applies to tags/property searches, and also to stuck
3378 projects because this search is based on a tags match as well.
3380 When set to the symbol `indented', sublevels are indented with
3381 leading dots.
3383 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3384 the sublevels of a headline matching a tag search often also match
3385 the same search. Listing all of them can create very long lists.
3386 Setting this variable to nil causes subtrees of a match to be skipped.
3388 This variable is semi-obsolete and probably should always be true. It
3389 is better to limit inheritance to certain tags using the variables
3390 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3391 :group 'org-tags
3392 :type '(choice
3393 (const :tag "No, don't list them" nil)
3394 (const :tag "Yes, do list them" t)
3395 (const :tag "List them, indented with leading dots" indented)))
3397 (defcustom org-tags-sort-function nil
3398 "When set, tags are sorted using this function as a comparator."
3399 :group 'org-tags
3400 :type '(choice
3401 (const :tag "No sorting" nil)
3402 (const :tag "Alphabetical" string<)
3403 (const :tag "Reverse alphabetical" string>)
3404 (function :tag "Custom function" nil)))
3406 (defvar org-tags-history nil
3407 "History of minibuffer reads for tags.")
3408 (defvar org-last-tags-completion-table nil
3409 "The last used completion table for tags.")
3410 (defvar org-after-tags-change-hook nil
3411 "Hook that is run after the tags in a line have changed.")
3413 (defgroup org-properties nil
3414 "Options concerning properties in Org-mode."
3415 :tag "Org Properties"
3416 :group 'org)
3418 (defcustom org-property-format "%-10s %s"
3419 "How property key/value pairs should be formatted by `indent-line'.
3420 When `indent-line' hits a property definition, it will format the line
3421 according to this format, mainly to make sure that the values are
3422 lined-up with respect to each other."
3423 :group 'org-properties
3424 :type 'string)
3426 (defcustom org-properties-postprocess-alist nil
3427 "Alist of properties and functions to adjust inserted values.
3428 Elements of this alist must be of the form
3430 ([string] [function])
3432 where [string] must be a property name and [function] must be a
3433 lambda expression: this lambda expression must take one argument,
3434 the value to adjust, and return the new value as a string.
3436 For example, this element will allow the property \"Remaining\"
3437 to be updated wrt the relation between the \"Effort\" property
3438 and the clock summary:
3440 ((\"Remaining\" (lambda(value)
3441 (let ((clocksum (org-clock-sum-current-item))
3442 (effort (org-duration-string-to-minutes
3443 (org-entry-get (point) \"Effort\"))))
3444 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3445 :group 'org-properties
3446 :version "24.1"
3447 :type '(alist :key-type (string :tag "Property")
3448 :value-type (function :tag "Function")))
3450 (defcustom org-use-property-inheritance nil
3451 "Non-nil means properties apply also for sublevels.
3453 This setting is chiefly used during property searches. Turning it on can
3454 cause significant overhead when doing a search, which is why it is not
3455 on by default.
3457 When nil, only the properties directly given in the current entry count.
3458 When t, every property is inherited. The value may also be a list of
3459 properties that should have inheritance, or a regular expression matching
3460 properties that should be inherited.
3462 However, note that some special properties use inheritance under special
3463 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3464 and the properties ending in \"_ALL\" when they are used as descriptor
3465 for valid values of a property.
3467 Note for programmers:
3468 When querying an entry with `org-entry-get', you can control if inheritance
3469 should be used. By default, `org-entry-get' looks only at the local
3470 properties. You can request inheritance by setting the inherit argument
3471 to t (to force inheritance) or to `selective' (to respect the setting
3472 in this variable)."
3473 :group 'org-properties
3474 :type '(choice
3475 (const :tag "Not" nil)
3476 (const :tag "Always" t)
3477 (repeat :tag "Specific properties" (string :tag "Property"))
3478 (regexp :tag "Properties matched by regexp")))
3480 (defun org-property-inherit-p (property)
3481 "Check if PROPERTY is one that should be inherited."
3482 (cond
3483 ((eq org-use-property-inheritance t) t)
3484 ((not org-use-property-inheritance) nil)
3485 ((stringp org-use-property-inheritance)
3486 (string-match org-use-property-inheritance property))
3487 ((listp org-use-property-inheritance)
3488 (member property org-use-property-inheritance))
3489 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3491 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3492 "The default column format, if no other format has been defined.
3493 This variable can be set on the per-file basis by inserting a line
3495 #+COLUMNS: %25ITEM ....."
3496 :group 'org-properties
3497 :type 'string)
3499 (defcustom org-columns-ellipses ".."
3500 "The ellipses to be used when a field in column view is truncated.
3501 When this is the empty string, as many characters as possible are shown,
3502 but then there will be no visual indication that the field has been truncated.
3503 When this is a string of length N, the last N characters of a truncated
3504 field are replaced by this string. If the column is narrower than the
3505 ellipses string, only part of the ellipses string will be shown."
3506 :group 'org-properties
3507 :type 'string)
3509 (defcustom org-columns-modify-value-for-display-function nil
3510 "Function that modifies values for display in column view.
3511 For example, it can be used to cut out a certain part from a time stamp.
3512 The function must take 2 arguments:
3514 column-title The title of the column (*not* the property name)
3515 value The value that should be modified.
3517 The function should return the value that should be displayed,
3518 or nil if the normal value should be used."
3519 :group 'org-properties
3520 :type '(choice (const nil) (function)))
3522 (defcustom org-effort-property "Effort"
3523 "The property that is being used to keep track of effort estimates.
3524 Effort estimates given in this property need to have the format H:MM."
3525 :group 'org-properties
3526 :group 'org-progress
3527 :type '(string :tag "Property"))
3529 (defconst org-global-properties-fixed
3530 '(("VISIBILITY_ALL" . "folded children content all")
3531 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3532 "List of property/value pairs that can be inherited by any entry.
3534 These are fixed values, for the preset properties. The user variable
3535 that can be used to add to this list is `org-global-properties'.
3537 The entries in this list are cons cells where the car is a property
3538 name and cdr is a string with the value. If the value represents
3539 multiple items like an \"_ALL\" property, separate the items by
3540 spaces.")
3542 (defcustom org-global-properties nil
3543 "List of property/value pairs that can be inherited by any entry.
3545 This list will be combined with the constant `org-global-properties-fixed'.
3547 The entries in this list are cons cells where the car is a property
3548 name and cdr is a string with the value.
3550 You can set buffer-local values for the same purpose in the variable
3551 `org-file-properties' this by adding lines like
3553 #+PROPERTY: NAME VALUE"
3554 :group 'org-properties
3555 :type '(repeat
3556 (cons (string :tag "Property")
3557 (string :tag "Value"))))
3559 (defvar org-file-properties nil
3560 "List of property/value pairs that can be inherited by any entry.
3561 Valid for the current buffer.
3562 This variable is populated from #+PROPERTY lines.")
3563 (make-variable-buffer-local 'org-file-properties)
3565 (defgroup org-agenda nil
3566 "Options concerning agenda views in Org-mode."
3567 :tag "Org Agenda"
3568 :group 'org)
3570 (defvar org-category nil
3571 "Variable used by org files to set a category for agenda display.
3572 Such files should use a file variable to set it, for example
3574 # -*- mode: org; org-category: \"ELisp\"
3576 or contain a special line
3578 #+CATEGORY: ELisp
3580 If the file does not specify a category, then file's base name
3581 is used instead.")
3582 (make-variable-buffer-local 'org-category)
3583 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3585 (defcustom org-agenda-files nil
3586 "The files to be used for agenda display.
3587 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3588 \\[org-remove-file]. You can also use customize to edit the list.
3590 If an entry is a directory, all files in that directory that are matched by
3591 `org-agenda-file-regexp' will be part of the file list.
3593 If the value of the variable is not a list but a single file name, then
3594 the list of agenda files is actually stored and maintained in that file, one
3595 agenda file per line. In this file paths can be given relative to
3596 `org-directory'. Tilde expansion and environment variable substitution
3597 are also made."
3598 :group 'org-agenda
3599 :type '(choice
3600 (repeat :tag "List of files and directories" file)
3601 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3603 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3604 "Regular expression to match files for `org-agenda-files'.
3605 If any element in the list in that variable contains a directory instead
3606 of a normal file, all files in that directory that are matched by this
3607 regular expression will be included."
3608 :group 'org-agenda
3609 :type 'regexp)
3611 (defcustom org-agenda-text-search-extra-files nil
3612 "List of extra files to be searched by text search commands.
3613 These files will be searched in addition to the agenda files by the
3614 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3615 Note that these files will only be searched for text search commands,
3616 not for the other agenda views like todo lists, tag searches or the weekly
3617 agenda. This variable is intended to list notes and possibly archive files
3618 that should also be searched by these two commands.
3619 In fact, if the first element in the list is the symbol `agenda-archives',
3620 then all archive files of all agenda files will be added to the search
3621 scope."
3622 :group 'org-agenda
3623 :type '(set :greedy t
3624 (const :tag "Agenda Archives" agenda-archives)
3625 (repeat :inline t (file))))
3627 (org-defvaralias 'org-agenda-multi-occur-extra-files
3628 'org-agenda-text-search-extra-files)
3630 (defcustom org-agenda-skip-unavailable-files nil
3631 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3632 A nil value means to remove them, after a query, from the list."
3633 :group 'org-agenda
3634 :type 'boolean)
3636 (defcustom org-calendar-to-agenda-key [?c]
3637 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3638 The command `org-calendar-goto-agenda' will be bound to this key. The
3639 default is the character `c' because then `c' can be used to switch back and
3640 forth between agenda and calendar."
3641 :group 'org-agenda
3642 :type 'sexp)
3644 (defcustom org-calendar-insert-diary-entry-key [?i]
3645 "The key to be installed in `calendar-mode-map' for adding diary entries.
3646 This option is irrelevant until `org-agenda-diary-file' has been configured
3647 to point to an Org-mode file. When that is the case, the command
3648 `org-agenda-diary-entry' will be bound to the key given here, by default
3649 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3650 if you want to continue doing this, you need to change this to a different
3651 key."
3652 :group 'org-agenda
3653 :type 'sexp)
3655 (defcustom org-agenda-diary-file 'diary-file
3656 "File to which to add new entries with the `i' key in agenda and calendar.
3657 When this is the symbol `diary-file', the functionality in the Emacs
3658 calendar will be used to add entries to the `diary-file'. But when this
3659 points to a file, `org-agenda-diary-entry' will be used instead."
3660 :group 'org-agenda
3661 :type '(choice
3662 (const :tag "The standard Emacs diary file" diary-file)
3663 (file :tag "Special Org file diary entries")))
3665 (eval-after-load "calendar"
3666 '(progn
3667 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3668 'org-calendar-goto-agenda)
3669 (add-hook 'calendar-mode-hook
3670 (lambda ()
3671 (unless (eq org-agenda-diary-file 'diary-file)
3672 (define-key calendar-mode-map
3673 org-calendar-insert-diary-entry-key
3674 'org-agenda-diary-entry))))))
3676 (defgroup org-latex nil
3677 "Options for embedding LaTeX code into Org-mode."
3678 :tag "Org LaTeX"
3679 :group 'org)
3681 (defcustom org-format-latex-options
3682 '(:foreground default :background default :scale 1.0
3683 :html-foreground "Black" :html-background "Transparent"
3684 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3685 "Options for creating images from LaTeX fragments.
3686 This is a property list with the following properties:
3687 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3688 `default' means use the foreground of the default face.
3689 `auto' means use the foreground from the text face.
3690 :background the background color, or \"Transparent\".
3691 `default' means use the background of the default face.
3692 `auto' means use the background from the text face.
3693 :scale a scaling factor for the size of the images, to get more pixels
3694 :html-foreground, :html-background, :html-scale
3695 the same numbers for HTML export.
3696 :matchers a list indicating which matchers should be used to
3697 find LaTeX fragments. Valid members of this list are:
3698 \"begin\" find environments
3699 \"$1\" find single characters surrounded by $.$
3700 \"$\" find math expressions surrounded by $...$
3701 \"$$\" find math expressions surrounded by $$....$$
3702 \"\\(\" find math expressions surrounded by \\(...\\)
3703 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3704 :group 'org-latex
3705 :type 'plist)
3707 (defcustom org-format-latex-signal-error t
3708 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3709 When nil, just push out a message."
3710 :group 'org-latex
3711 :version "24.1"
3712 :type 'boolean)
3714 (defcustom org-latex-to-mathml-jar-file nil
3715 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3716 Use this to specify additional executable file say a jar file.
3718 When using MathToWeb as the converter, specify the full-path to
3719 your mathtoweb.jar file."
3720 :group 'org-latex
3721 :version "24.1"
3722 :type '(choice
3723 (const :tag "None" nil)
3724 (file :tag "JAR file" :must-match t)))
3726 (defcustom org-latex-to-mathml-convert-command nil
3727 "Command to convert LaTeX fragments to MathML.
3728 Replace format-specifiers in the command as noted below and use
3729 `shell-command' to convert LaTeX to MathML.
3730 %j: Executable file in fully expanded form as specified by
3731 `org-latex-to-mathml-jar-file'.
3732 %I: Input LaTeX file in fully expanded form
3733 %o: Output MathML file
3734 This command is used by `org-create-math-formula'.
3736 When using MathToWeb as the converter, set this to
3737 \"java -jar %j -unicode -force -df %o %I\"."
3738 :group 'org-latex
3739 :version "24.1"
3740 :type '(choice
3741 (const :tag "None" nil)
3742 (string :tag "\nShell command")))
3744 (defcustom org-latex-create-formula-image-program 'dvipng
3745 "Program to convert LaTeX fragments with.
3747 dvipng Process the LaTeX fragments to dvi file, then convert
3748 dvi files to png files using dvipng.
3749 This will also include processing of non-math environments.
3750 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3751 to convert pdf files to png files"
3752 :group 'org-latex
3753 :version "24.1"
3754 :type '(choice
3755 (const :tag "dvipng" dvipng)
3756 (const :tag "imagemagick" imagemagick)))
3758 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3759 "Path to store latex preview images.
3760 A relative path here creates many directories relative to the
3761 processed org files paths. An absolute path puts all preview
3762 images at the same place."
3763 :group 'org-latex
3764 :version "24.3"
3765 :type 'string)
3767 (defun org-format-latex-mathml-available-p ()
3768 "Return t if `org-latex-to-mathml-convert-command' is usable."
3769 (save-match-data
3770 (when (and (boundp 'org-latex-to-mathml-convert-command)
3771 org-latex-to-mathml-convert-command)
3772 (let ((executable (car (split-string
3773 org-latex-to-mathml-convert-command))))
3774 (when (executable-find executable)
3775 (if (string-match
3776 "%j" org-latex-to-mathml-convert-command)
3777 (file-readable-p org-latex-to-mathml-jar-file)
3778 t))))))
3780 (defcustom org-format-latex-header "\\documentclass{article}
3781 \\usepackage[usenames]{color}
3782 \[PACKAGES]
3783 \[DEFAULT-PACKAGES]
3784 \\pagestyle{empty} % do not remove
3785 % The settings below are copied from fullpage.sty
3786 \\setlength{\\textwidth}{\\paperwidth}
3787 \\addtolength{\\textwidth}{-3cm}
3788 \\setlength{\\oddsidemargin}{1.5cm}
3789 \\addtolength{\\oddsidemargin}{-2.54cm}
3790 \\setlength{\\evensidemargin}{\\oddsidemargin}
3791 \\setlength{\\textheight}{\\paperheight}
3792 \\addtolength{\\textheight}{-\\headheight}
3793 \\addtolength{\\textheight}{-\\headsep}
3794 \\addtolength{\\textheight}{-\\footskip}
3795 \\addtolength{\\textheight}{-3cm}
3796 \\setlength{\\topmargin}{1.5cm}
3797 \\addtolength{\\topmargin}{-2.54cm}"
3798 "The document header used for processing LaTeX fragments.
3799 It is imperative that this header make sure that no page number
3800 appears on the page. The package defined in the variables
3801 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3802 will either replace the placeholder \"[PACKAGES]\" in this
3803 header, or they will be appended."
3804 :group 'org-latex
3805 :type 'string)
3807 (defun org-set-packages-alist (var val)
3808 "Set the packages alist and make sure it has 3 elements per entry."
3809 (set var (mapcar (lambda (x)
3810 (if (and (consp x) (= (length x) 2))
3811 (list (car x) (nth 1 x) t)
3813 val)))
3815 (defun org-get-packages-alist (var)
3816 "Get the packages alist and make sure it has 3 elements per entry."
3817 (mapcar (lambda (x)
3818 (if (and (consp x) (= (length x) 2))
3819 (list (car x) (nth 1 x) t)
3821 (default-value var)))
3823 (defcustom org-latex-default-packages-alist
3824 '(("AUTO" "inputenc" t)
3825 ("T1" "fontenc" t)
3826 ("" "fixltx2e" nil)
3827 ("" "graphicx" t)
3828 ("" "longtable" nil)
3829 ("" "float" nil)
3830 ("" "wrapfig" nil)
3831 ("" "rotating" nil)
3832 ("normalem" "ulem" t)
3833 ("" "amsmath" t)
3834 ("" "textcomp" t)
3835 ("" "marvosym" t)
3836 ("" "wasysym" t)
3837 ("" "amssymb" t)
3838 ("" "hyperref" nil)
3839 "\\tolerance=1000")
3840 "Alist of default packages to be inserted in the header.
3842 Change this only if one of the packages here causes an
3843 incompatibility with another package you are using.
3845 The packages in this list are needed by one part or another of
3846 Org mode to function properly:
3848 - inputenc, fontenc: for basic font and character selection
3849 - fixltx2e: Important patches of LaTeX itself
3850 - graphicx: for including images
3851 - longtable: For multipage tables
3852 - float, wrapfig: for figure placement
3853 - rotating: for sideways figures and tables
3854 - ulem: for underline and strike-through
3855 - amsmath: for subscript and superscript and math environments
3856 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3857 for interpreting the entities in `org-entities'. You can skip
3858 some of these packages if you don't use any of their symbols.
3859 - hyperref: for cross references
3861 Therefore you should not modify this variable unless you know
3862 what you are doing. The one reason to change it anyway is that
3863 you might be loading some other package that conflicts with one
3864 of the default packages. Each cell is of the format
3865 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3866 the package also needs to be included when compiling LaTeX
3867 snippets into images for inclusion into non-LaTeX output."
3868 :group 'org-latex
3869 :group 'org-export-latex
3870 :set 'org-set-packages-alist
3871 :get 'org-get-packages-alist
3872 :version "24.1"
3873 :type '(repeat
3874 (choice
3875 (list :tag "options/package pair"
3876 (string :tag "options")
3877 (string :tag "package")
3878 (boolean :tag "Snippet"))
3879 (string :tag "A line of LaTeX"))))
3881 (defcustom org-latex-packages-alist nil
3882 "Alist of packages to be inserted in every LaTeX header.
3884 These will be inserted after `org-latex-default-packages-alist'.
3885 Each cell is of the format:
3887 \(\"options\" \"package\" snippet-flag)
3889 SNIPPET-FLAG, when t, indicates that this package is also needed
3890 when turning LaTeX snippets into images for inclusion into
3891 non-LaTeX output.
3893 Make sure that you only list packages here which:
3895 - you want in every file
3896 - do not conflict with the setup in `org-format-latex-header'.
3897 - do not conflict with the default packages in
3898 `org-latex-default-packages-alist'."
3899 :group 'org-latex
3900 :group 'org-export-latex
3901 :set 'org-set-packages-alist
3902 :get 'org-get-packages-alist
3903 :type '(repeat
3904 (choice
3905 (list :tag "options/package pair"
3906 (string :tag "options")
3907 (string :tag "package")
3908 (boolean :tag "Snippet"))
3909 (string :tag "A line of LaTeX"))))
3911 (defgroup org-appearance nil
3912 "Settings for Org-mode appearance."
3913 :tag "Org Appearance"
3914 :group 'org)
3916 (defcustom org-level-color-stars-only nil
3917 "Non-nil means fontify only the stars in each headline.
3918 When nil, the entire headline is fontified.
3919 Changing it requires restart of `font-lock-mode' to become effective
3920 also in regions already fontified."
3921 :group 'org-appearance
3922 :type 'boolean)
3924 (defcustom org-hide-leading-stars nil
3925 "Non-nil means hide the first N-1 stars in a headline.
3926 This works by using the face `org-hide' for these stars. This
3927 face is white for a light background, and black for a dark
3928 background. You may have to customize the face `org-hide' to
3929 make this work.
3930 Changing it requires restart of `font-lock-mode' to become effective
3931 also in regions already fontified.
3932 You may also set this on a per-file basis by adding one of the following
3933 lines to the buffer:
3935 #+STARTUP: hidestars
3936 #+STARTUP: showstars"
3937 :group 'org-appearance
3938 :type 'boolean)
3940 (defcustom org-hidden-keywords nil
3941 "List of symbols corresponding to keywords to be hidden the org buffer.
3942 For example, a value '(title) for this list will make the document's title
3943 appear in the buffer without the initial #+TITLE: keyword."
3944 :group 'org-appearance
3945 :version "24.1"
3946 :type '(set (const :tag "#+AUTHOR" author)
3947 (const :tag "#+DATE" date)
3948 (const :tag "#+EMAIL" email)
3949 (const :tag "#+TITLE" title)))
3951 (defcustom org-custom-properties nil
3952 "List of properties (as strings) with a special meaning.
3953 The default use of these custom properties is to let the user
3954 hide them with `org-toggle-custom-properties-visibility'."
3955 :group 'org-properties
3956 :group 'org-appearance
3957 :version "24.3"
3958 :type '(repeat (string :tag "Property Name")))
3960 (defcustom org-fontify-done-headline nil
3961 "Non-nil means change the face of a headline if it is marked DONE.
3962 Normally, only the TODO/DONE keyword indicates the state of a headline.
3963 When this is non-nil, the headline after the keyword is set to the
3964 `org-headline-done' as an additional indication."
3965 :group 'org-appearance
3966 :type 'boolean)
3968 (defcustom org-fontify-emphasized-text t
3969 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3970 Changing this variable requires a restart of Emacs to take effect."
3971 :group 'org-appearance
3972 :type 'boolean)
3974 (defcustom org-fontify-whole-heading-line nil
3975 "Non-nil means fontify the whole line for headings.
3976 This is useful when setting a background color for the
3977 org-level-* faces."
3978 :group 'org-appearance
3979 :type 'boolean)
3981 (defcustom org-highlight-latex-and-related nil
3982 "Non-nil means highlight LaTeX related syntax in the buffer.
3983 When non nil, the value should be a list containing any of the
3984 following symbols:
3985 `latex' Highlight LaTeX snippets and environments.
3986 `script' Highlight subscript and superscript.
3987 `entities' Highlight entities."
3988 :group 'org-appearance
3989 :version "24.4"
3990 :package-version '(Org . "8.0")
3991 :type '(choice
3992 (const :tag "No highlighting" nil)
3993 (set :greedy t :tag "Highlight"
3994 (const :tag "LaTeX snippets and environments" latex)
3995 (const :tag "Subscript and superscript" script)
3996 (const :tag "Entities" entities))))
3998 (defcustom org-hide-emphasis-markers nil
3999 "Non-nil mean font-lock should hide the emphasis marker characters."
4000 :group 'org-appearance
4001 :type 'boolean)
4003 (defcustom org-pretty-entities nil
4004 "Non-nil means show entities as UTF8 characters.
4005 When nil, the \\name form remains in the buffer."
4006 :group 'org-appearance
4007 :version "24.1"
4008 :type 'boolean)
4010 (defcustom org-pretty-entities-include-sub-superscripts t
4011 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4012 :group 'org-appearance
4013 :version "24.1"
4014 :type 'boolean)
4016 (defvar org-emph-re nil
4017 "Regular expression for matching emphasis.
4018 After a match, the match groups contain these elements:
4019 0 The match of the full regular expression, including the characters
4020 before and after the proper match
4021 1 The character before the proper match, or empty at beginning of line
4022 2 The proper match, including the leading and trailing markers
4023 3 The leading marker like * or /, indicating the type of highlighting
4024 4 The text between the emphasis markers, not including the markers
4025 5 The character after the match, empty at the end of a line")
4026 (defvar org-verbatim-re nil
4027 "Regular expression for matching verbatim text.")
4028 (defvar org-emphasis-regexp-components) ; defined just below
4029 (defvar org-emphasis-alist) ; defined just below
4030 (defun org-set-emph-re (var val)
4031 "Set variable and compute the emphasis regular expression."
4032 (set var val)
4033 (when (and (boundp 'org-emphasis-alist)
4034 (boundp 'org-emphasis-regexp-components)
4035 org-emphasis-alist org-emphasis-regexp-components)
4036 (let* ((e org-emphasis-regexp-components)
4037 (pre (car e))
4038 (post (nth 1 e))
4039 (border (nth 2 e))
4040 (body (nth 3 e))
4041 (nl (nth 4 e))
4042 (body1 (concat body "*?"))
4043 (markers (mapconcat 'car org-emphasis-alist ""))
4044 (vmarkers (mapconcat
4045 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4046 org-emphasis-alist "")))
4047 ;; make sure special characters appear at the right position in the class
4048 (if (string-match "\\^" markers)
4049 (setq markers (concat (replace-match "" t t markers) "^")))
4050 (if (string-match "-" markers)
4051 (setq markers (concat (replace-match "" t t markers) "-")))
4052 (if (string-match "\\^" vmarkers)
4053 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4054 (if (string-match "-" vmarkers)
4055 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4056 (if (> nl 0)
4057 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4058 (int-to-string nl) "\\}")))
4059 ;; Make the regexp
4060 (setq org-emph-re
4061 (concat "\\([" pre "]\\|^\\)"
4062 "\\("
4063 "\\([" markers "]\\)"
4064 "\\("
4065 "[^" border "]\\|"
4066 "[^" border "]"
4067 body1
4068 "[^" border "]"
4069 "\\)"
4070 "\\3\\)"
4071 "\\([" post "]\\|$\\)"))
4072 (setq org-verbatim-re
4073 (concat "\\([" pre "]\\|^\\)"
4074 "\\("
4075 "\\([" vmarkers "]\\)"
4076 "\\("
4077 "[^" border "]\\|"
4078 "[^" border "]"
4079 body1
4080 "[^" border "]"
4081 "\\)"
4082 "\\3\\)"
4083 "\\([" post "]\\|$\\)")))))
4085 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4086 ;; set this option proved cumbersome. See this message/thread:
4087 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4088 (defvar org-emphasis-regexp-components
4089 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4090 "Components used to build the regular expression for emphasis.
4091 This is a list with five entries. Terminology: In an emphasis string
4092 like \" *strong word* \", we call the initial space PREMATCH, the final
4093 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4094 and \"trong wor\" is the body. The different components in this variable
4095 specify what is allowed/forbidden in each part:
4097 pre Chars allowed as prematch. Beginning of line will be allowed too.
4098 post Chars allowed as postmatch. End of line will be allowed too.
4099 border The chars *forbidden* as border characters.
4100 body-regexp A regexp like \".\" to match a body character. Don't use
4101 non-shy groups here, and don't allow newline here.
4102 newline The maximum number of newlines allowed in an emphasis exp.
4104 You need to reload Org or to restart Emacs after customizing this.")
4106 (defcustom org-emphasis-alist
4107 `(("*" bold)
4108 ("/" italic)
4109 ("_" underline)
4110 ("=" org-code verbatim)
4111 ("~" org-verbatim verbatim)
4112 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4113 "Alist of characters and faces to emphasize text.
4114 Text starting and ending with a special character will be emphasized,
4115 for example *bold*, _underlined_ and /italic/. This variable sets the
4116 marker characters and the face to be used by font-lock for highlighting
4117 in Org-mode Emacs buffers.
4119 You need to reload Org or to restart Emacs after customizing this."
4120 :group 'org-appearance
4121 :set 'org-set-emph-re
4122 :version "24.4"
4123 :package-version '(Org . "8.0")
4124 :type '(repeat
4125 (list
4126 (string :tag "Marker character")
4127 (choice
4128 (face :tag "Font-lock-face")
4129 (plist :tag "Face property list"))
4130 (option (const verbatim)))))
4132 (defvar org-protecting-blocks
4133 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4134 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4135 This is needed for font-lock setup.")
4137 ;;; Miscellaneous options
4139 (defgroup org-completion nil
4140 "Completion in Org-mode."
4141 :tag "Org Completion"
4142 :group 'org)
4144 (defcustom org-completion-use-ido nil
4145 "Non-nil means use ido completion wherever possible.
4146 Note that `ido-mode' must be active for this variable to be relevant.
4147 If you decide to turn this variable on, you might well want to turn off
4148 `org-outline-path-complete-in-steps'.
4149 See also `org-completion-use-iswitchb'."
4150 :group 'org-completion
4151 :type 'boolean)
4153 (defcustom org-completion-use-iswitchb nil
4154 "Non-nil means use iswitchb completion wherever possible.
4155 Note that `iswitchb-mode' must be active for this variable to be relevant.
4156 If you decide to turn this variable on, you might well want to turn off
4157 `org-outline-path-complete-in-steps'.
4158 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4159 :group 'org-completion
4160 :type 'boolean)
4162 (defcustom org-completion-fallback-command 'hippie-expand
4163 "The expansion command called by \\[pcomplete] in normal context.
4164 Normal means, no org-mode-specific context."
4165 :group 'org-completion
4166 :type 'function)
4168 ;;; Functions and variables from their packages
4169 ;; Declared here to avoid compiler warnings
4171 ;; XEmacs only
4172 (defvar outline-mode-menu-heading)
4173 (defvar outline-mode-menu-show)
4174 (defvar outline-mode-menu-hide)
4175 (defvar zmacs-regions) ; XEmacs regions
4177 ;; Emacs only
4178 (defvar mark-active)
4180 ;; Various packages
4181 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4182 (declare-function calendar-forward-day "cal-move" (arg))
4183 (declare-function calendar-goto-date "cal-move" (date))
4184 (declare-function calendar-goto-today "cal-move" ())
4185 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4186 (defvar calc-embedded-close-formula)
4187 (defvar calc-embedded-open-formula)
4188 (declare-function cdlatex-tab "ext:cdlatex" ())
4189 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4190 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4191 (defvar font-lock-unfontify-region-function)
4192 (declare-function iswitchb-read-buffer "iswitchb"
4193 (prompt &optional default require-match start matches-set))
4194 (defvar iswitchb-temp-buflist)
4195 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4196 (defvar org-agenda-tags-todo-honor-ignore-options)
4197 (declare-function org-agenda-skip "org-agenda" ())
4198 (declare-function
4199 org-agenda-format-item "org-agenda"
4200 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4201 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4202 (declare-function org-agenda-change-all-lines "org-agenda"
4203 (newhead hdmarker &optional fixface just-this))
4204 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4205 (declare-function org-agenda-maybe-redo "org-agenda" ())
4206 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4207 (beg end))
4208 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4209 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4210 "org-agenda" (&optional end))
4211 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4212 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4213 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4214 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4215 (declare-function org-indent-mode "org-indent" (&optional arg))
4216 (declare-function parse-time-string "parse-time" (string))
4217 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4218 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4219 (defvar remember-data-file)
4220 (defvar texmathp-why)
4221 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4222 (declare-function table--at-cell-p "table" (position &optional object at-column))
4224 (defvar org-latex-regexps)
4226 ;;; Autoload and prepare some org modules
4228 ;; Some table stuff that needs to be defined here, because it is used
4229 ;; by the functions setting up org-mode or checking for table context.
4231 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4232 "Detect an org-type or table-type table.")
4233 (defconst org-table-line-regexp "^[ \t]*|"
4234 "Detect an org-type table line.")
4235 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4236 "Detect an org-type table line.")
4237 (defconst org-table-hline-regexp "^[ \t]*|-"
4238 "Detect an org-type table hline.")
4239 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4240 "Detect a table-type table hline.")
4241 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4242 "Detect the first line outside a table when searching from within it.
4243 This works for both table types.")
4245 ;; Autoload the functions in org-table.el that are needed by functions here.
4247 (eval-and-compile
4248 (org-autoload "org-table"
4249 '(org-table-begin org-table-blank-field org-table-end)))
4251 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4252 "Detect a #+TBLFM line.")
4254 ;;;###autoload
4255 (defun turn-on-orgtbl ()
4256 "Unconditionally turn on `orgtbl-mode'."
4257 (require 'org-table)
4258 (orgtbl-mode 1))
4260 (defun org-at-table-p (&optional table-type)
4261 "Return t if the cursor is inside an org-type table.
4262 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4263 (if org-enable-table-editor
4264 (save-excursion
4265 (beginning-of-line 1)
4266 (looking-at (if table-type org-table-any-line-regexp
4267 org-table-line-regexp)))
4268 nil))
4269 (defsubst org-table-p () (org-at-table-p))
4271 (defun org-at-table.el-p ()
4272 "Return t if and only if we are at a table.el table."
4273 (and (org-at-table-p 'any)
4274 (save-excursion
4275 (goto-char (org-table-begin 'any))
4276 (looking-at org-table1-hline-regexp))))
4278 (defun org-table-recognize-table.el ()
4279 "If there is a table.el table nearby, recognize it and move into it."
4280 (if org-table-tab-recognizes-table.el
4281 (if (org-at-table.el-p)
4282 (progn
4283 (beginning-of-line 1)
4284 (if (looking-at org-table-dataline-regexp)
4286 (if (looking-at org-table1-hline-regexp)
4287 (progn
4288 (beginning-of-line 2)
4289 (if (looking-at org-table-any-border-regexp)
4290 (beginning-of-line -1)))))
4291 (if (re-search-forward "|" (org-table-end t) t)
4292 (progn
4293 (require 'table)
4294 (if (table--at-cell-p (point))
4296 (message "recognizing table.el table...")
4297 (table-recognize-table)
4298 (message "recognizing table.el table...done")))
4299 (error "This should not happen"))
4301 nil)
4302 nil))
4304 (defun org-at-table-hline-p ()
4305 "Return t if the cursor is inside a hline in a table."
4306 (if org-enable-table-editor
4307 (save-excursion
4308 (beginning-of-line 1)
4309 (looking-at org-table-hline-regexp))
4310 nil))
4312 (defun org-table-map-tables (function &optional quietly)
4313 "Apply FUNCTION to the start of all tables in the buffer."
4314 (save-excursion
4315 (save-restriction
4316 (widen)
4317 (goto-char (point-min))
4318 (while (re-search-forward org-table-any-line-regexp nil t)
4319 (unless quietly
4320 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4321 (beginning-of-line 1)
4322 (when (and (looking-at org-table-line-regexp)
4323 ;; Exclude tables in src/example/verbatim/clocktable blocks
4324 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4325 (save-excursion (funcall function))
4326 (or (looking-at org-table-line-regexp)
4327 (forward-char 1)))
4328 (re-search-forward org-table-any-border-regexp nil 1))))
4329 (unless quietly (message "Mapping tables: done")))
4331 ;; Declare and autoload functions from org-agenda.el
4333 (eval-and-compile
4334 (org-autoload "org-agenda"
4335 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4337 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4338 (declare-function org-clock-update-mode-line "org-clock" ())
4339 (declare-function org-resolve-clocks "org-clock"
4340 (&optional also-non-dangling-p prompt last-valid))
4342 (defun org-at-TBLFM-p (&optional pos)
4343 "Return t when point (or POS) is in #+TBLFM line."
4344 (save-excursion
4345 (let ((pos pos)))
4346 (goto-char (or pos (point)))
4347 (beginning-of-line 1)
4348 (looking-at org-TBLFM-regexp)))
4350 (defvar org-clock-start-time)
4351 (defvar org-clock-marker (make-marker)
4352 "Marker recording the last clock-in.")
4353 (defvar org-clock-hd-marker (make-marker)
4354 "Marker recording the last clock-in, but the headline position.")
4355 (defvar org-clock-heading ""
4356 "The heading of the current clock entry.")
4357 (defun org-clock-is-active ()
4358 "Return the buffer where the clock is currently running.
4359 Return nil if no clock is running."
4360 (marker-buffer org-clock-marker))
4362 (eval-and-compile
4363 (org-autoload "org-clock" '(org-clock-remove-overlays
4364 org-clock-update-time-maybe
4365 org-clocktable-shift)))
4367 (defun org-check-running-clock ()
4368 "Check if the current buffer contains the running clock.
4369 If yes, offer to stop it and to save the buffer with the changes."
4370 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4371 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4372 (buffer-name))))
4373 (org-clock-out)
4374 (when (y-or-n-p "Save changed buffer?")
4375 (save-buffer))))
4377 (defun org-clocktable-try-shift (dir n)
4378 "Check if this line starts a clock table, if yes, shift the time block."
4379 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4380 (org-clocktable-shift dir n)))
4382 ;;;###autoload
4383 (defun org-clock-persistence-insinuate ()
4384 "Set up hooks for clock persistence."
4385 (require 'org-clock)
4386 (add-hook 'org-mode-hook 'org-clock-load)
4387 (add-hook 'kill-emacs-hook 'org-clock-save))
4389 ;; Define the variable already here, to make sure we have it.
4390 (defvar org-indent-mode nil
4391 "Non-nil if Org-Indent mode is enabled.
4392 Use the command `org-indent-mode' to change this variable.")
4394 ;; Autoload archiving code
4395 ;; The stuff that is needed for cycling and tags has to be defined here.
4397 (defgroup org-archive nil
4398 "Options concerning archiving in Org-mode."
4399 :tag "Org Archive"
4400 :group 'org-structure)
4402 (defcustom org-archive-location "%s_archive::"
4403 "The location where subtrees should be archived.
4405 The value of this variable is a string, consisting of two parts,
4406 separated by a double-colon. The first part is a filename and
4407 the second part is a headline.
4409 When the filename is omitted, archiving happens in the same file.
4410 %s in the filename will be replaced by the current file
4411 name (without the directory part). Archiving to a different file
4412 is useful to keep archived entries from contributing to the
4413 Org-mode Agenda.
4415 The archived entries will be filed as subtrees of the specified
4416 headline. When the headline is omitted, the subtrees are simply
4417 filed away at the end of the file, as top-level entries. Also in
4418 the heading you can use %s to represent the file name, this can be
4419 useful when using the same archive for a number of different files.
4421 Here are a few examples:
4422 \"%s_archive::\"
4423 If the current file is Projects.org, archive in file
4424 Projects.org_archive, as top-level trees. This is the default.
4426 \"::* Archived Tasks\"
4427 Archive in the current file, under the top-level headline
4428 \"* Archived Tasks\".
4430 \"~/org/archive.org::\"
4431 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4433 \"~/org/archive.org::* From %s\"
4434 Archive in file ~/org/archive.org (absolute path), under headlines
4435 \"From FILENAME\" where file name is the current file name.
4437 \"~/org/datetree.org::datetree/* Finished Tasks\"
4438 The \"datetree/\" string is special, signifying to archive
4439 items to the datetree. Items are placed in either the CLOSED
4440 date of the item, or the current date if there is no CLOSED date.
4441 The heading will be a subentry to the current date. There doesn't
4442 need to be a heading, but there always needs to be a slash after
4443 datetree. For example, to store archived items directly in the
4444 datetree, use \"~/org/datetree.org::datetree/\".
4446 \"basement::** Finished Tasks\"
4447 Archive in file ./basement (relative path), as level 3 trees
4448 below the level 2 heading \"** Finished Tasks\".
4450 You may set this option on a per-file basis by adding to the buffer a
4451 line like
4453 #+ARCHIVE: basement::** Finished Tasks
4455 You may also define it locally for a subtree by setting an ARCHIVE property
4456 in the entry. If such a property is found in an entry, or anywhere up
4457 the hierarchy, it will be used."
4458 :group 'org-archive
4459 :type 'string)
4461 (defcustom org-archive-tag "ARCHIVE"
4462 "The tag that marks a subtree as archived.
4463 An archived subtree does not open during visibility cycling, and does
4464 not contribute to the agenda listings.
4465 After changing this, font-lock must be restarted in the relevant buffers to
4466 get the proper fontification."
4467 :group 'org-archive
4468 :group 'org-keywords
4469 :type 'string)
4471 (defcustom org-agenda-skip-archived-trees t
4472 "Non-nil means the agenda will skip any items located in archived trees.
4473 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4474 variable is no longer recommended, you should leave it at the value t.
4475 Instead, use the key `v' to cycle the archives-mode in the agenda."
4476 :group 'org-archive
4477 :group 'org-agenda-skip
4478 :type 'boolean)
4480 (defcustom org-columns-skip-archived-trees t
4481 "Non-nil means ignore archived trees when creating column view."
4482 :group 'org-archive
4483 :group 'org-properties
4484 :type 'boolean)
4486 (defcustom org-cycle-open-archived-trees nil
4487 "Non-nil means `org-cycle' will open archived trees.
4488 An archived tree is a tree marked with the tag ARCHIVE.
4489 When nil, archived trees will stay folded. You can still open them with
4490 normal outline commands like `show-all', but not with the cycling commands."
4491 :group 'org-archive
4492 :group 'org-cycle
4493 :type 'boolean)
4495 (defcustom org-sparse-tree-open-archived-trees nil
4496 "Non-nil means sparse tree construction shows matches in archived trees.
4497 When nil, matches in these trees are highlighted, but the trees are kept in
4498 collapsed state."
4499 :group 'org-archive
4500 :group 'org-sparse-trees
4501 :type 'boolean)
4503 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4504 "The default date type when building a sparse tree.
4505 When this is nil, a date is a scheduled or a deadline timestamp.
4506 Otherwise, these types are allowed:
4508 all: all timestamps
4509 active: only active timestamps (<...>)
4510 inactive: only inactive timestamps (<...)
4511 scheduled: only scheduled timestamps
4512 deadline: only deadline timestamps"
4513 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4514 (const :tag "All timestamps" all)
4515 (const :tag "Only active timestamps" active)
4516 (const :tag "Only inactive timestamps" inactive)
4517 (const :tag "Only scheduled timestamps" scheduled)
4518 (const :tag "Only deadline timestamps" deadline)
4519 (const :tag "Only closed timestamps" closed))
4520 :version "24.3"
4521 :group 'org-sparse-trees)
4523 (defun org-cycle-hide-archived-subtrees (state)
4524 "Re-hide all archived subtrees after a visibility state change."
4525 (when (and (not org-cycle-open-archived-trees)
4526 (not (memq state '(overview folded))))
4527 (save-excursion
4528 (let* ((globalp (memq state '(contents all)))
4529 (beg (if globalp (point-min) (point)))
4530 (end (if globalp (point-max) (org-end-of-subtree t))))
4531 (org-hide-archived-subtrees beg end)
4532 (goto-char beg)
4533 (if (looking-at (concat ".*:" org-archive-tag ":"))
4534 (message "%s" (substitute-command-keys
4535 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4537 (defun org-force-cycle-archived ()
4538 "Cycle subtree even if it is archived."
4539 (interactive)
4540 (setq this-command 'org-cycle)
4541 (let ((org-cycle-open-archived-trees t))
4542 (call-interactively 'org-cycle)))
4544 (defun org-hide-archived-subtrees (beg end)
4545 "Re-hide all archived subtrees after a visibility state change."
4546 (save-excursion
4547 (let* ((re (concat ":" org-archive-tag ":")))
4548 (goto-char beg)
4549 (while (re-search-forward re end t)
4550 (when (org-at-heading-p)
4551 (org-flag-subtree t)
4552 (org-end-of-subtree t))))))
4554 (declare-function outline-end-of-heading "outline" ())
4555 (declare-function outline-flag-region "outline" (from to flag))
4556 (defun org-flag-subtree (flag)
4557 (save-excursion
4558 (org-back-to-heading t)
4559 (outline-end-of-heading)
4560 (outline-flag-region (point)
4561 (progn (org-end-of-subtree t) (point))
4562 flag)))
4564 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4566 (eval-and-compile
4567 (org-autoload "org-archive"
4568 '(org-add-archive-files)))
4570 ;; Autoload Column View Code
4572 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4573 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4574 (declare-function org-columns-compute "org-colview" (property))
4576 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4577 '(org-columns-number-to-string
4578 org-columns-get-format-and-top-level
4579 org-columns-compute
4580 org-columns-remove-overlays))
4582 ;; Autoload ID code
4584 (declare-function org-id-store-link "org-id")
4585 (declare-function org-id-locations-load "org-id")
4586 (declare-function org-id-locations-save "org-id")
4587 (defvar org-id-track-globally)
4588 (org-autoload "org-id"
4589 '(org-id-new
4590 org-id-copy
4591 org-id-get-with-outline-path-completion
4592 org-id-get-with-outline-drilling))
4594 ;;; Variables for pre-computed regular expressions, all buffer local
4596 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4597 "Matches first line of a hidden block.")
4598 (make-variable-buffer-local 'org-drawer-regexp)
4599 (defvar org-todo-regexp nil
4600 "Matches any of the TODO state keywords.")
4601 (make-variable-buffer-local 'org-todo-regexp)
4602 (defvar org-not-done-regexp nil
4603 "Matches any of the TODO state keywords except the last one.")
4604 (make-variable-buffer-local 'org-not-done-regexp)
4605 (defvar org-not-done-heading-regexp nil
4606 "Matches a TODO headline that is not done.")
4607 (make-variable-buffer-local 'org-not-done-regexp)
4608 (defvar org-todo-line-regexp nil
4609 "Matches a headline and puts TODO state into group 2 if present.")
4610 (make-variable-buffer-local 'org-todo-line-regexp)
4611 (defvar org-complex-heading-regexp nil
4612 "Matches a headline and puts everything into groups:
4613 group 1: the stars
4614 group 2: The todo keyword, maybe
4615 group 3: Priority cookie
4616 group 4: True headline
4617 group 5: Tags")
4618 (make-variable-buffer-local 'org-complex-heading-regexp)
4619 (defvar org-complex-heading-regexp-format nil
4620 "Printf format to make regexp to match an exact headline.
4621 This regexp will match the headline of any node which has the
4622 exact headline text that is put into the format, but may have any
4623 TODO state, priority and tags.")
4624 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4625 (defvar org-todo-line-tags-regexp nil
4626 "Matches a headline and puts TODO state into group 2 if present.
4627 Also put tags into group 4 if tags are present.")
4628 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4629 (defvar org-ds-keyword-length 12
4630 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4631 (make-variable-buffer-local 'org-ds-keyword-length)
4632 (defvar org-deadline-regexp nil
4633 "Matches the DEADLINE keyword.")
4634 (make-variable-buffer-local 'org-deadline-regexp)
4635 (defvar org-deadline-time-regexp nil
4636 "Matches the DEADLINE keyword together with a time stamp.")
4637 (make-variable-buffer-local 'org-deadline-time-regexp)
4638 (defvar org-deadline-time-hour-regexp nil
4639 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4640 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4641 (defvar org-deadline-line-regexp nil
4642 "Matches the DEADLINE keyword and the rest of the line.")
4643 (make-variable-buffer-local 'org-deadline-line-regexp)
4644 (defvar org-scheduled-regexp nil
4645 "Matches the SCHEDULED keyword.")
4646 (make-variable-buffer-local 'org-scheduled-regexp)
4647 (defvar org-scheduled-time-regexp nil
4648 "Matches the SCHEDULED keyword together with a time stamp.")
4649 (make-variable-buffer-local 'org-scheduled-time-regexp)
4650 (defvar org-scheduled-time-hour-regexp nil
4651 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4652 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4653 (defvar org-closed-time-regexp nil
4654 "Matches the CLOSED keyword together with a time stamp.")
4655 (make-variable-buffer-local 'org-closed-time-regexp)
4657 (defvar org-keyword-time-regexp nil
4658 "Matches any of the 4 keywords, together with the time stamp.")
4659 (make-variable-buffer-local 'org-keyword-time-regexp)
4660 (defvar org-keyword-time-not-clock-regexp nil
4661 "Matches any of the 3 keywords, together with the time stamp.")
4662 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4663 (defvar org-maybe-keyword-time-regexp nil
4664 "Matches a timestamp, possibly preceded by a keyword.")
4665 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4666 (defvar org-all-time-keywords nil
4667 "List of time keywords.")
4668 (make-variable-buffer-local 'org-all-time-keywords)
4670 (defconst org-plain-time-of-day-regexp
4671 (concat
4672 "\\(\\<[012]?[0-9]"
4673 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4674 "\\(--?"
4675 "\\(\\<[012]?[0-9]"
4676 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4677 "\\)?")
4678 "Regular expression to match a plain time or time range.
4679 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4680 groups carry important information:
4681 0 the full match
4682 1 the first time, range or not
4683 8 the second time, if it is a range.")
4685 (defconst org-plain-time-extension-regexp
4686 (concat
4687 "\\(\\<[012]?[0-9]"
4688 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4689 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4690 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4691 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4692 groups carry important information:
4693 0 the full match
4694 7 hours of duration
4695 9 minutes of duration")
4697 (defconst org-stamp-time-of-day-regexp
4698 (concat
4699 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4700 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4701 "\\(--?"
4702 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4703 "Regular expression to match a timestamp time or time range.
4704 After a match, the following groups carry important information:
4705 0 the full match
4706 1 date plus weekday, for back referencing to make sure both times are on the same day
4707 2 the first time, range or not
4708 4 the second time, if it is a range.")
4710 (defconst org-startup-options
4711 '(("fold" org-startup-folded t)
4712 ("overview" org-startup-folded t)
4713 ("nofold" org-startup-folded nil)
4714 ("showall" org-startup-folded nil)
4715 ("showeverything" org-startup-folded showeverything)
4716 ("content" org-startup-folded content)
4717 ("indent" org-startup-indented t)
4718 ("noindent" org-startup-indented nil)
4719 ("hidestars" org-hide-leading-stars t)
4720 ("showstars" org-hide-leading-stars nil)
4721 ("odd" org-odd-levels-only t)
4722 ("oddeven" org-odd-levels-only nil)
4723 ("align" org-startup-align-all-tables t)
4724 ("noalign" org-startup-align-all-tables nil)
4725 ("inlineimages" org-startup-with-inline-images t)
4726 ("noinlineimages" org-startup-with-inline-images nil)
4727 ("latexpreview" org-startup-with-latex-preview t)
4728 ("nolatexpreview" org-startup-with-latex-preview nil)
4729 ("customtime" org-display-custom-times t)
4730 ("logdone" org-log-done time)
4731 ("lognotedone" org-log-done note)
4732 ("nologdone" org-log-done nil)
4733 ("lognoteclock-out" org-log-note-clock-out t)
4734 ("nolognoteclock-out" org-log-note-clock-out nil)
4735 ("logrepeat" org-log-repeat state)
4736 ("lognoterepeat" org-log-repeat note)
4737 ("logdrawer" org-log-into-drawer t)
4738 ("nologdrawer" org-log-into-drawer nil)
4739 ("logstatesreversed" org-log-states-order-reversed t)
4740 ("nologstatesreversed" org-log-states-order-reversed nil)
4741 ("nologrepeat" org-log-repeat nil)
4742 ("logreschedule" org-log-reschedule time)
4743 ("lognotereschedule" org-log-reschedule note)
4744 ("nologreschedule" org-log-reschedule nil)
4745 ("logredeadline" org-log-redeadline time)
4746 ("lognoteredeadline" org-log-redeadline note)
4747 ("nologredeadline" org-log-redeadline nil)
4748 ("logrefile" org-log-refile time)
4749 ("lognoterefile" org-log-refile note)
4750 ("nologrefile" org-log-refile nil)
4751 ("fninline" org-footnote-define-inline t)
4752 ("nofninline" org-footnote-define-inline nil)
4753 ("fnlocal" org-footnote-section nil)
4754 ("fnauto" org-footnote-auto-label t)
4755 ("fnprompt" org-footnote-auto-label nil)
4756 ("fnconfirm" org-footnote-auto-label confirm)
4757 ("fnplain" org-footnote-auto-label plain)
4758 ("fnadjust" org-footnote-auto-adjust t)
4759 ("nofnadjust" org-footnote-auto-adjust nil)
4760 ("constcgs" constants-unit-system cgs)
4761 ("constSI" constants-unit-system SI)
4762 ("noptag" org-tag-persistent-alist nil)
4763 ("hideblocks" org-hide-block-startup t)
4764 ("nohideblocks" org-hide-block-startup nil)
4765 ("beamer" org-startup-with-beamer-mode t)
4766 ("entitiespretty" org-pretty-entities t)
4767 ("entitiesplain" org-pretty-entities nil))
4768 "Variable associated with STARTUP options for org-mode.
4769 Each element is a list of three items: the startup options (as written
4770 in the #+STARTUP line), the corresponding variable, and the value to set
4771 this variable to if the option is found. An optional forth element PUSH
4772 means to push this value onto the list in the variable.")
4774 (defun org-update-property-plist (key val props)
4775 "Update PROPS with KEY and VAL."
4776 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4777 (key (if appending (substring key 0 (- (length key) 1)) key))
4778 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4779 (previous (cdr (assoc key props))))
4780 (if appending
4781 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4782 (cons (cons key val) remainder))))
4784 (defconst org-block-regexp
4785 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4786 "Regular expression for hiding blocks.")
4787 (defconst org-heading-keyword-regexp-format
4788 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4789 "Printf format for a regexp matching a headline with some keyword.
4790 This regexp will match the headline of any node which has the
4791 exact keyword that is put into the format. The keyword isn't in
4792 any group by default, but the stars and the body are.")
4793 (defconst org-heading-keyword-maybe-regexp-format
4794 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4795 "Printf format for a regexp matching a headline, possibly with some keyword.
4796 This regexp can match any headline with the specified keyword, or
4797 without a keyword. The keyword isn't in any group by default,
4798 but the stars and the body are.")
4800 (defcustom org-group-tags t
4801 "When non-nil (the default), use group tags.
4802 This can be turned on/off through `org-toggle-tags-groups'."
4803 :group 'org-tags
4804 :group 'org-startup
4805 :type 'boolean)
4807 (defun org-toggle-tags-groups ()
4808 "Toggle support for group tags.
4809 Support for group tags is controlled by the option
4810 `org-group-tags', which is non-nil by default."
4811 (interactive)
4812 (setq org-group-tags (not org-group-tags))
4813 (cond ((and (derived-mode-p 'org-agenda-mode)
4814 org-group-tags)
4815 (org-agenda-redo))
4816 ((derived-mode-p 'org-mode)
4817 (let ((org-inhibit-startup t)) (org-mode))))
4818 (message "Groups tags support has been turned %s"
4819 (if org-group-tags "on" "off")))
4821 (defun org-set-regexps-and-options-for-tags ()
4822 "Precompute variables used for tags."
4823 (when (derived-mode-p 'org-mode)
4824 (org-set-local 'org-file-tags nil)
4825 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4826 (splitre "[ \t]+")
4827 (start 0)
4828 tags ftags key value)
4829 (save-excursion
4830 (save-restriction
4831 (widen)
4832 (goto-char (point-min))
4833 (while (re-search-forward re nil t)
4834 (setq key (upcase (org-match-string-no-properties 1))
4835 value (org-match-string-no-properties 2))
4836 (if (stringp value) (setq value (org-trim value)))
4837 (cond
4838 ((equal key "TAGS")
4839 (setq tags (append tags (if tags '("\\n") nil)
4840 (org-split-string value splitre))))
4841 ((equal key "FILETAGS")
4842 (when (string-match "\\S-" value)
4843 (setq ftags
4844 (append
4845 ftags
4846 (apply 'append
4847 (mapcar (lambda (x) (org-split-string x ":"))
4848 (org-split-string value)))))))))))
4849 ;; Process the file tags.
4850 (and ftags (org-set-local 'org-file-tags
4851 (mapcar 'org-add-prop-inherited ftags)))
4852 (org-set-local 'org-tag-groups-alist nil)
4853 ;; Process the tags.
4854 (when (and (not tags) org-tag-alist)
4855 (setq tags
4856 (mapcar
4857 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4858 ((eq (car tg) :endgroup) "}")
4859 ((eq (car tg) :grouptags) ":")
4860 ((eq (car tg) :newline) "\n")
4861 (t (concat (car tg)
4862 (if (characterp (cdr tg))
4863 (format "(%s)" (char-to-string (cdr tg))) "")))))
4864 org-tag-alist)))
4865 (let (e tgs g)
4866 (while (setq e (pop tags))
4867 (cond
4868 ((equal e "{")
4869 (progn (push '(:startgroup) tgs)
4870 (when (equal (nth 1 tags) ":")
4871 (push (list (replace-regexp-in-string
4872 "(.+)$" "" (nth 0 tags)))
4873 org-tag-groups-alist)
4874 (setq g 0))))
4875 ((equal e ":") (push '(:grouptags) tgs))
4876 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4877 ((equal e "\\n") (push '(:newline) tgs))
4878 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4879 (push (cons (match-string 1 e)
4880 (string-to-char (match-string 2 e))) tgs)
4881 (if (and g (> g 0))
4882 (setcar org-tag-groups-alist
4883 (append (car org-tag-groups-alist)
4884 (list (match-string 1 e)))))
4885 (if g (setq g (1+ g))))
4886 (t (push (list e) tgs)
4887 (if (and g (> g 0))
4888 (setcar org-tag-groups-alist
4889 (append (car org-tag-groups-alist) (list e))))
4890 (if g (setq g (1+ g))))))
4891 (org-set-local 'org-tag-alist nil)
4892 (while (setq e (pop tgs))
4893 (or (and (stringp (car e))
4894 (assoc (car e) org-tag-alist))
4895 (push e org-tag-alist)))
4896 ;; Return a list with tag variables
4897 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4899 (defvar org-ota nil)
4900 (defun org-set-regexps-and-options ()
4901 "Precompute regular expressions used in the current buffer."
4902 (when (derived-mode-p 'org-mode)
4903 (org-set-local 'org-todo-kwd-alist nil)
4904 (org-set-local 'org-todo-key-alist nil)
4905 (org-set-local 'org-todo-key-trigger nil)
4906 (org-set-local 'org-todo-keywords-1 nil)
4907 (org-set-local 'org-done-keywords nil)
4908 (org-set-local 'org-todo-heads nil)
4909 (org-set-local 'org-todo-sets nil)
4910 (org-set-local 'org-todo-log-states nil)
4911 (org-set-local 'org-file-properties nil)
4912 (let ((re (org-make-options-regexp
4913 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4914 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4915 "SETUPFILE" "OPTIONS")
4916 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4917 (splitre "[ \t]+")
4918 (scripts org-use-sub-superscripts)
4919 kwds kws0 kwsa key log value cat arch const links hw dws
4920 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4921 (start 0))
4922 (save-excursion
4923 (save-restriction
4924 (widen)
4925 (goto-char (point-min))
4926 (while
4927 (or (and
4928 ext-setup-or-nil
4929 (not org-ota)
4930 (let (ret)
4931 (with-temp-buffer
4932 (insert ext-setup-or-nil)
4933 (let ((major-mode 'org-mode) org-ota)
4934 (setq ret (save-match-data
4935 (org-set-regexps-and-options-for-tags)))))
4936 ;; Append setupfile tags to existing tags
4937 (setq org-ota t)
4938 (setq org-file-tags
4939 (delq nil (append org-file-tags (nth 0 ret)))
4940 org-tag-alist
4941 (delq nil (append org-tag-alist (nth 1 ret)))
4942 org-tag-groups-alist
4943 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4944 (and ext-setup-or-nil
4945 (string-match re ext-setup-or-nil start)
4946 (setq start (match-end 0)))
4947 (and (setq ext-setup-or-nil nil start 0)
4948 (re-search-forward re nil t)))
4949 (setq key (upcase (match-string 1 ext-setup-or-nil))
4950 value (org-match-string-no-properties 2 ext-setup-or-nil))
4951 (if (stringp value) (setq value (org-trim value)))
4952 (cond
4953 ((equal key "CATEGORY")
4954 (setq cat value))
4955 ((member key '("SEQ_TODO" "TODO"))
4956 (push (cons 'sequence (org-split-string value splitre)) kwds))
4957 ((equal key "TYP_TODO")
4958 (push (cons 'type (org-split-string value splitre)) kwds))
4959 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4960 ;; general TODO-like setup
4961 (push (cons (intern (downcase (match-string 1 key)))
4962 (org-split-string value splitre)) kwds))
4963 ((equal key "COLUMNS")
4964 (org-set-local 'org-columns-default-format value))
4965 ((equal key "LINK")
4966 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4967 (push (cons (match-string 1 value)
4968 (org-trim (match-string 2 value)))
4969 links)))
4970 ((equal key "PRIORITIES")
4971 (setq prio (org-split-string value " +")))
4972 ((equal key "PROPERTY")
4973 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4974 (setq props (org-update-property-plist (match-string 1 value)
4975 (match-string 2 value)
4976 props))))
4977 ((equal key "DRAWERS")
4978 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4979 ((equal key "CONSTANTS")
4980 (org-table-set-constants))
4981 ((equal key "STARTUP")
4982 (let ((opts (org-split-string value splitre))
4983 l var val)
4984 (while (setq l (pop opts))
4985 (when (setq l (assoc l org-startup-options))
4986 (setq var (nth 1 l) val (nth 2 l))
4987 (if (not (nth 3 l))
4988 (set (make-local-variable var) val)
4989 (if (not (listp (symbol-value var)))
4990 (set (make-local-variable var) nil))
4991 (set (make-local-variable var) (symbol-value var))
4992 (add-to-list var val))))))
4993 ((equal key "ARCHIVE")
4994 (setq arch value)
4995 (remove-text-properties 0 (length arch)
4996 '(face t fontified t) arch))
4997 ((equal key "OPTIONS")
4998 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4999 (setq scripts (read (match-string 2 value)))))
5000 ((and (equal key "SETUPFILE")
5001 ;; Prevent checking in Gnus messages
5002 (not buffer-read-only))
5003 (setq setup-contents (org-file-contents
5004 (expand-file-name
5005 (org-remove-double-quotes value))
5006 'noerror))
5007 (if (not ext-setup-or-nil)
5008 (setq ext-setup-or-nil setup-contents start 0)
5009 (setq ext-setup-or-nil
5010 (concat (substring ext-setup-or-nil 0 start)
5011 "\n" setup-contents "\n"
5012 (substring ext-setup-or-nil start)))))))
5013 ;; search for property blocks
5014 (goto-char (point-min))
5015 (while (re-search-forward org-block-regexp nil t)
5016 (when (equal "PROPERTY" (upcase (match-string 1)))
5017 (setq value (replace-regexp-in-string
5018 "[\n\r]" " " (match-string 4)))
5019 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5020 (setq props (org-update-property-plist (match-string 1 value)
5021 (match-string 2 value)
5022 props)))))))
5023 (org-set-local 'org-use-sub-superscripts scripts)
5024 (when cat
5025 (org-set-local 'org-category (intern cat))
5026 (push (cons "CATEGORY" cat) props))
5027 (when prio
5028 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5029 (setq prio (mapcar 'string-to-char prio))
5030 (org-set-local 'org-highest-priority (nth 0 prio))
5031 (org-set-local 'org-lowest-priority (nth 1 prio))
5032 (org-set-local 'org-default-priority (nth 2 prio)))
5033 (and props (org-set-local 'org-file-properties (nreverse props)))
5034 (and drawers (org-set-local 'org-drawers drawers))
5035 (and arch (org-set-local 'org-archive-location arch))
5036 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5037 ;; Process the TODO keywords
5038 (unless kwds
5039 ;; Use the global values as if they had been given locally.
5040 (setq kwds (default-value 'org-todo-keywords))
5041 (if (stringp (car kwds))
5042 (setq kwds (list (cons org-todo-interpretation
5043 (default-value 'org-todo-keywords)))))
5044 (setq kwds (reverse kwds)))
5045 (setq kwds (nreverse kwds))
5046 (let (inter kws kw)
5047 (while (setq kws (pop kwds))
5048 (let ((kws (or
5049 (run-hook-with-args-until-success
5050 'org-todo-setup-filter-hook kws)
5051 kws)))
5052 (setq inter (pop kws) sep (member "|" kws)
5053 kws0 (delete "|" (copy-sequence kws))
5054 kwsa nil
5055 kws1 (mapcar
5056 (lambda (x)
5057 ;; 1 2
5058 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5059 (progn
5060 (setq kw (match-string 1 x)
5061 key (and (match-end 2) (match-string 2 x))
5062 log (org-extract-log-state-settings x))
5063 (push (cons kw (and key (string-to-char key))) kwsa)
5064 (and log (push log org-todo-log-states))
5066 (error "Invalid TODO keyword %s" x)))
5067 kws0)
5068 kwsa (if kwsa (append '((:startgroup))
5069 (nreverse kwsa)
5070 '((:endgroup))))
5071 hw (car kws1)
5072 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5073 tail (list inter hw (car dws) (org-last dws))))
5074 (add-to-list 'org-todo-heads hw 'append)
5075 (push kws1 org-todo-sets)
5076 (setq org-done-keywords (append org-done-keywords dws nil))
5077 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5078 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5079 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5080 (setq org-todo-sets (nreverse org-todo-sets)
5081 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5082 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5083 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5084 ;; Compute the regular expressions and other local variables.
5085 ;; Using `org-outline-regexp-bol' would complicate them much,
5086 ;; because of the fixed white space at the end of that string.
5087 (if (not org-done-keywords)
5088 (setq org-done-keywords (and org-todo-keywords-1
5089 (list (org-last org-todo-keywords-1)))))
5090 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5091 (length org-scheduled-string)
5092 (length org-clock-string)
5093 (length org-closed-string)))
5094 org-drawer-regexp
5095 (concat "^[ \t]*:\\("
5096 (mapconcat 'regexp-quote org-drawers "\\|")
5097 "\\):[ \t]*$")
5098 org-not-done-keywords
5099 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5100 org-todo-regexp
5101 (concat "\\("
5102 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5103 "\\)")
5104 org-not-done-regexp
5105 (concat "\\("
5106 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5107 "\\)")
5108 org-not-done-heading-regexp
5109 (format org-heading-keyword-regexp-format org-not-done-regexp)
5110 org-todo-line-regexp
5111 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5112 org-complex-heading-regexp
5113 (concat "^\\(\\*+\\)"
5114 "\\(?: +" org-todo-regexp "\\)?"
5115 "\\(?: +\\(\\[#.\\]\\)\\)?"
5116 "\\(?: +\\(.*?\\)\\)??"
5117 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5118 "[ \t]*$")
5119 org-complex-heading-regexp-format
5120 (concat "^\\(\\*+\\)"
5121 "\\(?: +" org-todo-regexp "\\)?"
5122 "\\(?: +\\(\\[#.\\]\\)\\)?"
5123 "\\(?: +"
5124 ;; Stats cookies can be stuck to body.
5125 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5126 "\\(%s\\)"
5127 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5128 "\\)"
5129 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5130 "[ \t]*$")
5131 org-todo-line-tags-regexp
5132 (concat "^\\(\\*+\\)"
5133 "\\(?: +" org-todo-regexp "\\)?"
5134 "\\(?: +\\(.*?\\)\\)??"
5135 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5136 "[ \t]*$")
5137 org-deadline-regexp (concat "\\<" org-deadline-string)
5138 org-deadline-time-regexp
5139 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5140 org-deadline-time-hour-regexp
5141 (concat "\\<" org-deadline-string
5142 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5143 org-deadline-line-regexp
5144 (concat "\\<\\(" org-deadline-string "\\).*")
5145 org-scheduled-regexp
5146 (concat "\\<" org-scheduled-string)
5147 org-scheduled-time-regexp
5148 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5149 org-scheduled-time-hour-regexp
5150 (concat "\\<" org-scheduled-string
5151 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5152 org-closed-time-regexp
5153 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5154 org-keyword-time-regexp
5155 (concat "\\<\\(" org-scheduled-string
5156 "\\|" org-deadline-string
5157 "\\|" org-closed-string
5158 "\\|" org-clock-string "\\)"
5159 " *[[<]\\([^]>]+\\)[]>]")
5160 org-keyword-time-not-clock-regexp
5161 (concat "\\<\\(" org-scheduled-string
5162 "\\|" org-deadline-string
5163 "\\|" org-closed-string
5164 "\\)"
5165 " *[[<]\\([^]>]+\\)[]>]")
5166 org-maybe-keyword-time-regexp
5167 (concat "\\(\\<\\(" org-scheduled-string
5168 "\\|" org-deadline-string
5169 "\\|" org-closed-string
5170 "\\|" org-clock-string "\\)\\)?"
5171 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5172 org-all-time-keywords
5173 (mapcar (lambda (w) (substring w 0 -1))
5174 (list org-scheduled-string org-deadline-string
5175 org-clock-string org-closed-string)))
5176 (setq org-ota nil)
5177 (org-compute-latex-and-related-regexp))))
5179 (defun org-file-contents (file &optional noerror)
5180 "Return the contents of FILE, as a string."
5181 (if (or (not file)
5182 (not (file-readable-p file)))
5183 (if noerror
5184 (message "Cannot read file \"%s\"" file)
5185 (error "Cannot read file \"%s\"" file))
5186 (with-temp-buffer
5187 (insert-file-contents file)
5188 (buffer-string))))
5190 (defun org-extract-log-state-settings (x)
5191 "Extract the log state setting from a TODO keyword string.
5192 This will extract info from a string like \"WAIT(w@/!)\"."
5193 (let (kw key log1 log2)
5194 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5195 (setq kw (match-string 1 x)
5196 key (and (match-end 2) (match-string 2 x))
5197 log1 (and (match-end 3) (match-string 3 x))
5198 log2 (and (match-end 4) (match-string 4 x)))
5199 (and (or log1 log2)
5200 (list kw
5201 (and log1 (if (equal log1 "!") 'time 'note))
5202 (and log2 (if (equal log2 "!") 'time 'note)))))))
5204 (defun org-remove-keyword-keys (list)
5205 "Remove a pair of parenthesis at the end of each string in LIST."
5206 (mapcar (lambda (x)
5207 (if (string-match "(.*)$" x)
5208 (substring x 0 (match-beginning 0))
5210 list))
5212 (defun org-assign-fast-keys (alist)
5213 "Assign fast keys to a keyword-key alist.
5214 Respect keys that are already there."
5215 (let (new e (alt ?0))
5216 (while (setq e (pop alist))
5217 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5218 (cdr e)) ;; Key already assigned.
5219 (push e new)
5220 (let ((clist (string-to-list (downcase (car e))))
5221 (used (append new alist)))
5222 (when (= (car clist) ?@)
5223 (pop clist))
5224 (while (and clist (rassoc (car clist) used))
5225 (pop clist))
5226 (unless clist
5227 (while (rassoc alt used)
5228 (incf alt)))
5229 (push (cons (car e) (or (car clist) alt)) new))))
5230 (nreverse new)))
5232 ;;; Some variables used in various places
5234 (defvar org-window-configuration nil
5235 "Used in various places to store a window configuration.")
5236 (defvar org-selected-window nil
5237 "Used in various places to store a window configuration.")
5238 (defvar org-finish-function nil
5239 "Function to be called when `C-c C-c' is used.
5240 This is for getting out of special buffers like capture.")
5243 ;; FIXME: Occasionally check by commenting these, to make sure
5244 ;; no other functions uses these, forgetting to let-bind them.
5245 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5246 (defvar org-last-state)
5247 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5249 ;; Defined somewhere in this file, but used before definition.
5250 (defvar org-entities) ;; defined in org-entities.el
5251 (defvar org-struct-menu)
5252 (defvar org-org-menu)
5253 (defvar org-tbl-menu)
5255 ;;;; Define the Org-mode
5257 ;; We use a before-change function to check if a table might need
5258 ;; an update.
5259 (defvar org-table-may-need-update t
5260 "Indicates that a table might need an update.
5261 This variable is set by `org-before-change-function'.
5262 `org-table-align' sets it back to nil.")
5263 (defun org-before-change-function (beg end)
5264 "Every change indicates that a table might need an update."
5265 (setq org-table-may-need-update t))
5266 (defvar org-mode-map)
5267 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5268 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5269 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5270 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5271 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5272 (defvar org-table-buffer-is-an nil)
5274 (defvar bidi-paragraph-direction)
5275 (defvar buffer-face-mode-face)
5277 (require 'outline)
5278 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5279 (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"))
5280 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5282 ;; Other stuff we need.
5283 (require 'time-date)
5284 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5285 (require 'easymenu)
5286 (require 'overlay)
5288 ;; (require 'org-macs) moved higher up in the file before it is first used
5289 (require 'org-entities)
5290 ;; (require 'org-compat) moved higher up in the file before it is first used
5291 (require 'org-faces)
5292 (require 'org-list)
5293 (require 'org-pcomplete)
5294 (require 'org-src)
5295 (require 'org-footnote)
5296 (require 'org-macro)
5298 ;; babel
5299 (require 'ob)
5301 ;;;###autoload
5302 (define-derived-mode org-mode outline-mode "Org"
5303 "Outline-based notes management and organizer, alias
5304 \"Carsten's outline-mode for keeping track of everything.\"
5306 Org-mode develops organizational tasks around a NOTES file which
5307 contains information about projects as plain text. Org-mode is
5308 implemented on top of outline-mode, which is ideal to keep the content
5309 of large files well structured. It supports ToDo items, deadlines and
5310 time stamps, which magically appear in the diary listing of the Emacs
5311 calendar. Tables are easily created with a built-in table editor.
5312 Plain text URL-like links connect to websites, emails (VM), Usenet
5313 messages (Gnus), BBDB entries, and any files related to the project.
5314 For printing and sharing of notes, an Org-mode file (or a part of it)
5315 can be exported as a structured ASCII or HTML file.
5317 The following commands are available:
5319 \\{org-mode-map}"
5321 ;; Get rid of Outline menus, they are not needed
5322 ;; Need to do this here because define-derived-mode sets up
5323 ;; the keymap so late. Still, it is a waste to call this each time
5324 ;; we switch another buffer into org-mode.
5325 (if (featurep 'xemacs)
5326 (when (boundp 'outline-mode-menu-heading)
5327 ;; Assume this is Greg's port, it uses easymenu
5328 (easy-menu-remove outline-mode-menu-heading)
5329 (easy-menu-remove outline-mode-menu-show)
5330 (easy-menu-remove outline-mode-menu-hide))
5331 (define-key org-mode-map [menu-bar headings] 'undefined)
5332 (define-key org-mode-map [menu-bar hide] 'undefined)
5333 (define-key org-mode-map [menu-bar show] 'undefined))
5335 (org-load-modules-maybe)
5336 (easy-menu-add org-org-menu)
5337 (easy-menu-add org-tbl-menu)
5338 (org-install-agenda-files-menu)
5339 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5340 (add-to-invisibility-spec '(org-cwidth))
5341 (add-to-invisibility-spec '(org-hide-block . t))
5342 (when (featurep 'xemacs)
5343 (org-set-local 'line-move-ignore-invisible t))
5344 (org-set-local 'outline-regexp org-outline-regexp)
5345 (org-set-local 'outline-level 'org-outline-level)
5346 (setq bidi-paragraph-direction 'left-to-right)
5347 (when (and org-ellipsis
5348 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5349 (fboundp 'make-glyph-code))
5350 (unless org-display-table
5351 (setq org-display-table (make-display-table)))
5352 (set-display-table-slot
5353 org-display-table 4
5354 (vconcat (mapcar
5355 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5356 org-ellipsis)))
5357 (if (stringp org-ellipsis) org-ellipsis "..."))))
5358 (setq buffer-display-table org-display-table))
5359 (org-set-regexps-and-options-for-tags)
5360 (org-set-regexps-and-options)
5361 (org-set-font-lock-defaults)
5362 (when (and org-tag-faces (not org-tags-special-faces-re))
5363 ;; tag faces set outside customize.... force initialization.
5364 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5365 ;; Calc embedded
5366 (org-set-local 'calc-embedded-open-mode "# ")
5367 ;; Modify a few syntax entries
5368 (modify-syntax-entry ?@ "w")
5369 (modify-syntax-entry ?\" "\"")
5370 (if org-startup-truncated (setq truncate-lines t))
5371 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5372 (org-set-local 'font-lock-unfontify-region-function
5373 'org-unfontify-region)
5374 ;; Activate before-change-function
5375 (org-set-local 'org-table-may-need-update t)
5376 (org-add-hook 'before-change-functions 'org-before-change-function nil
5377 'local)
5378 ;; Check for running clock before killing a buffer
5379 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5380 ;; Initialize macros templates.
5381 (org-macro-initialize-templates)
5382 ;; Initialize radio targets.
5383 (org-update-radio-target-regexp)
5384 ;; Indentation.
5385 (org-set-local 'indent-line-function 'org-indent-line)
5386 (org-set-local 'indent-region-function 'org-indent-region)
5387 ;; Filling and auto-filling.
5388 (org-setup-filling)
5389 ;; Comments.
5390 (org-setup-comments-handling)
5391 ;; Beginning/end of defun
5392 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5393 (org-set-local 'end-of-defun-function 'org-forward-element)
5394 ;; Next error for sparse trees
5395 (org-set-local 'next-error-function 'org-occur-next-match)
5396 ;; Make sure dependence stuff works reliably, even for users who set it
5397 ;; too late :-(
5398 (if org-enforce-todo-dependencies
5399 (add-hook 'org-blocker-hook
5400 'org-block-todo-from-children-or-siblings-or-parent)
5401 (remove-hook 'org-blocker-hook
5402 'org-block-todo-from-children-or-siblings-or-parent))
5403 (if org-enforce-todo-checkbox-dependencies
5404 (add-hook 'org-blocker-hook
5405 'org-block-todo-from-checkboxes)
5406 (remove-hook 'org-blocker-hook
5407 'org-block-todo-from-checkboxes))
5409 ;; Align options lines
5410 (org-set-local
5411 'align-mode-rules-list
5412 '((org-in-buffer-settings
5413 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5414 (modes . '(org-mode)))))
5416 ;; Imenu
5417 (org-set-local 'imenu-create-index-function
5418 'org-imenu-get-tree)
5420 ;; Make isearch reveal context
5421 (if (or (featurep 'xemacs)
5422 (not (boundp 'outline-isearch-open-invisible-function)))
5423 ;; Emacs 21 and XEmacs make use of the hook
5424 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5425 ;; Emacs 22 deals with this through a special variable
5426 (org-set-local 'outline-isearch-open-invisible-function
5427 (lambda (&rest ignore) (org-show-context 'isearch)))
5428 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5430 ;; Setup the pcomplete hooks
5431 (set (make-local-variable 'pcomplete-command-completion-function)
5432 'org-pcomplete-initial)
5433 (set (make-local-variable 'pcomplete-command-name-function)
5434 'org-command-at-point)
5435 (set (make-local-variable 'pcomplete-default-completion-function)
5436 'ignore)
5437 (set (make-local-variable 'pcomplete-parse-arguments-function)
5438 'org-parse-arguments)
5439 (set (make-local-variable 'pcomplete-termination-string) "")
5440 (when (>= emacs-major-version 23)
5441 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5443 ;; If empty file that did not turn on org-mode automatically, make it to.
5444 (if (and org-insert-mode-line-in-empty-file
5445 (org-called-interactively-p 'any)
5446 (= (point-min) (point-max)))
5447 (insert "# -*- mode: org -*-\n\n"))
5448 (unless org-inhibit-startup
5449 (org-unmodified
5450 (and org-startup-with-beamer-mode (org-beamer-mode))
5451 (when org-startup-align-all-tables
5452 (org-table-map-tables 'org-table-align 'quietly))
5453 (when org-startup-with-inline-images
5454 (org-display-inline-images))
5455 (when org-startup-with-latex-preview
5456 (org-preview-latex-fragment))
5457 (unless org-inhibit-startup-visibility-stuff
5458 (org-set-startup-visibility))))
5459 ;; Try to set org-hide correctly
5460 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5462 ;; Update `customize-package-emacs-version-alist'
5463 (add-to-list 'customize-package-emacs-version-alist
5464 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5465 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5466 ("8.0" . "24.4")))
5468 (defvar org-mode-transpose-word-syntax-table
5469 (let ((st (make-syntax-table)))
5470 (mapc (lambda(c) (modify-syntax-entry
5471 (string-to-char (car c)) "w p" st))
5472 org-emphasis-alist)
5473 st))
5475 (when (fboundp 'abbrev-table-put)
5476 (abbrev-table-put org-mode-abbrev-table
5477 :parents (list text-mode-abbrev-table)))
5479 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5481 (defsubst org-fix-ellipsis-at-bol ()
5482 (save-excursion (goto-char (window-start)) (recenter 0)))
5484 (defun org-find-invisible-foreground ()
5485 (let ((candidates (remove
5486 "unspecified-bg"
5487 (nconc
5488 (list (face-background 'default)
5489 (face-background 'org-default))
5490 (mapcar
5491 (lambda (alist)
5492 (when (boundp alist)
5493 (cdr (assoc 'background-color (symbol-value alist)))))
5494 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5495 (list (face-foreground 'org-hide))))))
5496 (car (remove nil candidates))))
5498 (defun org-current-time (&optional rounding-minutes past)
5499 "Current time, possibly rounded to ROUNDING-MINUTES.
5500 When ROUNDING-MINUTES is not an integer, fall back on the car of
5501 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5502 the rounding returns a past time."
5503 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5504 (car org-time-stamp-rounding-minutes)))
5505 (time (decode-time)) res)
5506 (if (< r 1)
5507 (current-time)
5508 (setq res
5509 (apply 'encode-time
5510 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5511 (nthcdr 2 time))))
5512 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5513 (seconds-to-time (- (org-float-time res) (* r 60)))
5514 res))))
5516 (defun org-today ()
5517 "Return today date, considering `org-extend-today-until'."
5518 (time-to-days
5519 (time-subtract (current-time)
5520 (list 0 (* 3600 org-extend-today-until) 0))))
5522 ;;;; Font-Lock stuff, including the activators
5524 (defvar org-mouse-map (make-sparse-keymap))
5525 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5526 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5527 (when org-mouse-1-follows-link
5528 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5529 (when org-tab-follows-link
5530 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5531 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5533 (require 'font-lock)
5535 (defconst org-non-link-chars "]\t\n\r<>")
5536 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5537 "shell" "elisp" "doi" "message"))
5538 (defvar org-link-types-re nil
5539 "Matches a link that has a url-like prefix like \"http:\"")
5540 (defvar org-link-re-with-space nil
5541 "Matches a link with spaces, optional angular brackets around it.")
5542 (defvar org-link-re-with-space2 nil
5543 "Matches a link with spaces, optional angular brackets around it.")
5544 (defvar org-link-re-with-space3 nil
5545 "Matches a link with spaces, only for internal part in bracket links.")
5546 (defvar org-angle-link-re nil
5547 "Matches link with angular brackets, spaces are allowed.")
5548 (defvar org-plain-link-re nil
5549 "Matches plain link, without spaces.")
5550 (defvar org-bracket-link-regexp nil
5551 "Matches a link in double brackets.")
5552 (defvar org-bracket-link-analytic-regexp nil
5553 "Regular expression used to analyze links.
5554 Here is what the match groups contain after a match:
5555 1: http:
5556 2: http
5557 3: path
5558 4: [desc]
5559 5: desc")
5560 (defvar org-bracket-link-analytic-regexp++ nil
5561 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5562 (defvar org-any-link-re nil
5563 "Regular expression matching any link.")
5565 (defconst org-match-sexp-depth 3
5566 "Number of stacked braces for sub/superscript matching.")
5568 (defun org-create-multibrace-regexp (left right n)
5569 "Create a regular expression which will match a balanced sexp.
5570 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5571 as single character strings.
5572 The regexp returned will match the entire expression including the
5573 delimiters. It will also define a single group which contains the
5574 match except for the outermost delimiters. The maximum depth of
5575 stacked delimiters is N. Escaping delimiters is not possible."
5576 (let* ((nothing (concat "[^" left right "]*?"))
5577 (or "\\|")
5578 (re nothing)
5579 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5580 (while (> n 1)
5581 (setq n (1- n)
5582 re (concat re or next)
5583 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5584 (concat left "\\(" re "\\)" right)))
5586 (defvar org-match-substring-regexp
5587 (concat
5588 "\\(\\S-\\)\\([_^]\\)\\("
5589 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5590 "\\|"
5591 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5592 "\\|"
5593 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5594 "The regular expression matching a sub- or superscript.")
5596 (defvar org-match-substring-with-braces-regexp
5597 (concat
5598 "\\(\\S-\\)\\([_^]\\)\\("
5599 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5600 "\\)")
5601 "The regular expression matching a sub- or superscript, forcing braces.")
5603 (defun org-make-link-regexps ()
5604 "Update the link regular expressions.
5605 This should be called after the variable `org-link-types' has changed."
5606 (setq org-link-types-re
5607 (concat
5608 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5609 org-link-re-with-space
5610 (concat
5611 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5612 "\\([^" org-non-link-chars " ]"
5613 "[^" org-non-link-chars "]*"
5614 "[^" org-non-link-chars " ]\\)>?")
5615 org-link-re-with-space2
5616 (concat
5617 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5618 "\\([^" org-non-link-chars " ]"
5619 "[^\t\n\r]*"
5620 "[^" org-non-link-chars " ]\\)>?")
5621 org-link-re-with-space3
5622 (concat
5623 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5624 "\\([^" org-non-link-chars " ]"
5625 "[^\t\n\r]*\\)")
5626 org-angle-link-re
5627 (concat
5628 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5629 "\\([^" org-non-link-chars " ]"
5630 "[^" org-non-link-chars "]*"
5631 "\\)>")
5632 org-plain-link-re
5633 (concat
5634 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5635 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5636 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5637 org-bracket-link-regexp
5638 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5639 org-bracket-link-analytic-regexp
5640 (concat
5641 "\\[\\["
5642 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5643 "\\([^]]+\\)"
5644 "\\]"
5645 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5646 "\\]")
5647 org-bracket-link-analytic-regexp++
5648 (concat
5649 "\\[\\["
5650 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5651 "\\([^]]+\\)"
5652 "\\]"
5653 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5654 "\\]")
5655 org-any-link-re
5656 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5657 org-angle-link-re "\\)\\|\\("
5658 org-plain-link-re "\\)")))
5660 (org-make-link-regexps)
5662 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5663 "Regular expression for fast time stamp matching.")
5664 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5665 "Regular expression for fast time stamp matching.")
5666 (defconst org-ts-regexp0
5667 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5668 "Regular expression matching time strings for analysis.
5669 This one does not require the space after the date, so it can be used
5670 on a string that terminates immediately after the date.")
5671 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5672 "Regular expression matching time strings for analysis.")
5673 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5674 "Regular expression matching time stamps, with groups.")
5675 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5676 "Regular expression matching time stamps (also [..]), with groups.")
5677 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5678 "Regular expression matching a time stamp range.")
5679 (defconst org-tr-regexp-both
5680 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5681 "Regular expression matching a time stamp range.")
5682 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5683 org-ts-regexp "\\)?")
5684 "Regular expression matching a time stamp or time stamp range.")
5685 (defconst org-tsr-regexp-both
5686 (concat org-ts-regexp-both "\\(--?-?"
5687 org-ts-regexp-both "\\)?")
5688 "Regular expression matching a time stamp or time stamp range.
5689 The time stamps may be either active or inactive.")
5691 (defvar org-emph-face nil)
5693 (defun org-do-emphasis-faces (limit)
5694 "Run through the buffer and add overlays to emphasized strings."
5695 (let (rtn a)
5696 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5697 (if (not (= (char-after (match-beginning 3))
5698 (char-after (match-beginning 4))))
5699 (progn
5700 (setq rtn t)
5701 (setq a (assoc (match-string 3) org-emphasis-alist))
5702 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5703 'face
5704 (nth 1 a))
5705 (and (nth 2 a)
5706 (org-remove-flyspell-overlays-in
5707 (match-beginning 0) (match-end 0)))
5708 (add-text-properties (match-beginning 2) (match-end 2)
5709 '(font-lock-multiline t org-emphasis t))
5710 (when org-hide-emphasis-markers
5711 (add-text-properties (match-end 4) (match-beginning 5)
5712 '(invisible org-link))
5713 (add-text-properties (match-beginning 3) (match-end 3)
5714 '(invisible org-link)))))
5715 (backward-char 1))
5716 rtn))
5718 (defun org-emphasize (&optional char)
5719 "Insert or change an emphasis, i.e. a font like bold or italic.
5720 If there is an active region, change that region to a new emphasis.
5721 If there is no region, just insert the marker characters and position
5722 the cursor between them.
5723 CHAR should be the marker character. If it is a space, it means to
5724 remove the emphasis of the selected region.
5725 If CHAR is not given (for example in an interactive call) it will be
5726 prompted for."
5727 (interactive)
5728 (let ((erc org-emphasis-regexp-components)
5729 (prompt "")
5730 (string "") beg end move c s)
5731 (if (org-region-active-p)
5732 (setq beg (region-beginning) end (region-end)
5733 string (buffer-substring beg end))
5734 (setq move t))
5736 (unless char
5737 (message "Emphasis marker or tag: [%s]"
5738 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5739 (setq char (read-char-exclusive)))
5740 (if (equal char ?\ )
5741 (setq s "" move nil)
5742 (unless (assoc (char-to-string char) org-emphasis-alist)
5743 (user-error "No such emphasis marker: \"%c\"" char))
5744 (setq s (char-to-string char)))
5745 (while (and (> (length string) 1)
5746 (equal (substring string 0 1) (substring string -1))
5747 (assoc (substring string 0 1) org-emphasis-alist))
5748 (setq string (substring string 1 -1)))
5749 (setq string (concat s string s))
5750 (if beg (delete-region beg end))
5751 (unless (or (bolp)
5752 (string-match (concat "[" (nth 0 erc) "\n]")
5753 (char-to-string (char-before (point)))))
5754 (insert " "))
5755 (unless (or (eobp)
5756 (string-match (concat "[" (nth 1 erc) "\n]")
5757 (char-to-string (char-after (point)))))
5758 (insert " ") (backward-char 1))
5759 (insert string)
5760 (and move (backward-char 1))))
5762 (defconst org-nonsticky-props
5763 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5765 (defsubst org-rear-nonsticky-at (pos)
5766 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5768 (defun org-activate-plain-links (limit)
5769 "Run through the buffer and add overlays to links."
5770 (let (f hl)
5771 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5772 (not (org-in-src-block-p)))
5773 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5774 (setq f (get-text-property (match-beginning 0) 'face))
5775 (setq hl (org-match-string-no-properties 0))
5776 (if (or (eq f 'org-tag)
5777 (and (listp f) (memq 'org-tag f)))
5779 (add-text-properties (match-beginning 0) (match-end 0)
5780 (list 'mouse-face 'highlight
5781 'face 'org-link
5782 'htmlize-link `(:uri ,hl)
5783 'keymap org-mouse-map))
5784 (org-rear-nonsticky-at (match-end 0)))
5785 t)))
5787 (defun org-activate-code (limit)
5788 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5789 (progn
5790 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5791 (remove-text-properties (match-beginning 0) (match-end 0)
5792 '(display t invisible t intangible t))
5793 t)))
5795 (defcustom org-src-fontify-natively nil
5796 "When non-nil, fontify code in code blocks."
5797 :type 'boolean
5798 :version "24.1"
5799 :group 'org-appearance
5800 :group 'org-babel)
5802 (defcustom org-allow-promoting-top-level-subtree nil
5803 "When non-nil, allow promoting a top level subtree.
5804 The leading star of the top level headline will be replaced
5805 by a #."
5806 :type 'boolean
5807 :version "24.1"
5808 :group 'org-appearance)
5810 (defun org-fontify-meta-lines-and-blocks (limit)
5811 (condition-case nil
5812 (org-fontify-meta-lines-and-blocks-1 limit)
5813 (error (message "org-mode fontification error"))))
5815 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5816 "Fontify #+ lines and blocks."
5817 (let ((case-fold-search t))
5818 (if (re-search-forward
5819 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5820 limit t)
5821 (let ((beg (match-beginning 0))
5822 (block-start (match-end 0))
5823 (block-end nil)
5824 (lang (match-string 7))
5825 (beg1 (line-beginning-position 2))
5826 (dc1 (downcase (match-string 2)))
5827 (dc3 (downcase (match-string 3)))
5828 end end1 quoting block-type ovl)
5829 (cond
5830 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5831 ;; a single line of backend-specific content
5832 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5833 (remove-text-properties (match-beginning 0) (match-end 0)
5834 '(display t invisible t intangible t))
5835 (add-text-properties (match-beginning 1) (match-end 3)
5836 '(font-lock-fontified t face org-meta-line))
5837 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5838 '(font-lock-fontified t face org-block))
5839 ; for backend-specific code
5841 ((and (match-end 4) (equal dc3 "+begin"))
5842 ;; Truly a block
5843 (setq block-type (downcase (match-string 5))
5844 quoting (member block-type org-protecting-blocks))
5845 (when (re-search-forward
5846 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5847 nil t) ;; on purpose, we look further than LIMIT
5848 (setq end (min (point-max) (match-end 0))
5849 end1 (min (point-max) (1- (match-beginning 0))))
5850 (setq block-end (match-beginning 0))
5851 (when quoting
5852 (remove-text-properties beg end
5853 '(display t invisible t intangible t)))
5854 (add-text-properties
5855 beg end
5856 '(font-lock-fontified t font-lock-multiline t))
5857 (add-text-properties beg beg1 '(face org-meta-line))
5858 (add-text-properties end1 (min (point-max) (1+ end))
5859 '(face org-meta-line)) ; for end_src
5860 (cond
5861 ((and lang (not (string= lang "")) org-src-fontify-natively)
5862 (org-src-font-lock-fontify-block lang block-start block-end)
5863 ;; remove old background overlays
5864 (mapc (lambda (ov)
5865 (if (eq (overlay-get ov 'face) 'org-block-background)
5866 (delete-overlay ov)))
5867 (overlays-at (/ (+ beg1 block-end) 2)))
5868 ;; add a background overlay
5869 (setq ovl (make-overlay beg1 block-end))
5870 (overlay-put ovl 'face 'org-block-background)
5871 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5872 (quoting
5873 (add-text-properties beg1 (min (point-max) (1+ end1))
5874 '(face org-block))) ; end of source block
5875 ((not org-fontify-quote-and-verse-blocks))
5876 ((string= block-type "quote")
5877 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5878 ((string= block-type "verse")
5879 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5880 (add-text-properties beg beg1 '(face org-block-begin-line))
5881 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5882 '(face org-block-end-line))
5884 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5885 (add-text-properties
5886 beg (match-end 3)
5887 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5888 '(font-lock-fontified t invisible t)
5889 '(font-lock-fontified t face org-document-info-keyword)))
5890 (add-text-properties
5891 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5892 (if (string-equal dc1 "+title:")
5893 '(font-lock-fontified t face org-document-title)
5894 '(font-lock-fontified t face org-document-info))))
5895 ((or (equal dc1 "+results")
5896 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5897 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5898 "+call:" "+header:" "+headers:" "+name:"))
5899 (and (match-end 4) (equal dc3 "+attr")))
5900 (add-text-properties
5901 beg (match-end 0)
5902 '(font-lock-fontified t face org-meta-line))
5904 ((member dc3 '(" " ""))
5905 (add-text-properties
5906 beg (match-end 0)
5907 '(font-lock-fontified t face font-lock-comment-face)))
5908 ((not (member (char-after beg) '(?\ ?\t)))
5909 ;; just any other in-buffer setting, but not indented
5910 (add-text-properties
5911 beg (match-end 0)
5912 '(font-lock-fontified t face org-meta-line))
5914 (t nil))))))
5916 (defun org-activate-angle-links (limit)
5917 "Run through the buffer and add overlays to links."
5918 (if (and (re-search-forward org-angle-link-re limit t)
5919 (not (org-in-src-block-p)))
5920 (progn
5921 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5922 (add-text-properties (match-beginning 0) (match-end 0)
5923 (list 'mouse-face 'highlight
5924 'keymap org-mouse-map))
5925 (org-rear-nonsticky-at (match-end 0))
5926 t)))
5928 (defun org-activate-footnote-links (limit)
5929 "Run through the buffer and add overlays to footnotes."
5930 (let ((fn (org-footnote-next-reference-or-definition limit)))
5931 (when fn
5932 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5933 (org-remove-flyspell-overlays-in beg end)
5934 (add-text-properties beg end
5935 (list 'mouse-face 'highlight
5936 'keymap org-mouse-map
5937 'help-echo
5938 (if (= (point-at-bol) beg)
5939 "Footnote definition"
5940 "Footnote reference")
5941 'font-lock-fontified t
5942 'font-lock-multiline t
5943 'face 'org-footnote))))))
5945 (defun org-activate-bracket-links (limit)
5946 "Run through the buffer and add overlays to bracketed links."
5947 (if (and (re-search-forward org-bracket-link-regexp limit t)
5948 (not (org-in-src-block-p)))
5949 (let* ((hl (org-match-string-no-properties 1))
5950 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5951 (ip (org-maybe-intangible
5952 (list 'invisible 'org-link
5953 'keymap org-mouse-map 'mouse-face 'highlight
5954 'font-lock-multiline t 'help-echo help
5955 'htmlize-link `(:uri ,hl))))
5956 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5957 'font-lock-multiline t 'help-echo help
5958 'htmlize-link `(:uri ,hl))))
5959 ;; We need to remove the invisible property here. Table narrowing
5960 ;; may have made some of this invisible.
5961 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5962 (remove-text-properties (match-beginning 0) (match-end 0)
5963 '(invisible nil))
5964 (if (match-end 3)
5965 (progn
5966 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5967 (org-rear-nonsticky-at (match-beginning 3))
5968 (add-text-properties (match-beginning 3) (match-end 3) vp)
5969 (org-rear-nonsticky-at (match-end 3))
5970 (add-text-properties (match-end 3) (match-end 0) ip)
5971 (org-rear-nonsticky-at (match-end 0)))
5972 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5973 (org-rear-nonsticky-at (match-beginning 1))
5974 (add-text-properties (match-beginning 1) (match-end 1) vp)
5975 (org-rear-nonsticky-at (match-end 1))
5976 (add-text-properties (match-end 1) (match-end 0) ip)
5977 (org-rear-nonsticky-at (match-end 0)))
5978 t)))
5980 (defun org-activate-dates (limit)
5981 "Run through the buffer and add overlays to dates."
5982 (if (and (re-search-forward org-tsr-regexp-both limit t)
5983 (not (equal (char-before (match-beginning 0)) 91)))
5984 (progn
5985 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5986 (add-text-properties (match-beginning 0) (match-end 0)
5987 (list 'mouse-face 'highlight
5988 'keymap org-mouse-map))
5989 (org-rear-nonsticky-at (match-end 0))
5990 (when org-display-custom-times
5991 (if (match-end 3)
5992 (org-display-custom-time (match-beginning 3) (match-end 3)))
5993 (org-display-custom-time (match-beginning 1) (match-end 1)))
5994 t)))
5996 (defvar org-target-link-regexp nil
5997 "Regular expression matching radio targets in plain text.")
5998 (make-variable-buffer-local 'org-target-link-regexp)
5999 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6000 "Regular expression matching a link target.")
6001 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6002 "Regular expression matching a radio target.")
6003 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6004 "Regular expression matching any target.")
6006 (defun org-activate-target-links (limit)
6007 "Run through the buffer and add overlays to target matches."
6008 (when org-target-link-regexp
6009 (let ((case-fold-search t))
6010 (if (re-search-forward org-target-link-regexp limit t)
6011 (progn
6012 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6013 (add-text-properties (match-beginning 0) (match-end 0)
6014 (list 'mouse-face 'highlight
6015 'keymap org-mouse-map
6016 'help-echo "Radio target link"
6017 'org-linked-text t))
6018 (org-rear-nonsticky-at (match-end 0))
6019 t)))))
6021 (defun org-update-radio-target-regexp ()
6022 "Find all radio targets in this file and update the regular expression."
6023 (interactive)
6024 (when (memq 'radio org-activate-links)
6025 (setq org-target-link-regexp
6026 (org-make-target-link-regexp (org-all-targets 'radio)))
6027 (org-restart-font-lock)))
6029 (defun org-hide-wide-columns (limit)
6030 (let (s e)
6031 (setq s (text-property-any (point) (or limit (point-max))
6032 'org-cwidth t))
6033 (when s
6034 (setq e (next-single-property-change s 'org-cwidth))
6035 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6036 (goto-char e)
6037 t)))
6039 (defvar org-latex-and-related-regexp nil
6040 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6041 (defvar org-match-substring-regexp)
6042 (defvar org-match-substring-with-braces-regexp)
6044 (defun org-compute-latex-and-related-regexp ()
6045 "Compute regular expression for LaTeX, entities and sub/superscript.
6046 Result depends on variable `org-highlight-latex-and-related'."
6047 (org-set-local
6048 'org-latex-and-related-regexp
6049 (let* ((re-sub
6050 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6051 ((eq org-use-sub-superscripts '{})
6052 (list org-match-substring-with-braces-regexp))
6053 (org-use-sub-superscripts (list org-match-substring-regexp))))
6054 (re-latex
6055 (when (memq 'latex org-highlight-latex-and-related)
6056 (let ((matchers (plist-get org-format-latex-options :matchers)))
6057 (delq nil
6058 (mapcar (lambda (x)
6059 (and (member (car x) matchers) (nth 1 x)))
6060 org-latex-regexps)))))
6061 (re-entities
6062 (when (memq 'entities org-highlight-latex-and-related)
6063 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6064 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6066 (defun org-do-latex-and-related (limit)
6067 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6068 LIMIT bounds the search for syntax to highlight. Stop at first
6069 highlighted object, if any. Return t if some highlighting was
6070 done, nil otherwise."
6071 (when (org-string-nw-p org-latex-and-related-regexp)
6072 (catch 'found
6073 (while (re-search-forward org-latex-and-related-regexp limit t)
6074 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6075 'face))
6076 '(org-code org-verbatim underline))
6077 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6078 '(?_ ?^))
6080 0)))
6081 (font-lock-prepend-text-property
6082 (+ offset (match-beginning 0)) (match-end 0)
6083 'face 'org-latex-and-related)
6084 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6085 '(font-lock-multiline t)))
6086 (throw 'found t)))
6087 nil)))
6089 (defun org-restart-font-lock ()
6090 "Restart `font-lock-mode', to force refontification."
6091 (when (and (boundp 'font-lock-mode) font-lock-mode)
6092 (font-lock-mode -1)
6093 (font-lock-mode 1)))
6095 (defun org-all-targets (&optional radio)
6096 "Return a list of all targets in this file.
6097 When optional argument RADIO is non-nil, only find radio
6098 targets."
6099 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6100 (save-excursion
6101 (goto-char (point-min))
6102 (while (re-search-forward re nil t)
6103 ;; Make sure point is really within the object.
6104 (backward-char)
6105 (let ((obj (org-element-context)))
6106 (when (memq (org-element-type obj) '(radio-target target))
6107 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6108 rtn)))
6110 (defun org-make-target-link-regexp (targets)
6111 "Make regular expression matching all strings in TARGETS.
6112 The regular expression finds the targets also if there is a line break
6113 between words."
6114 (and targets
6115 (concat
6116 "\\<\\("
6117 (mapconcat
6118 (lambda (x)
6119 (setq x (regexp-quote x))
6120 (while (string-match " +" x)
6121 (setq x (replace-match "\\s-+" t t x)))
6123 targets
6124 "\\|")
6125 "\\)\\>")))
6127 (defun org-activate-tags (limit)
6128 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6129 (progn
6130 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6131 (add-text-properties (match-beginning 1) (match-end 1)
6132 (list 'mouse-face 'highlight
6133 'keymap org-mouse-map))
6134 (org-rear-nonsticky-at (match-end 1))
6135 t)))
6137 (defun org-outline-level ()
6138 "Compute the outline level of the heading at point.
6139 If this is called at a normal headline, the level is the number of stars.
6140 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6141 (save-excursion
6142 (if (not (condition-case nil
6143 (org-back-to-heading t)
6144 (error nil)))
6146 (looking-at org-outline-regexp)
6147 (1- (- (match-end 0) (match-beginning 0))))))
6149 (defvar org-font-lock-keywords nil)
6151 (defsubst org-re-property (property &optional literal)
6152 "Return a regexp matching a PROPERTY line.
6153 Match group 3 will be set to the value if it exists."
6154 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6155 (if literal property (regexp-quote property))
6156 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6158 (defconst org-property-re
6159 (org-re-property ".*?" 'literal)
6160 "Regular expression matching a property line.
6161 There are four matching groups:
6162 1: :PROPKEY: including the leading and trailing colon,
6163 2: PROPKEY without the leading and trailing colon,
6164 3: PROPVAL without leading or trailing spaces,
6165 4: the indentation of the current line,
6166 5: trailing whitespace.")
6168 (defvar org-font-lock-hook nil
6169 "Functions to be called for special font lock stuff.")
6171 (defvar org-font-lock-set-keywords-hook nil
6172 "Functions that can manipulate `org-font-lock-extra-keywords'.
6173 This is called after `org-font-lock-extra-keywords' is defined, but before
6174 it is installed to be used by font lock. This can be useful if something
6175 needs to be inserted at a specific position in the font-lock sequence.")
6177 (defun org-font-lock-hook (limit)
6178 "Run `org-font-lock-hook' within LIMIT."
6179 (run-hook-with-args 'org-font-lock-hook limit))
6181 (defun org-set-font-lock-defaults ()
6182 "Set font lock defaults for the current buffer."
6183 (let* ((em org-fontify-emphasized-text)
6184 (lk org-activate-links)
6185 (org-font-lock-extra-keywords
6186 (list
6187 ;; Call the hook
6188 '(org-font-lock-hook)
6189 ;; Headlines
6190 `(,(if org-fontify-whole-heading-line
6191 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6192 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6193 (1 (org-get-level-face 1))
6194 (2 (org-get-level-face 2))
6195 (3 (org-get-level-face 3)))
6196 ;; Table lines
6197 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6198 (1 'org-table t))
6199 ;; Table internals
6200 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6201 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6202 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6203 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6204 ;; Drawers
6205 (list org-drawer-regexp '(0 'org-special-keyword t))
6206 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6207 ;; Properties
6208 (list org-property-re
6209 '(1 'org-special-keyword t)
6210 '(3 'org-property-value t))
6211 ;; Links
6212 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6213 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6214 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6215 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6216 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6217 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6218 (if (memq 'footnote lk) '(org-activate-footnote-links))
6219 ;; Targets.
6220 (list org-any-target-regexp '(0 'org-target t))
6221 ;; Diary sexps.
6222 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6223 ;; Macro
6224 '("{{{.+}}}" (0 'org-macro t))
6225 '(org-hide-wide-columns (0 nil append))
6226 ;; TODO keyword
6227 (list (format org-heading-keyword-regexp-format
6228 org-todo-regexp)
6229 '(2 (org-get-todo-face 2) t))
6230 ;; DONE
6231 (if org-fontify-done-headline
6232 (list (format org-heading-keyword-regexp-format
6233 (concat
6234 "\\(?:"
6235 (mapconcat 'regexp-quote org-done-keywords "\\|")
6236 "\\)"))
6237 '(2 'org-headline-done t))
6238 nil)
6239 ;; Priorities
6240 '(org-font-lock-add-priority-faces)
6241 ;; Tags
6242 '(org-font-lock-add-tag-faces)
6243 ;; Tags groups
6244 (if (and org-group-tags org-tag-groups-alist)
6245 (list (concat org-outline-regexp-bol ".+\\(:"
6246 (regexp-opt (mapcar 'car org-tag-groups-alist))
6247 ":\\).*$")
6248 '(1 'org-tag-group prepend)))
6249 ;; Special keywords
6250 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6251 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6252 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6253 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6254 ;; Emphasis
6255 (if em
6256 (if (featurep 'xemacs)
6257 '(org-do-emphasis-faces (0 nil append))
6258 '(org-do-emphasis-faces)))
6259 ;; Checkboxes
6260 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6261 1 'org-checkbox prepend)
6262 (if (cdr (assq 'checkbox org-list-automatic-rules))
6263 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6264 (0 (org-get-checkbox-statistics-face) t)))
6265 ;; Description list items
6266 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6267 1 'org-list-dt prepend)
6268 ;; ARCHIVEd headings
6269 (list (concat
6270 org-outline-regexp-bol
6271 "\\(.*:" org-archive-tag ":.*\\)")
6272 '(1 'org-archived prepend))
6273 ;; Specials
6274 '(org-do-latex-and-related)
6275 '(org-fontify-entities)
6276 '(org-raise-scripts)
6277 ;; Code
6278 '(org-activate-code (1 'org-code t))
6279 ;; COMMENT
6280 (list (format org-heading-keyword-regexp-format
6281 (concat "\\("
6282 org-comment-string "\\|" org-quote-string
6283 "\\)"))
6284 '(2 'org-special-keyword t))
6285 ;; Blocks and meta lines
6286 '(org-fontify-meta-lines-and-blocks))))
6287 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6288 (run-hooks 'org-font-lock-set-keywords-hook)
6289 ;; Now set the full font-lock-keywords
6290 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6291 (org-set-local 'font-lock-defaults
6292 '(org-font-lock-keywords t nil nil backward-paragraph))
6293 (kill-local-variable 'font-lock-keywords) nil))
6295 (defun org-toggle-pretty-entities ()
6296 "Toggle the composition display of entities as UTF8 characters."
6297 (interactive)
6298 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6299 (org-restart-font-lock)
6300 (if org-pretty-entities
6301 (message "Entities are now displayed as UTF8 characters")
6302 (save-restriction
6303 (widen)
6304 (org-decompose-region (point-min) (point-max))
6305 (message "Entities are now displayed as plain text"))))
6307 (defvar org-custom-properties-overlays nil
6308 "List of overlays used for custom properties.")
6309 (make-variable-buffer-local 'org-custom-properties-overlays)
6311 (defun org-toggle-custom-properties-visibility ()
6312 "Display or hide properties in `org-custom-properties'."
6313 (interactive)
6314 (if org-custom-properties-overlays
6315 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6316 (setq org-custom-properties-overlays nil))
6317 (unless (not org-custom-properties)
6318 (save-excursion
6319 (save-restriction
6320 (widen)
6321 (goto-char (point-min))
6322 (while (re-search-forward org-property-re nil t)
6323 (mapc (lambda(p)
6324 (when (equal p (substring (match-string 1) 1 -1))
6325 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6326 (overlay-put o 'invisible t)
6327 (overlay-put o 'org-custom-property t)
6328 (push o org-custom-properties-overlays))))
6329 org-custom-properties)))))))
6331 (defun org-fontify-entities (limit)
6332 "Find an entity to fontify."
6333 (let (ee)
6334 (when org-pretty-entities
6335 (catch 'match
6336 (while (re-search-forward
6337 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6338 limit t)
6339 (if (and (not (org-in-indented-comment-line))
6340 (setq ee (org-entity-get (match-string 1)))
6341 (= (length (nth 6 ee)) 1))
6342 (let*
6343 ((end (if (equal (match-string 2) "{}")
6344 (match-end 2)
6345 (match-end 1))))
6346 (add-text-properties
6347 (match-beginning 0) end
6348 (list 'font-lock-fontified t))
6349 (compose-region (match-beginning 0) end
6350 (nth 6 ee) nil)
6351 (backward-char 1)
6352 (throw 'match t))))
6353 nil))))
6355 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6356 "Fontify string S like in Org-mode."
6357 (with-temp-buffer
6358 (insert s)
6359 (let ((org-odd-levels-only odd-levels))
6360 (org-mode)
6361 (font-lock-fontify-buffer)
6362 (buffer-string))))
6364 (defvar org-m nil)
6365 (defvar org-l nil)
6366 (defvar org-f nil)
6367 (defun org-get-level-face (n)
6368 "Get the right face for match N in font-lock matching of headlines."
6369 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6370 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6371 (if org-cycle-level-faces
6372 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6373 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6374 (cond
6375 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6376 ((eq n 2) org-f)
6377 (t (if org-level-color-stars-only nil org-f))))
6380 (defun org-get-todo-face (kwd)
6381 "Get the right face for a TODO keyword KWD.
6382 If KWD is a number, get the corresponding match group."
6383 (if (numberp kwd) (setq kwd (match-string kwd)))
6384 (or (org-face-from-face-or-color
6385 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6386 (and (member kwd org-done-keywords) 'org-done)
6387 'org-todo))
6389 (defun org-face-from-face-or-color (context inherit face-or-color)
6390 "Create a face list that inherits INHERIT, but sets the foreground color.
6391 When FACE-OR-COLOR is not a string, just return it."
6392 (if (stringp face-or-color)
6393 (list :inherit inherit
6394 (cdr (assoc context org-faces-easy-properties))
6395 face-or-color)
6396 face-or-color))
6398 (defun org-font-lock-add-tag-faces (limit)
6399 "Add the special tag faces."
6400 (when (and org-tag-faces org-tags-special-faces-re)
6401 (while (re-search-forward org-tags-special-faces-re limit t)
6402 (add-text-properties (match-beginning 1) (match-end 1)
6403 (list 'face (org-get-tag-face 1)
6404 'font-lock-fontified t))
6405 (backward-char 1))))
6407 (defun org-font-lock-add-priority-faces (limit)
6408 "Add the special priority faces."
6409 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6410 (when (save-match-data (org-at-heading-p))
6411 (add-text-properties
6412 (match-beginning 0) (match-end 0)
6413 (list 'face (or (org-face-from-face-or-color
6414 'priority 'org-priority
6415 (cdr (assoc (char-after (match-beginning 1))
6416 org-priority-faces)))
6417 'org-priority)
6418 'font-lock-fontified t)))))
6420 (defun org-get-tag-face (kwd)
6421 "Get the right face for a TODO keyword KWD.
6422 If KWD is a number, get the corresponding match group."
6423 (if (numberp kwd) (setq kwd (match-string kwd)))
6424 (or (org-face-from-face-or-color
6425 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6426 'org-tag))
6428 (defun org-unfontify-region (beg end &optional maybe_loudly)
6429 "Remove fontification and activation overlays from links."
6430 (font-lock-default-unfontify-region beg end)
6431 (let* ((buffer-undo-list t)
6432 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6433 (inhibit-modification-hooks t)
6434 deactivate-mark buffer-file-name buffer-file-truename)
6435 (org-decompose-region beg end)
6436 (remove-text-properties beg end
6437 '(mouse-face t keymap t org-linked-text t
6438 invisible t intangible t
6439 org-no-flyspell t org-emphasis t))
6440 (org-remove-font-lock-display-properties beg end)))
6442 (defconst org-script-display '(((raise -0.3) (height 0.7))
6443 ((raise 0.3) (height 0.7))
6444 ((raise -0.5))
6445 ((raise 0.5)))
6446 "Display properties for showing superscripts and subscripts.")
6448 (defun org-remove-font-lock-display-properties (beg end)
6449 "Remove specific display properties that have been added by font lock.
6450 The will remove the raise properties that are used to show superscripts
6451 and subscripts."
6452 (let (next prop)
6453 (while (< beg end)
6454 (setq next (next-single-property-change beg 'display nil end)
6455 prop (get-text-property beg 'display))
6456 (if (member prop org-script-display)
6457 (put-text-property beg next 'display nil))
6458 (setq beg next))))
6460 (defun org-raise-scripts (limit)
6461 "Add raise properties to sub/superscripts."
6462 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6463 (if (re-search-forward
6464 (if (eq org-use-sub-superscripts t)
6465 org-match-substring-regexp
6466 org-match-substring-with-braces-regexp)
6467 limit t)
6468 (let* ((pos (point)) table-p comment-p
6469 (mpos (match-beginning 3))
6470 (emph-p (get-text-property mpos 'org-emphasis))
6471 (link-p (get-text-property mpos 'mouse-face))
6472 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6473 (goto-char (point-at-bol))
6474 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6475 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6476 (goto-char pos)
6477 ;; Handle a_b^c
6478 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6479 (if (or comment-p emph-p link-p keyw-p)
6481 (put-text-property (match-beginning 3) (match-end 0)
6482 'display
6483 (if (equal (char-after (match-beginning 2)) ?^)
6484 (nth (if table-p 3 1) org-script-display)
6485 (nth (if table-p 2 0) org-script-display)))
6486 (add-text-properties (match-beginning 2) (match-end 2)
6487 (list 'invisible t
6488 'org-dwidth t 'org-dwidth-n 1))
6489 (if (and (eq (char-after (match-beginning 3)) ?{)
6490 (eq (char-before (match-end 3)) ?}))
6491 (progn
6492 (add-text-properties
6493 (match-beginning 3) (1+ (match-beginning 3))
6494 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6495 (add-text-properties
6496 (1- (match-end 3)) (match-end 3)
6497 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6498 t)))))
6500 ;;;; Visibility cycling, including org-goto and indirect buffer
6502 ;;; Cycling
6504 (defvar org-cycle-global-status nil)
6505 (make-variable-buffer-local 'org-cycle-global-status)
6506 (put 'org-cycle-global-status 'org-state t)
6507 (defvar org-cycle-subtree-status nil)
6508 (make-variable-buffer-local 'org-cycle-subtree-status)
6509 (put 'org-cycle-subtree-status 'org-state t)
6511 (defvar org-inlinetask-min-level)
6513 (defun org-unlogged-message (&rest args)
6514 "Display a message, but avoid logging it in the *Messages* buffer."
6515 (let ((message-log-max nil))
6516 (apply 'message args)))
6518 ;;;###autoload
6519 (defun org-cycle (&optional arg)
6520 "TAB-action and visibility cycling for Org-mode.
6522 This is the command invoked in Org-mode by the TAB key. Its main purpose
6523 is outline visibility cycling, but it also invokes other actions
6524 in special contexts.
6526 - When this function is called with a prefix argument, rotate the entire
6527 buffer through 3 states (global cycling)
6528 1. OVERVIEW: Show only top-level headlines.
6529 2. CONTENTS: Show all headlines of all levels, but no body text.
6530 3. SHOW ALL: Show everything.
6531 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6532 determined by the variable `org-startup-folded', and by any VISIBILITY
6533 properties in the buffer.
6534 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6535 including any drawers.
6537 - When inside a table, re-align the table and move to the next field.
6539 - When point is at the beginning of a headline, rotate the subtree started
6540 by this line through 3 different states (local cycling)
6541 1. FOLDED: Only the main headline is shown.
6542 2. CHILDREN: The main headline and the direct children are shown.
6543 From this state, you can move to one of the children
6544 and zoom in further.
6545 3. SUBTREE: Show the entire subtree, including body text.
6546 If there is no subtree, switch directly from CHILDREN to FOLDED.
6548 - When point is at the beginning of an empty headline and the variable
6549 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6550 of the headline by demoting and promoting it to likely levels. This
6551 speeds up creation document structure by pressing TAB once or several
6552 times right after creating a new headline.
6554 - When there is a numeric prefix, go up to a heading with level ARG, do
6555 a `show-subtree' and return to the previous cursor position. If ARG
6556 is negative, go up that many levels.
6558 - When point is not at the beginning of a headline, execute the global
6559 binding for TAB, which is re-indenting the line. See the option
6560 `org-cycle-emulate-tab' for details.
6562 - Special case: if point is at the beginning of the buffer and there is
6563 no headline in line 1, this function will act as if called with prefix arg
6564 (C-u TAB, same as S-TAB) also when called without prefix arg.
6565 But only if also the variable `org-cycle-global-at-bob' is t."
6566 (interactive "P")
6567 (org-load-modules-maybe)
6568 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6569 (and org-cycle-level-after-item/entry-creation
6570 (or (org-cycle-level)
6571 (org-cycle-item-indentation))))
6572 (let* ((limit-level
6573 (or org-cycle-max-level
6574 (and (boundp 'org-inlinetask-min-level)
6575 org-inlinetask-min-level
6576 (1- org-inlinetask-min-level))))
6577 (nstars (and limit-level
6578 (if org-odd-levels-only
6579 (and limit-level (1- (* limit-level 2)))
6580 limit-level)))
6581 (org-outline-regexp
6582 (if (not (derived-mode-p 'org-mode))
6583 outline-regexp
6584 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6585 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6586 (not (looking-at org-outline-regexp))))
6587 (org-cycle-hook
6588 (if bob-special
6589 (delq 'org-optimize-window-after-visibility-change
6590 (copy-sequence org-cycle-hook))
6591 org-cycle-hook))
6592 (pos (point)))
6594 (if (or bob-special (equal arg '(4)))
6595 ;; special case: use global cycling
6596 (setq arg t))
6598 (cond
6600 ((equal arg '(16))
6601 (setq last-command 'dummy)
6602 (org-set-startup-visibility)
6603 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6605 ((equal arg '(64))
6606 (show-all)
6607 (org-unlogged-message "Entire buffer visible, including drawers"))
6609 ;; Table: enter it or move to the next field.
6610 ((org-at-table-p 'any)
6611 (if (org-at-table.el-p)
6612 (message "Use C-c ' to edit table.el tables")
6613 (if arg (org-table-edit-field t)
6614 (org-table-justify-field-maybe)
6615 (call-interactively 'org-table-next-field))))
6617 ((run-hook-with-args-until-success
6618 'org-tab-after-check-for-table-hook))
6620 ;; Global cycling: delegate to `org-cycle-internal-global'.
6621 ((eq arg t) (org-cycle-internal-global))
6623 ;; Drawers: delegate to `org-flag-drawer'.
6624 ((and org-drawers org-drawer-regexp
6625 (save-excursion
6626 (beginning-of-line 1)
6627 (looking-at org-drawer-regexp)))
6628 (org-flag-drawer ; toggle block visibility
6629 (not (get-char-property (match-end 0) 'invisible))))
6631 ;; Show-subtree, ARG levels up from here.
6632 ((integerp arg)
6633 (save-excursion
6634 (org-back-to-heading)
6635 (outline-up-heading (if (< arg 0) (- arg)
6636 (- (funcall outline-level) arg)))
6637 (org-show-subtree)))
6639 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6640 ((and (featurep 'org-inlinetask)
6641 (org-inlinetask-at-task-p)
6642 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6643 (org-inlinetask-toggle-visibility))
6645 ((org-try-cdlatex-tab))
6647 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6648 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6649 (save-excursion (beginning-of-line 1)
6650 (looking-at org-outline-regexp)))
6651 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6652 (org-cycle-internal-local))
6654 ;; From there: TAB emulation and template completion.
6655 (buffer-read-only (org-back-to-heading))
6657 ((run-hook-with-args-until-success
6658 'org-tab-after-check-for-cycling-hook))
6660 ((org-try-structure-completion))
6662 ((run-hook-with-args-until-success
6663 'org-tab-before-tab-emulation-hook))
6665 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6666 (or (not (bolp))
6667 (not (looking-at org-outline-regexp))))
6668 (call-interactively (global-key-binding "\t")))
6670 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6671 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6672 (or (and (eq org-cycle-emulate-tab 'white)
6673 (= (match-end 0) (point-at-eol)))
6674 (and (eq org-cycle-emulate-tab 'whitestart)
6675 (>= (match-end 0) pos))))
6677 (eq org-cycle-emulate-tab t))
6678 (call-interactively (global-key-binding "\t")))
6680 (t (save-excursion
6681 (org-back-to-heading)
6682 (org-cycle)))))))
6684 (defun org-cycle-internal-global ()
6685 "Do the global cycling action."
6686 ;; Hack to avoid display of messages for .org attachments in Gnus
6687 (let ((ga (string-match "\\*fontification" (buffer-name))))
6688 (cond
6689 ((and (eq last-command this-command)
6690 (eq org-cycle-global-status 'overview))
6691 ;; We just created the overview - now do table of contents
6692 ;; This can be slow in very large buffers, so indicate action
6693 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6694 (unless ga (org-unlogged-message "CONTENTS..."))
6695 (org-content)
6696 (unless ga (org-unlogged-message "CONTENTS...done"))
6697 (setq org-cycle-global-status 'contents)
6698 (run-hook-with-args 'org-cycle-hook 'contents))
6700 ((and (eq last-command this-command)
6701 (eq org-cycle-global-status 'contents))
6702 ;; We just showed the table of contents - now show everything
6703 (run-hook-with-args 'org-pre-cycle-hook 'all)
6704 (show-all)
6705 (unless ga (org-unlogged-message "SHOW ALL"))
6706 (setq org-cycle-global-status 'all)
6707 (run-hook-with-args 'org-cycle-hook 'all))
6710 ;; Default action: go to overview
6711 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6712 (org-overview)
6713 (unless ga (org-unlogged-message "OVERVIEW"))
6714 (setq org-cycle-global-status 'overview)
6715 (run-hook-with-args 'org-cycle-hook 'overview)))))
6717 (defun org-cycle-internal-local ()
6718 "Do the local cycling action."
6719 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6720 ;; First, determine end of headline (EOH), end of subtree or item
6721 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6722 (save-excursion
6723 (if (org-at-item-p)
6724 (progn
6725 (beginning-of-line)
6726 (setq struct (org-list-struct))
6727 (setq eoh (point-at-eol))
6728 (setq eos (org-list-get-item-end-before-blank (point) struct))
6729 (setq has-children (org-list-has-child-p (point) struct)))
6730 (org-back-to-heading)
6731 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6732 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6733 (setq has-children
6734 (or (save-excursion
6735 (let ((level (funcall outline-level)))
6736 (outline-next-heading)
6737 (and (org-at-heading-p t)
6738 (> (funcall outline-level) level))))
6739 (save-excursion
6740 (org-list-search-forward (org-item-beginning-re) eos t)))))
6741 ;; Determine end invisible part of buffer (EOL)
6742 (beginning-of-line 2)
6743 ;; XEmacs doesn't have `next-single-char-property-change'
6744 (if (featurep 'xemacs)
6745 (while (and (not (eobp)) ;; this is like `next-line'
6746 (get-char-property (1- (point)) 'invisible))
6747 (beginning-of-line 2))
6748 (while (and (not (eobp)) ;; this is like `next-line'
6749 (get-char-property (1- (point)) 'invisible))
6750 (goto-char (next-single-char-property-change (point) 'invisible))
6751 (and (eolp) (beginning-of-line 2))))
6752 (setq eol (point)))
6753 ;; Find out what to do next and set `this-command'
6754 (cond
6755 ((= eos eoh)
6756 ;; Nothing is hidden behind this heading
6757 (unless (org-before-first-heading-p)
6758 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6759 (org-unlogged-message "EMPTY ENTRY")
6760 (setq org-cycle-subtree-status nil)
6761 (save-excursion
6762 (goto-char eos)
6763 (outline-next-heading)
6764 (if (outline-invisible-p) (org-flag-heading nil))))
6765 ((and (or (>= eol eos)
6766 (not (string-match "\\S-" (buffer-substring eol eos))))
6767 (or has-children
6768 (not (setq children-skipped
6769 org-cycle-skip-children-state-if-no-children))))
6770 ;; Entire subtree is hidden in one line: children view
6771 (unless (org-before-first-heading-p)
6772 (run-hook-with-args 'org-pre-cycle-hook 'children))
6773 (if (org-at-item-p)
6774 (org-list-set-item-visibility (point-at-bol) struct 'children)
6775 (org-show-entry)
6776 (org-with-limited-levels (show-children))
6777 ;; FIXME: This slows down the func way too much.
6778 ;; How keep drawers hidden in subtree anyway?
6779 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6780 ;; (org-cycle-hide-drawers 'subtree))
6782 ;; Fold every list in subtree to top-level items.
6783 (when (eq org-cycle-include-plain-lists 'integrate)
6784 (save-excursion
6785 (org-back-to-heading)
6786 (while (org-list-search-forward (org-item-beginning-re) eos t)
6787 (beginning-of-line 1)
6788 (let* ((struct (org-list-struct))
6789 (prevs (org-list-prevs-alist struct))
6790 (end (org-list-get-bottom-point struct)))
6791 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6792 (org-list-get-all-items (point) struct prevs))
6793 (goto-char (if (< end eos) end eos)))))))
6794 (org-unlogged-message "CHILDREN")
6795 (save-excursion
6796 (goto-char eos)
6797 (outline-next-heading)
6798 (if (outline-invisible-p) (org-flag-heading nil)))
6799 (setq org-cycle-subtree-status 'children)
6800 (unless (org-before-first-heading-p)
6801 (run-hook-with-args 'org-cycle-hook 'children)))
6802 ((or children-skipped
6803 (and (eq last-command this-command)
6804 (eq org-cycle-subtree-status 'children)))
6805 ;; We just showed the children, or no children are there,
6806 ;; now show everything.
6807 (unless (org-before-first-heading-p)
6808 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6809 (outline-flag-region eoh eos nil)
6810 (org-unlogged-message
6811 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6812 (setq org-cycle-subtree-status 'subtree)
6813 (unless (org-before-first-heading-p)
6814 (run-hook-with-args 'org-cycle-hook 'subtree)))
6816 ;; Default action: hide the subtree.
6817 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6818 (outline-flag-region eoh eos t)
6819 (org-unlogged-message "FOLDED")
6820 (setq org-cycle-subtree-status 'folded)
6821 (unless (org-before-first-heading-p)
6822 (run-hook-with-args 'org-cycle-hook 'folded))))))
6824 ;;;###autoload
6825 (defun org-global-cycle (&optional arg)
6826 "Cycle the global visibility. For details see `org-cycle'.
6827 With \\[universal-argument] prefix arg, switch to startup visibility.
6828 With a numeric prefix, show all headlines up to that level."
6829 (interactive "P")
6830 (let ((org-cycle-include-plain-lists
6831 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6832 (cond
6833 ((integerp arg)
6834 (show-all)
6835 (hide-sublevels arg)
6836 (setq org-cycle-global-status 'contents))
6837 ((equal arg '(4))
6838 (org-set-startup-visibility)
6839 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6841 (org-cycle '(4))))))
6843 (defun org-set-startup-visibility ()
6844 "Set the visibility required by startup options and properties."
6845 (cond
6846 ((eq org-startup-folded t)
6847 (org-cycle '(4)))
6848 ((eq org-startup-folded 'content)
6849 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6850 (org-cycle '(4)) (org-cycle '(4)))))
6851 (unless (eq org-startup-folded 'showeverything)
6852 (if org-hide-block-startup (org-hide-block-all))
6853 (org-set-visibility-according-to-property 'no-cleanup)
6854 (org-cycle-hide-archived-subtrees 'all)
6855 (org-cycle-hide-drawers 'all)
6856 (org-cycle-show-empty-lines t)))
6858 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6859 "Switch subtree visibilities according to :VISIBILITY: property."
6860 (interactive)
6861 (let (org-show-entry-below state)
6862 (save-excursion
6863 (goto-char (point-min))
6864 (while (re-search-forward
6865 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6866 nil t)
6867 (setq state (match-string 1))
6868 (save-excursion
6869 (org-back-to-heading t)
6870 (hide-subtree)
6871 (org-reveal)
6872 (cond
6873 ((equal state '("fold" "folded"))
6874 (hide-subtree))
6875 ((equal state "children")
6876 (org-show-hidden-entry)
6877 (show-children))
6878 ((equal state "content")
6879 (save-excursion
6880 (save-restriction
6881 (org-narrow-to-subtree)
6882 (org-content))))
6883 ((member state '("all" "showall"))
6884 (show-subtree)))))
6885 (unless no-cleanup
6886 (org-cycle-hide-archived-subtrees 'all)
6887 (org-cycle-hide-drawers 'all)
6888 (org-cycle-show-empty-lines 'all)))))
6890 ;; This function uses outline-regexp instead of the more fundamental
6891 ;; org-outline-regexp so that org-cycle-global works outside of Org
6892 ;; buffers, where outline-regexp is needed.
6893 (defun org-overview ()
6894 "Switch to overview mode, showing only top-level headlines.
6895 Really, this shows all headlines with level equal or greater than the level
6896 of the first headline in the buffer. This is important, because if the
6897 first headline is not level one, then (hide-sublevels 1) gives confusing
6898 results."
6899 (interactive)
6900 (let ((pos (point))
6901 (level (save-excursion
6902 (goto-char (point-min))
6903 (if (re-search-forward (concat "^" outline-regexp) nil t)
6904 (progn
6905 (goto-char (match-beginning 0))
6906 (funcall outline-level))))))
6907 (and level (hide-sublevels level))
6908 (recenter '(4))
6909 (goto-char pos)))
6911 (defun org-content (&optional arg)
6912 "Show all headlines in the buffer, like a table of contents.
6913 With numerical argument N, show content up to level N."
6914 (interactive "P")
6915 (save-excursion
6916 ;; Visit all headings and show their offspring
6917 (and (integerp arg) (org-overview))
6918 (goto-char (point-max))
6919 (catch 'exit
6920 (while (and (progn (condition-case nil
6921 (outline-previous-visible-heading 1)
6922 (error (goto-char (point-min))))
6924 (looking-at org-outline-regexp))
6925 (if (integerp arg)
6926 (show-children (1- arg))
6927 (show-branches))
6928 (if (bobp) (throw 'exit nil))))))
6931 (defun org-optimize-window-after-visibility-change (state)
6932 "Adjust the window after a change in outline visibility.
6933 This function is the default value of the hook `org-cycle-hook'."
6934 (when (get-buffer-window (current-buffer))
6935 (cond
6936 ((eq state 'content) nil)
6937 ((eq state 'all) nil)
6938 ((eq state 'folded) nil)
6939 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6940 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6942 (defun org-remove-empty-overlays-at (pos)
6943 "Remove outline overlays that do not contain non-white stuff."
6944 (mapc
6945 (lambda (o)
6946 (and (eq 'outline (overlay-get o 'invisible))
6947 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6948 (overlay-end o))))
6949 (delete-overlay o)))
6950 (overlays-at pos)))
6952 (defun org-clean-visibility-after-subtree-move ()
6953 "Fix visibility issues after moving a subtree."
6954 ;; First, find a reasonable region to look at:
6955 ;; Start two siblings above, end three below
6956 (let* ((beg (save-excursion
6957 (and (org-get-last-sibling)
6958 (org-get-last-sibling))
6959 (point)))
6960 (end (save-excursion
6961 (and (org-get-next-sibling)
6962 (org-get-next-sibling)
6963 (org-get-next-sibling))
6964 (if (org-at-heading-p)
6965 (point-at-eol)
6966 (point))))
6967 (level (looking-at "\\*+"))
6968 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6969 (save-excursion
6970 (save-restriction
6971 (narrow-to-region beg end)
6972 (when re
6973 ;; Properly fold already folded siblings
6974 (goto-char (point-min))
6975 (while (re-search-forward re nil t)
6976 (if (and (not (outline-invisible-p))
6977 (save-excursion
6978 (goto-char (point-at-eol)) (outline-invisible-p)))
6979 (hide-entry))))
6980 (org-cycle-show-empty-lines 'overview)
6981 (org-cycle-hide-drawers 'overview)))))
6983 (defun org-cycle-show-empty-lines (state)
6984 "Show empty lines above all visible headlines.
6985 The region to be covered depends on STATE when called through
6986 `org-cycle-hook'. Lisp program can use t for STATE to get the
6987 entire buffer covered. Note that an empty line is only shown if there
6988 are at least `org-cycle-separator-lines' empty lines before the headline."
6989 (when (not (= org-cycle-separator-lines 0))
6990 (save-excursion
6991 (let* ((n (abs org-cycle-separator-lines))
6992 (re (cond
6993 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6994 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6995 (t (let ((ns (number-to-string (- n 2))))
6996 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6997 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6998 beg end b e)
6999 (cond
7000 ((memq state '(overview contents t))
7001 (setq beg (point-min) end (point-max)))
7002 ((memq state '(children folded))
7003 (setq beg (point) end (progn (org-end-of-subtree t t)
7004 (beginning-of-line 2)
7005 (point)))))
7006 (when beg
7007 (goto-char beg)
7008 (while (re-search-forward re end t)
7009 (unless (get-char-property (match-end 1) 'invisible)
7010 (setq e (match-end 1))
7011 (if (< org-cycle-separator-lines 0)
7012 (setq b (save-excursion
7013 (goto-char (match-beginning 0))
7014 (org-back-over-empty-lines)
7015 (if (save-excursion
7016 (goto-char (max (point-min) (1- (point))))
7017 (org-at-heading-p))
7018 (1- (point))
7019 (point))))
7020 (setq b (match-beginning 1)))
7021 (outline-flag-region b e nil)))))))
7022 ;; Never hide empty lines at the end of the file.
7023 (save-excursion
7024 (goto-char (point-max))
7025 (outline-previous-heading)
7026 (outline-end-of-heading)
7027 (if (and (looking-at "[ \t\n]+")
7028 (= (match-end 0) (point-max)))
7029 (outline-flag-region (point) (match-end 0) nil))))
7031 (defun org-show-empty-lines-in-parent ()
7032 "Move to the parent and re-show empty lines before visible headlines."
7033 (save-excursion
7034 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7035 (org-cycle-show-empty-lines context))))
7037 (defun org-files-list ()
7038 "Return `org-agenda-files' list, plus all open org-mode files.
7039 This is useful for operations that need to scan all of a user's
7040 open and agenda-wise Org files."
7041 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7042 (dolist (buf (buffer-list))
7043 (with-current-buffer buf
7044 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7045 (let ((file (expand-file-name (buffer-file-name))))
7046 (unless (member file files)
7047 (push file files))))))
7048 files))
7050 (defsubst org-entry-beginning-position ()
7051 "Return the beginning position of the current entry."
7052 (save-excursion (outline-back-to-heading t) (point)))
7054 (defsubst org-entry-end-position ()
7055 "Return the end position of the current entry."
7056 (save-excursion (outline-next-heading) (point)))
7058 (defun org-cycle-hide-drawers (state)
7059 "Re-hide all drawers after a visibility state change."
7060 (when (and (derived-mode-p 'org-mode)
7061 (not (memq state '(overview folded contents))))
7062 (save-excursion
7063 (let* ((globalp (memq state '(contents all)))
7064 (beg (if globalp (point-min) (point)))
7065 (end (if globalp (point-max)
7066 (if (eq state 'children)
7067 (save-excursion (outline-next-heading) (point))
7068 (org-end-of-subtree t)))))
7069 (goto-char beg)
7070 (while (re-search-forward org-drawer-regexp end t)
7071 (org-flag-drawer t))))))
7073 (defun org-cycle-hide-inline-tasks (state)
7074 "Re-hide inline tasks when switching to 'contents or 'children
7075 visibility state."
7076 (case state
7077 (contents
7078 (when (org-bound-and-true-p org-inlinetask-min-level)
7079 (hide-sublevels (1- org-inlinetask-min-level))))
7080 (children
7081 (when (featurep 'org-inlinetask)
7082 (save-excursion
7083 (while (and (outline-next-heading)
7084 (org-inlinetask-at-task-p))
7085 (org-inlinetask-toggle-visibility)
7086 (org-inlinetask-goto-end)))))))
7088 (defun org-flag-drawer (flag)
7089 "When FLAG is non-nil, hide the drawer we are within.
7090 Otherwise make it visible."
7091 (save-excursion
7092 (beginning-of-line 1)
7093 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7094 (let ((b (match-end 0)))
7095 (if (re-search-forward
7096 "^[ \t]*:END:"
7097 (save-excursion (outline-next-heading) (point)) t)
7098 (outline-flag-region b (point-at-eol) flag)
7099 (user-error ":END: line missing at position %s" b))))))
7101 (defun org-subtree-end-visible-p ()
7102 "Is the end of the current subtree visible?"
7103 (pos-visible-in-window-p
7104 (save-excursion (org-end-of-subtree t) (point))))
7106 (defun org-first-headline-recenter (&optional N)
7107 "Move cursor to the first headline and recenter the headline.
7108 Optional argument N means put the headline into the Nth line of the window."
7109 (goto-char (point-min))
7110 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7111 (beginning-of-line)
7112 (recenter (prefix-numeric-value N))))
7114 ;;; Saving and restoring visibility
7116 (defun org-outline-overlay-data (&optional use-markers)
7117 "Return a list of the locations of all outline overlays.
7118 These are overlays with the `invisible' property value `outline'.
7119 The return value is a list of cons cells, with start and stop
7120 positions for each overlay.
7121 If USE-MARKERS is set, return the positions as markers."
7122 (let (beg end)
7123 (save-excursion
7124 (save-restriction
7125 (widen)
7126 (delq nil
7127 (mapcar (lambda (o)
7128 (when (eq (overlay-get o 'invisible) 'outline)
7129 (setq beg (overlay-start o)
7130 end (overlay-end o))
7131 (and beg end (> end beg)
7132 (if use-markers
7133 (cons (move-marker (make-marker) beg)
7134 (move-marker (make-marker) end))
7135 (cons beg end)))))
7136 (overlays-in (point-min) (point-max))))))))
7138 (defun org-set-outline-overlay-data (data)
7139 "Create visibility overlays for all positions in DATA.
7140 DATA should have been made by `org-outline-overlay-data'."
7141 (let (o)
7142 (save-excursion
7143 (save-restriction
7144 (widen)
7145 (show-all)
7146 (mapc (lambda (c)
7147 (outline-flag-region (car c) (cdr c) t))
7148 data)))))
7150 ;;; Folding of blocks
7152 (defvar org-hide-block-overlays nil
7153 "Overlays hiding blocks.")
7154 (make-variable-buffer-local 'org-hide-block-overlays)
7156 (defun org-block-map (function &optional start end)
7157 "Call FUNCTION at the head of all source blocks in the current buffer.
7158 Optional arguments START and END can be used to limit the range."
7159 (let ((start (or start (point-min)))
7160 (end (or end (point-max))))
7161 (save-excursion
7162 (goto-char start)
7163 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7164 (save-excursion
7165 (save-match-data
7166 (goto-char (match-beginning 0))
7167 (funcall function)))))))
7169 (defun org-hide-block-toggle-all ()
7170 "Toggle the visibility of all blocks in the current buffer."
7171 (org-block-map #'org-hide-block-toggle))
7173 (defun org-hide-block-all ()
7174 "Fold all blocks in the current buffer."
7175 (interactive)
7176 (org-show-block-all)
7177 (org-block-map #'org-hide-block-toggle-maybe))
7179 (defun org-show-block-all ()
7180 "Unfold all blocks in the current buffer."
7181 (interactive)
7182 (mapc 'delete-overlay org-hide-block-overlays)
7183 (setq org-hide-block-overlays nil))
7185 (defun org-hide-block-toggle-maybe ()
7186 "Toggle visibility of block at point."
7187 (interactive)
7188 (let ((case-fold-search t))
7189 (if (save-excursion
7190 (beginning-of-line 1)
7191 (looking-at org-block-regexp))
7192 (progn (org-hide-block-toggle)
7193 t) ;; to signal that we took action
7194 nil))) ;; to signal that we did not
7196 (defun org-hide-block-toggle (&optional force)
7197 "Toggle the visibility of the current block."
7198 (interactive)
7199 (save-excursion
7200 (beginning-of-line)
7201 (if (re-search-forward org-block-regexp nil t)
7202 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7203 (end (match-end 0)) ;; end of entire body
7205 (if (memq t (mapcar (lambda (overlay)
7206 (eq (overlay-get overlay 'invisible)
7207 'org-hide-block))
7208 (overlays-at start)))
7209 (if (or (not force) (eq force 'off))
7210 (mapc (lambda (ov)
7211 (when (member ov org-hide-block-overlays)
7212 (setq org-hide-block-overlays
7213 (delq ov org-hide-block-overlays)))
7214 (when (eq (overlay-get ov 'invisible)
7215 'org-hide-block)
7216 (delete-overlay ov)))
7217 (overlays-at start)))
7218 (setq ov (make-overlay start end))
7219 (overlay-put ov 'invisible 'org-hide-block)
7220 ;; make the block accessible to isearch
7221 (overlay-put
7222 ov 'isearch-open-invisible
7223 (lambda (ov)
7224 (when (member ov org-hide-block-overlays)
7225 (setq org-hide-block-overlays
7226 (delq ov org-hide-block-overlays)))
7227 (when (eq (overlay-get ov 'invisible)
7228 'org-hide-block)
7229 (delete-overlay ov))))
7230 (push ov org-hide-block-overlays)))
7231 (user-error "Not looking at a source block"))))
7233 ;; org-tab-after-check-for-cycling-hook
7234 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7235 ;; Remove overlays when changing major mode
7236 (add-hook 'org-mode-hook
7237 (lambda () (org-add-hook 'change-major-mode-hook
7238 'org-show-block-all 'append 'local)))
7240 ;;; Org-goto
7242 (defvar org-goto-window-configuration nil)
7243 (defvar org-goto-marker nil)
7244 (defvar org-goto-map)
7245 (defun org-goto-map ()
7246 "Set the keymap `org-goto'."
7247 (setq org-goto-map
7248 (let ((map (make-sparse-keymap)))
7249 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7250 mouse-drag-region universal-argument org-occur))
7251 cmd)
7252 (while (setq cmd (pop cmds))
7253 (substitute-key-definition cmd cmd map global-map)))
7254 (suppress-keymap map)
7255 (org-defkey map "\C-m" 'org-goto-ret)
7256 (org-defkey map [(return)] 'org-goto-ret)
7257 (org-defkey map [(left)] 'org-goto-left)
7258 (org-defkey map [(right)] 'org-goto-right)
7259 (org-defkey map [(control ?g)] 'org-goto-quit)
7260 (org-defkey map "\C-i" 'org-cycle)
7261 (org-defkey map [(tab)] 'org-cycle)
7262 (org-defkey map [(down)] 'outline-next-visible-heading)
7263 (org-defkey map [(up)] 'outline-previous-visible-heading)
7264 (if org-goto-auto-isearch
7265 (if (fboundp 'define-key-after)
7266 (define-key-after map [t] 'org-goto-local-auto-isearch)
7267 nil)
7268 (org-defkey map "q" 'org-goto-quit)
7269 (org-defkey map "n" 'outline-next-visible-heading)
7270 (org-defkey map "p" 'outline-previous-visible-heading)
7271 (org-defkey map "f" 'outline-forward-same-level)
7272 (org-defkey map "b" 'outline-backward-same-level)
7273 (org-defkey map "u" 'outline-up-heading))
7274 (org-defkey map "/" 'org-occur)
7275 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7276 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7277 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7278 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7279 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7280 map)))
7282 (defconst org-goto-help
7283 "Browse buffer copy, to find location or copy text.%s
7284 RET=jump to location C-g=quit and return to previous location
7285 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7287 (defvar org-goto-start-pos) ; dynamically scoped parameter
7289 (defun org-goto (&optional alternative-interface)
7290 "Look up a different location in the current file, keeping current visibility.
7292 When you want look-up or go to a different location in a
7293 document, the fastest way is often to fold the entire buffer and
7294 then dive into the tree. This method has the disadvantage, that
7295 the previous location will be folded, which may not be what you
7296 want.
7298 This command works around this by showing a copy of the current
7299 buffer in an indirect buffer, in overview mode. You can dive
7300 into the tree in that copy, use org-occur and incremental search
7301 to find a location. When pressing RET or `Q', the command
7302 returns to the original buffer in which the visibility is still
7303 unchanged. After RET it will also jump to the location selected
7304 in the indirect buffer and expose the headline hierarchy above.
7306 With a prefix argument, use the alternative interface: e.g. if
7307 `org-goto-interface' is 'outline use 'outline-path-completion."
7308 (interactive "P")
7309 (org-goto-map)
7310 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7311 (org-refile-use-outline-path t)
7312 (org-refile-target-verify-function nil)
7313 (interface
7314 (if (not alternative-interface)
7315 org-goto-interface
7316 (if (eq org-goto-interface 'outline)
7317 'outline-path-completion
7318 'outline)))
7319 (org-goto-start-pos (point))
7320 (selected-point
7321 (if (eq interface 'outline)
7322 (car (org-get-location (current-buffer) org-goto-help))
7323 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7324 (org-refile-check-position pa)
7325 (nth 3 pa)))))
7326 (if selected-point
7327 (progn
7328 (org-mark-ring-push org-goto-start-pos)
7329 (goto-char selected-point)
7330 (if (or (outline-invisible-p) (org-invisible-p2))
7331 (org-show-context 'org-goto)))
7332 (message "Quit"))))
7334 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7335 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7336 (defvar org-goto-local-auto-isearch-map) ; defined below
7338 (defun org-get-location (buf help)
7339 "Let the user select a location in the Org-mode buffer BUF.
7340 This function uses a recursive edit. It returns the selected position
7341 or nil."
7342 (org-no-popups
7343 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7344 (isearch-hide-immediately nil)
7345 (isearch-search-fun-function
7346 (lambda () 'org-goto-local-search-headings))
7347 (org-goto-selected-point org-goto-exit-command))
7348 (save-excursion
7349 (save-window-excursion
7350 (delete-other-windows)
7351 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7352 (org-pop-to-buffer-same-window
7353 (condition-case nil
7354 (make-indirect-buffer (current-buffer) "*org-goto*")
7355 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7356 (with-output-to-temp-buffer "*Org Help*"
7357 (princ (format help (if org-goto-auto-isearch
7358 " Just type for auto-isearch."
7359 " n/p/f/b/u to navigate, q to quit."))))
7360 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7361 (setq buffer-read-only nil)
7362 (let ((org-startup-truncated t)
7363 (org-startup-folded nil)
7364 (org-startup-align-all-tables nil))
7365 (org-mode)
7366 (org-overview))
7367 (setq buffer-read-only t)
7368 (if (and (boundp 'org-goto-start-pos)
7369 (integer-or-marker-p org-goto-start-pos))
7370 (let ((org-show-hierarchy-above t)
7371 (org-show-siblings t)
7372 (org-show-following-heading t))
7373 (goto-char org-goto-start-pos)
7374 (and (outline-invisible-p) (org-show-context)))
7375 (goto-char (point-min)))
7376 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7377 (message "Select location and press RET")
7378 (use-local-map org-goto-map)
7379 (recursive-edit)))
7380 (kill-buffer "*org-goto*")
7381 (cons org-goto-selected-point org-goto-exit-command))))
7383 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7384 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7385 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7386 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7388 (defun org-goto-local-search-headings (string bound noerror)
7389 "Search and make sure that any matches are in headlines."
7390 (catch 'return
7391 (while (if isearch-forward
7392 (search-forward string bound noerror)
7393 (search-backward string bound noerror))
7394 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7395 (and (member :headline context)
7396 (not (member :tags context))))
7397 (throw 'return (point))))))
7399 (defun org-goto-local-auto-isearch ()
7400 "Start isearch."
7401 (interactive)
7402 (goto-char (point-min))
7403 (let ((keys (this-command-keys)))
7404 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7405 (isearch-mode t)
7406 (isearch-process-search-char (string-to-char keys)))))
7408 (defun org-goto-ret (&optional arg)
7409 "Finish `org-goto' by going to the new location."
7410 (interactive "P")
7411 (setq org-goto-selected-point (point)
7412 org-goto-exit-command 'return)
7413 (throw 'exit nil))
7415 (defun org-goto-left ()
7416 "Finish `org-goto' by going to the new location."
7417 (interactive)
7418 (if (org-at-heading-p)
7419 (progn
7420 (beginning-of-line 1)
7421 (setq org-goto-selected-point (point)
7422 org-goto-exit-command 'left)
7423 (throw 'exit nil))
7424 (user-error "Not on a heading")))
7426 (defun org-goto-right ()
7427 "Finish `org-goto' by going to the new location."
7428 (interactive)
7429 (if (org-at-heading-p)
7430 (progn
7431 (setq org-goto-selected-point (point)
7432 org-goto-exit-command 'right)
7433 (throw 'exit nil))
7434 (user-error "Not on a heading")))
7436 (defun org-goto-quit ()
7437 "Finish `org-goto' without cursor motion."
7438 (interactive)
7439 (setq org-goto-selected-point nil)
7440 (setq org-goto-exit-command 'quit)
7441 (throw 'exit nil))
7443 ;;; Indirect buffer display of subtrees
7445 (defvar org-indirect-dedicated-frame nil
7446 "This is the frame being used for indirect tree display.")
7447 (defvar org-last-indirect-buffer nil)
7449 (defun org-tree-to-indirect-buffer (&optional arg)
7450 "Create indirect buffer and narrow it to current subtree.
7451 With a numerical prefix ARG, go up to this level and then take that tree.
7452 If ARG is negative, go up that many levels.
7454 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7455 indirect buffer previously made with this command, to avoid proliferation of
7456 indirect buffers. However, when you call the command with a \
7457 \\[universal-argument] prefix, or
7458 when `org-indirect-buffer-display' is `new-frame', the last buffer
7459 is kept so that you can work with several indirect buffers at the same time.
7460 If `org-indirect-buffer-display' is `dedicated-frame', the \
7461 \\[universal-argument] prefix also
7462 requests that a new frame be made for the new buffer, so that the dedicated
7463 frame is not changed."
7464 (interactive "P")
7465 (let ((cbuf (current-buffer))
7466 (cwin (selected-window))
7467 (pos (point))
7468 beg end level heading ibuf)
7469 (save-excursion
7470 (org-back-to-heading t)
7471 (when (numberp arg)
7472 (setq level (org-outline-level))
7473 (if (< arg 0) (setq arg (+ level arg)))
7474 (while (> (setq level (org-outline-level)) arg)
7475 (org-up-heading-safe)))
7476 (setq beg (point)
7477 heading (org-get-heading))
7478 (org-end-of-subtree t t)
7479 (if (org-at-heading-p) (backward-char 1))
7480 (setq end (point)))
7481 (if (and (buffer-live-p org-last-indirect-buffer)
7482 (not (eq org-indirect-buffer-display 'new-frame))
7483 (not arg))
7484 (kill-buffer org-last-indirect-buffer))
7485 (setq ibuf (org-get-indirect-buffer cbuf)
7486 org-last-indirect-buffer ibuf)
7487 (cond
7488 ((or (eq org-indirect-buffer-display 'new-frame)
7489 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7490 (select-frame (make-frame))
7491 (delete-other-windows)
7492 (org-pop-to-buffer-same-window ibuf)
7493 (org-set-frame-title heading))
7494 ((eq org-indirect-buffer-display 'dedicated-frame)
7495 (raise-frame
7496 (select-frame (or (and org-indirect-dedicated-frame
7497 (frame-live-p org-indirect-dedicated-frame)
7498 org-indirect-dedicated-frame)
7499 (setq org-indirect-dedicated-frame (make-frame)))))
7500 (delete-other-windows)
7501 (org-pop-to-buffer-same-window ibuf)
7502 (org-set-frame-title (concat "Indirect: " heading)))
7503 ((eq org-indirect-buffer-display 'current-window)
7504 (org-pop-to-buffer-same-window ibuf))
7505 ((eq org-indirect-buffer-display 'other-window)
7506 (pop-to-buffer ibuf))
7507 (t (error "Invalid value")))
7508 (if (featurep 'xemacs)
7509 (save-excursion (org-mode) (turn-on-font-lock)))
7510 (narrow-to-region beg end)
7511 (show-all)
7512 (goto-char pos)
7513 (run-hook-with-args 'org-cycle-hook 'all)
7514 (and (window-live-p cwin) (select-window cwin))))
7516 (defun org-get-indirect-buffer (&optional buffer)
7517 (setq buffer (or buffer (current-buffer)))
7518 (let ((n 1) (base (buffer-name buffer)) bname)
7519 (while (buffer-live-p
7520 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7521 (setq n (1+ n)))
7522 (condition-case nil
7523 (make-indirect-buffer buffer bname 'clone)
7524 (error (make-indirect-buffer buffer bname)))))
7526 (defun org-set-frame-title (title)
7527 "Set the title of the current frame to the string TITLE."
7528 ;; FIXME: how to name a single frame in XEmacs???
7529 (unless (featurep 'xemacs)
7530 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7532 ;;;; Structure editing
7534 ;;; Inserting headlines
7536 (defun org-previous-line-empty-p (&optional next)
7537 "Is the previous line a blank line?
7538 When NEXT is non-nil, check the next line instead."
7539 (save-excursion
7540 (and (not (bobp))
7541 (or (beginning-of-line (if next 2 0)) t)
7542 (save-match-data
7543 (looking-at "[ \t]*$")))))
7545 (defun org-insert-heading (&optional arg invisible-ok)
7546 "Insert a new heading or item with same depth at point.
7547 If point is in a plain list and ARG is nil, create a new list item.
7548 With one universal prefix argument, insert a heading even in lists.
7549 With two universal prefix arguments, insert the heading at the end
7550 of the parent subtree.
7552 If point is at the beginning of a headline, insert a sibling before
7553 the current headline. If point is not at the beginning, split the line
7554 and create a new headline with the text in the current line after point
7555 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7557 If point is at the beginning of a normal line, turn this line into
7558 a heading.
7560 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7561 This is important for non-interactive uses of the command."
7562 (interactive "P")
7563 (if (org-called-interactively-p 'any) (org-reveal))
7564 (let ((itemp (org-in-item-p))
7565 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7566 (respect-content (or org-insert-heading-respect-content
7567 (equal arg '(16))))
7568 (initial-content "")
7569 (adjust-empty-lines t))
7571 (cond
7573 ((or (= (buffer-size) 0)
7574 (and (not (save-excursion
7575 (and (ignore-errors (org-back-to-heading invisible-ok))
7576 (org-at-heading-p))))
7577 (or arg (not itemp))))
7578 ;; At beginning of buffer or so high up that only a heading
7579 ;; makes sense.
7580 (insert
7581 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7582 (if (org-in-src-block-p) ",* " "* "))
7583 (run-hooks 'org-insert-heading-hook))
7585 ((and itemp (not (equal arg '(4))))
7586 ;; Insert an item
7587 (org-insert-item))
7590 ;; Insert a heading
7591 (save-restriction
7592 (widen)
7593 (let* ((level nil)
7594 (on-heading (org-at-heading-p))
7595 (empty-line-p (if on-heading
7596 (org-previous-line-empty-p)
7597 ;; We will decide later
7598 nil))
7599 ;; Get a level string to fall back on
7600 (fix-level
7601 (save-excursion
7602 (org-back-to-heading t)
7603 (if (org-previous-line-empty-p) (setq empty-line-p t))
7604 (looking-at org-outline-regexp)
7605 (make-string (1- (length (match-string 0))) ?*)))
7606 (stars
7607 (save-excursion
7608 (condition-case nil
7609 (progn
7610 (org-back-to-heading invisible-ok)
7611 (when (and (not on-heading)
7612 (featurep 'org-inlinetask)
7613 (integerp org-inlinetask-min-level)
7614 (>= (length (match-string 0))
7615 org-inlinetask-min-level))
7616 ;; Find a heading level before the inline task
7617 (while (and (setq level (org-up-heading-safe))
7618 (>= level org-inlinetask-min-level)))
7619 (if (org-at-heading-p)
7620 (org-back-to-heading invisible-ok)
7621 (error "This should not happen")))
7622 (unless (and (save-excursion
7623 (save-match-data
7624 (org-backward-heading-same-level
7625 1 invisible-ok))
7626 (= (point) (match-beginning 0)))
7627 (not (org-previous-line-empty-p t)))
7628 (setq empty-line-p (or empty-line-p
7629 (org-previous-line-empty-p))))
7630 (match-string 0))
7631 (error (or fix-level "* ")))))
7632 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7633 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7634 pos hide-previous previous-pos)
7636 ;; If we insert after content, move there and clean up whitespace
7637 (when respect-content
7638 (org-end-of-subtree nil t)
7639 (skip-chars-backward " \r\n")
7640 (and (looking-at "[ \t]+") (replace-match ""))
7641 (unless (eobp) (forward-char 1))
7642 (when (looking-at "^\\*")
7643 (unless (bobp) (backward-char 1))
7644 (insert "\n")))
7646 ;; If we are splitting, grab the text that should be moved to the new headline
7647 (when may-split
7648 (if (org-on-heading-p)
7649 ;; This is a heading, we split intelligently (keeping tags)
7650 (let ((pos (point)))
7651 (goto-char (point-at-bol))
7652 (unless (looking-at org-complex-heading-regexp)
7653 (error "This should not happen"))
7654 (when (and (match-beginning 4)
7655 (> pos (match-beginning 4))
7656 (< pos (match-end 4)))
7657 (setq initial-content (buffer-substring pos (match-end 4)))
7658 (goto-char pos)
7659 (delete-region (point) (match-end 4))
7660 (if (looking-at "[ \t]*$")
7661 (replace-match "")
7662 (insert (make-string (length initial-content) ?\ )))
7663 (setq initial-content (org-trim initial-content)))
7664 (goto-char pos))
7665 ;; a normal line
7666 (unless (bolp)
7667 (setq initial-content (buffer-substring (point) (point-at-eol)))
7668 (delete-region (point) (point-at-eol))
7669 (setq initial-content (org-trim initial-content)))))
7671 ;; If we are at the beginning of the line, insert before it. Else after
7672 (cond
7673 ((and (bolp) (looking-at "[ \t]*$")))
7674 ((and (bolp) (not (looking-at "[ \t]*$")))
7675 (open-line 1))
7677 (goto-char (point-at-eol))
7678 (insert "\n")))
7680 ;; Insert the new heading
7681 (insert stars)
7682 (just-one-space)
7683 (insert initial-content)
7684 (when adjust-empty-lines
7685 (if (or (not blank)
7686 (and blank (not (org-previous-line-empty-p))))
7687 (org-N-empty-lines-before-current (if blank 1 0))))
7688 (run-hooks 'org-insert-heading-hook)))))))
7690 (defun org-N-empty-lines-before-current (N)
7691 "Make the number of empty lines before current exactly N.
7692 So this will delete or add empty lines."
7693 (save-excursion
7694 (goto-char (point-at-bol))
7695 (if (looking-back "\\s-+" nil 'greedy)
7696 (replace-match ""))
7697 (or (bobp) (insert "\n"))
7698 (while (> N 0)
7699 (insert "\n")
7700 (setq N (1- N)))))
7702 (defun org-get-heading (&optional no-tags no-todo)
7703 "Return the heading of the current entry, without the stars.
7704 When NO-TAGS is non-nil, don't include tags.
7705 When NO-TODO is non-nil, don't include TODO keywords."
7706 (save-excursion
7707 (org-back-to-heading t)
7708 (cond
7709 ((and no-tags no-todo)
7710 (looking-at org-complex-heading-regexp)
7711 (match-string 4))
7712 (no-tags
7713 (looking-at (concat org-outline-regexp
7714 "\\(.*?\\)"
7715 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7716 (match-string 1))
7717 (no-todo
7718 (looking-at org-todo-line-regexp)
7719 (match-string 3))
7720 (t (looking-at org-heading-regexp)
7721 (match-string 2)))))
7723 (defvar orgstruct-mode) ; defined below
7725 (defun org-heading-components ()
7726 "Return the components of the current heading.
7727 This is a list with the following elements:
7728 - the level as an integer
7729 - the reduced level, different if `org-odd-levels-only' is set.
7730 - the TODO keyword, or nil
7731 - the priority character, like ?A, or nil if no priority is given
7732 - the headline text itself, or the tags string if no headline text
7733 - the tags string, or nil."
7734 (save-excursion
7735 (org-back-to-heading t)
7736 (if (let (case-fold-search)
7737 (looking-at
7738 (if orgstruct-mode
7739 org-heading-regexp
7740 org-complex-heading-regexp)))
7741 (if orgstruct-mode
7742 (list (length (match-string 1))
7743 (org-reduced-level (length (match-string 1)))
7746 (match-string 2)
7747 nil)
7748 (list (length (match-string 1))
7749 (org-reduced-level (length (match-string 1)))
7750 (org-match-string-no-properties 2)
7751 (and (match-end 3) (aref (match-string 3) 2))
7752 (org-match-string-no-properties 4)
7753 (org-match-string-no-properties 5))))))
7755 (defun org-get-entry ()
7756 "Get the entry text, after heading, entire subtree."
7757 (save-excursion
7758 (org-back-to-heading t)
7759 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7761 (defun org-insert-heading-after-current ()
7762 "Insert a new heading with same level as current, after current subtree."
7763 (interactive)
7764 (org-back-to-heading)
7765 (org-insert-heading)
7766 (org-move-subtree-down)
7767 (end-of-line 1))
7769 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7770 "Insert heading with `org-insert-heading-respect-content' set to t."
7771 (interactive "P")
7772 (let ((org-insert-heading-respect-content t))
7773 (org-insert-heading '(4) invisible-ok)))
7775 (defun org-insert-todo-heading-respect-content (&optional force-state)
7776 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7777 (interactive "P")
7778 (let ((org-insert-heading-respect-content t))
7779 (org-insert-todo-heading force-state '(4))))
7781 (defun org-insert-todo-heading (arg &optional force-heading)
7782 "Insert a new heading with the same level and TODO state as current heading.
7783 If the heading has no TODO state, or if the state is DONE, use the first
7784 state (TODO by default). Also one prefix arg, force first state. With two
7785 prefix args, force inserting at the end of the parent subtree."
7786 (interactive "P")
7787 (when (or force-heading (not (org-insert-item 'checkbox)))
7788 (org-insert-heading (or (and (equal arg '(16)) '(16))
7789 force-heading))
7790 (save-excursion
7791 (org-back-to-heading)
7792 (outline-previous-heading)
7793 (looking-at org-todo-line-regexp))
7794 (let*
7795 ((new-mark-x
7796 (if (or arg
7797 (not (match-beginning 2))
7798 (member (match-string 2) org-done-keywords))
7799 (car org-todo-keywords-1)
7800 (match-string 2)))
7801 (new-mark
7803 (run-hook-with-args-until-success
7804 'org-todo-get-default-hook new-mark-x nil)
7805 new-mark-x)))
7806 (beginning-of-line 1)
7807 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7808 (if org-treat-insert-todo-heading-as-state-change
7809 (org-todo new-mark)
7810 (insert new-mark " "))))
7811 (when org-provide-todo-statistics
7812 (org-update-parent-todo-statistics))))
7814 (defun org-insert-subheading (arg)
7815 "Insert a new subheading and demote it.
7816 Works for outline headings and for plain lists alike."
7817 (interactive "P")
7818 (org-insert-heading arg)
7819 (cond
7820 ((org-at-heading-p) (org-do-demote))
7821 ((org-at-item-p) (org-indent-item))))
7823 (defun org-insert-todo-subheading (arg)
7824 "Insert a new subheading with TODO keyword or checkbox and demote it.
7825 Works for outline headings and for plain lists alike."
7826 (interactive "P")
7827 (org-insert-todo-heading arg)
7828 (cond
7829 ((org-at-heading-p) (org-do-demote))
7830 ((org-at-item-p) (org-indent-item))))
7832 ;;; Promotion and Demotion
7834 (defvar org-after-demote-entry-hook nil
7835 "Hook run after an entry has been demoted.
7836 The cursor will be at the beginning of the entry.
7837 When a subtree is being demoted, the hook will be called for each node.")
7839 (defvar org-after-promote-entry-hook nil
7840 "Hook run after an entry has been promoted.
7841 The cursor will be at the beginning of the entry.
7842 When a subtree is being promoted, the hook will be called for each node.")
7844 (defun org-promote-subtree ()
7845 "Promote the entire subtree.
7846 See also `org-promote'."
7847 (interactive)
7848 (save-excursion
7849 (org-with-limited-levels (org-map-tree 'org-promote)))
7850 (org-fix-position-after-promote))
7852 (defun org-demote-subtree ()
7853 "Demote the entire subtree. See `org-demote'.
7854 See also `org-promote'."
7855 (interactive)
7856 (save-excursion
7857 (org-with-limited-levels (org-map-tree 'org-demote)))
7858 (org-fix-position-after-promote))
7861 (defun org-do-promote ()
7862 "Promote the current heading higher up the tree.
7863 If the region is active in `transient-mark-mode', promote all headings
7864 in the region."
7865 (interactive)
7866 (save-excursion
7867 (if (org-region-active-p)
7868 (org-map-region 'org-promote (region-beginning) (region-end))
7869 (org-promote)))
7870 (org-fix-position-after-promote))
7872 (defun org-do-demote ()
7873 "Demote the current heading lower down the tree.
7874 If the region is active in `transient-mark-mode', demote all headings
7875 in the region."
7876 (interactive)
7877 (save-excursion
7878 (if (org-region-active-p)
7879 (org-map-region 'org-demote (region-beginning) (region-end))
7880 (org-demote)))
7881 (org-fix-position-after-promote))
7883 (defun org-fix-position-after-promote ()
7884 "Make sure that after pro/demotion cursor position is right."
7885 (let ((pos (point)))
7886 (when (save-excursion
7887 (beginning-of-line 1)
7888 (looking-at org-todo-line-regexp)
7889 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7890 (cond ((eobp) (insert " "))
7891 ((eolp) (insert " "))
7892 ((equal (char-after) ?\ ) (forward-char 1))))))
7894 (defun org-current-level ()
7895 "Return the level of the current entry, or nil if before the first headline.
7896 The level is the number of stars at the beginning of the headline."
7897 (save-excursion
7898 (org-with-limited-levels
7899 (if (ignore-errors (org-back-to-heading t))
7900 (funcall outline-level)))))
7902 (defun org-get-previous-line-level ()
7903 "Return the outline depth of the last headline before the current line.
7904 Returns 0 for the first headline in the buffer, and nil if before the
7905 first headline."
7906 (let ((current-level (org-current-level))
7907 (prev-level (when (> (line-number-at-pos) 1)
7908 (save-excursion
7909 (beginning-of-line 0)
7910 (org-current-level)))))
7911 (cond ((null current-level) nil) ; Before first headline
7912 ((null prev-level) 0) ; At first headline
7913 (prev-level))))
7915 (defun org-reduced-level (l)
7916 "Compute the effective level of a heading.
7917 This takes into account the setting of `org-odd-levels-only'."
7918 (cond
7919 ((zerop l) 0)
7920 (org-odd-levels-only (1+ (floor (/ l 2))))
7921 (t l)))
7923 (defun org-level-increment ()
7924 "Return the number of stars that will be added or removed at a
7925 time to headlines when structure editing, based on the value of
7926 `org-odd-levels-only'."
7927 (if org-odd-levels-only 2 1))
7929 (defun org-get-valid-level (level &optional change)
7930 "Rectify a level change under the influence of `org-odd-levels-only'
7931 LEVEL is a current level, CHANGE is by how much the level should be
7932 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7933 even level numbers will become the next higher odd number."
7934 (if org-odd-levels-only
7935 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7936 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7937 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7938 (max 1 (+ level (or change 0)))))
7940 (if (boundp 'define-obsolete-function-alias)
7941 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7942 (define-obsolete-function-alias 'org-get-legal-level
7943 'org-get-valid-level)
7944 (define-obsolete-function-alias 'org-get-legal-level
7945 'org-get-valid-level "23.1")))
7947 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7948 ;; ̀org-with-limited-levels'
7949 (defun org-promote ()
7950 "Promote the current heading higher up the tree.
7951 If the region is active in `transient-mark-mode', promote all headings
7952 in the region."
7953 (org-back-to-heading t)
7954 (let* ((level (save-match-data (funcall outline-level)))
7955 (after-change-functions (remove 'flyspell-after-change-function
7956 after-change-functions))
7957 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7958 (diff (abs (- level (length up-head) -1))))
7959 (cond ((and (= level 1) org-called-with-limited-levels
7960 org-allow-promoting-top-level-subtree)
7961 (replace-match "# " nil t))
7962 ((= level 1)
7963 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7964 (t (replace-match up-head nil t)))
7965 ;; Fixup tag positioning
7966 (unless (= level 1)
7967 (and org-auto-align-tags (org-set-tags nil t))
7968 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7969 (run-hooks 'org-after-promote-entry-hook)))
7971 (defun org-demote ()
7972 "Demote the current heading lower down the tree.
7973 If the region is active in `transient-mark-mode', demote all headings
7974 in the region."
7975 (org-back-to-heading t)
7976 (let* ((level (save-match-data (funcall outline-level)))
7977 (after-change-functions (remove 'flyspell-after-change-function
7978 after-change-functions))
7979 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7980 (diff (abs (- level (length down-head) -1))))
7981 (replace-match down-head nil t)
7982 ;; Fixup tag positioning
7983 (and org-auto-align-tags (org-set-tags nil t))
7984 (if org-adapt-indentation (org-fixup-indentation diff))
7985 (run-hooks 'org-after-demote-entry-hook)))
7987 (defun org-cycle-level ()
7988 "Cycle the level of an empty headline through possible states.
7989 This goes first to child, then to parent, level, then up the hierarchy.
7990 After top level, it switches back to sibling level."
7991 (interactive)
7992 (let ((org-adapt-indentation nil))
7993 (when (org-point-at-end-of-empty-headline)
7994 (setq this-command 'org-cycle-level) ; Only needed for caching
7995 (let ((cur-level (org-current-level))
7996 (prev-level (org-get-previous-line-level)))
7997 (cond
7998 ;; If first headline in file, promote to top-level.
7999 ((= prev-level 0)
8000 (loop repeat (/ (- cur-level 1) (org-level-increment))
8001 do (org-do-promote)))
8002 ;; If same level as prev, demote one.
8003 ((= prev-level cur-level)
8004 (org-do-demote))
8005 ;; If parent is top-level, promote to top level if not already.
8006 ((= prev-level 1)
8007 (loop repeat (/ (- cur-level 1) (org-level-increment))
8008 do (org-do-promote)))
8009 ;; If top-level, return to prev-level.
8010 ((= cur-level 1)
8011 (loop repeat (/ (- prev-level 1) (org-level-increment))
8012 do (org-do-demote)))
8013 ;; If less than prev-level, promote one.
8014 ((< cur-level prev-level)
8015 (org-do-promote))
8016 ;; If deeper than prev-level, promote until higher than
8017 ;; prev-level.
8018 ((> cur-level prev-level)
8019 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8020 do (org-do-promote))))
8021 t))))
8023 (defun org-map-tree (fun)
8024 "Call FUN for every heading underneath the current one."
8025 (org-back-to-heading)
8026 (let ((level (funcall outline-level)))
8027 (save-excursion
8028 (funcall fun)
8029 (while (and (progn
8030 (outline-next-heading)
8031 (> (funcall outline-level) level))
8032 (not (eobp)))
8033 (funcall fun)))))
8035 (defun org-map-region (fun beg end)
8036 "Call FUN for every heading between BEG and END."
8037 (let ((org-ignore-region t))
8038 (save-excursion
8039 (setq end (copy-marker end))
8040 (goto-char beg)
8041 (if (and (re-search-forward org-outline-regexp-bol nil t)
8042 (< (point) end))
8043 (funcall fun))
8044 (while (and (progn
8045 (outline-next-heading)
8046 (< (point) end))
8047 (not (eobp)))
8048 (funcall fun)))))
8050 (defvar org-property-end-re) ; silence byte-compiler
8051 (defun org-fixup-indentation (diff)
8052 "Change the indentation in the current entry by DIFF.
8053 However, if any line in the current entry has no indentation, or if it
8054 would end up with no indentation after the change, nothing at all is done."
8055 (save-excursion
8056 (let ((end (save-excursion (outline-next-heading)
8057 (point-marker)))
8058 (prohibit (if (> diff 0)
8059 "^\\S-"
8060 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8061 col)
8062 (unless (save-excursion (end-of-line 1)
8063 (re-search-forward prohibit end t))
8064 (while (and (< (point) end)
8065 (re-search-forward "^[ \t]+" end t))
8066 (goto-char (match-end 0))
8067 (setq col (current-column))
8068 (if (< diff 0) (replace-match ""))
8069 (org-indent-to-column (+ diff col))))
8070 (move-marker end nil))))
8072 (defun org-convert-to-odd-levels ()
8073 "Convert an org-mode file with all levels allowed to one with odd levels.
8074 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8075 level 5 etc."
8076 (interactive)
8077 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8078 (let ((outline-level 'org-outline-level)
8079 (org-odd-levels-only nil) n)
8080 (save-excursion
8081 (goto-char (point-min))
8082 (while (re-search-forward "^\\*\\*+ " nil t)
8083 (setq n (- (length (match-string 0)) 2))
8084 (while (>= (setq n (1- n)) 0)
8085 (org-demote))
8086 (end-of-line 1))))))
8088 (defun org-convert-to-oddeven-levels ()
8089 "Convert an org-mode file with only odd levels to one with odd/even levels.
8090 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8091 file contains a section with an even level, conversion would
8092 destroy the structure of the file. An error is signaled in this
8093 case."
8094 (interactive)
8095 (goto-char (point-min))
8096 ;; First check if there are no even levels
8097 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8098 (org-show-context t)
8099 (error "Not all levels are odd in this file. Conversion not possible"))
8100 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8101 (let ((outline-regexp org-outline-regexp)
8102 (outline-level 'org-outline-level)
8103 (org-odd-levels-only nil) n)
8104 (save-excursion
8105 (goto-char (point-min))
8106 (while (re-search-forward "^\\*\\*+ " nil t)
8107 (setq n (/ (1- (length (match-string 0))) 2))
8108 (while (>= (setq n (1- n)) 0)
8109 (org-promote))
8110 (end-of-line 1))))))
8112 (defun org-tr-level (n)
8113 "Make N odd if required."
8114 (if org-odd-levels-only (1+ (/ n 2)) n))
8116 ;;; Vertical tree motion, cutting and pasting of subtrees
8118 (defun org-move-subtree-up (&optional arg)
8119 "Move the current subtree up past ARG headlines of the same level."
8120 (interactive "p")
8121 (org-move-subtree-down (- (prefix-numeric-value arg))))
8123 (defun org-move-subtree-down (&optional arg)
8124 "Move the current subtree down past ARG headlines of the same level."
8125 (interactive "p")
8126 (setq arg (prefix-numeric-value arg))
8127 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8128 'org-get-last-sibling))
8129 (ins-point (make-marker))
8130 (cnt (abs arg))
8131 (col (current-column))
8132 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8133 ;; Select the tree
8134 (org-back-to-heading)
8135 (setq beg0 (point))
8136 (save-excursion
8137 (setq ne-beg (org-back-over-empty-lines))
8138 (setq beg (point)))
8139 (save-match-data
8140 (save-excursion (outline-end-of-heading)
8141 (setq folded (outline-invisible-p)))
8142 (outline-end-of-subtree))
8143 (outline-next-heading)
8144 (setq ne-end (org-back-over-empty-lines))
8145 (setq end (point))
8146 (goto-char beg0)
8147 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8148 ;; include less whitespace
8149 (save-excursion
8150 (goto-char beg)
8151 (forward-line (- ne-beg ne-end))
8152 (setq beg (point))))
8153 ;; Find insertion point, with error handling
8154 (while (> cnt 0)
8155 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8156 (progn (goto-char beg0)
8157 (user-error "Cannot move past superior level or buffer limit")))
8158 (setq cnt (1- cnt)))
8159 (if (> arg 0)
8160 ;; Moving forward - still need to move over subtree
8161 (progn (org-end-of-subtree t t)
8162 (save-excursion
8163 (org-back-over-empty-lines)
8164 (or (bolp) (newline)))))
8165 (setq ne-ins (org-back-over-empty-lines))
8166 (move-marker ins-point (point))
8167 (setq txt (buffer-substring beg end))
8168 (org-save-markers-in-region beg end)
8169 (delete-region beg end)
8170 (org-remove-empty-overlays-at beg)
8171 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8172 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8173 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8174 (let ((bbb (point)))
8175 (insert-before-markers txt)
8176 (org-reinstall-markers-in-region bbb)
8177 (move-marker ins-point bbb))
8178 (or (bolp) (insert "\n"))
8179 (setq ins-end (point))
8180 (goto-char ins-point)
8181 (org-skip-whitespace)
8182 (when (and (< arg 0)
8183 (org-first-sibling-p)
8184 (> ne-ins ne-beg))
8185 ;; Move whitespace back to beginning
8186 (save-excursion
8187 (goto-char ins-end)
8188 (let ((kill-whole-line t))
8189 (kill-line (- ne-ins ne-beg)) (point)))
8190 (insert (make-string (- ne-ins ne-beg) ?\n)))
8191 (move-marker ins-point nil)
8192 (if folded
8193 (hide-subtree)
8194 (org-show-entry)
8195 (show-children)
8196 (org-cycle-hide-drawers 'children))
8197 (org-clean-visibility-after-subtree-move)
8198 ;; move back to the initial column we were at
8199 (move-to-column col)))
8201 (defvar org-subtree-clip ""
8202 "Clipboard for cut and paste of subtrees.
8203 This is actually only a copy of the kill, because we use the normal kill
8204 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8206 (defvar org-subtree-clip-folded nil
8207 "Was the last copied subtree folded?
8208 This is used to fold the tree back after pasting.")
8210 (defun org-cut-subtree (&optional n)
8211 "Cut the current subtree into the clipboard.
8212 With prefix arg N, cut this many sequential subtrees.
8213 This is a short-hand for marking the subtree and then cutting it."
8214 (interactive "p")
8215 (org-copy-subtree n 'cut))
8217 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8218 "Copy the current subtree it in the clipboard.
8219 With prefix arg N, copy this many sequential subtrees.
8220 This is a short-hand for marking the subtree and then copying it.
8221 If CUT is non-nil, actually cut the subtree.
8222 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8223 of some markers in the region, even if CUT is non-nil. This is
8224 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8225 (interactive "p")
8226 (let (beg end folded (beg0 (point)))
8227 (if (org-called-interactively-p 'any)
8228 (org-back-to-heading nil) ; take what looks like a subtree
8229 (org-back-to-heading t)) ; take what is really there
8230 (setq beg (point))
8231 (skip-chars-forward " \t\r\n")
8232 (save-match-data
8233 (if nosubtrees
8234 (outline-next-heading)
8235 (save-excursion (outline-end-of-heading)
8236 (setq folded (outline-invisible-p)))
8237 (condition-case nil
8238 (org-forward-heading-same-level (1- n) t)
8239 (error nil))
8240 (org-end-of-subtree t t)))
8241 (setq end (point))
8242 (goto-char beg0)
8243 (when (> end beg)
8244 (setq org-subtree-clip-folded folded)
8245 (when (or cut force-store-markers)
8246 (org-save-markers-in-region beg end))
8247 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8248 (setq org-subtree-clip (current-kill 0))
8249 (message "%s: Subtree(s) with %d characters"
8250 (if cut "Cut" "Copied")
8251 (length org-subtree-clip)))))
8253 (defun org-paste-subtree (&optional level tree for-yank)
8254 "Paste the clipboard as a subtree, with modification of headline level.
8255 The entire subtree is promoted or demoted in order to match a new headline
8256 level.
8258 If the cursor is at the beginning of a headline, the same level as
8259 that headline is used to paste the tree.
8261 If not, the new level is derived from the *visible* headings
8262 before and after the insertion point, and taken to be the inferior headline
8263 level of the two. So if the previous visible heading is level 3 and the
8264 next is level 4 (or vice versa), level 4 will be used for insertion.
8265 This makes sure that the subtree remains an independent subtree and does
8266 not swallow low level entries.
8268 You can also force a different level, either by using a numeric prefix
8269 argument, or by inserting the heading marker by hand. For example, if the
8270 cursor is after \"*****\", then the tree will be shifted to level 5.
8272 If optional TREE is given, use this text instead of the kill ring.
8274 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8275 move back over whitespace before inserting, and move point to the end of
8276 the inserted text when done."
8277 (interactive "P")
8278 (setq tree (or tree (and kill-ring (current-kill 0))))
8279 (unless (org-kill-is-subtree-p tree)
8280 (user-error "%s"
8281 (substitute-command-keys
8282 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8283 (org-with-limited-levels
8284 (let* ((visp (not (outline-invisible-p)))
8285 (txt tree)
8286 (^re_ "\\(\\*+\\)[ \t]*")
8287 (old-level (if (string-match org-outline-regexp-bol txt)
8288 (- (match-end 0) (match-beginning 0) 1)
8289 -1))
8290 (force-level (cond (level (prefix-numeric-value level))
8291 ((and (looking-at "[ \t]*$")
8292 (string-match
8293 "^\\*+$" (buffer-substring
8294 (point-at-bol) (point))))
8295 (- (match-end 1) (match-beginning 1)))
8296 ((and (bolp)
8297 (looking-at org-outline-regexp))
8298 (- (match-end 0) (point) 1))))
8299 (previous-level (save-excursion
8300 (condition-case nil
8301 (progn
8302 (outline-previous-visible-heading 1)
8303 (if (looking-at ^re_)
8304 (- (match-end 0) (match-beginning 0) 1)
8306 (error 1))))
8307 (next-level (save-excursion
8308 (condition-case nil
8309 (progn
8310 (or (looking-at org-outline-regexp)
8311 (outline-next-visible-heading 1))
8312 (if (looking-at ^re_)
8313 (- (match-end 0) (match-beginning 0) 1)
8315 (error 1))))
8316 (new-level (or force-level (max previous-level next-level)))
8317 (shift (if (or (= old-level -1)
8318 (= new-level -1)
8319 (= old-level new-level))
8321 (- new-level old-level)))
8322 (delta (if (> shift 0) -1 1))
8323 (func (if (> shift 0) 'org-demote 'org-promote))
8324 (org-odd-levels-only nil)
8325 beg end newend)
8326 ;; Remove the forced level indicator
8327 (if force-level
8328 (delete-region (point-at-bol) (point)))
8329 ;; Paste
8330 (beginning-of-line (if (bolp) 1 2))
8331 (setq beg (point))
8332 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8333 (insert-before-markers txt)
8334 (unless (string-match "\n\\'" txt) (insert "\n"))
8335 (setq newend (point))
8336 (org-reinstall-markers-in-region beg)
8337 (setq end (point))
8338 (goto-char beg)
8339 (skip-chars-forward " \t\n\r")
8340 (setq beg (point))
8341 (if (and (outline-invisible-p) visp)
8342 (save-excursion (outline-show-heading)))
8343 ;; Shift if necessary
8344 (unless (= shift 0)
8345 (save-restriction
8346 (narrow-to-region beg end)
8347 (while (not (= shift 0))
8348 (org-map-region func (point-min) (point-max))
8349 (setq shift (+ delta shift)))
8350 (goto-char (point-min))
8351 (setq newend (point-max))))
8352 (when (or (org-called-interactively-p 'interactive) for-yank)
8353 (message "Clipboard pasted as level %d subtree" new-level))
8354 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8355 kill-ring
8356 (eq org-subtree-clip (current-kill 0))
8357 org-subtree-clip-folded)
8358 ;; The tree was folded before it was killed/copied
8359 (hide-subtree))
8360 (and for-yank (goto-char newend)))))
8362 (defun org-kill-is-subtree-p (&optional txt)
8363 "Check if the current kill is an outline subtree, or a set of trees.
8364 Returns nil if kill does not start with a headline, or if the first
8365 headline level is not the largest headline level in the tree.
8366 So this will actually accept several entries of equal levels as well,
8367 which is OK for `org-paste-subtree'.
8368 If optional TXT is given, check this string instead of the current kill."
8369 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8370 (re (org-get-limited-outline-regexp))
8371 (^re (concat "^" re))
8372 (start-level (and kill
8373 (string-match
8374 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8375 kill)
8376 (- (match-end 2) (match-beginning 2) 1)))
8377 (start (1+ (or (match-beginning 2) -1))))
8378 (if (not start-level)
8379 (progn
8380 nil) ;; does not even start with a heading
8381 (catch 'exit
8382 (while (setq start (string-match ^re kill (1+ start)))
8383 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8384 (throw 'exit nil)))
8385 t))))
8387 (defvar org-markers-to-move nil
8388 "Markers that should be moved with a cut-and-paste operation.
8389 Those markers are stored together with their positions relative to
8390 the start of the region.")
8392 (defun org-save-markers-in-region (beg end)
8393 "Check markers in region.
8394 If these markers are between BEG and END, record their position relative
8395 to BEG, so that after moving the block of text, we can put the markers back
8396 into place.
8397 This function gets called just before an entry or tree gets cut from the
8398 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8399 called immediately, to move the markers with the entries."
8400 (setq org-markers-to-move nil)
8401 (when (featurep 'org-clock)
8402 (org-clock-save-markers-for-cut-and-paste beg end))
8403 (when (featurep 'org-agenda)
8404 (org-agenda-save-markers-for-cut-and-paste beg end)))
8406 (defun org-check-and-save-marker (marker beg end)
8407 "Check if MARKER is between BEG and END.
8408 If yes, remember the marker and the distance to BEG."
8409 (when (and (marker-buffer marker)
8410 (equal (marker-buffer marker) (current-buffer)))
8411 (if (and (>= marker beg) (< marker end))
8412 (push (cons marker (- marker beg)) org-markers-to-move))))
8414 (defun org-reinstall-markers-in-region (beg)
8415 "Move all remembered markers to their position relative to BEG."
8416 (mapc (lambda (x)
8417 (move-marker (car x) (+ beg (cdr x))))
8418 org-markers-to-move)
8419 (setq org-markers-to-move nil))
8421 (defun org-narrow-to-subtree ()
8422 "Narrow buffer to the current subtree."
8423 (interactive)
8424 (save-excursion
8425 (save-match-data
8426 (org-with-limited-levels
8427 (narrow-to-region
8428 (progn (org-back-to-heading t) (point))
8429 (progn (org-end-of-subtree t t)
8430 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8431 (point)))))))
8433 (defun org-narrow-to-block ()
8434 "Narrow buffer to the current block."
8435 (interactive)
8436 (let* ((case-fold-search t)
8437 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8438 "^[ \t]*#\\+end_.*")))
8439 (if blockp
8440 (narrow-to-region (car blockp) (cdr blockp))
8441 (user-error "Not in a block"))))
8443 (eval-when-compile
8444 (defvar org-property-drawer-re))
8446 (defvar org-property-start-re) ;; defined below
8447 (defun org-clone-subtree-with-time-shift (n &optional shift)
8448 "Clone the task (subtree) at point N times.
8449 The clones will be inserted as siblings.
8451 In interactive use, the user will be prompted for the number of
8452 clones to be produced. If the entry has a timestamp, the user
8453 will also be prompted for a time shift, which may be a repeater
8454 as used in time stamps, for example `+3d'. To disable this,
8455 you can call the function with a universal prefix argument.
8457 When a valid repeater is given and the entry contains any time
8458 stamps, the clones will become a sequence in time, with time
8459 stamps in the subtree shifted for each clone produced. If SHIFT
8460 is nil or the empty string, time stamps will be left alone. The
8461 ID property of the original subtree is removed.
8463 If the original subtree did contain time stamps with a repeater,
8464 the following will happen:
8465 - the repeater will be removed in each clone
8466 - an additional clone will be produced, with the current, unshifted
8467 date(s) in the entry.
8468 - the original entry will be placed *after* all the clones, with
8469 repeater intact.
8470 - the start days in the repeater in the original entry will be shifted
8471 to past the last clone.
8472 In this way you can spell out a number of instances of a repeating task,
8473 and still retain the repeater to cover future instances of the task."
8474 (interactive "nNumber of clones to produce: ")
8475 (let ((shift
8476 (or shift
8477 (if (and (not (equal current-prefix-arg '(4)))
8478 (save-excursion
8479 (re-search-forward org-ts-regexp-both
8480 (save-excursion
8481 (org-end-of-subtree t)
8482 (point)) t)))
8483 (read-from-minibuffer
8484 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8485 ""))) ;; No time shift
8486 (n-no-remove -1)
8487 (drawer-re org-drawer-regexp)
8488 beg end template task idprop
8489 shift-n shift-what doshift nmin nmax)
8490 (if (not (and (integerp n) (> n 0)))
8491 (error "Invalid number of replications %s" n))
8492 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8493 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8494 shift)))
8495 (error "Invalid shift specification %s" shift))
8496 (when doshift
8497 (setq shift-n (string-to-number (match-string 1 shift))
8498 shift-what (cdr (assoc (match-string 2 shift)
8499 '(("d" . day) ("w" . week)
8500 ("m" . month) ("y" . year))))))
8501 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8502 (setq nmin 1 nmax n)
8503 (org-back-to-heading t)
8504 (setq beg (point))
8505 (setq idprop (org-entry-get nil "ID"))
8506 (org-end-of-subtree t t)
8507 (or (bolp) (insert "\n"))
8508 (setq end (point))
8509 (setq template (buffer-substring beg end))
8510 (when (and doshift
8511 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8512 (delete-region beg end)
8513 (setq end beg)
8514 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8515 (goto-char end)
8516 (loop for n from nmin to nmax do
8517 ;; prepare clone
8518 (with-temp-buffer
8519 (insert template)
8520 (org-mode)
8521 (goto-char (point-min))
8522 (org-show-subtree)
8523 (and idprop (if org-clone-delete-id
8524 (org-entry-delete nil "ID")
8525 (org-id-get-create t)))
8526 (unless (= n 0)
8527 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8528 (kill-whole-line))
8529 (goto-char (point-min))
8530 (while (re-search-forward drawer-re nil t)
8531 (mapc (lambda (d)
8532 (org-remove-empty-drawer-at d (point))) org-drawers)))
8533 (goto-char (point-min))
8534 (when doshift
8535 (while (re-search-forward org-ts-regexp-both nil t)
8536 (org-timestamp-change (* n shift-n) shift-what))
8537 (unless (= n n-no-remove)
8538 (goto-char (point-min))
8539 (while (re-search-forward org-ts-regexp nil t)
8540 (save-excursion
8541 (goto-char (match-beginning 0))
8542 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8543 (delete-region (match-beginning 1) (match-end 1)))))))
8544 (setq task (buffer-string)))
8545 (insert task))
8546 (goto-char beg)))
8548 ;;; Outline Sorting
8550 (defun org-sort (with-case)
8551 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8552 Optional argument WITH-CASE means sort case-sensitively."
8553 (interactive "P")
8554 (cond
8555 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8556 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8558 (org-call-with-arg 'org-sort-entries with-case))))
8560 (defun org-sort-remove-invisible (s)
8561 "Remove invisible links from string S."
8562 (remove-text-properties 0 (length s) org-rm-props s)
8563 (while (string-match org-bracket-link-regexp s)
8564 (setq s (replace-match (if (match-end 2)
8565 (match-string 3 s)
8566 (match-string 1 s)) t t s)))
8567 (let ((st (format " %s " s)))
8568 (while (string-match org-emph-re st)
8569 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8570 (setq s (substring st 1 -1)))
8573 (defvar org-priority-regexp) ; defined later in the file
8575 (defvar org-after-sorting-entries-or-items-hook nil
8576 "Hook that is run after a bunch of entries or items have been sorted.
8577 When children are sorted, the cursor is in the parent line when this
8578 hook gets called. When a region or a plain list is sorted, the cursor
8579 will be in the first entry of the sorted region/list.")
8581 (defun org-sort-entries
8582 (&optional with-case sorting-type getkey-func compare-func property)
8583 "Sort entries on a certain level of an outline tree.
8584 If there is an active region, the entries in the region are sorted.
8585 Else, if the cursor is before the first entry, sort the top-level items.
8586 Else, the children of the entry at point are sorted.
8588 Sorting can be alphabetically, numerically, by date/time as given by
8589 a time stamp, by a property, by priority order, or by a custom function.
8591 The command prompts for the sorting type unless it has been given to the
8592 function through the SORTING-TYPE argument, which needs to be a character,
8593 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8594 precise meaning of each character:
8596 n Numerically, by converting the beginning of the entry/item to a number.
8597 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8598 o By order of TODO keywords.
8599 t By date/time, either the first active time stamp in the entry, or, if
8600 none exist, by the first inactive one.
8601 s By the scheduled date/time.
8602 d By deadline date/time.
8603 c By creation time, which is assumed to be the first inactive time stamp
8604 at the beginning of a line.
8605 p By priority according to the cookie.
8606 r By the value of a property.
8608 Capital letters will reverse the sort order.
8610 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8611 called with point at the beginning of the record. It must return either
8612 a string or a number that should serve as the sorting key for that record.
8614 Comparing entries ignores case by default. However, with an optional argument
8615 WITH-CASE, the sorting considers case as well.
8617 Sorting is done against the visible part of the headlines, it ignores hidden
8618 links."
8619 (interactive "P")
8620 (let ((case-func (if with-case 'identity 'downcase))
8621 (cmstr
8622 ;; The clock marker is lost when using `sort-subr', let's
8623 ;; store the clocking string.
8624 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8625 (save-excursion
8626 (goto-char org-clock-marker)
8627 (looking-back "^.*") (match-string-no-properties 0))))
8628 start beg end stars re re2
8629 txt what tmp)
8630 ;; Find beginning and end of region to sort
8631 (cond
8632 ((org-region-active-p)
8633 ;; we will sort the region
8634 (setq end (region-end)
8635 what "region")
8636 (goto-char (region-beginning))
8637 (if (not (org-at-heading-p)) (outline-next-heading))
8638 (setq start (point)))
8639 ((or (org-at-heading-p)
8640 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8641 ;; we will sort the children of the current headline
8642 (org-back-to-heading)
8643 (setq start (point)
8644 end (progn (org-end-of-subtree t t)
8645 (or (bolp) (insert "\n"))
8646 (org-back-over-empty-lines)
8647 (point))
8648 what "children")
8649 (goto-char start)
8650 (show-subtree)
8651 (outline-next-heading))
8653 ;; we will sort the top-level entries in this file
8654 (goto-char (point-min))
8655 (or (org-at-heading-p) (outline-next-heading))
8656 (setq start (point))
8657 (goto-char (point-max))
8658 (beginning-of-line 1)
8659 (when (looking-at ".*?\\S-")
8660 ;; File ends in a non-white line
8661 (end-of-line 1)
8662 (insert "\n"))
8663 (setq end (point-max))
8664 (setq what "top-level")
8665 (goto-char start)
8666 (show-all)))
8668 (setq beg (point))
8669 (if (>= beg end) (user-error "Nothing to sort"))
8671 (looking-at "\\(\\*+\\)")
8672 (setq stars (match-string 1)
8673 re (concat "^" (regexp-quote stars) " +")
8674 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8675 txt (buffer-substring beg end))
8676 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8677 (if (and (not (equal stars "*")) (string-match re2 txt))
8678 (user-error "Region to sort contains a level above the first entry"))
8680 (unless sorting-type
8681 (message
8682 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8683 [t]ime [s]cheduled [d]eadline [c]reated
8684 A/N/P/R/O/F/T/S/D/C means reversed:"
8685 what)
8686 (setq sorting-type (read-char-exclusive))
8688 (unless getkey-func
8689 (and (= (downcase sorting-type) ?f)
8690 (setq getkey-func
8691 (org-icompleting-read "Sort using function: "
8692 obarray 'fboundp t nil nil))
8693 (setq getkey-func (intern getkey-func))))
8695 (and (= (downcase sorting-type) ?r)
8696 (not property)
8697 (setq property
8698 (org-icompleting-read "Property: "
8699 (mapcar 'list (org-buffer-property-keys t))
8700 nil t))))
8702 (message "Sorting entries...")
8704 (save-restriction
8705 (narrow-to-region start end)
8706 (let ((dcst (downcase sorting-type))
8707 (case-fold-search nil)
8708 (now (current-time)))
8709 (sort-subr
8710 (/= dcst sorting-type)
8711 ;; This function moves to the beginning character of the "record" to
8712 ;; be sorted.
8713 (lambda nil
8714 (if (re-search-forward re nil t)
8715 (goto-char (match-beginning 0))
8716 (goto-char (point-max))))
8717 ;; This function moves to the last character of the "record" being
8718 ;; sorted.
8719 (lambda nil
8720 (save-match-data
8721 (condition-case nil
8722 (outline-forward-same-level 1)
8723 (error
8724 (goto-char (point-max))))))
8725 ;; This function returns the value that gets sorted against.
8726 (lambda nil
8727 (cond
8728 ((= dcst ?n)
8729 (if (looking-at org-complex-heading-regexp)
8730 (string-to-number (org-sort-remove-invisible (match-string 4)))
8731 nil))
8732 ((= dcst ?a)
8733 (if (looking-at org-complex-heading-regexp)
8734 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8735 nil))
8736 ((= dcst ?t)
8737 (let ((end (save-excursion (outline-next-heading) (point))))
8738 (if (or (re-search-forward org-ts-regexp end t)
8739 (re-search-forward org-ts-regexp-both end t))
8740 (org-time-string-to-seconds (match-string 0))
8741 (org-float-time now))))
8742 ((= dcst ?c)
8743 (let ((end (save-excursion (outline-next-heading) (point))))
8744 (if (re-search-forward
8745 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8746 end t)
8747 (org-time-string-to-seconds (match-string 0))
8748 (org-float-time now))))
8749 ((= dcst ?s)
8750 (let ((end (save-excursion (outline-next-heading) (point))))
8751 (if (re-search-forward org-scheduled-time-regexp end t)
8752 (org-time-string-to-seconds (match-string 1))
8753 (org-float-time now))))
8754 ((= dcst ?d)
8755 (let ((end (save-excursion (outline-next-heading) (point))))
8756 (if (re-search-forward org-deadline-time-regexp end t)
8757 (org-time-string-to-seconds (match-string 1))
8758 (org-float-time now))))
8759 ((= dcst ?p)
8760 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8761 (string-to-char (match-string 2))
8762 org-default-priority))
8763 ((= dcst ?r)
8764 (or (org-entry-get nil property) ""))
8765 ((= dcst ?o)
8766 (if (looking-at org-complex-heading-regexp)
8767 (- 9999 (length (member (match-string 2)
8768 org-todo-keywords-1)))))
8769 ((= dcst ?f)
8770 (if getkey-func
8771 (progn
8772 (setq tmp (funcall getkey-func))
8773 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8774 tmp)
8775 (error "Invalid key function `%s'" getkey-func)))
8776 (t (error "Invalid sorting type `%c'" sorting-type))))
8778 (cond
8779 ((= dcst ?a) 'string<)
8780 ((= dcst ?f) compare-func)
8781 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8782 (run-hooks 'org-after-sorting-entries-or-items-hook)
8783 ;; Reset the clock marker if needed
8784 (when cmstr
8785 (save-excursion
8786 (goto-char start)
8787 (search-forward cmstr nil t)
8788 (move-marker org-clock-marker (point))))
8789 (message "Sorting entries...done")))
8791 (defun org-do-sort (table what &optional with-case sorting-type)
8792 "Sort TABLE of WHAT according to SORTING-TYPE.
8793 The user will be prompted for the SORTING-TYPE if the call to this
8794 function does not specify it. WHAT is only for the prompt, to indicate
8795 what is being sorted. The sorting key will be extracted from
8796 the car of the elements of the table.
8797 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8798 (unless sorting-type
8799 (message
8800 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8801 what)
8802 (setq sorting-type (read-char-exclusive)))
8803 (let ((dcst (downcase sorting-type))
8804 extractfun comparefun)
8805 ;; Define the appropriate functions
8806 (cond
8807 ((= dcst ?n)
8808 (setq extractfun 'string-to-number
8809 comparefun (if (= dcst sorting-type) '< '>)))
8810 ((= dcst ?a)
8811 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8812 (lambda(x) (downcase (org-sort-remove-invisible x))))
8813 comparefun (if (= dcst sorting-type)
8814 'string<
8815 (lambda (a b) (and (not (string< a b))
8816 (not (string= a b)))))))
8817 ((= dcst ?t)
8818 (setq extractfun
8819 (lambda (x)
8820 (if (or (string-match org-ts-regexp x)
8821 (string-match org-ts-regexp-both x))
8822 (org-float-time
8823 (org-time-string-to-time (match-string 0 x)))
8825 comparefun (if (= dcst sorting-type) '< '>)))
8826 (t (error "Invalid sorting type `%c'" sorting-type)))
8828 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8829 table)
8830 (lambda (a b) (funcall comparefun (car a) (car b))))))
8833 ;;; The orgstruct minor mode
8835 ;; Define a minor mode which can be used in other modes in order to
8836 ;; integrate the org-mode structure editing commands.
8838 ;; This is really a hack, because the org-mode structure commands use
8839 ;; keys which normally belong to the major mode. Here is how it
8840 ;; works: The minor mode defines all the keys necessary to operate the
8841 ;; structure commands, but wraps the commands into a function which
8842 ;; tests if the cursor is currently at a headline or a plain list
8843 ;; item. If that is the case, the structure command is used,
8844 ;; temporarily setting many Org-mode variables like regular
8845 ;; expressions for filling etc. However, when any of those keys is
8846 ;; used at a different location, function uses `key-binding' to look
8847 ;; up if the key has an associated command in another currently active
8848 ;; keymap (minor modes, major mode, global), and executes that
8849 ;; command. There might be problems if any of the keys is otherwise
8850 ;; used as a prefix key.
8852 (defcustom orgstruct-heading-prefix-regexp nil
8853 "Regexp that matches the custom prefix of Org headlines in
8854 orgstruct(++)-mode."
8855 :group 'org
8856 :version "24.4"
8857 :package-version '(Org . "8.0")
8858 :type 'string)
8859 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8861 (defcustom orgstruct-setup-hook nil
8862 "Hook run after orgstruct-mode-map is filled."
8863 :group 'org
8864 :version "24.4"
8865 :package-version '(Org . "8.0")
8866 :type 'hook)
8868 (defvar orgstruct-initialized nil)
8870 (defvar org-local-vars nil
8871 "List of local variables, for use by `orgstruct-mode'.")
8873 ;;;###autoload
8874 (define-minor-mode orgstruct-mode
8875 "Toggle the minor mode `orgstruct-mode'.
8876 This mode is for using Org-mode structure commands in other
8877 modes. The following keys behave as if Org-mode were active, if
8878 the cursor is on a headline, or on a plain list item (both as
8879 defined by Org-mode)."
8880 nil " OrgStruct" (make-sparse-keymap)
8881 (funcall (if orgstruct-mode
8882 'add-to-invisibility-spec
8883 'remove-from-invisibility-spec)
8884 '(outline . t))
8885 (when orgstruct-mode
8886 (org-load-modules-maybe)
8887 (unless orgstruct-initialized
8888 (orgstruct-setup)
8889 (setq orgstruct-initialized t))))
8891 ;;;###autoload
8892 (defun turn-on-orgstruct ()
8893 "Unconditionally turn on `orgstruct-mode'."
8894 (orgstruct-mode 1))
8896 (defvar org-fb-vars nil)
8897 (make-variable-buffer-local 'org-fb-vars)
8898 (defun orgstruct++-mode (&optional arg)
8899 "Toggle `orgstruct-mode', the enhanced version of it.
8900 In addition to setting orgstruct-mode, this also exports all
8901 indentation and autofilling variables from org-mode into the
8902 buffer. It will also recognize item context in multiline items."
8903 (interactive "P")
8904 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8905 (if (< arg 1)
8906 (progn (orgstruct-mode -1)
8907 (mapc (lambda(v)
8908 (org-set-local (car v)
8909 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8910 org-fb-vars))
8911 (orgstruct-mode 1)
8912 (setq org-fb-vars nil)
8913 (unless org-local-vars
8914 (setq org-local-vars (org-get-local-variables)))
8915 (let (var val)
8916 (mapc
8917 (lambda (x)
8918 (when (string-match
8919 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8920 (symbol-name (car x)))
8921 (setq var (car x) val (nth 1 x))
8922 (push (list var `(quote ,(eval var))) org-fb-vars)
8923 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8924 org-local-vars)
8925 (org-set-local 'orgstruct-is-++ t))))
8927 (defvar orgstruct-is-++ nil
8928 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8929 (make-variable-buffer-local 'orgstruct-is-++)
8931 ;;;###autoload
8932 (defun turn-on-orgstruct++ ()
8933 "Unconditionally turn on `orgstruct++-mode'."
8934 (orgstruct++-mode 1))
8936 (defun orgstruct-error ()
8937 "Error when there is no default binding for a structure key."
8938 (interactive)
8939 (funcall (if (fboundp 'user-error)
8940 'user-error
8941 'error)
8942 "This key has no function outside structure elements"))
8944 (defun orgstruct-setup ()
8945 "Setup orgstruct keymap."
8946 (dolist (cell '((org-demote . t)
8947 (org-metaleft . t)
8948 (org-metaright . t)
8949 (org-promote . t)
8950 (org-shiftmetaleft . t)
8951 (org-shiftmetaright . t)
8952 org-backward-element
8953 org-backward-heading-same-level
8954 org-ctrl-c-ret
8955 org-ctrl-c-minus
8956 org-ctrl-c-star
8957 org-cycle
8958 org-forward-heading-same-level
8959 org-insert-heading
8960 org-insert-heading-respect-content
8961 org-kill-note-or-show-branches
8962 org-mark-subtree
8963 org-meta-return
8964 org-metadown
8965 org-metaup
8966 org-narrow-to-subtree
8967 org-promote-subtree
8968 org-reveal
8969 org-shiftdown
8970 org-shiftleft
8971 org-shiftmetadown
8972 org-shiftmetaup
8973 org-shiftright
8974 org-shifttab
8975 org-shifttab
8976 org-shiftup
8977 org-show-subtree
8978 org-sort
8979 org-up-element
8980 outline-demote
8981 outline-next-visible-heading
8982 outline-previous-visible-heading
8983 outline-promote
8984 outline-up-heading
8985 show-children))
8986 (let ((f (or (car-safe cell) cell))
8987 (disable-when-heading-prefix (cdr-safe cell)))
8988 (when (fboundp f)
8989 (let ((new-bindings))
8990 (dolist (binding (nconc (where-is-internal f org-mode-map)
8991 (where-is-internal f outline-mode-map)))
8992 (push binding new-bindings)
8993 ;; TODO use local-function-key-map
8994 (dolist (rep '(("<tab>" . "TAB")
8995 ("<return>" . "RET")
8996 ("<escape>" . "ESC")
8997 ("<delete>" . "DEL")))
8998 (setq binding (read-kbd-macro
8999 (let ((case-fold-search))
9000 (replace-regexp-in-string
9001 (regexp-quote (cdr rep))
9002 (car rep)
9003 (key-description binding)))))
9004 (pushnew binding new-bindings :test 'equal)))
9005 (dolist (binding new-bindings)
9006 (let ((key (lookup-key orgstruct-mode-map binding)))
9007 (when (or (not key) (numberp key))
9008 (condition-case nil
9009 (org-defkey orgstruct-mode-map
9010 binding
9011 (orgstruct-make-binding f binding disable-when-heading-prefix))
9012 (error nil)))))))))
9013 (run-hooks 'orgstruct-setup-hook))
9015 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9016 "Create a function for binding in the structure minor mode.
9017 FUN is the command to call inside a table. KEY is the key that
9018 should be checked in for a command to execute outside of tables.
9019 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
9020 if `orgstruct-heading-prefix-regexp' is non-nil."
9021 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9022 (let ((nname name)
9023 (i 0))
9024 (while (fboundp (intern nname))
9025 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9026 (setq name (intern nname)))
9027 (eval
9028 (let ((bindings '((org-heading-regexp
9029 (concat "^"
9030 orgstruct-heading-prefix-regexp
9031 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9032 (org-outline-regexp
9033 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9034 (org-outline-regexp-bol
9035 (concat "^" org-outline-regexp))
9036 (outline-regexp org-outline-regexp)
9037 (outline-heading-end-regexp "\n")
9038 (outline-level 'org-outline-level)
9039 (outline-heading-alist))))
9040 `(defun ,name (arg)
9041 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9042 "Outside of structure, run the binding of `"
9043 (key-description key) "'."
9044 (when disable-when-heading-prefix
9045 (concat
9046 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9047 "back to the default binding due to limitations of Org's implementation of\n"
9048 "`" (symbol-name fun) "'.")))
9049 (interactive "p")
9050 (let* ((disable
9051 ,(when disable-when-heading-prefix
9052 '(and orgstruct-heading-prefix-regexp
9053 (not (string= orgstruct-heading-prefix-regexp "")))))
9054 (fallback
9055 (or disable
9056 (not
9057 (let* ,bindings
9058 (org-context-p 'headline 'item
9059 ,(when (memq fun
9060 '(org-insert-heading
9061 org-insert-heading-respect-content
9062 org-meta-return))
9063 '(when orgstruct-is-++
9064 'item-body))))))))
9065 (if fallback
9066 (let* ((orgstruct-mode)
9067 (binding
9068 (loop with key = ,key
9069 for rep in
9070 '(nil
9071 ("<\\([^>]*\\)tab>" . "\\1TAB")
9072 ("<\\([^>]*\\)return>" . "\\1RET")
9073 ("<\\([^>]*\\)escape>" . "\\1ESC")
9074 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9076 (when rep
9077 (setq key (read-kbd-macro
9078 (let ((case-fold-search))
9079 (replace-regexp-in-string
9080 (car rep)
9081 (cdr rep)
9082 (key-description key))))))
9083 thereis (key-binding key))))
9084 (if (keymapp binding)
9085 (set-temporary-overlay-map binding)
9086 (let ((func (or binding
9087 (unless disable
9088 'orgstruct-error))))
9089 (when func
9090 (call-interactively func)))))
9091 (org-run-like-in-org-mode
9092 (lambda ()
9093 (interactive)
9094 (let* ,bindings
9095 (call-interactively ',fun)))))))))
9096 name))
9098 (defun org-contextualize-keys (alist contexts)
9099 "Return valid elements in ALIST depending on CONTEXTS.
9101 `org-agenda-custom-commands' or `org-capture-templates' are the
9102 values used for ALIST, and `org-agenda-custom-commands-contexts'
9103 or `org-capture-templates-contexts' are the associated contexts
9104 definitions."
9105 (let ((contexts
9106 ;; normalize contexts
9107 (mapcar
9108 (lambda(c) (cond ((listp (cadr c))
9109 (list (car c) (car c) (cadr c)))
9110 ((string= "" (cadr c))
9111 (list (car c) (car c) (caddr c)))
9112 (t c))) contexts))
9113 (a alist) c r s)
9114 ;; loop over all commands or templates
9115 (while (setq c (pop a))
9116 (let (vrules repl)
9117 (cond
9118 ((not (assoc (car c) contexts))
9119 (push c r))
9120 ((and (assoc (car c) contexts)
9121 (setq vrules (org-contextualize-validate-key
9122 (car c) contexts)))
9123 (mapc (lambda (vr)
9124 (when (not (equal (car vr) (cadr vr)))
9125 (setq repl vr))) vrules)
9126 (if (not repl) (push c r)
9127 (push (cadr repl) s)
9128 (push
9129 (cons (car c)
9130 (cdr (or (assoc (cadr repl) alist)
9131 (error "Undefined key `%s' as contextual replacement for `%s'"
9132 (cadr repl) (car c)))))
9133 r))))))
9134 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9135 (delq
9137 (delete-dups
9138 (mapcar (lambda (x)
9139 (let ((tpl (car x)))
9140 (when (not (delq
9142 (mapcar (lambda(y)
9143 (equal y tpl)) s))) x)))
9144 (reverse r))))))
9146 (defun org-contextualize-validate-key (key contexts)
9147 "Check CONTEXTS for agenda or capture KEY."
9148 (let (r rr res)
9149 (while (setq r (pop contexts))
9150 (mapc
9151 (lambda (rr)
9152 (when
9153 (and (equal key (car r))
9154 (if (functionp rr) (funcall rr)
9155 (or (and (eq (car rr) 'in-file)
9156 (buffer-file-name)
9157 (string-match (cdr rr) (buffer-file-name)))
9158 (and (eq (car rr) 'in-mode)
9159 (string-match (cdr rr) (symbol-name major-mode)))
9160 (and (eq (car rr) 'in-buffer)
9161 (string-match (cdr rr) (buffer-name)))
9162 (when (and (eq (car rr) 'not-in-file)
9163 (buffer-file-name))
9164 (not (string-match (cdr rr) (buffer-file-name))))
9165 (when (eq (car rr) 'not-in-mode)
9166 (not (string-match (cdr rr) (symbol-name major-mode))))
9167 (when (eq (car rr) 'not-in-buffer)
9168 (not (string-match (cdr rr) (buffer-name)))))))
9169 (push r res)))
9170 (car (last r))))
9171 (delete-dups (delq nil res))))
9173 (defun org-context-p (&rest contexts)
9174 "Check if local context is any of CONTEXTS.
9175 Possible values in the list of contexts are `table', `headline', and `item'."
9176 (let ((pos (point)))
9177 (goto-char (point-at-bol))
9178 (prog1 (or (and (memq 'table contexts)
9179 (looking-at "[ \t]*|"))
9180 (and (memq 'headline contexts)
9181 (looking-at org-outline-regexp))
9182 (and (memq 'item contexts)
9183 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9184 (and (memq 'item-body contexts)
9185 (org-in-item-p)))
9186 (goto-char pos))))
9188 (defun org-get-local-variables ()
9189 "Return a list of all local variables in an Org mode buffer."
9190 (let (varlist)
9191 (with-current-buffer (get-buffer-create "*Org tmp*")
9192 (erase-buffer)
9193 (org-mode)
9194 (setq varlist (buffer-local-variables)))
9195 (kill-buffer "*Org tmp*")
9196 (delq nil
9197 (mapcar
9198 (lambda (x)
9199 (setq x
9200 (if (symbolp x)
9201 (list x)
9202 (list (car x) (cdr x))))
9203 (if (and (not (get (car x) 'org-state))
9204 (string-match
9205 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9206 (symbol-name (car x))))
9207 x nil))
9208 varlist))))
9210 (defun org-clone-local-variables (from-buffer &optional regexp)
9211 "Clone local variables from FROM-BUFFER.
9212 Optional argument REGEXP selects variables to clone."
9213 (mapc
9214 (lambda (pair)
9215 (and (symbolp (car pair))
9216 (or (null regexp)
9217 (string-match regexp (symbol-name (car pair))))
9218 (set (make-local-variable (car pair))
9219 (cdr pair))))
9220 (buffer-local-variables from-buffer)))
9222 ;;;###autoload
9223 (defun org-run-like-in-org-mode (cmd)
9224 "Run a command, pretending that the current buffer is in Org-mode.
9225 This will temporarily bind local variables that are typically bound in
9226 Org-mode to the values they have in Org-mode, and then interactively
9227 call CMD."
9228 (org-load-modules-maybe)
9229 (unless org-local-vars
9230 (setq org-local-vars (org-get-local-variables)))
9231 (let (binds)
9232 (dolist (var org-local-vars)
9233 (when (or (not (boundp (car var)))
9234 (eq (symbol-value (car var))
9235 (default-value (car var))))
9236 (push (list (car var) `(quote ,(cadr var))) binds)))
9237 (eval `(let ,binds
9238 (call-interactively (quote ,cmd))))))
9240 ;;;; Archiving
9242 (defun org-get-category (&optional pos force-refresh)
9243 "Get the category applying to position POS."
9244 (save-match-data
9245 (if force-refresh (org-refresh-category-properties))
9246 (let ((pos (or pos (point))))
9247 (or (get-text-property pos 'org-category)
9248 (progn (org-refresh-category-properties)
9249 (get-text-property pos 'org-category))))))
9251 (defun org-refresh-category-properties ()
9252 "Refresh category text properties in the buffer."
9253 (let ((case-fold-search t)
9254 (inhibit-read-only t)
9255 (def-cat (cond
9256 ((null org-category)
9257 (if buffer-file-name
9258 (file-name-sans-extension
9259 (file-name-nondirectory buffer-file-name))
9260 "???"))
9261 ((symbolp org-category) (symbol-name org-category))
9262 (t org-category)))
9263 beg end cat pos optionp)
9264 (org-with-silent-modifications
9265 (save-excursion
9266 (save-restriction
9267 (widen)
9268 (goto-char (point-min))
9269 (put-text-property (point) (point-max) 'org-category def-cat)
9270 (while (re-search-forward
9271 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9272 (setq pos (match-end 0)
9273 optionp (equal (char-after (match-beginning 0)) ?#)
9274 cat (org-trim (match-string 2)))
9275 (if optionp
9276 (setq beg (point-at-bol) end (point-max))
9277 (org-back-to-heading t)
9278 (setq beg (point) end (org-end-of-subtree t t)))
9279 (put-text-property beg end 'org-category cat)
9280 (put-text-property beg end 'org-category-position beg)
9281 (goto-char pos)))))))
9283 (defun org-refresh-properties (dprop tprop)
9284 "Refresh buffer text properties.
9285 DPROP is the drawer property and TPROP is the corresponding text
9286 property to set."
9287 (let ((case-fold-search t)
9288 (inhibit-read-only t) p)
9289 (org-with-silent-modifications
9290 (save-excursion
9291 (save-restriction
9292 (widen)
9293 (goto-char (point-min))
9294 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9295 (setq p (org-match-string-no-properties 1))
9296 (save-excursion
9297 (org-back-to-heading t)
9298 (put-text-property
9299 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9302 ;;;; Link Stuff
9304 ;;; Link abbreviations
9306 (defun org-link-expand-abbrev (link)
9307 "Apply replacements as defined in `org-link-abbrev-alist'."
9308 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9309 (let* ((key (match-string 1 link))
9310 (as (or (assoc key org-link-abbrev-alist-local)
9311 (assoc key org-link-abbrev-alist)))
9312 (tag (and (match-end 2) (match-string 3 link)))
9313 rpl)
9314 (if (not as)
9315 link
9316 (setq rpl (cdr as))
9317 (cond
9318 ((symbolp rpl) (funcall rpl tag))
9319 ((string-match "%(\\([^)]+\\))" rpl)
9320 (replace-match
9321 (save-match-data
9322 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9323 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9324 ((string-match "%h" rpl)
9325 (replace-match (url-hexify-string (or tag "")) t t rpl))
9326 (t (concat rpl tag)))))
9327 link))
9329 ;;; Storing and inserting links
9331 (defvar org-insert-link-history nil
9332 "Minibuffer history for links inserted with `org-insert-link'.")
9334 (defvar org-stored-links nil
9335 "Contains the links stored with `org-store-link'.")
9337 (defvar org-store-link-plist nil
9338 "Plist with info about the most recently link created with `org-store-link'.")
9340 (defvar org-link-protocols nil
9341 "Link protocols added to Org-mode using `org-add-link-type'.")
9343 (defvar org-store-link-functions nil
9344 "List of functions that are called to create and store a link.
9345 Each function will be called in turn until one returns a non-nil
9346 value. Each function should check if it is responsible for creating
9347 this link (for example by looking at the major mode).
9348 If not, it must exit and return nil.
9349 If yes, it should return a non-nil value after a calling
9350 `org-store-link-props' with a list of properties and values.
9351 Special properties are:
9353 :type The link prefix, like \"http\". This must be given.
9354 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9355 This is obligatory as well.
9356 :description Optional default description for the second pair
9357 of brackets in an Org-mode link. The user can still change
9358 this when inserting this link into an Org-mode buffer.
9360 In addition to these, any additional properties can be specified
9361 and then used in capture templates.")
9363 (defun org-add-link-type (type &optional follow export)
9364 "Add TYPE to the list of `org-link-types'.
9365 Re-compute all regular expressions depending on `org-link-types'
9367 FOLLOW and EXPORT are two functions.
9369 FOLLOW should take the link path as the single argument and do whatever
9370 is necessary to follow the link, for example find a file or display
9371 a mail message.
9373 EXPORT should format the link path for export to one of the export formats.
9374 It should be a function accepting three arguments:
9376 path the path of the link, the text after the prefix (like \"http:\")
9377 desc the description of the link, if any, or a description added by
9378 org-export-normalize-links if there is none
9379 format the export format, a symbol like `html' or `latex' or `ascii'..
9381 The function may use the FORMAT information to return different values
9382 depending on the format. The return value will be put literally into
9383 the exported file. If the return value is nil, this means Org should
9384 do what it normally does with links which do not have EXPORT defined.
9386 Org-mode has a built-in default for exporting links. If you are happy with
9387 this default, there is no need to define an export function for the link
9388 type. For a simple example of an export function, see `org-bbdb.el'."
9389 (add-to-list 'org-link-types type t)
9390 (org-make-link-regexps)
9391 (if (assoc type org-link-protocols)
9392 (setcdr (assoc type org-link-protocols) (list follow export))
9393 (push (list type follow export) org-link-protocols)))
9395 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9396 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9398 ;;;###autoload
9399 (defun org-store-link (arg)
9400 "\\<org-mode-map>Store an org-link to the current location.
9401 This link is added to `org-stored-links' and can later be inserted
9402 into an org-buffer with \\[org-insert-link].
9404 For some link types, a prefix arg is interpreted.
9405 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9406 For file links, arg negates `org-context-in-file-links'.
9408 A double prefix arg force skipping storing functions that are not
9409 part of Org's core.
9411 A triple prefix arg force storing a link for each line in the
9412 active region."
9413 (interactive "P")
9414 (org-load-modules-maybe)
9415 (if (and (equal arg '(64)) (org-region-active-p))
9416 (save-excursion
9417 (let ((end (region-end)))
9418 (goto-char (region-beginning))
9419 (set-mark (point))
9420 (while (< (point-at-eol) end)
9421 (move-end-of-line 1) (activate-mark)
9422 (let (current-prefix-arg)
9423 (call-interactively 'org-store-link))
9424 (move-beginning-of-line 2)
9425 (set-mark (point)))))
9426 (org-with-limited-levels
9427 (setq org-store-link-plist nil)
9428 (let (link cpltxt desc description search
9429 txt custom-id agenda-link sfuns sfunsn)
9430 (cond
9432 ;; Store a link using an external link type
9433 ((and (not (equal arg '(16)))
9434 (setq sfuns
9435 (delq
9436 nil (mapcar (lambda (f)
9437 (let (fs) (if (funcall f) (push f fs))))
9438 org-store-link-functions))
9439 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9440 (or (and (cdr sfuns)
9441 (funcall (intern
9442 (completing-read
9443 "Which function for creating the link? "
9444 sfunsn t (car sfunsn)))))
9445 (funcall (caar sfuns)))
9446 (setq link (plist-get org-store-link-plist :link)
9447 desc (or (plist-get org-store-link-plist
9448 :description) link))))
9450 ;; Store a link from a source code buffer
9451 ((org-src-edit-buffer-p)
9452 (let (label gc)
9453 (while (or (not label)
9454 (save-excursion
9455 (save-restriction
9456 (widen)
9457 (goto-char (point-min))
9458 (re-search-forward
9459 (regexp-quote (format org-coderef-label-format label))
9460 nil t))))
9461 (when label (message "Label exists already") (sit-for 2))
9462 (setq label (read-string "Code line label: " label)))
9463 (end-of-line 1)
9464 (setq link (format org-coderef-label-format label))
9465 (setq gc (- 79 (length link)))
9466 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9467 (insert link)
9468 (setq link (concat "(" label ")") desc nil)))
9470 ;; We are in the agenda, link to referenced location
9471 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9472 (let ((m (or (get-text-property (point) 'org-hd-marker)
9473 (get-text-property (point) 'org-marker))))
9474 (when m
9475 (org-with-point-at m
9476 (setq agenda-link
9477 (if (org-called-interactively-p 'any)
9478 (call-interactively 'org-store-link)
9479 (org-store-link nil)))))))
9481 ((eq major-mode 'calendar-mode)
9482 (let ((cd (calendar-cursor-to-date)))
9483 (setq link
9484 (format-time-string
9485 (car org-time-stamp-formats)
9486 (apply 'encode-time
9487 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9488 nil nil nil))))
9489 (org-store-link-props :type "calendar" :date cd)))
9491 ((eq major-mode 'help-mode)
9492 (setq link (concat "help:" (save-excursion
9493 (goto-char (point-min))
9494 (looking-at "^[^ ]+")
9495 (match-string 0))))
9496 (org-store-link-props :type "help"))
9498 ((eq major-mode 'w3-mode)
9499 (setq cpltxt (if (and (buffer-name)
9500 (not (string-match "Untitled" (buffer-name))))
9501 (buffer-name)
9502 (url-view-url t))
9503 link (url-view-url t))
9504 (org-store-link-props :type "w3" :url (url-view-url t)))
9506 ((eq major-mode 'image-mode)
9507 (setq cpltxt (concat "file:"
9508 (abbreviate-file-name buffer-file-name))
9509 link cpltxt)
9510 (org-store-link-props :type "image" :file buffer-file-name))
9512 ;; In dired, store a link to the file of the current line
9513 ((eq major-mode 'dired-mode)
9514 (let ((file (dired-get-filename nil t)))
9515 (setq file (if file
9516 (abbreviate-file-name
9517 (expand-file-name (dired-get-filename nil t)))
9518 ;; otherwise, no file so use current directory.
9519 default-directory))
9520 (setq cpltxt (concat "file:" file)
9521 link cpltxt)))
9523 ((setq search (run-hook-with-args-until-success
9524 'org-create-file-search-functions))
9525 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9526 "::" search))
9527 (setq cpltxt (or description link)))
9529 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9530 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9531 (cond
9532 ;; Store a link using the target at point
9533 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9534 (setq cpltxt
9535 (concat "file:"
9536 (abbreviate-file-name
9537 (buffer-file-name (buffer-base-buffer)))
9538 "::" (match-string 1))
9539 link cpltxt))
9540 ((and (featurep 'org-id)
9541 (or (eq org-id-link-to-org-use-id t)
9542 (and (org-called-interactively-p 'any)
9543 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9544 (and (eq org-id-link-to-org-use-id
9545 'create-if-interactive-and-no-custom-id)
9546 (not custom-id))))
9547 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9548 ;; Store a link using the ID at point
9549 (setq link (condition-case nil
9550 (prog1 (org-id-store-link)
9551 (setq desc (plist-get org-store-link-plist
9552 :description)))
9553 (error
9554 ;; Probably before first headline, link only to file
9555 (concat "file:"
9556 (abbreviate-file-name
9557 (buffer-file-name (buffer-base-buffer))))))))
9559 ;; Just link to current headline
9560 (setq cpltxt (concat "file:"
9561 (abbreviate-file-name
9562 (buffer-file-name (buffer-base-buffer)))))
9563 ;; Add a context search string
9564 (when (org-xor org-context-in-file-links arg)
9565 (let* ((ee (org-element-at-point))
9566 (et (org-element-type ee))
9567 (ev (plist-get (cadr ee) :value))
9568 (ek (plist-get (cadr ee) :key))
9569 (eok (and (stringp ek) (string-match "name" ek))))
9570 (setq txt (cond
9571 ((org-at-heading-p) nil)
9572 ((and (eq et 'keyword) eok) ev)
9573 ((org-region-active-p)
9574 (buffer-substring (region-beginning) (region-end)))))
9575 (when (or (null txt) (string-match "\\S-" txt))
9576 (setq cpltxt
9577 (concat cpltxt "::"
9578 (condition-case nil
9579 (org-make-org-heading-search-string txt)
9580 (error "")))
9581 desc (or (and (eq et 'keyword) eok ev)
9582 (nth 4 (ignore-errors (org-heading-components)))
9583 "NONE")))))
9584 (if (string-match "::\\'" cpltxt)
9585 (setq cpltxt (substring cpltxt 0 -2)))
9586 (setq link cpltxt))))
9588 ((buffer-file-name (buffer-base-buffer))
9589 ;; Just link to this file here.
9590 (setq cpltxt (concat "file:"
9591 (abbreviate-file-name
9592 (buffer-file-name (buffer-base-buffer)))))
9593 ;; Add a context string.
9594 (when (org-xor org-context-in-file-links arg)
9595 (setq txt (if (org-region-active-p)
9596 (buffer-substring (region-beginning) (region-end))
9597 (buffer-substring (point-at-bol) (point-at-eol))))
9598 ;; Only use search option if there is some text.
9599 (when (string-match "\\S-" txt)
9600 (setq cpltxt
9601 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9602 desc "NONE")))
9603 (setq link cpltxt))
9605 ((org-called-interactively-p 'interactive)
9606 (user-error "No method for storing a link from this buffer"))
9608 (t (setq link nil)))
9610 ;; We're done setting link and desc, clean up
9611 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9612 (setq link (or link cpltxt)
9613 desc (or desc cpltxt))
9614 (cond ((equal desc "NONE") (setq desc nil))
9615 ((string-match org-bracket-link-analytic-regexp desc)
9616 (let ((d0 (match-string 3 desc))
9617 (p0 (match-string 5 desc)))
9618 (setq desc
9619 (replace-regexp-in-string
9620 org-bracket-link-regexp
9621 (concat (or p0 d0)
9622 (if (equal (length (match-string 0 desc))
9623 (length desc)) "*" "")) desc)))))
9625 ;; Return the link
9626 (if (not (and (or (org-called-interactively-p 'any)
9627 executing-kbd-macro) link))
9628 (or agenda-link (and link (org-make-link-string link desc)))
9629 (push (list link desc) org-stored-links)
9630 (message "Stored: %s" (or desc link))
9631 (when custom-id
9632 (setq link (concat "file:" (abbreviate-file-name
9633 (buffer-file-name)) "::#" custom-id))
9634 (push (list link desc) org-stored-links)))))))
9636 (defun org-store-link-props (&rest plist)
9637 "Store link properties, extract names and addresses."
9638 (let (x adr)
9639 (when (setq x (plist-get plist :from))
9640 (setq adr (mail-extract-address-components x))
9641 (setq plist (plist-put plist :fromname (car adr)))
9642 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9643 (when (setq x (plist-get plist :to))
9644 (setq adr (mail-extract-address-components x))
9645 (setq plist (plist-put plist :toname (car adr)))
9646 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9647 (let ((from (plist-get plist :from))
9648 (to (plist-get plist :to)))
9649 (when (and from to org-from-is-user-regexp)
9650 (setq plist
9651 (plist-put plist :fromto
9652 (if (string-match org-from-is-user-regexp from)
9653 (concat "to %t")
9654 (concat "from %f"))))))
9655 (setq org-store-link-plist plist))
9657 (defun org-add-link-props (&rest plist)
9658 "Add these properties to the link property list."
9659 (let (key value)
9660 (while plist
9661 (setq key (pop plist) value (pop plist))
9662 (setq org-store-link-plist
9663 (plist-put org-store-link-plist key value)))))
9665 (defun org-email-link-description (&optional fmt)
9666 "Return the description part of an email link.
9667 This takes information from `org-store-link-plist' and formats it
9668 according to FMT (default from `org-email-link-description-format')."
9669 (setq fmt (or fmt org-email-link-description-format))
9670 (let* ((p org-store-link-plist)
9671 (to (plist-get p :toaddress))
9672 (from (plist-get p :fromaddress))
9673 (table
9674 (list
9675 (cons "%c" (plist-get p :fromto))
9676 (cons "%F" (plist-get p :from))
9677 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9678 (cons "%T" (plist-get p :to))
9679 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9680 (cons "%s" (plist-get p :subject))
9681 (cons "%d" (plist-get p :date))
9682 (cons "%m" (plist-get p :message-id)))))
9683 (when (string-match "%c" fmt)
9684 ;; Check if the user wrote this message
9685 (if (and org-from-is-user-regexp from to
9686 (save-match-data (string-match org-from-is-user-regexp from)))
9687 (setq fmt (replace-match "to %t" t t fmt))
9688 (setq fmt (replace-match "from %f" t t fmt))))
9689 (org-replace-escapes fmt table)))
9691 (defun org-make-org-heading-search-string (&optional string)
9692 "Make search string for the current headline or STRING."
9693 (let ((s (or string
9694 (and (derived-mode-p 'org-mode)
9695 (save-excursion
9696 (org-back-to-heading t)
9697 (org-element-property :raw-value (org-element-at-point))))))
9698 (lines org-context-in-file-links))
9699 (or string (setq s (concat "*" s))) ; Add * for headlines
9700 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9701 (when (and string (integerp lines) (> lines 0))
9702 (let ((slines (org-split-string s "\n")))
9703 (when (< lines (length slines))
9704 (setq s (mapconcat
9705 'identity
9706 (reverse (nthcdr (- (length slines) lines)
9707 (reverse slines))) "\n")))))
9708 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9710 (defun org-make-link-string (link &optional description)
9711 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9712 (unless (string-match "\\S-" link)
9713 (error "Empty link"))
9714 (when (and description
9715 (stringp description)
9716 (not (string-match "\\S-" description)))
9717 (setq description nil))
9718 (when (stringp description)
9719 ;; Remove brackets from the description, they are fatal.
9720 (while (string-match "\\[" description)
9721 (setq description (replace-match "{" t t description)))
9722 (while (string-match "\\]" description)
9723 (setq description (replace-match "}" t t description))))
9724 (when (equal link description)
9725 ;; No description needed, it is identical
9726 (setq description nil))
9727 (when (and (not description)
9728 (not (string-match (org-image-file-name-regexp) link))
9729 (not (equal link (org-link-escape link))))
9730 (setq description (org-extract-attributes link)))
9731 (setq link
9732 (cond ((string-match (org-image-file-name-regexp) link) link)
9733 ((string-match org-link-types-re link)
9734 (concat (match-string 1 link)
9735 (org-link-escape (substring link (match-end 1)))))
9736 (t (org-link-escape link))))
9737 (concat "[[" link "]"
9738 (if description (concat "[" description "]") "")
9739 "]"))
9741 (defconst org-link-escape-chars
9742 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9743 "List of characters that should be escaped in link.
9744 This is the list that is used for internal purposes.")
9746 (defconst org-link-escape-chars-browser
9747 '(?\ ?\")
9748 "List of escapes for characters that are problematic in links.
9749 This is the list that is used before handing over to the browser.")
9751 (defun org-link-escape (text &optional table merge)
9752 "Return percent escaped representation of TEXT.
9753 TEXT is a string with the text to escape.
9754 Optional argument TABLE is a list with characters that should be
9755 escaped. When nil, `org-link-escape-chars' is used.
9756 If optional argument MERGE is set, merge TABLE into
9757 `org-link-escape-chars'."
9758 (cond
9759 ((and table merge)
9760 (mapc (lambda (defchr)
9761 (unless (member defchr table)
9762 (setq table (cons defchr table)))) org-link-escape-chars))
9763 ((null table)
9764 (setq table org-link-escape-chars)))
9765 (mapconcat
9766 (lambda (char)
9767 (if (or (member char table)
9768 (and (or (< char 32) (= char 37) (> char 126))
9769 org-url-hexify-p))
9770 (mapconcat (lambda (sequence-element)
9771 (format "%%%.2X" sequence-element))
9772 (or (encode-coding-char char 'utf-8)
9773 (error "Unable to percent escape character: %s"
9774 (char-to-string char))) "")
9775 (char-to-string char))) text ""))
9777 (defun org-link-unescape (str)
9778 "Unhex hexified Unicode strings as returned from the JavaScript function
9779 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9780 (unless (and (null str) (string= "" str))
9781 (let ((pos 0) (case-fold-search t) unhexed)
9782 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9783 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9784 (setq str (replace-match unhexed t t str))
9785 (setq pos (+ pos (length unhexed))))))
9786 str)
9788 (defun org-link-unescape-compound (hex)
9789 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9790 Note: this function also decodes single byte encodings like
9791 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9792 (save-match-data
9793 (let* ((bytes (cdr (split-string hex "%")))
9794 (ret "")
9795 (eat 0)
9796 (sum 0))
9797 (while bytes
9798 (let* ((val (string-to-number (pop bytes) 16))
9799 (shift-xor
9800 (if (= 0 eat)
9801 (cond
9802 ((>= val 252) (cons 6 252))
9803 ((>= val 248) (cons 5 248))
9804 ((>= val 240) (cons 4 240))
9805 ((>= val 224) (cons 3 224))
9806 ((>= val 192) (cons 2 192))
9807 (t (cons 0 0)))
9808 (cons 6 128))))
9809 (if (>= val 192) (setq eat (car shift-xor)))
9810 (setq val (logxor val (cdr shift-xor)))
9811 (setq sum (+ (lsh sum (car shift-xor)) val))
9812 (if (> eat 0) (setq eat (- eat 1)))
9813 (cond
9814 ((= 0 eat) ;multi byte
9815 (setq ret (concat ret (org-char-to-string sum)))
9816 (setq sum 0))
9817 ((not bytes) ; single byte(s)
9818 (setq ret (org-link-unescape-single-byte-sequence hex))))
9819 )) ;; end (while bytes
9820 ret )))
9822 (defun org-link-unescape-single-byte-sequence (hex)
9823 "Unhexify hex-encoded single byte character sequences."
9824 (mapconcat (lambda (byte)
9825 (char-to-string (string-to-number byte 16)))
9826 (cdr (split-string hex "%")) ""))
9828 (defun org-xor (a b)
9829 "Exclusive or."
9830 (if a (not b) b))
9832 (defun org-fixup-message-id-for-http (s)
9833 "Replace special characters in a message id, so it can be used in an http query."
9834 (when (string-match "%" s)
9835 (setq s (mapconcat (lambda (c)
9836 (if (eq c ?%)
9837 "%25"
9838 (char-to-string c)))
9839 s "")))
9840 (while (string-match "<" s)
9841 (setq s (replace-match "%3C" t t s)))
9842 (while (string-match ">" s)
9843 (setq s (replace-match "%3E" t t s)))
9844 (while (string-match "@" s)
9845 (setq s (replace-match "%40" t t s)))
9848 (defun org-link-prettify (link)
9849 "Return a human-readable representation of LINK.
9850 The car of LINK must be a raw link the cdr of LINK must be either
9851 a link description or nil."
9852 (let ((desc (or (cadr link) "<no description>")))
9853 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9854 "<" (car link) ">")))
9856 ;;;###autoload
9857 (defun org-insert-link-global ()
9858 "Insert a link like Org-mode does.
9859 This command can be called in any mode to insert a link in Org-mode syntax."
9860 (interactive)
9861 (org-load-modules-maybe)
9862 (org-run-like-in-org-mode 'org-insert-link))
9864 (defun org-insert-all-links (&optional keep)
9865 "Insert all links in `org-stored-links'."
9866 (interactive "P")
9867 (let ((links (copy-sequence org-stored-links)) l)
9868 (while (setq l (if keep (pop links) (pop org-stored-links)))
9869 (insert "- ")
9870 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9871 (insert "\n"))))
9873 (defun org-link-fontify-links-to-this-file ()
9874 "Fontify links to the current file in `org-stored-links'."
9875 (let ((f (buffer-file-name)) a b)
9876 (setq a (mapcar (lambda(l)
9877 (let ((ll (car l)))
9878 (when (and (string-match "^file:\\(.+\\)::" ll)
9879 (equal f (expand-file-name (match-string 1 ll))))
9880 ll)))
9881 org-stored-links))
9882 (when (featurep 'org-id)
9883 (setq b (mapcar (lambda(l)
9884 (let ((ll (car l)))
9885 (when (and (string-match "^id:\\(.+\\)$" ll)
9886 (equal f (expand-file-name
9887 (or (org-id-find-id-file
9888 (match-string 1 ll)) ""))))
9889 ll)))
9890 org-stored-links)))
9891 (mapcar (lambda(l)
9892 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9893 (delq nil (append a b)))))
9895 (defvar org-link-links-in-this-file nil)
9896 (defun org-insert-link (&optional complete-file link-location default-description)
9897 "Insert a link. At the prompt, enter the link.
9899 Completion can be used to insert any of the link protocol prefixes like
9900 http or ftp in use.
9902 The history can be used to select a link previously stored with
9903 `org-store-link'. When the empty string is entered (i.e. if you just
9904 press RET at the prompt), the link defaults to the most recently
9905 stored link. As SPC triggers completion in the minibuffer, you need to
9906 use M-SPC or C-q SPC to force the insertion of a space character.
9908 You will also be prompted for a description, and if one is given, it will
9909 be displayed in the buffer instead of the link.
9911 If there is already a link at point, this command will allow you to edit link
9912 and description parts.
9914 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9915 be selected using completion. The path to the file will be relative to the
9916 current directory if the file is in the current directory or a subdirectory.
9917 Otherwise, the link will be the absolute path as completed in the minibuffer
9918 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9919 option `org-link-file-path-type'.
9921 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9922 the current directory or below.
9924 With three \\[universal-argument] prefixes, negate the meaning of
9925 `org-keep-stored-link-after-insertion'.
9927 If `org-make-link-description-function' is non-nil, this function will be
9928 called with the link target, and the result will be the default
9929 link description.
9931 If the LINK-LOCATION parameter is non-nil, this value will be
9932 used as the link location instead of reading one interactively.
9934 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9935 be used as the default description."
9936 (interactive "P")
9937 (let* ((wcf (current-window-configuration))
9938 (origbuf (current-buffer))
9939 (region (if (org-region-active-p)
9940 (buffer-substring (region-beginning) (region-end))))
9941 (remove (and region (list (region-beginning) (region-end))))
9942 (desc region)
9943 tmphist ; byte-compile incorrectly complains about this
9944 (link link-location)
9945 (abbrevs org-link-abbrev-alist-local)
9946 entry file all-prefixes auto-desc)
9947 (cond
9948 (link-location) ; specified by arg, just use it.
9949 ((org-in-regexp org-bracket-link-regexp 1)
9950 ;; We do have a link at point, and we are going to edit it.
9951 (setq remove (list (match-beginning 0) (match-end 0)))
9952 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9953 (setq link (read-string "Link: "
9954 (org-link-unescape
9955 (org-match-string-no-properties 1)))))
9956 ((or (org-in-regexp org-angle-link-re)
9957 (org-in-regexp org-plain-link-re))
9958 ;; Convert to bracket link
9959 (setq remove (list (match-beginning 0) (match-end 0))
9960 link (read-string "Link: "
9961 (org-remove-angle-brackets (match-string 0)))))
9962 ((member complete-file '((4) (16)))
9963 ;; Completing read for file names.
9964 (setq link (org-file-complete-link complete-file)))
9966 ;; Read link, with completion for stored links.
9967 (org-link-fontify-links-to-this-file)
9968 (org-switch-to-buffer-other-window "*Org Links*")
9969 (with-current-buffer "*Org Links*"
9970 (erase-buffer)
9971 (insert "Insert a link.
9972 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9973 (when org-stored-links
9974 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9975 (insert (mapconcat 'org-link-prettify
9976 (reverse org-stored-links) "\n")))
9977 (goto-char (point-min)))
9978 (let ((cw (selected-window)))
9979 (select-window (get-buffer-window "*Org Links*" 'visible))
9980 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9981 (unless (pos-visible-in-window-p (point-max))
9982 (org-fit-window-to-buffer))
9983 (and (window-live-p cw) (select-window cw)))
9984 ;; Fake a link history, containing the stored links.
9985 (setq tmphist (append (mapcar 'car org-stored-links)
9986 org-insert-link-history))
9987 (setq all-prefixes (append (mapcar 'car abbrevs)
9988 (mapcar 'car org-link-abbrev-alist)
9989 org-link-types))
9990 (unwind-protect
9991 (progn
9992 (setq link
9993 (org-completing-read
9994 "Link: "
9995 (append
9996 (mapcar (lambda (x) (concat x ":"))
9997 all-prefixes)
9998 (mapcar 'car org-stored-links))
9999 nil nil nil
10000 'tmphist
10001 (caar org-stored-links)))
10002 (if (not (string-match "\\S-" link))
10003 (user-error "No link selected"))
10004 (mapc (lambda(l)
10005 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10006 org-stored-links)
10007 (if (or (member link all-prefixes)
10008 (and (equal ":" (substring link -1))
10009 (member (substring link 0 -1) all-prefixes)
10010 (setq link (substring link 0 -1))))
10011 (setq link (with-current-buffer origbuf
10012 (org-link-try-special-completion link)))))
10013 (set-window-configuration wcf)
10014 (kill-buffer "*Org Links*"))
10015 (setq entry (assoc link org-stored-links))
10016 (or entry (push link org-insert-link-history))
10017 (setq desc (or desc (nth 1 entry)))))
10019 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10020 (not org-keep-stored-link-after-insertion))
10021 (setq org-stored-links (delq (assoc link org-stored-links)
10022 org-stored-links)))
10024 (if (and (string-match org-plain-link-re link)
10025 (not (string-match org-ts-regexp link)))
10026 ;; URL-like link, normalize the use of angular brackets.
10027 (setq link (org-remove-angle-brackets link)))
10029 ;; Check if we are linking to the current file with a search
10030 ;; option If yes, simplify the link by using only the search
10031 ;; option.
10032 (when (and buffer-file-name
10033 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10034 (let* ((path (match-string 1 link))
10035 (case-fold-search nil)
10036 (search (match-string 2 link)))
10037 (save-match-data
10038 (if (equal (file-truename buffer-file-name) (file-truename path))
10039 ;; We are linking to this same file, with a search option
10040 (setq link search)))))
10042 ;; Check if we can/should use a relative path. If yes, simplify the link
10043 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10044 (let* ((type (match-string 1 link))
10045 (path (match-string 2 link))
10046 (origpath path)
10047 (case-fold-search nil))
10048 (cond
10049 ((or (eq org-link-file-path-type 'absolute)
10050 (equal complete-file '(16)))
10051 (setq path (abbreviate-file-name (expand-file-name path))))
10052 ((eq org-link-file-path-type 'noabbrev)
10053 (setq path (expand-file-name path)))
10054 ((eq org-link-file-path-type 'relative)
10055 (setq path (file-relative-name path)))
10057 (save-match-data
10058 (if (string-match (concat "^" (regexp-quote
10059 (expand-file-name
10060 (file-name-as-directory
10061 default-directory))))
10062 (expand-file-name path))
10063 ;; We are linking a file with relative path name.
10064 (setq path (substring (expand-file-name path)
10065 (match-end 0)))
10066 (setq path (abbreviate-file-name (expand-file-name path)))))))
10067 (setq link (concat type path))
10068 (if (equal desc origpath)
10069 (setq desc path))))
10071 (if org-make-link-description-function
10072 (setq desc
10073 (or (condition-case nil
10074 (funcall org-make-link-description-function link desc)
10075 (error (progn (message "Can't get link description from `%s'"
10076 (symbol-name org-make-link-description-function))
10077 (sit-for 2) nil)))
10078 (read-string "Description: " default-description)))
10079 (if default-description (setq desc default-description)
10080 (setq desc (or (and auto-desc desc)
10081 (read-string "Description: " desc)))))
10083 (unless (string-match "\\S-" desc) (setq desc nil))
10084 (if remove (apply 'delete-region remove))
10085 (insert (org-make-link-string link desc))))
10087 (defun org-link-try-special-completion (type)
10088 "If there is completion support for link type TYPE, offer it."
10089 (let ((fun (intern (concat "org-" type "-complete-link"))))
10090 (if (functionp fun)
10091 (funcall fun)
10092 (read-string "Link (no completion support): " (concat type ":")))))
10094 (defun org-file-complete-link (&optional arg)
10095 "Create a file link using completion."
10096 (let (file link)
10097 (setq file (org-iread-file-name "File: "))
10098 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10099 (pwd1 (file-name-as-directory (abbreviate-file-name
10100 (expand-file-name ".")))))
10101 (cond
10102 ((equal arg '(16))
10103 (setq link (concat
10104 "file:"
10105 (abbreviate-file-name (expand-file-name file)))))
10106 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10107 (setq link (concat "file:" (match-string 1 file))))
10108 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10109 (expand-file-name file))
10110 (setq link (concat
10111 "file:" (match-string 1 (expand-file-name file)))))
10112 (t (setq link (concat "file:" file)))))
10113 link))
10115 (defun org-iread-file-name (&rest args)
10116 "Read-file-name using `ido-mode' speedup if available.
10117 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10118 See `read-file-name' for a description of parameters."
10119 (org-without-partial-completion
10120 (if (and org-completion-use-ido
10121 (fboundp 'ido-read-file-name)
10122 (boundp 'ido-mode) ido-mode
10123 (listp (second args)))
10124 (let ((ido-enter-matching-directory nil))
10125 (apply 'ido-read-file-name args))
10126 (apply 'read-file-name args))))
10128 (defun org-completing-read (&rest args)
10129 "Completing-read with SPACE being a normal character."
10130 (let ((enable-recursive-minibuffers t)
10131 (minibuffer-local-completion-map
10132 (copy-keymap minibuffer-local-completion-map)))
10133 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10134 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10135 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10136 (apply 'org-icompleting-read args)))
10138 (defun org-completing-read-no-i (&rest args)
10139 (let (org-completion-use-ido org-completion-use-iswitchb)
10140 (apply 'org-completing-read args)))
10142 (defun org-iswitchb-completing-read (prompt choices &rest args)
10143 "Use iswitch as a completing-read replacement to choose from choices.
10144 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10145 from."
10146 (let* ((iswitchb-use-virtual-buffers nil)
10147 (iswitchb-make-buflist-hook
10148 (lambda ()
10149 (setq iswitchb-temp-buflist choices))))
10150 (iswitchb-read-buffer prompt)))
10152 (defun org-icompleting-read (&rest args)
10153 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10154 (org-without-partial-completion
10155 (if (and org-completion-use-ido
10156 (fboundp 'ido-completing-read)
10157 (boundp 'ido-mode) ido-mode
10158 (listp (second args)))
10159 (let ((ido-enter-matching-directory nil))
10160 (apply 'ido-completing-read (concat (car args))
10161 (if (consp (car (nth 1 args)))
10162 (mapcar 'car (nth 1 args))
10163 (nth 1 args))
10164 (cddr args)))
10165 (if (and org-completion-use-iswitchb
10166 (boundp 'iswitchb-mode) iswitchb-mode
10167 (listp (second args)))
10168 (apply 'org-iswitchb-completing-read (concat (car args))
10169 (if (consp (car (nth 1 args)))
10170 (mapcar 'car (nth 1 args))
10171 (nth 1 args))
10172 (cddr args))
10173 (apply 'completing-read args)))))
10175 (defun org-extract-attributes (s)
10176 "Extract the attributes cookie from a string and set as text property."
10177 (let (a attr (start 0) key value)
10178 (save-match-data
10179 (when (string-match "{{\\([^}]+\\)}}$" s)
10180 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10181 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10182 (setq key (match-string 1 a) value (match-string 2 a)
10183 start (match-end 0)
10184 attr (plist-put attr (intern key) value))))
10185 (org-add-props s nil 'org-attr attr))
10188 ;;; Opening/following a link
10190 (defvar org-link-search-failed nil)
10192 (defvar org-open-link-functions nil
10193 "Hook for functions finding a plain text link.
10194 These functions must take a single argument, the link content.
10195 They will be called for links that look like [[link text][description]]
10196 when LINK TEXT does not have a protocol like \"http:\" and does not look
10197 like a filename (e.g. \"./blue.png\").
10199 These functions will be called *before* Org attempts to resolve the
10200 link by doing text searches in the current buffer - so if you want a
10201 link \"[[target]]\" to still find \"<<target>>\", your function should
10202 handle this as a special case.
10204 When the function does handle the link, it must return a non-nil value.
10205 If it decides that it is not responsible for this link, it must return
10206 nil to indicate that that Org-mode can continue with other options
10207 like exact and fuzzy text search.")
10209 (defun org-next-link (&optional search-backward)
10210 "Move forward to the next link.
10211 If the link is in hidden text, expose it."
10212 (interactive "P")
10213 (when (and org-link-search-failed (eq this-command last-command))
10214 (goto-char (point-min))
10215 (message "Link search wrapped back to beginning of buffer"))
10216 (setq org-link-search-failed nil)
10217 (let* ((pos (point))
10218 (ct (org-context))
10219 (a (assoc :link ct))
10220 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10221 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10222 ((looking-at org-any-link-re)
10223 ;; Don't stay stuck at link without an org-link face
10224 (forward-char (if search-backward -1 1))))
10225 (if (funcall srch-fun org-any-link-re nil t)
10226 (progn
10227 (goto-char (match-beginning 0))
10228 (if (outline-invisible-p) (org-show-context)))
10229 (goto-char pos)
10230 (setq org-link-search-failed t)
10231 (message "No further link found"))))
10233 (defun org-previous-link ()
10234 "Move backward to the previous link.
10235 If the link is in hidden text, expose it."
10236 (interactive)
10237 (funcall 'org-next-link t))
10239 (defun org-translate-link (s)
10240 "Translate a link string if a translation function has been defined."
10241 (if (and org-link-translation-function
10242 (fboundp org-link-translation-function)
10243 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10244 (progn
10245 (setq s (funcall org-link-translation-function
10246 (match-string 1 s) (match-string 2 s)))
10247 (concat (car s) ":" (cdr s)))
10250 (defun org-translate-link-from-planner (type path)
10251 "Translate a link from Emacs Planner syntax so that Org can follow it.
10252 This is still an experimental function, your mileage may vary."
10253 (cond
10254 ((member type '("http" "https" "news" "ftp"))
10255 ;; standard Internet links are the same.
10256 nil)
10257 ((and (equal type "irc") (string-match "^//" path))
10258 ;; Planner has two / at the beginning of an irc link, we have 1.
10259 ;; We should have zero, actually....
10260 (setq path (substring path 1)))
10261 ((and (equal type "lisp") (string-match "^/" path))
10262 ;; Planner has a slash, we do not.
10263 (setq type "elisp" path (substring path 1)))
10264 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10265 ;; A typical message link. Planner has the id after the final slash,
10266 ;; we separate it with a hash mark
10267 (setq path (concat (match-string 1 path) "#"
10268 (org-remove-angle-brackets (match-string 2 path))))))
10269 (cons type path))
10271 (defun org-find-file-at-mouse (ev)
10272 "Open file link or URL at mouse."
10273 (interactive "e")
10274 (mouse-set-point ev)
10275 (org-open-at-point 'in-emacs))
10277 (defun org-open-at-mouse (ev)
10278 "Open file link or URL at mouse.
10279 See the docstring of `org-open-file' for details."
10280 (interactive "e")
10281 (mouse-set-point ev)
10282 (if (eq major-mode 'org-agenda-mode)
10283 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10284 (org-open-at-point))
10286 (defvar org-window-config-before-follow-link nil
10287 "The window configuration before following a link.
10288 This is saved in case the need arises to restore it.")
10290 (defvar org-open-link-marker (make-marker)
10291 "Marker pointing to the location where `org-open-at-point; was called.")
10293 ;;;###autoload
10294 (defun org-open-at-point-global ()
10295 "Follow a link like Org-mode does.
10296 This command can be called in any mode to follow a link that has
10297 Org-mode syntax."
10298 (interactive)
10299 (org-run-like-in-org-mode 'org-open-at-point))
10301 ;;;###autoload
10302 (defun org-open-link-from-string (s &optional arg reference-buffer)
10303 "Open a link in the string S, as if it was in Org-mode."
10304 (interactive "sLink: \nP")
10305 (let ((reference-buffer (or reference-buffer (current-buffer))))
10306 (with-temp-buffer
10307 (let ((org-inhibit-startup (not reference-buffer)))
10308 (org-mode)
10309 (insert s)
10310 (goto-char (point-min))
10311 (when reference-buffer
10312 (setq org-link-abbrev-alist-local
10313 (with-current-buffer reference-buffer
10314 org-link-abbrev-alist-local)))
10315 (org-open-at-point arg reference-buffer)))))
10317 (defvar org-open-at-point-functions nil
10318 "Hook that is run when following a link at point.
10320 Functions in this hook must return t if they identify and follow
10321 a link at point. If they don't find anything interesting at point,
10322 they must return nil.")
10324 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10325 (defun org-open-at-point (&optional arg reference-buffer)
10326 "Open link at or after point.
10327 If there is no link at point, this function will search forward up to
10328 the end of the current line.
10329 Normally, files will be opened by an appropriate application. If the
10330 optional prefix argument ARG is non-nil, Emacs will visit the file.
10331 With a double prefix argument, try to open outside of Emacs, in the
10332 application the system uses for this file type."
10333 (interactive "P")
10334 ;; if in a code block, then open the block's results
10335 (unless (call-interactively #'org-babel-open-src-block-result)
10336 (org-load-modules-maybe)
10337 (move-marker org-open-link-marker (point))
10338 (setq org-window-config-before-follow-link (current-window-configuration))
10339 (org-remove-occur-highlights nil nil t)
10340 (cond
10341 ((and (org-at-heading-p)
10342 (not (org-at-timestamp-p t))
10343 (not (org-in-regexp
10344 (concat org-plain-link-re "\\|"
10345 org-bracket-link-regexp "\\|"
10346 org-angle-link-re "\\|"
10347 "[ \t]:[^ \t\n]+:[ \t]*$")))
10348 (not (get-text-property (point) 'org-linked-text)))
10349 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10350 (lk0 (car lkall))
10351 (lk (if (stringp lk0) (list lk0) lk0))
10352 (lkend (cdr lkall)))
10353 (mapcar (lambda(l)
10354 (search-forward l nil lkend)
10355 (goto-char (match-beginning 0))
10356 (org-open-at-point))
10357 lk))
10358 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10359 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10360 ((and (org-at-timestamp-p t)
10361 (not (org-in-regexp org-bracket-link-regexp)))
10362 (org-follow-timestamp-link))
10363 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10364 (not (org-in-regexp org-any-link-re)))
10365 (org-footnote-action))
10367 (let (type path link line search (pos (point)))
10368 (catch 'match
10369 (save-excursion
10370 (skip-chars-forward "^]\n\r")
10371 (when (org-in-regexp org-bracket-link-regexp 1)
10372 (setq link (org-extract-attributes
10373 (org-link-unescape (org-match-string-no-properties 1))))
10374 (while (string-match " *\n *" link)
10375 (setq link (replace-match " " t t link)))
10376 (setq link (org-link-expand-abbrev link))
10377 (cond
10378 ((or (file-name-absolute-p link)
10379 (string-match "^\\.\\.?/" link))
10380 (setq type "file" path link))
10381 ((string-match org-link-re-with-space3 link)
10382 (setq type (match-string 1 link) path (match-string 2 link)))
10383 ((string-match "^help:+\\(.+\\)" link)
10384 (setq type "help" path (match-string 1 link)))
10385 (t (setq type "thisfile" path link)))
10386 (throw 'match t)))
10388 (when (get-text-property (point) 'org-linked-text)
10389 (setq type "thisfile"
10390 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10391 (1+ (point)) (point))
10392 path (buffer-substring
10393 (or (previous-single-property-change pos 'org-linked-text)
10394 (point-min))
10395 (or (next-single-property-change pos 'org-linked-text)
10396 (point-max)))
10397 ;; Ensure we will search for a <<<radio>>> link, not
10398 ;; a simple reference like <<ref>>
10399 path (concat "<" path))
10400 (throw 'match t))
10402 (save-excursion
10403 (when (or (org-in-regexp org-angle-link-re)
10404 (let ((match (org-in-regexp org-plain-link-re)))
10405 ;; Check a plain link is not within a bracket link
10406 (and match
10407 (save-excursion
10408 (progn
10409 (goto-char (car match))
10410 (not (org-in-regexp org-bracket-link-regexp))))))
10411 (let ((line_ending (save-excursion (end-of-line) (point))))
10412 ;; We are in a line before a plain or bracket link
10413 (or (re-search-forward org-plain-link-re line_ending t)
10414 (re-search-forward org-bracket-link-regexp line_ending t))))
10415 (setq type (match-string 1)
10416 path (org-link-unescape (match-string 2)))
10417 (throw 'match t)))
10418 (save-excursion
10419 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10420 (setq type "tags"
10421 path (match-string 1))
10422 (while (string-match ":" path)
10423 (setq path (replace-match "+" t t path)))
10424 (throw 'match t)))
10425 (when (org-in-regexp "<\\([^><\n]+\\)>")
10426 (setq type "tree-match"
10427 path (match-string 1))
10428 (throw 'match t)))
10429 (unless path
10430 (user-error "No link found"))
10432 ;; switch back to reference buffer
10433 ;; needed when if called in a temporary buffer through
10434 ;; org-open-link-from-string
10435 (with-current-buffer (or reference-buffer (current-buffer))
10437 ;; Remove any trailing spaces in path
10438 (if (string-match " +\\'" path)
10439 (setq path (replace-match "" t t path)))
10440 (if (and org-link-translation-function
10441 (fboundp org-link-translation-function))
10442 ;; Check if we need to translate the link
10443 (let ((tmp (funcall org-link-translation-function type path)))
10444 (setq type (car tmp) path (cdr tmp))))
10446 (cond
10448 ((assoc type org-link-protocols)
10449 (funcall (nth 1 (assoc type org-link-protocols)) path))
10451 ((equal type "help")
10452 (let ((f-or-v (intern path)))
10453 (cond ((fboundp f-or-v)
10454 (describe-function f-or-v))
10455 ((boundp f-or-v)
10456 (describe-variable f-or-v))
10457 (t (error "Not a known function or variable")))))
10459 ((equal type "mailto")
10460 (let ((cmd (car org-link-mailto-program))
10461 (args (cdr org-link-mailto-program)) args1
10462 (address path) (subject "") a)
10463 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10464 (setq address (match-string 1 path)
10465 subject (org-link-escape (match-string 2 path))))
10466 (while args
10467 (cond
10468 ((not (stringp (car args))) (push (pop args) args1))
10469 (t (setq a (pop args))
10470 (if (string-match "%a" a)
10471 (setq a (replace-match address t t a)))
10472 (if (string-match "%s" a)
10473 (setq a (replace-match subject t t a)))
10474 (push a args1))))
10475 (apply cmd (nreverse args1))))
10477 ((member type '("http" "https" "ftp" "news"))
10478 (browse-url
10479 (concat type ":"
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 ((string= type "doi")
10488 (browse-url
10489 (concat org-doi-server-url
10490 (if (org-string-match-p
10491 (concat "[[:nonascii:]"
10492 org-link-escape-chars-browser "]")
10493 path)
10494 (org-link-escape path org-link-escape-chars-browser)
10495 path))))
10497 ((member type '("message"))
10498 (browse-url (concat type ":" path)))
10500 ((string= type "tags")
10501 (org-tags-view arg path))
10503 ((string= type "tree-match")
10504 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10506 ((string= type "file")
10507 (if (string-match "::\\([0-9]+\\)\\'" path)
10508 (setq line (string-to-number (match-string 1 path))
10509 path (substring path 0 (match-beginning 0)))
10510 (if (string-match "::\\(.+\\)\\'" path)
10511 (setq search (match-string 1 path)
10512 path (substring path 0 (match-beginning 0)))))
10513 (if (string-match "[*?{]" (file-name-nondirectory path))
10514 (dired path)
10515 (org-open-file path arg line search)))
10517 ((string= type "shell")
10518 (let ((buf (generate-new-buffer "*Org Shell Output"))
10519 (cmd path))
10520 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10521 (string-match org-confirm-shell-link-not-regexp cmd))
10522 (not org-confirm-shell-link-function)
10523 (funcall org-confirm-shell-link-function
10524 (format "Execute \"%s\" in shell? "
10525 (org-add-props cmd nil
10526 'face 'org-warning))))
10527 (progn
10528 (message "Executing %s" cmd)
10529 (shell-command cmd buf)
10530 (if (featurep 'midnight)
10531 (setq clean-buffer-list-kill-buffer-names
10532 (cons buf clean-buffer-list-kill-buffer-names))))
10533 (error "Abort"))))
10535 ((string= type "elisp")
10536 (let ((cmd path))
10537 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10538 (string-match org-confirm-elisp-link-not-regexp cmd))
10539 (not org-confirm-elisp-link-function)
10540 (funcall org-confirm-elisp-link-function
10541 (format "Execute \"%s\" as elisp? "
10542 (org-add-props cmd nil
10543 'face 'org-warning))))
10544 (message "%s => %s" cmd
10545 (if (equal (string-to-char cmd) ?\()
10546 (eval (read cmd))
10547 (call-interactively (read cmd))))
10548 (error "Abort"))))
10550 ((and (string= type "thisfile")
10551 (or (run-hook-with-args-until-success
10552 'org-open-link-functions path)
10553 (and link
10554 (string-match "^id:" link)
10555 (or (featurep 'org-id) (require 'org-id))
10556 (progn
10557 (funcall (nth 1 (assoc "id" org-link-protocols))
10558 (substring path 3))
10559 t)))))
10561 ((string= type "thisfile")
10562 (if arg
10563 (switch-to-buffer-other-window
10564 (org-get-buffer-for-internal-link (current-buffer)))
10565 (org-mark-ring-push))
10566 (let ((cmd `(org-link-search
10567 ,path
10568 ,(cond ((equal arg '(4)) ''occur)
10569 ((equal arg '(16)) ''org-occur))
10570 ,pos)))
10571 (condition-case nil (let ((org-link-search-inhibit-query t))
10572 (eval cmd))
10573 (error (progn (widen) (eval cmd))))))
10575 (t (browse-url-at-point)))))))
10576 (move-marker org-open-link-marker nil)
10577 (run-hook-with-args 'org-follow-link-hook)))
10579 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10580 "Offer links in the current entry and return the selected link.
10581 If there is only one link, return it.
10582 If NTH is an integer, return the NTH link found.
10583 If ZERO is a string, check also this string for a link, and if
10584 there is one, return it."
10585 (with-current-buffer buffer
10586 (save-excursion
10587 (save-restriction
10588 (widen)
10589 (goto-char marker)
10590 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10591 "\\(" org-angle-link-re "\\)\\|"
10592 "\\(" org-plain-link-re "\\)"))
10593 (cnt ?0)
10594 (in-emacs (if (integerp nth) nil nth))
10595 have-zero end links link c)
10596 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10597 (push (match-string 0 zero) links)
10598 (setq cnt (1- cnt) have-zero t))
10599 (save-excursion
10600 (org-back-to-heading t)
10601 (setq end (save-excursion (outline-next-heading) (point)))
10602 (while (re-search-forward re end t)
10603 (push (match-string 0) links))
10604 (setq links (org-uniquify (reverse links))))
10605 (cond
10606 ((null links)
10607 (message "No links"))
10608 ((equal (length links) 1)
10609 (setq link (car links)))
10610 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10611 (setq link (nth (if have-zero nth (1- nth)) links)))
10612 (t ; we have to select a link
10613 (save-excursion
10614 (save-window-excursion
10615 (delete-other-windows)
10616 (with-output-to-temp-buffer "*Select Link*"
10617 (mapc (lambda (l)
10618 (if (not (string-match org-bracket-link-regexp l))
10619 (princ (format "[%c] %s\n" (incf cnt)
10620 (org-remove-angle-brackets l)))
10621 (if (match-end 3)
10622 (princ (format "[%c] %s (%s)\n" (incf cnt)
10623 (match-string 3 l) (match-string 1 l)))
10624 (princ (format "[%c] %s\n" (incf cnt)
10625 (match-string 1 l))))))
10626 links))
10627 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10628 (message "Select link to open, RET to open all:")
10629 (setq c (read-char-exclusive))
10630 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10631 (when (equal c ?q) (error "Abort"))
10632 (if (equal c ?\C-m)
10633 (setq link links)
10634 (setq nth (- c ?0))
10635 (if have-zero (setq nth (1+ nth)))
10636 (unless (and (integerp nth) (>= (length links) nth))
10637 (user-error "Invalid link selection"))
10638 (setq link (nth (1- nth) links)))))
10639 (cons link end))))))
10641 ;; Add special file links that specify the way of opening
10643 (org-add-link-type "file+sys" 'org-open-file-with-system)
10644 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10645 (defun org-open-file-with-system (path)
10646 "Open file at PATH using the system way of opening it."
10647 (org-open-file path 'system))
10648 (defun org-open-file-with-emacs (path)
10649 "Open file at PATH in Emacs."
10650 (org-open-file path 'emacs))
10653 ;;; File search
10655 (defvar org-create-file-search-functions nil
10656 "List of functions to construct the right search string for a file link.
10657 These functions are called in turn with point at the location to
10658 which the link should point.
10660 A function in the hook should first test if it would like to
10661 handle this file type, for example by checking the `major-mode'
10662 or the file extension. If it decides not to handle this file, it
10663 should just return nil to give other functions a chance. If it
10664 does handle the file, it must return the search string to be used
10665 when following the link. The search string will be part of the
10666 file link, given after a double colon, and `org-open-at-point'
10667 will automatically search for it. If special measures must be
10668 taken to make the search successful, another function should be
10669 added to the companion hook `org-execute-file-search-functions',
10670 which see.
10672 A function in this hook may also use `setq' to set the variable
10673 `description' to provide a suggestion for the descriptive text to
10674 be used for this link when it gets inserted into an Org-mode
10675 buffer with \\[org-insert-link].")
10677 (defvar org-execute-file-search-functions nil
10678 "List of functions to execute a file search triggered by a link.
10680 Functions added to this hook must accept a single argument, the
10681 search string that was part of the file link, the part after the
10682 double colon. The function must first check if it would like to
10683 handle this search, for example by checking the `major-mode' or
10684 the file extension. If it decides not to handle this search, it
10685 should just return nil to give other functions a chance. If it
10686 does handle the search, it must return a non-nil value to keep
10687 other functions from trying.
10689 Each function can access the current prefix argument through the
10690 variable `current-prefix-arg'. Note that a single prefix is used
10691 to force opening a link in Emacs, so it may be good to only use a
10692 numeric or double prefix to guide the search function.
10694 In case this is needed, a function in this hook can also restore
10695 the window configuration before `org-open-at-point' was called using:
10697 (set-window-configuration org-window-config-before-follow-link)")
10699 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10700 (defun org-link-search (s &optional type avoid-pos stealth)
10701 "Search for a link search option.
10702 If S is surrounded by forward slashes, it is interpreted as a
10703 regular expression. In org-mode files, this will create an `org-occur'
10704 sparse tree. In ordinary files, `occur' will be used to list matches.
10705 If the current buffer is in `dired-mode', grep will be used to search
10706 in all files. If AVOID-POS is given, ignore matches near that position.
10708 When optional argument STEALTH is non-nil, do not modify
10709 visibility around point, thus ignoring
10710 `org-show-hierarchy-above', `org-show-following-heading' and
10711 `org-show-siblings' variables."
10712 (let ((case-fold-search t)
10713 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10714 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10715 (append '(("") (" ") ("\t") ("\n"))
10716 org-emphasis-alist)
10717 "\\|") "\\)"))
10718 (pos (point))
10719 (pre nil) (post nil)
10720 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10721 (cond
10722 ;; First check if there are any special search functions
10723 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10724 ;; Now try the builtin stuff
10725 ((and (equal (string-to-char s0) ?#)
10726 (> (length s0) 1)
10727 (save-excursion
10728 (goto-char (point-min))
10729 (and
10730 (re-search-forward
10731 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10732 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10733 (setq type 'dedicated
10734 pos (match-beginning 0))))
10735 ;; There is an exact target for this
10736 (goto-char pos)
10737 (org-back-to-heading t)))
10738 ((save-excursion
10739 (goto-char (point-min))
10740 (and
10741 (re-search-forward
10742 (concat "<<" (regexp-quote s0) ">>") nil t)
10743 (setq type 'dedicated
10744 pos (match-beginning 0))))
10745 ;; There is an exact target for this
10746 (goto-char pos))
10747 ((save-excursion
10748 (goto-char (point-min))
10749 (and
10750 (re-search-forward
10751 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10752 (setq type 'dedicated pos (match-beginning 0))))
10753 ;; Found an element with a matching #+name affiliated keyword.
10754 (goto-char pos))
10755 ((and (string-match "^(\\(.*\\))$" s0)
10756 (save-excursion
10757 (goto-char (point-min))
10758 (and
10759 (re-search-forward
10760 (concat "[^[]" (regexp-quote
10761 (format org-coderef-label-format
10762 (match-string 1 s0))))
10763 nil t)
10764 (setq type 'dedicated
10765 pos (1+ (match-beginning 0))))))
10766 ;; There is a coderef target for this
10767 (goto-char pos))
10768 ((string-match "^/\\(.*\\)/$" s)
10769 ;; A regular expression
10770 (cond
10771 ((derived-mode-p 'org-mode)
10772 (org-occur (match-string 1 s)))
10773 (t (org-do-occur (match-string 1 s)))))
10774 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10775 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10776 (goto-char (point-min))
10777 (cond
10778 ((let (case-fold-search)
10779 (re-search-forward (format org-complex-heading-regexp-format
10780 (regexp-quote s))
10781 nil t))
10782 ;; OK, found a match
10783 (setq type 'dedicated)
10784 (goto-char (match-beginning 0)))
10785 ((and (not org-link-search-inhibit-query)
10786 (eq org-link-search-must-match-exact-headline 'query-to-create)
10787 (y-or-n-p "No match - create this as a new heading? "))
10788 (goto-char (point-max))
10789 (or (bolp) (newline))
10790 (insert "* " s "\n")
10791 (beginning-of-line 0))
10793 (goto-char pos)
10794 (error "No match"))))
10796 ;; A normal search string
10797 (when (equal (string-to-char s) ?*)
10798 ;; Anchor on headlines, post may include tags.
10799 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10800 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10801 s (substring s 1)))
10802 (remove-text-properties
10803 0 (length s)
10804 '(face nil mouse-face nil keymap nil fontified nil) s)
10805 ;; Make a series of regular expressions to find a match
10806 (setq words (org-split-string s "[ \n\r\t]+")
10808 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10809 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10810 "\\)" markers)
10811 re2a_ (concat "\\(" (mapconcat 'downcase words
10812 "[ \t\r\n]+") "\\)[ \t\r\n]")
10813 re2a (concat "[ \t\r\n]" re2a_)
10814 re4_ (concat "\\(" (mapconcat 'downcase words
10815 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10816 re4 (concat "[^a-zA-Z_]" re4_)
10818 re1 (concat pre re2 post)
10819 re3 (concat pre (if pre re4_ re4) post)
10820 re5 (concat pre ".*" re4)
10821 re2 (concat pre re2)
10822 re2a (concat pre (if pre re2a_ re2a))
10823 re4 (concat pre (if pre re4_ re4))
10824 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10825 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10826 re5 "\\)"))
10827 (cond
10828 ((eq type 'org-occur) (org-occur reall))
10829 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10830 (t (goto-char (point-min))
10831 (setq type 'fuzzy)
10832 (if (or (and (org-search-not-self 1 re0 nil t)
10833 (setq type 'dedicated))
10834 (org-search-not-self 1 re1 nil t)
10835 (org-search-not-self 1 re2 nil t)
10836 (org-search-not-self 1 re2a nil t)
10837 (org-search-not-self 1 re3 nil t)
10838 (org-search-not-self 1 re4 nil t)
10839 (org-search-not-self 1 re5 nil t))
10840 (goto-char (match-beginning 1))
10841 (goto-char pos)
10842 (error "No match"))))))
10843 (and (derived-mode-p 'org-mode)
10844 (not stealth)
10845 (org-show-context 'link-search))
10846 type))
10848 (defun org-search-not-self (group &rest args)
10849 "Execute `re-search-forward', but only accept matches that do not
10850 enclose the position of `org-open-link-marker'."
10851 (let ((m org-open-link-marker))
10852 (catch 'exit
10853 (while (apply 're-search-forward args)
10854 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10855 (goto-char (match-end group))
10856 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10857 (> (match-beginning 0) (marker-position m))
10858 (< (match-end 0) (marker-position m)))
10859 (save-match-data
10860 (or (not (org-in-regexp
10861 org-bracket-link-analytic-regexp 1))
10862 (not (match-end 4)) ; no description
10863 (and (<= (match-beginning 4) (point))
10864 (>= (match-end 4) (point))))))
10865 (throw 'exit (point))))))))
10867 (defun org-get-buffer-for-internal-link (buffer)
10868 "Return a buffer to be used for displaying the link target of internal links."
10869 (cond
10870 ((not org-display-internal-link-with-indirect-buffer)
10871 buffer)
10872 ((string-match "(Clone)$" (buffer-name buffer))
10873 (message "Buffer is already a clone, not making another one")
10874 ;; we also do not modify visibility in this case
10875 buffer)
10876 (t ; make a new indirect buffer for displaying the link
10877 (let* ((bn (buffer-name buffer))
10878 (ibn (concat bn "(Clone)"))
10879 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10880 (with-current-buffer ib (org-overview))
10881 ib))))
10883 (defun org-do-occur (regexp &optional cleanup)
10884 "Call the Emacs command `occur'.
10885 If CLEANUP is non-nil, remove the printout of the regular expression
10886 in the *Occur* buffer. This is useful if the regex is long and not useful
10887 to read."
10888 (occur regexp)
10889 (when cleanup
10890 (let ((cwin (selected-window)) win beg end)
10891 (when (setq win (get-buffer-window "*Occur*"))
10892 (select-window win))
10893 (goto-char (point-min))
10894 (when (re-search-forward "match[a-z]+" nil t)
10895 (setq beg (match-end 0))
10896 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10897 (setq end (1- (match-beginning 0)))))
10898 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10899 (goto-char (point-min))
10900 (select-window cwin))))
10902 ;;; The mark ring for links jumps
10904 (defvar org-mark-ring nil
10905 "Mark ring for positions before jumps in Org-mode.")
10906 (defvar org-mark-ring-last-goto nil
10907 "Last position in the mark ring used to go back.")
10908 ;; Fill and close the ring
10909 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10910 (loop for i from 1 to org-mark-ring-length do
10911 (push (make-marker) org-mark-ring))
10912 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10913 org-mark-ring)
10915 (defun org-mark-ring-push (&optional pos buffer)
10916 "Put the current position or POS into the mark ring and rotate it."
10917 (interactive)
10918 (setq pos (or pos (point)))
10919 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10920 (move-marker (car org-mark-ring)
10921 (or pos (point))
10922 (or buffer (current-buffer)))
10923 (message "%s"
10924 (substitute-command-keys
10925 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10927 (defun org-mark-ring-goto (&optional n)
10928 "Jump to the previous position in the mark ring.
10929 With prefix arg N, jump back that many stored positions. When
10930 called several times in succession, walk through the entire ring.
10931 Org-mode commands jumping to a different position in the current file,
10932 or to another Org-mode file, automatically push the old position
10933 onto the ring."
10934 (interactive "p")
10935 (let (p m)
10936 (if (eq last-command this-command)
10937 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10938 (setq p org-mark-ring))
10939 (setq org-mark-ring-last-goto p)
10940 (setq m (car p))
10941 (org-pop-to-buffer-same-window (marker-buffer m))
10942 (goto-char m)
10943 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10945 (defun org-remove-angle-brackets (s)
10946 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10947 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10949 (defun org-add-angle-brackets (s)
10950 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10951 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10953 (defun org-remove-double-quotes (s)
10954 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10955 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10958 ;;; Following specific links
10960 (defun org-follow-timestamp-link ()
10961 "Open an agenda view for the time-stamp date/range at point."
10962 (cond
10963 ((org-at-date-range-p t)
10964 (let ((org-agenda-start-on-weekday)
10965 (t1 (match-string 1))
10966 (t2 (match-string 2)) tt1 tt2)
10967 (setq tt1 (time-to-days (org-time-string-to-time t1))
10968 tt2 (time-to-days (org-time-string-to-time t2)))
10969 (let ((org-agenda-buffer-tmp-name
10970 (format "*Org Agenda(a:%s)"
10971 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10972 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10973 ((org-at-timestamp-p t)
10974 (let ((org-agenda-buffer-tmp-name
10975 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10976 (org-agenda-list nil (time-to-days (org-time-string-to-time
10977 (substring (match-string 1) 0 10)))
10978 1)))
10979 (t (error "This should not happen"))))
10982 ;;; Following file links
10983 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10984 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10985 (declare-function mailcap-mime-info
10986 "mailcap" (string &optional request no-decode))
10987 (defvar org-wait nil)
10988 (defun org-open-file (path &optional in-emacs line search)
10989 "Open the file at PATH.
10990 First, this expands any special file name abbreviations. Then the
10991 configuration variable `org-file-apps' is checked if it contains an
10992 entry for this file type, and if yes, the corresponding command is launched.
10994 If no application is found, Emacs simply visits the file.
10996 With optional prefix argument IN-EMACS, Emacs will visit the file.
10997 With a double \\[universal-argument] \\[universal-argument] \
10998 prefix arg, Org tries to avoid opening in Emacs
10999 and to use an external application to visit the file.
11001 Optional LINE specifies a line to go to, optional SEARCH a string
11002 to search for. If LINE or SEARCH is given, the file will be
11003 opened in Emacs, unless an entry from org-file-apps that makes
11004 use of groups in a regexp matches.
11006 If you want to change the way frames are used when following a
11007 link, please customize `org-link-frame-setup'.
11009 If the file does not exist, an error is thrown."
11010 (let* ((file (if (equal path "")
11011 buffer-file-name
11012 (substitute-in-file-name (expand-file-name path))))
11013 (file-apps (append org-file-apps (org-default-apps)))
11014 (apps (org-remove-if
11015 'org-file-apps-entry-match-against-dlink-p file-apps))
11016 (apps-dlink (org-remove-if-not
11017 'org-file-apps-entry-match-against-dlink-p file-apps))
11018 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11019 (dirp (if remp nil (file-directory-p file)))
11020 (file (if (and dirp org-open-directory-means-index-dot-org)
11021 (concat (file-name-as-directory file) "index.org")
11022 file))
11023 (a-m-a-p (assq 'auto-mode apps))
11024 (dfile (downcase file))
11025 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11026 (link (cond ((and (eq line nil)
11027 (eq search nil))
11028 file)
11029 (line
11030 (concat file "::" (number-to-string line)))
11031 (search
11032 (concat file "::" search))))
11033 (dlink (downcase link))
11034 (old-buffer (current-buffer))
11035 (old-pos (point))
11036 (old-mode major-mode)
11037 ext cmd link-match-data)
11038 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11039 (setq ext (match-string 1 dfile))
11040 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11041 (setq ext (match-string 1 dfile))))
11042 (cond
11043 ((member in-emacs '((16) system))
11044 (setq cmd (cdr (assoc 'system apps))))
11045 (in-emacs (setq cmd 'emacs))
11047 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11048 (and dirp (cdr (assoc 'directory apps)))
11049 ; first, try matching against apps-dlink
11050 ; if we get a match here, store the match data for later
11051 (let ((match (assoc-default dlink apps-dlink
11052 'string-match)))
11053 (if match
11054 (progn (setq link-match-data (match-data))
11055 match)
11056 (progn (setq in-emacs (or in-emacs line search))
11057 nil))) ; if we have no match in apps-dlink,
11058 ; always open the file in emacs if line or search
11059 ; is given (for backwards compatibility)
11060 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11061 'string-match)
11062 (cdr (assoc ext apps))
11063 (cdr (assoc t apps))))))
11064 (when (eq cmd 'system)
11065 (setq cmd (cdr (assoc 'system apps))))
11066 (when (eq cmd 'default)
11067 (setq cmd (cdr (assoc t apps))))
11068 (when (eq cmd 'mailcap)
11069 (require 'mailcap)
11070 (mailcap-parse-mailcaps)
11071 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11072 (command (mailcap-mime-info mime-type)))
11073 (if (stringp command)
11074 (setq cmd command)
11075 (setq cmd 'emacs))))
11076 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11077 (not (file-exists-p file))
11078 (not org-open-non-existing-files))
11079 (user-error "No such file: %s" file))
11080 (cond
11081 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11082 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11083 (while (string-match "['\"]%s['\"]" cmd)
11084 (setq cmd (replace-match "%s" t t cmd)))
11085 (while (string-match "%s" cmd)
11086 (setq cmd (replace-match
11087 (save-match-data
11088 (shell-quote-argument
11089 (convert-standard-filename file)))
11090 t t cmd)))
11092 ;; Replace "%1", "%2" etc. in command with group matches from regex
11093 (save-match-data
11094 (let ((match-index 1)
11095 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11096 (set-match-data link-match-data)
11097 (while (<= match-index number-of-groups)
11098 (let ((regex (concat "%" (number-to-string match-index)))
11099 (replace-with (match-string match-index dlink)))
11100 (while (string-match regex cmd)
11101 (setq cmd (replace-match replace-with t t cmd))))
11102 (setq match-index (+ match-index 1)))))
11104 (save-window-excursion
11105 (message "Running %s...done" cmd)
11106 (start-process-shell-command cmd nil cmd)
11107 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11108 ((or (stringp cmd)
11109 (eq cmd 'emacs))
11110 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11111 (widen)
11112 (if line (org-goto-line line)
11113 (if search (org-link-search search))))
11114 ((consp cmd)
11115 (let ((file (convert-standard-filename file)))
11116 (save-match-data
11117 (set-match-data link-match-data)
11118 (eval cmd))))
11119 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11120 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11121 (or (not (equal old-buffer (current-buffer)))
11122 (not (equal old-pos (point))))
11123 (org-mark-ring-push old-pos old-buffer))))
11125 (defun org-file-apps-entry-match-against-dlink-p (entry)
11126 "This function returns non-nil if `entry' uses a regular
11127 expression which should be matched against the whole link by
11128 org-open-file.
11130 It assumes that is the case when the entry uses a regular
11131 expression which has at least one grouping construct and the
11132 action is either a lisp form or a command string containing
11133 '%1', i.e. using at least one subexpression match as a
11134 parameter."
11135 (let ((selector (car entry))
11136 (action (cdr entry)))
11137 (if (stringp selector)
11138 (and (> (regexp-opt-depth selector) 0)
11139 (or (and (stringp action)
11140 (string-match "%[0-9]" action))
11141 (consp action)))
11142 nil)))
11144 (defun org-default-apps ()
11145 "Return the default applications for this operating system."
11146 (cond
11147 ((eq system-type 'darwin)
11148 org-file-apps-defaults-macosx)
11149 ((eq system-type 'windows-nt)
11150 org-file-apps-defaults-windowsnt)
11151 (t org-file-apps-defaults-gnu)))
11153 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11154 "Convert extensions to regular expressions in the cars of LIST.
11155 Also, weed out any non-string entries, because the return value is used
11156 only for regexp matching.
11157 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11158 point to the symbol `emacs', indicating that the file should
11159 be opened in Emacs."
11160 (append
11161 (delq nil
11162 (mapcar (lambda (x)
11163 (if (not (stringp (car x)))
11165 (if (string-match "\\W" (car x))
11167 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11168 list))
11169 (if add-auto-mode
11170 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11172 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11173 (defun org-file-remote-p (file)
11174 "Test whether FILE specifies a location on a remote system.
11175 Return non-nil if the location is indeed remote.
11177 For example, the filename \"/user@host:/foo\" specifies a location
11178 on the system \"/user@host:\"."
11179 (cond ((fboundp 'file-remote-p)
11180 (file-remote-p file))
11181 ((fboundp 'tramp-handle-file-remote-p)
11182 (tramp-handle-file-remote-p file))
11183 ((and (boundp 'ange-ftp-name-format)
11184 (string-match (car ange-ftp-name-format) file))
11185 t)))
11188 ;;;; Refiling
11190 (defun org-get-org-file ()
11191 "Read a filename, with default directory `org-directory'."
11192 (let ((default (or org-default-notes-file remember-data-file)))
11193 (read-file-name (format "File name [%s]: " default)
11194 (file-name-as-directory org-directory)
11195 default)))
11197 (defun org-notes-order-reversed-p ()
11198 "Check if the current file should receive notes in reversed order."
11199 (cond
11200 ((not org-reverse-note-order) nil)
11201 ((eq t org-reverse-note-order) t)
11202 ((not (listp org-reverse-note-order)) nil)
11203 (t (catch 'exit
11204 (let ((all org-reverse-note-order)
11205 entry)
11206 (while (setq entry (pop all))
11207 (if (string-match (car entry) buffer-file-name)
11208 (throw 'exit (cdr entry))))
11209 nil)))))
11211 (defvar org-refile-target-table nil
11212 "The list of refile targets, created by `org-refile'.")
11214 (defvar org-agenda-new-buffers nil
11215 "Buffers created to visit agenda files.")
11217 (defvar org-refile-cache nil
11218 "Cache for refile targets.")
11220 (defvar org-refile-markers nil
11221 "All the markers used for caching refile locations.")
11223 (defun org-refile-marker (pos)
11224 "Get a new refile marker, but only if caching is in use."
11225 (if (not org-refile-use-cache)
11227 (let ((m (make-marker)))
11228 (move-marker m pos)
11229 (push m org-refile-markers)
11230 m)))
11232 (defun org-refile-cache-clear ()
11233 "Clear the refile cache and disable all the markers."
11234 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11235 (setq org-refile-markers nil)
11236 (setq org-refile-cache nil)
11237 (message "Refile cache has been cleared"))
11239 (defun org-refile-cache-check-set (set)
11240 "Check if all the markers in the cache still have live buffers."
11241 (let (marker)
11242 (catch 'exit
11243 (while (and set (setq marker (nth 3 (pop set))))
11244 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11245 (when (and marker (null (marker-buffer marker)))
11246 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11247 (sit-for 3)
11248 (throw 'exit nil)))
11249 t)))
11251 (defun org-refile-cache-put (set &rest identifiers)
11252 "Push the refile targets SET into the cache, under IDENTIFIERS."
11253 (let* ((key (sha1 (prin1-to-string identifiers)))
11254 (entry (assoc key org-refile-cache)))
11255 (if entry
11256 (setcdr entry set)
11257 (push (cons key set) org-refile-cache))))
11259 (defun org-refile-cache-get (&rest identifiers)
11260 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11261 (cond
11262 ((not org-refile-cache) nil)
11263 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11265 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11266 org-refile-cache))))
11267 (and set (org-refile-cache-check-set set) set)))))
11269 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11270 "Produce a table with refile targets."
11271 (let ((case-fold-search nil)
11272 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11273 (entries (or org-refile-targets '((nil . (:level . 1)))))
11274 targets tgs txt re files f desc descre fast-path-p level pos0)
11275 (message "Getting targets...")
11276 (with-current-buffer (or default-buffer (current-buffer))
11277 (while (setq entry (pop entries))
11278 (setq files (car entry) desc (cdr entry))
11279 (setq fast-path-p nil)
11280 (cond
11281 ((null files) (setq files (list (current-buffer))))
11282 ((eq files 'org-agenda-files)
11283 (setq files (org-agenda-files 'unrestricted)))
11284 ((and (symbolp files) (fboundp files))
11285 (setq files (funcall files)))
11286 ((and (symbolp files) (boundp files))
11287 (setq files (symbol-value files))))
11288 (if (stringp files) (setq files (list files)))
11289 (cond
11290 ((eq (car desc) :tag)
11291 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11292 ((eq (car desc) :todo)
11293 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11294 ((eq (car desc) :regexp)
11295 (setq descre (cdr desc)))
11296 ((eq (car desc) :level)
11297 (setq descre (concat "^\\*\\{" (number-to-string
11298 (if org-odd-levels-only
11299 (1- (* 2 (cdr desc)))
11300 (cdr desc)))
11301 "\\}[ \t]")))
11302 ((eq (car desc) :maxlevel)
11303 (setq fast-path-p t)
11304 (setq descre (concat "^\\*\\{1," (number-to-string
11305 (if org-odd-levels-only
11306 (1- (* 2 (cdr desc)))
11307 (cdr desc)))
11308 "\\}[ \t]")))
11309 (t (error "Bad refiling target description %s" desc)))
11310 (while (setq f (pop files))
11311 (with-current-buffer
11312 (if (bufferp f) f (org-get-agenda-file-buffer f))
11314 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11315 (progn
11316 (if (bufferp f) (setq f (buffer-file-name
11317 (buffer-base-buffer f))))
11318 (setq f (and f (expand-file-name f)))
11319 (if (eq org-refile-use-outline-path 'file)
11320 (push (list (file-name-nondirectory f) f nil nil) tgs))
11321 (save-excursion
11322 (save-restriction
11323 (widen)
11324 (goto-char (point-min))
11325 (while (re-search-forward descre nil t)
11326 (goto-char (setq pos0 (point-at-bol)))
11327 (catch 'next
11328 (when org-refile-target-verify-function
11329 (save-match-data
11330 (or (funcall org-refile-target-verify-function)
11331 (throw 'next t))))
11332 (when (and (looking-at org-complex-heading-regexp)
11333 (not (member (match-string 4) excluded-entries))
11334 (match-string 4))
11335 (setq level (org-reduced-level
11336 (- (match-end 1) (match-beginning 1)))
11337 txt (org-link-display-format (match-string 4))
11338 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11339 re (format org-complex-heading-regexp-format
11340 (regexp-quote (match-string 4))))
11341 (when org-refile-use-outline-path
11342 (setq txt (mapconcat
11343 'org-protect-slash
11344 (append
11345 (if (eq org-refile-use-outline-path
11346 'file)
11347 (list (file-name-nondirectory
11348 (buffer-file-name
11349 (buffer-base-buffer))))
11350 (if (eq org-refile-use-outline-path
11351 'full-file-path)
11352 (list (buffer-file-name
11353 (buffer-base-buffer)))))
11354 (org-get-outline-path fast-path-p
11355 level txt)
11356 (list txt))
11357 "/")))
11358 (push (list txt f re (org-refile-marker (point)))
11359 tgs)))
11360 (when (= (point) pos0)
11361 ;; verification function has not moved point
11362 (goto-char (point-at-eol))))))))
11363 (when org-refile-use-cache
11364 (org-refile-cache-put tgs (buffer-file-name) descre))
11365 (setq targets (append tgs targets))))))
11366 (message "Getting targets...done")
11367 (nreverse targets)))
11369 (defun org-protect-slash (s)
11370 (while (string-match "/" s)
11371 (setq s (replace-match "\\" t t s)))
11374 (defvar org-olpa (make-vector 20 nil))
11376 (defun org-get-outline-path (&optional fastp level heading)
11377 "Return the outline path to the current entry, as a list.
11379 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11380 routine which makes outline path derivations for an entire file,
11381 avoiding backtracing. Refile target collection makes use of that."
11382 (if fastp
11383 (progn
11384 (if (> level 19)
11385 (error "Outline path failure, more than 19 levels"))
11386 (loop for i from level upto 19 do
11387 (aset org-olpa i nil))
11388 (prog1
11389 (delq nil (append org-olpa nil))
11390 (aset org-olpa level heading)))
11391 (let (rtn case-fold-search)
11392 (save-excursion
11393 (save-restriction
11394 (widen)
11395 (while (org-up-heading-safe)
11396 (when (looking-at org-complex-heading-regexp)
11397 (push (org-trim
11398 (replace-regexp-in-string
11399 ;; Remove statistical/checkboxes cookies
11400 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11401 (org-match-string-no-properties 4)))
11402 rtn)))
11403 rtn)))))
11405 (defun org-format-outline-path (path &optional width prefix separator)
11406 "Format the outline path PATH for display.
11407 WIDTH is the maximum number of characters that is available.
11408 PREFIX is a prefix to be included in the returned string,
11409 such as the file name.
11410 SEPARATOR is inserted between the different parts of the path,
11411 the default is \"/\"."
11412 (setq width (or width 79))
11413 (if prefix (setq width (- width (length prefix))))
11414 (if (not path)
11415 (or prefix "")
11416 (let* ((nsteps (length path))
11417 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11418 (maxwidth (if (<= total-width width)
11419 10000 ;; everything fits
11420 ;; we need to shorten the level headings
11421 (/ (- width nsteps) nsteps)))
11422 (org-odd-levels-only nil)
11423 (n 0)
11424 (total (1+ (length prefix))))
11425 (setq maxwidth (max maxwidth 10))
11426 (concat prefix
11427 (if prefix (or separator "/"))
11428 (mapconcat
11429 (lambda (h)
11430 (setq n (1+ n))
11431 (if (and (= n nsteps) (< maxwidth 10000))
11432 (setq maxwidth (- total-width total)))
11433 (if (< (length h) maxwidth)
11434 (progn (setq total (+ total (length h) 1)) h)
11435 (setq h (substring h 0 (- maxwidth 2))
11436 total (+ total maxwidth 1))
11437 (if (string-match "[ \t]+\\'" h)
11438 (setq h (substring h 0 (match-beginning 0))))
11439 (setq h (concat h "..")))
11440 (org-add-props h nil 'face
11441 (nth (% (1- n) org-n-level-faces)
11442 org-level-faces))
11444 path (or separator "/"))))))
11446 (defun org-display-outline-path (&optional file current separator just-return-string)
11447 "Display the current outline path in the echo area.
11449 If FILE is non-nil, prepend the output with the file name.
11450 If CURRENT is non-nil, append the current heading to the output.
11451 SEPARATOR is passed through to `org-format-outline-path'. It separates
11452 the different parts of the path and defaults to \"/\".
11453 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11454 (interactive "P")
11455 (let* (case-fold-search
11456 (bfn (buffer-file-name (buffer-base-buffer)))
11457 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11458 res)
11459 (if current (setq path (append path
11460 (save-excursion
11461 (org-back-to-heading t)
11462 (if (looking-at org-complex-heading-regexp)
11463 (list (match-string 4)))))))
11464 (setq res
11465 (org-format-outline-path
11466 path
11467 (1- (frame-width))
11468 (and file bfn (concat (file-name-nondirectory bfn) separator))
11469 separator))
11470 (if just-return-string
11471 (org-no-properties res)
11472 (org-unlogged-message "%s" res))))
11474 (defvar org-refile-history nil
11475 "History for refiling operations.")
11477 (defvar org-after-refile-insert-hook nil
11478 "Hook run after `org-refile' has inserted its stuff at the new location.
11479 Note that this is still *before* the stuff will be removed from
11480 the *old* location.")
11482 (defvar org-capture-last-stored-marker)
11483 (defvar org-refile-keep nil
11484 "Non-nil means `org-refile' will copy instead of refile.")
11486 (defun org-copy ()
11487 "Like `org-refile', but copy."
11488 (interactive)
11489 (let ((org-refile-keep t))
11490 (funcall 'org-refile nil nil nil "Copy")))
11492 (defun org-refile (&optional goto default-buffer rfloc msg)
11493 "Move the entry or entries at point to another heading.
11494 The list of target headings is compiled using the information in
11495 `org-refile-targets', which see.
11497 At the target location, the entry is filed as a subitem of the target
11498 heading. Depending on `org-reverse-note-order', the new subitem will
11499 either be the first or the last subitem.
11501 If there is an active region, all entries in that region will be moved.
11502 However, the region must fulfill the requirement that the first heading
11503 is the first one sets the top-level of the moved text - at most siblings
11504 below it are allowed.
11506 With prefix arg GOTO, the command will only visit the target location
11507 and not actually move anything.
11509 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11510 go to the location where the last refiling operation has put the subtree.
11512 With a numeric prefix argument of `2', refile to the running clock.
11514 With a numeric prefix argument of `3', emulate `org-refile-keep'
11515 being set to `t' and copy to the target location, don't move it.
11516 Beware that keeping refiled entries may result in duplicated ID
11517 properties.
11519 RFLOC can be a refile location obtained in a different way.
11521 MSG is a string to replace \"Refile\" in the default prompt with
11522 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11524 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11526 If you are using target caching (see `org-refile-use-cache'),
11527 you have to clear the target cache in order to find new targets.
11528 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11529 prefix argument (`C-u C-u C-u C-c C-w')."
11531 (interactive "P")
11532 (if (member goto '(0 (64)))
11533 (org-refile-cache-clear)
11534 (let* ((actionmsg (or msg "Refile"))
11535 (cbuf (current-buffer))
11536 (regionp (org-region-active-p))
11537 (region-start (and regionp (region-beginning)))
11538 (region-end (and regionp (region-end)))
11539 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11540 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11541 pos it nbuf file re level reversed)
11542 (setq last-command nil)
11543 (when regionp
11544 (goto-char region-start)
11545 (or (bolp) (goto-char (point-at-bol)))
11546 (setq region-start (point))
11547 (unless (or (org-kill-is-subtree-p
11548 (buffer-substring region-start region-end))
11549 (prog1 org-refile-active-region-within-subtree
11550 (let ((s (point-at-eol)))
11551 (org-toggle-heading)
11552 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11553 (user-error "The region is not a (sequence of) subtree(s)")))
11554 (if (equal goto '(16))
11555 (org-refile-goto-last-stored)
11556 (when (or
11557 (and (equal goto 2)
11558 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11559 (prog1
11560 (setq it (list (or org-clock-heading "running clock")
11561 (buffer-file-name
11562 (marker-buffer org-clock-hd-marker))
11564 (marker-position org-clock-hd-marker)))
11565 (setq goto nil)))
11566 (setq it (or rfloc
11567 (let (heading-text)
11568 (save-excursion
11569 (unless goto
11570 (org-back-to-heading t)
11571 (setq heading-text
11572 (nth 4 (org-heading-components))))
11574 (org-refile-get-location
11575 (cond (goto "Goto")
11576 (regionp (concat actionmsg " region to"))
11577 (t (concat actionmsg " subtree \""
11578 heading-text "\" to")))
11579 default-buffer
11580 (and (not (equal '(4) goto))
11581 org-refile-allow-creating-parent-nodes)
11582 goto))))))
11583 (setq file (nth 1 it)
11584 re (nth 2 it)
11585 pos (nth 3 it))
11586 (if (and (not goto)
11588 (equal (buffer-file-name) file)
11589 (if regionp
11590 (and (>= pos region-start)
11591 (<= pos region-end))
11592 (and (>= pos (point))
11593 (< pos (save-excursion
11594 (org-end-of-subtree t t))))))
11595 (error "Cannot refile to position inside the tree or region"))
11597 (setq nbuf (or (find-buffer-visiting file)
11598 (find-file-noselect file)))
11599 (if (and goto (not (equal goto 3)))
11600 (progn
11601 (org-pop-to-buffer-same-window nbuf)
11602 (goto-char pos)
11603 (org-show-context 'org-goto))
11604 (if regionp
11605 (progn
11606 (org-kill-new (buffer-substring region-start region-end))
11607 (org-save-markers-in-region region-start region-end))
11608 (org-copy-subtree 1 nil t))
11609 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11610 (find-file-noselect file)))
11611 (setq reversed (org-notes-order-reversed-p))
11612 (save-excursion
11613 (save-restriction
11614 (widen)
11615 (if pos
11616 (progn
11617 (goto-char pos)
11618 (looking-at org-outline-regexp)
11619 (setq level (org-get-valid-level (funcall outline-level) 1))
11620 (goto-char
11621 (if reversed
11622 (or (outline-next-heading) (point-max))
11623 (or (save-excursion (org-get-next-sibling))
11624 (org-end-of-subtree t t)
11625 (point-max)))))
11626 (setq level 1)
11627 (if (not reversed)
11628 (goto-char (point-max))
11629 (goto-char (point-min))
11630 (or (outline-next-heading) (goto-char (point-max)))))
11631 (if (not (bolp)) (newline))
11632 (org-paste-subtree level)
11633 (when org-log-refile
11634 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11635 (unless (eq org-log-refile 'note)
11636 (save-excursion (org-add-log-note))))
11637 (and org-auto-align-tags
11638 (let ((org-loop-over-headlines-in-active-region nil))
11639 (org-set-tags nil t)))
11640 (let ((bookmark-name (plist-get org-bookmark-names-plist
11641 :last-refile)))
11642 (when bookmark-name
11643 (with-demoted-errors
11644 (bookmark-set bookmark-name))))
11645 ;; If we are refiling for capture, make sure that the
11646 ;; last-capture pointers point here
11647 (when (org-bound-and-true-p org-refile-for-capture)
11648 (let ((bookmark-name (plist-get org-bookmark-names-plist
11649 :last-capture-marker)))
11650 (when bookmark-name
11651 (with-demoted-errors
11652 (bookmark-set bookmark-name))))
11653 (move-marker org-capture-last-stored-marker (point)))
11654 (if (fboundp 'deactivate-mark) (deactivate-mark))
11655 (run-hooks 'org-after-refile-insert-hook))))
11656 (unless org-refile-keep
11657 (if regionp
11658 (delete-region (point) (+ (point) (- region-end region-start)))
11659 (delete-region
11660 (and (org-back-to-heading t) (point))
11661 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11662 (when (featurep 'org-inlinetask)
11663 (org-inlinetask-remove-END-maybe))
11664 (setq org-markers-to-move nil)
11665 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11667 (defun org-refile-goto-last-stored ()
11668 "Go to the location where the last refile was stored."
11669 (interactive)
11670 (bookmark-jump "org-refile-last-stored")
11671 (message "This is the location of the last refile"))
11673 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11674 no-exclude)
11675 "Prompt the user for a refile location, using PROMPT.
11676 PROMPT should not be suffixed with a colon and a space, because
11677 this function appends the default value from
11678 `org-refile-history' automatically, if that is not empty.
11679 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11680 this is used for the GOTO interface."
11681 (let ((org-refile-targets org-refile-targets)
11682 (org-refile-use-outline-path org-refile-use-outline-path)
11683 excluded-entries)
11684 (when (and (derived-mode-p 'org-mode)
11685 (not org-refile-use-cache)
11686 (not no-exclude))
11687 (org-map-tree
11688 (lambda()
11689 (setq excluded-entries
11690 (append excluded-entries (list (org-get-heading t t)))))))
11691 (setq org-refile-target-table
11692 (org-refile-get-targets default-buffer excluded-entries)))
11693 (unless org-refile-target-table
11694 (user-error "No refile targets"))
11695 (let* ((cbuf (current-buffer))
11696 (partial-completion-mode nil)
11697 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11698 (cfunc (if (and org-refile-use-outline-path
11699 org-outline-path-complete-in-steps)
11700 'org-olpath-completing-read
11701 'org-icompleting-read))
11702 (extra (if org-refile-use-outline-path "/" ""))
11703 (cbnex (concat (buffer-name) extra))
11704 (filename (and cfn (expand-file-name cfn)))
11705 (tbl (mapcar
11706 (lambda (x)
11707 (if (and (not (member org-refile-use-outline-path
11708 '(file full-file-path)))
11709 (not (equal filename (nth 1 x))))
11710 (cons (concat (car x) extra " ("
11711 (file-name-nondirectory (nth 1 x)) ")")
11712 (cdr x))
11713 (cons (concat (car x) extra) (cdr x))))
11714 org-refile-target-table))
11715 (completion-ignore-case t)
11716 cdef
11717 (prompt (concat prompt
11718 (or (and (car org-refile-history)
11719 (concat " (default " (car org-refile-history) ")"))
11720 (and (assoc cbnex tbl) (setq cdef cbnex)
11721 (concat " (default " cbnex ")"))) ": "))
11722 pa answ parent-target child parent old-hist)
11723 (setq old-hist org-refile-history)
11724 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11725 nil 'org-refile-history (or cdef (car org-refile-history))))
11726 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11727 (org-refile-check-position pa)
11728 (if pa
11729 (progn
11730 (when (or (not org-refile-history)
11731 (not (eq old-hist org-refile-history))
11732 (not (equal (car pa) (car org-refile-history))))
11733 (setq org-refile-history
11734 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11735 org-refile-history
11736 (cdr org-refile-history))))
11737 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11738 (pop org-refile-history)))
11740 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11741 (progn
11742 (setq parent (match-string 1 answ)
11743 child (match-string 2 answ))
11744 (setq parent-target (or (assoc parent tbl)
11745 (assoc (concat parent "/") tbl)))
11746 (when (and parent-target
11747 (or (eq new-nodes t)
11748 (and (eq new-nodes 'confirm)
11749 (y-or-n-p (format "Create new node \"%s\"? "
11750 child)))))
11751 (org-refile-new-child parent-target child)))
11752 (user-error "Invalid target location")))))
11754 (declare-function org-string-nw-p "org-macs" (s))
11755 (defun org-refile-check-position (refile-pointer)
11756 "Check if the refile pointer matches the headline to which it points."
11757 (let* ((file (nth 1 refile-pointer))
11758 (re (nth 2 refile-pointer))
11759 (pos (nth 3 refile-pointer))
11760 buffer)
11761 (if (and (not (markerp pos)) (not file))
11762 (user-error "Please save the buffer to a file before refiling")
11763 (when (org-string-nw-p re)
11764 (setq buffer (if (markerp pos)
11765 (marker-buffer pos)
11766 (or (find-buffer-visiting file)
11767 (find-file-noselect file))))
11768 (with-current-buffer buffer
11769 (save-excursion
11770 (save-restriction
11771 (widen)
11772 (goto-char pos)
11773 (beginning-of-line 1)
11774 (unless (org-looking-at-p re)
11775 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11777 (defun org-refile-new-child (parent-target child)
11778 "Use refile target PARENT-TARGET to add new CHILD below it."
11779 (unless parent-target
11780 (error "Cannot find parent for new node"))
11781 (let ((file (nth 1 parent-target))
11782 (pos (nth 3 parent-target))
11783 level)
11784 (with-current-buffer (or (find-buffer-visiting file)
11785 (find-file-noselect file))
11786 (save-excursion
11787 (save-restriction
11788 (widen)
11789 (if pos
11790 (goto-char pos)
11791 (goto-char (point-max))
11792 (if (not (bolp)) (newline)))
11793 (when (looking-at org-outline-regexp)
11794 (setq level (funcall outline-level))
11795 (org-end-of-subtree t t))
11796 (org-back-over-empty-lines)
11797 (insert "\n" (make-string
11798 (if pos (org-get-valid-level level 1) 1) ?*)
11799 " " child "\n")
11800 (beginning-of-line 0)
11801 (list (concat (car parent-target) "/" child) file "" (point)))))))
11803 (defun org-olpath-completing-read (prompt collection &rest args)
11804 "Read an outline path like a file name."
11805 (let ((thetable collection)
11806 (org-completion-use-ido nil) ; does not work with ido.
11807 (org-completion-use-iswitchb nil)) ; or iswitchb
11808 (apply
11809 'org-icompleting-read prompt
11810 (lambda (string predicate &optional flag)
11811 (let (rtn r f (l (length string)))
11812 (cond
11813 ((eq flag nil)
11814 ;; try completion
11815 (try-completion string thetable))
11816 ((eq flag t)
11817 ;; all-completions
11818 (setq rtn (all-completions string thetable predicate))
11819 (mapcar
11820 (lambda (x)
11821 (setq r (substring x l))
11822 (if (string-match " ([^)]*)$" x)
11823 (setq f (match-string 0 x))
11824 (setq f ""))
11825 (if (string-match "/" r)
11826 (concat string (substring r 0 (match-end 0)) f)
11828 rtn))
11829 ((eq flag 'lambda)
11830 ;; exact match?
11831 (assoc string thetable)))))
11832 args)))
11834 ;;;; Dynamic blocks
11836 (defun org-find-dblock (name)
11837 "Find the first dynamic block with name NAME in the buffer.
11838 If not found, stay at current position and return nil."
11839 (let ((case-fold-search t) pos)
11840 (save-excursion
11841 (goto-char (point-min))
11842 (setq pos (and (re-search-forward
11843 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11844 (match-beginning 0))))
11845 (if pos (goto-char pos))
11846 pos))
11848 (defconst org-dblock-start-re
11849 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11850 "Matches the start line of a dynamic block, with parameters.")
11852 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11853 "Matches the end of a dynamic block.")
11855 (defun org-create-dblock (plist)
11856 "Create a dynamic block section, with parameters taken from PLIST.
11857 PLIST must contain a :name entry which is used as name of the block."
11858 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11859 (end-of-line 1)
11860 (newline))
11861 (let ((col (current-column))
11862 (name (plist-get plist :name)))
11863 (insert "#+BEGIN: " name)
11864 (while plist
11865 (if (eq (car plist) :name)
11866 (setq plist (cddr plist))
11867 (insert " " (prin1-to-string (pop plist)))))
11868 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11869 (beginning-of-line -2)))
11871 (defun org-prepare-dblock ()
11872 "Prepare dynamic block for refresh.
11873 This empties the block, puts the cursor at the insert position and returns
11874 the property list including an extra property :name with the block name."
11875 (unless (looking-at org-dblock-start-re)
11876 (user-error "Not at a dynamic block"))
11877 (let* ((begdel (1+ (match-end 0)))
11878 (name (org-no-properties (match-string 1)))
11879 (params (append (list :name name)
11880 (read (concat "(" (match-string 3) ")")))))
11881 (save-excursion
11882 (beginning-of-line 1)
11883 (skip-chars-forward " \t")
11884 (setq params (plist-put params :indentation-column (current-column))))
11885 (unless (re-search-forward org-dblock-end-re nil t)
11886 (error "Dynamic block not terminated"))
11887 (setq params
11888 (append params
11889 (list :content (buffer-substring
11890 begdel (match-beginning 0)))))
11891 (delete-region begdel (match-beginning 0))
11892 (goto-char begdel)
11893 (open-line 1)
11894 params))
11896 (defun org-map-dblocks (&optional command)
11897 "Apply COMMAND to all dynamic blocks in the current buffer.
11898 If COMMAND is not given, use `org-update-dblock'."
11899 (let ((cmd (or command 'org-update-dblock)))
11900 (save-excursion
11901 (goto-char (point-min))
11902 (while (re-search-forward org-dblock-start-re nil t)
11903 (goto-char (match-beginning 0))
11904 (save-excursion
11905 (condition-case nil
11906 (funcall cmd)
11907 (error (message "Error during update of dynamic block"))))
11908 (unless (re-search-forward org-dblock-end-re nil t)
11909 (error "Dynamic block not terminated"))))))
11911 (defun org-dblock-update (&optional arg)
11912 "User command for updating dynamic blocks.
11913 Update the dynamic block at point. With prefix ARG, update all dynamic
11914 blocks in the buffer."
11915 (interactive "P")
11916 (if arg
11917 (org-update-all-dblocks)
11918 (or (looking-at org-dblock-start-re)
11919 (org-beginning-of-dblock))
11920 (org-update-dblock)))
11922 (defun org-update-dblock ()
11923 "Update the dynamic block at point.
11924 This means to empty the block, parse for parameters and then call
11925 the correct writing function."
11926 (interactive)
11927 (save-window-excursion
11928 (let* ((pos (point))
11929 (line (org-current-line))
11930 (params (org-prepare-dblock))
11931 (name (plist-get params :name))
11932 (indent (plist-get params :indentation-column))
11933 (cmd (intern (concat "org-dblock-write:" name))))
11934 (message "Updating dynamic block `%s' at line %d..." name line)
11935 (funcall cmd params)
11936 (message "Updating dynamic block `%s' at line %d...done" name line)
11937 (goto-char pos)
11938 (when (and indent (> indent 0))
11939 (setq indent (make-string indent ?\ ))
11940 (save-excursion
11941 (org-beginning-of-dblock)
11942 (forward-line 1)
11943 (while (not (looking-at org-dblock-end-re))
11944 (insert indent)
11945 (beginning-of-line 2))
11946 (when (looking-at org-dblock-end-re)
11947 (and (looking-at "[ \t]+")
11948 (replace-match ""))
11949 (insert indent)))))))
11951 (defun org-beginning-of-dblock ()
11952 "Find the beginning of the dynamic block at point.
11953 Error if there is no such block at point."
11954 (let ((pos (point))
11955 beg)
11956 (end-of-line 1)
11957 (if (and (re-search-backward org-dblock-start-re nil t)
11958 (setq beg (match-beginning 0))
11959 (re-search-forward org-dblock-end-re nil t)
11960 (> (match-end 0) pos))
11961 (goto-char beg)
11962 (goto-char pos)
11963 (error "Not in a dynamic block"))))
11965 (defun org-update-all-dblocks ()
11966 "Update all dynamic blocks in the buffer.
11967 This function can be used in a hook."
11968 (interactive)
11969 (when (derived-mode-p 'org-mode)
11970 (org-map-dblocks 'org-update-dblock)))
11973 ;;;; Completion
11975 (declare-function org-export-backend-name "org-export" (cl-x))
11976 (declare-function org-export-backend-options "org-export" (cl-x))
11977 (defun org-get-export-keywords ()
11978 "Return a list of all currently understood export keywords.
11979 Export keywords include options, block names, attributes and
11980 keywords relative to each registered export back-end."
11981 (let (keywords)
11982 (dolist (backend
11983 (org-bound-and-true-p org-export--registered-backends)
11984 (delq nil keywords))
11985 ;; Back-end name (for keywords, like #+LATEX:)
11986 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11987 (dolist (option-entry (org-export-backend-options backend))
11988 ;; Back-end options.
11989 (push (nth 1 option-entry) keywords)))))
11991 (defconst org-options-keywords
11992 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11993 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11994 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11995 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11996 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11998 (defcustom org-structure-template-alist
11999 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12000 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12001 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12002 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12003 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12004 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12005 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12006 "<literal style=\"latex\">\n?\n</literal>")
12007 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12008 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12009 "<literal style=\"html\">\n?\n</literal>")
12010 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12011 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12012 ("A" "#+ASCII: " "")
12013 ("i" "#+INDEX: ?" "#+INDEX: ?")
12014 ("I" "#+INCLUDE: %file ?"
12015 "<include file=%file markup=\"?\">"))
12016 "Structure completion elements.
12017 This is a list of abbreviation keys and values. The value gets inserted
12018 if you type `<' followed by the key and then press the completion key,
12019 usually `M-TAB'. %file will be replaced by a file name after prompting
12020 for the file using completion. The cursor will be placed at the position
12021 of the `?` in the template.
12022 There are two templates for each key, the first uses the original Org syntax,
12023 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12024 the default when the /org-mtags.el/ module has been loaded. See also the
12025 variable `org-mtags-prefer-muse-templates'."
12026 :group 'org-completion
12027 :type '(repeat
12028 (list
12029 (string :tag "Key")
12030 (string :tag "Template")
12031 (string :tag "Muse Template"))))
12033 (defun org-try-structure-completion ()
12034 "Try to complete a structure template before point.
12035 This looks for strings like \"<e\" on an otherwise empty line and
12036 expands them."
12037 (let ((l (buffer-substring (point-at-bol) (point)))
12039 (when (and (looking-at "[ \t]*$")
12040 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12041 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12042 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12043 (match-beginning 1)) a)
12044 t)))
12046 (defun org-complete-expand-structure-template (start cell)
12047 "Expand a structure template."
12048 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12049 (rpl (nth (if musep 2 1) cell))
12050 (ind ""))
12051 (delete-region start (point))
12052 (when (string-match "\\`#\\+" rpl)
12053 (cond
12054 ((bolp))
12055 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12056 (setq ind (buffer-substring (point-at-bol) (point))))
12057 (t (newline))))
12058 (setq start (point))
12059 (if (string-match "%file" rpl)
12060 (setq rpl (replace-match
12061 (concat
12062 "\""
12063 (save-match-data
12064 (abbreviate-file-name (read-file-name "Include file: ")))
12065 "\"")
12066 t t rpl)))
12067 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12068 (concat "\n" ind)))
12069 (insert rpl)
12070 (if (re-search-backward "\\?" start t) (delete-char 1))))
12072 ;;;; TODO, DEADLINE, Comments
12074 (defun org-toggle-comment ()
12075 "Change the COMMENT state of an entry."
12076 (interactive)
12077 (save-excursion
12078 (org-back-to-heading)
12079 (let (case-fold-search)
12080 (cond
12081 ((looking-at (format org-heading-keyword-regexp-format
12082 org-comment-string))
12083 (goto-char (match-end 1))
12084 (looking-at (concat " +" org-comment-string))
12085 (replace-match "" t t)
12086 (when (eolp) (insert " ")))
12087 ((looking-at org-outline-regexp)
12088 (goto-char (match-end 0))
12089 (insert org-comment-string " "))))))
12091 (defvar org-last-todo-state-is-todo nil
12092 "This is non-nil when the last TODO state change led to a TODO state.
12093 If the last change removed the TODO tag or switched to DONE, then
12094 this is nil.")
12096 (defvar org-setting-tags nil) ; dynamically skipped
12098 (defvar org-todo-setup-filter-hook nil
12099 "Hook for functions that pre-filter todo specs.
12100 Each function takes a todo spec and returns either nil or the spec
12101 transformed into canonical form." )
12103 (defvar org-todo-get-default-hook nil
12104 "Hook for functions that get a default item for todo.
12105 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12106 nil or a string to be used for the todo mark." )
12108 (defvar org-agenda-headline-snapshot-before-repeat)
12110 (defun org-current-effective-time ()
12111 "Return current time adjusted for `org-extend-today-until' variable."
12112 (let* ((ct (org-current-time))
12113 (dct (decode-time ct))
12114 (ct1
12115 (cond
12116 (org-use-last-clock-out-time-as-effective-time
12117 (or (org-clock-get-last-clock-out-time) ct))
12118 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12119 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12120 (t ct))))
12121 ct1))
12123 (defun org-todo-yesterday (&optional arg)
12124 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12125 (interactive "P")
12126 (if (eq major-mode 'org-agenda-mode)
12127 (apply 'org-agenda-todo-yesterday arg)
12128 (let* ((hour (third (decode-time
12129 (org-current-time))))
12130 (org-extend-today-until (1+ hour)))
12131 (org-todo arg))))
12133 (defvar org-block-entry-blocking ""
12134 "First entry preventing the TODO state change.")
12136 (defun org-todo (&optional arg)
12137 "Change the TODO state of an item.
12138 The state of an item is given by a keyword at the start of the heading,
12139 like
12140 *** TODO Write paper
12141 *** DONE Call mom
12143 The different keywords are specified in the variable `org-todo-keywords'.
12144 By default the available states are \"TODO\" and \"DONE\".
12145 So for this example: when the item starts with TODO, it is changed to DONE.
12146 When it starts with DONE, the DONE is removed. And when neither TODO nor
12147 DONE are present, add TODO at the beginning of the heading.
12149 With \\[universal-argument] prefix arg, use completion to determine the new \
12150 state.
12151 With numeric prefix arg, switch to that state.
12152 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12153 keywords (nextset).
12154 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12155 With a numeric prefix arg of 0, inhibit note taking for the change.
12157 For calling through lisp, arg is also interpreted in the following way:
12158 'none -> empty state
12159 \"\"(empty string) -> switch to empty state
12160 'done -> switch to DONE
12161 'nextset -> switch to the next set of keywords
12162 'previousset -> switch to the previous set of keywords
12163 \"WAITING\" -> switch to the specified keyword, but only if it
12164 really is a member of `org-todo-keywords'."
12165 (interactive "P")
12166 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12167 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12168 'region-start-level 'region))
12169 org-loop-over-headlines-in-active-region)
12170 (org-map-entries
12171 `(org-todo ,arg)
12172 org-loop-over-headlines-in-active-region
12173 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12174 (if (equal arg '(16)) (setq arg 'nextset))
12175 (let ((org-blocker-hook org-blocker-hook)
12176 commentp
12177 case-fold-search)
12178 (when (equal arg '(64))
12179 (setq arg nil org-blocker-hook nil))
12180 (when (and org-blocker-hook
12181 (or org-inhibit-blocking
12182 (org-entry-get nil "NOBLOCKING")))
12183 (setq org-blocker-hook nil))
12184 (save-excursion
12185 (catch 'exit
12186 (org-back-to-heading t)
12187 (when (looking-at (concat "^\\*+ " org-comment-string))
12188 (org-toggle-comment)
12189 (setq commentp t))
12190 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12191 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12192 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12193 (let* ((match-data (match-data))
12194 (startpos (point-at-bol))
12195 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12196 (org-log-done org-log-done)
12197 (org-log-repeat org-log-repeat)
12198 (org-todo-log-states org-todo-log-states)
12199 (org-inhibit-logging
12200 (if (equal arg 0)
12201 (progn (setq arg nil) 'note) org-inhibit-logging))
12202 (this (match-string 1))
12203 (hl-pos (match-beginning 0))
12204 (head (org-get-todo-sequence-head this))
12205 (ass (assoc head org-todo-kwd-alist))
12206 (interpret (nth 1 ass))
12207 (done-word (nth 3 ass))
12208 (final-done-word (nth 4 ass))
12209 (org-last-state (or this ""))
12210 (completion-ignore-case t)
12211 (member (member this org-todo-keywords-1))
12212 (tail (cdr member))
12213 (org-state (cond
12214 ((and org-todo-key-trigger
12215 (or (and (equal arg '(4))
12216 (eq org-use-fast-todo-selection 'prefix))
12217 (and (not arg) org-use-fast-todo-selection
12218 (not (eq org-use-fast-todo-selection
12219 'prefix)))))
12220 ;; Use fast selection
12221 (org-fast-todo-selection))
12222 ((and (equal arg '(4))
12223 (or (not org-use-fast-todo-selection)
12224 (not org-todo-key-trigger)))
12225 ;; Read a state with completion
12226 (org-icompleting-read
12227 "State: " (mapcar 'list org-todo-keywords-1)
12228 nil t))
12229 ((eq arg 'right)
12230 (if this
12231 (if tail (car tail) nil)
12232 (car org-todo-keywords-1)))
12233 ((eq arg 'left)
12234 (if (equal member org-todo-keywords-1)
12236 (if this
12237 (nth (- (length org-todo-keywords-1)
12238 (length tail) 2)
12239 org-todo-keywords-1)
12240 (org-last org-todo-keywords-1))))
12241 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12242 (setq arg nil))) ; hack to fall back to cycling
12243 (arg
12244 ;; user or caller requests a specific state
12245 (cond
12246 ((equal arg "") nil)
12247 ((eq arg 'none) nil)
12248 ((eq arg 'done) (or done-word (car org-done-keywords)))
12249 ((eq arg 'nextset)
12250 (or (car (cdr (member head org-todo-heads)))
12251 (car org-todo-heads)))
12252 ((eq arg 'previousset)
12253 (let ((org-todo-heads (reverse org-todo-heads)))
12254 (or (car (cdr (member head org-todo-heads)))
12255 (car org-todo-heads))))
12256 ((car (member arg org-todo-keywords-1)))
12257 ((stringp arg)
12258 (user-error "State `%s' not valid in this file" arg))
12259 ((nth (1- (prefix-numeric-value arg))
12260 org-todo-keywords-1))))
12261 ((null member) (or head (car org-todo-keywords-1)))
12262 ((equal this final-done-word) nil) ;; -> make empty
12263 ((null tail) nil) ;; -> first entry
12264 ((memq interpret '(type priority))
12265 (if (eq this-command last-command)
12266 (car tail)
12267 (if (> (length tail) 0)
12268 (or done-word (car org-done-keywords))
12269 nil)))
12271 (car tail))))
12272 (org-state (or
12273 (run-hook-with-args-until-success
12274 'org-todo-get-default-hook org-state org-last-state)
12275 org-state))
12276 (next (if org-state (concat " " org-state " ") " "))
12277 (change-plist (list :type 'todo-state-change :from this :to org-state
12278 :position startpos))
12279 dolog now-done-p)
12280 (when org-blocker-hook
12281 (setq org-last-todo-state-is-todo
12282 (not (member this org-done-keywords)))
12283 (unless (save-excursion
12284 (save-match-data
12285 (org-with-wide-buffer
12286 (run-hook-with-args-until-failure
12287 'org-blocker-hook change-plist))))
12288 (if (org-called-interactively-p 'interactive)
12289 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12290 this org-state org-block-entry-blocking)
12291 ;; fail silently
12292 (message "TODO state change from %s to %s blocked (by \"%s\")"
12293 this org-state org-block-entry-blocking)
12294 (throw 'exit nil))))
12295 (store-match-data match-data)
12296 (replace-match next t t)
12297 (unless (pos-visible-in-window-p hl-pos)
12298 (message "TODO state changed to %s" (org-trim next)))
12299 (unless head
12300 (setq head (org-get-todo-sequence-head org-state)
12301 ass (assoc head org-todo-kwd-alist)
12302 interpret (nth 1 ass)
12303 done-word (nth 3 ass)
12304 final-done-word (nth 4 ass)))
12305 (when (memq arg '(nextset previousset))
12306 (message "Keyword-Set %d/%d: %s"
12307 (- (length org-todo-sets) -1
12308 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12309 (length org-todo-sets)
12310 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12311 (setq org-last-todo-state-is-todo
12312 (not (member org-state org-done-keywords)))
12313 (setq now-done-p (and (member org-state org-done-keywords)
12314 (not (member this org-done-keywords))))
12315 (and logging (org-local-logging logging))
12316 (when (and (or org-todo-log-states org-log-done)
12317 (not (eq org-inhibit-logging t))
12318 (not (memq arg '(nextset previousset))))
12319 ;; we need to look at recording a time and note
12320 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12321 (nth 2 (assoc this org-todo-log-states))))
12322 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12323 (setq dolog 'time))
12324 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12325 (and org-state
12326 (member org-state org-not-done-keywords)
12327 (not (member this org-not-done-keywords))))
12328 ;; This is now a todo state and was not one before
12329 ;; If there was a CLOSED time stamp, get rid of it.
12330 (org-add-planning-info nil nil 'closed))
12331 (when (and now-done-p org-log-done)
12332 ;; It is now done, and it was not done before
12333 (org-add-planning-info 'closed (org-current-effective-time))
12334 (if (and (not dolog) (eq 'note org-log-done))
12335 (org-add-log-setup 'done org-state this 'findpos 'note)))
12336 (when (and org-state dolog)
12337 ;; This is a non-nil state, and we need to log it
12338 (org-add-log-setup 'state org-state this 'findpos dolog)))
12339 ;; Fixup tag positioning
12340 (org-todo-trigger-tag-changes org-state)
12341 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12342 (when org-provide-todo-statistics
12343 (org-update-parent-todo-statistics))
12344 (run-hooks 'org-after-todo-state-change-hook)
12345 (if (and arg (not (member org-state org-done-keywords)))
12346 (setq head (org-get-todo-sequence-head org-state)))
12347 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12348 ;; Do we need to trigger a repeat?
12349 (when now-done-p
12350 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12351 ;; This is for the agenda, take a snapshot of the headline.
12352 (save-match-data
12353 (setq org-agenda-headline-snapshot-before-repeat
12354 (org-get-heading))))
12355 (org-auto-repeat-maybe org-state))
12356 ;; Fixup cursor location if close to the keyword
12357 (if (and (outline-on-heading-p)
12358 (not (bolp))
12359 (save-excursion (beginning-of-line 1)
12360 (looking-at org-todo-line-regexp))
12361 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12362 (progn
12363 (goto-char (or (match-end 2) (match-end 1)))
12364 (and (looking-at " ") (just-one-space))))
12365 (when org-trigger-hook
12366 (save-excursion
12367 (run-hook-with-args 'org-trigger-hook change-plist)))
12368 (when commentp (org-toggle-comment))))))))
12370 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12371 "Block turning an entry into a TODO, using the hierarchy.
12372 This checks whether the current task should be blocked from state
12373 changes. Such blocking occurs when:
12375 1. The task has children which are not all in a completed state.
12377 2. A task has a parent with the property :ORDERED:, and there
12378 are siblings prior to the current task with incomplete
12379 status.
12381 3. The parent of the task is blocked because it has siblings that should
12382 be done first, or is child of a block grandparent TODO entry."
12384 (if (not org-enforce-todo-dependencies)
12385 t ; if locally turned off don't block
12386 (catch 'dont-block
12387 ;; If this is not a todo state change, or if this entry is already DONE,
12388 ;; do not block
12389 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12390 (member (plist-get change-plist :from)
12391 (cons 'done org-done-keywords))
12392 (member (plist-get change-plist :to)
12393 (cons 'todo org-not-done-keywords))
12394 (not (plist-get change-plist :to)))
12395 (throw 'dont-block t))
12396 ;; If this task has children, and any are undone, it's blocked
12397 (save-excursion
12398 (org-back-to-heading t)
12399 (let ((this-level (funcall outline-level)))
12400 (outline-next-heading)
12401 (let ((child-level (funcall outline-level)))
12402 (while (and (not (eobp))
12403 (> child-level this-level))
12404 ;; this todo has children, check whether they are all
12405 ;; completed
12406 (if (and (not (org-entry-is-done-p))
12407 (org-entry-is-todo-p))
12408 (progn (setq org-block-entry-blocking (org-get-heading))
12409 (throw 'dont-block nil)))
12410 (outline-next-heading)
12411 (setq child-level (funcall outline-level))))))
12412 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12413 ;; any previous siblings are undone, it's blocked
12414 (save-excursion
12415 (org-back-to-heading t)
12416 (let* ((pos (point))
12417 (parent-pos (and (org-up-heading-safe) (point))))
12418 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12419 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12420 (forward-line 1)
12421 (re-search-forward org-not-done-heading-regexp pos t))
12422 (setq org-block-entry-blocking (match-string 0))
12423 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12424 ;; Search further up the hierarchy, to see if an ancestor is blocked
12425 (while t
12426 (goto-char parent-pos)
12427 (if (not (looking-at org-not-done-heading-regexp))
12428 (throw 'dont-block t)) ; do not block, parent is not a TODO
12429 (setq pos (point))
12430 (setq parent-pos (and (org-up-heading-safe) (point)))
12431 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12432 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12433 (forward-line 1)
12434 (re-search-forward org-not-done-heading-regexp pos t)
12435 (setq org-block-entry-blocking (org-get-heading)))
12436 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12438 (defcustom org-track-ordered-property-with-tag nil
12439 "Should the ORDERED property also be shown as a tag?
12440 The ORDERED property decides if an entry should require subtasks to be
12441 completed in sequence. Since a property is not very visible, setting
12442 this option means that toggling the ORDERED property with the command
12443 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12444 not relevant for the behavior, but it makes things more visible.
12446 Note that toggling the tag with tags commands will not change the property
12447 and therefore not influence behavior!
12449 This can be t, meaning the tag ORDERED should be used, It can also be a
12450 string to select a different tag for this task."
12451 :group 'org-todo
12452 :type '(choice
12453 (const :tag "No tracking" nil)
12454 (const :tag "Track with ORDERED tag" t)
12455 (string :tag "Use other tag")))
12457 (defun org-toggle-ordered-property ()
12458 "Toggle the ORDERED property of the current entry.
12459 For better visibility, you can track the value of this property with a tag.
12460 See variable `org-track-ordered-property-with-tag'."
12461 (interactive)
12462 (let* ((t1 org-track-ordered-property-with-tag)
12463 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12464 (save-excursion
12465 (org-back-to-heading)
12466 (if (org-entry-get nil "ORDERED")
12467 (progn
12468 (org-delete-property "ORDERED" "PROPERTIES")
12469 (and tag (org-toggle-tag tag 'off))
12470 (message "Subtasks can be completed in arbitrary order"))
12471 (org-entry-put nil "ORDERED" "t")
12472 (and tag (org-toggle-tag tag 'on))
12473 (message "Subtasks must be completed in sequence")))))
12475 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12476 (defun org-block-todo-from-checkboxes (change-plist)
12477 "Block turning an entry into a TODO, using checkboxes.
12478 This checks whether the current task should be blocked from state
12479 changes because there are unchecked boxes in this entry."
12480 (if (not org-enforce-todo-checkbox-dependencies)
12481 t ; if locally turned off don't block
12482 (catch 'dont-block
12483 ;; If this is not a todo state change, or if this entry is already DONE,
12484 ;; do not block
12485 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12486 (member (plist-get change-plist :from)
12487 (cons 'done org-done-keywords))
12488 (member (plist-get change-plist :to)
12489 (cons 'todo org-not-done-keywords))
12490 (not (plist-get change-plist :to)))
12491 (throw 'dont-block t))
12492 ;; If this task has checkboxes that are not checked, it's blocked
12493 (save-excursion
12494 (org-back-to-heading t)
12495 (let ((beg (point)) end)
12496 (outline-next-heading)
12497 (setq end (point))
12498 (goto-char beg)
12499 (if (org-list-search-forward
12500 (concat (org-item-beginning-re)
12501 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12502 "\\[[- ]\\]")
12503 end t)
12504 (progn
12505 (if (boundp 'org-blocked-by-checkboxes)
12506 (setq org-blocked-by-checkboxes t))
12507 (throw 'dont-block nil)))))
12508 t))) ; do not block
12510 (defun org-entry-blocked-p ()
12511 "Is the current entry blocked?"
12512 (org-with-silent-modifications
12513 (if (org-entry-get nil "NOBLOCKING")
12514 nil ;; Never block this entry
12515 (not (run-hook-with-args-until-failure
12516 'org-blocker-hook
12517 (list :type 'todo-state-change
12518 :position (point)
12519 :from 'todo
12520 :to 'done))))))
12522 (defun org-update-statistics-cookies (all)
12523 "Update the statistics cookie, either from TODO or from checkboxes.
12524 This should be called with the cursor in a line with a statistics cookie."
12525 (interactive "P")
12526 (if all
12527 (progn
12528 (org-update-checkbox-count 'all)
12529 (org-map-entries 'org-update-parent-todo-statistics))
12530 (if (not (org-at-heading-p))
12531 (org-update-checkbox-count)
12532 (let ((pos (point-marker))
12533 end l1 l2)
12534 (ignore-errors (org-back-to-heading t))
12535 (if (not (org-at-heading-p))
12536 (org-update-checkbox-count)
12537 (setq l1 (org-outline-level))
12538 (setq end (save-excursion
12539 (outline-next-heading)
12540 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12541 (point)))
12542 (if (and (save-excursion
12543 (re-search-forward
12544 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12545 (not (save-excursion (re-search-forward
12546 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12547 (org-update-checkbox-count)
12548 (if (and l2 (> l2 l1))
12549 (progn
12550 (goto-char end)
12551 (org-update-parent-todo-statistics))
12552 (goto-char pos)
12553 (beginning-of-line 1)
12554 (while (re-search-forward
12555 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12556 (point-at-eol) t)
12557 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12558 (goto-char pos)
12559 (move-marker pos nil)))))
12561 (defvar org-entry-property-inherited-from) ;; defined below
12562 (defun org-update-parent-todo-statistics ()
12563 "Update any statistics cookie in the parent of the current headline.
12564 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12565 the entire subtree and this will travel up the hierarchy and update
12566 statistics everywhere."
12567 (let* ((prop (save-excursion (org-up-heading-safe)
12568 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12569 (recursive (or (not org-hierarchical-todo-statistics)
12570 (and prop (string-match "\\<recursive\\>" prop))))
12571 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12573 (first t)
12574 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12575 level ltoggle l1 new ndel
12576 (cnt-all 0) (cnt-done 0) is-percent kwd
12577 checkbox-beg ov ovs ove cookie-present)
12578 (catch 'exit
12579 (save-excursion
12580 (beginning-of-line 1)
12581 (setq ltoggle (funcall outline-level))
12582 ;; Three situations are to consider:
12584 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12585 ;; to the top-level ancestor on the headline;
12587 ;; 2. If parent has "recursive" property, repeat up to the
12588 ;; headline setting that property, taking inheritance into
12589 ;; account;
12591 ;; 3. Else, move up to direct parent and proceed only once.
12592 (while (and (setq level (org-up-heading-safe))
12593 (or recursive first)
12594 (>= (point) lim))
12595 (setq first nil cookie-present nil)
12596 (unless (and level
12597 (not (string-match
12598 "\\<checkbox\\>"
12599 (downcase (or (org-entry-get nil "COOKIE_DATA")
12600 "")))))
12601 (throw 'exit nil))
12602 (while (re-search-forward box-re (point-at-eol) t)
12603 (setq cnt-all 0 cnt-done 0 cookie-present t)
12604 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12605 (save-match-data
12606 (unless (outline-next-heading) (throw 'exit nil))
12607 (while (and (looking-at org-complex-heading-regexp)
12608 (> (setq l1 (length (match-string 1))) level))
12609 (setq kwd (and (or recursive (= l1 ltoggle))
12610 (match-string 2)))
12611 (if (or (eq org-provide-todo-statistics 'all-headlines)
12612 (and (listp org-provide-todo-statistics)
12613 (or (member kwd org-provide-todo-statistics)
12614 (member kwd org-done-keywords))))
12615 (setq cnt-all (1+ cnt-all))
12616 (if (eq org-provide-todo-statistics t)
12617 (and kwd (setq cnt-all (1+ cnt-all)))))
12618 (and (member kwd org-done-keywords)
12619 (setq cnt-done (1+ cnt-done)))
12620 (outline-next-heading)))
12621 (setq new
12622 (if is-percent
12623 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12624 (format "[%d/%d]" cnt-done cnt-all))
12625 ndel (- (match-end 0) checkbox-beg))
12626 ;; handle overlays when updating cookie from column view
12627 (when (setq ov (car (overlays-at checkbox-beg)))
12628 (setq ovs (overlay-start ov) ove (overlay-end ov))
12629 (delete-overlay ov))
12630 (goto-char checkbox-beg)
12631 (insert new)
12632 (delete-region (point) (+ (point) ndel))
12633 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12634 (when ov (move-overlay ov ovs ove)))
12635 (when cookie-present
12636 (run-hook-with-args 'org-after-todo-statistics-hook
12637 cnt-done (- cnt-all cnt-done))))))
12638 (run-hooks 'org-todo-statistics-hook)))
12640 (defvar org-after-todo-statistics-hook nil
12641 "Hook that is called after a TODO statistics cookie has been updated.
12642 Each function is called with two arguments: the number of not-done entries
12643 and the number of done entries.
12645 For example, the following function, when added to this hook, will switch
12646 an entry to DONE when all children are done, and back to TODO when new
12647 entries are set to a TODO status. Note that this hook is only called
12648 when there is a statistics cookie in the headline!
12650 (defun org-summary-todo (n-done n-not-done)
12651 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12652 (let (org-log-done org-log-states) ; turn off logging
12653 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12656 (defvar org-todo-statistics-hook nil
12657 "Hook that is run whenever Org thinks TODO statistics should be updated.
12658 This hook runs even if there is no statistics cookie present, in which case
12659 `org-after-todo-statistics-hook' would not run.")
12661 (defun org-todo-trigger-tag-changes (state)
12662 "Apply the changes defined in `org-todo-state-tags-triggers'."
12663 (let ((l org-todo-state-tags-triggers)
12664 changes)
12665 (when (or (not state) (equal state ""))
12666 (setq changes (append changes (cdr (assoc "" l)))))
12667 (when (and (stringp state) (> (length state) 0))
12668 (setq changes (append changes (cdr (assoc state l)))))
12669 (when (member state org-not-done-keywords)
12670 (setq changes (append changes (cdr (assoc 'todo l)))))
12671 (when (member state org-done-keywords)
12672 (setq changes (append changes (cdr (assoc 'done l)))))
12673 (dolist (c changes)
12674 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12676 (defun org-local-logging (value)
12677 "Get logging settings from a property VALUE."
12678 (let* (words w a)
12679 ;; directly set the variables, they are already local.
12680 (setq org-log-done nil
12681 org-log-repeat nil
12682 org-todo-log-states nil)
12683 (setq words (org-split-string value))
12684 (while (setq w (pop words))
12685 (cond
12686 ((setq a (assoc w org-startup-options))
12687 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12688 (set (nth 1 a) (nth 2 a))))
12689 ((setq a (org-extract-log-state-settings w))
12690 (and (member (car a) org-todo-keywords-1)
12691 (push a org-todo-log-states)))))))
12693 (defun org-get-todo-sequence-head (kwd)
12694 "Return the head of the TODO sequence to which KWD belongs.
12695 If KWD is not set, check if there is a text property remembering the
12696 right sequence."
12697 (let (p)
12698 (cond
12699 ((not kwd)
12700 (or (get-text-property (point-at-bol) 'org-todo-head)
12701 (progn
12702 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12703 nil (point-at-eol)))
12704 (get-text-property p 'org-todo-head))))
12705 ((not (member kwd org-todo-keywords-1))
12706 (car org-todo-keywords-1))
12707 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12709 (defun org-fast-todo-selection ()
12710 "Fast TODO keyword selection with single keys.
12711 Returns the new TODO keyword, or nil if no state change should occur."
12712 (let* ((fulltable org-todo-key-alist)
12713 (done-keywords org-done-keywords) ;; needed for the faces.
12714 (maxlen (apply 'max (mapcar
12715 (lambda (x)
12716 (if (stringp (car x)) (string-width (car x)) 0))
12717 fulltable)))
12718 (expert nil)
12719 (fwidth (+ maxlen 3 1 3))
12720 (ncol (/ (- (window-width) 4) fwidth))
12721 tg cnt e c tbl
12722 groups ingroup)
12723 (save-excursion
12724 (save-window-excursion
12725 (if expert
12726 (set-buffer (get-buffer-create " *Org todo*"))
12727 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12728 (erase-buffer)
12729 (org-set-local 'org-done-keywords done-keywords)
12730 (setq tbl fulltable cnt 0)
12731 (while (setq e (pop tbl))
12732 (cond
12733 ((equal e '(:startgroup))
12734 (push '() groups) (setq ingroup t)
12735 (when (not (= cnt 0))
12736 (setq cnt 0)
12737 (insert "\n"))
12738 (insert "{ "))
12739 ((equal e '(:endgroup))
12740 (setq ingroup nil cnt 0)
12741 (insert "}\n"))
12742 ((equal e '(:newline))
12743 (when (not (= cnt 0))
12744 (setq cnt 0)
12745 (insert "\n")
12746 (setq e (car tbl))
12747 (while (equal (car tbl) '(:newline))
12748 (insert "\n")
12749 (setq tbl (cdr tbl)))))
12751 (setq tg (car e) c (cdr e))
12752 (if ingroup (push tg (car groups)))
12753 (setq tg (org-add-props tg nil 'face
12754 (org-get-todo-face tg)))
12755 (if (and (= cnt 0) (not ingroup)) (insert " "))
12756 (insert "[" c "] " tg (make-string
12757 (- fwidth 4 (length tg)) ?\ ))
12758 (when (= (setq cnt (1+ cnt)) ncol)
12759 (insert "\n")
12760 (if ingroup (insert " "))
12761 (setq cnt 0)))))
12762 (insert "\n")
12763 (goto-char (point-min))
12764 (if (not expert) (org-fit-window-to-buffer))
12765 (message "[a-z..]:Set [SPC]:clear")
12766 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12767 (cond
12768 ((or (= c ?\C-g)
12769 (and (= c ?q) (not (rassoc c fulltable))))
12770 (setq quit-flag t))
12771 ((= c ?\ ) nil)
12772 ((setq e (rassoc c fulltable) tg (car e))
12774 (t (setq quit-flag t)))))))
12776 (defun org-entry-is-todo-p ()
12777 (member (org-get-todo-state) org-not-done-keywords))
12779 (defun org-entry-is-done-p ()
12780 (member (org-get-todo-state) org-done-keywords))
12782 (defun org-get-todo-state ()
12783 "Return the TODO keyword of the current subtree."
12784 (save-excursion
12785 (org-back-to-heading t)
12786 (and (looking-at org-todo-line-regexp)
12787 (match-end 2)
12788 (match-string 2))))
12790 (defun org-at-date-range-p (&optional inactive-ok)
12791 "Is the cursor inside a date range?"
12792 (interactive)
12793 (save-excursion
12794 (catch 'exit
12795 (let ((pos (point)))
12796 (skip-chars-backward "^[<\r\n")
12797 (skip-chars-backward "<[")
12798 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12799 (>= (match-end 0) pos)
12800 (throw 'exit t))
12801 (skip-chars-backward "^<[\r\n")
12802 (skip-chars-backward "<[")
12803 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12804 (>= (match-end 0) pos)
12805 (throw 'exit t)))
12806 nil)))
12808 (defun org-get-repeat (&optional tagline)
12809 "Check if there is a deadline/schedule with repeater in this entry."
12810 (save-match-data
12811 (save-excursion
12812 (org-back-to-heading t)
12813 (and (re-search-forward (if tagline
12814 (concat tagline "\\s-*" org-repeat-re)
12815 org-repeat-re)
12816 (org-entry-end-position) t)
12817 (match-string-no-properties 1)))))
12819 (defvar org-last-changed-timestamp)
12820 (defvar org-last-inserted-timestamp)
12821 (defvar org-log-post-message)
12822 (defvar org-log-note-purpose)
12823 (defvar org-log-note-how)
12824 (defvar org-log-note-extra)
12825 (defun org-auto-repeat-maybe (done-word)
12826 "Check if the current headline contains a repeated deadline/schedule.
12827 If yes, set TODO state back to what it was and change the base date
12828 of repeating deadline/scheduled time stamps to new date.
12829 This function is run automatically after each state change to a DONE state."
12830 ;; last-state is dynamically scoped into this function
12831 (let* ((repeat (org-get-repeat))
12832 (aa (assoc org-last-state org-todo-kwd-alist))
12833 (interpret (nth 1 aa))
12834 (head (nth 2 aa))
12835 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12836 (msg "Entry repeats: ")
12837 (org-log-done nil)
12838 (org-todo-log-states nil)
12839 re type n what ts time to-state)
12840 (when repeat
12841 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12842 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12843 org-todo-repeat-to-state))
12844 (unless (and to-state (member to-state org-todo-keywords-1))
12845 (setq to-state (if (eq interpret 'type) org-last-state head)))
12846 (org-todo to-state)
12847 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12848 (org-entry-put nil "LAST_REPEAT" (format-time-string
12849 (org-time-stamp-format t t))))
12850 (when org-log-repeat
12851 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12852 (memq 'org-add-log-note post-command-hook))
12853 ;; OK, we are already setup for some record
12854 (if (eq org-log-repeat 'note)
12855 ;; make sure we take a note, not only a time stamp
12856 (setq org-log-note-how 'note))
12857 ;; Set up for taking a record
12858 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12859 org-last-state
12860 'findpos org-log-repeat)))
12861 (org-back-to-heading t)
12862 (org-add-planning-info nil nil 'closed)
12863 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12864 org-deadline-time-regexp "\\)\\|\\("
12865 org-ts-regexp "\\)"))
12866 (while (re-search-forward
12867 re (save-excursion (outline-next-heading) (point)) t)
12868 (setq type (if (match-end 1) org-scheduled-string
12869 (if (match-end 3) org-deadline-string "Plain:"))
12870 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12871 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12872 (setq n (string-to-number (match-string 2 ts))
12873 what (match-string 3 ts))
12874 (if (equal what "w") (setq n (* n 7) what "d"))
12875 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12876 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12877 ;; Preparation, see if we need to modify the start date for the change
12878 (when (match-end 1)
12879 (setq time (save-match-data (org-time-string-to-time ts)))
12880 (cond
12881 ((equal (match-string 1 ts) ".")
12882 ;; Shift starting date to today
12883 (org-timestamp-change
12884 (- (org-today) (time-to-days time))
12885 'day))
12886 ((equal (match-string 1 ts) "+")
12887 (let ((nshiftmax 10) (nshift 0))
12888 (while (or (= nshift 0)
12889 (<= (time-to-days time)
12890 (time-to-days (current-time))))
12891 (when (= (incf nshift) nshiftmax)
12892 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12893 (error "Abort")))
12894 (org-timestamp-change n (cdr (assoc what whata)))
12895 (org-at-timestamp-p t)
12896 (setq ts (match-string 1))
12897 (setq time (save-match-data (org-time-string-to-time ts)))))
12898 (org-timestamp-change (- n) (cdr (assoc what whata)))
12899 ;; rematch, so that we have everything in place for the real shift
12900 (org-at-timestamp-p t)
12901 (setq ts (match-string 1))
12902 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12903 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12904 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12905 (setq org-log-post-message msg)
12906 (message "%s" msg))))
12908 (defun org-show-todo-tree (arg)
12909 "Make a compact tree which shows all headlines marked with TODO.
12910 The tree will show the lines where the regexp matches, and all higher
12911 headlines above the match.
12912 With a \\[universal-argument] prefix, prompt for a regexp to match.
12913 With a numeric prefix N, construct a sparse tree for the Nth element
12914 of `org-todo-keywords-1'."
12915 (interactive "P")
12916 (let ((case-fold-search nil)
12917 (kwd-re
12918 (cond ((null arg) org-not-done-regexp)
12919 ((equal arg '(4))
12920 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12921 (mapcar 'list org-todo-keywords-1))))
12922 (concat "\\("
12923 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12924 "\\)\\>")))
12925 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12926 (regexp-quote (nth (1- (prefix-numeric-value arg))
12927 org-todo-keywords-1)))
12928 (t (user-error "Invalid prefix argument: %s" arg)))))
12929 (message "%d TODO entries found"
12930 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12932 (defun org-deadline (arg &optional time)
12933 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12934 With one universal prefix argument, remove any deadline from the item.
12935 With two universal prefix arguments, prompt for a warning delay.
12936 With argument TIME, set the deadline at the corresponding date. TIME
12937 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12938 (interactive "P")
12939 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12940 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12941 'region-start-level 'region))
12942 org-loop-over-headlines-in-active-region)
12943 (org-map-entries
12944 `(org-deadline ',arg ,time)
12945 org-loop-over-headlines-in-active-region
12946 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12947 (let* ((old-date (org-entry-get nil "DEADLINE"))
12948 (old-date-time (if old-date (org-time-string-to-time old-date)))
12949 (repeater (and old-date
12950 (string-match
12951 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12952 old-date)
12953 (match-string 1 old-date))))
12954 (cond
12955 ((equal arg '(4))
12956 (when (and old-date org-log-redeadline)
12957 (org-add-log-setup 'deldeadline nil old-date 'findpos
12958 org-log-redeadline))
12959 (org-remove-timestamp-with-keyword org-deadline-string)
12960 (message "Item no longer has a deadline."))
12961 ((equal arg '(16))
12962 (save-excursion
12963 (org-back-to-heading t)
12964 (if (re-search-forward
12965 org-deadline-time-regexp
12966 (save-excursion (outline-next-heading) (point)) t)
12967 (let* ((rpl0 (match-string 1))
12968 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12969 (replace-match
12970 (concat org-deadline-string
12971 " <" rpl
12972 (format " -%dd"
12973 (abs
12974 (- (time-to-days
12975 (save-match-data
12976 (org-read-date nil t nil "Warn starting from" old-date-time)))
12977 (time-to-days old-date-time))))
12978 ">") t t))
12979 (user-error "No deadline information to update"))))
12981 (org-add-planning-info 'deadline time 'closed)
12982 (when (and old-date org-log-redeadline
12983 (not (equal old-date
12984 (substring org-last-inserted-timestamp 1 -1))))
12985 (org-add-log-setup 'redeadline nil old-date 'findpos
12986 org-log-redeadline))
12987 (when repeater
12988 (save-excursion
12989 (org-back-to-heading t)
12990 (when (re-search-forward (concat org-deadline-string " "
12991 org-last-inserted-timestamp)
12992 (save-excursion
12993 (outline-next-heading) (point)) t)
12994 (goto-char (1- (match-end 0)))
12995 (insert " " repeater)
12996 (setq org-last-inserted-timestamp
12997 (concat (substring org-last-inserted-timestamp 0 -1)
12998 " " repeater
12999 (substring org-last-inserted-timestamp -1))))))
13000 (message "Deadline on %s" org-last-inserted-timestamp))))))
13002 (defun org-schedule (arg &optional time)
13003 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13004 With one universal prefix argument, remove any scheduling date from the item.
13005 With two universal prefix arguments, prompt for a delay cookie.
13006 With argument TIME, scheduled at the corresponding date. TIME can
13007 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13008 (interactive "P")
13009 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13010 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13011 'region-start-level 'region))
13012 org-loop-over-headlines-in-active-region)
13013 (org-map-entries
13014 `(org-schedule ',arg ,time)
13015 org-loop-over-headlines-in-active-region
13016 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13017 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13018 (old-date-time (if old-date (org-time-string-to-time old-date)))
13019 (repeater (and old-date
13020 (string-match
13021 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13022 old-date)
13023 (match-string 1 old-date))))
13024 (cond
13025 ((equal arg '(4))
13026 (progn
13027 (when (and old-date org-log-reschedule)
13028 (org-add-log-setup 'delschedule nil old-date 'findpos
13029 org-log-reschedule))
13030 (org-remove-timestamp-with-keyword org-scheduled-string)
13031 (message "Item is no longer scheduled.")))
13032 ((equal arg '(16))
13033 (save-excursion
13034 (org-back-to-heading t)
13035 (if (re-search-forward
13036 org-scheduled-time-regexp
13037 (save-excursion (outline-next-heading) (point)) t)
13038 (let* ((rpl0 (match-string 1))
13039 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13040 (replace-match
13041 (concat org-scheduled-string
13042 " <" rpl
13043 (format " -%dd"
13044 (abs
13045 (- (time-to-days
13046 (save-match-data
13047 (org-read-date nil t nil "Delay until" old-date-time)))
13048 (time-to-days old-date-time))))
13049 ">") t t))
13050 (user-error "No scheduled information to update"))))
13052 (org-add-planning-info 'scheduled time 'closed)
13053 (when (and old-date org-log-reschedule
13054 (not (equal old-date
13055 (substring org-last-inserted-timestamp 1 -1))))
13056 (org-add-log-setup 'reschedule nil old-date 'findpos
13057 org-log-reschedule))
13058 (when repeater
13059 (save-excursion
13060 (org-back-to-heading t)
13061 (when (re-search-forward (concat org-scheduled-string " "
13062 org-last-inserted-timestamp)
13063 (save-excursion
13064 (outline-next-heading) (point)) t)
13065 (goto-char (1- (match-end 0)))
13066 (insert " " repeater)
13067 (setq org-last-inserted-timestamp
13068 (concat (substring org-last-inserted-timestamp 0 -1)
13069 " " repeater
13070 (substring org-last-inserted-timestamp -1))))))
13071 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13073 (defun org-get-scheduled-time (pom &optional inherit)
13074 "Get the scheduled time as a time tuple, of a format suitable
13075 for calling org-schedule with, or if there is no scheduling,
13076 returns nil."
13077 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13078 (when time
13079 (apply 'encode-time (org-parse-time-string time)))))
13081 (defun org-get-deadline-time (pom &optional inherit)
13082 "Get the deadline as a time tuple, of a format suitable for
13083 calling org-deadline with, or if there is no scheduling, returns
13084 nil."
13085 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13086 (when time
13087 (apply 'encode-time (org-parse-time-string time)))))
13089 (defun org-remove-timestamp-with-keyword (keyword)
13090 "Remove all time stamps with KEYWORD in the current entry."
13091 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13092 beg)
13093 (save-excursion
13094 (org-back-to-heading t)
13095 (setq beg (point))
13096 (outline-next-heading)
13097 (while (re-search-backward re beg t)
13098 (replace-match "")
13099 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13100 (equal (char-before) ?\ ))
13101 (backward-delete-char 1)
13102 (if (string-match "^[ \t]*$" (buffer-substring
13103 (point-at-bol) (point-at-eol)))
13104 (delete-region (point-at-bol)
13105 (min (point-max) (1+ (point-at-eol))))))))))
13107 (defun org-add-planning-info (what &optional time &rest remove)
13108 "Insert new timestamp with keyword in the line directly after the headline.
13109 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13110 If non is given, the user is prompted for a date.
13111 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13112 be removed."
13113 (interactive)
13114 (let (org-time-was-given org-end-time-was-given ts
13115 end default-time default-input)
13117 (catch 'exit
13118 (when (and (memq what '(scheduled deadline))
13119 (or (not time)
13120 (and (stringp time)
13121 (string-match "^[-+]+[0-9]" time))))
13122 ;; Try to get a default date/time from existing timestamp
13123 (save-excursion
13124 (org-back-to-heading t)
13125 (setq end (save-excursion (outline-next-heading) (point)))
13126 (when (re-search-forward (if (eq what 'scheduled)
13127 org-scheduled-time-regexp
13128 org-deadline-time-regexp)
13129 end t)
13130 (setq ts (match-string 1)
13131 default-time
13132 (apply 'encode-time (org-parse-time-string ts))
13133 default-input (and ts (org-get-compact-tod ts))))))
13134 (when what
13135 (setq time
13136 (if (stringp time)
13137 ;; This is a string (relative or absolute), set proper date
13138 (apply 'encode-time
13139 (org-read-date-analyze
13140 time default-time (decode-time default-time)))
13141 ;; If necessary, get the time from the user
13142 (or time (org-read-date nil 'to-time nil nil
13143 default-time default-input)))))
13145 (when (and org-insert-labeled-timestamps-at-point
13146 (member what '(scheduled deadline)))
13147 (insert
13148 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13149 (org-insert-time-stamp time org-time-was-given
13150 nil nil nil (list org-end-time-was-given))
13151 (setq what nil))
13152 (save-excursion
13153 (save-restriction
13154 (let (col list elt ts buffer-invisibility-spec)
13155 (org-back-to-heading t)
13156 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13157 (goto-char (match-end 1))
13158 (setq col (current-column))
13159 (goto-char (match-end 0))
13160 (if (eobp) (insert "\n") (forward-char 1))
13161 (when (and (not what)
13162 (not (looking-at
13163 (concat "[ \t]*"
13164 org-keyword-time-not-clock-regexp))))
13165 ;; Nothing to add, nothing to remove...... :-)
13166 (throw 'exit nil))
13167 (if (and (not (looking-at org-outline-regexp))
13168 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13169 "[^\r\n]*"))
13170 (not (equal (match-string 1) org-clock-string)))
13171 (narrow-to-region (match-beginning 0) (match-end 0))
13172 (insert-before-markers "\n")
13173 (backward-char 1)
13174 (narrow-to-region (point) (point))
13175 (and org-adapt-indentation (org-indent-to-column col)))
13176 ;; Check if we have to remove something.
13177 (setq list (cons what remove))
13178 (while list
13179 (setq elt (pop list))
13180 (when (or (and (eq elt 'scheduled)
13181 (re-search-forward org-scheduled-time-regexp nil t))
13182 (and (eq elt 'deadline)
13183 (re-search-forward org-deadline-time-regexp nil t))
13184 (and (eq elt 'closed)
13185 (re-search-forward org-closed-time-regexp nil t)))
13186 (replace-match "")
13187 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13188 (and (looking-at "[ \t]+") (replace-match ""))
13189 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13190 (when what
13191 (insert
13192 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13193 (cond ((eq what 'scheduled) org-scheduled-string)
13194 ((eq what 'deadline) org-deadline-string)
13195 ((eq what 'closed) org-closed-string))
13196 " ")
13197 (setq ts (org-insert-time-stamp
13198 time
13199 (or org-time-was-given
13200 (and (eq what 'closed) org-log-done-with-time))
13201 (eq what 'closed)
13202 nil nil (list org-end-time-was-given)))
13203 (insert
13204 (if (not (or (bolp) (eq (char-before) ?\ )
13205 (memq (char-after) '(32 10))
13206 (eobp))) " " ""))
13207 (end-of-line 1))
13208 (goto-char (point-min))
13209 (widen)
13210 (if (and (looking-at "[ \t]*\n")
13211 (equal (char-before) ?\n))
13212 (delete-region (1- (point)) (point-at-eol)))
13213 ts))))))
13215 (defvar org-log-note-marker (make-marker))
13216 (defvar org-log-note-purpose nil)
13217 (defvar org-log-note-state nil)
13218 (defvar org-log-note-previous-state nil)
13219 (defvar org-log-note-how nil)
13220 (defvar org-log-note-extra nil)
13221 (defvar org-log-note-window-configuration nil)
13222 (defvar org-log-note-return-to (make-marker))
13223 (defvar org-log-note-effective-time nil
13224 "Remembered current time so that dynamically scoped
13225 `org-extend-today-until' affects tha timestamps in state change
13226 log")
13228 (defvar org-log-post-message nil
13229 "Message to be displayed after a log note has been stored.
13230 The auto-repeater uses this.")
13232 (defun org-add-note ()
13233 "Add a note to the current entry.
13234 This is done in the same way as adding a state change note."
13235 (interactive)
13236 (org-add-log-setup 'note nil nil 'findpos nil))
13238 (defvar org-property-end-re)
13239 (defun org-add-log-setup (&optional purpose state prev-state
13240 findpos how extra)
13241 "Set up the post command hook to take a note.
13242 If this is about to TODO state change, the new state is expected in STATE.
13243 When FINDPOS is non-nil, find the correct position for the note in
13244 the current entry. If not, assume that it can be inserted at point.
13245 HOW is an indicator what kind of note should be created.
13246 EXTRA is additional text that will be inserted into the notes buffer."
13247 (let* ((org-log-into-drawer (org-log-into-drawer))
13248 (drawer (cond ((stringp org-log-into-drawer)
13249 org-log-into-drawer)
13250 (org-log-into-drawer "LOGBOOK"))))
13251 (save-restriction
13252 (save-excursion
13253 (when findpos
13254 (org-back-to-heading t)
13255 (narrow-to-region (point) (save-excursion
13256 (outline-next-heading) (point)))
13257 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13258 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13259 "[^\r\n]*\\)?"))
13260 (goto-char (match-end 0))
13261 (cond
13262 (drawer
13263 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13264 nil t)
13265 (progn
13266 (goto-char (match-end 0))
13267 (or org-log-states-order-reversed
13268 (and (re-search-forward org-property-end-re nil t)
13269 (goto-char (1- (match-beginning 0))))))
13270 (insert "\n:" drawer ":\n:END:")
13271 (beginning-of-line 0)
13272 (org-indent-line)
13273 (beginning-of-line 2)
13274 (org-indent-line)
13275 (end-of-line 0)))
13276 ((and org-log-state-notes-insert-after-drawers
13277 (save-excursion
13278 (forward-line) (looking-at org-drawer-regexp)))
13279 (forward-line)
13280 (while (looking-at org-drawer-regexp)
13281 (goto-char (match-end 0))
13282 (re-search-forward org-property-end-re (point-max) t)
13283 (forward-line))
13284 (forward-line -1)))
13285 (unless org-log-states-order-reversed
13286 (and (= (char-after) ?\n) (forward-char 1))
13287 (org-skip-over-state-notes)
13288 (skip-chars-backward " \t\n\r")))
13289 (move-marker org-log-note-marker (point))
13290 (setq org-log-note-purpose purpose
13291 org-log-note-state state
13292 org-log-note-previous-state prev-state
13293 org-log-note-how how
13294 org-log-note-extra extra
13295 org-log-note-effective-time (org-current-effective-time))
13296 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13298 (defun org-skip-over-state-notes ()
13299 "Skip past the list of State notes in an entry."
13300 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13301 (when (ignore-errors (goto-char (org-in-item-p)))
13302 (let* ((struct (org-list-struct))
13303 (prevs (org-list-prevs-alist struct)))
13304 (while (looking-at "[ \t]*- State")
13305 (goto-char (or (org-list-get-next-item (point) struct prevs)
13306 (org-list-get-item-end (point) struct)))))))
13308 (defun org-add-log-note (&optional purpose)
13309 "Pop up a window for taking a note, and add this note later at point."
13310 (remove-hook 'post-command-hook 'org-add-log-note)
13311 (setq org-log-note-window-configuration (current-window-configuration))
13312 (delete-other-windows)
13313 (move-marker org-log-note-return-to (point))
13314 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13315 (goto-char org-log-note-marker)
13316 (org-switch-to-buffer-other-window "*Org Note*")
13317 (erase-buffer)
13318 (if (memq org-log-note-how '(time state))
13319 (let (current-prefix-arg) (org-store-log-note))
13320 (let ((org-inhibit-startup t)) (org-mode))
13321 (insert (format "# Insert note for %s.
13322 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13323 (cond
13324 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13325 ((eq org-log-note-purpose 'done) "closed todo item")
13326 ((eq org-log-note-purpose 'state)
13327 (format "state change from \"%s\" to \"%s\""
13328 (or org-log-note-previous-state "")
13329 (or org-log-note-state "")))
13330 ((eq org-log-note-purpose 'reschedule)
13331 "rescheduling")
13332 ((eq org-log-note-purpose 'delschedule)
13333 "no longer scheduled")
13334 ((eq org-log-note-purpose 'redeadline)
13335 "changing deadline")
13336 ((eq org-log-note-purpose 'deldeadline)
13337 "removing deadline")
13338 ((eq org-log-note-purpose 'refile)
13339 "refiling")
13340 ((eq org-log-note-purpose 'note)
13341 "this entry")
13342 (t (error "This should not happen")))))
13343 (if org-log-note-extra (insert org-log-note-extra))
13344 (org-set-local 'org-finish-function 'org-store-log-note)
13345 (run-hooks 'org-log-buffer-setup-hook)))
13347 (defvar org-note-abort nil) ; dynamically scoped
13348 (defun org-store-log-note ()
13349 "Finish taking a log note, and insert it to where it belongs."
13350 (let ((txt (buffer-string)))
13351 (kill-buffer (current-buffer))
13352 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13353 lines ind bul)
13354 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13355 (setq txt (replace-match "" t t txt)))
13356 (if (string-match "\\s-+\\'" txt)
13357 (setq txt (replace-match "" t t txt)))
13358 (setq lines (org-split-string txt "\n"))
13359 (when (and note (string-match "\\S-" note))
13360 (setq note
13361 (org-replace-escapes
13362 note
13363 (list (cons "%u" (user-login-name))
13364 (cons "%U" user-full-name)
13365 (cons "%t" (format-time-string
13366 (org-time-stamp-format 'long 'inactive)
13367 org-log-note-effective-time))
13368 (cons "%T" (format-time-string
13369 (org-time-stamp-format 'long nil)
13370 org-log-note-effective-time))
13371 (cons "%d" (format-time-string
13372 (org-time-stamp-format nil 'inactive)
13373 org-log-note-effective-time))
13374 (cons "%D" (format-time-string
13375 (org-time-stamp-format nil nil)
13376 org-log-note-effective-time))
13377 (cons "%s" (if org-log-note-state
13378 (concat "\"" org-log-note-state "\"")
13379 ""))
13380 (cons "%S" (if org-log-note-previous-state
13381 (concat "\"" org-log-note-previous-state "\"")
13382 "\"\"")))))
13383 (if lines (setq note (concat note " \\\\")))
13384 (push note lines))
13385 (when (or current-prefix-arg org-note-abort)
13386 (when org-log-into-drawer
13387 (org-remove-empty-drawer-at
13388 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13389 org-log-note-marker))
13390 (setq lines nil))
13391 (when lines
13392 (with-current-buffer (marker-buffer org-log-note-marker)
13393 (save-excursion
13394 (goto-char org-log-note-marker)
13395 (move-marker org-log-note-marker nil)
13396 (end-of-line 1)
13397 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13398 (setq ind (save-excursion
13399 (if (ignore-errors (goto-char (org-in-item-p)))
13400 (let ((struct (org-list-struct)))
13401 (org-list-get-ind
13402 (org-list-get-top-point struct) struct))
13403 (skip-chars-backward " \r\t\n")
13404 (cond
13405 ((and (org-at-heading-p)
13406 org-adapt-indentation)
13407 (1+ (org-current-level)))
13408 ((org-at-heading-p) 0)
13409 (t (org-get-indentation))))))
13410 (setq bul (org-list-bullet-string "-"))
13411 (org-indent-line-to ind)
13412 (insert bul (pop lines))
13413 (let ((ind-body (+ (length bul) ind)))
13414 (while lines
13415 (insert "\n")
13416 (org-indent-line-to ind-body)
13417 (insert (pop lines))))
13418 (message "Note stored")
13419 (org-back-to-heading t)
13420 (org-cycle-hide-drawers 'children))
13421 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13422 ;; from within `org-add-log-note' because `buffer-undo-list'
13423 ;; is then modified outside of `org-with-remote-undo'.
13424 (when (eq this-command 'org-agenda-todo)
13425 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13426 ;; Don't add undo information when called from `org-agenda-todo'
13427 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13428 (set-window-configuration org-log-note-window-configuration)
13429 (with-current-buffer (marker-buffer org-log-note-return-to)
13430 (goto-char org-log-note-return-to))
13431 (move-marker org-log-note-return-to nil)
13432 (and org-log-post-message (message "%s" org-log-post-message))))
13434 (defun org-remove-empty-drawer-at (drawer pos)
13435 "Remove an empty drawer DRAWER at position POS.
13436 POS may also be a marker."
13437 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13438 (save-excursion
13439 (save-restriction
13440 (widen)
13441 (goto-char pos)
13442 (if (org-in-regexp
13443 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13444 (replace-match ""))))))
13446 (defvar org-ts-type nil)
13447 (defun org-sparse-tree (&optional arg type)
13448 "Create a sparse tree, prompt for the details.
13449 This command can create sparse trees. You first need to select the type
13450 of match used to create the tree:
13452 t Show all TODO entries.
13453 T Show entries with a specific TODO keyword.
13454 m Show entries selected by a tags/property match.
13455 p Enter a property name and its value (both with completion on existing
13456 names/values) and show entries with that property.
13457 r Show entries matching a regular expression (`/' can be used as well).
13458 b Show deadlines and scheduled items before a date.
13459 a Show deadlines and scheduled items after a date.
13460 d Show deadlines due within `org-deadline-warning-days'.
13461 D Show deadlines and scheduled items between a date range."
13462 (interactive "P")
13463 (let (ans kwd value ts-type)
13464 (setq type (or type org-sparse-tree-default-date-type))
13465 (setq org-ts-type type)
13466 (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"
13467 (cond ((eq type 'all) "all timestamps")
13468 ((eq type 'scheduled) "only scheduled")
13469 ((eq type 'deadline) "only deadline")
13470 ((eq type 'active) "only active timestamps")
13471 ((eq type 'inactive) "only inactive timestamps")
13472 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13473 ((eq type 'closed) "with a closed time-stamp")
13474 (t "scheduled/deadline")))
13475 (setq ans (read-char-exclusive))
13476 (cond
13477 ((equal ans ?c)
13478 (org-sparse-tree
13479 arg (cadr (member type '(scheduled-or-deadline
13480 all scheduled deadline active inactive closed)))))
13481 ((equal ans ?d)
13482 (call-interactively 'org-check-deadlines))
13483 ((equal ans ?b)
13484 (call-interactively 'org-check-before-date))
13485 ((equal ans ?a)
13486 (call-interactively 'org-check-after-date))
13487 ((equal ans ?D)
13488 (call-interactively 'org-check-dates-range))
13489 ((equal ans ?t)
13490 (call-interactively 'org-show-todo-tree))
13491 ((equal ans ?T)
13492 (org-show-todo-tree '(4)))
13493 ((member ans '(?T ?m))
13494 (call-interactively 'org-match-sparse-tree))
13495 ((member ans '(?p ?P))
13496 (setq kwd (org-icompleting-read "Property: "
13497 (mapcar 'list (org-buffer-property-keys))))
13498 (setq value (org-icompleting-read "Value: "
13499 (mapcar 'list (org-property-values kwd))))
13500 (unless (string-match "\\`{.*}\\'" value)
13501 (setq value (concat "\"" value "\"")))
13502 (org-match-sparse-tree arg (concat kwd "=" value)))
13503 ((member ans '(?r ?R ?/))
13504 (call-interactively 'org-occur))
13505 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13507 (defvar org-occur-highlights nil
13508 "List of overlays used for occur matches.")
13509 (make-variable-buffer-local 'org-occur-highlights)
13510 (defvar org-occur-parameters nil
13511 "Parameters of the active org-occur calls.
13512 This is a list, each call to org-occur pushes as cons cell,
13513 containing the regular expression and the callback, onto the list.
13514 The list can contain several entries if `org-occur' has been called
13515 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13516 will only contain one set of parameters. When the highlights are
13517 removed (for example with `C-c C-c', or with the next edit (depending
13518 on `org-remove-highlights-with-change'), this variable is emptied
13519 as well.")
13520 (make-variable-buffer-local 'org-occur-parameters)
13522 (defun org-occur (regexp &optional keep-previous callback)
13523 "Make a compact tree which shows all matches of REGEXP.
13524 The tree will show the lines where the regexp matches, and all higher
13525 headlines above the match. It will also show the heading after the match,
13526 to make sure editing the matching entry is easy.
13527 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13528 call to `org-occur' will be kept, to allow stacking of calls to this
13529 command.
13530 If CALLBACK is non-nil, it is a function which is called to confirm
13531 that the match should indeed be shown."
13532 (interactive "sRegexp: \nP")
13533 (when (equal regexp "")
13534 (user-error "Regexp cannot be empty"))
13535 (unless keep-previous
13536 (org-remove-occur-highlights nil nil t))
13537 (push (cons regexp callback) org-occur-parameters)
13538 (let ((cnt 0))
13539 (save-excursion
13540 (goto-char (point-min))
13541 (if (or (not keep-previous) ; do not want to keep
13542 (not org-occur-highlights)) ; no previous matches
13543 ;; hide everything
13544 (org-overview))
13545 (while (re-search-forward regexp nil t)
13546 (when (or (not callback)
13547 (save-match-data (funcall callback)))
13548 (setq cnt (1+ cnt))
13549 (when org-highlight-sparse-tree-matches
13550 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13551 (org-show-context 'occur-tree))))
13552 (when org-remove-highlights-with-change
13553 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13554 nil 'local))
13555 (unless org-sparse-tree-open-archived-trees
13556 (org-hide-archived-subtrees (point-min) (point-max)))
13557 (run-hooks 'org-occur-hook)
13558 (if (org-called-interactively-p 'interactive)
13559 (message "%d match(es) for regexp %s" cnt regexp))
13560 cnt))
13562 (defun org-occur-next-match (&optional n reset)
13563 "Function for `next-error-function' to find sparse tree matches.
13564 N is the number of matches to move, when negative move backwards.
13565 RESET is entirely ignored - this function always goes back to the
13566 starting point when no match is found."
13567 (let* ((limit (if (< n 0) (point-min) (point-max)))
13568 (search-func (if (< n 0)
13569 'previous-single-char-property-change
13570 'next-single-char-property-change))
13571 (n (abs n))
13572 (pos (point))
13574 (catch 'exit
13575 (while (setq p1 (funcall search-func (point) 'org-type))
13576 (when (equal p1 limit)
13577 (goto-char pos)
13578 (error "No more matches"))
13579 (when (equal (get-char-property p1 'org-type) 'org-occur)
13580 (setq n (1- n))
13581 (when (= n 0)
13582 (goto-char p1)
13583 (throw 'exit (point))))
13584 (goto-char p1))
13585 (goto-char p1)
13586 (error "No more matches"))))
13588 (defun org-show-context (&optional key)
13589 "Make sure point and context are visible.
13590 How much context is shown depends upon the variables
13591 `org-show-hierarchy-above', `org-show-following-heading',
13592 `org-show-entry-below' and `org-show-siblings'."
13593 (let ((heading-p (org-at-heading-p t))
13594 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13595 (following-p (org-get-alist-option org-show-following-heading key))
13596 (entry-p (org-get-alist-option org-show-entry-below key))
13597 (siblings-p (org-get-alist-option org-show-siblings key)))
13598 ;; Show heading or entry text
13599 (if (and heading-p (not entry-p))
13600 (org-flag-heading nil) ; only show the heading
13601 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13602 (org-show-hidden-entry))) ; show entire entry
13603 (when following-p
13604 ;; Show next sibling, or heading below text
13605 (save-excursion
13606 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13607 (org-flag-heading nil))))
13608 (when siblings-p (org-show-siblings))
13609 (when hierarchy-p
13610 ;; show all higher headings, possibly with siblings
13611 (save-excursion
13612 (while (and (condition-case nil
13613 (progn (org-up-heading-all 1) t)
13614 (error nil))
13615 (not (bobp)))
13616 (org-flag-heading nil)
13617 (when siblings-p (org-show-siblings)))))
13618 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13620 (defvar org-reveal-start-hook nil
13621 "Hook run before revealing a location.")
13623 (defun org-reveal (&optional siblings)
13624 "Show current entry, hierarchy above it, and the following headline.
13625 This can be used to show a consistent set of context around locations
13626 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13627 not t for the search context.
13629 With optional argument SIBLINGS, on each level of the hierarchy all
13630 siblings are shown. This repairs the tree structure to what it would
13631 look like when opened with hierarchical calls to `org-cycle'.
13632 With double optional argument \\[universal-argument] \\[universal-argument], \
13633 go to the parent and show the
13634 entire tree."
13635 (interactive "P")
13636 (run-hooks 'org-reveal-start-hook)
13637 (let ((org-show-hierarchy-above t)
13638 (org-show-following-heading t)
13639 (org-show-siblings (if siblings t org-show-siblings)))
13640 (org-show-context nil))
13641 (when (equal siblings '(16))
13642 (save-excursion
13643 (when (org-up-heading-safe)
13644 (org-show-subtree)
13645 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13647 (defun org-highlight-new-match (beg end)
13648 "Highlight from BEG to END and mark the highlight is an occur headline."
13649 (let ((ov (make-overlay beg end)))
13650 (overlay-put ov 'face 'secondary-selection)
13651 (overlay-put ov 'org-type 'org-occur)
13652 (push ov org-occur-highlights)))
13654 (defun org-remove-occur-highlights (&optional beg end noremove)
13655 "Remove the occur highlights from the buffer.
13656 BEG and END are ignored. If NOREMOVE is nil, remove this function
13657 from the `before-change-functions' in the current buffer."
13658 (interactive)
13659 (unless org-inhibit-highlight-removal
13660 (mapc 'delete-overlay org-occur-highlights)
13661 (setq org-occur-highlights nil)
13662 (setq org-occur-parameters nil)
13663 (unless noremove
13664 (remove-hook 'before-change-functions
13665 'org-remove-occur-highlights 'local))))
13667 ;;;; Priorities
13669 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13670 "Regular expression matching the priority indicator.")
13672 (defvar org-remove-priority-next-time nil)
13674 (defun org-priority-up ()
13675 "Increase the priority of the current item."
13676 (interactive)
13677 (org-priority 'up))
13679 (defun org-priority-down ()
13680 "Decrease the priority of the current item."
13681 (interactive)
13682 (org-priority 'down))
13684 (defun org-priority (&optional action show)
13685 "Change the priority of an item.
13686 ACTION can be `set', `up', `down', or a character."
13687 (interactive "P")
13688 (if (equal action '(4))
13689 (org-show-priority)
13690 (unless org-enable-priority-commands
13691 (user-error "Priority commands are disabled"))
13692 (setq action (or action 'set))
13693 (let (current new news have remove)
13694 (save-excursion
13695 (org-back-to-heading t)
13696 (if (looking-at org-priority-regexp)
13697 (setq current (string-to-char (match-string 2))
13698 have t))
13699 (cond
13700 ((eq action 'remove)
13701 (setq remove t new ?\ ))
13702 ((or (eq action 'set)
13703 (if (featurep 'xemacs) (characterp action) (integerp action)))
13704 (if (not (eq action 'set))
13705 (setq new action)
13706 (message "Priority %c-%c, SPC to remove: "
13707 org-highest-priority org-lowest-priority)
13708 (save-match-data
13709 (setq new (read-char-exclusive))))
13710 (if (and (= (upcase org-highest-priority) org-highest-priority)
13711 (= (upcase org-lowest-priority) org-lowest-priority))
13712 (setq new (upcase new)))
13713 (cond ((equal new ?\ ) (setq remove t))
13714 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13715 (user-error "Priority must be between `%c' and `%c'"
13716 org-highest-priority org-lowest-priority))))
13717 ((eq action 'up)
13718 (setq new (if have
13719 (1- current) ; normal cycling
13720 ;; last priority was empty
13721 (if (eq last-command this-command)
13722 org-lowest-priority ; wrap around empty to lowest
13723 ;; default
13724 (if org-priority-start-cycle-with-default
13725 org-default-priority
13726 (1- org-default-priority))))))
13727 ((eq action 'down)
13728 (setq new (if have
13729 (1+ current) ; normal cycling
13730 ;; last priority was empty
13731 (if (eq last-command this-command)
13732 org-highest-priority ; wrap around empty to highest
13733 ;; default
13734 (if org-priority-start-cycle-with-default
13735 org-default-priority
13736 (1+ org-default-priority))))))
13737 (t (user-error "Invalid action")))
13738 (if (or (< (upcase new) org-highest-priority)
13739 (> (upcase new) org-lowest-priority))
13740 (if (and (memq action '(up down))
13741 (not have) (not (eq last-command this-command)))
13742 ;; `new' is from default priority
13743 (error
13744 "The default can not be set, see `org-default-priority' why")
13745 ;; normal cycling: `new' is beyond highest/lowest priority
13746 ;; and is wrapped around to the empty priority
13747 (setq remove t)))
13748 (setq news (format "%c" new))
13749 (if have
13750 (if remove
13751 (replace-match "" t t nil 1)
13752 (replace-match news t t nil 2))
13753 (if remove
13754 (user-error "No priority cookie found in line")
13755 (let ((case-fold-search nil))
13756 (looking-at org-todo-line-regexp))
13757 (if (match-end 2)
13758 (progn
13759 (goto-char (match-end 2))
13760 (insert " [#" news "]"))
13761 (goto-char (match-beginning 3))
13762 (insert "[#" news "] "))))
13763 (org-preserve-lc (org-set-tags nil 'align)))
13764 (if remove
13765 (message "Priority removed")
13766 (message "Priority of current item set to %s" news)))))
13768 (defun org-show-priority ()
13769 "Show the priority of the current item.
13770 This priority is composed of the main priority given with the [#A] cookies,
13771 and by additional input from the age of a schedules or deadline entry."
13772 (interactive)
13773 (let ((pri (if (eq major-mode 'org-agenda-mode)
13774 (org-get-at-bol 'priority)
13775 (save-excursion
13776 (save-match-data
13777 (beginning-of-line)
13778 (and (looking-at org-heading-regexp)
13779 (org-get-priority (match-string 0))))))))
13780 (message "Priority is %d" (if pri pri -1000))))
13782 (defun org-get-priority (s)
13783 "Find priority cookie and return priority."
13784 (save-match-data
13785 (if (functionp org-get-priority-function)
13786 (funcall org-get-priority-function)
13787 (if (not (string-match org-priority-regexp s))
13788 (* 1000 (- org-lowest-priority org-default-priority))
13789 (* 1000 (- org-lowest-priority
13790 (string-to-char (match-string 2 s))))))))
13792 ;;;; Tags
13794 (defvar org-agenda-archives-mode)
13795 (defvar org-map-continue-from nil
13796 "Position from where mapping should continue.
13797 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13799 (defvar org-scanner-tags nil
13800 "The current tag list while the tags scanner is running.")
13801 (defvar org-trust-scanner-tags nil
13802 "Should `org-get-tags-at' use the tags for the scanner.
13803 This is for internal dynamical scoping only.
13804 When this is non-nil, the function `org-get-tags-at' will return the value
13805 of `org-scanner-tags' instead of building the list by itself. This
13806 can lead to large speed-ups when the tags scanner is used in a file with
13807 many entries, and when the list of tags is retrieved, for example to
13808 obtain a list of properties. Building the tags list for each entry in such
13809 a file becomes an N^2 operation - but with this variable set, it scales
13810 as N.")
13812 (defun org-scan-tags (action matcher todo-only &optional start-level)
13813 "Sca headline tags with inheritance and produce output ACTION.
13815 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13816 or `agenda' to produce an entry list for an agenda view. It can also be
13817 a Lisp form or a function that should be called at each matched headline, in
13818 this case the return value is a list of all return values from these calls.
13820 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13821 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13822 only lines with a not-done TODO keyword are included in the output.
13823 This should be the same variable that was scoped into
13824 and set by `org-make-tags-matcher' when it constructed MATCHER.
13826 START-LEVEL can be a string with asterisks, reducing the scope to
13827 headlines matching this string."
13828 (require 'org-agenda)
13829 (let* ((re (concat "^"
13830 (if start-level
13831 ;; Get the correct level to match
13832 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13833 org-outline-regexp)
13834 " *\\(\\<\\("
13835 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13836 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13837 (props (list 'face 'default
13838 'done-face 'org-agenda-done
13839 'undone-face 'default
13840 'mouse-face 'highlight
13841 'org-not-done-regexp org-not-done-regexp
13842 'org-todo-regexp org-todo-regexp
13843 'org-complex-heading-regexp org-complex-heading-regexp
13844 'help-echo
13845 (format "mouse-2 or RET jump to org file %s"
13846 (abbreviate-file-name
13847 (or (buffer-file-name (buffer-base-buffer))
13848 (buffer-name (buffer-base-buffer)))))))
13849 (org-map-continue-from nil)
13850 lspos tags tags-list
13851 (tags-alist (list (cons 0 org-file-tags)))
13852 (llast 0) rtn rtn1 level category i txt
13853 todo marker entry priority)
13854 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13855 (setq action (list 'lambda nil action)))
13856 (save-excursion
13857 (goto-char (point-min))
13858 (when (eq action 'sparse-tree)
13859 (org-overview)
13860 (org-remove-occur-highlights))
13861 (while (let (case-fold-search)
13862 (re-search-forward re nil t))
13863 (setq org-map-continue-from nil)
13864 (catch :skip
13865 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13866 tags (if (match-end 4) (org-match-string-no-properties 4)))
13867 (goto-char (setq lspos (match-beginning 0)))
13868 (setq level (org-reduced-level (org-outline-level))
13869 category (org-get-category))
13870 (setq i llast llast level)
13871 ;; remove tag lists from same and sublevels
13872 (while (>= i level)
13873 (when (setq entry (assoc i tags-alist))
13874 (setq tags-alist (delete entry tags-alist)))
13875 (setq i (1- i)))
13876 ;; add the next tags
13877 (when tags
13878 (setq tags (org-split-string tags ":")
13879 tags-alist
13880 (cons (cons level tags) tags-alist)))
13881 ;; compile tags for current headline
13882 (setq tags-list
13883 (if org-use-tag-inheritance
13884 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13885 tags)
13886 org-scanner-tags tags-list)
13887 (when org-use-tag-inheritance
13888 (setcdr (car tags-alist)
13889 (mapcar (lambda (x)
13890 (setq x (copy-sequence x))
13891 (org-add-prop-inherited x))
13892 (cdar tags-alist))))
13893 (when (and tags org-use-tag-inheritance
13894 (or (not (eq t org-use-tag-inheritance))
13895 org-tags-exclude-from-inheritance))
13896 ;; selective inheritance, remove uninherited ones
13897 (setcdr (car tags-alist)
13898 (org-remove-uninherited-tags (cdar tags-alist))))
13899 (when (and
13901 ;; eval matcher only when the todo condition is OK
13902 (and (or (not todo-only) (member todo org-not-done-keywords))
13903 (let ((case-fold-search t) (org-trust-scanner-tags t))
13904 (eval matcher)))
13906 ;; Call the skipper, but return t if it does not skip,
13907 ;; so that the `and' form continues evaluating
13908 (progn
13909 (unless (eq action 'sparse-tree) (org-agenda-skip))
13912 ;; Check if timestamps are deselecting this entry
13913 (or (not todo-only)
13914 (and (member todo org-not-done-keywords)
13915 (or (not org-agenda-tags-todo-honor-ignore-options)
13916 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13918 ;; select this headline
13919 (cond
13920 ((eq action 'sparse-tree)
13921 (and org-highlight-sparse-tree-matches
13922 (org-get-heading) (match-end 0)
13923 (org-highlight-new-match
13924 (match-beginning 1) (match-end 1)))
13925 (org-show-context 'tags-tree))
13926 ((eq action 'agenda)
13927 (setq txt (org-agenda-format-item
13929 (concat
13930 (if (eq org-tags-match-list-sublevels 'indented)
13931 (make-string (1- level) ?.) "")
13932 (org-get-heading))
13933 level category
13934 tags-list)
13935 priority (org-get-priority txt))
13936 (goto-char lspos)
13937 (setq marker (org-agenda-new-marker))
13938 (org-add-props txt props
13939 'org-marker marker 'org-hd-marker marker 'org-category category
13940 'todo-state todo
13941 'priority priority 'type "tagsmatch")
13942 (push txt rtn))
13943 ((functionp action)
13944 (setq org-map-continue-from nil)
13945 (save-excursion
13946 (setq rtn1 (funcall action))
13947 (push rtn1 rtn)))
13948 (t (user-error "Invalid action")))
13950 ;; if we are to skip sublevels, jump to end of subtree
13951 (unless org-tags-match-list-sublevels
13952 (org-end-of-subtree t)
13953 (backward-char 1))))
13954 ;; Get the correct position from where to continue
13955 (if org-map-continue-from
13956 (goto-char org-map-continue-from)
13957 (and (= (point) lspos) (end-of-line 1)))))
13958 (when (and (eq action 'sparse-tree)
13959 (not org-sparse-tree-open-archived-trees))
13960 (org-hide-archived-subtrees (point-min) (point-max)))
13961 (nreverse rtn)))
13963 (defun org-remove-uninherited-tags (tags)
13964 "Remove all tags that are not inherited from the list TAGS."
13965 (cond
13966 ((eq org-use-tag-inheritance t)
13967 (if org-tags-exclude-from-inheritance
13968 (org-delete-all org-tags-exclude-from-inheritance tags)
13969 tags))
13970 ((not org-use-tag-inheritance) nil)
13971 ((stringp org-use-tag-inheritance)
13972 (delq nil (mapcar
13973 (lambda (x)
13974 (if (and (string-match org-use-tag-inheritance x)
13975 (not (member x org-tags-exclude-from-inheritance)))
13976 x nil))
13977 tags)))
13978 ((listp org-use-tag-inheritance)
13979 (delq nil (mapcar
13980 (lambda (x)
13981 (if (member x org-use-tag-inheritance) x nil))
13982 tags)))))
13984 (defun org-match-sparse-tree (&optional todo-only match)
13985 "Create a sparse tree according to tags string MATCH.
13986 MATCH can contain positive and negative selection of tags, like
13987 \"+WORK+URGENT-WITHBOSS\".
13988 If optional argument TODO-ONLY is non-nil, only select lines that are
13989 also TODO lines."
13990 (interactive "P")
13991 (org-agenda-prepare-buffers (list (current-buffer)))
13992 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13994 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13996 (defvar org-cached-props nil)
13997 (defun org-cached-entry-get (pom property)
13998 (if (or (eq t org-use-property-inheritance)
13999 (and (stringp org-use-property-inheritance)
14000 (string-match org-use-property-inheritance property))
14001 (and (listp org-use-property-inheritance)
14002 (member property org-use-property-inheritance)))
14003 ;; Caching is not possible, check it directly
14004 (org-entry-get pom property 'inherit)
14005 ;; Get all properties, so that we can do complicated checks easily
14006 (cdr (assoc property (or org-cached-props
14007 (setq org-cached-props
14008 (org-entry-properties pom)))))))
14010 (defun org-global-tags-completion-table (&optional files)
14011 "Return the list of all tags in all agenda buffer/files.
14012 Optional FILES argument is a list of files which can be used
14013 instead of the agenda files."
14014 (save-excursion
14015 (org-uniquify
14016 (delq nil
14017 (apply 'append
14018 (mapcar
14019 (lambda (file)
14020 (set-buffer (find-file-noselect file))
14021 (append (org-get-buffer-tags)
14022 (mapcar (lambda (x) (if (stringp (car-safe x))
14023 (list (car-safe x)) nil))
14024 org-tag-alist)))
14025 (if (and files (car files))
14026 files
14027 (org-agenda-files))))))))
14029 (defun org-make-tags-matcher (match)
14030 "Create the TAGS/TODO matcher form for the selection string MATCH.
14032 The variable `todo-only' is scoped dynamically into this function.
14033 It will be set to t if the matcher restricts matching to TODO entries,
14034 otherwise will not be touched.
14036 Returns a cons of the selection string MATCH and the constructed
14037 lisp form implementing the matcher. The matcher is to be evaluated
14038 at an Org entry, with point on the headline, and returns t if the
14039 entry matches the selection string MATCH. The returned lisp form
14040 references two variables with information about the entry, which
14041 must be bound around the form's evaluation: todo, the TODO keyword
14042 at the entry (or nil of none); and tags-list, the list of all tags
14043 at the entry including inherited ones. Additionally, the category
14044 of the entry (if any) must be specified as the text property
14045 'org-category on the headline.
14047 See also `org-scan-tags'.
14049 (declare (special todo-only))
14050 (unless (boundp 'todo-only)
14051 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14052 (unless match
14053 ;; Get a new match request, with completion against the global
14054 ;; tags table and the local tags in current buffer
14055 (let ((org-last-tags-completion-table
14056 (org-uniquify
14057 (delq nil (append (org-get-buffer-tags)
14058 (org-global-tags-completion-table))))))
14059 (setq match (org-completing-read-no-i
14060 "Match: " 'org-tags-completion-function nil nil nil
14061 'org-tags-history))))
14063 ;; Parse the string and create a lisp form
14064 (let ((match0 match)
14065 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14066 minus tag mm
14067 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14068 orterms term orlist re-p str-p level-p level-op time-p
14069 prop-p pn pv po gv rest (start 0) (ss 0))
14070 ;; Expand group tags
14071 (setq match (org-tags-expand match))
14073 ;; Check if there is a TODO part of this match, which would be the
14074 ;; part after a "/". TO make sure that this slash is not part of
14075 ;; a property value to be matched against, we also check that there
14076 ;; is no " after that slash.
14077 ;; First, find the last slash
14078 (while (string-match "/+" match ss)
14079 (setq start (match-beginning 0) ss (match-end 0)))
14080 (if (and (string-match "/+" match start)
14081 (not (save-match-data (string-match "\"" match start))))
14082 ;; match contains also a todo-matching request
14083 (progn
14084 (setq tagsmatch (substring match 0 (match-beginning 0))
14085 todomatch (substring match (match-end 0)))
14086 (if (string-match "^!" todomatch)
14087 (setq todo-only t todomatch (substring todomatch 1)))
14088 (if (string-match "^\\s-*$" todomatch)
14089 (setq todomatch nil)))
14090 ;; only matching tags
14091 (setq tagsmatch match todomatch nil))
14093 ;; Make the tags matcher
14094 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14095 (setq tagsmatcher t)
14096 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14097 (while (setq term (pop orterms))
14098 (while (and (equal (substring term -1) "\\") orterms)
14099 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14100 (while (string-match re term)
14101 (setq rest (substring term (match-end 0))
14102 minus (and (match-end 1)
14103 (equal (match-string 1 term) "-"))
14104 tag (save-match-data (replace-regexp-in-string
14105 "\\\\-" "-"
14106 (match-string 2 term)))
14107 re-p (equal (string-to-char tag) ?{)
14108 level-p (match-end 4)
14109 prop-p (match-end 5)
14110 mm (cond
14111 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14112 (level-p
14113 (setq level-op (org-op-to-function (match-string 3 term)))
14114 `(,level-op level ,(string-to-number
14115 (match-string 4 term))))
14116 (prop-p
14117 (setq pn (match-string 5 term)
14118 po (match-string 6 term)
14119 pv (match-string 7 term)
14120 re-p (equal (string-to-char pv) ?{)
14121 str-p (equal (string-to-char pv) ?\")
14122 time-p (save-match-data
14123 (string-match "^\"[[<].*[]>]\"$" pv))
14124 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14125 (if time-p (setq pv (org-matcher-time pv)))
14126 (setq po (org-op-to-function po (if time-p 'time str-p)))
14127 (cond
14128 ((equal pn "CATEGORY")
14129 (setq gv '(get-text-property (point) 'org-category)))
14130 ((equal pn "TODO")
14131 (setq gv 'todo))
14133 (setq gv `(org-cached-entry-get nil ,pn))))
14134 (if re-p
14135 (if (eq po 'org<>)
14136 `(not (string-match ,pv (or ,gv "")))
14137 `(string-match ,pv (or ,gv "")))
14138 (if str-p
14139 `(,po (or ,gv "") ,pv)
14140 `(,po (string-to-number (or ,gv ""))
14141 ,(string-to-number pv) ))))
14142 (t `(member ,tag tags-list)))
14143 mm (if minus (list 'not mm) mm)
14144 term rest)
14145 (push mm tagsmatcher))
14146 (push (if (> (length tagsmatcher) 1)
14147 (cons 'and tagsmatcher)
14148 (car tagsmatcher))
14149 orlist)
14150 (setq tagsmatcher nil))
14151 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14152 (setq tagsmatcher
14153 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14154 ;; Make the todo matcher
14155 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14156 (setq todomatcher t)
14157 (setq orterms (org-split-string todomatch "|") orlist nil)
14158 (while (setq term (pop orterms))
14159 (while (string-match re term)
14160 (setq minus (and (match-end 1)
14161 (equal (match-string 1 term) "-"))
14162 kwd (match-string 2 term)
14163 re-p (equal (string-to-char kwd) ?{)
14164 term (substring term (match-end 0))
14165 mm (if re-p
14166 `(string-match ,(substring kwd 1 -1) todo)
14167 (list 'equal 'todo kwd))
14168 mm (if minus (list 'not mm) mm))
14169 (push mm todomatcher))
14170 (push (if (> (length todomatcher) 1)
14171 (cons 'and todomatcher)
14172 (car todomatcher))
14173 orlist)
14174 (setq todomatcher nil))
14175 (setq todomatcher (if (> (length orlist) 1)
14176 (cons 'or orlist) (car orlist))))
14178 ;; Return the string and lisp forms of the matcher
14179 (setq matcher (if todomatcher
14180 (list 'and tagsmatcher todomatcher)
14181 tagsmatcher))
14182 (when todo-only
14183 (setq matcher (list 'and '(member todo org-not-done-keywords)
14184 matcher)))
14185 (cons match0 matcher)))
14187 (defun org-tags-expand (match &optional single-as-list downcased)
14188 "Expand group tags in MATCH.
14190 This replaces every group tag in MATCH with a regexp tag search.
14191 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14192 will be replaced like this:
14194 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14195 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14196 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14198 Replacing by a regexp preserves the structure of the match.
14199 E.g., this expansion
14201 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14203 will match anything tagged with \"Lab\" and \"Home\", or tagged
14204 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14206 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14207 assumed to be a single group tag, and the function will return
14208 the list of tags in this group.
14210 When DOWNCASE is non-nil, expand downcased TAGS."
14211 (if org-group-tags
14212 (let* ((case-fold-search t)
14213 (stable org-mode-syntax-table)
14214 (tal (or org-tag-groups-alist-for-agenda
14215 org-tag-groups-alist))
14216 (tal (if downcased
14217 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14218 (tml (mapcar 'car tal))
14219 (rtnmatch match) rpl)
14220 ;; @ and _ are allowed as word-components in tags
14221 (modify-syntax-entry ?@ "w" stable)
14222 (modify-syntax-entry ?_ "w" stable)
14223 (while (and tml
14224 (with-syntax-table stable
14225 (string-match
14226 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14227 (regexp-opt tml) "\\>\\)") rtnmatch)))
14228 (let* ((dir (match-string 1 rtnmatch))
14229 (tag (match-string 2 rtnmatch))
14230 (tag (if downcased (downcase tag) tag)))
14231 (setq tml (delete tag tml))
14232 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14233 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14234 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14235 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14236 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14237 (if single-as-list
14238 (or (reverse rpl) (list rtnmatch))
14239 rtnmatch))
14240 (if single-as-list (list (if downcased (downcase match) match))
14241 match)))
14243 (defun org-op-to-function (op &optional stringp)
14244 "Turn an operator into the appropriate function."
14245 (setq op
14246 (cond
14247 ((equal op "<" ) '(< string< org-time<))
14248 ((equal op ">" ) '(> org-string> org-time>))
14249 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14250 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14251 ((member op '("=" "==")) '(= string= org-time=))
14252 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14253 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14255 (defun org<> (a b) (not (= a b)))
14256 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14257 (defun org-string>= (a b) (not (string< a b)))
14258 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14259 (defun org-string<> (a b) (not (string= a b)))
14260 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14261 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14262 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14263 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14264 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14265 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14266 (defun org-2ft (s)
14267 "Convert S to a floating point time.
14268 If S is already a number, just return it. If it is a string, parse
14269 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14270 (cond
14271 ((numberp s) s)
14272 ((stringp s)
14273 (condition-case nil
14274 (float-time (apply 'encode-time (org-parse-time-string s)))
14275 (error 0.)))
14276 (t 0.)))
14278 (defun org-time-today ()
14279 "Time in seconds today at 0:00.
14280 Returns the float number of seconds since the beginning of the
14281 epoch to the beginning of today (00:00)."
14282 (float-time (apply 'encode-time
14283 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14285 (defun org-matcher-time (s)
14286 "Interpret a time comparison value."
14287 (save-match-data
14288 (cond
14289 ((string= s "<now>") (float-time))
14290 ((string= s "<today>") (org-time-today))
14291 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14292 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14293 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14294 (+ (org-time-today)
14295 (* (string-to-number (match-string 1 s))
14296 (cdr (assoc (match-string 2 s)
14297 '(("d" . 86400.0) ("w" . 604800.0)
14298 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14299 (t (org-2ft s)))))
14301 (defun org-match-any-p (re list)
14302 "Does re match any element of list?"
14303 (setq list (mapcar (lambda (x) (string-match re x)) list))
14304 (delq nil list))
14306 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14307 (defvar org-tags-overlay (make-overlay 1 1))
14308 (org-detach-overlay org-tags-overlay)
14310 (defun org-get-local-tags-at (&optional pos)
14311 "Get a list of tags defined in the current headline."
14312 (org-get-tags-at pos 'local))
14314 (defun org-get-local-tags ()
14315 "Get a list of tags defined in the current headline."
14316 (org-get-tags-at nil 'local))
14318 (defun org-get-tags-at (&optional pos local)
14319 "Get a list of all headline tags applicable at POS.
14320 POS defaults to point. If tags are inherited, the list contains
14321 the targets in the same sequence as the headlines appear, i.e.
14322 the tags of the current headline come last.
14323 When LOCAL is non-nil, only return tags from the current headline,
14324 ignore inherited ones."
14325 (interactive)
14326 (if (and org-trust-scanner-tags
14327 (or (not pos) (equal pos (point)))
14328 (not local))
14329 org-scanner-tags
14330 (let (tags ltags lastpos parent)
14331 (save-excursion
14332 (save-restriction
14333 (widen)
14334 (goto-char (or pos (point)))
14335 (save-match-data
14336 (catch 'done
14337 (condition-case nil
14338 (progn
14339 (org-back-to-heading t)
14340 (while (not (equal lastpos (point)))
14341 (setq lastpos (point))
14342 (when (looking-at
14343 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14344 (setq ltags (org-split-string
14345 (org-match-string-no-properties 1) ":"))
14346 (when parent
14347 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14348 (setq tags (append
14349 (if parent
14350 (org-remove-uninherited-tags ltags)
14351 ltags)
14352 tags)))
14353 (or org-use-tag-inheritance (throw 'done t))
14354 (if local (throw 'done t))
14355 (or (org-up-heading-safe) (error nil))
14356 (setq parent t)))
14357 (error nil)))))
14358 (if local
14359 tags
14360 (reverse (delete-dups
14361 (reverse (append
14362 (org-remove-uninherited-tags
14363 org-file-tags) tags)))))))))
14365 (defun org-add-prop-inherited (s)
14366 (add-text-properties 0 (length s) '(inherited t) s)
14369 (defun org-toggle-tag (tag &optional onoff)
14370 "Toggle the tag TAG for the current line.
14371 If ONOFF is `on' or `off', don't toggle but set to this state."
14372 (let (res current)
14373 (save-excursion
14374 (org-back-to-heading t)
14375 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14376 (point-at-eol) t)
14377 (progn
14378 (setq current (match-string 1))
14379 (replace-match ""))
14380 (setq current ""))
14381 (setq current (nreverse (org-split-string current ":")))
14382 (cond
14383 ((eq onoff 'on)
14384 (setq res t)
14385 (or (member tag current) (push tag current)))
14386 ((eq onoff 'off)
14387 (or (not (member tag current)) (setq current (delete tag current))))
14388 (t (if (member tag current)
14389 (setq current (delete tag current))
14390 (setq res t)
14391 (push tag current))))
14392 (end-of-line 1)
14393 (if current
14394 (progn
14395 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14396 (org-set-tags nil t))
14397 (delete-horizontal-space))
14398 (run-hooks 'org-after-tags-change-hook))
14399 res))
14401 (defun org-align-tags-here (to-col)
14402 ;; Assumes that this is a headline
14403 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14404 (beginning-of-line 1)
14405 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14406 (< pos (match-beginning 2)))
14407 (progn
14408 (setq tags-l (- (match-end 2) (match-beginning 2)))
14409 (goto-char (match-beginning 1))
14410 (insert " ")
14411 (delete-region (point) (1+ (match-beginning 2)))
14412 (setq ncol (max (current-column)
14413 (1+ col)
14414 (if (> to-col 0)
14415 to-col
14416 (- (abs to-col) tags-l))))
14417 (setq p (point))
14418 (insert (make-string (- ncol (current-column)) ?\ ))
14419 (setq ncol (current-column))
14420 (when indent-tabs-mode (tabify p (point-at-eol)))
14421 (org-move-to-column (min ncol col) t nil t))
14422 (goto-char pos))))
14424 (defun org-set-tags-command (&optional arg just-align)
14425 "Call the set-tags command for the current entry."
14426 (interactive "P")
14427 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14428 (org-set-tags arg just-align)
14429 (save-excursion
14430 (unless (and (org-region-active-p)
14431 org-loop-over-headlines-in-active-region)
14432 (org-back-to-heading t))
14433 (org-set-tags arg just-align))))
14435 (defun org-set-tags-to (data)
14436 "Set the tags of the current entry to DATA, replacing the current tags.
14437 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14438 If DATA is nil or the empty string, any tags will be removed."
14439 (interactive "sTags: ")
14440 (setq data
14441 (cond
14442 ((eq data nil) "")
14443 ((equal data "") "")
14444 ((stringp data)
14445 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14446 ":"))
14447 ((listp data)
14448 (concat ":" (mapconcat 'identity data ":") ":"))))
14449 (when data
14450 (save-excursion
14451 (org-back-to-heading t)
14452 (when (looking-at org-complex-heading-regexp)
14453 (if (match-end 5)
14454 (progn
14455 (goto-char (match-beginning 5))
14456 (insert data)
14457 (delete-region (point) (point-at-eol))
14458 (org-set-tags nil 'align))
14459 (goto-char (point-at-eol))
14460 (insert " " data)
14461 (org-set-tags nil 'align)))
14462 (beginning-of-line 1)
14463 (if (looking-at ".*?\\([ \t]+\\)$")
14464 (delete-region (match-beginning 1) (match-end 1))))))
14466 (defun org-align-all-tags ()
14467 "Align the tags i all headings."
14468 (interactive)
14469 (save-excursion
14470 (or (ignore-errors (org-back-to-heading t))
14471 (outline-next-heading))
14472 (if (org-at-heading-p)
14473 (org-set-tags t)
14474 (message "No headings"))))
14476 (defvar org-indent-indentation-per-level)
14477 (defun org-set-tags (&optional arg just-align)
14478 "Set the tags for the current headline.
14479 With prefix ARG, realign all tags in headings in the current buffer."
14480 (interactive "P")
14481 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14482 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14483 'region-start-level 'region))
14484 org-loop-over-headlines-in-active-region)
14485 (org-map-entries
14486 ;; We don't use ARG and JUST-ALIGN here these args are not
14487 ;; useful when looping over headlines
14488 `(org-set-tags)
14489 org-loop-over-headlines-in-active-region
14490 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14491 (let* ((re org-outline-regexp-bol)
14492 (current (unless arg (org-get-tags-string)))
14493 (col (current-column))
14494 (org-setting-tags t)
14495 table current-tags inherited-tags ; computed below when needed
14496 tags p0 c0 c1 rpl di tc level)
14497 (if arg
14498 (save-excursion
14499 (goto-char (point-min))
14500 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14501 (while (re-search-forward re nil t)
14502 (org-set-tags nil t)
14503 (end-of-line 1)))
14504 (message "All tags realigned to column %d" org-tags-column))
14505 (if just-align
14506 (setq tags current)
14507 ;; Get a new set of tags from the user
14508 (save-excursion
14509 (setq table (append org-tag-persistent-alist
14510 (or org-tag-alist (org-get-buffer-tags))
14511 (and
14512 org-complete-tags-always-offer-all-agenda-tags
14513 (org-global-tags-completion-table
14514 (org-agenda-files))))
14515 org-last-tags-completion-table table
14516 current-tags (org-split-string current ":")
14517 inherited-tags (nreverse
14518 (nthcdr (length current-tags)
14519 (nreverse (org-get-tags-at))))
14520 tags
14521 (if (or (eq t org-use-fast-tag-selection)
14522 (and org-use-fast-tag-selection
14523 (delq nil (mapcar 'cdr table))))
14524 (org-fast-tag-selection
14525 current-tags inherited-tags table
14526 (if org-fast-tag-selection-include-todo
14527 org-todo-key-alist))
14528 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14529 (org-trim
14530 (org-icompleting-read "Tags: "
14531 'org-tags-completion-function
14532 nil nil current 'org-tags-history))))))
14533 (while (string-match "[-+&]+" tags)
14534 ;; No boolean logic, just a list
14535 (setq tags (replace-match ":" t t tags))))
14537 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14539 (if org-tags-sort-function
14540 (setq tags (mapconcat 'identity
14541 (sort (org-split-string
14542 tags (org-re "[^[:alnum:]_@#%]+"))
14543 org-tags-sort-function) ":")))
14545 (if (string-match "\\`[\t ]*\\'" tags)
14546 (setq tags "")
14547 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14548 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14550 ;; Insert new tags at the correct column
14551 (beginning-of-line 1)
14552 (setq level (or (and (looking-at org-outline-regexp)
14553 (- (match-end 0) (point) 1))
14555 (cond
14556 ((and (equal current "") (equal tags "")))
14557 ((re-search-forward
14558 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14559 (point-at-eol) t)
14560 (if (equal tags "")
14561 (setq rpl "")
14562 (goto-char (match-beginning 0))
14563 (setq c0 (current-column)
14564 ;; compute offset for the case of org-indent-mode active
14565 di (if org-indent-mode
14566 (* (1- org-indent-indentation-per-level) (1- level))
14568 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14569 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14570 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14571 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14572 (replace-match rpl t t)
14573 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14574 tags)
14575 (t (error "Tags alignment failed")))
14576 (org-move-to-column col)
14577 (unless just-align
14578 (run-hooks 'org-after-tags-change-hook))))))
14580 (defun org-change-tag-in-region (beg end tag off)
14581 "Add or remove TAG for each entry in the region.
14582 This works in the agenda, and also in an org-mode buffer."
14583 (interactive
14584 (list (region-beginning) (region-end)
14585 (let ((org-last-tags-completion-table
14586 (if (derived-mode-p 'org-mode)
14587 (org-uniquify
14588 (delq nil (append (org-get-buffer-tags)
14589 (org-global-tags-completion-table))))
14590 (org-global-tags-completion-table))))
14591 (org-icompleting-read
14592 "Tag: " 'org-tags-completion-function nil nil nil
14593 'org-tags-history))
14594 (progn
14595 (message "[s]et or [r]emove? ")
14596 (equal (read-char-exclusive) ?r))))
14597 (if (fboundp 'deactivate-mark) (deactivate-mark))
14598 (let ((agendap (equal major-mode 'org-agenda-mode))
14599 l1 l2 m buf pos newhead (cnt 0))
14600 (goto-char end)
14601 (setq l2 (1- (org-current-line)))
14602 (goto-char beg)
14603 (setq l1 (org-current-line))
14604 (loop for l from l1 to l2 do
14605 (org-goto-line l)
14606 (setq m (get-text-property (point) 'org-hd-marker))
14607 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14608 (and agendap m))
14609 (setq buf (if agendap (marker-buffer m) (current-buffer))
14610 pos (if agendap m (point)))
14611 (with-current-buffer buf
14612 (save-excursion
14613 (save-restriction
14614 (goto-char pos)
14615 (setq cnt (1+ cnt))
14616 (org-toggle-tag tag (if off 'off 'on))
14617 (setq newhead (org-get-heading)))))
14618 (and agendap (org-agenda-change-all-lines newhead m))))
14619 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14621 (defun org-tags-completion-function (string predicate &optional flag)
14622 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14623 (confirm (lambda (x) (stringp (car x)))))
14624 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14625 (setq s1 (match-string 1 string)
14626 s2 (match-string 2 string))
14627 (setq s1 "" s2 string))
14628 (cond
14629 ((eq flag nil)
14630 ;; try completion
14631 (setq rtn (try-completion s2 ctable confirm))
14632 (if (stringp rtn)
14633 (setq rtn
14634 (concat s1 s2 (substring rtn (length s2))
14635 (if (and org-add-colon-after-tag-completion
14636 (assoc rtn ctable))
14637 ":" ""))))
14638 rtn)
14639 ((eq flag t)
14640 ;; all-completions
14641 (all-completions s2 ctable confirm))
14642 ((eq flag 'lambda)
14643 ;; exact match?
14644 (assoc s2 ctable)))))
14646 (defun org-fast-tag-insert (kwd tags face &optional end)
14647 "Insert KDW, and the TAGS, the latter with face FACE.
14648 Also insert END."
14649 (insert (format "%-12s" (concat kwd ":"))
14650 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14651 (or end "")))
14653 (defun org-fast-tag-show-exit (flag)
14654 (save-excursion
14655 (org-goto-line 3)
14656 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14657 (replace-match ""))
14658 (when flag
14659 (end-of-line 1)
14660 (org-move-to-column (- (window-width) 19) t)
14661 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14663 (defun org-set-current-tags-overlay (current prefix)
14664 "Add an overlay to CURRENT tag with PREFIX."
14665 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14666 (if (featurep 'xemacs)
14667 (org-overlay-display org-tags-overlay (concat prefix s)
14668 'secondary-selection)
14669 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14670 (org-overlay-display org-tags-overlay (concat prefix s)))))
14672 (defvar org-last-tag-selection-key nil)
14673 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14674 "Fast tag selection with single keys.
14675 CURRENT is the current list of tags in the headline, INHERITED is the
14676 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14677 possibly with grouping information. TODO-TABLE is a similar table with
14678 TODO keywords, should these have keys assigned to them.
14679 If the keys are nil, a-z are automatically assigned.
14680 Returns the new tags string, or nil to not change the current settings."
14681 (let* ((fulltable (append table todo-table))
14682 (maxlen (apply 'max (mapcar
14683 (lambda (x)
14684 (if (stringp (car x)) (string-width (car x)) 0))
14685 fulltable)))
14686 (buf (current-buffer))
14687 (expert (eq org-fast-tag-selection-single-key 'expert))
14688 (buffer-tags nil)
14689 (fwidth (+ maxlen 3 1 3))
14690 (ncol (/ (- (window-width) 4) fwidth))
14691 (i-face 'org-done)
14692 (c-face 'org-todo)
14693 tg cnt e c char c1 c2 ntable tbl rtn
14694 ov-start ov-end ov-prefix
14695 (exit-after-next org-fast-tag-selection-single-key)
14696 (done-keywords org-done-keywords)
14697 groups ingroup)
14698 (save-excursion
14699 (beginning-of-line 1)
14700 (if (looking-at
14701 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14702 (setq ov-start (match-beginning 1)
14703 ov-end (match-end 1)
14704 ov-prefix "")
14705 (setq ov-start (1- (point-at-eol))
14706 ov-end (1+ ov-start))
14707 (skip-chars-forward "^\n\r")
14708 (setq ov-prefix
14709 (concat
14710 (buffer-substring (1- (point)) (point))
14711 (if (> (current-column) org-tags-column)
14713 (make-string (- org-tags-column (current-column)) ?\ ))))))
14714 (move-overlay org-tags-overlay ov-start ov-end)
14715 (save-window-excursion
14716 (if expert
14717 (set-buffer (get-buffer-create " *Org tags*"))
14718 (delete-other-windows)
14719 (split-window-vertically)
14720 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14721 (erase-buffer)
14722 (org-set-local 'org-done-keywords done-keywords)
14723 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14724 (org-fast-tag-insert "Current" current c-face "\n\n")
14725 (org-fast-tag-show-exit exit-after-next)
14726 (org-set-current-tags-overlay current ov-prefix)
14727 (setq tbl fulltable char ?a cnt 0)
14728 (while (setq e (pop tbl))
14729 (cond
14730 ((equal (car e) :startgroup)
14731 (push '() groups) (setq ingroup t)
14732 (when (not (= cnt 0))
14733 (setq cnt 0)
14734 (insert "\n"))
14735 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14736 ((equal (car e) :endgroup)
14737 (setq ingroup nil cnt 0)
14738 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14739 ((equal e '(:newline))
14740 (when (not (= cnt 0))
14741 (setq cnt 0)
14742 (insert "\n")
14743 (setq e (car tbl))
14744 (while (equal (car tbl) '(:newline))
14745 (insert "\n")
14746 (setq tbl (cdr tbl)))))
14747 ((equal e '(:grouptags)) nil)
14749 (setq tg (copy-sequence (car e)) c2 nil)
14750 (if (cdr e)
14751 (setq c (cdr e))
14752 ;; automatically assign a character.
14753 (setq c1 (string-to-char
14754 (downcase (substring
14755 tg (if (= (string-to-char tg) ?@) 1 0)))))
14756 (if (or (rassoc c1 ntable) (rassoc c1 table))
14757 (while (or (rassoc char ntable) (rassoc char table))
14758 (setq char (1+ char)))
14759 (setq c2 c1))
14760 (setq c (or c2 char)))
14761 (if ingroup (push tg (car groups)))
14762 (setq tg (org-add-props tg nil 'face
14763 (cond
14764 ((not (assoc tg table))
14765 (org-get-todo-face tg))
14766 ((member tg current) c-face)
14767 ((member tg inherited) i-face))))
14768 (if (equal (caar tbl) :grouptags)
14769 (org-add-props tg nil 'face 'org-tag-group))
14770 (if (and (= cnt 0) (not ingroup)) (insert " "))
14771 (insert "[" c "] " tg (make-string
14772 (- fwidth 4 (length tg)) ?\ ))
14773 (push (cons tg c) ntable)
14774 (when (= (setq cnt (1+ cnt)) ncol)
14775 (insert "\n")
14776 (if ingroup (insert " "))
14777 (setq cnt 0)))))
14778 (setq ntable (nreverse ntable))
14779 (insert "\n")
14780 (goto-char (point-min))
14781 (if (not expert) (org-fit-window-to-buffer))
14782 (setq rtn
14783 (catch 'exit
14784 (while t
14785 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14786 (if (not groups) "no " "")
14787 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14788 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14789 (setq org-last-tag-selection-key c)
14790 (cond
14791 ((= c ?\r) (throw 'exit t))
14792 ((= c ?!)
14793 (setq groups (not groups))
14794 (goto-char (point-min))
14795 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14796 ((= c ?\C-c)
14797 (if (not expert)
14798 (org-fast-tag-show-exit
14799 (setq exit-after-next (not exit-after-next)))
14800 (setq expert nil)
14801 (delete-other-windows)
14802 (set-window-buffer (split-window-vertically) " *Org tags*")
14803 (org-switch-to-buffer-other-window " *Org tags*")
14804 (org-fit-window-to-buffer)))
14805 ((or (= c ?\C-g)
14806 (and (= c ?q) (not (rassoc c ntable))))
14807 (org-detach-overlay org-tags-overlay)
14808 (setq quit-flag t))
14809 ((= c ?\ )
14810 (setq current nil)
14811 (if exit-after-next (setq exit-after-next 'now)))
14812 ((= c ?\t)
14813 (condition-case nil
14814 (setq tg (org-icompleting-read
14815 "Tag: "
14816 (or buffer-tags
14817 (with-current-buffer buf
14818 (org-get-buffer-tags)))))
14819 (quit (setq tg "")))
14820 (when (string-match "\\S-" tg)
14821 (add-to-list 'buffer-tags (list tg))
14822 (if (member tg current)
14823 (setq current (delete tg current))
14824 (push tg current)))
14825 (if exit-after-next (setq exit-after-next 'now)))
14826 ((setq e (rassoc c todo-table) tg (car e))
14827 (with-current-buffer buf
14828 (save-excursion (org-todo tg)))
14829 (if exit-after-next (setq exit-after-next 'now)))
14830 ((setq e (rassoc c ntable) tg (car e))
14831 (if (member tg current)
14832 (setq current (delete tg current))
14833 (loop for g in groups do
14834 (if (member tg g)
14835 (mapc (lambda (x)
14836 (setq current (delete x current)))
14837 g)))
14838 (push tg current))
14839 (if exit-after-next (setq exit-after-next 'now))))
14841 ;; Create a sorted list
14842 (setq current
14843 (sort current
14844 (lambda (a b)
14845 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14846 (if (eq exit-after-next 'now) (throw 'exit t))
14847 (goto-char (point-min))
14848 (beginning-of-line 2)
14849 (delete-region (point) (point-at-eol))
14850 (org-fast-tag-insert "Current" current c-face)
14851 (org-set-current-tags-overlay current ov-prefix)
14852 (while (re-search-forward
14853 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14854 (setq tg (match-string 1))
14855 (add-text-properties
14856 (match-beginning 1) (match-end 1)
14857 (list 'face
14858 (cond
14859 ((member tg current) c-face)
14860 ((member tg inherited) i-face)
14861 (t (get-text-property (match-beginning 1) 'face))))))
14862 (goto-char (point-min)))))
14863 (org-detach-overlay org-tags-overlay)
14864 (if rtn
14865 (mapconcat 'identity current ":")
14866 nil))))
14868 (defun org-get-tags-string ()
14869 "Get the TAGS string in the current headline."
14870 (unless (org-at-heading-p t)
14871 (user-error "Not on a heading"))
14872 (save-excursion
14873 (beginning-of-line 1)
14874 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14875 (org-match-string-no-properties 1)
14876 "")))
14878 (defun org-get-tags ()
14879 "Get the list of tags specified in the current headline."
14880 (org-split-string (org-get-tags-string) ":"))
14882 (defun org-get-buffer-tags ()
14883 "Get a table of all tags used in the buffer, for completion."
14884 (let (tags)
14885 (save-excursion
14886 (goto-char (point-min))
14887 (while (re-search-forward
14888 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14889 (when (equal (char-after (point-at-bol 0)) ?*)
14890 (mapc (lambda (x) (add-to-list 'tags x))
14891 (org-split-string (org-match-string-no-properties 1) ":")))))
14892 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14893 (mapcar 'list tags)))
14895 ;;;; The mapping API
14897 (defun org-map-entries (func &optional match scope &rest skip)
14898 "Call FUNC at each headline selected by MATCH in SCOPE.
14900 FUNC is a function or a lisp form. The function will be called without
14901 arguments, with the cursor positioned at the beginning of the headline.
14902 The return values of all calls to the function will be collected and
14903 returned as a list.
14905 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14906 does not need to preserve point. After evaluation, the cursor will be
14907 moved to the end of the line (presumably of the headline of the
14908 processed entry) and search continues from there. Under some
14909 circumstances, this may not produce the wanted results. For example,
14910 if you have removed (e.g. archived) the current (sub)tree it could
14911 mean that the next entry will be skipped entirely. In such cases, you
14912 can specify the position from where search should continue by making
14913 FUNC set the variable `org-map-continue-from' to the desired buffer
14914 position.
14916 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14917 Only headlines that are matched by this query will be considered during
14918 the iteration. When MATCH is nil or t, all headlines will be
14919 visited by the iteration.
14921 SCOPE determines the scope of this command. It can be any of:
14923 nil The current buffer, respecting the restriction if any
14924 tree The subtree started with the entry at point
14925 region The entries within the active region, if any
14926 region-start-level
14927 The entries within the active region, but only those at
14928 the same level than the first one.
14929 file The current buffer, without restriction
14930 file-with-archives
14931 The current buffer, and any archives associated with it
14932 agenda All agenda files
14933 agenda-with-archives
14934 All agenda files with any archive files associated with them
14935 \(file1 file2 ...)
14936 If this is a list, all files in the list will be scanned
14938 The remaining args are treated as settings for the skipping facilities of
14939 the scanner. The following items can be given here:
14941 archive skip trees with the archive tag
14942 comment skip trees with the COMMENT keyword
14943 function or Emacs Lisp form:
14944 will be used as value for `org-agenda-skip-function', so
14945 whenever the function returns a position, FUNC will not be
14946 called for that entry and search will continue from the
14947 position returned
14949 If your function needs to retrieve the tags including inherited tags
14950 at the *current* entry, you can use the value of the variable
14951 `org-scanner-tags' which will be much faster than getting the value
14952 with `org-get-tags-at'. If your function gets properties with
14953 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14954 to t around the call to `org-entry-properties' to get the same speedup.
14955 Note that if your function moves around to retrieve tags and properties at
14956 a *different* entry, you cannot use these techniques."
14957 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14958 (not (org-region-active-p)))
14959 (let* ((org-agenda-archives-mode nil) ; just to make sure
14960 (org-agenda-skip-archived-trees (memq 'archive skip))
14961 (org-agenda-skip-comment-trees (memq 'comment skip))
14962 (org-agenda-skip-function
14963 (car (org-delete-all '(comment archive) skip)))
14964 (org-tags-match-list-sublevels t)
14965 (start-level (eq scope 'region-start-level))
14966 matcher file res
14967 org-todo-keywords-for-agenda
14968 org-done-keywords-for-agenda
14969 org-todo-keyword-alist-for-agenda
14970 org-drawers-for-agenda
14971 org-tag-alist-for-agenda
14972 todo-only)
14974 (cond
14975 ((eq match t) (setq matcher t))
14976 ((eq match nil) (setq matcher t))
14977 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14979 (save-window-excursion
14980 (save-restriction
14981 (cond ((eq scope 'tree)
14982 (org-back-to-heading t)
14983 (org-narrow-to-subtree)
14984 (setq scope nil))
14985 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14986 (org-region-active-p))
14987 ;; If needed, set start-level to a string like "2"
14988 (when start-level
14989 (save-excursion
14990 (goto-char (region-beginning))
14991 (unless (org-at-heading-p) (outline-next-heading))
14992 (setq start-level (org-current-level))))
14993 (narrow-to-region (region-beginning)
14994 (save-excursion
14995 (goto-char (region-end))
14996 (unless (and (bolp) (org-at-heading-p))
14997 (outline-next-heading))
14998 (point)))
14999 (setq scope nil)))
15001 (if (not scope)
15002 (progn
15003 (org-agenda-prepare-buffers
15004 (list (buffer-file-name (current-buffer))))
15005 (setq res (org-scan-tags func matcher todo-only start-level)))
15006 ;; Get the right scope
15007 (cond
15008 ((and scope (listp scope) (symbolp (car scope)))
15009 (setq scope (eval scope)))
15010 ((eq scope 'agenda)
15011 (setq scope (org-agenda-files t)))
15012 ((eq scope 'agenda-with-archives)
15013 (setq scope (org-agenda-files t))
15014 (setq scope (org-add-archive-files scope)))
15015 ((eq scope 'file)
15016 (setq scope (list (buffer-file-name))))
15017 ((eq scope 'file-with-archives)
15018 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15019 (org-agenda-prepare-buffers scope)
15020 (while (setq file (pop scope))
15021 (with-current-buffer (org-find-base-buffer-visiting file)
15022 (save-excursion
15023 (save-restriction
15024 (widen)
15025 (goto-char (point-min))
15026 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15027 res)))
15029 ;;;; Properties
15031 ;;; Setting and retrieving properties
15033 (defconst org-special-properties
15034 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15035 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15036 "The special properties valid in Org-mode.
15038 These are properties that are not defined in the property drawer,
15039 but in some other way.")
15041 (defconst org-default-properties
15042 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15043 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15044 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15045 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15046 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15047 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15048 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15049 "Some properties that are used by Org-mode for various purposes.
15050 Being in this list makes sure that they are offered for completion.")
15052 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15053 "Regular expression matching the first line of a property drawer.")
15055 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15056 "Regular expression matching the last line of a property drawer.")
15058 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15059 "Regular expression matching the first line of a property drawer.")
15061 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15062 "Regular expression matching the first line of a property drawer.")
15064 (defconst org-property-drawer-re
15065 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15066 org-property-end-re "\\)\n?")
15067 "Matches an entire property drawer.")
15069 (defconst org-clock-drawer-re
15070 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15071 org-property-end-re "\\)\n?")
15072 "Matches an entire clock drawer.")
15074 (defun org-property-action ()
15075 "Do an action on properties."
15076 (interactive)
15077 (let (c)
15078 (org-at-property-p)
15079 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15080 (setq c (read-char-exclusive))
15081 (cond
15082 ((equal c ?s)
15083 (call-interactively 'org-set-property))
15084 ((equal c ?d)
15085 (call-interactively 'org-delete-property))
15086 ((equal c ?D)
15087 (call-interactively 'org-delete-property-globally))
15088 ((equal c ?c)
15089 (call-interactively 'org-compute-property-at-point))
15090 (t (user-error "No such property action %c" c)))))
15092 (defun org-inc-effort ()
15093 "Increment the value of the effort property in the current entry."
15094 (interactive)
15095 (org-set-effort nil t))
15097 (defvar org-clock-effort) ;; Defined in org-clock.el
15098 (defvar org-clock-current-task) ;; Defined in org-clock.el
15099 (defun org-set-effort (&optional value increment)
15100 "Set the effort property of the current entry.
15101 With numerical prefix arg, use the nth allowed value, 0 stands for the
15102 10th allowed value.
15104 When INCREMENT is non-nil, set the property to the next allowed value."
15105 (interactive "P")
15106 (if (equal value 0) (setq value 10))
15107 (let* ((completion-ignore-case t)
15108 (prop org-effort-property)
15109 (cur (org-entry-get nil prop))
15110 (allowed (org-property-get-allowed-values nil prop 'table))
15111 (existing (mapcar 'list (org-property-values prop)))
15112 (heading (nth 4 (org-heading-components)))
15114 (val (cond
15115 ((stringp value) value)
15116 ((and allowed (integerp value))
15117 (or (car (nth (1- value) allowed))
15118 (car (org-last allowed))))
15119 ((and allowed increment)
15120 (or (caadr (member (list cur) allowed))
15121 (user-error "Allowed effort values are not set")))
15122 (allowed
15123 (message "Select 1-9,0, [RET%s]: %s"
15124 (if cur (concat "=" cur) "")
15125 (mapconcat 'car allowed " "))
15126 (setq rpl (read-char-exclusive))
15127 (if (equal rpl ?\r)
15129 (setq rpl (- rpl ?0))
15130 (if (equal rpl 0) (setq rpl 10))
15131 (if (and (> rpl 0) (<= rpl (length allowed)))
15132 (car (nth (1- rpl) allowed))
15133 (org-completing-read "Effort: " allowed nil))))
15135 (let (org-completion-use-ido org-completion-use-iswitchb)
15136 (org-completing-read
15137 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15138 (concat "[" cur "]") "")
15139 ": ")
15140 existing nil nil "" nil cur))))))
15141 (unless (equal (org-entry-get nil prop) val)
15142 (org-entry-put nil prop val))
15143 (save-excursion
15144 (org-back-to-heading t)
15145 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15146 (when (string= heading org-clock-current-task)
15147 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15148 (org-clock-update-mode-line))
15149 (message "%s is now %s" prop val)))
15151 (defun org-at-property-p ()
15152 "Is cursor inside a property drawer?"
15153 (save-excursion
15154 (when (equal 'node-property (car (org-element-at-point)))
15155 (beginning-of-line 1)
15156 (looking-at org-property-re))))
15158 (defun org-get-property-block (&optional beg end force)
15159 "Return the (beg . end) range of the body of the property drawer.
15160 BEG and END are the beginning and end of the current subtree, or of
15161 the part before the first headline. If they are not given, they will
15162 be found. If the drawer does not exist and FORCE is non-nil, create
15163 the drawer."
15164 (catch 'exit
15165 (save-excursion
15166 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15167 (progn (org-back-to-heading t) (point))))
15168 (end (or end (and (not (outline-next-heading)) (point-max))
15169 (point))))
15170 (goto-char beg)
15171 (if (re-search-forward org-property-start-re end t)
15172 (setq beg (1+ (match-end 0)))
15173 (if force
15174 (save-excursion
15175 (org-insert-property-drawer)
15176 (setq end (progn (outline-next-heading) (point))))
15177 (throw 'exit nil))
15178 (goto-char beg)
15179 (if (re-search-forward org-property-start-re end t)
15180 (setq beg (1+ (match-end 0)))))
15181 (if (re-search-forward org-property-end-re end t)
15182 (setq end (match-beginning 0))
15183 (or force (throw 'exit nil))
15184 (goto-char beg)
15185 (setq end beg)
15186 (org-indent-line)
15187 (insert ":END:\n"))
15188 (cons beg end)))))
15190 (defun org-entry-properties (&optional pom which specific)
15191 "Get all properties of the entry at point-or-marker POM.
15192 This includes the TODO keyword, the tags, time strings for deadline,
15193 scheduled, and clocking, and any additional properties defined in the
15194 entry. The return value is an alist, keys may occur multiple times
15195 if the property key was used several times.
15196 POM may also be nil, in which case the current entry is used.
15197 If WHICH is nil or `all', get all properties. If WHICH is
15198 `special' or `standard', only get that subclass. If WHICH
15199 is a string only get exactly this property. SPECIFIC can be a string, the
15200 specific property we are interested in. Specifying it can speed
15201 things up because then unnecessary parsing is avoided."
15202 (setq which (or which 'all))
15203 (org-with-point-at pom
15204 (let ((clockstr (substring org-clock-string 0 -1))
15205 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15206 (case-fold-search nil)
15207 beg end range props sum-props key key1 value string clocksum clocksumt)
15208 (save-excursion
15209 (when (condition-case nil
15210 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15211 (error nil))
15212 (setq beg (point))
15213 (setq sum-props (get-text-property (point) 'org-summaries))
15214 (setq clocksum (get-text-property (point) :org-clock-minutes)
15215 clocksumt (get-text-property (point) :org-clock-minutes-today))
15216 (outline-next-heading)
15217 (setq end (point))
15218 (when (memq which '(all special))
15219 ;; Get the special properties, like TODO and tags
15220 (goto-char beg)
15221 (when (and (or (not specific) (string= specific "TODO"))
15222 (looking-at org-todo-line-regexp) (match-end 2))
15223 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15224 (when (and (or (not specific) (string= specific "PRIORITY"))
15225 (looking-at org-priority-regexp))
15226 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15227 (when (or (not specific) (string= specific "FILE"))
15228 (push (cons "FILE" buffer-file-name) props))
15229 (when (and (or (not specific) (string= specific "TAGS"))
15230 (setq value (org-get-tags-string))
15231 (string-match "\\S-" value))
15232 (push (cons "TAGS" value) props))
15233 (when (and (or (not specific) (string= specific "ALLTAGS"))
15234 (setq value (org-get-tags-at)))
15235 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15236 ":"))
15237 props))
15238 (when (or (not specific) (string= specific "BLOCKED"))
15239 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15240 (when (or (not specific)
15241 (member specific
15242 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15243 "TIMESTAMP" "TIMESTAMP_IA")))
15244 (catch 'match
15245 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15246 (setq key (if (match-end 1)
15247 (substring (org-match-string-no-properties 1)
15248 0 -1))
15249 string (if (equal key clockstr)
15250 (org-trim
15251 (buffer-substring-no-properties
15252 (match-beginning 3) (goto-char
15253 (point-at-eol))))
15254 (substring (org-match-string-no-properties 3)
15255 1 -1)))
15256 ;; Get the correct property name from the key. This is
15257 ;; necessary if the user has configured time keywords.
15258 (setq key1 (concat key ":"))
15259 (cond
15260 ((not key)
15261 (setq key
15262 (if (= (char-after (match-beginning 3)) ?\[)
15263 "TIMESTAMP_IA" "TIMESTAMP")))
15264 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15265 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15266 ((equal key1 org-closed-string) (setq key "CLOSED"))
15267 ((equal key1 org-clock-string) (setq key "CLOCK")))
15268 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15269 (progn
15270 (push (cons key string) props)
15271 ;; no need to search further if match is found
15272 (throw 'match t))
15273 (when (or (equal key "CLOCK") (not (assoc key props)))
15274 (push (cons key string) props)))))))
15276 (when (memq which '(all standard))
15277 ;; Get the standard properties, like :PROP: ...
15278 (setq range (org-get-property-block beg end))
15279 (when range
15280 (goto-char (car range))
15281 (while (re-search-forward org-property-re
15282 (cdr range) t)
15283 (setq key (org-match-string-no-properties 2)
15284 value (org-trim (or (org-match-string-no-properties 3) "")))
15285 (unless (member key excluded)
15286 (push (cons key (or value "")) props)))))
15287 (if clocksum
15288 (push (cons "CLOCKSUM"
15289 (org-columns-number-to-string (/ (float clocksum) 60.)
15290 'add_times))
15291 props))
15292 (if clocksumt
15293 (push (cons "CLOCKSUM_T"
15294 (org-columns-number-to-string (/ (float clocksumt) 60.)
15295 'add_times))
15296 props))
15297 (unless (assoc "CATEGORY" props)
15298 (push (cons "CATEGORY" (org-get-category)) props))
15299 (append sum-props (nreverse props)))))))
15301 (defun org-entry-get (pom property &optional inherit literal-nil)
15302 "Get value of PROPERTY for entry or content at point-or-marker POM.
15303 If INHERIT is non-nil and the entry does not have the property,
15304 then also check higher levels of the hierarchy.
15305 If INHERIT is the symbol `selective', use inheritance only if the setting
15306 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15307 If the property is present but empty, the return value is the empty string.
15308 If the property is not present at all, nil is returned.
15310 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15311 do not interpret it as the list atom nil. This is used for inheritance
15312 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15313 (org-with-point-at pom
15314 (if (and inherit (if (eq inherit 'selective)
15315 (org-property-inherit-p property)
15317 (org-entry-get-with-inheritance property literal-nil)
15318 (if (member property org-special-properties)
15319 ;; We need a special property. Use `org-entry-properties' to
15320 ;; retrieve it, but specify the wanted property
15321 (cdr (assoc property (org-entry-properties nil 'special property)))
15322 (let ((range (org-get-property-block)))
15323 (when (and range (not (eq (car range) (cdr range))))
15324 (let* ((props (list (or (assoc property org-file-properties)
15325 (assoc property org-global-properties)
15326 (assoc property org-global-properties-fixed))))
15327 (ap (lambda (key)
15328 (when (re-search-forward
15329 (org-re-property key) (cdr range) t)
15330 (setq props
15331 (org-update-property-plist
15333 (if (match-end 3)
15334 (org-match-string-no-properties 3) "")
15335 props)))))
15336 val)
15337 (goto-char (car range))
15338 (funcall ap property)
15339 (goto-char (car range))
15340 (while (funcall ap (concat property "+")))
15341 (setq val (cdr (assoc property props)))
15342 (when val (if literal-nil val (org-not-nil val))))))))))
15344 (defun org-property-or-variable-value (var &optional inherit)
15345 "Check if there is a property fixing the value of VAR.
15346 If yes, return this value. If not, return the current value of the variable."
15347 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15348 (if (and prop (stringp prop) (string-match "\\S-" prop))
15349 (read prop)
15350 (symbol-value var))))
15352 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15353 "Delete the property PROPERTY from entry at point-or-marker POM.
15354 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15355 an empty drawer to delete."
15356 (org-with-point-at pom
15357 (if (member property org-special-properties)
15358 nil ; cannot delete these properties.
15359 (let ((range (org-get-property-block)))
15360 (if (and range
15361 (goto-char (car range))
15362 (re-search-forward
15363 (org-re-property property)
15364 (cdr range) t))
15365 (progn
15366 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15367 (and delete-empty-drawer
15368 (org-remove-empty-drawer-at
15369 delete-empty-drawer (car range)))
15371 nil)))))
15373 ;; Multi-values properties are properties that contain multiple values
15374 ;; These values are assumed to be single words, separated by whitespace.
15375 (defun org-entry-add-to-multivalued-property (pom property value)
15376 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15377 (let* ((old (org-entry-get pom property))
15378 (values (and old (org-split-string old "[ \t]"))))
15379 (setq value (org-entry-protect-space value))
15380 (unless (member value values)
15381 (setq values (append values (list value)))
15382 (org-entry-put pom property
15383 (mapconcat 'identity values " ")))))
15385 (defun org-entry-remove-from-multivalued-property (pom property value)
15386 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15387 (let* ((old (org-entry-get pom property))
15388 (values (and old (org-split-string old "[ \t]"))))
15389 (setq value (org-entry-protect-space value))
15390 (when (member value values)
15391 (setq values (delete value values))
15392 (org-entry-put pom property
15393 (mapconcat 'identity values " ")))))
15395 (defun org-entry-member-in-multivalued-property (pom property value)
15396 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15397 (let* ((old (org-entry-get pom property))
15398 (values (and old (org-split-string old "[ \t]"))))
15399 (setq value (org-entry-protect-space value))
15400 (member value values)))
15402 (defun org-entry-get-multivalued-property (pom property)
15403 "Return a list of values in a multivalued property."
15404 (let* ((value (org-entry-get pom property))
15405 (values (and value (org-split-string value "[ \t]"))))
15406 (mapcar 'org-entry-restore-space values)))
15408 (defun org-entry-put-multivalued-property (pom property &rest values)
15409 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15410 VALUES should be a list of strings. Spaces will be protected."
15411 (org-entry-put pom property
15412 (mapconcat 'org-entry-protect-space values " "))
15413 (let* ((value (org-entry-get pom property))
15414 (values (and value (org-split-string value "[ \t]"))))
15415 (mapcar 'org-entry-restore-space values)))
15417 (defun org-entry-protect-space (s)
15418 "Protect spaces and newline in string S."
15419 (while (string-match " " s)
15420 (setq s (replace-match "%20" t t s)))
15421 (while (string-match "\n" s)
15422 (setq s (replace-match "%0A" t t s)))
15425 (defun org-entry-restore-space (s)
15426 "Restore spaces and newline in string S."
15427 (while (string-match "%20" s)
15428 (setq s (replace-match " " t t s)))
15429 (while (string-match "%0A" s)
15430 (setq s (replace-match "\n" t t s)))
15433 (defvar org-entry-property-inherited-from (make-marker)
15434 "Marker pointing to the entry from where a property was inherited.
15435 Each call to `org-entry-get-with-inheritance' will set this marker to the
15436 location of the entry where the inheritance search matched. If there was
15437 no match, the marker will point nowhere.
15438 Note that also `org-entry-get' calls this function, if the INHERIT flag
15439 is set.")
15441 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15442 "Get PROPERTY of entry or content at point, search higher levels if needed.
15443 The search will stop at the first ancestor which has the property defined.
15444 If the value found is \"nil\", return nil to show that the property
15445 should be considered as undefined (this is the meaning of nil here).
15446 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15447 (move-marker org-entry-property-inherited-from nil)
15448 (let (tmp)
15449 (save-excursion
15450 (save-restriction
15451 (widen)
15452 (catch 'ex
15453 (while t
15454 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15455 (or (ignore-errors (org-back-to-heading t))
15456 (goto-char (point-min)))
15457 (move-marker org-entry-property-inherited-from (point))
15458 (throw 'ex tmp))
15459 (or (ignore-errors (org-up-heading-safe))
15460 (throw 'ex nil))))))
15461 (setq tmp (or tmp
15462 (cdr (assoc property org-file-properties))
15463 (cdr (assoc property org-global-properties))
15464 (cdr (assoc property org-global-properties-fixed))))
15465 (if literal-nil tmp (org-not-nil tmp))))
15467 (defvar org-property-changed-functions nil
15468 "Hook called when the value of a property has changed.
15469 Each hook function should accept two arguments, the name of the property
15470 and the new value.")
15472 (defun org-entry-put (pom property value)
15473 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15474 (org-with-point-at pom
15475 (org-back-to-heading t)
15476 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15477 range)
15478 (cond
15479 ((equal property "TODO")
15480 (when (and (stringp value) (string-match "\\S-" value)
15481 (not (member value org-todo-keywords-1)))
15482 (user-error "\"%s\" is not a valid TODO state" value))
15483 (if (or (not value)
15484 (not (string-match "\\S-" value)))
15485 (setq value 'none))
15486 (org-todo value)
15487 (org-set-tags nil 'align))
15488 ((equal property "PRIORITY")
15489 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15490 (string-to-char value) ?\ ))
15491 (org-set-tags nil 'align))
15492 ((equal property "CLOCKSUM")
15493 (if (not (re-search-forward
15494 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15495 (error "Cannot find a clock log")
15496 (goto-char (- (match-end 1) 2))
15497 (cond
15498 ((eq value 'earlier) (org-timestamp-down))
15499 ((eq value 'later) (org-timestamp-up)))
15500 (org-clock-sum-current-item)))
15501 ((equal property "SCHEDULED")
15502 (if (re-search-forward org-scheduled-time-regexp end t)
15503 (cond
15504 ((eq value 'earlier) (org-timestamp-change -1 'day))
15505 ((eq value 'later) (org-timestamp-change 1 'day))
15506 (t (call-interactively 'org-schedule)))
15507 (call-interactively 'org-schedule)))
15508 ((equal property "DEADLINE")
15509 (if (re-search-forward org-deadline-time-regexp end t)
15510 (cond
15511 ((eq value 'earlier) (org-timestamp-change -1 'day))
15512 ((eq value 'later) (org-timestamp-change 1 'day))
15513 (t (call-interactively 'org-deadline)))
15514 (call-interactively 'org-deadline)))
15515 ((member property org-special-properties)
15516 (error "The %s property can not yet be set with `org-entry-put'"
15517 property))
15518 (t ; a non-special property
15519 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15520 (setq range (org-get-property-block beg end 'force))
15521 (goto-char (car range))
15522 (if (re-search-forward
15523 (org-re-property property) (cdr range) t)
15524 (progn
15525 (delete-region (match-beginning 0) (match-end 0))
15526 (goto-char (match-beginning 0)))
15527 (goto-char (cdr range))
15528 (insert "\n")
15529 (backward-char 1)
15530 (org-indent-line))
15531 (insert ":" property ":")
15532 (and value (insert " " value))
15533 (org-indent-line)))))
15534 (run-hook-with-args 'org-property-changed-functions property value)))
15536 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15537 "Get all property keys in the current buffer.
15538 With INCLUDE-SPECIALS, also list the special properties that reflect things
15539 like tags and TODO state.
15540 With INCLUDE-DEFAULTS, also include properties that has special meaning
15541 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15542 and others.
15543 With INCLUDE-COLUMNS, also include property names given in COLUMN
15544 formats in the current buffer."
15545 (let (rtn range cfmt s p)
15546 (save-excursion
15547 (save-restriction
15548 (widen)
15549 (goto-char (point-min))
15550 (while (re-search-forward org-property-start-re nil t)
15551 (setq range (org-get-property-block))
15552 (goto-char (car range))
15553 (while (re-search-forward org-property-re
15554 (cdr range) t)
15555 (add-to-list 'rtn (org-match-string-no-properties 2)))
15556 (outline-next-heading))))
15558 (when include-specials
15559 (setq rtn (append org-special-properties rtn)))
15561 (when include-defaults
15562 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15563 (add-to-list 'rtn org-effort-property))
15565 (when include-columns
15566 (save-excursion
15567 (save-restriction
15568 (widen)
15569 (goto-char (point-min))
15570 (while (re-search-forward
15571 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15572 nil t)
15573 (setq cfmt (match-string 2) s 0)
15574 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15575 cfmt s)
15576 (setq s (match-end 0)
15577 p (match-string 1 cfmt))
15578 (unless (or (equal p "ITEM")
15579 (member p org-special-properties))
15580 (add-to-list 'rtn (match-string 1 cfmt))))))))
15582 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15584 (defun org-property-values (key)
15585 "Return a list of all values of property KEY in the current buffer."
15586 (save-excursion
15587 (save-restriction
15588 (widen)
15589 (goto-char (point-min))
15590 (let ((re (org-re-property key))
15591 values)
15592 (while (re-search-forward re nil t)
15593 (add-to-list 'values (org-trim (match-string 3))))
15594 (delete "" values)))))
15596 (defun org-insert-property-drawer ()
15597 "Insert a property drawer into the current entry."
15598 (org-back-to-heading t)
15599 (looking-at org-outline-regexp)
15600 (let ((indent (if org-adapt-indentation
15601 (- (match-end 0) (match-beginning 0))
15603 (beg (point))
15604 (re (concat "^[ \t]*" org-keyword-time-regexp))
15605 end hiddenp)
15606 (outline-next-heading)
15607 (setq end (point))
15608 (goto-char beg)
15609 (while (re-search-forward re end t))
15610 (setq hiddenp (outline-invisible-p))
15611 (end-of-line 1)
15612 (and (equal (char-after) ?\n) (forward-char 1))
15613 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15614 (if (member (match-string 1) '("CLOCK:" ":END:"))
15615 ;; just skip this line
15616 (beginning-of-line 2)
15617 ;; Drawer start, find the end
15618 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15619 (beginning-of-line 1)))
15620 (org-skip-over-state-notes)
15621 (skip-chars-backward " \t\n\r")
15622 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15623 (forward-char 1))
15624 (goto-char (point-at-eol))
15625 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15626 (beginning-of-line 0)
15627 (org-indent-to-column indent)
15628 (beginning-of-line 2)
15629 (org-indent-to-column indent)
15630 (beginning-of-line 0)
15631 (if hiddenp
15632 (save-excursion
15633 (org-back-to-heading t)
15634 (hide-entry))
15635 (org-flag-drawer t))))
15637 (defun org-insert-drawer (&optional arg drawer)
15638 "Insert a drawer at point.
15640 Optional argument DRAWER, when non-nil, is a string representing
15641 drawer's name. Otherwise, the user is prompted for a name.
15643 If a region is active, insert the drawer around that region
15644 instead.
15646 Point is left between drawer's boundaries."
15647 (interactive "P")
15648 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15649 "LOGBOOK"))
15650 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15651 ;; internally by Org. They are meant to be inserted
15652 ;; automatically.
15653 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15654 ;; Remove system drawers from list. Note: For some reason,
15655 ;; `org-completing-read' ignores the predicate while
15656 ;; `completing-read' handles it fine.
15657 (drawer (if arg "PROPERTIES"
15658 (or drawer
15659 (completing-read
15660 "Drawer: " org-drawers
15661 (lambda (d) (not (member d system-drawers))))))))
15662 (cond
15663 ;; With C-u, fall back on `org-insert-property-drawer'
15664 (arg (org-insert-property-drawer))
15665 ;; With an active region, insert a drawer at point.
15666 ((not (org-region-active-p))
15667 (progn
15668 (unless (bolp) (insert "\n"))
15669 (insert (format ":%s:\n\n:END:\n" drawer))
15670 (forward-line -2)))
15671 ;; Otherwise, insert the drawer at point
15673 (let ((rbeg (region-beginning))
15674 (rend (copy-marker (region-end))))
15675 (unwind-protect
15676 (progn
15677 (goto-char rbeg)
15678 (beginning-of-line)
15679 (when (save-excursion
15680 (re-search-forward org-outline-regexp-bol rend t))
15681 (user-error "Drawers cannot contain headlines"))
15682 ;; Position point at the beginning of the first
15683 ;; non-blank line in region. Insert drawer's opening
15684 ;; there, then indent it.
15685 (org-skip-whitespace)
15686 (beginning-of-line)
15687 (insert ":" drawer ":\n")
15688 (forward-line -1)
15689 (indent-for-tab-command)
15690 ;; Move point to the beginning of the first blank line
15691 ;; after the last non-blank line in region. Insert
15692 ;; drawer's closing, then indent it.
15693 (goto-char rend)
15694 (skip-chars-backward " \r\t\n")
15695 (insert "\n:END:")
15696 (deactivate-mark t)
15697 (indent-for-tab-command)
15698 (unless (eolp) (insert "\n")))
15699 ;; Clear marker, whatever the outcome of insertion is.
15700 (set-marker rend nil)))))))
15702 (defvar org-property-set-functions-alist nil
15703 "Property set function alist.
15704 Each entry should have the following format:
15706 (PROPERTY . READ-FUNCTION)
15708 The read function will be called with the same argument as
15709 `org-completing-read'.")
15711 (defun org-set-property-function (property)
15712 "Get the function that should be used to set PROPERTY.
15713 This is computed according to `org-property-set-functions-alist'."
15714 (or (cdr (assoc property org-property-set-functions-alist))
15715 'org-completing-read))
15717 (defun org-read-property-value (property)
15718 "Read PROPERTY value from user."
15719 (let* ((completion-ignore-case t)
15720 (allowed (org-property-get-allowed-values nil property 'table))
15721 (cur (org-entry-get nil property))
15722 (prompt (concat property " value"
15723 (if (and cur (string-match "\\S-" cur))
15724 (concat " [" cur "]") "") ": "))
15725 (set-function (org-set-property-function property))
15726 (val (if allowed
15727 (funcall set-function prompt allowed nil
15728 (not (get-text-property 0 'org-unrestricted
15729 (caar allowed))))
15730 (let (org-completion-use-ido org-completion-use-iswitchb)
15731 (funcall set-function prompt
15732 (mapcar 'list (org-property-values property))
15733 nil nil "" nil cur)))))
15734 (if (equal val "")
15736 val)))
15738 (defvar org-last-set-property nil)
15739 (defvar org-last-set-property-value nil)
15740 (defun org-read-property-name ()
15741 "Read a property name."
15742 (let* ((completion-ignore-case t)
15743 (keys (org-buffer-property-keys nil t t))
15744 (default-prop (or (save-excursion
15745 (save-match-data
15746 (beginning-of-line)
15747 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15748 (null (string= (match-string 1) "END"))
15749 (match-string 1))))
15750 org-last-set-property))
15751 (property (org-icompleting-read
15752 (concat "Property"
15753 (if default-prop (concat " [" default-prop "]") "")
15754 ": ")
15755 (mapcar 'list keys)
15756 nil nil nil nil
15757 default-prop)))
15758 (if (member property keys)
15759 property
15760 (or (cdr (assoc (downcase property)
15761 (mapcar (lambda (x) (cons (downcase x) x))
15762 keys)))
15763 property))))
15765 (defun org-set-property-and-value (use-last)
15766 "Allow to set [PROPERTY]: [value] direction from prompt.
15767 When use-default, don't even ask, just use the last
15768 \"[PROPERTY]: [value]\" string from the history."
15769 (interactive "P")
15770 (let* ((completion-ignore-case t)
15771 (pv (or (and use-last org-last-set-property-value)
15772 (org-completing-read
15773 "Enter a \"[Property]: [value]\" pair: "
15774 nil nil nil nil nil
15775 org-last-set-property-value)))
15776 prop val)
15777 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15778 (setq prop (match-string 1 pv)
15779 val (match-string 2 pv))
15780 (org-set-property prop val))))
15782 (defun org-set-property (property value)
15783 "In the current entry, set PROPERTY to VALUE.
15784 When called interactively, this will prompt for a property name, offering
15785 completion on existing and default properties. And then it will prompt
15786 for a value, offering completion either on allowed values (via an inherited
15787 xxx_ALL property) or on existing values in other instances of this property
15788 in the current file."
15789 (interactive (list nil nil))
15790 (let* ((property (or property (org-read-property-name)))
15791 (value (or value (org-read-property-value property)))
15792 (fn (cdr (assoc property org-properties-postprocess-alist))))
15793 (setq org-last-set-property property)
15794 (setq org-last-set-property-value (concat property ": " value))
15795 ;; Possibly postprocess the inserted value:
15796 (when fn (setq value (funcall fn value)))
15797 (unless (equal (org-entry-get nil property) value)
15798 (org-entry-put nil property value))))
15800 (defun org-delete-property (property &optional delete-empty-drawer)
15801 "In the current entry, delete PROPERTY.
15802 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15803 an empty drawer to delete."
15804 (interactive
15805 (let* ((completion-ignore-case t)
15806 (prop (org-icompleting-read "Property: "
15807 (org-entry-properties nil 'standard))))
15808 (list prop)))
15809 (message "Property %s %s" property
15810 (if (org-entry-delete nil property delete-empty-drawer)
15811 "deleted"
15812 "was not present in the entry")))
15814 (defun org-delete-property-globally (property)
15815 "Remove PROPERTY globally, from all entries."
15816 (interactive
15817 (let* ((completion-ignore-case t)
15818 (prop (org-icompleting-read
15819 "Globally remove property: "
15820 (mapcar 'list (org-buffer-property-keys)))))
15821 (list prop)))
15822 (save-excursion
15823 (save-restriction
15824 (widen)
15825 (goto-char (point-min))
15826 (let ((cnt 0))
15827 (while (re-search-forward
15828 (org-re-property property)
15829 nil t)
15830 (setq cnt (1+ cnt))
15831 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15832 (message "Property \"%s\" removed from %d entries" property cnt)))))
15834 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15836 (defun org-compute-property-at-point ()
15837 "Compute the property at point.
15838 This looks for an enclosing column format, extracts the operator and
15839 then applies it to the property in the column format's scope."
15840 (interactive)
15841 (unless (org-at-property-p)
15842 (user-error "Not at a property"))
15843 (let ((prop (org-match-string-no-properties 2)))
15844 (org-columns-get-format-and-top-level)
15845 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15846 (user-error "No operator defined for property %s" prop))
15847 (org-columns-compute prop)))
15849 (defvar org-property-allowed-value-functions nil
15850 "Hook for functions supplying allowed values for a specific property.
15851 The functions must take a single argument, the name of the property, and
15852 return a flat list of allowed values. If \":ETC\" is one of
15853 the values, this means that these values are intended as defaults for
15854 completion, but that other values should be allowed too.
15855 The functions must return nil if they are not responsible for this
15856 property.")
15858 (defun org-property-get-allowed-values (pom property &optional table)
15859 "Get allowed values for the property PROPERTY.
15860 When TABLE is non-nil, return an alist that can directly be used for
15861 completion."
15862 (let (vals)
15863 (cond
15864 ((equal property "TODO")
15865 (setq vals (org-with-point-at pom
15866 (append org-todo-keywords-1 '("")))))
15867 ((equal property "PRIORITY")
15868 (let ((n org-lowest-priority))
15869 (while (>= n org-highest-priority)
15870 (push (char-to-string n) vals)
15871 (setq n (1- n)))))
15872 ((member property org-special-properties))
15873 ((setq vals (run-hook-with-args-until-success
15874 'org-property-allowed-value-functions property)))
15876 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15877 (when (and vals (string-match "\\S-" vals))
15878 (setq vals (car (read-from-string (concat "(" vals ")"))))
15879 (setq vals (mapcar (lambda (x)
15880 (cond ((stringp x) x)
15881 ((numberp x) (number-to-string x))
15882 ((symbolp x) (symbol-name x))
15883 (t "???")))
15884 vals)))))
15885 (when (member ":ETC" vals)
15886 (setq vals (remove ":ETC" vals))
15887 (org-add-props (car vals) '(org-unrestricted t)))
15888 (if table (mapcar 'list vals) vals)))
15890 (defun org-property-previous-allowed-value (&optional previous)
15891 "Switch to the next allowed value for this property."
15892 (interactive)
15893 (org-property-next-allowed-value t))
15895 (defun org-property-next-allowed-value (&optional previous)
15896 "Switch to the next allowed value for this property."
15897 (interactive)
15898 (unless (org-at-property-p)
15899 (user-error "Not at a property"))
15900 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15901 (key (match-string 2))
15902 (value (match-string 3))
15903 (allowed (or (org-property-get-allowed-values (point) key)
15904 (and (member value '("[ ]" "[-]" "[X]"))
15905 '("[ ]" "[X]"))))
15906 (heading (save-match-data (nth 4 (org-heading-components))))
15907 nval)
15908 (unless allowed
15909 (user-error "Allowed values for this property have not been defined"))
15910 (if previous (setq allowed (reverse allowed)))
15911 (if (member value allowed)
15912 (setq nval (car (cdr (member value allowed)))))
15913 (setq nval (or nval (car allowed)))
15914 (if (equal nval value)
15915 (user-error "Only one allowed value for this property"))
15916 (org-at-property-p)
15917 (replace-match (concat " :" key ": " nval) t t)
15918 (org-indent-line)
15919 (beginning-of-line 1)
15920 (skip-chars-forward " \t")
15921 (when (equal prop org-effort-property)
15922 (save-excursion
15923 (org-back-to-heading t)
15924 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15925 (when (string= org-clock-current-task heading)
15926 (setq org-clock-effort nval)
15927 (org-clock-update-mode-line)))
15928 (run-hook-with-args 'org-property-changed-functions key nval)))
15930 (defun org-find-olp (path &optional this-buffer)
15931 "Return a marker pointing to the entry at outline path OLP.
15932 If anything goes wrong, throw an error.
15933 You can wrap this call to catch the error like this:
15935 (condition-case msg
15936 (org-mobile-locate-entry (match-string 4))
15937 (error (nth 1 msg)))
15939 The return value will then be either a string with the error message,
15940 or a marker if everything is OK.
15942 If THIS-BUFFER is set, the outline path does not contain a file,
15943 only headings."
15944 (let* ((file (if this-buffer buffer-file-name (pop path)))
15945 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15946 (level 1)
15947 (lmin 1)
15948 (lmax 1)
15949 limit re end found pos heading cnt flevel)
15950 (unless buffer (error "File not found :%s" file))
15951 (with-current-buffer buffer
15952 (save-excursion
15953 (save-restriction
15954 (widen)
15955 (setq limit (point-max))
15956 (goto-char (point-min))
15957 (while (setq heading (pop path))
15958 (setq re (format org-complex-heading-regexp-format
15959 (regexp-quote heading)))
15960 (setq cnt 0 pos (point))
15961 (while (re-search-forward re end t)
15962 (setq level (- (match-end 1) (match-beginning 1)))
15963 (if (and (>= level lmin) (<= level lmax))
15964 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15965 (when (= cnt 0) (error "Heading not found on level %d: %s"
15966 lmax heading))
15967 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15968 lmax heading))
15969 (goto-char found)
15970 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15971 (setq end (save-excursion (org-end-of-subtree t t))))
15972 (when (org-at-heading-p)
15973 (point-marker)))))))
15975 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15976 "Find node HEADING in BUFFER.
15977 Return a marker to the heading if it was found, or nil if not.
15978 If POS-ONLY is set, return just the position instead of a marker.
15980 The heading text must match exact, but it may have a TODO keyword,
15981 a priority cookie and tags in the standard locations."
15982 (with-current-buffer (or buffer (current-buffer))
15983 (save-excursion
15984 (save-restriction
15985 (widen)
15986 (goto-char (point-min))
15987 (let (case-fold-search)
15988 (if (re-search-forward
15989 (format org-complex-heading-regexp-format
15990 (regexp-quote heading)) nil t)
15991 (if pos-only
15992 (match-beginning 0)
15993 (move-marker (make-marker) (match-beginning 0)))))))))
15995 (defun org-find-exact-heading-in-directory (heading &optional dir)
15996 "Find Org node headline HEADING in all .org files in directory DIR.
15997 When the target headline is found, return a marker to this location."
15998 (let ((files (directory-files (or dir default-directory)
15999 nil "\\`[^.#].*\\.org\\'"))
16000 file visiting m buffer)
16001 (catch 'found
16002 (while (setq file (pop files))
16003 (message "trying %s" file)
16004 (setq visiting (org-find-base-buffer-visiting file))
16005 (setq buffer (or visiting (find-file-noselect file)))
16006 (setq m (org-find-exact-headline-in-buffer
16007 heading buffer))
16008 (when (and (not m) (not visiting)) (kill-buffer buffer))
16009 (and m (throw 'found m))))))
16011 (defun org-find-entry-with-id (ident)
16012 "Locate the entry that contains the ID property with exact value IDENT.
16013 IDENT can be a string, a symbol or a number, this function will search for
16014 the string representation of it.
16015 Return the position where this entry starts, or nil if there is no such entry."
16016 (interactive "sID: ")
16017 (let ((id (cond
16018 ((stringp ident) ident)
16019 ((symbol-name ident) (symbol-name ident))
16020 ((numberp ident) (number-to-string ident))
16021 (t (error "IDENT %s must be a string, symbol or number" ident))))
16022 (case-fold-search nil))
16023 (save-excursion
16024 (save-restriction
16025 (widen)
16026 (goto-char (point-min))
16027 (when (re-search-forward
16028 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16029 nil t)
16030 (org-back-to-heading t)
16031 (point))))))
16033 ;;;; Timestamps
16035 (defvar org-last-changed-timestamp nil)
16036 (defvar org-last-inserted-timestamp nil
16037 "The last time stamp inserted with `org-insert-time-stamp'.")
16038 (defvar org-time-was-given) ; dynamically scoped parameter
16039 (defvar org-end-time-was-given) ; dynamically scoped parameter
16040 (defvar org-ts-what) ; dynamically scoped parameter
16042 (defun org-time-stamp (arg &optional inactive)
16043 "Prompt for a date/time and insert a time stamp.
16044 If the user specifies a time like HH:MM or if this command is
16045 called with at least one prefix argument, the time stamp contains
16046 the date and the time. Otherwise, only the date is be included.
16048 All parts of a date not specified by the user is filled in from
16049 the current date/time. So if you just press return without
16050 typing anything, the time stamp will represent the current
16051 date/time.
16053 If there is already a timestamp at the cursor, it will be
16054 modified.
16056 With two universal prefix arguments, insert an active timestamp
16057 with the current time without prompting the user.
16059 When called from lisp, the timestamp is inactive if INACTIVE is
16060 non-nil."
16061 (interactive "P")
16062 (let* ((ts nil)
16063 (default-time
16064 ;; Default time is either today, or, when entering a range,
16065 ;; the range start.
16066 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16067 (save-excursion
16068 (re-search-backward
16069 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16070 (- (point) 20) t)))
16071 (apply 'encode-time (org-parse-time-string (match-string 1)))
16072 (current-time)))
16073 (default-input (and ts (org-get-compact-tod ts)))
16074 (repeater (save-excursion
16075 (save-match-data
16076 (beginning-of-line)
16077 (when (re-search-forward
16078 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16079 (save-excursion (progn (end-of-line) (point))) t)
16080 (match-string 0)))))
16081 org-time-was-given org-end-time-was-given time)
16082 (cond
16083 ((and (org-at-timestamp-p t)
16084 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16085 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16086 (insert "--")
16087 (setq time (let ((this-command this-command))
16088 (org-read-date arg 'totime nil nil
16089 default-time default-input inactive)))
16090 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16091 ((org-at-timestamp-p t)
16092 (setq time (let ((this-command this-command))
16093 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16094 (when (org-at-timestamp-p t) ; just to get the match data
16095 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16096 (replace-match "")
16097 (setq org-last-changed-timestamp
16098 (org-insert-time-stamp
16099 time (or org-time-was-given arg)
16100 inactive nil nil (list org-end-time-was-given)))
16101 (when repeater (goto-char (1- (point))) (insert " " repeater)
16102 (setq org-last-changed-timestamp
16103 (concat (substring org-last-inserted-timestamp 0 -1)
16104 " " repeater ">"))))
16105 (message "Timestamp updated"))
16106 ((equal arg '(16))
16107 (org-insert-time-stamp (current-time) t inactive))
16109 (setq time (let ((this-command this-command))
16110 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16111 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16112 nil nil (list org-end-time-was-given))))))
16114 ;; FIXME: can we use this for something else, like computing time differences?
16115 (defun org-get-compact-tod (s)
16116 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16117 (let* ((t1 (match-string 1 s))
16118 (h1 (string-to-number (match-string 2 s)))
16119 (m1 (string-to-number (match-string 3 s)))
16120 (t2 (and (match-end 4) (match-string 5 s)))
16121 (h2 (and t2 (string-to-number (match-string 6 s))))
16122 (m2 (and t2 (string-to-number (match-string 7 s))))
16123 dh dm)
16124 (if (not t2)
16126 (setq dh (- h2 h1) dm (- m2 m1))
16127 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16128 (concat t1 "+" (number-to-string dh)
16129 (and (/= 0 dm) (format ":%02d" dm)))))))
16131 (defun org-time-stamp-inactive (&optional arg)
16132 "Insert an inactive time stamp.
16133 An inactive time stamp is enclosed in square brackets instead of angle
16134 brackets. It is inactive in the sense that it does not trigger agenda entries,
16135 does not link to the calendar and cannot be changed with the S-cursor keys.
16136 So these are more for recording a certain time/date."
16137 (interactive "P")
16138 (org-time-stamp arg 'inactive))
16140 (defvar org-date-ovl (make-overlay 1 1))
16141 (overlay-put org-date-ovl 'face 'org-date-selected)
16142 (org-detach-overlay org-date-ovl)
16144 (defvar org-ans1) ; dynamically scoped parameter
16145 (defvar org-ans2) ; dynamically scoped parameter
16147 (defvar org-plain-time-of-day-regexp) ; defined below
16149 (defvar org-overriding-default-time nil) ; dynamically scoped
16150 (defvar org-read-date-overlay nil)
16151 (defvar org-dcst nil) ; dynamically scoped
16152 (defvar org-read-date-history nil)
16153 (defvar org-read-date-final-answer nil)
16154 (defvar org-read-date-analyze-futurep nil)
16155 (defvar org-read-date-analyze-forced-year nil)
16156 (defvar org-read-date-inactive)
16158 (defvar org-read-date-minibuffer-local-map
16159 (let* ((org-replace-disputed-keys nil)
16160 (map (make-sparse-keymap)))
16161 (set-keymap-parent map minibuffer-local-map)
16162 (org-defkey map (kbd ".")
16163 (lambda () (interactive)
16164 ;; Are we at the beginning of the prompt?
16165 (if (looking-back "^[^:]+: ")
16166 (org-eval-in-calendar '(calendar-goto-today))
16167 (insert "."))))
16168 (org-defkey map (kbd "C-.")
16169 (lambda () (interactive)
16170 (org-eval-in-calendar '(calendar-goto-today))))
16171 (org-defkey map [(meta shift left)]
16172 (lambda () (interactive)
16173 (org-eval-in-calendar '(calendar-backward-month 1))))
16174 (org-defkey map [(meta shift right)]
16175 (lambda () (interactive)
16176 (org-eval-in-calendar '(calendar-forward-month 1))))
16177 (org-defkey map [(meta shift up)]
16178 (lambda () (interactive)
16179 (org-eval-in-calendar '(calendar-backward-year 1))))
16180 (org-defkey map [(meta shift down)]
16181 (lambda () (interactive)
16182 (org-eval-in-calendar '(calendar-forward-year 1))))
16183 (org-defkey map [?\e (shift left)]
16184 (lambda () (interactive)
16185 (org-eval-in-calendar '(calendar-backward-month 1))))
16186 (org-defkey map [?\e (shift right)]
16187 (lambda () (interactive)
16188 (org-eval-in-calendar '(calendar-forward-month 1))))
16189 (org-defkey map [?\e (shift up)]
16190 (lambda () (interactive)
16191 (org-eval-in-calendar '(calendar-backward-year 1))))
16192 (org-defkey map [?\e (shift down)]
16193 (lambda () (interactive)
16194 (org-eval-in-calendar '(calendar-forward-year 1))))
16195 (org-defkey map [(shift up)]
16196 (lambda () (interactive)
16197 (org-eval-in-calendar '(calendar-backward-week 1))))
16198 (org-defkey map [(shift down)]
16199 (lambda () (interactive)
16200 (org-eval-in-calendar '(calendar-forward-week 1))))
16201 (org-defkey map [(shift left)]
16202 (lambda () (interactive)
16203 (org-eval-in-calendar '(calendar-backward-day 1))))
16204 (org-defkey map [(shift right)]
16205 (lambda () (interactive)
16206 (org-eval-in-calendar '(calendar-forward-day 1))))
16207 (org-defkey map "!"
16208 (lambda () (interactive)
16209 (org-eval-in-calendar '(diary-view-entries))
16210 (message "")))
16211 (org-defkey map ">"
16212 (lambda () (interactive)
16213 (org-eval-in-calendar '(scroll-calendar-left 1))))
16214 (org-defkey map "<"
16215 (lambda () (interactive)
16216 (org-eval-in-calendar '(scroll-calendar-right 1))))
16217 (org-defkey map "\C-v"
16218 (lambda () (interactive)
16219 (org-eval-in-calendar
16220 '(calendar-scroll-left-three-months 1))))
16221 (org-defkey map "\M-v"
16222 (lambda () (interactive)
16223 (org-eval-in-calendar
16224 '(calendar-scroll-right-three-months 1))))
16225 map)
16226 "Keymap for minibuffer commands when using `org-read-date'.")
16228 (defun org-read-date (&optional org-with-time to-time from-string prompt
16229 default-time default-input inactive)
16230 "Read a date, possibly a time, and make things smooth for the user.
16231 The prompt will suggest to enter an ISO date, but you can also enter anything
16232 which will at least partially be understood by `parse-time-string'.
16233 Unrecognized parts of the date will default to the current day, month, year,
16234 hour and minute. If this command is called to replace a timestamp at point,
16235 or to enter the second timestamp of a range, the default time is taken
16236 from the existing stamp. Furthermore, the command prefers the future,
16237 so if you are giving a date where the year is not given, and the day-month
16238 combination is already past in the current year, it will assume you
16239 mean next year. For details, see the manual. A few examples:
16241 3-2-5 --> 2003-02-05
16242 feb 15 --> currentyear-02-15
16243 2/15 --> currentyear-02-15
16244 sep 12 9 --> 2009-09-12
16245 12:45 --> today 12:45
16246 22 sept 0:34 --> currentyear-09-22 0:34
16247 12 --> currentyear-currentmonth-12
16248 Fri --> nearest Friday after today
16249 -Tue --> last Tuesday
16250 etc.
16252 Furthermore you can specify a relative date by giving, as the *first* thing
16253 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16254 change in days weeks, months, years.
16255 With a single plus or minus, the date is relative to today. With a double
16256 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16257 +4d --> four days from today
16258 +4 --> same as above
16259 +2w --> two weeks from today
16260 ++5 --> five days from default date
16262 The function understands only English month and weekday abbreviations.
16264 While prompting, a calendar is popped up - you can also select the
16265 date with the mouse (button 1). The calendar shows a period of three
16266 months. To scroll it to other months, use the keys `>' and `<'.
16267 If you don't like the calendar, turn it off with
16268 \(setq org-read-date-popup-calendar nil)
16270 With optional argument TO-TIME, the date will immediately be converted
16271 to an internal time.
16272 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16273 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16274 still enter a time, and this function will inform the calling routine
16275 about this change. The calling routine may then choose to change the
16276 format used to insert the time stamp into the buffer to include the time.
16277 With optional argument FROM-STRING, read from this string instead from
16278 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16279 the time/date that is used for everything that is not specified by the
16280 user."
16281 (require 'parse-time)
16282 (let* ((org-time-stamp-rounding-minutes
16283 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16284 (org-dcst org-display-custom-times)
16285 (ct (org-current-time))
16286 (org-def (or org-overriding-default-time default-time ct))
16287 (org-defdecode (decode-time org-def))
16288 (dummy (progn
16289 (when (< (nth 2 org-defdecode) org-extend-today-until)
16290 (setcar (nthcdr 2 org-defdecode) -1)
16291 (setcar (nthcdr 1 org-defdecode) 59)
16292 (setq org-def (apply 'encode-time org-defdecode)
16293 org-defdecode (decode-time org-def)))))
16294 (mouse-autoselect-window nil) ; Don't let the mouse jump
16295 (calendar-frame-setup nil)
16296 (calendar-setup nil)
16297 (calendar-move-hook nil)
16298 (calendar-view-diary-initially-flag nil)
16299 (calendar-view-holidays-initially-flag nil)
16300 (timestr (format-time-string
16301 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16302 (prompt (concat (if prompt (concat prompt " ") "")
16303 (format "Date+time [%s]: " timestr)))
16304 ans (org-ans0 "") org-ans1 org-ans2 final)
16306 (cond
16307 (from-string (setq ans from-string))
16308 (org-read-date-popup-calendar
16309 (save-excursion
16310 (save-window-excursion
16311 (calendar)
16312 (org-eval-in-calendar '(setq cursor-type nil) t)
16313 (unwind-protect
16314 (progn
16315 (calendar-forward-day (- (time-to-days org-def)
16316 (calendar-absolute-from-gregorian
16317 (calendar-current-date))))
16318 (org-eval-in-calendar nil t)
16319 (let* ((old-map (current-local-map))
16320 (map (copy-keymap calendar-mode-map))
16321 (minibuffer-local-map
16322 (copy-keymap org-read-date-minibuffer-local-map)))
16323 (org-defkey map (kbd "RET") 'org-calendar-select)
16324 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16325 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16326 (unwind-protect
16327 (progn
16328 (use-local-map map)
16329 (setq org-read-date-inactive inactive)
16330 (add-hook 'post-command-hook 'org-read-date-display)
16331 (setq org-ans0 (read-string prompt default-input
16332 'org-read-date-history nil))
16333 ;; org-ans0: from prompt
16334 ;; org-ans1: from mouse click
16335 ;; org-ans2: from calendar motion
16336 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16337 (remove-hook 'post-command-hook 'org-read-date-display)
16338 (use-local-map old-map)
16339 (when org-read-date-overlay
16340 (delete-overlay org-read-date-overlay)
16341 (setq org-read-date-overlay nil)))))
16342 (bury-buffer "*Calendar*")))))
16344 (t ; Naked prompt only
16345 (unwind-protect
16346 (setq ans (read-string prompt default-input
16347 'org-read-date-history timestr))
16348 (when org-read-date-overlay
16349 (delete-overlay org-read-date-overlay)
16350 (setq org-read-date-overlay nil)))))
16352 (setq final (org-read-date-analyze ans org-def org-defdecode))
16354 (when org-read-date-analyze-forced-year
16355 (message "Year was forced into %s"
16356 (if org-read-date-force-compatible-dates
16357 "compatible range (1970-2037)"
16358 "range representable on this machine"))
16359 (ding))
16361 ;; One round trip to get rid of 34th of August and stuff like that....
16362 (setq final (decode-time (apply 'encode-time final)))
16364 (setq org-read-date-final-answer ans)
16366 (if to-time
16367 (apply 'encode-time final)
16368 (if (and (boundp 'org-time-was-given) org-time-was-given)
16369 (format "%04d-%02d-%02d %02d:%02d"
16370 (nth 5 final) (nth 4 final) (nth 3 final)
16371 (nth 2 final) (nth 1 final))
16372 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16374 (defvar org-def)
16375 (defvar org-defdecode)
16376 (defvar org-with-time)
16377 (defun org-read-date-display ()
16378 "Display the current date prompt interpretation in the minibuffer."
16379 (when org-read-date-display-live
16380 (when org-read-date-overlay
16381 (delete-overlay org-read-date-overlay))
16382 (when (minibufferp (current-buffer))
16383 (save-excursion
16384 (end-of-line 1)
16385 (while (not (equal (buffer-substring
16386 (max (point-min) (- (point) 4)) (point))
16387 " "))
16388 (insert " ")))
16389 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16390 " " (or org-ans1 org-ans2)))
16391 (org-end-time-was-given nil)
16392 (f (org-read-date-analyze ans org-def org-defdecode))
16393 (fmts (if org-dcst
16394 org-time-stamp-custom-formats
16395 org-time-stamp-formats))
16396 (fmt (if (or org-with-time
16397 (and (boundp 'org-time-was-given) org-time-was-given))
16398 (cdr fmts)
16399 (car fmts)))
16400 (txt (format-time-string fmt (apply 'encode-time f)))
16401 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16402 (txt (concat "=> " txt)))
16403 (when (and org-end-time-was-given
16404 (string-match org-plain-time-of-day-regexp txt))
16405 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16406 org-end-time-was-given
16407 (substring txt (match-end 0)))))
16408 (when org-read-date-analyze-futurep
16409 (setq txt (concat txt " (=>F)")))
16410 (setq org-read-date-overlay
16411 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16412 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16414 (defun org-read-date-analyze (ans org-def org-defdecode)
16415 "Analyze the combined answer of the date prompt."
16416 ;; FIXME: cleanup and comment
16417 (let ((nowdecode (decode-time (current-time)))
16418 delta deltan deltaw deltadef year month day
16419 hour minute second wday pm h2 m2 tl wday1
16420 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16421 (setq org-read-date-analyze-futurep nil
16422 org-read-date-analyze-forced-year nil)
16423 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16424 (setq ans "+0"))
16426 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16427 (setq ans (replace-match "" t t ans)
16428 deltan (car delta)
16429 deltaw (nth 1 delta)
16430 deltadef (nth 2 delta)))
16432 ;; Check if there is an iso week date in there. If yes, store the
16433 ;; info and postpone interpreting it until the rest of the parsing
16434 ;; is done.
16435 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16436 (setq iso-year (if (match-end 1)
16437 (org-small-year-to-year
16438 (string-to-number (match-string 1 ans))))
16439 iso-weekday (if (match-end 3)
16440 (string-to-number (match-string 3 ans)))
16441 iso-week (string-to-number (match-string 2 ans)))
16442 (setq ans (replace-match "" t t ans)))
16444 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16445 (when (string-match
16446 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16447 (setq year (if (match-end 2)
16448 (string-to-number (match-string 2 ans))
16449 (progn (setq kill-year t)
16450 (string-to-number (format-time-string "%Y"))))
16451 month (string-to-number (match-string 3 ans))
16452 day (string-to-number (match-string 4 ans)))
16453 (if (< year 100) (setq year (+ 2000 year)))
16454 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16455 t nil ans)))
16457 ;; Help matching dotted european dates
16458 (when (string-match
16459 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16460 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16461 (setq kill-year t)
16462 (string-to-number (format-time-string "%Y")))
16463 day (string-to-number (match-string 1 ans))
16464 month (string-to-number (match-string 2 ans))
16465 ans (replace-match (format "%04d-%02d-%02d" year month day)
16466 t nil ans)))
16468 ;; Help matching american dates, like 5/30 or 5/30/7
16469 (when (string-match
16470 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16471 (setq year (if (match-end 4)
16472 (string-to-number (match-string 4 ans))
16473 (progn (setq kill-year t)
16474 (string-to-number (format-time-string "%Y"))))
16475 month (string-to-number (match-string 1 ans))
16476 day (string-to-number (match-string 2 ans)))
16477 (if (< year 100) (setq year (+ 2000 year)))
16478 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16479 t nil ans)))
16480 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16481 ;; If there is a time with am/pm, and *no* time without it, we convert
16482 ;; so that matching will be successful.
16483 (loop for i from 1 to 2 do ; twice, for end time as well
16484 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16485 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16486 (setq hour (string-to-number (match-string 1 ans))
16487 minute (if (match-end 3)
16488 (string-to-number (match-string 3 ans))
16490 pm (equal ?p
16491 (string-to-char (downcase (match-string 4 ans)))))
16492 (if (and (= hour 12) (not pm))
16493 (setq hour 0)
16494 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16495 (setq ans (replace-match (format "%02d:%02d" hour minute)
16496 t t ans))))
16498 ;; Check if a time range is given as a duration
16499 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16500 (setq hour (string-to-number (match-string 1 ans))
16501 h2 (+ hour (string-to-number (match-string 3 ans)))
16502 minute (string-to-number (match-string 2 ans))
16503 m2 (+ minute (if (match-end 5) (string-to-number
16504 (match-string 5 ans))0)))
16505 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16506 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16507 t t ans)))
16509 ;; Check if there is a time range
16510 (when (boundp 'org-end-time-was-given)
16511 (setq org-time-was-given nil)
16512 (when (and (string-match org-plain-time-of-day-regexp ans)
16513 (match-end 8))
16514 (setq org-end-time-was-given (match-string 8 ans))
16515 (setq ans (concat (substring ans 0 (match-beginning 7))
16516 (substring ans (match-end 7))))))
16518 (setq tl (parse-time-string ans)
16519 day (or (nth 3 tl) (nth 3 org-defdecode))
16520 month (or (nth 4 tl)
16521 (if (and org-read-date-prefer-future
16522 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16523 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16524 (nth 4 org-defdecode)))
16525 year (or (and (not kill-year) (nth 5 tl))
16526 (if (and org-read-date-prefer-future
16527 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16528 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16529 (nth 5 org-defdecode)))
16530 hour (or (nth 2 tl) (nth 2 org-defdecode))
16531 minute (or (nth 1 tl) (nth 1 org-defdecode))
16532 second (or (nth 0 tl) 0)
16533 wday (nth 6 tl))
16535 (when (and (eq org-read-date-prefer-future 'time)
16536 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16537 (equal day (nth 3 nowdecode))
16538 (equal month (nth 4 nowdecode))
16539 (equal year (nth 5 nowdecode))
16540 (nth 2 tl)
16541 (or (< (nth 2 tl) (nth 2 nowdecode))
16542 (and (= (nth 2 tl) (nth 2 nowdecode))
16543 (nth 1 tl)
16544 (< (nth 1 tl) (nth 1 nowdecode)))))
16545 (setq day (1+ day)
16546 futurep t))
16548 ;; Special date definitions below
16549 (cond
16550 (iso-week
16551 ;; There was an iso week
16552 (require 'cal-iso)
16553 (setq futurep nil)
16554 (setq year (or iso-year year)
16555 day (or iso-weekday wday 1)
16556 wday nil ; to make sure that the trigger below does not match
16557 iso-date (calendar-gregorian-from-absolute
16558 (calendar-absolute-from-iso
16559 (list iso-week day year))))
16560 ; FIXME: Should we also push ISO weeks into the future?
16561 ; (when (and org-read-date-prefer-future
16562 ; (not iso-year)
16563 ; (< (calendar-absolute-from-gregorian iso-date)
16564 ; (time-to-days (current-time))))
16565 ; (setq year (1+ year)
16566 ; iso-date (calendar-gregorian-from-absolute
16567 ; (calendar-absolute-from-iso
16568 ; (list iso-week day year)))))
16569 (setq month (car iso-date)
16570 year (nth 2 iso-date)
16571 day (nth 1 iso-date)))
16572 (deltan
16573 (setq futurep nil)
16574 (unless deltadef
16575 (let ((now (decode-time (current-time))))
16576 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16577 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16578 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16579 ((equal deltaw "m") (setq month (+ month deltan)))
16580 ((equal deltaw "y") (setq year (+ year deltan)))))
16581 ((and wday (not (nth 3 tl)))
16582 ;; Weekday was given, but no day, so pick that day in the week
16583 ;; on or after the derived date.
16584 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16585 (unless (equal wday wday1)
16586 (setq day (+ day (% (- wday wday1 -7) 7))))))
16587 (if (and (boundp 'org-time-was-given)
16588 (nth 2 tl))
16589 (setq org-time-was-given t))
16590 (if (< year 100) (setq year (+ 2000 year)))
16591 ;; Check of the date is representable
16592 (if org-read-date-force-compatible-dates
16593 (progn
16594 (if (< year 1970)
16595 (setq year 1970 org-read-date-analyze-forced-year t))
16596 (if (> year 2037)
16597 (setq year 2037 org-read-date-analyze-forced-year t)))
16598 (condition-case nil
16599 (ignore (encode-time second minute hour day month year))
16600 (error
16601 (setq year (nth 5 org-defdecode))
16602 (setq org-read-date-analyze-forced-year t))))
16603 (setq org-read-date-analyze-futurep futurep)
16604 (list second minute hour day month year)))
16606 (defvar parse-time-weekdays)
16607 (defun org-read-date-get-relative (s today default)
16608 "Check string S for special relative date string.
16609 TODAY and DEFAULT are internal times, for today and for a default.
16610 Return shift list (N what def-flag)
16611 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16612 N is the number of WHATs to shift.
16613 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16614 the DEFAULT date rather than TODAY."
16615 (require 'parse-time)
16616 (when (and
16617 (string-match
16618 (concat
16619 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16620 "\\([0-9]+\\)?"
16621 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16622 "\\([ \t]\\|$\\)") s)
16623 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16624 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16625 (string-to-char (substring (match-string 1 s) -1))
16626 ?+))
16627 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16628 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16629 (what (if (match-end 3) (match-string 3 s) "d"))
16630 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16631 (date (if rel default today))
16632 (wday (nth 6 (decode-time date)))
16633 delta)
16634 (if wday1
16635 (progn
16636 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16637 (if (= delta 0) (setq delta 7))
16638 (if (= dir ?-)
16639 (progn
16640 (setq delta (- delta 7))
16641 (if (= delta 0) (setq delta -7))))
16642 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16643 (list delta "d" rel))
16644 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16646 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16647 "Turn a user-specified date into the internal representation.
16648 The internal representation needed by the calendar is (month day year).
16649 This is a wrapper to handle the brain-dead convention in calendar that
16650 user function argument order change dependent on argument order."
16651 (if (boundp 'calendar-date-style)
16652 (cond
16653 ((eq calendar-date-style 'american)
16654 (list arg1 arg2 arg3))
16655 ((eq calendar-date-style 'european)
16656 (list arg2 arg1 arg3))
16657 ((eq calendar-date-style 'iso)
16658 (list arg2 arg3 arg1)))
16659 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16660 (if (org-bound-and-true-p european-calendar-style)
16661 (list arg2 arg1 arg3)
16662 (list arg1 arg2 arg3)))))
16664 (defun org-eval-in-calendar (form &optional keepdate)
16665 "Eval FORM in the calendar window and return to current window.
16666 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16667 otherwise stick to the current value of `org-ans2'."
16668 (let ((sf (selected-frame))
16669 (sw (selected-window)))
16670 (select-window (get-buffer-window "*Calendar*" t))
16671 (eval form)
16672 (when (and (not keepdate) (calendar-cursor-to-date))
16673 (let* ((date (calendar-cursor-to-date))
16674 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16675 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16676 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16677 (select-window sw)
16678 (org-select-frame-set-input-focus sf)))
16680 (defun org-calendar-select ()
16681 "Return to `org-read-date' with the date currently selected.
16682 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16683 (interactive)
16684 (when (calendar-cursor-to-date)
16685 (let* ((date (calendar-cursor-to-date))
16686 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16687 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16688 (if (active-minibuffer-window) (exit-minibuffer))))
16690 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16691 "Insert a date stamp for the date given by the internal TIME.
16692 WITH-HM means use the stamp format that includes the time of the day.
16693 INACTIVE means use square brackets instead of angular ones, so that the
16694 stamp will not contribute to the agenda.
16695 PRE and POST are optional strings to be inserted before and after the
16696 stamp.
16697 The command returns the inserted time stamp."
16698 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16699 stamp)
16700 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16701 (insert-before-markers (or pre ""))
16702 (when (listp extra)
16703 (setq extra (car extra))
16704 (if (and (stringp extra)
16705 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16706 (setq extra (format "-%02d:%02d"
16707 (string-to-number (match-string 1 extra))
16708 (string-to-number (match-string 2 extra))))
16709 (setq extra nil)))
16710 (when extra
16711 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16712 (insert-before-markers (setq stamp (format-time-string fmt time)))
16713 (insert-before-markers (or post ""))
16714 (setq org-last-inserted-timestamp stamp)))
16716 (defun org-toggle-time-stamp-overlays ()
16717 "Toggle the use of custom time stamp formats."
16718 (interactive)
16719 (setq org-display-custom-times (not org-display-custom-times))
16720 (unless org-display-custom-times
16721 (let ((p (point-min)) (bmp (buffer-modified-p)))
16722 (while (setq p (next-single-property-change p 'display))
16723 (if (and (get-text-property p 'display)
16724 (eq (get-text-property p 'face) 'org-date))
16725 (remove-text-properties
16726 p (setq p (next-single-property-change p 'display))
16727 '(display t))))
16728 (set-buffer-modified-p bmp)))
16729 (if (featurep 'xemacs)
16730 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16731 (org-restart-font-lock)
16732 (setq org-table-may-need-update t)
16733 (if org-display-custom-times
16734 (message "Time stamps are overlaid with custom format")
16735 (message "Time stamp overlays removed")))
16737 (defun org-display-custom-time (beg end)
16738 "Overlay modified time stamp format over timestamp between BEG and END."
16739 (let* ((ts (buffer-substring beg end))
16740 t1 w1 with-hm tf time str w2 (off 0))
16741 (save-match-data
16742 (setq t1 (org-parse-time-string ts t))
16743 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16744 (setq off (- (match-end 0) (match-beginning 0)))))
16745 (setq end (- end off))
16746 (setq w1 (- end beg)
16747 with-hm (and (nth 1 t1) (nth 2 t1))
16748 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16749 time (org-fix-decoded-time t1)
16750 str (org-add-props
16751 (format-time-string
16752 (substring tf 1 -1) (apply 'encode-time time))
16753 nil 'mouse-face 'highlight)
16754 w2 (length str))
16755 (if (not (= w2 w1))
16756 (add-text-properties (1+ beg) (+ 2 beg)
16757 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16758 (if (featurep 'xemacs)
16759 (progn
16760 (put-text-property beg end 'invisible t)
16761 (put-text-property beg end 'end-glyph (make-glyph str)))
16762 (put-text-property beg end 'display str))))
16764 (defun org-translate-time (string)
16765 "Translate all timestamps in STRING to custom format.
16766 But do this only if the variable `org-display-custom-times' is set."
16767 (when org-display-custom-times
16768 (save-match-data
16769 (let* ((start 0)
16770 (re org-ts-regexp-both)
16771 t1 with-hm inactive tf time str beg end)
16772 (while (setq start (string-match re string start))
16773 (setq beg (match-beginning 0)
16774 end (match-end 0)
16775 t1 (save-match-data
16776 (org-parse-time-string (substring string beg end) t))
16777 with-hm (and (nth 1 t1) (nth 2 t1))
16778 inactive (equal (substring string beg (1+ beg)) "[")
16779 tf (funcall (if with-hm 'cdr 'car)
16780 org-time-stamp-custom-formats)
16781 time (org-fix-decoded-time t1)
16782 str (format-time-string
16783 (concat
16784 (if inactive "[" "<") (substring tf 1 -1)
16785 (if inactive "]" ">"))
16786 (apply 'encode-time time))
16787 string (replace-match str t t string)
16788 start (+ start (length str)))))))
16789 string)
16791 (defun org-fix-decoded-time (time)
16792 "Set 0 instead of nil for the first 6 elements of time.
16793 Don't touch the rest."
16794 (let ((n 0))
16795 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16797 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16799 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16800 "Difference between TIMESTAMP-STRING and now in days.
16801 If SECONDS is non-nil, return the difference in seconds."
16802 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16803 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16804 (funcall fdiff (current-time)))))
16806 (defun org-deadline-close (timestamp-string &optional ndays)
16807 "Is the time in TIMESTAMP-STRING close to the current date?"
16808 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16809 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16810 (not (org-entry-is-done-p))))
16812 (defun org-get-wdays (ts &optional delay zero-delay)
16813 "Get the deadline lead time appropriate for timestring TS.
16814 When DELAY is non-nil, get the delay time for scheduled items
16815 instead of the deadline lead time. When ZERO-DELAY is non-nil
16816 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16817 don't try to find the delay cookie in the scheduled timestamp."
16818 (let ((tv (if delay org-scheduled-delay-days
16819 org-deadline-warning-days)))
16820 (cond
16821 ((or (and delay (< tv 0))
16822 (and delay zero-delay (<= tv 0))
16823 (and (not delay) (<= tv 0)))
16824 ;; Enforce this value no matter what
16825 (- tv))
16826 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16827 ;; lead time is specified.
16828 (floor (* (string-to-number (match-string 1 ts))
16829 (cdr (assoc (match-string 2 ts)
16830 '(("d" . 1) ("w" . 7)
16831 ("m" . 30.4) ("y" . 365.25)
16832 ("h" . 0.041667)))))))
16833 ;; go for the default.
16834 (t tv))))
16836 (defun org-calendar-select-mouse (ev)
16837 "Return to `org-read-date' with the date currently selected.
16838 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16839 (interactive "e")
16840 (mouse-set-point ev)
16841 (when (calendar-cursor-to-date)
16842 (let* ((date (calendar-cursor-to-date))
16843 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16844 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16845 (if (active-minibuffer-window) (exit-minibuffer))))
16847 (defun org-check-deadlines (ndays)
16848 "Check if there are any deadlines due or past due.
16849 A deadline is considered due if it happens within `org-deadline-warning-days'
16850 days from today's date. If the deadline appears in an entry marked DONE,
16851 it is not shown. The prefix arg NDAYS can be used to test that many
16852 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16853 (interactive "P")
16854 (let* ((org-warn-days
16855 (cond
16856 ((equal ndays '(4)) 100000)
16857 (ndays (prefix-numeric-value ndays))
16858 (t (abs org-deadline-warning-days))))
16859 (case-fold-search nil)
16860 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16861 (callback
16862 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16864 (message "%d deadlines past-due or due within %d days"
16865 (org-occur regexp nil callback)
16866 org-warn-days)))
16868 (defsubst org-re-timestamp (type)
16869 "Return a regexp for timestamp TYPE.
16870 Allowed values for TYPE are:
16872 all: all timestamps
16873 active: only active timestamps (<...>)
16874 inactive: only inactive timestamps ([...])
16875 scheduled: only scheduled timestamps
16876 deadline: only deadline timestamps
16877 closed: only closed time-stamps
16879 When TYPE is nil, fall back on returning a regexp that matches
16880 both scheduled and deadline timestamps."
16881 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16882 ((eq type 'active) org-ts-regexp)
16883 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16884 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16885 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16886 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16887 ((eq type 'scheduled-or-deadline)
16888 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16890 (defun org-check-before-date (date)
16891 "Check if there are deadlines or scheduled entries before DATE."
16892 (interactive (list (org-read-date)))
16893 (let ((case-fold-search nil)
16894 (regexp (org-re-timestamp org-ts-type))
16895 (callback
16896 (lambda () (time-less-p
16897 (org-time-string-to-time (match-string 1))
16898 (org-time-string-to-time date)))))
16899 (message "%d entries before %s"
16900 (org-occur regexp nil callback) date)))
16902 (defun org-check-after-date (date)
16903 "Check if there are deadlines or scheduled entries after DATE."
16904 (interactive (list (org-read-date)))
16905 (let ((case-fold-search nil)
16906 (regexp (org-re-timestamp org-ts-type))
16907 (callback
16908 (lambda () (not
16909 (time-less-p
16910 (org-time-string-to-time (match-string 1))
16911 (org-time-string-to-time date))))))
16912 (message "%d entries after %s"
16913 (org-occur regexp nil callback) date)))
16915 (defun org-check-dates-range (start-date end-date)
16916 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16917 (interactive (list (org-read-date nil nil nil "Range starts")
16918 (org-read-date nil nil nil "Range end")))
16919 (let ((case-fold-search nil)
16920 (regexp (org-re-timestamp org-ts-type))
16921 (callback
16922 (lambda ()
16923 (let ((match (match-string 1)))
16924 (and
16925 (not (time-less-p
16926 (org-time-string-to-time match)
16927 (org-time-string-to-time start-date)))
16928 (time-less-p
16929 (org-time-string-to-time match)
16930 (org-time-string-to-time end-date)))))))
16931 (message "%d entries between %s and %s"
16932 (org-occur regexp nil callback) start-date end-date)))
16934 (defun org-evaluate-time-range (&optional to-buffer)
16935 "Evaluate a time range by computing the difference between start and end.
16936 Normally the result is just printed in the echo area, but with prefix arg
16937 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16938 If the time range is actually in a table, the result is inserted into the
16939 next column.
16940 For time difference computation, a year is assumed to be exactly 365
16941 days in order to avoid rounding problems."
16942 (interactive "P")
16944 (org-clock-update-time-maybe)
16945 (save-excursion
16946 (unless (org-at-date-range-p t)
16947 (goto-char (point-at-bol))
16948 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16949 (if (not (org-at-date-range-p t))
16950 (user-error "Not at a time-stamp range, and none found in current line")))
16951 (let* ((ts1 (match-string 1))
16952 (ts2 (match-string 2))
16953 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16954 (match-end (match-end 0))
16955 (time1 (org-time-string-to-time ts1))
16956 (time2 (org-time-string-to-time ts2))
16957 (t1 (org-float-time time1))
16958 (t2 (org-float-time time2))
16959 (diff (abs (- t2 t1)))
16960 (negative (< (- t2 t1) 0))
16961 ;; (ys (floor (* 365 24 60 60)))
16962 (ds (* 24 60 60))
16963 (hs (* 60 60))
16964 (fy "%dy %dd %02d:%02d")
16965 (fy1 "%dy %dd")
16966 (fd "%dd %02d:%02d")
16967 (fd1 "%dd")
16968 (fh "%02d:%02d")
16969 y d h m align)
16970 (if havetime
16971 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16973 d (floor (/ diff ds)) diff (mod diff ds)
16974 h (floor (/ diff hs)) diff (mod diff hs)
16975 m (floor (/ diff 60)))
16976 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16978 d (floor (+ (/ diff ds) 0.5))
16979 h 0 m 0))
16980 (if (not to-buffer)
16981 (message "%s" (org-make-tdiff-string y d h m))
16982 (if (org-at-table-p)
16983 (progn
16984 (goto-char match-end)
16985 (setq align t)
16986 (and (looking-at " *|") (goto-char (match-end 0))))
16987 (goto-char match-end))
16988 (if (looking-at
16989 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16990 (replace-match ""))
16991 (if negative (insert " -"))
16992 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16993 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16994 (insert " " (format fh h m))))
16995 (if align (org-table-align))
16996 (message "Time difference inserted")))))
16998 (defun org-make-tdiff-string (y d h m)
16999 (let ((fmt "")
17000 (l nil))
17001 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17002 l (push y l)))
17003 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17004 l (push d l)))
17005 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17006 l (push h l)))
17007 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17008 l (push m l)))
17009 (apply 'format fmt (nreverse l))))
17011 (defun org-time-string-to-time (s &optional buffer pos)
17012 "Convert a timestamp string into internal time."
17013 (condition-case errdata
17014 (apply 'encode-time (org-parse-time-string s))
17015 (error (error "Bad timestamp `%s'%s\nError was: %s"
17016 s (if (not (and buffer pos))
17018 (format " at %d in buffer `%s'" pos buffer))
17019 (cdr errdata)))))
17021 (defun org-time-string-to-seconds (s)
17022 "Convert a timestamp string to a number of seconds."
17023 (org-float-time (org-time-string-to-time s)))
17025 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17026 "Convert a time stamp to an absolute day number.
17027 If there is a specifier for a cyclic time stamp, get the closest
17028 date to DAYNR.
17029 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17030 The variable `date' is bound by the calendar when this is called."
17031 (cond
17032 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17033 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17034 daynr
17035 (+ daynr 1000)))
17036 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17037 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17038 (time-to-days (current-time))) (match-string 0 s)
17039 prefer show-all))
17040 (t (time-to-days
17041 (condition-case errdata
17042 (apply 'encode-time (org-parse-time-string s))
17043 (error (error "Bad timestamp `%s'%s\nError was: %s"
17044 s (if (not (and buffer pos))
17046 (format " at %d in buffer `%s'" pos buffer))
17047 (cdr errdata))))))))
17049 (defun org-days-to-iso-week (days)
17050 "Return the iso week number."
17051 (require 'cal-iso)
17052 (car (calendar-iso-from-absolute days)))
17054 (defun org-small-year-to-year (year)
17055 "Convert 2-digit years into 4-digit years.
17056 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17057 The year 2000 cannot be abbreviated. Any year larger than 99
17058 is returned unchanged."
17059 (if (< year 38)
17060 (setq year (+ 2000 year))
17061 (if (< year 100)
17062 (setq year (+ 1900 year))))
17063 year)
17065 (defun org-time-from-absolute (d)
17066 "Return the time corresponding to date D.
17067 D may be an absolute day number, or a calendar-type list (month day year)."
17068 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17069 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17071 (defun org-calendar-holiday ()
17072 "List of holidays, for Diary display in Org-mode."
17073 (require 'holidays)
17074 (let ((hl (funcall
17075 (if (fboundp 'calendar-check-holidays)
17076 'calendar-check-holidays 'check-calendar-holidays) date)))
17077 (if hl (mapconcat 'identity hl "; "))))
17079 (defun org-diary-sexp-entry (sexp entry date)
17080 "Process a SEXP diary ENTRY for DATE."
17081 (require 'diary-lib)
17082 (let ((result (if calendar-debug-sexp
17083 (let ((stack-trace-on-error t))
17084 (eval (car (read-from-string sexp))))
17085 (condition-case nil
17086 (eval (car (read-from-string sexp)))
17087 (error
17088 (beep)
17089 (message "Bad sexp at line %d in %s: %s"
17090 (org-current-line)
17091 (buffer-file-name) sexp)
17092 (sleep-for 2))))))
17093 (cond ((stringp result) (split-string result "; "))
17094 ((and (consp result)
17095 (not (consp (cdr result)))
17096 (stringp (cdr result))) (cdr result))
17097 ((and (consp result)
17098 (stringp (car result))) result)
17099 (result entry))))
17101 (defun org-diary-to-ical-string (frombuf)
17102 "Get iCalendar entries from diary entries in buffer FROMBUF.
17103 This uses the icalendar.el library."
17104 (let* ((tmpdir (if (featurep 'xemacs)
17105 (temp-directory)
17106 temporary-file-directory))
17107 (tmpfile (make-temp-name
17108 (expand-file-name "orgics" tmpdir)))
17109 buf rtn b e)
17110 (with-current-buffer frombuf
17111 (icalendar-export-region (point-min) (point-max) tmpfile)
17112 (setq buf (find-buffer-visiting tmpfile))
17113 (set-buffer buf)
17114 (goto-char (point-min))
17115 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17116 (setq b (match-beginning 0)))
17117 (goto-char (point-max))
17118 (if (re-search-backward "^END:VEVENT" nil t)
17119 (setq e (match-end 0)))
17120 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17121 (kill-buffer buf)
17122 (delete-file tmpfile)
17123 rtn))
17125 (defun org-closest-date (start current change prefer show-all)
17126 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17127 When PREFER is `past', return a date that is either CURRENT or past.
17128 When PREFER is `future', return a date that is either CURRENT or future.
17129 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17130 ;; Make the proper lists from the dates
17131 (catch 'exit
17132 (let ((a1 '(("h" . hour)
17133 ("d" . day)
17134 ("w" . week)
17135 ("m" . month)
17136 ("y" . year)))
17137 (shour (nth 2 (org-parse-time-string start)))
17138 dn dw sday cday n1 n2 n0
17139 d m y y1 y2 date1 date2 nmonths nm ny m2)
17141 (setq start (org-date-to-gregorian start)
17142 current (org-date-to-gregorian
17143 (if show-all
17144 current
17145 (time-to-days (current-time))))
17146 sday (calendar-absolute-from-gregorian start)
17147 cday (calendar-absolute-from-gregorian current))
17149 (if (<= cday sday) (throw 'exit sday))
17151 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17152 (setq dn (string-to-number (match-string 1 change))
17153 dw (cdr (assoc (match-string 2 change) a1)))
17154 (user-error "Invalid change specifier: %s" change))
17155 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17156 (cond
17157 ((eq dw 'hour)
17158 (let ((missing-hours
17159 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17160 dn)))
17161 (setq n1 (if (zerop missing-hours) cday
17162 (- cday (1+ (floor (/ missing-hours 24)))))
17163 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17164 ((eq dw 'day)
17165 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17166 n2 (+ n1 dn)))
17167 ((eq dw 'year)
17168 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17169 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17170 (setq date1 (list m d y1)
17171 n1 (calendar-absolute-from-gregorian date1)
17172 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17173 n2 (calendar-absolute-from-gregorian date2)))
17174 ((eq dw 'month)
17175 ;; approx number of month between the two dates
17176 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17177 ;; How often does dn fit in there?
17178 (setq d (nth 1 start) m (car start) y (nth 2 start)
17179 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17180 m (+ m nm)
17181 ny (floor (/ m 12))
17182 y (+ y ny)
17183 m (- m (* ny 12)))
17184 (while (> m 12) (setq m (- m 12) y (1+ y)))
17185 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17186 (setq m2 (+ m dn) y2 y)
17187 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17188 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17189 (while (<= n2 cday)
17190 (setq n1 n2 m m2 y y2)
17191 (setq m2 (+ m dn) y2 y)
17192 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17193 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17194 ;; Make sure n1 is the earlier date
17195 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17196 (if show-all
17197 (cond
17198 ((eq prefer 'past) (if (= cday n2) n2 n1))
17199 ((eq prefer 'future) (if (= cday n1) n1 n2))
17200 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17201 (cond
17202 ((eq prefer 'past) (if (= cday n2) n2 n1))
17203 ((eq prefer 'future) (if (= cday n1) n1 n2))
17204 (t (if (= cday n1) n1 n2)))))))
17206 (defun org-date-to-gregorian (date)
17207 "Turn any specification of DATE into a Gregorian date for the calendar."
17208 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17209 ((and (listp date) (= (length date) 3)) date)
17210 ((stringp date)
17211 (setq date (org-parse-time-string date))
17212 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17213 ((listp date)
17214 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17216 (defun org-parse-time-string (s &optional nodefault)
17217 "Parse the standard Org-mode time string.
17218 This should be a lot faster than the normal `parse-time-string'.
17219 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17220 hour and minute fields will be nil if not given."
17221 (cond ((string-match org-ts-regexp0 s)
17222 (list 0
17223 (if (or (match-beginning 8) (not nodefault))
17224 (string-to-number (or (match-string 8 s) "0")))
17225 (if (or (match-beginning 7) (not nodefault))
17226 (string-to-number (or (match-string 7 s) "0")))
17227 (string-to-number (match-string 4 s))
17228 (string-to-number (match-string 3 s))
17229 (string-to-number (match-string 2 s))
17230 nil nil nil))
17231 ((string-match "^<[^>]+>$" s)
17232 (decode-time (seconds-to-time (org-matcher-time s))))
17233 (t (error "Not a standard Org-mode time string: %s" s))))
17235 (defun org-timestamp-up (&optional arg)
17236 "Increase the date item at the cursor by one.
17237 If the cursor is on the year, change the year. If it is on the month,
17238 the day or the time, change that.
17239 With prefix ARG, change by that many units."
17240 (interactive "p")
17241 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17243 (defun org-timestamp-down (&optional arg)
17244 "Decrease the date item at the cursor by one.
17245 If the cursor is on the year, change the year. If it is on the month,
17246 the day or the time, change that.
17247 With prefix ARG, change by that many units."
17248 (interactive "p")
17249 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17251 (defun org-timestamp-up-day (&optional arg)
17252 "Increase the date in the time stamp by one day.
17253 With prefix ARG, change that many days."
17254 (interactive "p")
17255 (if (and (not (org-at-timestamp-p t))
17256 (org-at-heading-p))
17257 (org-todo 'up)
17258 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17260 (defun org-timestamp-down-day (&optional arg)
17261 "Decrease the date in the time stamp by one day.
17262 With prefix ARG, change that many days."
17263 (interactive "p")
17264 (if (and (not (org-at-timestamp-p t))
17265 (org-at-heading-p))
17266 (org-todo 'down)
17267 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17269 (defun org-at-timestamp-p (&optional inactive-ok)
17270 "Determine if the cursor is in or at a timestamp."
17271 (interactive)
17272 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17273 (pos (point))
17274 (ans (or (looking-at tsr)
17275 (save-excursion
17276 (skip-chars-backward "^[<\n\r\t")
17277 (if (> (point) (point-min)) (backward-char 1))
17278 (and (looking-at tsr)
17279 (> (- (match-end 0) pos) -1))))))
17280 (and ans
17281 (boundp 'org-ts-what)
17282 (setq org-ts-what
17283 (cond
17284 ((= pos (match-beginning 0)) 'bracket)
17285 ;; Point is considered to be "on the bracket" whether
17286 ;; it's really on it or right after it.
17287 ((= pos (1- (match-end 0))) 'bracket)
17288 ((= pos (match-end 0)) 'after)
17289 ((org-pos-in-match-range pos 2) 'year)
17290 ((org-pos-in-match-range pos 3) 'month)
17291 ((org-pos-in-match-range pos 7) 'hour)
17292 ((org-pos-in-match-range pos 8) 'minute)
17293 ((or (org-pos-in-match-range pos 4)
17294 (org-pos-in-match-range pos 5)) 'day)
17295 ((and (> pos (or (match-end 8) (match-end 5)))
17296 (< pos (match-end 0)))
17297 (- pos (or (match-end 8) (match-end 5))))
17298 (t 'day))))
17299 ans))
17301 (defun org-toggle-timestamp-type ()
17302 "Toggle the type (<active> or [inactive]) of a time stamp."
17303 (interactive)
17304 (when (org-at-timestamp-p t)
17305 (let ((beg (match-beginning 0)) (end (match-end 0))
17306 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17307 (save-excursion
17308 (goto-char beg)
17309 (while (re-search-forward "[][<>]" end t)
17310 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17311 t t)))
17312 (message "Timestamp is now %sactive"
17313 (if (equal (char-after beg) ?<) "" "in")))))
17315 (defun org-at-clock-log-p nil
17316 "Is the cursor on the clock log line?"
17317 (save-excursion
17318 (move-beginning-of-line 1)
17319 (looking-at "^[ \t]*CLOCK:")))
17321 (defvar org-clock-history) ; defined in org-clock.el
17322 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17323 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17324 "Change the date in the time stamp at point.
17325 The date will be changed by N times WHAT. WHAT can be `day', `month',
17326 `year', `minute', `second'. If WHAT is not given, the cursor position
17327 in the timestamp determines what will be changed.
17328 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17329 (let ((origin (point)) origin-cat
17330 with-hm inactive
17331 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17332 org-ts-what
17333 extra rem
17334 ts time time0 fixnext clrgx)
17335 (if (not (org-at-timestamp-p t))
17336 (user-error "Not at a timestamp"))
17337 (if (and (not what) (eq org-ts-what 'bracket))
17338 (org-toggle-timestamp-type)
17339 ;; Point isn't on brackets. Remember the part of the time-stamp
17340 ;; the point was in. Indeed, size of time-stamps may change,
17341 ;; but point must be kept in the same category nonetheless.
17342 (setq origin-cat org-ts-what)
17343 (if (and (not what) (not (eq org-ts-what 'day))
17344 org-display-custom-times
17345 (get-text-property (point) 'display)
17346 (not (get-text-property (1- (point)) 'display)))
17347 (setq org-ts-what 'day))
17348 (setq org-ts-what (or what org-ts-what)
17349 inactive (= (char-after (match-beginning 0)) ?\[)
17350 ts (match-string 0))
17351 (replace-match "")
17352 (when (string-match
17353 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17355 (setq extra (match-string 1 ts))
17356 (if suppress-tmp-delay
17357 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17358 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17359 (setq with-hm t))
17360 (setq time0 (org-parse-time-string ts))
17361 (when (and updown
17362 (eq org-ts-what 'minute)
17363 (not current-prefix-arg))
17364 ;; This looks like s-up and s-down. Change by one rounding step.
17365 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17366 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17367 (setcar (cdr time0) (+ (nth 1 time0)
17368 (if (> n 0) (- rem) (- dm rem))))))
17369 (setq time
17370 (encode-time (or (car time0) 0)
17371 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17372 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17373 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17374 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17375 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17376 (nthcdr 6 time0)))
17377 (when (and (member org-ts-what '(hour minute))
17378 extra
17379 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17380 (setq extra (org-modify-ts-extra
17381 extra
17382 (if (eq org-ts-what 'hour) 2 5)
17383 n dm)))
17384 (when (integerp org-ts-what)
17385 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17386 (if (eq what 'calendar)
17387 (let ((cal-date (org-get-date-from-calendar)))
17388 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17389 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17390 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17391 (setcar time0 (or (car time0) 0))
17392 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17393 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17394 (setq time (apply 'encode-time time0))))
17395 ;; Insert the new time-stamp, and ensure point stays in the same
17396 ;; category as before (i.e. not after the last position in that
17397 ;; category).
17398 (let ((pos (point)))
17399 ;; Stay before inserted string. `save-excursion' is of no use.
17400 (setq org-last-changed-timestamp
17401 (org-insert-time-stamp time with-hm inactive nil nil extra))
17402 (goto-char pos))
17403 (save-match-data
17404 (looking-at org-ts-regexp3)
17405 (goto-char (cond
17406 ;; `day' category ends before `hour' if any, or at
17407 ;; the end of the day name.
17408 ((eq origin-cat 'day)
17409 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17410 ((eq origin-cat 'hour) (min (match-end 7) origin))
17411 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17412 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17413 ;; `year' and `month' have both fixed size: point
17414 ;; couldn't have moved into another part.
17415 (t origin))))
17416 ;; Update clock if on a CLOCK line.
17417 (org-clock-update-time-maybe)
17418 ;; Maybe adjust the closest clock in `org-clock-history'
17419 (when org-clock-adjust-closest
17420 (if (not (and (org-at-clock-log-p)
17421 (< 1 (length (delq nil (mapcar 'marker-position
17422 org-clock-history))))))
17423 (message "No clock to adjust")
17424 (cond ((save-excursion ; fix previous clock?
17425 (re-search-backward org-ts-regexp0 nil t)
17426 (org-looking-back (concat org-clock-string " \\[")))
17427 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17428 ((save-excursion ; fix next clock?
17429 (re-search-backward org-ts-regexp0 nil t)
17430 (looking-at (concat org-ts-regexp0 "\\] =>")))
17431 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17432 (save-window-excursion
17433 ;; Find closest clock to point, adjust the previous/next one in history
17434 (let* ((p (save-excursion (org-back-to-heading t)))
17435 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17436 (clfixnth
17437 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17438 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17439 (if (not clfixpos)
17440 (message "No clock to adjust")
17441 (save-excursion
17442 (org-goto-marker-or-bmk clfixpos)
17443 (org-show-subtree)
17444 (when (re-search-forward clrgx nil t)
17445 (goto-char (match-beginning 1))
17446 (let (org-clock-adjust-closest)
17447 (org-timestamp-change n org-ts-what updown))
17448 (message "Clock adjusted in %s for heading: %s"
17449 (file-name-nondirectory (buffer-file-name))
17450 (org-get-heading t t)))))))))
17451 ;; Try to recenter the calendar window, if any.
17452 (if (and org-calendar-follow-timestamp-change
17453 (get-buffer-window "*Calendar*" t)
17454 (memq org-ts-what '(day month year)))
17455 (org-recenter-calendar (time-to-days time))))))
17457 (defun org-modify-ts-extra (s pos n dm)
17458 "Change the different parts of the lead-time and repeat fields in timestamp."
17459 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17460 ng h m new rem)
17461 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17462 (cond
17463 ((or (org-pos-in-match-range pos 2)
17464 (org-pos-in-match-range pos 3))
17465 (setq m (string-to-number (match-string 3 s))
17466 h (string-to-number (match-string 2 s)))
17467 (if (org-pos-in-match-range pos 2)
17468 (setq h (+ h n))
17469 (setq n (* dm (org-no-warnings (signum n))))
17470 (when (not (= 0 (setq rem (% m dm))))
17471 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17472 (setq m (+ m n)))
17473 (if (< m 0) (setq m (+ m 60) h (1- h)))
17474 (if (> m 59) (setq m (- m 60) h (1+ h)))
17475 (setq h (min 24 (max 0 h)))
17476 (setq ng 1 new (format "-%02d:%02d" h m)))
17477 ((org-pos-in-match-range pos 6)
17478 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17479 ((org-pos-in-match-range pos 5)
17480 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17482 ((org-pos-in-match-range pos 9)
17483 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17484 ((org-pos-in-match-range pos 8)
17485 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17487 (when ng
17488 (setq s (concat
17489 (substring s 0 (match-beginning ng))
17491 (substring s (match-end ng))))))
17494 (defun org-recenter-calendar (date)
17495 "If the calendar is visible, recenter it to DATE."
17496 (let ((cwin (get-buffer-window "*Calendar*" t)))
17497 (when cwin
17498 (let ((calendar-move-hook nil))
17499 (with-selected-window cwin
17500 (calendar-goto-date (if (listp date) date
17501 (calendar-gregorian-from-absolute date))))))))
17503 (defun org-goto-calendar (&optional arg)
17504 "Go to the Emacs calendar at the current date.
17505 If there is a time stamp in the current line, go to that date.
17506 A prefix ARG can be used to force the current date."
17507 (interactive "P")
17508 (let ((tsr org-ts-regexp) diff
17509 (calendar-move-hook nil)
17510 (calendar-view-holidays-initially-flag nil)
17511 (calendar-view-diary-initially-flag nil))
17512 (if (or (org-at-timestamp-p)
17513 (save-excursion
17514 (beginning-of-line 1)
17515 (looking-at (concat ".*" tsr))))
17516 (let ((d1 (time-to-days (current-time)))
17517 (d2 (time-to-days
17518 (org-time-string-to-time (match-string 1)))))
17519 (setq diff (- d2 d1))))
17520 (calendar)
17521 (calendar-goto-today)
17522 (if (and diff (not arg)) (calendar-forward-day diff))))
17524 (defun org-get-date-from-calendar ()
17525 "Return a list (month day year) of date at point in calendar."
17526 (with-current-buffer "*Calendar*"
17527 (save-match-data
17528 (calendar-cursor-to-date))))
17530 (defun org-date-from-calendar ()
17531 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17532 If there is already a time stamp at the cursor position, update it."
17533 (interactive)
17534 (if (org-at-timestamp-p t)
17535 (org-timestamp-change 0 'calendar)
17536 (let ((cal-date (org-get-date-from-calendar)))
17537 (org-insert-time-stamp
17538 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17540 (defcustom org-effort-durations
17541 `(("h" . 60)
17542 ("d" . ,(* 60 8))
17543 ("w" . ,(* 60 8 5))
17544 ("m" . ,(* 60 8 5 4))
17545 ("y" . ,(* 60 8 5 40)))
17546 "Conversion factor to minutes for an effort modifier.
17548 Each entry has the form (MODIFIER . MINUTES).
17550 In an effort string, a number followed by MODIFIER is multiplied
17551 by the specified number of MINUTES to obtain an effort in
17552 minutes.
17554 For example, if the value of this variable is ((\"hours\" . 60)), then an
17555 effort string \"2hours\" is equivalent to 120 minutes."
17556 :group 'org-agenda
17557 :version "24.1"
17558 :type '(alist :key-type (string :tag "Modifier")
17559 :value-type (number :tag "Minutes")))
17561 (defun org-minutes-to-clocksum-string (m)
17562 "Format number of minutes as a clocksum string.
17563 The format is determined by `org-time-clocksum-format',
17564 `org-time-clocksum-use-fractional' and
17565 `org-time-clocksum-fractional-format' and
17566 `org-time-clocksum-use-effort-durations'."
17567 (let ((clocksum "")
17568 (m (round m)) ; Don't allow fractions of minutes
17569 h d w mo y fmt n)
17570 (setq h (if org-time-clocksum-use-effort-durations
17571 (cdr (assoc "h" org-effort-durations)) 60)
17572 d (if org-time-clocksum-use-effort-durations
17573 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17574 w (if org-time-clocksum-use-effort-durations
17575 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17576 mo (if org-time-clocksum-use-effort-durations
17577 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17578 y (if org-time-clocksum-use-effort-durations
17579 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17580 ;; fractional format
17581 (if org-time-clocksum-use-fractional
17582 (cond
17583 ;; single format string
17584 ((stringp org-time-clocksum-fractional-format)
17585 (format org-time-clocksum-fractional-format (/ m (float h))))
17586 ;; choice of fractional formats for different time units
17587 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17588 (> (/ (truncate m) (* y d h)) 0))
17589 (format fmt (/ m (* y d (float h)))))
17590 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17591 (> (/ (truncate m) (* mo d h)) 0))
17592 (format fmt (/ m (* mo d (float h)))))
17593 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17594 (> (/ (truncate m) (* w d h)) 0))
17595 (format fmt (/ m (* w d (float h)))))
17596 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17597 (> (/ (truncate m) (* d h)) 0))
17598 (format fmt (/ m (* d (float h)))))
17599 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17600 (> (/ (truncate m) h) 0))
17601 (format fmt (/ m (float h))))
17602 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17603 (format fmt m))
17604 ;; fall back to smallest time unit with a format
17605 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17606 (format fmt (/ m (float h))))
17607 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17608 (format fmt (/ m (* d (float h)))))
17609 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17610 (format fmt (/ m (* w d (float h)))))
17611 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17612 (format fmt (/ m (* mo d (float h)))))
17613 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17614 (format fmt (/ m (* y d (float h))))))
17615 ;; standard (non-fractional) format, with single format string
17616 (if (stringp org-time-clocksum-format)
17617 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17618 ;; separate formats components
17619 (and (setq fmt (plist-get org-time-clocksum-format :years))
17620 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17621 (plist-get org-time-clocksum-format :require-years))
17622 (setq clocksum (concat clocksum (format fmt n))
17623 m (- m (* n y d h))))
17624 (and (setq fmt (plist-get org-time-clocksum-format :months))
17625 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17626 (plist-get org-time-clocksum-format :require-months))
17627 (setq clocksum (concat clocksum (format fmt n))
17628 m (- m (* n mo d h))))
17629 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17630 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17631 (plist-get org-time-clocksum-format :require-weeks))
17632 (setq clocksum (concat clocksum (format fmt n))
17633 m (- m (* n w d h))))
17634 (and (setq fmt (plist-get org-time-clocksum-format :days))
17635 (or (> (setq n (/ (truncate m) (* d h))) 0)
17636 (plist-get org-time-clocksum-format :require-days))
17637 (setq clocksum (concat clocksum (format fmt n))
17638 m (- m (* n d h))))
17639 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17640 (or (> (setq n (/ (truncate m) h)) 0)
17641 (plist-get org-time-clocksum-format :require-hours))
17642 (setq clocksum (concat clocksum (format fmt n))
17643 m (- m (* n h))))
17644 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17645 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17646 (setq clocksum (concat clocksum (format fmt m))))
17647 ;; return formatted time duration
17648 clocksum))))
17650 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17651 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17652 "Org mode version 8.0")
17654 (defun org-hours-to-clocksum-string (n)
17655 (org-minutes-to-clocksum-string (* n 60)))
17657 (defun org-hh:mm-string-to-minutes (s)
17658 "Convert a string H:MM to a number of minutes.
17659 If the string is just a number, interpret it as minutes.
17660 In fact, the first hh:mm or number in the string will be taken,
17661 there can be extra stuff in the string.
17662 If no number is found, the return value is 0."
17663 (cond
17664 ((integerp s) s)
17665 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17666 (+ (* (string-to-number (match-string 1 s)) 60)
17667 (string-to-number (match-string 2 s))))
17668 ((string-match "\\([0-9]+\\)" s)
17669 (string-to-number (match-string 1 s)))
17670 (t 0)))
17672 (defcustom org-image-actual-width t
17673 "Should we use the actual width of images when inlining them?
17675 When set to `t', always use the image width.
17677 When set to a number, use imagemagick (when available) to set
17678 the image's width to this value.
17680 When set to a number in a list, try to get the width from any
17681 #+ATTR.* keyword if it matches a width specification like
17683 #+ATTR_HTML: :width 300px
17685 and fall back on that number if none is found.
17687 When set to nil, try to get the width from an #+ATTR.* keyword
17688 and fall back on the original width if none is found.
17690 This requires Emacs >= 24.1, build with imagemagick support."
17691 :group 'org-appearance
17692 :version "24.4"
17693 :package-version '(Org . "8.0")
17694 :type '(choice
17695 (const :tag "Use the image width" t)
17696 (integer :tag "Use a number of pixels")
17697 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17698 (const :tag "Use #+ATTR* or don't resize" nil)))
17700 (defcustom org-agenda-inhibit-startup nil
17701 "Inhibit startup when preparing agenda buffers.
17702 When this variable is `t' (the default), the initialization of
17703 the Org agenda buffers is inhibited: e.g. the visibility state
17704 is not set, the tables are not re-aligned, etc."
17705 :type 'boolean
17706 :version "24.3"
17707 :group 'org-agenda)
17709 (defcustom org-agenda-ignore-drawer-properties nil
17710 "Avoid updating text properties when building the agenda.
17711 Properties are used to prepare buffers for effort estimates, appointments,
17712 and subtree-local categories.
17713 If you don't use these in the agenda, you can add them to this list and
17714 agenda building will be a bit faster.
17715 The value is a list, with zero or more of the symbols `effort', `appt',
17716 or `category'."
17717 :type '(set :greedy t
17718 (const effort)
17719 (const appt)
17720 (const category))
17721 :version "24.3"
17722 :group 'org-agenda)
17724 (defun org-duration-string-to-minutes (s &optional output-to-string)
17725 "Convert a duration string S to minutes.
17727 A bare number is interpreted as minutes, modifiers can be set by
17728 customizing `org-effort-durations' (which see).
17730 Entries containing a colon are interpreted as H:MM by
17731 `org-hh:mm-string-to-minutes'."
17732 (let ((result 0)
17733 (re (concat "\\([0-9.]+\\) *\\("
17734 (regexp-opt (mapcar 'car org-effort-durations))
17735 "\\)")))
17736 (while (string-match re s)
17737 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17738 (string-to-number (match-string 1 s))))
17739 (setq s (replace-match "" nil t s)))
17740 (setq result (floor result))
17741 (incf result (org-hh:mm-string-to-minutes s))
17742 (if output-to-string (number-to-string result) result)))
17744 ;;;; Files
17746 (defun org-save-all-org-buffers ()
17747 "Save all Org-mode buffers without user confirmation."
17748 (interactive)
17749 (message "Saving all Org-mode buffers...")
17750 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17751 (when (featurep 'org-id) (org-id-locations-save))
17752 (message "Saving all Org-mode buffers... done"))
17754 (defun org-revert-all-org-buffers ()
17755 "Revert all Org-mode buffers.
17756 Prompt for confirmation when there are unsaved changes.
17757 Be sure you know what you are doing before letting this function
17758 overwrite your changes.
17760 This function is useful in a setup where one tracks org files
17761 with a version control system, to revert on one machine after pulling
17762 changes from another. I believe the procedure must be like this:
17764 1. M-x org-save-all-org-buffers
17765 2. Pull changes from the other machine, resolve conflicts
17766 3. M-x org-revert-all-org-buffers"
17767 (interactive)
17768 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17769 (user-error "Abort"))
17770 (save-excursion
17771 (save-window-excursion
17772 (mapc
17773 (lambda (b)
17774 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17775 (with-current-buffer b buffer-file-name))
17776 (org-pop-to-buffer-same-window b)
17777 (revert-buffer t 'no-confirm)))
17778 (buffer-list))
17779 (when (and (featurep 'org-id) org-id-track-globally)
17780 (org-id-locations-load)))))
17782 ;;;; Agenda files
17784 ;;;###autoload
17785 (defun org-switchb (&optional arg)
17786 "Switch between Org buffers.
17787 With one prefix argument, restrict available buffers to files.
17788 With two prefix arguments, restrict available buffers to agenda files.
17790 Defaults to `iswitchb' for buffer name completion.
17791 Set `org-completion-use-ido' to make it use ido instead."
17792 (interactive "P")
17793 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17794 ((equal arg '(16)) (org-buffer-list 'agenda))
17795 (t (org-buffer-list))))
17796 (org-completion-use-iswitchb org-completion-use-iswitchb)
17797 (org-completion-use-ido org-completion-use-ido))
17798 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17799 (setq org-completion-use-iswitchb t))
17800 (org-pop-to-buffer-same-window
17801 (org-icompleting-read "Org buffer: "
17802 (mapcar 'list (mapcar 'buffer-name blist))
17803 nil t))))
17805 ;;; Define some older names previously used for this functionality
17806 ;;;###autoload
17807 (defalias 'org-ido-switchb 'org-switchb)
17808 ;;;###autoload
17809 (defalias 'org-iswitchb 'org-switchb)
17811 (defun org-buffer-list (&optional predicate exclude-tmp)
17812 "Return a list of Org buffers.
17813 PREDICATE can be `export', `files' or `agenda'.
17815 export restrict the list to Export buffers.
17816 files restrict the list to buffers visiting Org files.
17817 agenda restrict the list to buffers visiting agenda files.
17819 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17820 (let* ((bfn nil)
17821 (agenda-files (and (eq predicate 'agenda)
17822 (mapcar 'file-truename (org-agenda-files t))))
17823 (filter
17824 (cond
17825 ((eq predicate 'files)
17826 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17827 ((eq predicate 'export)
17828 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17829 ((eq predicate 'agenda)
17830 (lambda (b)
17831 (with-current-buffer b
17832 (and (derived-mode-p 'org-mode)
17833 (setq bfn (buffer-file-name b))
17834 (member (file-truename bfn) agenda-files)))))
17835 (t (lambda (b) (with-current-buffer b
17836 (or (derived-mode-p 'org-mode)
17837 (string-match "\*Org .*Export"
17838 (buffer-name b)))))))))
17839 (delq nil
17840 (mapcar
17841 (lambda(b)
17842 (if (and (funcall filter b)
17843 (or (not exclude-tmp)
17844 (not (string-match "tmp" (buffer-name b)))))
17846 nil))
17847 (buffer-list)))))
17849 (defun org-agenda-files (&optional unrestricted archives)
17850 "Get the list of agenda files.
17851 Optional UNRESTRICTED means return the full list even if a restriction
17852 is currently in place.
17853 When ARCHIVES is t, include all archive files that are really being
17854 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17855 `org-agenda-archives-mode' is t."
17856 (let ((files
17857 (cond
17858 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17859 ((stringp org-agenda-files) (org-read-agenda-file-list))
17860 ((listp org-agenda-files) org-agenda-files)
17861 (t (error "Invalid value of `org-agenda-files'")))))
17862 (setq files (apply 'append
17863 (mapcar (lambda (f)
17864 (if (file-directory-p f)
17865 (directory-files
17866 f t org-agenda-file-regexp)
17867 (list f)))
17868 files)))
17869 (when org-agenda-skip-unavailable-files
17870 (setq files (delq nil
17871 (mapcar (function
17872 (lambda (file)
17873 (and (file-readable-p file) file)))
17874 files))))
17875 (when (or (eq archives t)
17876 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17877 (setq files (org-add-archive-files files)))
17878 files))
17880 (defun org-agenda-file-p (&optional file)
17881 "Return non-nil, if FILE is an agenda file.
17882 If FILE is omitted, use the file associated with the current
17883 buffer."
17884 (member (or file (buffer-file-name))
17885 (org-agenda-files t)))
17887 (defun org-edit-agenda-file-list ()
17888 "Edit the list of agenda files.
17889 Depending on setup, this either uses customize to edit the variable
17890 `org-agenda-files', or it visits the file that is holding the list. In the
17891 latter case, the buffer is set up in a way that saving it automatically kills
17892 the buffer and restores the previous window configuration."
17893 (interactive)
17894 (if (stringp org-agenda-files)
17895 (let ((cw (current-window-configuration)))
17896 (find-file org-agenda-files)
17897 (org-set-local 'org-window-configuration cw)
17898 (org-add-hook 'after-save-hook
17899 (lambda ()
17900 (set-window-configuration
17901 (prog1 org-window-configuration
17902 (kill-buffer (current-buffer))))
17903 (org-install-agenda-files-menu)
17904 (message "New agenda file list installed"))
17905 nil 'local)
17906 (message "%s" (substitute-command-keys
17907 "Edit list and finish with \\[save-buffer]")))
17908 (customize-variable 'org-agenda-files)))
17910 (defun org-store-new-agenda-file-list (list)
17911 "Set new value for the agenda file list and save it correctly."
17912 (if (stringp org-agenda-files)
17913 (let ((fe (org-read-agenda-file-list t)) b u)
17914 (while (setq b (find-buffer-visiting org-agenda-files))
17915 (kill-buffer b))
17916 (with-temp-file org-agenda-files
17917 (insert
17918 (mapconcat
17919 (lambda (f) ;; Keep un-expanded entries.
17920 (if (setq u (assoc f fe))
17921 (cdr u)
17923 list "\n")
17924 "\n")))
17925 (let ((org-mode-hook nil) (org-inhibit-startup t)
17926 (org-insert-mode-line-in-empty-file nil))
17927 (setq org-agenda-files list)
17928 (customize-save-variable 'org-agenda-files org-agenda-files))))
17930 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17931 "Read the list of agenda files from a file.
17932 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17933 filenames, used by `org-store-new-agenda-file-list' to write back
17934 un-expanded file names."
17935 (when (file-directory-p org-agenda-files)
17936 (error "`org-agenda-files' cannot be a single directory"))
17937 (when (stringp org-agenda-files)
17938 (with-temp-buffer
17939 (insert-file-contents org-agenda-files)
17940 (mapcar
17941 (lambda (f)
17942 (let ((e (expand-file-name (substitute-in-file-name f)
17943 org-directory)))
17944 (if pair-with-expansion
17945 (cons e f)
17946 e)))
17947 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17949 ;;;###autoload
17950 (defun org-cycle-agenda-files ()
17951 "Cycle through the files in `org-agenda-files'.
17952 If the current buffer visits an agenda file, find the next one in the list.
17953 If the current buffer does not, find the first agenda file."
17954 (interactive)
17955 (let* ((fs (org-agenda-files t))
17956 (files (append fs (list (car fs))))
17957 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17958 file)
17959 (unless files (user-error "No agenda files"))
17960 (catch 'exit
17961 (while (setq file (pop files))
17962 (if (equal (file-truename file) tcf)
17963 (when (car files)
17964 (find-file (car files))
17965 (throw 'exit t))))
17966 (find-file (car fs)))
17967 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17969 (defun org-agenda-file-to-front (&optional to-end)
17970 "Move/add the current file to the top of the agenda file list.
17971 If the file is not present in the list, it is added to the front. If it is
17972 present, it is moved there. With optional argument TO-END, add/move to the
17973 end of the list."
17974 (interactive "P")
17975 (let ((org-agenda-skip-unavailable-files nil)
17976 (file-alist (mapcar (lambda (x)
17977 (cons (file-truename x) x))
17978 (org-agenda-files t)))
17979 (ctf (file-truename
17980 (or buffer-file-name
17981 (user-error "Please save the current buffer to a file"))))
17982 x had)
17983 (setq x (assoc ctf file-alist) had x)
17985 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17986 (if to-end
17987 (setq file-alist (append (delq x file-alist) (list x)))
17988 (setq file-alist (cons x (delq x file-alist))))
17989 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17990 (org-install-agenda-files-menu)
17991 (message "File %s to %s of agenda file list"
17992 (if had "moved" "added") (if to-end "end" "front"))))
17994 (defun org-remove-file (&optional file)
17995 "Remove current file from the list of files in variable `org-agenda-files'.
17996 These are the files which are being checked for agenda entries.
17997 Optional argument FILE means use this file instead of the current."
17998 (interactive)
17999 (let* ((org-agenda-skip-unavailable-files nil)
18000 (file (or file buffer-file-name
18001 (user-error "Current buffer does not visit a file")))
18002 (true-file (file-truename file))
18003 (afile (abbreviate-file-name file))
18004 (files (delq nil (mapcar
18005 (lambda (x)
18006 (if (equal true-file
18007 (file-truename x))
18008 nil x))
18009 (org-agenda-files t)))))
18010 (if (not (= (length files) (length (org-agenda-files t))))
18011 (progn
18012 (org-store-new-agenda-file-list files)
18013 (org-install-agenda-files-menu)
18014 (message "Removed file: %s" afile))
18015 (message "File was not in list: %s (not removed)" afile))))
18017 (defun org-file-menu-entry (file)
18018 (vector file (list 'find-file file) t))
18020 (defun org-check-agenda-file (file)
18021 "Make sure FILE exists. If not, ask user what to do."
18022 (when (not (file-exists-p file))
18023 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18024 (abbreviate-file-name file))
18025 (let ((r (downcase (read-char-exclusive))))
18026 (cond
18027 ((equal r ?r)
18028 (org-remove-file file)
18029 (throw 'nextfile t))
18030 (t (error "Abort"))))))
18032 (defun org-get-agenda-file-buffer (file)
18033 "Get a buffer visiting FILE. If the buffer needs to be created, add
18034 it to the list of buffers which might be released later."
18035 (let ((buf (org-find-base-buffer-visiting file)))
18036 (if buf
18037 buf ; just return it
18038 ;; Make a new buffer and remember it
18039 (setq buf (find-file-noselect file))
18040 (if buf (push buf org-agenda-new-buffers))
18041 buf)))
18043 (defun org-release-buffers (blist)
18044 "Release all buffers in list, asking the user for confirmation when needed.
18045 When a buffer is unmodified, it is just killed. When modified, it is saved
18046 \(if the user agrees) and then killed."
18047 (let (buf file)
18048 (while (setq buf (pop blist))
18049 (setq file (buffer-file-name buf))
18050 (when (and (buffer-modified-p buf)
18051 file
18052 (y-or-n-p (format "Save file %s? " file)))
18053 (with-current-buffer buf (save-buffer)))
18054 (kill-buffer buf))))
18056 (defun org-agenda-prepare-buffers (files)
18057 "Create buffers for all agenda files, protect archived trees and comments."
18058 (interactive)
18059 (let ((pa '(:org-archived t))
18060 (pc '(:org-comment t))
18061 (pall '(:org-archived t :org-comment t))
18062 (inhibit-read-only t)
18063 (org-inhibit-startup org-agenda-inhibit-startup)
18064 (rea (concat ":" org-archive-tag ":"))
18065 file re pos)
18066 (setq org-tag-alist-for-agenda nil
18067 org-tag-groups-alist-for-agenda nil)
18068 (save-window-excursion
18069 (save-restriction
18070 (while (setq file (pop files))
18071 (catch 'nextfile
18072 (if (bufferp file)
18073 (set-buffer file)
18074 (org-check-agenda-file file)
18075 (set-buffer (org-get-agenda-file-buffer file)))
18076 (widen)
18077 (org-set-regexps-and-options-for-tags)
18078 (setq pos (point))
18079 (goto-char (point-min))
18080 (let ((case-fold-search t))
18081 (when (search-forward "#+setupfile" nil t)
18082 ;; Don't set all regexps and options systematically as
18083 ;; this is only run for setting agenda tags from setup
18084 ;; file
18085 (org-set-regexps-and-options)))
18086 (or (memq 'category org-agenda-ignore-drawer-properties)
18087 (org-refresh-category-properties))
18088 (or (memq 'effort org-agenda-ignore-drawer-properties)
18089 (org-refresh-properties org-effort-property 'org-effort))
18090 (or (memq 'appt org-agenda-ignore-drawer-properties)
18091 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18092 (setq org-todo-keywords-for-agenda
18093 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18094 (setq org-done-keywords-for-agenda
18095 (append org-done-keywords-for-agenda org-done-keywords))
18096 (setq org-todo-keyword-alist-for-agenda
18097 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18098 (setq org-drawers-for-agenda
18099 (append org-drawers-for-agenda org-drawers))
18100 (setq org-tag-alist-for-agenda
18101 (org-uniquify
18102 (append org-tag-alist-for-agenda
18103 org-tag-alist
18104 org-tag-persistent-alist)))
18105 (if org-group-tags
18106 (setq org-tag-groups-alist-for-agenda
18107 (org-uniquify-alist
18108 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18109 (org-with-silent-modifications
18110 (save-excursion
18111 (remove-text-properties (point-min) (point-max) pall)
18112 (when org-agenda-skip-archived-trees
18113 (goto-char (point-min))
18114 (while (re-search-forward rea nil t)
18115 (if (org-at-heading-p t)
18116 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18117 (goto-char (point-min))
18118 (setq re (format org-heading-keyword-regexp-format
18119 org-comment-string))
18120 (while (re-search-forward re nil t)
18121 (add-text-properties
18122 (match-beginning 0) (org-end-of-subtree t) pc))))
18123 (goto-char pos)))))
18124 (setq org-todo-keywords-for-agenda
18125 (org-uniquify org-todo-keywords-for-agenda))
18126 (setq org-todo-keyword-alist-for-agenda
18127 (org-uniquify org-todo-keyword-alist-for-agenda))))
18130 ;;;; CDLaTeX minor mode
18132 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18133 "Keymap for the minor `org-cdlatex-mode'.")
18135 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18136 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18137 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18138 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18139 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18141 (defvar org-cdlatex-texmathp-advice-is-done nil
18142 "Flag remembering if we have applied the advice to texmathp already.")
18144 (define-minor-mode org-cdlatex-mode
18145 "Toggle the minor `org-cdlatex-mode'.
18146 This mode supports entering LaTeX environment and math in LaTeX fragments
18147 in Org-mode.
18148 \\{org-cdlatex-mode-map}"
18149 nil " OCDL" nil
18150 (when org-cdlatex-mode
18151 (require 'cdlatex)
18152 (run-hooks 'cdlatex-mode-hook)
18153 (cdlatex-compute-tables))
18154 (unless org-cdlatex-texmathp-advice-is-done
18155 (setq org-cdlatex-texmathp-advice-is-done t)
18156 (defadvice texmathp (around org-math-always-on activate)
18157 "Always return t in org-mode buffers.
18158 This is because we want to insert math symbols without dollars even outside
18159 the LaTeX math segments. If Orgmode thinks that point is actually inside
18160 an embedded LaTeX fragment, let texmathp do its job.
18161 \\[org-cdlatex-mode-map]"
18162 (interactive)
18163 (let (p)
18164 (cond
18165 ((not (derived-mode-p 'org-mode)) ad-do-it)
18166 ((eq this-command 'cdlatex-math-symbol)
18167 (setq ad-return-value t
18168 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18170 (let ((p (org-inside-LaTeX-fragment-p)))
18171 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18172 (setq ad-return-value t
18173 texmathp-why '("Org-mode embedded math" . 0))
18174 (if p ad-do-it)))))))))
18176 (defun turn-on-org-cdlatex ()
18177 "Unconditionally turn on `org-cdlatex-mode'."
18178 (org-cdlatex-mode 1))
18180 (defun org-try-cdlatex-tab ()
18181 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18182 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18183 - inside a LaTeX fragment, or
18184 - after the first word in a line, where an abbreviation expansion could
18185 insert a LaTeX environment."
18186 (when org-cdlatex-mode
18187 (cond
18188 ;; Before any word on the line: No expansion possible.
18189 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18190 ;; Just after first word on the line: Expand it. Make sure it
18191 ;; cannot happen on headlines, though.
18192 ((save-excursion
18193 (skip-chars-backward "a-zA-Z0-9*")
18194 (skip-chars-backward " \t")
18195 (and (bolp) (not (org-at-heading-p))))
18196 (cdlatex-tab) t)
18197 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18199 (defun org-cdlatex-underscore-caret (&optional arg)
18200 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18201 Revert to the normal definition outside of these fragments."
18202 (interactive "P")
18203 (if (org-inside-LaTeX-fragment-p)
18204 (call-interactively 'cdlatex-sub-superscript)
18205 (let (org-cdlatex-mode)
18206 (call-interactively (key-binding (vector last-input-event))))))
18208 (defun org-cdlatex-math-modify (&optional arg)
18209 "Execute `cdlatex-math-modify' in LaTeX fragments.
18210 Revert to the normal definition outside of these fragments."
18211 (interactive "P")
18212 (if (org-inside-LaTeX-fragment-p)
18213 (call-interactively 'cdlatex-math-modify)
18214 (let (org-cdlatex-mode)
18215 (call-interactively (key-binding (vector last-input-event))))))
18219 ;;;; LaTeX fragments
18221 (defvar org-latex-regexps
18222 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18223 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18224 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18225 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18226 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18227 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18228 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18229 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18230 "Regular expressions for matching embedded LaTeX.")
18232 (defun org-inside-LaTeX-fragment-p ()
18233 "Test if point is inside a LaTeX fragment.
18234 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18235 sequence appearing also before point.
18236 Even though the matchers for math are configurable, this function assumes
18237 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18238 delimiters are skipped when they have been removed by customization.
18239 The return value is nil, or a cons cell with the delimiter and the
18240 position of this delimiter.
18242 This function does a reasonably good job, but can locally be fooled by
18243 for example currency specifications. For example it will assume being in
18244 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18245 fragments that are properly closed, but during editing, we have to live
18246 with the uncertainty caused by missing closing delimiters. This function
18247 looks only before point, not after."
18248 (catch 'exit
18249 (let ((pos (point))
18250 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18251 (lim (progn
18252 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18253 (point)))
18254 dd-on str (start 0) m re)
18255 (goto-char pos)
18256 (when dodollar
18257 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18258 re (nth 1 (assoc "$" org-latex-regexps)))
18259 (while (string-match re str start)
18260 (cond
18261 ((= (match-end 0) (length str))
18262 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18263 ((= (match-end 0) (- (length str) 5))
18264 (throw 'exit nil))
18265 (t (setq start (match-end 0))))))
18266 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18267 (goto-char pos)
18268 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18269 (and (match-beginning 2) (throw 'exit nil))
18270 ;; count $$
18271 (while (re-search-backward "\\$\\$" lim t)
18272 (setq dd-on (not dd-on)))
18273 (goto-char pos)
18274 (if dd-on (cons "$$" m))))))
18276 (defun org-inside-latex-macro-p ()
18277 "Is point inside a LaTeX macro or its arguments?"
18278 (save-match-data
18279 (org-in-regexp
18280 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18282 (defvar org-latex-fragment-image-overlays nil
18283 "List of overlays carrying the images of latex fragments.")
18284 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18286 (defun org-remove-latex-fragment-image-overlays ()
18287 "Remove all overlays with LaTeX fragment images in current buffer."
18288 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18289 (setq org-latex-fragment-image-overlays nil))
18291 (defun org-preview-latex-fragment (&optional subtree)
18292 "Preview the LaTeX fragment at point, or all locally or globally.
18293 If the cursor is in a LaTeX fragment, create the image and overlay
18294 it over the source code. If there is no fragment at point, display
18295 all fragments in the current text, from one headline to the next. With
18296 prefix SUBTREE, display all fragments in the current subtree. With a
18297 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18298 the cursor is before the first headline,
18299 display all fragments in the buffer.
18300 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18301 (interactive "P")
18302 (unless buffer-file-name
18303 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18304 (when (display-graphic-p)
18305 (org-remove-latex-fragment-image-overlays)
18306 (save-excursion
18307 (save-restriction
18308 (let (beg end at msg)
18309 (cond
18310 ((or (equal subtree '(16))
18311 (not (save-excursion
18312 (re-search-backward org-outline-regexp-bol nil t))))
18313 (setq beg (point-min) end (point-max)
18314 msg "Creating images for buffer...%s"))
18315 ((equal subtree '(4))
18316 (org-back-to-heading)
18317 (setq beg (point) end (org-end-of-subtree t)
18318 msg "Creating images for subtree...%s"))
18320 (if (setq at (org-inside-LaTeX-fragment-p))
18321 (goto-char (max (point-min) (- (cdr at) 2)))
18322 (org-back-to-heading))
18323 (setq beg (point) end (progn (outline-next-heading) (point))
18324 msg (if at "Creating image...%s"
18325 "Creating images for entry...%s"))))
18326 (message msg "")
18327 (narrow-to-region beg end)
18328 (goto-char beg)
18329 (org-format-latex
18330 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18331 (file-name-nondirectory
18332 buffer-file-name)))
18333 default-directory 'overlays msg at 'forbuffer
18334 org-latex-create-formula-image-program)
18335 (message msg "done. Use `C-c C-c' to remove images."))))))
18337 (defun org-format-latex (prefix &optional dir overlays msg at
18338 forbuffer processing-type)
18339 "Replace LaTeX fragments with links to an image, and produce images.
18340 Some of the options can be changed using the variable
18341 `org-format-latex-options'."
18342 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18343 (let* ((prefixnodir (file-name-nondirectory prefix))
18344 (absprefix (expand-file-name prefix dir))
18345 (todir (file-name-directory absprefix))
18346 (opt org-format-latex-options)
18347 (optnew org-format-latex-options)
18348 (matchers (plist-get opt :matchers))
18349 (re-list org-latex-regexps)
18350 (cnt 0) txt hash link beg end re e checkdir
18351 string
18352 m n block-type block linkfile movefile ov)
18353 ;; Check the different regular expressions
18354 (while (setq e (pop re-list))
18355 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18356 block (if block-type "\n\n" ""))
18357 (when (member m matchers)
18358 (goto-char (point-min))
18359 (while (re-search-forward re nil t)
18360 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18361 (or (not overlays)
18362 (not (eq (get-char-property (match-beginning n)
18363 'org-overlay-type)
18364 'org-latex-overlay))))
18365 (cond
18366 ((eq processing-type 'verbatim))
18367 ((eq processing-type 'mathjax)
18368 ;; Prepare for MathJax processing.
18369 (setq string (match-string n))
18370 (when (member m '("$" "$1"))
18371 (save-excursion
18372 (delete-region (match-beginning n) (match-end n))
18373 (goto-char (match-beginning n))
18374 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18375 ((or (eq processing-type 'dvipng)
18376 (eq processing-type 'imagemagick))
18377 ;; Process to an image.
18378 (setq txt (match-string n)
18379 beg (match-beginning n) end (match-end n)
18380 cnt (1+ cnt))
18381 (let ((face (face-at-point))
18382 (fg (plist-get opt :foreground))
18383 (bg (plist-get opt :background))
18384 ;; Ensure full list is printed.
18385 print-length print-level)
18386 (when forbuffer
18387 ;; Get the colors from the face at point.
18388 (goto-char beg)
18389 (when (eq fg 'auto)
18390 (setq fg (face-attribute face :foreground nil 'default)))
18391 (when (eq bg 'auto)
18392 (setq bg (face-attribute face :background nil 'default)))
18393 (setq optnew (copy-sequence opt))
18394 (plist-put optnew :foreground fg)
18395 (plist-put optnew :background bg))
18396 (setq hash (sha1 (prin1-to-string
18397 (list org-format-latex-header
18398 org-latex-default-packages-alist
18399 org-latex-packages-alist
18400 org-format-latex-options
18401 forbuffer txt fg bg)))
18402 linkfile (format "%s_%s.png" prefix hash)
18403 movefile (format "%s_%s.png" absprefix hash)))
18404 (setq link (concat block "[[file:" linkfile "]]" block))
18405 (if msg (message msg cnt))
18406 (goto-char beg)
18407 (unless checkdir ; Ensure the directory exists.
18408 (setq checkdir t)
18409 (or (file-directory-p todir) (make-directory todir t)))
18410 (unless (file-exists-p movefile)
18411 (org-create-formula-image
18412 txt movefile optnew forbuffer processing-type))
18413 (if overlays
18414 (progn
18415 (mapc (lambda (o)
18416 (if (eq (overlay-get o 'org-overlay-type)
18417 'org-latex-overlay)
18418 (delete-overlay o)))
18419 (overlays-in beg end))
18420 (setq ov (make-overlay beg end))
18421 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18422 (if (featurep 'xemacs)
18423 (progn
18424 (overlay-put ov 'invisible t)
18425 (overlay-put
18426 ov 'end-glyph
18427 (make-glyph (vector 'png :file movefile))))
18428 (overlay-put
18429 ov 'display
18430 (list 'image :type 'png :file movefile :ascent 'center)))
18431 (push ov org-latex-fragment-image-overlays)
18432 (goto-char end))
18433 (delete-region beg end)
18434 (insert (org-add-props link
18435 (list 'org-latex-src
18436 (replace-regexp-in-string
18437 "\"" "" txt)
18438 'org-latex-src-embed-type
18439 (if block-type 'paragraph 'character))))))
18440 ((eq processing-type 'mathml)
18441 ;; Process to MathML
18442 (unless (save-match-data (org-format-latex-mathml-available-p))
18443 (user-error "LaTeX to MathML converter not configured"))
18444 (setq txt (match-string n)
18445 beg (match-beginning n) end (match-end n)
18446 cnt (1+ cnt))
18447 (if msg (message msg cnt))
18448 (goto-char beg)
18449 (delete-region beg end)
18450 (insert (org-format-latex-as-mathml
18451 txt block-type prefix dir)))
18453 (error "Unknown conversion type %s for LaTeX fragments"
18454 processing-type)))))))))
18456 (defun org-create-math-formula (latex-frag &optional mathml-file)
18457 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18458 Use `org-latex-to-mathml-convert-command'. If the conversion is
18459 sucessful, return the portion between \"<math...> </math>\"
18460 elements otherwise return nil. When MATHML-FILE is specified,
18461 write the results in to that file. When invoked as an
18462 interactive command, prompt for LATEX-FRAG, with initial value
18463 set to the current active region and echo the results for user
18464 inspection."
18465 (interactive (list (let ((frag (when (org-region-active-p)
18466 (buffer-substring-no-properties
18467 (region-beginning) (region-end)))))
18468 (read-string "LaTeX Fragment: " frag nil frag))))
18469 (unless latex-frag (error "Invalid LaTeX fragment"))
18470 (let* ((tmp-in-file (file-relative-name
18471 (make-temp-name (expand-file-name "ltxmathml-in"))))
18472 (ignore (write-region latex-frag nil tmp-in-file))
18473 (tmp-out-file (file-relative-name
18474 (make-temp-name (expand-file-name "ltxmathml-out"))))
18475 (cmd (format-spec
18476 org-latex-to-mathml-convert-command
18477 `((?j . ,(shell-quote-argument
18478 (expand-file-name org-latex-to-mathml-jar-file)))
18479 (?I . ,(shell-quote-argument tmp-in-file))
18480 (?o . ,(shell-quote-argument tmp-out-file)))))
18481 mathml shell-command-output)
18482 (when (org-called-interactively-p 'any)
18483 (unless (org-format-latex-mathml-available-p)
18484 (user-error "LaTeX to MathML converter not configured")))
18485 (message "Running %s" cmd)
18486 (setq shell-command-output (shell-command-to-string cmd))
18487 (setq mathml
18488 (when (file-readable-p tmp-out-file)
18489 (with-current-buffer (find-file-noselect tmp-out-file t)
18490 (goto-char (point-min))
18491 (when (re-search-forward
18492 (concat
18493 (regexp-quote
18494 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18495 "\\(.\\|\n\\)*"
18496 (regexp-quote "</math>")) nil t)
18497 (prog1 (match-string 0) (kill-buffer))))))
18498 (cond
18499 (mathml
18500 (setq mathml
18501 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18502 (when mathml-file
18503 (write-region mathml nil mathml-file))
18504 (when (org-called-interactively-p 'any)
18505 (message mathml)))
18506 ((message "LaTeX to MathML conversion failed")
18507 (message shell-command-output)))
18508 (delete-file tmp-in-file)
18509 (when (file-exists-p tmp-out-file)
18510 (delete-file tmp-out-file))
18511 mathml))
18513 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18514 prefix &optional dir)
18515 "Use `org-create-math-formula' but check local cache first."
18516 (let* ((absprefix (expand-file-name prefix dir))
18517 (print-length nil) (print-level nil)
18518 (formula-id (concat
18519 "formula-"
18520 (sha1
18521 (prin1-to-string
18522 (list latex-frag
18523 org-latex-to-mathml-convert-command)))))
18524 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18525 (formula-cache-dir (file-name-directory formula-cache)))
18527 (unless (file-directory-p formula-cache-dir)
18528 (make-directory formula-cache-dir t))
18530 (unless (file-exists-p formula-cache)
18531 (org-create-math-formula latex-frag formula-cache))
18533 (if (file-exists-p formula-cache)
18534 ;; Successful conversion. Return the link to MathML file.
18535 (org-add-props
18536 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18537 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18538 'org-latex-src-embed-type (if latex-frag-type
18539 'paragraph 'character)))
18540 ;; Failed conversion. Return the LaTeX fragment verbatim
18541 latex-frag)))
18543 (defun org-create-formula-image (string tofile options buffer &optional type)
18544 "Create an image from LaTeX source using dvipng or convert.
18545 This function calls either `org-create-formula-image-with-dvipng'
18546 or `org-create-formula-image-with-imagemagick' depending on the
18547 value of `org-latex-create-formula-image-program' or on the value
18548 of the optional TYPE variable.
18550 Note: ultimately these two function should be combined as they
18551 share a good deal of logic."
18552 (org-check-external-command
18553 "latex" "needed to convert LaTeX fragments to images")
18554 (funcall
18555 (case (or type org-latex-create-formula-image-program)
18556 ('dvipng
18557 (org-check-external-command
18558 "dvipng" "needed to convert LaTeX fragments to images")
18559 #'org-create-formula-image-with-dvipng)
18560 ('imagemagick
18561 (org-check-external-command
18562 "convert" "you need to install imagemagick")
18563 #'org-create-formula-image-with-imagemagick)
18564 (t (error
18565 "Invalid value of `org-latex-create-formula-image-program'")))
18566 string tofile options buffer))
18568 (declare-function org-export-get-backend "ox" (name))
18569 (declare-function org-export--get-global-options "ox" (&optional backend))
18570 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18571 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18572 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18573 (defun org-create-formula--latex-header ()
18574 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18575 (let ((info (org-combine-plists (org-export--get-global-options
18576 (org-export-get-backend 'latex))
18577 (org-export--get-inbuffer-options
18578 (org-export-get-backend 'latex)))))
18579 (org-latex-guess-babel-language
18580 (org-latex-guess-inputenc
18581 (org-splice-latex-header
18582 org-format-latex-header
18583 org-latex-default-packages-alist
18584 org-latex-packages-alist t
18585 (plist-get info :latex-header)))
18586 info)))
18588 ;; This function borrows from Ganesh Swami's latex2png.el
18589 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18590 "This calls dvipng."
18591 (require 'ox-latex)
18592 (let* ((tmpdir (if (featurep 'xemacs)
18593 (temp-directory)
18594 temporary-file-directory))
18595 (texfilebase (make-temp-name
18596 (expand-file-name "orgtex" tmpdir)))
18597 (texfile (concat texfilebase ".tex"))
18598 (dvifile (concat texfilebase ".dvi"))
18599 (pngfile (concat texfilebase ".png"))
18600 (fnh (if (featurep 'xemacs)
18601 (font-height (face-font 'default))
18602 (face-attribute 'default :height nil)))
18603 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18604 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18605 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18606 "Black"))
18607 (bg (or (plist-get options (if buffer :background :html-background))
18608 "Transparent")))
18609 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18610 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18611 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18612 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18613 (let ((latex-header (org-create-formula--latex-header)))
18614 (with-temp-file texfile
18615 (insert latex-header)
18616 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18617 (let ((dir default-directory))
18618 (condition-case nil
18619 (progn
18620 (cd tmpdir)
18621 (call-process "latex" nil nil nil texfile))
18622 (error nil))
18623 (cd dir))
18624 (if (not (file-exists-p dvifile))
18625 (progn (message "Failed to create dvi file from %s" texfile) nil)
18626 (condition-case nil
18627 (if (featurep 'xemacs)
18628 (call-process "dvipng" nil nil nil
18629 "-fg" fg "-bg" bg
18630 "-T" "tight"
18631 "-o" pngfile
18632 dvifile)
18633 (call-process "dvipng" nil nil nil
18634 "-fg" fg "-bg" bg
18635 "-D" dpi
18636 ;;"-x" scale "-y" scale
18637 "-T" "tight"
18638 "-o" pngfile
18639 dvifile))
18640 (error nil))
18641 (if (not (file-exists-p pngfile))
18642 (if org-format-latex-signal-error
18643 (error "Failed to create png file from %s" texfile)
18644 (message "Failed to create png file from %s" texfile)
18645 nil)
18646 ;; Use the requested file name and clean up
18647 (copy-file pngfile tofile 'replace)
18648 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18649 (if (file-exists-p (concat texfilebase e))
18650 (delete-file (concat texfilebase e))))
18651 pngfile))))
18653 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18654 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18655 "This calls convert, which is included into imagemagick."
18656 (require 'ox-latex)
18657 (let* ((tmpdir (if (featurep 'xemacs)
18658 (temp-directory)
18659 temporary-file-directory))
18660 (texfilebase (make-temp-name
18661 (expand-file-name "orgtex" tmpdir)))
18662 (texfile (concat texfilebase ".tex"))
18663 (pdffile (concat texfilebase ".pdf"))
18664 (pngfile (concat texfilebase ".png"))
18665 (fnh (if (featurep 'xemacs)
18666 (font-height (face-font 'default))
18667 (face-attribute 'default :height nil)))
18668 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18669 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18670 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18671 "black"))
18672 (bg (or (plist-get options (if buffer :background :html-background))
18673 "white")))
18674 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18675 (setq fg (org-latex-color-format fg)))
18676 (if (eq bg 'default) (setq bg (org-latex-color :background))
18677 (setq bg (org-latex-color-format
18678 (if (string= bg "Transparent") "white" bg))))
18679 (let ((latex-header (org-create-formula--latex-header)))
18680 (with-temp-file texfile
18681 (insert latex-header)
18682 (insert "\n\\begin{document}\n"
18683 "\\definecolor{fg}{rgb}{" fg "}\n"
18684 "\\definecolor{bg}{rgb}{" bg "}\n"
18685 "\n\\pagecolor{bg}\n"
18686 "\n{\\color{fg}\n"
18687 string
18688 "\n}\n"
18689 "\n\\end{document}\n")))
18690 (org-latex-compile texfile t)
18691 (if (not (file-exists-p pdffile))
18692 (progn (message "Failed to create pdf file from %s" texfile) nil)
18693 (condition-case nil
18694 (if (featurep 'xemacs)
18695 (call-process "convert" nil nil nil
18696 "-density" "96"
18697 "-trim"
18698 "-antialias"
18699 pdffile
18700 "-quality" "100"
18701 ;; "-sharpen" "0x1.0"
18702 pngfile)
18703 (call-process "convert" nil nil nil
18704 "-density" dpi
18705 "-trim"
18706 "-antialias"
18707 pdffile
18708 "-quality" "100"
18709 ;; "-sharpen" "0x1.0"
18710 pngfile))
18711 (error nil))
18712 (if (not (file-exists-p pngfile))
18713 (if org-format-latex-signal-error
18714 (error "Failed to create png file from %s" texfile)
18715 (message "Failed to create png file from %s" texfile)
18716 nil)
18717 ;; Use the requested file name and clean up
18718 (copy-file pngfile tofile 'replace)
18719 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18720 (if (file-exists-p (concat texfilebase e))
18721 (delete-file (concat texfilebase e))))
18722 pngfile))))
18724 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18725 "Fill a LaTeX header template TPL.
18726 In the template, the following place holders will be recognized:
18728 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18729 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18730 [PACKAGES] \\usepackage statements for PKG
18731 [NO-PACKAGES] do not include PKG
18732 [EXTRA] the string EXTRA
18733 [NO-EXTRA] do not include EXTRA
18735 For backward compatibility, if both the positive and the negative place
18736 holder is missing, the positive one (without the \"NO-\") will be
18737 assumed to be present at the end of the template.
18738 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18739 EXTRA is a string.
18740 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18741 (let (rpl (end ""))
18742 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18743 (setq rpl (if (or (match-end 1) (not def-pkg))
18744 "" (org-latex-packages-to-string def-pkg snippets-p t))
18745 tpl (replace-match rpl t t tpl))
18746 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18748 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18749 (setq rpl (if (or (match-end 1) (not pkg))
18750 "" (org-latex-packages-to-string pkg snippets-p t))
18751 tpl (replace-match rpl t t tpl))
18752 (if pkg (setq end
18753 (concat end "\n"
18754 (org-latex-packages-to-string pkg snippets-p)))))
18756 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18757 (setq rpl (if (or (match-end 1) (not extra))
18758 "" (concat extra "\n"))
18759 tpl (replace-match rpl t t tpl))
18760 (if (and extra (string-match "\\S-" extra))
18761 (setq end (concat end "\n" extra))))
18763 (if (string-match "\\S-" end)
18764 (concat tpl "\n" end)
18765 tpl)))
18767 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18768 "Turn an alist of packages into a string with the \\usepackage macros."
18769 (setq pkg (mapconcat (lambda(p)
18770 (cond
18771 ((stringp p) p)
18772 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18773 (format "%% Package %s omitted" (cadr p)))
18774 ((equal "" (car p))
18775 (format "\\usepackage{%s}" (cadr p)))
18777 (format "\\usepackage[%s]{%s}"
18778 (car p) (cadr p)))))
18780 "\n"))
18781 (if newline (concat pkg "\n") pkg))
18783 (defun org-dvipng-color (attr)
18784 "Return a RGB color specification for dvipng."
18785 (apply 'format "rgb %s %s %s"
18786 (mapcar 'org-normalize-color
18787 (if (featurep 'xemacs)
18788 (color-rgb-components
18789 (face-property 'default
18790 (cond ((eq attr :foreground) 'foreground)
18791 ((eq attr :background) 'background))))
18792 (color-values (face-attribute 'default attr nil))))))
18794 (defun org-dvipng-color-format (color-name)
18795 "Convert COLOR-NAME to a RGB color value for dvipng."
18796 (apply 'format "rgb %s %s %s"
18797 (mapcar 'org-normalize-color
18798 (color-values color-name))))
18800 (defun org-latex-color (attr)
18801 "Return a RGB color for the LaTeX color package."
18802 (apply 'format "%s,%s,%s"
18803 (mapcar 'org-normalize-color
18804 (if (featurep 'xemacs)
18805 (color-rgb-components
18806 (face-property 'default
18807 (cond ((eq attr :foreground) 'foreground)
18808 ((eq attr :background) 'background))))
18809 (color-values (face-attribute 'default attr nil))))))
18811 (defun org-latex-color-format (color-name)
18812 "Convert COLOR-NAME to a RGB color value."
18813 (apply 'format "%s,%s,%s"
18814 (mapcar 'org-normalize-color
18815 (color-values color-name))))
18817 (defun org-normalize-color (value)
18818 "Return string to be used as color value for an RGB component."
18819 (format "%g" (/ value 65535.0)))
18823 ;; Image display
18825 (defvar org-inline-image-overlays nil)
18826 (make-variable-buffer-local 'org-inline-image-overlays)
18828 (defun org-toggle-inline-images (&optional include-linked)
18829 "Toggle the display of inline images.
18830 INCLUDE-LINKED is passed to `org-display-inline-images'."
18831 (interactive "P")
18832 (if org-inline-image-overlays
18833 (progn
18834 (org-remove-inline-images)
18835 (message "Inline image display turned off"))
18836 (org-display-inline-images include-linked)
18837 (if (and (org-called-interactively-p)
18838 org-inline-image-overlays)
18839 (message "%d images displayed inline"
18840 (length org-inline-image-overlays))
18841 (message "No images to display inline"))))
18843 (defun org-redisplay-inline-images ()
18844 "Refresh the display of inline images."
18845 (interactive)
18846 (if (not org-inline-image-overlays)
18847 (org-toggle-inline-images)
18848 (org-toggle-inline-images)
18849 (org-toggle-inline-images)))
18851 (defun org-display-inline-images (&optional include-linked refresh beg end)
18852 "Display inline images.
18853 Normally only links without a description part are inlined, because this
18854 is how it will work for export. When INCLUDE-LINKED is set, also links
18855 with a description part will be inlined. This can be nice for a quick
18856 look at those images, but it does not reflect what exported files will look
18857 like.
18858 When REFRESH is set, refresh existing images between BEG and END.
18859 This will create new image displays only if necessary.
18860 BEG and END default to the buffer boundaries."
18861 (interactive "P")
18862 (when (display-graphic-p)
18863 (unless refresh
18864 (org-remove-inline-images)
18865 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18866 (save-excursion
18867 (save-restriction
18868 (widen)
18869 (setq beg (or beg (point-min)) end (or end (point-max)))
18870 (goto-char beg)
18871 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18872 (substring (org-image-file-name-regexp) 0 -2)
18873 "\\)\\]" (if include-linked "" "\\]")))
18874 (case-fold-search t)
18875 old file ov img type attrwidth width)
18876 (while (re-search-forward re end t)
18877 (setq old (get-char-property-and-overlay (match-beginning 1)
18878 'org-image-overlay)
18879 file (expand-file-name
18880 (concat (or (match-string 3) "") (match-string 4))))
18881 (when (image-type-available-p 'imagemagick)
18882 (setq attrwidth (if (or (listp org-image-actual-width)
18883 (null org-image-actual-width))
18884 (save-excursion
18885 (save-match-data
18886 (when (re-search-backward
18887 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18888 (save-excursion
18889 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18890 (string-to-number (match-string 1))))))
18891 width (cond ((eq org-image-actual-width t) nil)
18892 ((null org-image-actual-width) attrwidth)
18893 ((numberp org-image-actual-width)
18894 org-image-actual-width)
18895 ((listp org-image-actual-width)
18896 (or attrwidth (car org-image-actual-width))))
18897 type (if width 'imagemagick)))
18898 (when (file-exists-p file)
18899 (if (and (car-safe old) refresh)
18900 (image-refresh (overlay-get (cdr old) 'display))
18901 (setq img (save-match-data (create-image file type nil :width width)))
18902 (when img
18903 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18904 (overlay-put ov 'display img)
18905 (overlay-put ov 'face 'default)
18906 (overlay-put ov 'org-image-overlay t)
18907 (overlay-put ov 'modification-hooks
18908 (list 'org-display-inline-remove-overlay))
18909 (push ov org-inline-image-overlays))))))))))
18911 (define-obsolete-function-alias
18912 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18914 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18915 "Remove inline-display overlay if a corresponding region is modified."
18916 (let ((inhibit-modification-hooks t))
18917 (when (and ov after)
18918 (delete ov org-inline-image-overlays)
18919 (delete-overlay ov))))
18921 (defun org-remove-inline-images ()
18922 "Remove inline display of images."
18923 (interactive)
18924 (mapc 'delete-overlay org-inline-image-overlays)
18925 (setq org-inline-image-overlays nil))
18927 ;;;; Key bindings
18929 ;; Outline functions from `outline-mode-prefix-map'
18930 ;; that can be remapped in Org:
18931 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18932 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18933 (define-key org-mode-map [remap outline-forward-same-level]
18934 'org-forward-heading-same-level)
18935 (define-key org-mode-map [remap outline-backward-same-level]
18936 'org-backward-heading-same-level)
18937 (define-key org-mode-map [remap show-branches]
18938 'org-kill-note-or-show-branches)
18939 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18940 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18941 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18943 ;; Outline functions from `outline-mode-prefix-map' that can not
18944 ;; be remapped in Org:
18946 ;; - the column "key binding" shows whether the Outline function is still
18947 ;; available in Org mode on the same key that it has been bound to in
18948 ;; Outline mode:
18949 ;; - "overridden": key used for a different functionality in Org mode
18950 ;; - else: key still bound to the same Outline function in Org mode
18952 ;; | Outline function | key binding | Org replacement |
18953 ;; |------------------------------------+-------------+-----------------------|
18954 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18955 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18956 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18957 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18958 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18959 ;; | `show-entry' | overridden | no replacement |
18960 ;; | `show-children' | `C-c C-i' | visibility cycling |
18961 ;; | `show-branches' | `C-c C-k' | still same function |
18962 ;; | `show-subtree' | overridden | visibility cycling |
18963 ;; | `show-all' | overridden | no replacement |
18964 ;; | `hide-subtree' | overridden | visibility cycling |
18965 ;; | `hide-body' | overridden | no replacement |
18966 ;; | `hide-entry' | overridden | visibility cycling |
18967 ;; | `hide-leaves' | overridden | no replacement |
18968 ;; | `hide-sublevels' | overridden | no replacement |
18969 ;; | `hide-other' | overridden | no replacement |
18971 ;; Make `C-c C-x' a prefix key
18972 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18974 ;; TAB key with modifiers
18975 (org-defkey org-mode-map "\C-i" 'org-cycle)
18976 (org-defkey org-mode-map [(tab)] 'org-cycle)
18977 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18978 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18979 ;; The following line is necessary under Suse GNU/Linux
18980 (unless (featurep 'xemacs)
18981 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18982 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18983 (define-key org-mode-map [backtab] 'org-shifttab)
18985 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18986 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18987 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18989 ;; Cursor keys with modifiers
18990 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18991 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18992 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18993 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18995 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18996 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18997 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18998 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19000 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19001 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19002 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19003 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19005 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19006 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19007 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19008 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19010 ;; Babel keys
19011 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19012 (mapc (lambda (pair)
19013 (define-key org-babel-map (car pair) (cdr pair)))
19014 org-babel-key-bindings)
19016 ;;; Extra keys for tty access.
19017 ;; We only set them when really needed because otherwise the
19018 ;; menus don't show the simple keys
19020 (when (or org-use-extra-keys
19021 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19022 (not window-system))
19023 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19024 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19025 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19026 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19027 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19028 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19029 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19030 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19031 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19032 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19033 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19034 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19035 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19036 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19037 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19038 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19039 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19040 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19041 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19042 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19043 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19044 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19045 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19046 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19047 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19048 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19049 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19050 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19052 ;; All the other keys
19054 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19055 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19056 (if (boundp 'narrow-map)
19057 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19058 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19059 (if (boundp 'narrow-map)
19060 (org-defkey narrow-map "b" 'org-narrow-to-block)
19061 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19062 (if (boundp 'narrow-map)
19063 (org-defkey narrow-map "e" 'org-narrow-to-element)
19064 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19065 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19066 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19067 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19068 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19069 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19070 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19071 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19072 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19073 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19074 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19075 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19076 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19077 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19078 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19079 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19080 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19081 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19082 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19083 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19084 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19085 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19086 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19087 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19088 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19089 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19090 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19091 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19092 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19093 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19094 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19095 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19096 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19097 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19098 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19099 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19100 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19101 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19102 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19103 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19104 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19105 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19106 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19107 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19108 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19109 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19110 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19111 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19112 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19113 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19114 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19115 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19116 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19117 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19118 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19119 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19120 (org-defkey org-mode-map "\C-c^" 'org-sort)
19121 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19122 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19123 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19124 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19125 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19126 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19127 (org-defkey org-mode-map "\C-m" 'org-return)
19128 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19129 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19130 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19131 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19132 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19133 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19134 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19135 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19136 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19137 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19138 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19139 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19140 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19141 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19142 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19143 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19144 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19145 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19146 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19147 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19148 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19149 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19150 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19152 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19153 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19154 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19156 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19157 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19158 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19159 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19160 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19161 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19162 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19163 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19164 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19165 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19166 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19167 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19168 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19169 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19170 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19171 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19172 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19173 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19174 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19175 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19176 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19177 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19178 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19180 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19181 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19182 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19183 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19184 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19186 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19188 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19190 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19191 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19193 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19196 (when (featurep 'xemacs)
19197 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19200 (defconst org-speed-commands-default
19202 ("Outline Navigation")
19203 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19204 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19205 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19206 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19207 ("F" . org-next-block)
19208 ("B" . org-previous-block)
19209 ("u" . (org-speed-move-safe 'outline-up-heading))
19210 ("j" . org-goto)
19211 ("g" . (org-refile t))
19212 ("Outline Visibility")
19213 ("c" . org-cycle)
19214 ("C" . org-shifttab)
19215 (" " . org-display-outline-path)
19216 ("s" . org-narrow-to-subtree)
19217 ("=" . org-columns)
19218 ("Outline Structure Editing")
19219 ("U" . org-shiftmetaup)
19220 ("D" . org-shiftmetadown)
19221 ("r" . org-metaright)
19222 ("l" . org-metaleft)
19223 ("R" . org-shiftmetaright)
19224 ("L" . org-shiftmetaleft)
19225 ("i" . (progn (forward-char 1) (call-interactively
19226 'org-insert-heading-respect-content)))
19227 ("^" . org-sort)
19228 ("w" . org-refile)
19229 ("a" . org-archive-subtree-default-with-confirmation)
19230 ("@" . org-mark-subtree)
19231 ("#" . org-toggle-comment)
19232 ("Clock Commands")
19233 ("I" . org-clock-in)
19234 ("O" . org-clock-out)
19235 ("Meta Data Editing")
19236 ("t" . org-todo)
19237 ("," . (org-priority))
19238 ("0" . (org-priority ?\ ))
19239 ("1" . (org-priority ?A))
19240 ("2" . (org-priority ?B))
19241 ("3" . (org-priority ?C))
19242 (":" . org-set-tags-command)
19243 ("e" . org-set-effort)
19244 ("E" . org-inc-effort)
19245 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19246 (org-entry-put (point) "APPT_WARNTIME" m)))
19247 ("Agenda Views etc")
19248 ("v" . org-agenda)
19249 ("/" . org-sparse-tree)
19250 ("Misc")
19251 ("o" . org-open-at-point)
19252 ("?" . org-speed-command-help)
19253 ("<" . (org-agenda-set-restriction-lock 'subtree))
19254 (">" . (org-agenda-remove-restriction-lock))
19256 "The default speed commands.")
19258 (defun org-print-speed-command (e)
19259 (if (> (length (car e)) 1)
19260 (progn
19261 (princ "\n")
19262 (princ (car e))
19263 (princ "\n")
19264 (princ (make-string (length (car e)) ?-))
19265 (princ "\n"))
19266 (princ (car e))
19267 (princ " ")
19268 (if (symbolp (cdr e))
19269 (princ (symbol-name (cdr e)))
19270 (prin1 (cdr e)))
19271 (princ "\n")))
19273 (defun org-speed-command-help ()
19274 "Show the available speed commands."
19275 (interactive)
19276 (if (not org-use-speed-commands)
19277 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19278 (with-output-to-temp-buffer "*Help*"
19279 (princ "User-defined Speed commands\n===========================\n")
19280 (mapc 'org-print-speed-command org-speed-commands-user)
19281 (princ "\n")
19282 (princ "Built-in Speed commands\n=======================\n")
19283 (mapc 'org-print-speed-command org-speed-commands-default))
19284 (with-current-buffer "*Help*"
19285 (setq truncate-lines t))))
19287 (defun org-speed-move-safe (cmd)
19288 "Execute CMD, but make sure that the cursor always ends up in a headline.
19289 If not, return to the original position and throw an error."
19290 (interactive)
19291 (let ((pos (point)))
19292 (call-interactively cmd)
19293 (unless (and (bolp) (org-at-heading-p))
19294 (goto-char pos)
19295 (error "Boundary reached while executing %s" cmd))))
19297 (defvar org-self-insert-command-undo-counter 0)
19299 (defvar org-table-auto-blank-field) ; defined in org-table.el
19300 (defvar org-speed-command nil)
19302 (define-obsolete-function-alias
19303 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19305 (defun org-speed-command-activate (keys)
19306 "Hook for activating single-letter speed commands.
19307 `org-speed-commands-default' specifies a minimal command set.
19308 Use `org-speed-commands-user' for further customization."
19309 (when (or (and (bolp) (looking-at org-outline-regexp))
19310 (and (functionp org-use-speed-commands)
19311 (funcall org-use-speed-commands)))
19312 (cdr (assoc keys (append org-speed-commands-user
19313 org-speed-commands-default)))))
19315 (define-obsolete-function-alias
19316 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19318 (defun org-babel-speed-command-activate (keys)
19319 "Hook for activating single-letter code block commands."
19320 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19321 (cdr (assoc keys org-babel-key-bindings))))
19323 (defcustom org-speed-command-hook
19324 '(org-speed-command-default-hook org-babel-speed-command-hook)
19325 "Hook for activating speed commands at strategic locations.
19326 Hook functions are called in sequence until a valid handler is
19327 found.
19329 Each hook takes a single argument, a user-pressed command key
19330 which is also a `self-insert-command' from the global map.
19332 Within the hook, examine the cursor position and the command key
19333 and return nil or a valid handler as appropriate. Handler could
19334 be one of an interactive command, a function, or a form.
19336 Set `org-use-speed-commands' to non-nil value to enable this
19337 hook. The default setting is `org-speed-command-activate'."
19338 :group 'org-structure
19339 :version "24.1"
19340 :type 'hook)
19342 (defun org-self-insert-command (N)
19343 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19344 If the cursor is in a table looking at whitespace, the whitespace is
19345 overwritten, and the table is not marked as requiring realignment."
19346 (interactive "p")
19347 (org-check-before-invisible-edit 'insert)
19348 (cond
19349 ((and org-use-speed-commands
19350 (setq org-speed-command
19351 (run-hook-with-args-until-success
19352 'org-speed-command-hook (this-command-keys))))
19353 (cond
19354 ((commandp org-speed-command)
19355 (setq this-command org-speed-command)
19356 (call-interactively org-speed-command))
19357 ((functionp org-speed-command)
19358 (funcall org-speed-command))
19359 ((and org-speed-command (listp org-speed-command))
19360 (eval org-speed-command))
19361 (t (let (org-use-speed-commands)
19362 (call-interactively 'org-self-insert-command)))))
19363 ((and
19364 (org-table-p)
19365 (progn
19366 ;; check if we blank the field, and if that triggers align
19367 (and (featurep 'org-table) org-table-auto-blank-field
19368 (member last-command
19369 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19370 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19371 ;; got extra space, this field does not determine column width
19372 (let (org-table-may-need-update) (org-table-blank-field))
19373 ;; no extra space, this field may determine column width
19374 (org-table-blank-field)))
19376 (eq N 1)
19377 (looking-at "[^|\n]* |"))
19378 (let (org-table-may-need-update)
19379 (goto-char (1- (match-end 0)))
19380 (backward-delete-char 1)
19381 (goto-char (match-beginning 0))
19382 (self-insert-command N)))
19384 (setq org-table-may-need-update t)
19385 (self-insert-command N)
19386 (org-fix-tags-on-the-fly)
19387 (if org-self-insert-cluster-for-undo
19388 (if (not (eq last-command 'org-self-insert-command))
19389 (setq org-self-insert-command-undo-counter 1)
19390 (if (>= org-self-insert-command-undo-counter 20)
19391 (setq org-self-insert-command-undo-counter 1)
19392 (and (> org-self-insert-command-undo-counter 0)
19393 buffer-undo-list (listp buffer-undo-list)
19394 (not (cadr buffer-undo-list)) ; remove nil entry
19395 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19396 (setq org-self-insert-command-undo-counter
19397 (1+ org-self-insert-command-undo-counter))))))))
19399 (defun org-check-before-invisible-edit (kind)
19400 "Check is editing if kind KIND would be dangerous with invisible text around.
19401 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19402 ;; First, try to get out of here as quickly as possible, to reduce overhead
19403 (if (and org-catch-invisible-edits
19404 (or (not (boundp 'visible-mode)) (not visible-mode))
19405 (or (get-char-property (point) 'invisible)
19406 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19407 ;; OK, we need to take a closer look
19408 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19409 (invisible-before-point (if (bobp) nil (get-char-property
19410 (1- (point)) 'invisible)))
19411 (border-and-ok-direction
19413 ;; Check if we are acting predictably before invisible text
19414 (and invisible-at-point (not invisible-before-point)
19415 (memq kind '(insert delete-backward)))
19416 ;; Check if we are acting predictably after invisible text
19417 ;; This works not well, and I have turned it off. It seems
19418 ;; better to always show and stop after invisible text.
19419 ;; (and (not invisible-at-point) invisible-before-point
19420 ;; (memq kind '(insert delete)))
19422 (when (or (memq invisible-at-point '(outline org-hide-block t))
19423 (memq invisible-before-point '(outline org-hide-block t)))
19424 (if (eq org-catch-invisible-edits 'error)
19425 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19426 (if (and org-custom-properties-overlays
19427 (y-or-n-p "Display invisible properties in this buffer? "))
19428 (org-toggle-custom-properties-visibility)
19429 ;; Make the area visible
19430 (save-excursion
19431 (if invisible-before-point
19432 (goto-char (previous-single-char-property-change
19433 (point) 'invisible)))
19434 (org-cycle))
19435 (cond
19436 ((eq org-catch-invisible-edits 'show)
19437 ;; That's it, we do the edit after showing
19438 (message
19439 "Unfolding invisible region around point before editing")
19440 (sit-for 1))
19441 ((and (eq org-catch-invisible-edits 'smart)
19442 border-and-ok-direction)
19443 (message "Unfolding invisible region around point before editing"))
19445 ;; Don't do the edit, make the user repeat it in full visibility
19446 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19448 (defun org-fix-tags-on-the-fly ()
19449 (when (and (equal (char-after (point-at-bol)) ?*)
19450 (org-at-heading-p))
19451 (org-align-tags-here org-tags-column)))
19453 (defun org-delete-backward-char (N)
19454 "Like `delete-backward-char', insert whitespace at field end in tables.
19455 When deleting backwards, in tables this function will insert whitespace in
19456 front of the next \"|\" separator, to keep the table aligned. The table will
19457 still be marked for re-alignment if the field did fill the entire column,
19458 because, in this case the deletion might narrow the column."
19459 (interactive "p")
19460 (save-match-data
19461 (org-check-before-invisible-edit 'delete-backward)
19462 (if (and (org-table-p)
19463 (eq N 1)
19464 (string-match "|" (buffer-substring (point-at-bol) (point)))
19465 (looking-at ".*?|"))
19466 (let ((pos (point))
19467 (noalign (looking-at "[^|\n\r]* |"))
19468 (c org-table-may-need-update))
19469 (backward-delete-char N)
19470 (if (not overwrite-mode)
19471 (progn
19472 (skip-chars-forward "^|")
19473 (insert " ")
19474 (goto-char (1- pos))))
19475 ;; noalign: if there were two spaces at the end, this field
19476 ;; does not determine the width of the column.
19477 (if noalign (setq org-table-may-need-update c)))
19478 (backward-delete-char N)
19479 (org-fix-tags-on-the-fly))))
19481 (defun org-delete-char (N)
19482 "Like `delete-char', but insert whitespace at field end in tables.
19483 When deleting characters, in tables this function will insert whitespace in
19484 front of the next \"|\" separator, to keep the table aligned. The table will
19485 still be marked for re-alignment if the field did fill the entire column,
19486 because, in this case the deletion might narrow the column."
19487 (interactive "p")
19488 (save-match-data
19489 (org-check-before-invisible-edit 'delete)
19490 (if (and (org-table-p)
19491 (not (bolp))
19492 (not (= (char-after) ?|))
19493 (eq N 1))
19494 (if (looking-at ".*?|")
19495 (let ((pos (point))
19496 (noalign (looking-at "[^|\n\r]* |"))
19497 (c org-table-may-need-update))
19498 (replace-match
19499 (concat (substring (match-string 0) 1 -1) " |") nil t)
19500 (goto-char pos)
19501 ;; noalign: if there were two spaces at the end, this field
19502 ;; does not determine the width of the column.
19503 (if noalign (setq org-table-may-need-update c)))
19504 (delete-char N))
19505 (delete-char N)
19506 (org-fix-tags-on-the-fly))))
19508 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19509 (put 'org-self-insert-command 'delete-selection t)
19510 (put 'orgtbl-self-insert-command 'delete-selection t)
19511 (put 'org-delete-char 'delete-selection 'supersede)
19512 (put 'org-delete-backward-char 'delete-selection 'supersede)
19513 (put 'org-yank 'delete-selection 'yank)
19515 ;; Make `flyspell-mode' delay after some commands
19516 (put 'org-self-insert-command 'flyspell-delayed t)
19517 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19518 (put 'org-delete-char 'flyspell-delayed t)
19519 (put 'org-delete-backward-char 'flyspell-delayed t)
19521 ;; Make pabbrev-mode expand after org-mode commands
19522 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19523 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19525 ;; How to do this: Measure non-white length of current string
19526 ;; If equal to column width, we should realign.
19528 (defun org-remap (map &rest commands)
19529 "In MAP, remap the functions given in COMMANDS.
19530 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19531 (let (new old)
19532 (while commands
19533 (setq old (pop commands) new (pop commands))
19534 (if (fboundp 'command-remapping)
19535 (org-defkey map (vector 'remap old) new)
19536 (substitute-key-definition old new map global-map)))))
19538 (defun org-transpose-words ()
19539 "Transpose words for Org.
19540 This uses the `org-mode-transpose-word-syntax-table' syntax
19541 table, which interprets characters in `org-emphasis-alist' as
19542 word constituants."
19543 (interactive)
19544 (with-syntax-table org-mode-transpose-word-syntax-table
19545 (call-interactively 'transpose-words)))
19546 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19548 (when (eq org-enable-table-editor 'optimized)
19549 ;; If the user wants maximum table support, we need to hijack
19550 ;; some standard editing functions
19551 (org-remap org-mode-map
19552 'self-insert-command 'org-self-insert-command
19553 'delete-char 'org-delete-char
19554 'delete-backward-char 'org-delete-backward-char)
19555 (org-defkey org-mode-map "|" 'org-force-self-insert))
19557 (defvar org-ctrl-c-ctrl-c-hook nil
19558 "Hook for functions attaching themselves to `C-c C-c'.
19560 This can be used to add additional functionality to the C-c C-c
19561 key which executes context-dependent commands. This hook is run
19562 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19563 run after the last test.
19565 Each function will be called with no arguments. The function
19566 must check if the context is appropriate for it to act. If yes,
19567 it should do its thing and then return a non-nil value. If the
19568 context is wrong, just do nothing and return nil.")
19570 (defvar org-ctrl-c-ctrl-c-final-hook nil
19571 "Hook for functions attaching themselves to `C-c C-c'.
19573 This can be used to add additional functionality to the C-c C-c
19574 key which executes context-dependent commands. This hook is run
19575 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19576 before the first test.
19578 Each function will be called with no arguments. The function
19579 must check if the context is appropriate for it to act. If yes,
19580 it should do its thing and then return a non-nil value. If the
19581 context is wrong, just do nothing and return nil.")
19583 (defvar org-tab-first-hook nil
19584 "Hook for functions to attach themselves to TAB.
19585 See `org-ctrl-c-ctrl-c-hook' for more information.
19586 This hook runs as the first action when TAB is pressed, even before
19587 `org-cycle' messes around with the `outline-regexp' to cater for
19588 inline tasks and plain list item folding.
19589 If any function in this hook returns t, any other actions that
19590 would have been caused by TAB (such as table field motion or visibility
19591 cycling) will not occur.")
19593 (defvar org-tab-after-check-for-table-hook nil
19594 "Hook for functions to attach themselves to TAB.
19595 See `org-ctrl-c-ctrl-c-hook' for more information.
19596 This hook runs after it has been established that the cursor is not in a
19597 table, but before checking if the cursor is in a headline or if global cycling
19598 should be done.
19599 If any function in this hook returns t, not other actions like visibility
19600 cycling will be done.")
19602 (defvar org-tab-after-check-for-cycling-hook nil
19603 "Hook for functions to attach themselves to TAB.
19604 See `org-ctrl-c-ctrl-c-hook' for more information.
19605 This hook runs after it has been established that not table field motion and
19606 not visibility should be done because of current context. This is probably
19607 the place where a package like yasnippets can hook in.")
19609 (defvar org-tab-before-tab-emulation-hook nil
19610 "Hook for functions to attach themselves to TAB.
19611 See `org-ctrl-c-ctrl-c-hook' for more information.
19612 This hook runs after every other options for TAB have been exhausted, but
19613 before indentation and \t insertion takes place.")
19615 (defvar org-metaleft-hook nil
19616 "Hook for functions attaching themselves to `M-left'.
19617 See `org-ctrl-c-ctrl-c-hook' for more information.")
19618 (defvar org-metaright-hook nil
19619 "Hook for functions attaching themselves to `M-right'.
19620 See `org-ctrl-c-ctrl-c-hook' for more information.")
19621 (defvar org-metaup-hook nil
19622 "Hook for functions attaching themselves to `M-up'.
19623 See `org-ctrl-c-ctrl-c-hook' for more information.")
19624 (defvar org-metadown-hook nil
19625 "Hook for functions attaching themselves to `M-down'.
19626 See `org-ctrl-c-ctrl-c-hook' for more information.")
19627 (defvar org-shiftmetaleft-hook nil
19628 "Hook for functions attaching themselves to `M-S-left'.
19629 See `org-ctrl-c-ctrl-c-hook' for more information.")
19630 (defvar org-shiftmetaright-hook nil
19631 "Hook for functions attaching themselves to `M-S-right'.
19632 See `org-ctrl-c-ctrl-c-hook' for more information.")
19633 (defvar org-shiftmetaup-hook nil
19634 "Hook for functions attaching themselves to `M-S-up'.
19635 See `org-ctrl-c-ctrl-c-hook' for more information.")
19636 (defvar org-shiftmetadown-hook nil
19637 "Hook for functions attaching themselves to `M-S-down'.
19638 See `org-ctrl-c-ctrl-c-hook' for more information.")
19639 (defvar org-metareturn-hook nil
19640 "Hook for functions attaching themselves to `M-RET'.
19641 See `org-ctrl-c-ctrl-c-hook' for more information.")
19642 (defvar org-shiftup-hook nil
19643 "Hook for functions attaching themselves to `S-up'.
19644 See `org-ctrl-c-ctrl-c-hook' for more information.")
19645 (defvar org-shiftup-final-hook nil
19646 "Hook for functions attaching themselves to `S-up'.
19647 This one runs after all other options except shift-select have been excluded.
19648 See `org-ctrl-c-ctrl-c-hook' for more information.")
19649 (defvar org-shiftdown-hook nil
19650 "Hook for functions attaching themselves to `S-down'.
19651 See `org-ctrl-c-ctrl-c-hook' for more information.")
19652 (defvar org-shiftdown-final-hook nil
19653 "Hook for functions attaching themselves to `S-down'.
19654 This one runs after all other options except shift-select have been excluded.
19655 See `org-ctrl-c-ctrl-c-hook' for more information.")
19656 (defvar org-shiftleft-hook nil
19657 "Hook for functions attaching themselves to `S-left'.
19658 See `org-ctrl-c-ctrl-c-hook' for more information.")
19659 (defvar org-shiftleft-final-hook nil
19660 "Hook for functions attaching themselves to `S-left'.
19661 This one runs after all other options except shift-select have been excluded.
19662 See `org-ctrl-c-ctrl-c-hook' for more information.")
19663 (defvar org-shiftright-hook nil
19664 "Hook for functions attaching themselves to `S-right'.
19665 See `org-ctrl-c-ctrl-c-hook' for more information.")
19666 (defvar org-shiftright-final-hook nil
19667 "Hook for functions attaching themselves to `S-right'.
19668 This one runs after all other options except shift-select have been excluded.
19669 See `org-ctrl-c-ctrl-c-hook' for more information.")
19671 (defun org-modifier-cursor-error ()
19672 "Throw an error, a modified cursor command was applied in wrong context."
19673 (user-error "This command is active in special context like tables, headlines or items"))
19675 (defun org-shiftselect-error ()
19676 "Throw an error because Shift-Cursor command was applied in wrong context."
19677 (if (and (boundp 'shift-select-mode) shift-select-mode)
19678 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19679 (user-error "This command works only in special context like headlines or timestamps")))
19681 (defun org-call-for-shift-select (cmd)
19682 (let ((this-command-keys-shift-translated t))
19683 (call-interactively cmd)))
19685 (defun org-shifttab (&optional arg)
19686 "Global visibility cycling or move to previous table field.
19687 Call `org-table-previous-field' within a table.
19688 When ARG is nil, cycle globally through visibility states.
19689 When ARG is a numeric prefix, show contents of this level."
19690 (interactive "P")
19691 (cond
19692 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19693 ((integerp arg)
19694 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19695 (message "Content view to level: %d" arg)
19696 (org-content (prefix-numeric-value arg2))
19697 (org-cycle-show-empty-lines t)
19698 (setq org-cycle-global-status 'overview)))
19699 (t (call-interactively 'org-global-cycle))))
19701 (defun org-shiftmetaleft ()
19702 "Promote subtree or delete table column.
19703 Calls `org-promote-subtree', `org-outdent-item-tree', or
19704 `org-table-delete-column', depending on context. See the
19705 individual commands for more information."
19706 (interactive)
19707 (cond
19708 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19709 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19710 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19711 ((if (not (org-region-active-p)) (org-at-item-p)
19712 (save-excursion (goto-char (region-beginning))
19713 (org-at-item-p)))
19714 (call-interactively 'org-outdent-item-tree))
19715 (t (org-modifier-cursor-error))))
19717 (defun org-shiftmetaright ()
19718 "Demote subtree or insert table column.
19719 Calls `org-demote-subtree', `org-indent-item-tree', or
19720 `org-table-insert-column', depending on context. See the
19721 individual commands for more information."
19722 (interactive)
19723 (cond
19724 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19725 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19726 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19727 ((if (not (org-region-active-p)) (org-at-item-p)
19728 (save-excursion (goto-char (region-beginning))
19729 (org-at-item-p)))
19730 (call-interactively 'org-indent-item-tree))
19731 (t (org-modifier-cursor-error))))
19733 (defun org-shiftmetaup (&optional arg)
19734 "Move subtree up or kill table row.
19735 Calls `org-move-subtree-up' or `org-table-kill-row' or
19736 `org-move-item-up' or `org-timestamp-up', depending on context.
19737 See the individual commands for more information."
19738 (interactive "P")
19739 (cond
19740 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19741 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19742 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19743 ((org-at-item-p) (call-interactively 'org-move-item-up))
19744 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19745 (call-interactively 'org-timestamp-up)))
19746 (t (call-interactively 'org-drag-line-backward))))
19748 (defun org-shiftmetadown (&optional arg)
19749 "Move subtree down or insert table row.
19750 Calls `org-move-subtree-down' or `org-table-insert-row' or
19751 `org-move-item-down' or `org-timestamp-up', depending on context.
19752 See the individual commands for more information."
19753 (interactive "P")
19754 (cond
19755 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19756 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19757 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19758 ((org-at-item-p) (call-interactively 'org-move-item-down))
19759 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19760 (call-interactively 'org-timestamp-down)))
19761 (t (call-interactively 'org-drag-line-forward))))
19763 (defsubst org-hidden-tree-error ()
19764 (user-error
19765 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19767 (defun org-metaleft (&optional arg)
19768 "Promote heading or move table column to left.
19769 Calls `org-do-promote' or `org-table-move-column', depending on context.
19770 With no specific context, calls the Emacs default `backward-word'.
19771 See the individual commands for more information."
19772 (interactive "P")
19773 (cond
19774 ((run-hook-with-args-until-success 'org-metaleft-hook))
19775 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19776 ((org-with-limited-levels
19777 (or (org-at-heading-p)
19778 (and (org-region-active-p)
19779 (save-excursion
19780 (goto-char (region-beginning))
19781 (org-at-heading-p)))))
19782 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19783 (call-interactively 'org-do-promote))
19784 ;; At an inline task.
19785 ((org-at-heading-p)
19786 (call-interactively 'org-inlinetask-promote))
19787 ((or (org-at-item-p)
19788 (and (org-region-active-p)
19789 (save-excursion
19790 (goto-char (region-beginning))
19791 (org-at-item-p))))
19792 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19793 (call-interactively 'org-outdent-item))
19794 (t (call-interactively 'backward-word))))
19796 (defun org-metaright (&optional arg)
19797 "Demote a subtree, a list item or move table column to right.
19798 In front of a drawer or a block keyword, indent it correctly.
19799 With no specific context, calls the Emacs default `forward-word'.
19800 See the individual commands for more information."
19801 (interactive "P")
19802 (cond
19803 ((run-hook-with-args-until-success 'org-metaright-hook))
19804 ((org-at-table-p) (call-interactively 'org-table-move-column))
19805 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19806 ((org-at-block-p) (call-interactively 'org-indent-block))
19807 ((org-with-limited-levels
19808 (or (org-at-heading-p)
19809 (and (org-region-active-p)
19810 (save-excursion
19811 (goto-char (region-beginning))
19812 (org-at-heading-p)))))
19813 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19814 (call-interactively 'org-do-demote))
19815 ;; At an inline task.
19816 ((org-at-heading-p)
19817 (call-interactively 'org-inlinetask-demote))
19818 ((or (org-at-item-p)
19819 (and (org-region-active-p)
19820 (save-excursion
19821 (goto-char (region-beginning))
19822 (org-at-item-p))))
19823 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19824 (call-interactively 'org-indent-item))
19825 (t (call-interactively 'forward-word))))
19827 (defun org-check-for-hidden (what)
19828 "Check if there are hidden headlines/items in the current visual line.
19829 WHAT can be either `headlines' or `items'. If the current line is
19830 an outline or item heading and it has a folded subtree below it,
19831 this function returns t, nil otherwise."
19832 (let ((re (cond
19833 ((eq what 'headlines) org-outline-regexp-bol)
19834 ((eq what 'items) (org-item-beginning-re))
19835 (t (error "This should not happen"))))
19836 beg end)
19837 (save-excursion
19838 (catch 'exit
19839 (unless (org-region-active-p)
19840 (setq beg (point-at-bol))
19841 (beginning-of-line 2)
19842 (while (and (not (eobp)) ;; this is like `next-line'
19843 (get-char-property (1- (point)) 'invisible))
19844 (beginning-of-line 2))
19845 (setq end (point))
19846 (goto-char beg)
19847 (goto-char (point-at-eol))
19848 (setq end (max end (point)))
19849 (while (re-search-forward re end t)
19850 (if (get-char-property (match-beginning 0) 'invisible)
19851 (throw 'exit t))))
19852 nil))))
19854 (defun org-metaup (&optional arg)
19855 "Move subtree up or move table row up.
19856 Calls `org-move-subtree-up' or `org-table-move-row' or
19857 `org-move-item-up', depending on context. See the individual commands
19858 for more information."
19859 (interactive "P")
19860 (cond
19861 ((run-hook-with-args-until-success 'org-metaup-hook))
19862 ((org-region-active-p)
19863 (let* ((a (min (region-beginning) (region-end)))
19864 (b (1- (max (region-beginning) (region-end))))
19865 (c (save-excursion (goto-char a)
19866 (move-beginning-of-line 0)))
19867 (d (save-excursion (goto-char a)
19868 (move-end-of-line 0) (point))))
19869 (transpose-regions a b c d)
19870 (goto-char c)))
19871 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19872 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19873 ((org-at-item-p) (call-interactively 'org-move-item-up))
19874 (t (org-drag-element-backward))))
19876 (defun org-metadown (&optional arg)
19877 "Move subtree down or move table row down.
19878 Calls `org-move-subtree-down' or `org-table-move-row' or
19879 `org-move-item-down', depending on context. See the individual
19880 commands for more information."
19881 (interactive "P")
19882 (cond
19883 ((run-hook-with-args-until-success 'org-metadown-hook))
19884 ((org-region-active-p)
19885 (let* ((a (min (region-beginning) (region-end)))
19886 (b (max (region-beginning) (region-end)))
19887 (c (save-excursion (goto-char b)
19888 (move-beginning-of-line 1)))
19889 (d (save-excursion (goto-char b)
19890 (move-end-of-line 1) (1+ (point)))))
19891 (transpose-regions a b c d)
19892 (goto-char d)))
19893 ((org-at-table-p) (call-interactively 'org-table-move-row))
19894 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19895 ((org-at-item-p) (call-interactively 'org-move-item-down))
19896 (t (org-drag-element-forward))))
19898 (defun org-shiftup (&optional arg)
19899 "Increase item in timestamp or increase priority of current headline.
19900 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19901 depending on context. See the individual commands for more information."
19902 (interactive "P")
19903 (cond
19904 ((run-hook-with-args-until-success 'org-shiftup-hook))
19905 ((and org-support-shift-select (org-region-active-p))
19906 (org-call-for-shift-select 'previous-line))
19907 ((org-at-timestamp-p t)
19908 (call-interactively (if org-edit-timestamp-down-means-later
19909 'org-timestamp-down 'org-timestamp-up)))
19910 ((and (not (eq org-support-shift-select 'always))
19911 org-enable-priority-commands
19912 (org-at-heading-p))
19913 (call-interactively 'org-priority-up))
19914 ((and (not org-support-shift-select) (org-at-item-p))
19915 (call-interactively 'org-previous-item))
19916 ((org-clocktable-try-shift 'up arg))
19917 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19918 (org-support-shift-select
19919 (org-call-for-shift-select 'previous-line))
19920 (t (org-shiftselect-error))))
19922 (defun org-shiftdown (&optional arg)
19923 "Decrease item in timestamp or decrease priority of current headline.
19924 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19925 depending on context. See the individual commands for more information."
19926 (interactive "P")
19927 (cond
19928 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19929 ((and org-support-shift-select (org-region-active-p))
19930 (org-call-for-shift-select 'next-line))
19931 ((org-at-timestamp-p t)
19932 (call-interactively (if org-edit-timestamp-down-means-later
19933 'org-timestamp-up 'org-timestamp-down)))
19934 ((and (not (eq org-support-shift-select 'always))
19935 org-enable-priority-commands
19936 (org-at-heading-p))
19937 (call-interactively 'org-priority-down))
19938 ((and (not org-support-shift-select) (org-at-item-p))
19939 (call-interactively 'org-next-item))
19940 ((org-clocktable-try-shift 'down arg))
19941 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19942 (org-support-shift-select
19943 (org-call-for-shift-select 'next-line))
19944 (t (org-shiftselect-error))))
19946 (defun org-shiftright (&optional arg)
19947 "Cycle the thing at point or in the current line, depending on context.
19948 Depending on context, this does one of the following:
19950 - switch a timestamp at point one day into the future
19951 - on a headline, switch to the next TODO keyword.
19952 - on an item, switch entire list to the next bullet type
19953 - on a property line, switch to the next allowed value
19954 - on a clocktable definition line, move time block into the future"
19955 (interactive "P")
19956 (cond
19957 ((run-hook-with-args-until-success 'org-shiftright-hook))
19958 ((and org-support-shift-select (org-region-active-p))
19959 (org-call-for-shift-select 'forward-char))
19960 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19961 ((and (not (eq org-support-shift-select 'always))
19962 (org-at-heading-p))
19963 (let ((org-inhibit-logging
19964 (not org-treat-S-cursor-todo-selection-as-state-change))
19965 (org-inhibit-blocking
19966 (not org-treat-S-cursor-todo-selection-as-state-change)))
19967 (org-call-with-arg 'org-todo 'right)))
19968 ((or (and org-support-shift-select
19969 (not (eq org-support-shift-select 'always))
19970 (org-at-item-bullet-p))
19971 (and (not org-support-shift-select) (org-at-item-p)))
19972 (org-call-with-arg 'org-cycle-list-bullet nil))
19973 ((and (not (eq org-support-shift-select 'always))
19974 (org-at-property-p))
19975 (call-interactively 'org-property-next-allowed-value))
19976 ((org-clocktable-try-shift 'right arg))
19977 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19978 (org-support-shift-select
19979 (org-call-for-shift-select 'forward-char))
19980 (t (org-shiftselect-error))))
19982 (defun org-shiftleft (&optional arg)
19983 "Cycle the thing at point or in the current line, depending on context.
19984 Depending on context, this does one of the following:
19986 - switch a timestamp at point one day into the past
19987 - on a headline, switch to the previous TODO keyword.
19988 - on an item, switch entire list to the previous bullet type
19989 - on a property line, switch to the previous allowed value
19990 - on a clocktable definition line, move time block into the past"
19991 (interactive "P")
19992 (cond
19993 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19994 ((and org-support-shift-select (org-region-active-p))
19995 (org-call-for-shift-select 'backward-char))
19996 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19997 ((and (not (eq org-support-shift-select 'always))
19998 (org-at-heading-p))
19999 (let ((org-inhibit-logging
20000 (not org-treat-S-cursor-todo-selection-as-state-change))
20001 (org-inhibit-blocking
20002 (not org-treat-S-cursor-todo-selection-as-state-change)))
20003 (org-call-with-arg 'org-todo 'left)))
20004 ((or (and org-support-shift-select
20005 (not (eq org-support-shift-select 'always))
20006 (org-at-item-bullet-p))
20007 (and (not org-support-shift-select) (org-at-item-p)))
20008 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20009 ((and (not (eq org-support-shift-select 'always))
20010 (org-at-property-p))
20011 (call-interactively 'org-property-previous-allowed-value))
20012 ((org-clocktable-try-shift 'left arg))
20013 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20014 (org-support-shift-select
20015 (org-call-for-shift-select 'backward-char))
20016 (t (org-shiftselect-error))))
20018 (defun org-shiftcontrolright ()
20019 "Switch to next TODO set."
20020 (interactive)
20021 (cond
20022 ((and org-support-shift-select (org-region-active-p))
20023 (org-call-for-shift-select 'forward-word))
20024 ((and (not (eq org-support-shift-select 'always))
20025 (org-at-heading-p))
20026 (org-call-with-arg 'org-todo 'nextset))
20027 (org-support-shift-select
20028 (org-call-for-shift-select 'forward-word))
20029 (t (org-shiftselect-error))))
20031 (defun org-shiftcontrolleft ()
20032 "Switch to previous TODO set."
20033 (interactive)
20034 (cond
20035 ((and org-support-shift-select (org-region-active-p))
20036 (org-call-for-shift-select 'backward-word))
20037 ((and (not (eq org-support-shift-select 'always))
20038 (org-at-heading-p))
20039 (org-call-with-arg 'org-todo 'previousset))
20040 (org-support-shift-select
20041 (org-call-for-shift-select 'backward-word))
20042 (t (org-shiftselect-error))))
20044 (defun org-shiftcontrolup (&optional n)
20045 "Change timestamps synchronously up in CLOCK log lines.
20046 Optional argument N tells to change by that many units."
20047 (interactive "P")
20048 (cond ((and (not org-support-shift-select)
20049 (org-at-clock-log-p)
20050 (org-at-timestamp-p t))
20051 (org-clock-timestamps-up n))
20052 (t (org-shiftselect-error))))
20054 (defun org-shiftcontroldown (&optional n)
20055 "Change timestamps synchronously down in CLOCK log lines.
20056 Optional argument N tells to change by that many units."
20057 (interactive "P")
20058 (cond ((and (not org-support-shift-select)
20059 (org-at-clock-log-p)
20060 (org-at-timestamp-p t))
20061 (org-clock-timestamps-down n))
20062 (t (org-shiftselect-error))))
20064 (defun org-ctrl-c-ret ()
20065 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20066 (interactive)
20067 (cond
20068 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20069 (t (call-interactively 'org-insert-heading))))
20071 (defun org-find-visible ()
20072 (let ((s (point)))
20073 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20074 (get-char-property s 'invisible)))
20076 (defun org-find-invisible ()
20077 (let ((s (point)))
20078 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20079 (not (get-char-property s 'invisible))))
20082 (defun org-copy-visible (beg end)
20083 "Copy the visible parts of the region."
20084 (interactive "r")
20085 (let (snippets s)
20086 (save-excursion
20087 (save-restriction
20088 (narrow-to-region beg end)
20089 (setq s (goto-char (point-min)))
20090 (while (not (= (point) (point-max)))
20091 (goto-char (org-find-invisible))
20092 (push (buffer-substring s (point)) snippets)
20093 (setq s (goto-char (org-find-visible))))))
20094 (kill-new (apply 'concat (nreverse snippets)))))
20096 (defun org-copy-special ()
20097 "Copy region in table or copy current subtree.
20098 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20099 See the individual commands for more information."
20100 (interactive)
20101 (call-interactively
20102 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20104 (defun org-cut-special ()
20105 "Cut region in table or cut current subtree.
20106 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20107 See the individual commands for more information."
20108 (interactive)
20109 (call-interactively
20110 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20112 (defun org-paste-special (arg)
20113 "Paste rectangular region into table, or past subtree relative to level.
20114 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20115 See the individual commands for more information."
20116 (interactive "P")
20117 (if (org-at-table-p)
20118 (org-table-paste-rectangle)
20119 (org-paste-subtree arg)))
20121 (defsubst org-in-fixed-width-region-p ()
20122 "Is point in a fixed-width region?"
20123 (save-match-data
20124 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20126 (defun org-edit-special (&optional arg)
20127 "Call a special editor for the element at point.
20128 When at a table, call the formula editor with `org-table-edit-formulas'.
20129 When in a source code block, call `org-edit-src-code'.
20130 When in a fixed-width region, call `org-edit-fixed-width-region'.
20131 When at an #+INCLUDE keyword, visit the included file.
20132 On a link, call `ffap' to visit the link at point.
20133 Otherwise, return a user error."
20134 (interactive "P")
20135 (let ((element (org-element-at-point)))
20136 (assert (not buffer-read-only) nil
20137 "Buffer is read-only: %s" (buffer-name))
20138 (case (org-element-type element)
20139 (src-block
20140 (if (not arg) (org-edit-src-code)
20141 (let* ((info (org-babel-get-src-block-info))
20142 (lang (nth 0 info))
20143 (params (nth 2 info))
20144 (session (cdr (assq :session params))))
20145 (if (not session) (org-edit-src-code)
20146 ;; At a src-block with a session and function called with
20147 ;; an ARG: switch to the buffer related to the inferior
20148 ;; process.
20149 (switch-to-buffer
20150 (funcall (intern (concat "org-babel-prep-session:" lang))
20151 session params))))))
20152 (keyword
20153 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20154 (find-file
20155 (org-remove-double-quotes
20156 (car (org-split-string (org-element-property :value element)))))
20157 (user-error "No special environment to edit here")))
20158 (table
20159 (if (eq (org-element-property :type element) 'table.el)
20160 (org-edit-src-code)
20161 (call-interactively 'org-table-edit-formulas)))
20162 ;; Only Org tables contain `table-row' type elements.
20163 (table-row (call-interactively 'org-table-edit-formulas))
20164 ((example-block export-block) (org-edit-src-code))
20165 (fixed-width (org-edit-fixed-width-region))
20166 (otherwise
20167 ;; No notable element at point. Though, we may be at a link,
20168 ;; which is an object. Thus, scan deeper.
20169 (if (eq (org-element-type (org-element-context element)) 'link)
20170 (call-interactively 'ffap)
20171 (user-error "No special environment to edit here"))))))
20173 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20174 (defun org-ctrl-c-ctrl-c (&optional arg)
20175 "Set tags in headline, or update according to changed information at point.
20177 This command does many different things, depending on context:
20179 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20180 this is what we do.
20182 - If the cursor is on a statistics cookie, update it.
20184 - If the cursor is in a headline, prompt for tags and insert them
20185 into the current line, aligned to `org-tags-column'. When called
20186 with prefix arg, realign all tags in the current buffer.
20188 - If the cursor is in one of the special #+KEYWORD lines, this
20189 triggers scanning the buffer for these lines and updating the
20190 information.
20192 - If the cursor is inside a table, realign the table. This command
20193 works even if the automatic table editor has been turned off.
20195 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20196 the entire table.
20198 - If the cursor is at a footnote reference or definition, jump to
20199 the corresponding definition or references, respectively.
20201 - If the cursor is a the beginning of a dynamic block, update it.
20203 - If the current buffer is a capture buffer, close note and file it.
20205 - If the cursor is on a <<<target>>>, update radio targets and
20206 corresponding links in this buffer.
20208 - If the cursor is on a numbered item in a plain list, renumber the
20209 ordered list.
20211 - If the cursor is on a checkbox, toggle it.
20213 - If the cursor is on a code block, evaluate it. The variable
20214 `org-confirm-babel-evaluate' can be used to control prompting
20215 before code block evaluation, by default every code block
20216 evaluation requires confirmation. Code block evaluation can be
20217 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20218 (interactive "P")
20219 (cond
20220 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20221 org-occur-highlights
20222 org-latex-fragment-image-overlays)
20223 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20224 (org-remove-occur-highlights)
20225 (org-remove-latex-fragment-image-overlays)
20226 (message "Temporary highlights/overlays removed from current buffer"))
20227 ((and (local-variable-p 'org-finish-function (current-buffer))
20228 (fboundp org-finish-function))
20229 (funcall org-finish-function))
20230 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20232 (let* ((context (org-element-context)) (type (org-element-type context)))
20233 ;; Test if point is within a blank line.
20234 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20235 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20236 (user-error "C-c C-c can do nothing useful at this location"))
20237 ;; When at a link, act according to the parent instead.
20238 (when (eq type 'link)
20239 (setq context (org-element-property :parent context))
20240 (setq type (org-element-type context)))
20241 ;; For convenience: at the first line of a paragraph on the
20242 ;; same line as an item, apply function on that item instead.
20243 (when (eq type 'paragraph)
20244 (let ((parent (org-element-property :parent context)))
20245 (when (and (eq (org-element-type parent) 'item)
20246 (= (point-at-bol) (org-element-property :begin parent)))
20247 (setq context parent type 'item))))
20248 ;; Act according to type of element or object at point.
20249 (case type
20250 (clock (org-clock-update-time-maybe))
20251 (dynamic-block
20252 (save-excursion
20253 (goto-char (org-element-property :post-affiliated context))
20254 (org-update-dblock)))
20255 (footnote-definition
20256 (goto-char (org-element-property :post-affiliated context))
20257 (call-interactively 'org-footnote-action))
20258 (footnote-reference (call-interactively 'org-footnote-action))
20259 ((headline inlinetask)
20260 (save-excursion (goto-char (org-element-property :begin context))
20261 (call-interactively 'org-set-tags)))
20262 (item
20263 ;; At an item: a double C-u set checkbox to "[-]"
20264 ;; unconditionally, whereas a single one will toggle its
20265 ;; presence. Without an universal argument, if the item
20266 ;; has a checkbox, toggle it. Otherwise repair the list.
20267 (let* ((box (org-element-property :checkbox context))
20268 (struct (org-element-property :structure context))
20269 (old-struct (copy-tree struct))
20270 (parents (org-list-parents-alist struct))
20271 (prevs (org-list-prevs-alist struct))
20272 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20273 (org-list-set-checkbox
20274 (org-element-property :begin context) struct
20275 (cond ((equal arg '(16)) "[-]")
20276 ((and (not box) (equal arg '(4))) "[ ]")
20277 ((or (not box) (equal arg '(4))) nil)
20278 ((eq box 'on) "[ ]")
20279 (t "[X]")))
20280 ;; Mimic `org-list-write-struct' but with grabbing
20281 ;; a return value from `org-list-struct-fix-box'.
20282 (org-list-struct-fix-ind struct parents 2)
20283 (org-list-struct-fix-item-end struct)
20284 (org-list-struct-fix-bul struct prevs)
20285 (org-list-struct-fix-ind struct parents)
20286 (let ((block-item
20287 (org-list-struct-fix-box struct parents prevs orderedp)))
20288 (if (and box (equal struct old-struct))
20289 (if (equal arg '(16))
20290 (message "Checkboxes already reset")
20291 (user-error "Cannot toggle this checkbox: %s"
20292 (if (eq box 'on)
20293 "all subitems checked"
20294 "unchecked subitems")))
20295 (org-list-struct-apply-struct struct old-struct)
20296 (org-update-checkbox-count-maybe))
20297 (when block-item
20298 (message "Checkboxes were removed due to empty box at line %d"
20299 (org-current-line block-item))))))
20300 (keyword
20301 (let ((org-inhibit-startup-visibility-stuff t)
20302 (org-startup-align-all-tables nil))
20303 (when (boundp 'org-table-coordinate-overlays)
20304 (mapc 'delete-overlay org-table-coordinate-overlays)
20305 (setq org-table-coordinate-overlays nil))
20306 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20307 (message "Local setup has been refreshed"))
20308 (plain-list
20309 ;; At a plain list, with a double C-u argument, set
20310 ;; checkboxes of each item to "[-]", whereas a single one
20311 ;; will toggle their presence according to the state of the
20312 ;; first item in the list. Without an argument, repair the
20313 ;; list.
20314 (let* ((begin (org-element-property :contents-begin context))
20315 (beginm (move-marker (make-marker) begin))
20316 (struct (org-element-property :structure context))
20317 (old-struct (copy-tree struct))
20318 (first-box (save-excursion
20319 (goto-char begin)
20320 (looking-at org-list-full-item-re)
20321 (match-string-no-properties 3)))
20322 (new-box (cond ((equal arg '(16)) "[-]")
20323 ((equal arg '(4)) (unless first-box "[ ]"))
20324 ((equal first-box "[X]") "[ ]")
20325 (t "[X]"))))
20326 (cond
20327 (arg
20328 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20329 (org-list-get-all-items
20330 begin struct (org-list-prevs-alist struct))))
20331 ((and first-box (eq (point) begin))
20332 ;; For convenience, when point is at bol on the first
20333 ;; item of the list and no argument is provided, simply
20334 ;; toggle checkbox of that item, if any.
20335 (org-list-set-checkbox begin struct new-box)))
20336 (org-list-write-struct
20337 struct (org-list-parents-alist struct) old-struct)
20338 (org-update-checkbox-count-maybe)
20339 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20340 ((property-drawer node-property)
20341 (call-interactively 'org-property-action))
20342 ((radio-target target)
20343 (call-interactively 'org-update-radio-target-regexp))
20344 (statistics-cookie
20345 (call-interactively 'org-update-statistics-cookies))
20346 ((table table-cell table-row)
20347 ;; At a table, recalculate every field and align it. Also
20348 ;; send the table if necessary. If the table has
20349 ;; a `table.el' type, just give up. At a table row or
20350 ;; cell, maybe recalculate line but always align table.
20351 (if (eq (org-element-property :type context) 'table.el)
20352 (message "Use C-c ' to edit table.el tables")
20353 (let ((org-enable-table-editor t))
20354 (if (or (eq type 'table)
20355 ;; Check if point is at a TBLFM line.
20356 (and (eq type 'table-row)
20357 (= (point) (org-element-property :end context))))
20358 (save-excursion
20359 (if (org-at-TBLFM-p)
20360 (progn (require 'org-table)
20361 (org-table-calc-current-TBLFM))
20362 (goto-char (org-element-property :contents-begin context))
20363 (org-call-with-arg 'org-table-recalculate (or arg t))
20364 (orgtbl-send-table 'maybe)))
20365 (org-table-maybe-eval-formula)
20366 (cond (arg (call-interactively 'org-table-recalculate))
20367 ((org-table-maybe-recalculate-line))
20368 (t (org-table-align)))))))
20369 (timestamp (org-timestamp-change 0 'day))
20370 (otherwise
20371 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20372 (user-error
20373 "C-c C-c can do nothing useful at this location")))))))))
20375 (defun org-mode-restart ()
20376 "Restart Org-mode, to scan again for special lines.
20377 Also updates the keyword regular expressions."
20378 (interactive)
20379 (org-mode)
20380 (message "Org-mode restarted"))
20382 (defun org-kill-note-or-show-branches ()
20383 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20384 (interactive)
20385 (if (not org-finish-function)
20386 (progn
20387 (hide-subtree)
20388 (call-interactively 'show-branches))
20389 (let ((org-note-abort t))
20390 (funcall org-finish-function))))
20392 (defun org-open-line (n)
20393 "Insert a new row in tables, call `open-line' elsewhere.
20394 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20395 (interactive "*p")
20396 (cond
20397 ((not org-special-ctrl-o)
20398 (open-line n))
20399 ((org-at-table-p)
20400 (org-table-insert-row))
20402 (open-line n))))
20404 (defun org-return (&optional indent)
20405 "Goto next table row or insert a newline.
20406 Calls `org-table-next-row' or `newline', depending on context.
20407 See the individual commands for more information."
20408 (interactive)
20409 (let (org-ts-what)
20410 (cond
20411 ((or (bobp) (org-in-src-block-p))
20412 (if indent (newline-and-indent) (newline)))
20413 ((org-at-table-p)
20414 (org-table-justify-field-maybe)
20415 (call-interactively 'org-table-next-row))
20416 ;; when `newline-and-indent' is called within a list, make sure
20417 ;; text moved stays inside the item.
20418 ((and (org-in-item-p) indent)
20419 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20420 (progn
20421 (save-match-data (newline))
20422 (org-indent-line-to (length (match-string 0))))
20423 (let ((ind (org-get-indentation)))
20424 (newline)
20425 (if (org-looking-back org-list-end-re)
20426 (org-indent-line)
20427 (org-indent-line-to ind)))))
20428 ((and org-return-follows-link
20429 (org-at-timestamp-p t)
20430 (not (eq org-ts-what 'after)))
20431 (org-follow-timestamp-link))
20432 ((and org-return-follows-link
20433 (let ((tprop (get-text-property (point) 'face)))
20434 (or (eq tprop 'org-link)
20435 (and (listp tprop) (memq 'org-link tprop)))))
20436 (call-interactively 'org-open-at-point))
20437 ((and (org-at-heading-p)
20438 (looking-at
20439 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20440 (org-show-entry)
20441 (end-of-line 1)
20442 (newline))
20443 (t (if indent (newline-and-indent) (newline))))))
20445 (defun org-return-indent ()
20446 "Goto next table row or insert a newline and indent.
20447 Calls `org-table-next-row' or `newline-and-indent', depending on
20448 context. See the individual commands for more information."
20449 (interactive)
20450 (org-return t))
20452 (defun org-ctrl-c-star ()
20453 "Compute table, or change heading status of lines.
20454 Calls `org-table-recalculate' or `org-toggle-heading',
20455 depending on context."
20456 (interactive)
20457 (cond
20458 ((org-at-table-p)
20459 (call-interactively 'org-table-recalculate))
20461 ;; Convert all lines in region to list items
20462 (call-interactively 'org-toggle-heading))))
20464 (defun org-ctrl-c-minus ()
20465 "Insert separator line in table or modify bullet status of line.
20466 Also turns a plain line or a region of lines into list items.
20467 Calls `org-table-insert-hline', `org-toggle-item', or
20468 `org-cycle-list-bullet', depending on context."
20469 (interactive)
20470 (cond
20471 ((org-at-table-p)
20472 (call-interactively 'org-table-insert-hline))
20473 ((org-region-active-p)
20474 (call-interactively 'org-toggle-item))
20475 ((org-in-item-p)
20476 (call-interactively 'org-cycle-list-bullet))
20478 (call-interactively 'org-toggle-item))))
20480 (defun org-toggle-item (arg)
20481 "Convert headings or normal lines to items, items to normal lines.
20482 If there is no active region, only the current line is considered.
20484 If the first non blank line in the region is a headline, convert
20485 all headlines to items, shifting text accordingly.
20487 If it is an item, convert all items to normal lines.
20489 If it is normal text, change region into a list of items.
20490 With a prefix argument ARG, change the region in a single item."
20491 (interactive "P")
20492 (let ((shift-text
20493 (function
20494 ;; Shift text in current section to IND, from point to END.
20495 ;; The function leaves point to END line.
20496 (lambda (ind end)
20497 (let ((min-i 1000) (end (copy-marker end)))
20498 ;; First determine the minimum indentation (MIN-I) of
20499 ;; the text.
20500 (save-excursion
20501 (catch 'exit
20502 (while (< (point) end)
20503 (let ((i (org-get-indentation)))
20504 (cond
20505 ;; Skip blank lines and inline tasks.
20506 ((looking-at "^[ \t]*$"))
20507 ((looking-at org-outline-regexp-bol))
20508 ;; We can't find less than 0 indentation.
20509 ((zerop i) (throw 'exit (setq min-i 0)))
20510 ((< i min-i) (setq min-i i))))
20511 (forward-line))))
20512 ;; Then indent each line so that a line indented to
20513 ;; MIN-I becomes indented to IND. Ignore blank lines
20514 ;; and inline tasks in the process.
20515 (let ((delta (- ind min-i)))
20516 (while (< (point) end)
20517 (unless (or (looking-at "^[ \t]*$")
20518 (looking-at org-outline-regexp-bol))
20519 (org-indent-line-to (+ (org-get-indentation) delta)))
20520 (forward-line)))))))
20521 (skip-blanks
20522 (function
20523 ;; Return beginning of first non-blank line, starting from
20524 ;; line at POS.
20525 (lambda (pos)
20526 (save-excursion
20527 (goto-char pos)
20528 (skip-chars-forward " \r\t\n")
20529 (point-at-bol)))))
20530 beg end)
20531 ;; Determine boundaries of changes.
20532 (if (org-region-active-p)
20533 (setq beg (funcall skip-blanks (region-beginning))
20534 end (copy-marker (region-end)))
20535 (setq beg (funcall skip-blanks (point-at-bol))
20536 end (copy-marker (point-at-eol))))
20537 ;; Depending on the starting line, choose an action on the text
20538 ;; between BEG and END.
20539 (org-with-limited-levels
20540 (save-excursion
20541 (goto-char beg)
20542 (cond
20543 ;; Case 1. Start at an item: de-itemize. Note that it only
20544 ;; happens when a region is active: `org-ctrl-c-minus'
20545 ;; would call `org-cycle-list-bullet' otherwise.
20546 ((org-at-item-p)
20547 (while (< (point) end)
20548 (when (org-at-item-p)
20549 (skip-chars-forward " \t")
20550 (delete-region (point) (match-end 0)))
20551 (forward-line)))
20552 ;; Case 2. Start at an heading: convert to items.
20553 ((org-at-heading-p)
20554 (let* ((bul (org-list-bullet-string "-"))
20555 (bul-len (length bul))
20556 ;; Indentation of the first heading. It should be
20557 ;; relative to the indentation of its parent, if any.
20558 (start-ind (save-excursion
20559 (cond
20560 ((not org-adapt-indentation) 0)
20561 ((not (outline-previous-heading)) 0)
20562 (t (length (match-string 0))))))
20563 ;; Level of first heading. Further headings will be
20564 ;; compared to it to determine hierarchy in the list.
20565 (ref-level (org-reduced-level (org-outline-level))))
20566 (while (< (point) end)
20567 (let* ((level (org-reduced-level (org-outline-level)))
20568 (delta (max 0 (- level ref-level))))
20569 ;; If current headline is less indented than the first
20570 ;; one, set it as reference, in order to preserve
20571 ;; subtrees.
20572 (when (< level ref-level) (setq ref-level level))
20573 (replace-match bul t t)
20574 (org-indent-line-to (+ start-ind (* delta bul-len)))
20575 ;; Ensure all text down to END (or SECTION-END) belongs
20576 ;; to the newly created item.
20577 (let ((section-end (save-excursion
20578 (or (outline-next-heading) (point)))))
20579 (forward-line)
20580 (funcall shift-text
20581 (+ start-ind (* (1+ delta) bul-len))
20582 (min end section-end)))))))
20583 ;; Case 3. Normal line with ARG: make the first line of region
20584 ;; an item, and shift indentation of others lines to
20585 ;; set them as item's body.
20586 (arg (let* ((bul (org-list-bullet-string "-"))
20587 (bul-len (length bul))
20588 (ref-ind (org-get-indentation)))
20589 (skip-chars-forward " \t")
20590 (insert bul)
20591 (forward-line)
20592 (while (< (point) end)
20593 ;; Ensure that lines less indented than first one
20594 ;; still get included in item body.
20595 (funcall shift-text
20596 (+ ref-ind bul-len)
20597 (min end (save-excursion (or (outline-next-heading)
20598 (point)))))
20599 (forward-line))))
20600 ;; Case 4. Normal line without ARG: turn each non-item line
20601 ;; into an item.
20603 (while (< (point) end)
20604 (unless (or (org-at-heading-p) (org-at-item-p))
20605 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20606 (replace-match
20607 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20608 (forward-line))))))))
20610 (defun org-toggle-heading (&optional nstars)
20611 "Convert headings to normal text, or items or text to headings.
20612 If there is no active region, only convert the current line.
20614 With a \\[universal-argument] prefix, convert the whole list at
20615 point into heading.
20617 In a region:
20619 - If the first non blank line is a headline, remove the stars
20620 from all headlines in the region.
20622 - If it is a normal line, turn each and every normal line (i.e.,
20623 not an heading or an item) in the region into headings. If you
20624 want to convert only the first line of this region, use one
20625 universal prefix argument.
20627 - If it is a plain list item, turn all plain list items into headings.
20629 When converting a line into a heading, the number of stars is chosen
20630 such that the lines become children of the current entry. However,
20631 when a numeric prefix argument is given, its value determines the
20632 number of stars to add."
20633 (interactive "P")
20634 (let ((skip-blanks
20635 (function
20636 ;; Return beginning of first non-blank line, starting from
20637 ;; line at POS.
20638 (lambda (pos)
20639 (save-excursion
20640 (goto-char pos)
20641 (while (org-at-comment-p) (forward-line))
20642 (skip-chars-forward " \r\t\n")
20643 (point-at-bol)))))
20644 beg end toggled)
20645 ;; Determine boundaries of changes. If a universal prefix has
20646 ;; been given, put the list in a region. If region ends at a bol,
20647 ;; do not consider the last line to be in the region.
20649 (when (and current-prefix-arg (org-at-item-p))
20650 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20651 (org-mark-element))
20653 (if (org-region-active-p)
20654 (setq beg (funcall skip-blanks (region-beginning))
20655 end (copy-marker (save-excursion
20656 (goto-char (region-end))
20657 (if (bolp) (point) (point-at-eol)))))
20658 (setq beg (funcall skip-blanks (point-at-bol))
20659 end (copy-marker (point-at-eol))))
20660 ;; Ensure inline tasks don't count as headings.
20661 (org-with-limited-levels
20662 (save-excursion
20663 (goto-char beg)
20664 (cond
20665 ;; Case 1. Started at an heading: de-star headings.
20666 ((org-at-heading-p)
20667 (while (< (point) end)
20668 (when (org-at-heading-p t)
20669 (looking-at org-outline-regexp) (replace-match "")
20670 (setq toggled t))
20671 (forward-line)))
20672 ;; Case 2. Started at an item: change items into headlines.
20673 ;; One star will be added by `org-list-to-subtree'.
20674 ((org-at-item-p)
20675 (let* ((stars (make-string
20676 ;; subtract the star that will be added again by
20677 ;; `org-list-to-subtree'
20678 (if (numberp nstars) (1- nstars)
20679 (or (org-current-level) 0))
20680 ?*))
20681 (add-stars
20682 (cond (nstars "") ; stars from prefix only
20683 ((equal stars "") "") ; before first heading
20684 (org-odd-levels-only "*") ; inside heading, odd
20685 (t "")))) ; inside heading, oddeven
20686 (while (< (point) end)
20687 (when (org-at-item-p)
20688 ;; Pay attention to cases when region ends before list.
20689 (let* ((struct (org-list-struct))
20690 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20691 (save-restriction
20692 (narrow-to-region (point) list-end)
20693 (insert
20694 (org-list-to-subtree
20695 (org-list-parse-list t)
20696 '(:istart (concat stars add-stars (funcall get-stars depth))
20697 :icount (concat stars add-stars (funcall get-stars depth)))))))
20698 (setq toggled t))
20699 (forward-line))))
20700 ;; Case 3. Started at normal text: make every line an heading,
20701 ;; skipping headlines and items.
20702 (t (let* ((stars
20703 (make-string
20704 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20705 (add-stars
20706 (cond (nstars "") ; stars from prefix only
20707 ((equal stars "") "*") ; before first heading
20708 (org-odd-levels-only "**") ; inside heading, odd
20709 (t "*"))) ; inside heading, oddeven
20710 (rpl (concat stars add-stars " "))
20711 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20712 (while (< (point) (if (equal nstars '(4)) lend end))
20713 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20714 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20715 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20716 (forward-line)))))))
20717 (unless toggled (message "Cannot toggle heading from here"))))
20719 (defun org-meta-return (&optional arg)
20720 "Insert a new heading or wrap a region in a table.
20721 Calls `org-insert-heading' or `org-table-wrap-region', depending
20722 on context. See the individual commands for more information."
20723 (interactive "P")
20724 (org-check-before-invisible-edit 'insert)
20725 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20726 (let* ((element (org-element-at-point))
20727 (type (org-element-type element)))
20728 (when (eq type 'table-row)
20729 (setq element (org-element-property :parent element))
20730 (setq type 'table))
20731 (if (and (eq type 'table)
20732 (eq (org-element-property :type element) 'org)
20733 (>= (point) (org-element-property :contents-begin element))
20734 (< (point) (org-element-property :contents-end element)))
20735 (call-interactively 'org-table-wrap-region)
20736 (call-interactively 'org-insert-heading)))))
20738 ;;; Menu entries
20740 (defsubst org-in-subtree-not-table-p ()
20741 "Are we in a subtree and not in a table?"
20742 (and (not (org-before-first-heading-p))
20743 (not (org-at-table-p))))
20745 ;; Define the Org-mode menus
20746 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20747 '("Tbl"
20748 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20749 ["Next Field" org-cycle (org-at-table-p)]
20750 ["Previous Field" org-shifttab (org-at-table-p)]
20751 ["Next Row" org-return (org-at-table-p)]
20752 "--"
20753 ["Blank Field" org-table-blank-field (org-at-table-p)]
20754 ["Edit Field" org-table-edit-field (org-at-table-p)]
20755 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20756 "--"
20757 ("Column"
20758 ["Move Column Left" org-metaleft (org-at-table-p)]
20759 ["Move Column Right" org-metaright (org-at-table-p)]
20760 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20761 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20762 ("Row"
20763 ["Move Row Up" org-metaup (org-at-table-p)]
20764 ["Move Row Down" org-metadown (org-at-table-p)]
20765 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20766 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20767 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20768 "--"
20769 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20770 ("Rectangle"
20771 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20772 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20773 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20774 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20775 "--"
20776 ("Calculate"
20777 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20778 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20779 ["Edit Formulas" org-edit-special (org-at-table-p)]
20780 "--"
20781 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20782 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20783 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20784 "--"
20785 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20786 "--"
20787 ["Sum Column/Rectangle" org-table-sum
20788 (or (org-at-table-p) (org-region-active-p))]
20789 ["Which Column?" org-table-current-column (org-at-table-p)])
20790 ["Debug Formulas"
20791 org-table-toggle-formula-debugger
20792 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20793 ["Show Col/Row Numbers"
20794 org-table-toggle-coordinate-overlays
20795 :style toggle
20796 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20797 "--"
20798 ["Create" org-table-create (and (not (org-at-table-p))
20799 org-enable-table-editor)]
20800 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20801 ["Import from File" org-table-import (not (org-at-table-p))]
20802 ["Export to File" org-table-export (org-at-table-p)]
20803 "--"
20804 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20806 (easy-menu-define org-org-menu org-mode-map "Org menu"
20807 '("Org"
20808 ("Show/Hide"
20809 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20810 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20811 ["Sparse Tree..." org-sparse-tree t]
20812 ["Reveal Context" org-reveal t]
20813 ["Show All" show-all t]
20814 "--"
20815 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20816 "--"
20817 ["New Heading" org-insert-heading t]
20818 ("Navigate Headings"
20819 ["Up" outline-up-heading t]
20820 ["Next" outline-next-visible-heading t]
20821 ["Previous" outline-previous-visible-heading t]
20822 ["Next Same Level" outline-forward-same-level t]
20823 ["Previous Same Level" outline-backward-same-level t]
20824 "--"
20825 ["Jump" org-goto t])
20826 ("Edit Structure"
20827 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20828 "--"
20829 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20830 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20831 "--"
20832 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20833 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20834 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20835 "--"
20836 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20837 "--"
20838 ["Copy visible text" org-copy-visible t]
20839 "--"
20840 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20841 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20842 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20843 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20844 "--"
20845 ["Sort Region/Children" org-sort t]
20846 "--"
20847 ["Convert to odd levels" org-convert-to-odd-levels t]
20848 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20849 ("Editing"
20850 ["Emphasis..." org-emphasize t]
20851 ["Edit Source Example" org-edit-special t]
20852 "--"
20853 ["Footnote new/jump" org-footnote-action t]
20854 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20855 ("Archive"
20856 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20857 "--"
20858 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20859 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20860 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20862 "--"
20863 ("Hyperlinks"
20864 ["Store Link (Global)" org-store-link t]
20865 ["Find existing link to here" org-occur-link-in-agenda-files t]
20866 ["Insert Link" org-insert-link t]
20867 ["Follow Link" org-open-at-point t]
20868 "--"
20869 ["Next link" org-next-link t]
20870 ["Previous link" org-previous-link t]
20871 "--"
20872 ["Descriptive Links"
20873 org-toggle-link-display
20874 :style radio
20875 :selected org-descriptive-links
20877 ["Literal Links"
20878 org-toggle-link-display
20879 :style radio
20880 :selected (not org-descriptive-links)])
20881 "--"
20882 ("TODO Lists"
20883 ["TODO/DONE/-" org-todo t]
20884 ("Select keyword"
20885 ["Next keyword" org-shiftright (org-at-heading-p)]
20886 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20887 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20888 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20889 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20890 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20891 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20892 "--"
20893 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20894 :selected org-enforce-todo-dependencies :style toggle :active t]
20895 "Settings for tree at point"
20896 ["Do Children sequentially" org-toggle-ordered-property :style radio
20897 :selected (org-entry-get nil "ORDERED")
20898 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20899 ["Do Children parallel" org-toggle-ordered-property :style radio
20900 :selected (not (org-entry-get nil "ORDERED"))
20901 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20902 "--"
20903 ["Set Priority" org-priority t]
20904 ["Priority Up" org-shiftup t]
20905 ["Priority Down" org-shiftdown t]
20906 "--"
20907 ["Get news from all feeds" org-feed-update-all t]
20908 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20909 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20910 ("TAGS and Properties"
20911 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20912 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20913 "--"
20914 ["Set property" org-set-property (not (org-before-first-heading-p))]
20915 ["Column view of properties" org-columns t]
20916 ["Insert Column View DBlock" org-insert-columns-dblock t])
20917 ("Dates and Scheduling"
20918 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20919 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20920 ("Change Date"
20921 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20922 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20923 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20924 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20925 ["Compute Time Range" org-evaluate-time-range t]
20926 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20927 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20928 "--"
20929 ["Custom time format" org-toggle-time-stamp-overlays
20930 :style radio :selected org-display-custom-times]
20931 "--"
20932 ["Goto Calendar" org-goto-calendar t]
20933 ["Date from Calendar" org-date-from-calendar t]
20934 "--"
20935 ["Start/Restart Timer" org-timer-start t]
20936 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20937 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20938 ["Insert Timer String" org-timer t]
20939 ["Insert Timer Item" org-timer-item t])
20940 ("Logging work"
20941 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20942 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20943 ["Clock out" org-clock-out t]
20944 ["Clock cancel" org-clock-cancel t]
20945 "--"
20946 ["Mark as default task" org-clock-mark-default-task t]
20947 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20948 ["Goto running clock" org-clock-goto t]
20949 "--"
20950 ["Display times" org-clock-display t]
20951 ["Create clock table" org-clock-report t]
20952 "--"
20953 ["Record DONE time"
20954 (progn (setq org-log-done (not org-log-done))
20955 (message "Switching to %s will %s record a timestamp"
20956 (car org-done-keywords)
20957 (if org-log-done "automatically" "not")))
20958 :style toggle :selected org-log-done])
20959 "--"
20960 ["Agenda Command..." org-agenda t]
20961 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20962 ("File List for Agenda")
20963 ("Special views current file"
20964 ["TODO Tree" org-show-todo-tree t]
20965 ["Check Deadlines" org-check-deadlines t]
20966 ["Timeline" org-timeline t]
20967 ["Tags/Property tree" org-match-sparse-tree t])
20968 "--"
20969 ["Export/Publish..." org-export-dispatch t]
20970 ("LaTeX"
20971 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20972 :selected org-cdlatex-mode]
20973 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20974 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20975 ["Modify math symbol" org-cdlatex-math-modify
20976 (org-inside-LaTeX-fragment-p)]
20977 ["Insert citation" org-reftex-citation t]
20978 "--"
20979 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20980 "--"
20981 ("MobileOrg"
20982 ["Push Files and Views" org-mobile-push t]
20983 ["Get Captured and Flagged" org-mobile-pull t]
20984 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20985 "--"
20986 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20987 "--"
20988 ("Documentation"
20989 ["Show Version" org-version t]
20990 ["Info Documentation" org-info t])
20991 ("Customize"
20992 ["Browse Org Group" org-customize t]
20993 "--"
20994 ["Expand This Menu" org-create-customize-menu
20995 (fboundp 'customize-menu-create)])
20996 ["Send bug report" org-submit-bug-report t]
20997 "--"
20998 ("Refresh/Reload"
20999 ["Refresh setup current buffer" org-mode-restart t]
21000 ["Reload Org (after update)" org-reload t]
21001 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21004 (defun org-info (&optional node)
21005 "Read documentation for Org-mode in the info system.
21006 With optional NODE, go directly to that node."
21007 (interactive)
21008 (info (format "(org)%s" (or node ""))))
21010 ;;;###autoload
21011 (defun org-submit-bug-report ()
21012 "Submit a bug report on Org-mode via mail.
21014 Don't hesitate to report any problems or inaccurate documentation.
21016 If you don't have setup sending mail from (X)Emacs, please copy the
21017 output buffer into your mail program, as it gives us important
21018 information about your Org-mode version and configuration."
21019 (interactive)
21020 (require 'reporter)
21021 (org-load-modules-maybe)
21022 (org-require-autoloaded-modules)
21023 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21024 (reporter-submit-bug-report
21025 "emacs-orgmode@gnu.org"
21026 (org-version nil 'full)
21027 (let (list)
21028 (save-window-excursion
21029 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21030 (delete-other-windows)
21031 (erase-buffer)
21032 (insert "You are about to submit a bug report to the Org-mode mailing list.
21034 We would like to add your full Org-mode and Outline configuration to the
21035 bug report. This greatly simplifies the work of the maintainer and
21036 other experts on the mailing list.
21038 HOWEVER, some variables you have customized may contain private
21039 information. The names of customers, colleagues, or friends, might
21040 appear in the form of file names, tags, todo states, or search strings.
21041 If you answer yes to the prompt, you might want to check and remove
21042 such private information before sending the email.")
21043 (add-text-properties (point-min) (point-max) '(face org-warning))
21044 (when (yes-or-no-p "Include your Org-mode configuration ")
21045 (mapatoms
21046 (lambda (v)
21047 (and (boundp v)
21048 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21049 (or (and (symbol-value v)
21050 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21051 (and
21052 (get v 'custom-type) (get v 'standard-value)
21053 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21054 (push v list)))))
21055 (kill-buffer (get-buffer "*Warn about privacy*"))
21056 list))
21057 nil nil
21058 "Remember to cover the basics, that is, what you expected to happen and
21059 what in fact did happen. You don't know how to make a good report? See
21061 http://orgmode.org/manual/Feedback.html#Feedback
21063 Your bug report will be posted to the Org-mode mailing list.
21064 ------------------------------------------------------------------------")
21065 (save-excursion
21066 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21067 (replace-match "\\1Bug: \\3 [\\2]")))))
21070 (defun org-install-agenda-files-menu ()
21071 (let ((bl (buffer-list)))
21072 (save-excursion
21073 (while bl
21074 (set-buffer (pop bl))
21075 (if (derived-mode-p 'org-mode) (setq bl nil)))
21076 (when (derived-mode-p 'org-mode)
21077 (easy-menu-change
21078 '("Org") "File List for Agenda"
21079 (append
21080 (list
21081 ["Edit File List" (org-edit-agenda-file-list) t]
21082 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21083 ["Remove Current File from List" org-remove-file t]
21084 ["Cycle through agenda files" org-cycle-agenda-files t]
21085 ["Occur in all agenda files" org-occur-in-agenda-files t]
21086 "--")
21087 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21089 ;;;; Documentation
21091 (defun org-require-autoloaded-modules ()
21092 (interactive)
21093 (mapc 'require
21094 '(org-agenda org-archive org-attach org-clock org-colview org-id
21095 org-table org-timer)))
21097 ;;;###autoload
21098 (defun org-reload (&optional uncompiled)
21099 "Reload all org lisp files.
21100 With prefix arg UNCOMPILED, load the uncompiled versions."
21101 (interactive "P")
21102 (require 'loadhist)
21103 (let* ((org-dir (org-find-library-dir "org"))
21104 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21105 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21106 (remove-re (mapconcat 'identity
21107 (mapcar (lambda (f) (concat "^" f "$"))
21108 (list (if (featurep 'xemacs)
21109 "org-colview"
21110 "org-colview-xemacs")
21111 "org" "org-loaddefs" "org-version"))
21112 "\\|"))
21113 (feats (delete-dups
21114 (mapcar 'file-name-sans-extension
21115 (mapcar 'file-name-nondirectory
21116 (delq nil
21117 (mapcar 'feature-file
21118 features))))))
21119 (lfeat (append
21120 (sort
21121 (setq feats
21122 (delq nil (mapcar
21123 (lambda (f)
21124 (if (and (string-match feature-re f)
21125 (not (string-match remove-re f)))
21126 f nil))
21127 feats)))
21128 'string-lessp)
21129 (list "org-version" "org")))
21130 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21131 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21132 load-uncore load-misses)
21133 (setq load-misses
21134 (delq 't
21135 (mapcar (lambda (f)
21136 (or (org-load-noerror-mustsuffix (concat org-dir f))
21137 (and (string= org-dir contrib-dir)
21138 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21139 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21140 (add-to-list 'load-uncore f 'append)
21143 lfeat)))
21144 (if load-uncore
21145 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21146 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21147 (if load-misses
21148 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21149 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21150 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21152 ;;;###autoload
21153 (defun org-customize ()
21154 "Call the customize function with org as argument."
21155 (interactive)
21156 (org-load-modules-maybe)
21157 (org-require-autoloaded-modules)
21158 (customize-browse 'org))
21160 (defun org-create-customize-menu ()
21161 "Create a full customization menu for Org-mode, insert it into the menu."
21162 (interactive)
21163 (org-load-modules-maybe)
21164 (org-require-autoloaded-modules)
21165 (if (fboundp 'customize-menu-create)
21166 (progn
21167 (easy-menu-change
21168 '("Org") "Customize"
21169 `(["Browse Org group" org-customize t]
21170 "--"
21171 ,(customize-menu-create 'org)
21172 ["Set" Custom-set t]
21173 ["Save" Custom-save t]
21174 ["Reset to Current" Custom-reset-current t]
21175 ["Reset to Saved" Custom-reset-saved t]
21176 ["Reset to Standard Settings" Custom-reset-standard t]))
21177 (message "\"Org\"-menu now contains full customization menu"))
21178 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21180 ;;;; Miscellaneous stuff
21182 ;;; Generally useful functions
21184 (defun org-get-at-bol (property)
21185 "Get text property PROPERTY at beginning of line."
21186 (get-text-property (point-at-bol) property))
21188 (defun org-find-text-property-in-string (prop s)
21189 "Return the first non-nil value of property PROP in string S."
21190 (or (get-text-property 0 prop s)
21191 (get-text-property (or (next-single-property-change 0 prop s) 0)
21192 prop s)))
21194 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21195 "Display the given MESSAGE as a warning."
21196 (if (fboundp 'display-warning)
21197 (display-warning 'org message
21198 (if (featurep 'xemacs) 'warning :warning))
21199 (let ((buf (get-buffer-create "*Org warnings*")))
21200 (with-current-buffer buf
21201 (goto-char (point-max))
21202 (insert "Warning (Org): " message)
21203 (unless (bolp)
21204 (newline)))
21205 (display-buffer buf)
21206 (sit-for 0))))
21208 (defun org-eval (form)
21209 "Eval FORM and return result."
21210 (condition-case error
21211 (eval form)
21212 (error (format "%%![Error: %s]" error))))
21214 (defun org-in-clocktable-p ()
21215 "Check if the cursor is in a clocktable."
21216 (let ((pos (point)) start)
21217 (save-excursion
21218 (end-of-line 1)
21219 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21220 (setq start (match-beginning 0))
21221 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21222 (>= (match-end 0) pos)
21223 start))))
21225 (defun org-in-commented-line ()
21226 "Is point in a line starting with `#'?"
21227 (equal (char-after (point-at-bol)) ?#))
21229 (defun org-in-indented-comment-line ()
21230 "Is point in a line starting with `#' after some white space?"
21231 (save-excursion
21232 (save-match-data
21233 (goto-char (point-at-bol))
21234 (looking-at "[ \t]*#"))))
21236 (defun org-in-verbatim-emphasis ()
21237 (save-match-data
21238 (and (org-in-regexp org-emph-re 2)
21239 (>= (point) (match-beginning 3))
21240 (<= (point) (match-end 4))
21241 (member (match-string 3) '("=" "~")))))
21243 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21244 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21245 (if (and marker (marker-buffer marker)
21246 (buffer-live-p (marker-buffer marker)))
21247 (progn
21248 (org-pop-to-buffer-same-window (marker-buffer marker))
21249 (if (or (> marker (point-max)) (< marker (point-min)))
21250 (widen))
21251 (goto-char marker)
21252 (org-show-context 'org-goto))
21253 (if bookmark
21254 (bookmark-jump bookmark)
21255 (error "Cannot find location"))))
21257 (defun org-quote-csv-field (s)
21258 "Quote field for inclusion in CSV material."
21259 (if (string-match "[\",]" s)
21260 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21263 (defun org-force-self-insert (N)
21264 "Needed to enforce self-insert under remapping."
21265 (interactive "p")
21266 (self-insert-command N))
21268 (defun org-string-width (s)
21269 "Compute width of string, ignoring invisible characters.
21270 This ignores character with invisibility property `org-link', and also
21271 characters with property `org-cwidth', because these will become invisible
21272 upon the next fontification round."
21273 (let (b l)
21274 (when (or (eq t buffer-invisibility-spec)
21275 (assq 'org-link buffer-invisibility-spec))
21276 (while (setq b (text-property-any 0 (length s)
21277 'invisible 'org-link s))
21278 (setq s (concat (substring s 0 b)
21279 (substring s (or (next-single-property-change
21280 b 'invisible s) (length s)))))))
21281 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21282 (setq s (concat (substring s 0 b)
21283 (substring s (or (next-single-property-change
21284 b 'org-cwidth s) (length s))))))
21285 (setq l (string-width s) b -1)
21286 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21287 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21290 (defun org-shorten-string (s maxlength)
21291 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21292 If the string is shorter or has length MAXLENGTH, just return the
21293 original string. If it is longer, the functions finds a space in the
21294 string, breaks this string off at that locations and adds three dots
21295 as ellipsis. Including the ellipsis, the string will not be longer
21296 than MAXLENGTH. If finding a good breaking point in the string does
21297 not work, the string is just chopped off in the middle of a word
21298 if necessary."
21299 (if (<= (length s) maxlength)
21301 (let* ((n (max (- maxlength 4) 1))
21302 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21303 (if (string-match re s)
21304 (concat (match-string 1 s) "...")
21305 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21307 (defun org-get-indentation (&optional line)
21308 "Get the indentation of the current line, interpreting tabs.
21309 When LINE is given, assume it represents a line and compute its indentation."
21310 (if line
21311 (if (string-match "^ *" (org-remove-tabs line))
21312 (match-end 0))
21313 (save-excursion
21314 (beginning-of-line 1)
21315 (skip-chars-forward " \t")
21316 (current-column))))
21318 (defun org-get-string-indentation (s)
21319 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21320 (let ((n -1) (i 0) (w tab-width) c)
21321 (catch 'exit
21322 (while (< (setq n (1+ n)) (length s))
21323 (setq c (aref s n))
21324 (cond ((= c ?\ ) (setq i (1+ i)))
21325 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21326 (t (throw 'exit t)))))
21329 (defun org-remove-tabs (s &optional width)
21330 "Replace tabulators in S with spaces.
21331 Assumes that s is a single line, starting in column 0."
21332 (setq width (or width tab-width))
21333 (while (string-match "\t" s)
21334 (setq s (replace-match
21335 (make-string
21336 (- (* width (/ (+ (match-beginning 0) width) width))
21337 (match-beginning 0)) ?\ )
21338 t t s)))
21341 (defun org-fix-indentation (line ind)
21342 "Fix indentation in LINE.
21343 IND is a cons cell with target and minimum indentation.
21344 If the current indentation in LINE is smaller than the minimum,
21345 leave it alone. If it is larger than ind, set it to the target."
21346 (let* ((l (org-remove-tabs line))
21347 (i (org-get-indentation l))
21348 (i1 (car ind)) (i2 (cdr ind)))
21349 (if (>= i i2) (setq l (substring line i2)))
21350 (if (> i1 0)
21351 (concat (make-string i1 ?\ ) l)
21352 l)))
21354 (defun org-remove-indentation (code &optional n)
21355 "Remove the maximum common indentation from the lines in CODE.
21356 N may optionally be the number of spaces to remove."
21357 (with-temp-buffer
21358 (insert code)
21359 (org-do-remove-indentation n)
21360 (buffer-string)))
21362 (defun org-do-remove-indentation (&optional n)
21363 "Remove the maximum common indentation from the buffer."
21364 (untabify (point-min) (point-max))
21365 (let ((min 10000) re)
21366 (if n
21367 (setq min n)
21368 (goto-char (point-min))
21369 (while (re-search-forward "^ *[^ \n]" nil t)
21370 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21371 (unless (or (= min 0) (= min 10000))
21372 (setq re (format "^ \\{%d\\}" min))
21373 (goto-char (point-min))
21374 (while (re-search-forward re nil t)
21375 (replace-match "")
21376 (end-of-line 1))
21377 min)))
21379 (defun org-fill-template (template alist)
21380 "Find each %key of ALIST in TEMPLATE and replace it."
21381 (let ((case-fold-search nil)
21382 entry key value)
21383 (setq alist (sort (copy-sequence alist)
21384 (lambda (a b) (< (length (car a)) (length (car b))))))
21385 (while (setq entry (pop alist))
21386 (setq template
21387 (replace-regexp-in-string
21388 (concat "%" (regexp-quote (car entry)))
21389 (or (cdr entry) "") template t t)))
21390 template))
21392 (defun org-base-buffer (buffer)
21393 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21394 (if (not buffer)
21395 buffer
21396 (or (buffer-base-buffer buffer)
21397 buffer)))
21399 (defun org-trim (s)
21400 "Remove whitespace at beginning and end of string."
21401 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21402 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21405 (defun org-wrap (string &optional width lines)
21406 "Wrap string to either a number of lines, or a width in characters.
21407 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21408 that costs. If there is a word longer than WIDTH, the text is actually
21409 wrapped to the length of that word.
21410 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21411 many lines, whatever width that takes.
21412 The return value is a list of lines, without newlines at the end."
21413 (let* ((words (org-split-string string "[ \t\n]+"))
21414 (maxword (apply 'max (mapcar 'org-string-width words)))
21415 w ll)
21416 (cond (width
21417 (org-do-wrap words (max maxword width)))
21418 (lines
21419 (setq w maxword)
21420 (setq ll (org-do-wrap words maxword))
21421 (if (<= (length ll) lines)
21423 (setq ll words)
21424 (while (> (length ll) lines)
21425 (setq w (1+ w))
21426 (setq ll (org-do-wrap words w)))
21427 ll))
21428 (t (error "Cannot wrap this")))))
21430 (defun org-do-wrap (words width)
21431 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21432 (let (lines line)
21433 (while words
21434 (setq line (pop words))
21435 (while (and words (< (+ (length line) (length (car words))) width))
21436 (setq line (concat line " " (pop words))))
21437 (setq lines (push line lines)))
21438 (nreverse lines)))
21440 (defun org-split-string (string &optional separators)
21441 "Splits STRING into substrings at SEPARATORS.
21442 No empty strings are returned if there are matches at the beginning
21443 and end of string."
21444 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21445 (start 0)
21446 notfirst
21447 (list nil))
21448 (while (and (string-match rexp string
21449 (if (and notfirst
21450 (= start (match-beginning 0))
21451 (< start (length string)))
21452 (1+ start) start))
21453 (< (match-beginning 0) (length string)))
21454 (setq notfirst t)
21455 (or (eq (match-beginning 0) 0)
21456 (and (eq (match-beginning 0) (match-end 0))
21457 (eq (match-beginning 0) start))
21458 (setq list
21459 (cons (substring string start (match-beginning 0))
21460 list)))
21461 (setq start (match-end 0)))
21462 (or (eq start (length string))
21463 (setq list
21464 (cons (substring string start)
21465 list)))
21466 (nreverse list)))
21468 (defun org-quote-vert (s)
21469 "Replace \"|\" with \"\\vert\"."
21470 (while (string-match "|" s)
21471 (setq s (replace-match "\\vert" t t s)))
21474 (defun org-uuidgen-p (s)
21475 "Is S an ID created by UUIDGEN?"
21476 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21478 (defun org-in-src-block-p (&optional inside)
21479 "Whether point is in a code source block.
21480 When INSIDE is non-nil, don't consider we are within a src block
21481 when point is at #+BEGIN_SRC or #+END_SRC."
21482 (let ((case-fold-search t) ov)
21483 (or (and (setq ov (overlays-at (point)))
21484 (memq 'org-block-background
21485 (overlay-properties (car ov))))
21486 (and (not inside)
21487 (save-match-data
21488 (save-excursion
21489 (beginning-of-line)
21490 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21492 (defun org-context ()
21493 "Return a list of contexts of the current cursor position.
21494 If several contexts apply, all are returned.
21495 Each context entry is a list with a symbol naming the context, and
21496 two positions indicating start and end of the context. Possible
21497 contexts are:
21499 :headline anywhere in a headline
21500 :headline-stars on the leading stars in a headline
21501 :todo-keyword on a TODO keyword (including DONE) in a headline
21502 :tags on the TAGS in a headline
21503 :priority on the priority cookie in a headline
21504 :item on the first line of a plain list item
21505 :item-bullet on the bullet/number of a plain list item
21506 :checkbox on the checkbox in a plain list item
21507 :table in an org-mode table
21508 :table-special on a special filed in a table
21509 :table-table in a table.el table
21510 :clocktable in a clocktable
21511 :src-block in a source block
21512 :link on a hyperlink
21513 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21514 :target on a <<target>>
21515 :radio-target on a <<<radio-target>>>
21516 :latex-fragment on a LaTeX fragment
21517 :latex-preview on a LaTeX fragment with overlaid preview image
21519 This function expects the position to be visible because it uses font-lock
21520 faces as a help to recognize the following contexts: :table-special, :link,
21521 and :keyword."
21522 (let* ((f (get-text-property (point) 'face))
21523 (faces (if (listp f) f (list f)))
21524 (case-fold-search t)
21525 (p (point)) clist o)
21526 ;; First the large context
21527 (cond
21528 ((org-at-heading-p t)
21529 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21530 (when (progn
21531 (beginning-of-line 1)
21532 (looking-at org-todo-line-tags-regexp))
21533 (push (org-point-in-group p 1 :headline-stars) clist)
21534 (push (org-point-in-group p 2 :todo-keyword) clist)
21535 (push (org-point-in-group p 4 :tags) clist))
21536 (goto-char p)
21537 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21538 (if (looking-at "\\[#[A-Z0-9]\\]")
21539 (push (org-point-in-group p 0 :priority) clist)))
21541 ((org-at-item-p)
21542 (push (org-point-in-group p 2 :item-bullet) clist)
21543 (push (list :item (point-at-bol)
21544 (save-excursion (org-end-of-item) (point)))
21545 clist)
21546 (and (org-at-item-checkbox-p)
21547 (push (org-point-in-group p 0 :checkbox) clist)))
21549 ((org-at-table-p)
21550 (push (list :table (org-table-begin) (org-table-end)) clist)
21551 (if (memq 'org-formula faces)
21552 (push (list :table-special
21553 (previous-single-property-change p 'face)
21554 (next-single-property-change p 'face)) clist)))
21555 ((org-at-table-p 'any)
21556 (push (list :table-table) clist)))
21557 (goto-char p)
21559 (let ((case-fold-search t))
21560 ;; New the "medium" contexts: clocktables, source blocks
21561 (cond ((org-in-clocktable-p)
21562 (push (list :clocktable
21563 (and (or (looking-at "#\\+BEGIN: clocktable")
21564 (search-backward "#+BEGIN: clocktable" nil t))
21565 (match-beginning 0))
21566 (and (re-search-forward "#\\+END:?" nil t)
21567 (match-end 0))) clist))
21568 ((org-in-src-block-p)
21569 (push (list :src-block
21570 (and (or (looking-at "#\\+BEGIN_SRC")
21571 (search-backward "#+BEGIN_SRC" nil t))
21572 (match-beginning 0))
21573 (and (search-forward "#+END_SRC" nil t)
21574 (match-beginning 0))) clist))))
21575 (goto-char p)
21577 ;; Now the small context
21578 (cond
21579 ((org-at-timestamp-p)
21580 (push (org-point-in-group p 0 :timestamp) clist))
21581 ((memq 'org-link faces)
21582 (push (list :link
21583 (previous-single-property-change p 'face)
21584 (next-single-property-change p 'face)) clist))
21585 ((memq 'org-special-keyword faces)
21586 (push (list :keyword
21587 (previous-single-property-change p 'face)
21588 (next-single-property-change p 'face)) clist))
21589 ((org-at-target-p)
21590 (push (org-point-in-group p 0 :target) clist)
21591 (goto-char (1- (match-beginning 0)))
21592 (if (looking-at org-radio-target-regexp)
21593 (push (org-point-in-group p 0 :radio-target) clist))
21594 (goto-char p))
21595 ((setq o (car (delq nil
21596 (mapcar
21597 (lambda (x)
21598 (if (memq x org-latex-fragment-image-overlays) x))
21599 (overlays-at (point))))))
21600 (push (list :latex-fragment
21601 (overlay-start o) (overlay-end o)) clist)
21602 (push (list :latex-preview
21603 (overlay-start o) (overlay-end o)) clist))
21604 ((org-inside-LaTeX-fragment-p)
21605 ;; FIXME: positions wrong.
21606 (push (list :latex-fragment (point) (point)) clist)))
21608 (setq clist (nreverse (delq nil clist)))
21609 clist))
21611 ;; FIXME: Compare with at-regexp-p Do we need both?
21612 (defun org-in-regexp (re &optional nlines visually)
21613 "Check if point is inside a match of regexp.
21614 Normally only the current line is checked, but you can include NLINES extra
21615 lines both before and after point into the search.
21616 If VISUALLY is set, require that the cursor is not after the match but
21617 really on, so that the block visually is on the match."
21618 (catch 'exit
21619 (let ((pos (point))
21620 (eol (point-at-eol (+ 1 (or nlines 0))))
21621 (inc (if visually 1 0)))
21622 (save-excursion
21623 (beginning-of-line (- 1 (or nlines 0)))
21624 (while (re-search-forward re eol t)
21625 (if (and (<= (match-beginning 0) pos)
21626 (>= (+ inc (match-end 0)) pos))
21627 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21629 (defun org-at-regexp-p (regexp)
21630 "Is point inside a match of REGEXP in the current line?"
21631 (catch 'exit
21632 (save-excursion
21633 (let ((pos (point)) (end (point-at-eol)))
21634 (beginning-of-line 1)
21635 (while (re-search-forward regexp end t)
21636 (if (and (<= (match-beginning 0) pos)
21637 (>= (match-end 0) pos))
21638 (throw 'exit t)))
21639 nil))))
21641 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21642 "Non-nil when point is between matches of START-RE and END-RE.
21644 Also return a non-nil value when point is on one of the matches.
21646 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21647 buffer positions. Default values are the positions of headlines
21648 surrounding the point.
21650 The functions returns a cons cell whose car (resp. cdr) is the
21651 position before START-RE (resp. after END-RE)."
21652 (save-match-data
21653 (let ((pos (point))
21654 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21655 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21656 beg end)
21657 (save-excursion
21658 ;; Point is on a block when on START-RE or if START-RE can be
21659 ;; found before it...
21660 (and (or (org-at-regexp-p start-re)
21661 (re-search-backward start-re limit-up t))
21662 (setq beg (match-beginning 0))
21663 ;; ... and END-RE after it...
21664 (goto-char (match-end 0))
21665 (re-search-forward end-re limit-down t)
21666 (> (setq end (match-end 0)) pos)
21667 ;; ... without another START-RE in-between.
21668 (goto-char (match-beginning 0))
21669 (not (re-search-backward start-re (1+ beg) t))
21670 ;; Return value.
21671 (cons beg end))))))
21673 (defun org-in-block-p (names)
21674 "Non-nil when point belongs to a block whose name belongs to NAMES.
21676 NAMES is a list of strings containing names of blocks.
21678 Return first block name matched, or nil. Beware that in case of
21679 nested blocks, the returned name may not belong to the closest
21680 block from point."
21681 (save-match-data
21682 (catch 'exit
21683 (let ((case-fold-search t)
21684 (lim-up (save-excursion (outline-previous-heading)))
21685 (lim-down (save-excursion (outline-next-heading))))
21686 (mapc (lambda (name)
21687 (let ((n (regexp-quote name)))
21688 (when (org-between-regexps-p
21689 (concat "^[ \t]*#\\+begin_" n)
21690 (concat "^[ \t]*#\\+end_" n)
21691 lim-up lim-down)
21692 (throw 'exit n))))
21693 names))
21694 nil)))
21696 (defun org-in-drawer-p ()
21697 "Is point within a drawer?"
21698 (save-match-data
21699 (let ((case-fold-search t)
21700 (lim-up (save-excursion (outline-previous-heading)))
21701 (lim-down (save-excursion (outline-next-heading))))
21702 (org-between-regexps-p
21703 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21704 "^[ \t]*:end:.*$"
21705 lim-up lim-down))))
21707 (defun org-occur-in-agenda-files (regexp &optional nlines)
21708 "Call `multi-occur' with buffers for all agenda files."
21709 (interactive "sOrg-files matching: \np")
21710 (let* ((files (org-agenda-files))
21711 (tnames (mapcar 'file-truename files))
21712 (extra org-agenda-text-search-extra-files)
21714 (when (eq (car extra) 'agenda-archives)
21715 (setq extra (cdr extra))
21716 (setq files (org-add-archive-files files)))
21717 (while (setq f (pop extra))
21718 (unless (member (file-truename f) tnames)
21719 (add-to-list 'files f 'append)
21720 (add-to-list 'tnames (file-truename f) 'append)))
21721 (multi-occur
21722 (mapcar (lambda (x)
21723 (with-current-buffer
21724 (or (get-file-buffer x) (find-file-noselect x))
21725 (widen)
21726 (current-buffer)))
21727 files)
21728 regexp)))
21730 (if (boundp 'occur-mode-find-occurrence-hook)
21731 ;; Emacs 23
21732 (add-hook 'occur-mode-find-occurrence-hook
21733 (lambda ()
21734 (when (derived-mode-p 'org-mode)
21735 (org-reveal))))
21736 ;; Emacs 22
21737 (defadvice occur-mode-goto-occurrence
21738 (after org-occur-reveal activate)
21739 (and (derived-mode-p 'org-mode) (org-reveal)))
21740 (defadvice occur-mode-goto-occurrence-other-window
21741 (after org-occur-reveal activate)
21742 (and (derived-mode-p 'org-mode) (org-reveal)))
21743 (defadvice occur-mode-display-occurrence
21744 (after org-occur-reveal activate)
21745 (when (derived-mode-p 'org-mode)
21746 (let ((pos (occur-mode-find-occurrence)))
21747 (with-current-buffer (marker-buffer pos)
21748 (save-excursion
21749 (goto-char pos)
21750 (org-reveal)))))))
21752 (defun org-occur-link-in-agenda-files ()
21753 "Create a link and search for it in the agendas.
21754 The link is not stored in `org-stored-links', it is just created
21755 for the search purpose."
21756 (interactive)
21757 (let ((link (condition-case nil
21758 (org-store-link nil)
21759 (error "Unable to create a link to here"))))
21760 (org-occur-in-agenda-files (regexp-quote link))))
21762 (defun org-reverse-string (string)
21763 "Return the reverse of STRING."
21764 (apply 'string (reverse (string-to-list string))))
21766 (defsubst org-uniquify (list)
21767 "Non-destructively remove duplicate elements from LIST."
21768 (let ((res (copy-sequence list))) (delete-dups res)))
21770 (defun org-uniquify-alist (alist)
21771 "Merge elements of ALIST with the same key.
21773 For example, in this alist:
21775 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21776 => '((a 1 3) (b 2))
21778 merge (a 1) and (a 3) into (a 1 3).
21780 The function returns the new ALIST."
21781 (let (rtn)
21782 (mapc
21783 (lambda (e)
21784 (let (n)
21785 (if (not (assoc (car e) rtn))
21786 (push e rtn)
21787 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21788 (setq rtn (assq-delete-all (car e) rtn))
21789 (push n rtn))))
21790 alist)
21791 rtn))
21793 (defun org-delete-all (elts list)
21794 "Remove all elements in ELTS from LIST."
21795 (while elts
21796 (setq list (delete (pop elts) list)))
21797 list)
21799 (defun org-count (cl-item cl-seq)
21800 "Count the number of occurrences of ITEM in SEQ.
21801 Taken from `count' in cl-seq.el with all keyword arguments removed."
21802 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21803 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21804 (while (< cl-start cl-end)
21805 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21806 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21807 (setq cl-start (1+ cl-start)))
21808 cl-count))
21810 (defun org-remove-if (predicate seq)
21811 "Remove everything from SEQ that fulfills PREDICATE."
21812 (let (res e)
21813 (while seq
21814 (setq e (pop seq))
21815 (if (not (funcall predicate e)) (push e res)))
21816 (nreverse res)))
21818 (defun org-remove-if-not (predicate seq)
21819 "Remove everything from SEQ that does not fulfill PREDICATE."
21820 (let (res e)
21821 (while seq
21822 (setq e (pop seq))
21823 (if (funcall predicate e) (push e res)))
21824 (nreverse res)))
21826 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21827 "Reduce two-argument FUNCTION across SEQ.
21828 Taken from `reduce' in cl-seq.el with all keyword arguments but
21829 \":initial-value\" removed."
21830 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21831 (cadr (memq :initial-value cl-keys)))
21832 (cl-seq (pop cl-seq))
21833 (t (funcall cl-func)))))
21834 (while cl-seq
21835 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21836 cl-accum))
21838 (defun org-every (pred seq)
21839 "Return true if PREDICATE is true of every element of SEQ.
21840 Adapted from `every' in cl.el."
21841 (catch 'org-every
21842 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21845 (defun org-some (pred seq)
21846 "Return true if PREDICATE is true of any element of SEQ.
21847 Adapted from `some' in cl.el."
21848 (catch 'org-some
21849 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21850 nil))
21852 (defun org-back-over-empty-lines ()
21853 "Move backwards over whitespace, to the beginning of the first empty line.
21854 Returns the number of empty lines passed."
21855 (let ((pos (point)))
21856 (if (cdr (assoc 'heading org-blank-before-new-entry))
21857 (skip-chars-backward " \t\n\r")
21858 (unless (eobp)
21859 (forward-line -1)))
21860 (beginning-of-line 2)
21861 (goto-char (min (point) pos))
21862 (count-lines (point) pos)))
21864 (defun org-skip-whitespace ()
21865 (skip-chars-forward " \t\n\r"))
21867 (defun org-point-in-group (point group &optional context)
21868 "Check if POINT is in match-group GROUP.
21869 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21870 match. If the match group does not exist or point is not inside it,
21871 return nil."
21872 (and (match-beginning group)
21873 (>= point (match-beginning group))
21874 (<= point (match-end group))
21875 (if context
21876 (list context (match-beginning group) (match-end group))
21877 t)))
21879 (defun org-switch-to-buffer-other-window (&rest args)
21880 "Switch to buffer in a second window on the current frame.
21881 In particular, do not allow pop-up frames.
21882 Returns the newly created buffer."
21883 (org-no-popups
21884 (apply 'switch-to-buffer-other-window args)))
21886 (defun org-combine-plists (&rest plists)
21887 "Create a single property list from all plists in PLISTS.
21888 The process starts by copying the first list, and then setting properties
21889 from the other lists. Settings in the last list are the most significant
21890 ones and overrule settings in the other lists."
21891 (let ((rtn (copy-sequence (pop plists)))
21892 p v ls)
21893 (while plists
21894 (setq ls (pop plists))
21895 (while ls
21896 (setq p (pop ls) v (pop ls))
21897 (setq rtn (plist-put rtn p v))))
21898 rtn))
21900 (defun org-replace-escapes (string table)
21901 "Replace %-escapes in STRING with values in TABLE.
21902 TABLE is an association list with keys like \"%a\" and string values.
21903 The sequences in STRING may contain normal field width and padding information,
21904 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21905 so values can contain further %-escapes if they are define later in TABLE."
21906 (let ((tbl (copy-alist table))
21907 (case-fold-search nil)
21908 (pchg 0)
21909 e re rpl)
21910 (while (setq e (pop tbl))
21911 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21912 (when (and (cdr e) (string-match re (cdr e)))
21913 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21914 (safe "SREF"))
21915 (add-text-properties 0 3 (list 'sref sref) safe)
21916 (setcdr e (replace-match safe t t (cdr e)))))
21917 (while (string-match re string)
21918 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21919 (cdr e)))
21920 (setq string (replace-match rpl t t string))))
21921 (while (setq pchg (next-property-change pchg string))
21922 (let ((sref (get-text-property pchg 'sref string)))
21923 (when (and sref (string-match "SREF" string pchg))
21924 (setq string (replace-match sref t t string)))))
21925 string))
21927 (defun org-sublist (list start end)
21928 "Return a section of LIST, from START to END.
21929 Counting starts at 1."
21930 (let (rtn (c start))
21931 (setq list (nthcdr (1- start) list))
21932 (while (and list (<= c end))
21933 (push (pop list) rtn)
21934 (setq c (1+ c)))
21935 (nreverse rtn)))
21937 (defun org-find-base-buffer-visiting (file)
21938 "Like `find-buffer-visiting' but always return the base buffer and
21939 not an indirect buffer."
21940 (let ((buf (or (get-file-buffer file)
21941 (find-buffer-visiting file))))
21942 (if buf
21943 (or (buffer-base-buffer buf) buf)
21944 nil)))
21946 (defun org-image-file-name-regexp (&optional extensions)
21947 "Return regexp matching the file names of images.
21948 If EXTENSIONS is given, only match these."
21949 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21950 (image-file-name-regexp)
21951 (let ((image-file-name-extensions
21952 (or extensions
21953 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21954 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21955 (concat "\\."
21956 (regexp-opt (nconc (mapcar 'upcase
21957 image-file-name-extensions)
21958 image-file-name-extensions)
21960 "\\'"))))
21962 (defun org-file-image-p (file &optional extensions)
21963 "Return non-nil if FILE is an image."
21964 (save-match-data
21965 (string-match (org-image-file-name-regexp extensions) file)))
21967 (defun org-get-cursor-date (&optional with-time)
21968 "Return the date at cursor in as a time.
21969 This works in the calendar and in the agenda, anywhere else it just
21970 returns the current time.
21971 If WITH-TIME is non-nil, returns the time of the event at point (in
21972 the agenda) or the current time of the day."
21973 (let (date day defd tp tm hod mod)
21974 (when with-time
21975 (setq tp (get-text-property (point) 'time))
21976 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21977 (setq hod (string-to-number (match-string 1 tp))
21978 mod (string-to-number (match-string 2 tp))))
21979 (or tp (setq hod (nth 2 (decode-time (current-time)))
21980 mod (nth 1 (decode-time (current-time))))))
21981 (cond
21982 ((eq major-mode 'calendar-mode)
21983 (setq date (calendar-cursor-to-date)
21984 defd (encode-time 0 (or mod 0) (or hod 0)
21985 (nth 1 date) (nth 0 date) (nth 2 date))))
21986 ((eq major-mode 'org-agenda-mode)
21987 (setq day (get-text-property (point) 'day))
21988 (if day
21989 (setq date (calendar-gregorian-from-absolute day)
21990 defd (encode-time 0 (or mod 0) (or hod 0)
21991 (nth 1 date) (nth 0 date) (nth 2 date))))))
21992 (or defd (current-time))))
21994 (defun org-mark-subtree (&optional up)
21995 "Mark the current subtree.
21996 This puts point at the start of the current subtree, and mark at
21997 the end. If a numeric prefix UP is given, move up into the
21998 hierarchy of headlines by UP levels before marking the subtree."
21999 (interactive "P")
22000 (org-with-limited-levels
22001 (cond ((org-at-heading-p) (beginning-of-line))
22002 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22003 (t (outline-previous-visible-heading 1))))
22004 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22005 (if (org-called-interactively-p 'any)
22006 (call-interactively 'org-mark-element)
22007 (org-mark-element)))
22010 ;;; Indentation
22012 (defun org-indent-line ()
22013 "Indent line depending on context."
22014 (interactive)
22015 (let* ((pos (point))
22016 (itemp (org-at-item-p))
22017 (case-fold-search t)
22018 (org-drawer-regexp (or org-drawer-regexp "\000"))
22019 (inline-task-p (and (featurep 'org-inlinetask)
22020 (org-inlinetask-in-task-p)))
22021 (inline-re (and inline-task-p
22022 (org-inlinetask-outline-regexp)))
22023 column)
22024 (if (and orgstruct-is-++ (eq pos (point)))
22025 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22026 (indent-according-to-mode))
22027 (beginning-of-line 1)
22028 (cond
22029 ;; Headings
22030 ((looking-at org-outline-regexp) (setq column 0))
22031 ;; Footnote definition
22032 ((looking-at org-footnote-definition-re) (setq column 0))
22033 ;; Literal examples
22034 ((looking-at "[ \t]*:\\( \\|$\\)")
22035 (setq column (org-get-indentation))) ; do nothing
22036 ;; Lists
22037 ((ignore-errors (goto-char (org-in-item-p)))
22038 (setq column (if itemp
22039 (org-get-indentation)
22040 (org-list-item-body-column (point))))
22041 (goto-char pos))
22042 ;; Drawers
22043 ((and (looking-at "[ \t]*:END:")
22044 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22045 (save-excursion
22046 (goto-char (1- (match-beginning 1)))
22047 (setq column (current-column))))
22048 ;; Special blocks
22049 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22050 (save-excursion
22051 (re-search-backward
22052 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22053 (setq column (org-get-indentation (match-string 0))))
22054 ((and (not (looking-at "[ \t]*#\\+begin_"))
22055 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22056 (save-excursion
22057 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22058 (setq column
22059 (cond ((equal (downcase (match-string 1)) "src")
22060 ;; src blocks: let `org-edit-src-exit' handle them
22061 (org-get-indentation))
22062 ((equal (downcase (match-string 1)) "example")
22063 (max (org-get-indentation)
22064 (org-get-indentation (match-string 0))))
22066 (org-get-indentation (match-string 0))))))
22067 ;; This line has nothing special, look at the previous relevant
22068 ;; line to compute indentation
22070 (beginning-of-line 0)
22071 (while (and (not (bobp))
22072 (not (looking-at org-table-line-regexp))
22073 (not (looking-at org-drawer-regexp))
22074 ;; When point started in an inline task, do not move
22075 ;; above task starting line.
22076 (not (and inline-task-p (looking-at inline-re)))
22077 ;; Skip drawers, blocks, empty lines, verbatim,
22078 ;; comments, tables, footnotes definitions, lists,
22079 ;; inline tasks.
22080 (or (and (looking-at "[ \t]*:END:")
22081 (re-search-backward org-drawer-regexp nil t))
22082 (and (looking-at "[ \t]*#\\+end_")
22083 (re-search-backward "[ \t]*#\\+begin_"nil t))
22084 (looking-at "[ \t]*[\n:#|]")
22085 (looking-at org-footnote-definition-re)
22086 (and (not inline-task-p)
22087 (featurep 'org-inlinetask)
22088 (org-inlinetask-in-task-p)
22089 (or (org-inlinetask-goto-beginning) t))))
22090 (beginning-of-line 0))
22091 (cond
22092 ;; There was a list item above.
22093 ((ignore-errors (goto-char (org-in-item-p)))
22094 (goto-char (org-list-get-top-point (org-list-struct)))
22095 (setq column (org-get-indentation)))
22096 ;; There was an heading above.
22097 ((looking-at "\\*+[ \t]+")
22098 (if (not org-adapt-indentation)
22099 (setq column 0)
22100 (goto-char (match-end 0))
22101 (setq column (current-column))))
22102 ;; A drawer had started and is unfinished
22103 ((looking-at org-drawer-regexp)
22104 (goto-char (1- (match-beginning 1)))
22105 (setq column (current-column)))
22106 ;; Else, nothing noticeable found: get indentation and go on.
22107 (t (setq column (org-get-indentation))))))
22108 ;; Now apply indentation and move cursor accordingly
22109 (goto-char pos)
22110 (if (<= (current-column) (current-indentation))
22111 (org-indent-line-to column)
22112 (save-excursion (org-indent-line-to column)))
22113 ;; Special polishing for properties, see `org-property-format'
22114 (setq column (current-column))
22115 (beginning-of-line 1)
22116 (if (looking-at org-property-re)
22117 (replace-match (concat (match-string 4)
22118 (format org-property-format
22119 (match-string 1) (match-string 3)))
22120 t t))
22121 (org-move-to-column column))))
22123 (defun org-indent-drawer ()
22124 "Indent the drawer at point."
22125 (interactive)
22126 (let ((p (point))
22127 (e (and (save-excursion (re-search-forward ":END:" nil t))
22128 (match-end 0)))
22129 (folded
22130 (save-excursion
22131 (end-of-line)
22132 (when (overlays-at (point))
22133 (member 'invisible (overlay-properties
22134 (car (overlays-at (point)))))))))
22135 (when folded (org-cycle))
22136 (indent-for-tab-command)
22137 (while (and (move-beginning-of-line 2) (< (point) e))
22138 (indent-for-tab-command))
22139 (goto-char p)
22140 (when folded (org-cycle)))
22141 (message "Drawer at point indented"))
22143 (defun org-indent-block ()
22144 "Indent the block at point."
22145 (interactive)
22146 (let ((p (point))
22147 (case-fold-search t)
22148 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22149 (match-end 0)))
22150 (folded
22151 (save-excursion
22152 (end-of-line)
22153 (when (overlays-at (point))
22154 (member 'invisible (overlay-properties
22155 (car (overlays-at (point)))))))))
22156 (when folded (org-cycle))
22157 (indent-for-tab-command)
22158 (while (and (move-beginning-of-line 2) (< (point) e))
22159 (indent-for-tab-command))
22160 (goto-char p)
22161 (when folded (org-cycle)))
22162 (message "Block at point indented"))
22164 (defun org-indent-region (start end)
22165 "Indent region."
22166 (interactive "r")
22167 (save-excursion
22168 (let ((line-end (org-current-line end)))
22169 (goto-char start)
22170 (while (< (org-current-line) line-end)
22171 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22172 (t (call-interactively 'org-indent-line)))
22173 (move-beginning-of-line 2)))))
22176 ;;; Filling
22178 ;; We use our own fill-paragraph and auto-fill functions.
22180 ;; `org-fill-paragraph' relies on adaptive filling and context
22181 ;; checking. Appropriate `fill-prefix' is computed with
22182 ;; `org-adaptive-fill-function'.
22184 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22185 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22186 ;; `org-adaptive-fill-function' value. Internally,
22187 ;; `org-comment-line-break-function' breaks the line.
22189 ;; `org-setup-filling' installs filling and auto-filling related
22190 ;; variables during `org-mode' initialization.
22192 (defvar org-element-paragraph-separate) ; org-element.el
22193 (defun org-setup-filling ()
22194 (require 'org-element)
22195 ;; Prevent auto-fill from inserting unwanted new items.
22196 (when (boundp 'fill-nobreak-predicate)
22197 (org-set-local
22198 'fill-nobreak-predicate
22199 (org-uniquify
22200 (append fill-nobreak-predicate
22201 '(org-fill-line-break-nobreak-p
22202 org-fill-paragraph-with-timestamp-nobreak-p)))))
22203 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22204 (org-set-local 'paragraph-start paragraph-ending)
22205 (org-set-local 'paragraph-separate paragraph-ending))
22206 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22207 (org-set-local 'auto-fill-inhibit-regexp nil)
22208 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22209 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22210 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22212 (defun org-fill-line-break-nobreak-p ()
22213 "Non-nil when a new line at point would create an Org line break."
22214 (save-excursion
22215 (skip-chars-backward "[ \t]")
22216 (skip-chars-backward "\\\\")
22217 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22219 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22220 "Non-nil when a new line at point would split a timestamp."
22221 (and (org-at-timestamp-p t)
22222 (not (looking-at org-ts-regexp-both))))
22224 (declare-function message-in-body-p "message" ())
22225 (defvar orgtbl-line-start-regexp) ; From org-table.el
22226 (defun org-adaptive-fill-function ()
22227 "Compute a fill prefix for the current line.
22228 Return fill prefix, as a string, or nil if current line isn't
22229 meant to be filled. For convenience, if `adaptive-fill-regexp'
22230 matches in paragraphs or comments, use it."
22231 (catch 'exit
22232 (when (derived-mode-p 'message-mode)
22233 (save-excursion
22234 (beginning-of-line)
22235 (cond ((or (not (message-in-body-p))
22236 (looking-at orgtbl-line-start-regexp))
22237 (throw 'exit nil))
22238 ((looking-at message-cite-prefix-regexp)
22239 (throw 'exit (match-string-no-properties 0)))
22240 ((looking-at org-outline-regexp)
22241 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22242 (org-with-wide-buffer
22243 (let* ((p (line-beginning-position))
22244 (element (save-excursion
22245 (beginning-of-line)
22246 (or (ignore-errors (org-element-at-point))
22247 (user-error "An element cannot be parsed line %d"
22248 (line-number-at-pos (point))))))
22249 (type (org-element-type element))
22250 (post-affiliated (org-element-property :post-affiliated element)))
22251 (unless (and post-affiliated (< p post-affiliated))
22252 (case type
22253 (comment
22254 (save-excursion
22255 (beginning-of-line)
22256 (looking-at "[ \t]*")
22257 (concat (match-string 0) "# ")))
22258 (footnote-definition "")
22259 ((item plain-list)
22260 (make-string (org-list-item-body-column
22261 (or post-affiliated
22262 (org-element-property :begin element)))
22263 ? ))
22264 (paragraph
22265 ;; Fill prefix is usually the same as the current line,
22266 ;; unless the paragraph is at the beginning of an item.
22267 (let ((parent (org-element-property :parent element)))
22268 (save-excursion
22269 (beginning-of-line)
22270 (cond ((eq (org-element-type parent) 'item)
22271 (make-string (org-list-item-body-column
22272 (org-element-property :begin parent))
22273 ? ))
22274 ((and adaptive-fill-regexp
22275 ;; Locally disable
22276 ;; `adaptive-fill-function' to let
22277 ;; `fill-context-prefix' handle
22278 ;; `adaptive-fill-regexp' variable.
22279 (let (adaptive-fill-function)
22280 (fill-context-prefix
22281 post-affiliated
22282 (org-element-property :end element)))))
22283 ((looking-at "[ \t]+") (match-string 0))
22284 (t "")))))
22285 (comment-block
22286 ;; Only fill contents if P is within block boundaries.
22287 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22288 (forward-line)
22289 (point)))
22290 (cend (save-excursion
22291 (goto-char (org-element-property :end element))
22292 (skip-chars-backward " \r\t\n")
22293 (line-beginning-position))))
22294 (when (and (>= p cbeg) (< p cend))
22295 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22296 (match-string 0)
22297 ""))))))))))
22299 (declare-function message-goto-body "message" ())
22300 (defvar message-cite-prefix-regexp) ; From message.el
22301 (defun org-fill-paragraph (&optional justify)
22302 "Fill element at point, when applicable.
22304 This function only applies to comment blocks, comments, example
22305 blocks and paragraphs. Also, as a special case, re-align table
22306 when point is at one.
22308 If JUSTIFY is non-nil (interactively, with prefix argument),
22309 justify as well. If `sentence-end-double-space' is non-nil, then
22310 period followed by one space does not end a sentence, so don't
22311 break a line there. The variable `fill-column' controls the
22312 width for filling.
22314 For convenience, when point is at a plain list, an item or
22315 a footnote definition, try to fill the first paragraph within."
22316 (interactive)
22317 (if (and (derived-mode-p 'message-mode)
22318 (or (not (message-in-body-p))
22319 (save-excursion (move-beginning-of-line 1)
22320 (looking-at message-cite-prefix-regexp))))
22321 ;; First ensure filling is correct in message-mode.
22322 (let ((fill-paragraph-function
22323 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22324 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22325 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22326 (paragraph-separate
22327 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22328 (fill-paragraph nil))
22329 (with-syntax-table org-mode-transpose-word-syntax-table
22330 ;; Move to end of line in order to get the first paragraph
22331 ;; within a plain list or a footnote definition.
22332 (let ((element (save-excursion
22333 (end-of-line)
22334 (or (ignore-errors (org-element-at-point))
22335 (user-error "An element cannot be parsed line %d"
22336 (line-number-at-pos (point)))))))
22337 ;; First check if point is in a blank line at the beginning of
22338 ;; the buffer. In that case, ignore filling.
22339 (case (org-element-type element)
22340 ;; Use major mode filling function is src blocks.
22341 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22342 ;; Align Org tables, leave table.el tables as-is.
22343 (table-row (org-table-align) t)
22344 (table
22345 (when (eq (org-element-property :type element) 'org)
22346 (save-excursion
22347 (goto-char (org-element-property :post-affiliated element))
22348 (org-table-align)))
22350 (paragraph
22351 ;; Paragraphs may contain `line-break' type objects.
22352 (let ((beg (max (point-min)
22353 (org-element-property :contents-begin element)))
22354 (end (min (point-max)
22355 (org-element-property :contents-end element))))
22356 ;; Do nothing if point is at an affiliated keyword.
22357 (if (< (line-end-position) beg) t
22358 (when (derived-mode-p 'message-mode)
22359 ;; In `message-mode', do not fill following citation
22360 ;; in current paragraph nor text before message body.
22361 (let ((body-start (save-excursion (message-goto-body))))
22362 (when body-start (setq beg (max body-start beg))))
22363 (when (save-excursion
22364 (re-search-forward
22365 (concat "^" message-cite-prefix-regexp) end t))
22366 (setq end (match-beginning 0))))
22367 ;; Fill paragraph, taking line breaks into account.
22368 ;; For that, slice the paragraph using line breaks as
22369 ;; separators, and fill the parts in reverse order to
22370 ;; avoid messing with markers.
22371 (save-excursion
22372 (goto-char end)
22373 (mapc
22374 (lambda (pos)
22375 (fill-region-as-paragraph pos (point) justify)
22376 (goto-char pos))
22377 ;; Find the list of ending positions for line breaks
22378 ;; in the current paragraph. Add paragraph
22379 ;; beginning to include first slice.
22380 (nreverse
22381 (cons beg
22382 (org-element-map
22383 (org-element--parse-objects
22384 beg end nil (org-element-restriction 'paragraph))
22385 'line-break
22386 (lambda (lb) (org-element-property :end lb)))))))
22387 t)))
22388 ;; Contents of `comment-block' type elements should be
22389 ;; filled as plain text, but only if point is within block
22390 ;; markers.
22391 (comment-block
22392 (let* ((case-fold-search t)
22393 (beg (save-excursion
22394 (goto-char (org-element-property :begin element))
22395 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22396 (forward-line)
22397 (point)))
22398 (end (save-excursion
22399 (goto-char (org-element-property :end element))
22400 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22401 (line-beginning-position))))
22402 (if (or (< (point) beg) (> (point) end)) t
22403 (fill-region-as-paragraph
22404 (save-excursion (end-of-line)
22405 (re-search-backward "^[ \t]*$" beg 'move)
22406 (line-beginning-position))
22407 (save-excursion (beginning-of-line)
22408 (re-search-forward "^[ \t]*$" end 'move)
22409 (line-beginning-position))
22410 justify))))
22411 ;; Fill comments.
22412 (comment
22413 (let ((begin (org-element-property :post-affiliated element))
22414 (end (org-element-property :end element)))
22415 (when (and (>= (point) begin) (<= (point) end))
22416 (let ((begin (save-excursion
22417 (end-of-line)
22418 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22419 (progn (forward-line) (point))
22420 begin)))
22421 (end (save-excursion
22422 (end-of-line)
22423 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22424 (1- (line-beginning-position))
22425 (skip-chars-backward " \r\t\n")
22426 (line-end-position)))))
22427 ;; Do not fill comments when at a blank line.
22428 (when (> end begin)
22429 (let ((fill-prefix
22430 (save-excursion
22431 (beginning-of-line)
22432 (looking-at "[ \t]*#")
22433 (let ((comment-prefix (match-string 0)))
22434 (goto-char (match-end 0))
22435 (if (looking-at adaptive-fill-regexp)
22436 (concat comment-prefix (match-string 0))
22437 (concat comment-prefix " "))))))
22438 (save-excursion
22439 (fill-region-as-paragraph begin end justify))))))
22441 ;; Ignore every other element.
22442 (otherwise t))))))
22444 (defun org-auto-fill-function ()
22445 "Auto-fill function."
22446 ;; Check if auto-filling is meaningful.
22447 (let ((fc (current-fill-column)))
22448 (when (and fc (> (current-column) fc))
22449 (let* ((fill-prefix (org-adaptive-fill-function))
22450 ;; Enforce empty fill prefix, if required. Otherwise, it
22451 ;; will be computed again.
22452 (adaptive-fill-mode (not (equal fill-prefix ""))))
22453 (when fill-prefix (do-auto-fill))))))
22455 (defun org-comment-line-break-function (&optional soft)
22456 "Break line at point and indent, continuing comment if within one.
22457 The inserted newline is marked hard if variable
22458 `use-hard-newlines' is true, unless optional argument SOFT is
22459 non-nil."
22460 (if soft (insert-and-inherit ?\n) (newline 1))
22461 (save-excursion (forward-char -1) (delete-horizontal-space))
22462 (delete-horizontal-space)
22463 (indent-to-left-margin)
22464 (insert-before-markers-and-inherit fill-prefix))
22467 ;;; Comments
22469 ;; Org comments syntax is quite complex. It requires the entire line
22470 ;; to be just a comment. Also, even with the right syntax at the
22471 ;; beginning of line, some some elements (i.e. verse-block or
22472 ;; example-block) don't accept comments. Usual Emacs comment commands
22473 ;; cannot cope with those requirements. Therefore, Org replaces them.
22475 ;; Org still relies on `comment-dwim', but cannot trust
22476 ;; `comment-only-p'. So, `comment-region-function' and
22477 ;; `uncomment-region-function' both point
22478 ;; to`org-comment-or-uncomment-region'. Eventually,
22479 ;; `org-insert-comment' takes care of insertion of comments at the
22480 ;; beginning of line.
22482 ;; `org-setup-comments-handling' install comments related variables
22483 ;; during `org-mode' initialization.
22485 (defun org-setup-comments-handling ()
22486 (interactive)
22487 (org-set-local 'comment-use-syntax nil)
22488 (org-set-local 'comment-start "# ")
22489 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22490 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22491 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22492 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22494 (defun org-insert-comment ()
22495 "Insert an empty comment above current line.
22496 If the line is empty, insert comment at its beginning."
22497 (beginning-of-line)
22498 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22499 (org-indent-line)
22500 (insert "# "))
22502 (defvar comment-empty-lines) ; From newcomment.el.
22503 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22504 "Comment or uncomment each non-blank line in the region.
22505 Uncomment each non-blank line between BEG and END if it only
22506 contains commented lines. Otherwise, comment them."
22507 (save-restriction
22508 ;; Restrict region
22509 (narrow-to-region (save-excursion (goto-char beg)
22510 (skip-chars-forward " \r\t\n" end)
22511 (line-beginning-position))
22512 (save-excursion (goto-char end)
22513 (skip-chars-backward " \r\t\n" beg)
22514 (line-end-position)))
22515 (let ((uncommentp
22516 ;; UNCOMMENTP is non-nil when every non blank line between
22517 ;; BEG and END is a comment.
22518 (save-excursion
22519 (goto-char (point-min))
22520 (while (and (not (eobp))
22521 (let ((element (org-element-at-point)))
22522 (and (eq (org-element-type element) 'comment)
22523 (goto-char (min (point-max)
22524 (org-element-property
22525 :end element)))))))
22526 (eobp))))
22527 (if uncommentp
22528 ;; Only blank lines and comments in region: uncomment it.
22529 (save-excursion
22530 (goto-char (point-min))
22531 (while (not (eobp))
22532 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22533 (replace-match "" nil nil nil 1))
22534 (forward-line)))
22535 ;; Comment each line in region.
22536 (let ((min-indent (point-max)))
22537 ;; First find the minimum indentation across all lines.
22538 (save-excursion
22539 (goto-char (point-min))
22540 (while (and (not (eobp)) (not (zerop min-indent)))
22541 (unless (looking-at "[ \t]*$")
22542 (setq min-indent (min min-indent (current-indentation))))
22543 (forward-line)))
22544 ;; Then loop over all lines.
22545 (save-excursion
22546 (goto-char (point-min))
22547 (while (not (eobp))
22548 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22549 ;; Don't get fooled by invisible text (e.g. link path)
22550 ;; when moving to column MIN-INDENT.
22551 (let ((buffer-invisibility-spec nil))
22552 (org-move-to-column min-indent t))
22553 (insert comment-start))
22554 (forward-line))))))))
22557 ;;; Planning
22559 ;; This section contains tools to operate on timestamp objects, as
22560 ;; returned by, e.g. `org-element-context'.
22562 (defun org-timestamp-has-time-p (timestamp)
22563 "Non-nil when TIMESTAMP has a time specified."
22564 (org-element-property :hour-start timestamp))
22566 (defun org-timestamp-format (timestamp format &optional end utc)
22567 "Format a TIMESTAMP element into a string.
22569 FORMAT is a format specifier to be passed to
22570 `format-time-string'.
22572 When optional argument END is non-nil, use end of date-range or
22573 time-range, if possible.
22575 When optional argument UTC is non-nil, time will be expressed as
22576 Universal Time."
22577 (format-time-string
22578 format
22579 (apply 'encode-time
22580 (cons 0
22581 (mapcar
22582 (lambda (prop) (or (org-element-property prop timestamp) 0))
22583 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22584 '(:minute-start :hour-start :day-start :month-start
22585 :year-start)))))
22586 utc))
22588 (defun org-timestamp-split-range (timestamp &optional end)
22589 "Extract a timestamp object from a date or time range.
22591 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22592 the end of the range. Otherwise, extract its start.
22594 Return a new timestamp object sharing the same parent as
22595 TIMESTAMP."
22596 (let ((type (org-element-property :type timestamp)))
22597 (if (memq type '(active inactive diary)) timestamp
22598 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22599 ;; Set new type.
22600 (org-element-put-property
22601 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22602 ;; Copy start properties over end properties if END is
22603 ;; non-nil. Otherwise, copy end properties over `start' ones.
22604 (let ((p-alist '((:minute-start . :minute-end)
22605 (:hour-start . :hour-end)
22606 (:day-start . :day-end)
22607 (:month-start . :month-end)
22608 (:year-start . :year-end))))
22609 (dolist (p-cell p-alist)
22610 (org-element-put-property
22611 split-ts
22612 (funcall (if end 'car 'cdr) p-cell)
22613 (org-element-property
22614 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22615 ;; Eventually refresh `:raw-value'.
22616 (org-element-put-property split-ts :raw-value nil)
22617 (org-element-put-property
22618 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22620 (defun org-timestamp-translate (timestamp &optional boundary)
22621 "Apply `org-translate-time' on a TIMESTAMP object.
22622 When optional argument BOUNDARY is non-nil, it is either the
22623 symbol `start' or `end'. In this case, only translate the
22624 starting or ending part of TIMESTAMP if it is a date or time
22625 range. Otherwise, translate both parts."
22626 (if (and (not boundary)
22627 (memq (org-element-property :type timestamp)
22628 '(active-range inactive-range)))
22629 (concat
22630 (org-translate-time
22631 (org-element-property :raw-value
22632 (org-timestamp-split-range timestamp)))
22633 "--"
22634 (org-translate-time
22635 (org-element-property :raw-value
22636 (org-timestamp-split-range timestamp t))))
22637 (org-translate-time
22638 (org-element-property
22639 :raw-value
22640 (if (not boundary) timestamp
22641 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22645 ;;; Other stuff.
22647 (defun org-toggle-fixed-width-section (arg)
22648 "Toggle the fixed-width export.
22649 If there is no active region, the QUOTE keyword at the current headline is
22650 inserted or removed. When present, it causes the text between this headline
22651 and the next to be exported as fixed-width text, and unmodified.
22652 If there is an active region, this command adds or removes a colon as the
22653 first character of this line. If the first character of a line is a colon,
22654 this line is also exported in fixed-width font."
22655 (interactive "P")
22656 (let* ((cc 0)
22657 (regionp (org-region-active-p))
22658 (beg (if regionp (region-beginning) (point)))
22659 (end (if regionp (region-end)))
22660 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22661 (case-fold-search nil)
22662 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22663 off)
22664 (if regionp
22665 (save-excursion
22666 (goto-char beg)
22667 (setq cc (current-column))
22668 (beginning-of-line 1)
22669 (setq off (looking-at re))
22670 (while (> nlines 0)
22671 (setq nlines (1- nlines))
22672 (beginning-of-line 1)
22673 (cond
22674 (arg
22675 (org-move-to-column cc t)
22676 (insert ": \n")
22677 (forward-line -1))
22678 ((and off (looking-at re))
22679 (replace-match "" t t nil 1))
22680 ((not off) (org-move-to-column cc t) (insert ": ")))
22681 (forward-line 1)))
22682 (save-excursion
22683 (org-back-to-heading)
22684 (cond
22685 ((looking-at (format org-heading-keyword-regexp-format
22686 org-quote-string))
22687 (goto-char (match-end 1))
22688 (looking-at (concat " +" org-quote-string))
22689 (replace-match "" t t)
22690 (when (eolp) (insert " ")))
22691 ((looking-at org-outline-regexp)
22692 (goto-char (match-end 0))
22693 (insert org-quote-string " ")))))))
22695 (defun org-reftex-citation ()
22696 "Use reftex-citation to insert a citation into the buffer.
22697 This looks for a line like
22699 #+BIBLIOGRAPHY: foo plain option:-d
22701 and derives from it that foo.bib is the bibliography file relevant
22702 for this document. It then installs the necessary environment for RefTeX
22703 to work in this buffer and calls `reftex-citation' to insert a citation
22704 into the buffer.
22706 Export of such citations to both LaTeX and HTML is handled by the contributed
22707 package ox-bibtex by Taru Karttunen."
22708 (interactive)
22709 (let ((reftex-docstruct-symbol 'rds)
22710 (reftex-cite-format "\\cite{%l}")
22711 rds bib)
22712 (save-excursion
22713 (save-restriction
22714 (widen)
22715 (let ((case-fold-search t)
22716 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22717 (if (not (save-excursion
22718 (or (re-search-forward re nil t)
22719 (re-search-backward re nil t))))
22720 (error "No bibliography defined in file")
22721 (setq bib (concat (match-string 1) ".bib")
22722 rds (list (list 'bib bib)))))))
22723 (call-interactively 'reftex-citation)))
22725 ;;;; Functions extending outline functionality
22727 (defun org-beginning-of-line (&optional arg)
22728 "Go to the beginning of the current line. If that is invisible, continue
22729 to a visible line beginning. This makes the function of C-a more intuitive.
22730 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22731 first attempt, and only move to after the tags when the cursor is already
22732 beyond the end of the headline."
22733 (interactive "P")
22734 (let ((pos (point))
22735 (special (if (consp org-special-ctrl-a/e)
22736 (car org-special-ctrl-a/e)
22737 org-special-ctrl-a/e))
22738 deactivate-mark refpos)
22739 (if (org-bound-and-true-p visual-line-mode)
22740 (beginning-of-visual-line 1)
22741 (beginning-of-line 1))
22742 (if (and arg (fboundp 'move-beginning-of-line))
22743 (call-interactively 'move-beginning-of-line)
22744 (if (bobp)
22746 (backward-char 1)
22747 (if (org-truely-invisible-p)
22748 (while (and (not (bobp)) (org-truely-invisible-p))
22749 (backward-char 1)
22750 (beginning-of-line 1))
22751 (forward-char 1))))
22752 (when special
22753 (cond
22754 ((and (looking-at org-complex-heading-regexp)
22755 (= (char-after (match-end 1)) ?\ ))
22756 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22757 (point-at-eol)))
22758 (goto-char
22759 (if (eq special t)
22760 (cond ((> pos refpos) refpos)
22761 ((= pos (point)) refpos)
22762 (t (point)))
22763 (cond ((> pos (point)) (point))
22764 ((not (eq last-command this-command)) (point))
22765 (t refpos)))))
22766 ((org-at-item-p)
22767 ;; Being at an item and not looking at an the item means point
22768 ;; was previously moved to beginning of a visual line, which
22769 ;; doesn't contain the item. Therefore, do nothing special,
22770 ;; just stay here.
22771 (when (looking-at org-list-full-item-re)
22772 ;; Set special position at first white space character after
22773 ;; bullet, and check-box, if any.
22774 (let ((after-bullet
22775 (let ((box (match-end 3)))
22776 (if (not box) (match-end 1)
22777 (let ((after (char-after box)))
22778 (if (and after (= after ? )) (1+ box) box))))))
22779 ;; Special case: Move point to special position when
22780 ;; currently after it or at beginning of line.
22781 (if (eq special t)
22782 (when (or (> pos after-bullet) (= (point) pos))
22783 (goto-char after-bullet))
22784 ;; Reversed case: Move point to special position when
22785 ;; point was already at beginning of line and command is
22786 ;; repeated.
22787 (when (and (= (point) pos) (eq last-command this-command))
22788 (goto-char after-bullet))))))))
22789 (org-no-warnings
22790 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22791 (setq disable-point-adjustment
22792 (or (not (invisible-p (point)))
22793 (not (invisible-p (max (point-min) (1- (point))))))))
22795 (defun org-end-of-line (&optional arg)
22796 "Go to the end of the line.
22797 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22798 tags on the first attempt, and only move to after the tags when
22799 the cursor is already beyond the end of the headline."
22800 (interactive "P")
22801 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22802 org-special-ctrl-a/e))
22803 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22804 'end-of-visual-line)
22805 ((fboundp 'move-end-of-line) 'move-end-of-line)
22806 (t 'end-of-line)))
22807 deactivate-mark)
22808 (if (or (not special) arg) (call-interactively move-fun)
22809 (let* ((element (save-excursion (beginning-of-line)
22810 (org-element-at-point)))
22811 (type (org-element-type element)))
22812 (cond
22813 ((memq type '(headline inlinetask))
22814 (let ((pos (point)))
22815 (beginning-of-line 1)
22816 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22817 (if (eq special t)
22818 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22819 (goto-char (match-beginning 1))
22820 (goto-char (match-end 0)))
22821 (if (or (< pos (match-end 0))
22822 (not (eq this-command last-command)))
22823 (goto-char (match-end 0))
22824 (goto-char (match-beginning 1))))
22825 (call-interactively move-fun))))
22826 ((org-element-property :hiddenp element)
22827 ;; If element is hidden, `move-end-of-line' would put point
22828 ;; after it. Use `end-of-line' to stay on current line.
22829 (call-interactively 'end-of-line))
22830 (t (call-interactively move-fun)))))
22831 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22832 (setq disable-point-adjustment
22833 (or (not (invisible-p (point)))
22834 (not (invisible-p (max (point-min) (1- (point))))))))
22836 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22837 (define-key org-mode-map "\C-e" 'org-end-of-line)
22839 (defun org-backward-sentence (&optional arg)
22840 "Go to beginning of sentence, or beginning of table field.
22841 This will call `backward-sentence' or `org-table-beginning-of-field',
22842 depending on context."
22843 (interactive "P")
22844 (cond
22845 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22846 (t (call-interactively 'backward-sentence))))
22848 (defun org-forward-sentence (&optional arg)
22849 "Go to end of sentence, or end of table field.
22850 This will call `forward-sentence' or `org-table-end-of-field',
22851 depending on context."
22852 (interactive "P")
22853 (cond
22854 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22855 (t (call-interactively 'forward-sentence))))
22857 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22858 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22860 (defun org-kill-line (&optional arg)
22861 "Kill line, to tags or end of line."
22862 (interactive "P")
22863 (cond
22864 ((or (not org-special-ctrl-k)
22865 (bolp)
22866 (not (org-at-heading-p)))
22867 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22868 org-ctrl-k-protect-subtree)
22869 (if (or (eq org-ctrl-k-protect-subtree 'error)
22870 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22871 (user-error "C-k aborted as it would kill a hidden subtree")))
22872 (call-interactively
22873 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22874 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22875 (kill-region (point) (match-beginning 1))
22876 (org-set-tags nil t))
22877 (t (kill-region (point) (point-at-eol)))))
22879 (define-key org-mode-map "\C-k" 'org-kill-line)
22881 (defun org-yank (&optional arg)
22882 "Yank. If the kill is a subtree, treat it specially.
22883 This command will look at the current kill and check if is a single
22884 subtree, or a series of subtrees[1]. If it passes the test, and if the
22885 cursor is at the beginning of a line or after the stars of a currently
22886 empty headline, then the yank is handled specially. How exactly depends
22887 on the value of the following variables, both set by default.
22889 org-yank-folded-subtrees
22890 When set, the subtree(s) will be folded after insertion, but only
22891 if doing so would now swallow text after the yanked text.
22893 org-yank-adjusted-subtrees
22894 When set, the subtree will be promoted or demoted in order to
22895 fit into the local outline tree structure, which means that the level
22896 will be adjusted so that it becomes the smaller one of the two
22897 *visible* surrounding headings.
22899 Any prefix to this command will cause `yank' to be called directly with
22900 no special treatment. In particular, a simple \\[universal-argument] prefix \
22901 will just
22902 plainly yank the text as it is.
22904 \[1] The test checks if the first non-white line is a heading
22905 and if there are no other headings with fewer stars."
22906 (interactive "P")
22907 (org-yank-generic 'yank arg))
22909 (defun org-yank-generic (command arg)
22910 "Perform some yank-like command.
22912 This function implements the behavior described in the `org-yank'
22913 documentation. However, it has been generalized to work for any
22914 interactive command with similar behavior."
22916 ;; pretend to be command COMMAND
22917 (setq this-command command)
22919 (if arg
22920 (call-interactively command)
22922 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22923 (and (org-kill-is-subtree-p)
22924 (or (bolp)
22925 (and (looking-at "[ \t]*$")
22926 (string-match
22927 "\\`\\*+\\'"
22928 (buffer-substring (point-at-bol) (point)))))))
22929 swallowp)
22930 (cond
22931 ((and subtreep org-yank-folded-subtrees)
22932 (let ((beg (point))
22933 end)
22934 (if (and subtreep org-yank-adjusted-subtrees)
22935 (org-paste-subtree nil nil 'for-yank)
22936 (call-interactively command))
22938 (setq end (point))
22939 (goto-char beg)
22940 (when (and (bolp) subtreep
22941 (not (setq swallowp
22942 (org-yank-folding-would-swallow-text beg end))))
22943 (org-with-limited-levels
22944 (or (looking-at org-outline-regexp)
22945 (re-search-forward org-outline-regexp-bol end t))
22946 (while (and (< (point) end) (looking-at org-outline-regexp))
22947 (hide-subtree)
22948 (org-cycle-show-empty-lines 'folded)
22949 (condition-case nil
22950 (outline-forward-same-level 1)
22951 (error (goto-char end))))))
22952 (when swallowp
22953 (message
22954 "Inserted text not folded because that would swallow text"))
22956 (goto-char end)
22957 (skip-chars-forward " \t\n\r")
22958 (beginning-of-line 1)
22959 (push-mark beg 'nomsg)))
22960 ((and subtreep org-yank-adjusted-subtrees)
22961 (let ((beg (point-at-bol)))
22962 (org-paste-subtree nil nil 'for-yank)
22963 (push-mark beg 'nomsg)))
22965 (call-interactively command))))))
22967 (defun org-yank-folding-would-swallow-text (beg end)
22968 "Would hide-subtree at BEG swallow any text after END?"
22969 (let (level)
22970 (org-with-limited-levels
22971 (save-excursion
22972 (goto-char beg)
22973 (when (or (looking-at org-outline-regexp)
22974 (re-search-forward org-outline-regexp-bol end t))
22975 (setq level (org-outline-level)))
22976 (goto-char end)
22977 (skip-chars-forward " \t\r\n\v\f")
22978 (if (or (eobp)
22979 (and (bolp) (looking-at org-outline-regexp)
22980 (<= (org-outline-level) level)))
22981 nil ; Nothing would be swallowed
22982 t))))) ; something would swallow
22984 (define-key org-mode-map "\C-y" 'org-yank)
22986 (defun org-truely-invisible-p ()
22987 "Check if point is at a character currently not visible.
22988 This version does not only check the character property, but also
22989 `visible-mode'."
22990 ;; Early versions of noutline don't have `outline-invisible-p'.
22991 (if (org-bound-and-true-p visible-mode)
22993 (outline-invisible-p)))
22995 (defun org-invisible-p2 ()
22996 "Check if point is at a character currently not visible."
22997 (save-excursion
22998 (if (and (eolp) (not (bobp))) (backward-char 1))
22999 ;; Early versions of noutline don't have `outline-invisible-p'.
23000 (outline-invisible-p)))
23002 (defun org-back-to-heading (&optional invisible-ok)
23003 "Call `outline-back-to-heading', but provide a better error message."
23004 (condition-case nil
23005 (outline-back-to-heading invisible-ok)
23006 (error (error "Before first headline at position %d in buffer %s"
23007 (point) (current-buffer)))))
23009 (defun org-before-first-heading-p ()
23010 "Before first heading?"
23011 (save-excursion
23012 (end-of-line)
23013 (null (re-search-backward org-outline-regexp-bol nil t))))
23015 (defun org-at-heading-p (&optional ignored)
23016 (outline-on-heading-p t))
23017 ;; Compatibility alias with Org versions < 7.8.03
23018 (defalias 'org-on-heading-p 'org-at-heading-p)
23020 (defun org-at-comment-p nil
23021 "Is cursor in a line starting with a # character?"
23022 (save-excursion
23023 (beginning-of-line)
23024 (looking-at "^#")))
23026 (defun org-at-drawer-p nil
23027 "Is cursor at a drawer keyword?"
23028 (save-excursion
23029 (move-beginning-of-line 1)
23030 (looking-at org-drawer-regexp)))
23032 (defun org-at-block-p nil
23033 "Is cursor at a block keyword?"
23034 (save-excursion
23035 (move-beginning-of-line 1)
23036 (looking-at org-block-regexp)))
23038 (defun org-point-at-end-of-empty-headline ()
23039 "If point is at the end of an empty headline, return t, else nil.
23040 If the heading only contains a TODO keyword, it is still still considered
23041 empty."
23042 (and (looking-at "[ \t]*$")
23043 (when org-todo-line-regexp
23044 (save-excursion
23045 (beginning-of-line 1)
23046 (let ((case-fold-search nil))
23047 (looking-at org-todo-line-regexp)
23048 (string= (match-string 3) ""))))))
23050 (defun org-at-heading-or-item-p ()
23051 (or (org-at-heading-p) (org-at-item-p)))
23053 (defun org-at-target-p ()
23054 (or (org-in-regexp org-radio-target-regexp)
23055 (org-in-regexp org-target-regexp)))
23056 ;; Compatibility alias with Org versions < 7.8.03
23057 (defalias 'org-on-target-p 'org-at-target-p)
23059 (defun org-up-heading-all (arg)
23060 "Move to the heading line of which the present line is a subheading.
23061 This function considers both visible and invisible heading lines.
23062 With argument, move up ARG levels."
23063 (if (fboundp 'outline-up-heading-all)
23064 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23065 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23067 (defun org-up-heading-safe ()
23068 "Move to the heading line of which the present line is a subheading.
23069 This version will not throw an error. It will return the level of the
23070 headline found, or nil if no higher level is found.
23072 Also, this function will be a lot faster than `outline-up-heading',
23073 because it relies on stars being the outline starters. This can really
23074 make a significant difference in outlines with very many siblings."
23075 (let (start-level re)
23076 (org-back-to-heading t)
23077 (setq start-level (funcall outline-level))
23078 (if (equal start-level 1)
23080 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23081 (if (re-search-backward re nil t)
23082 (funcall outline-level)))))
23084 (defun org-first-sibling-p ()
23085 "Is this heading the first child of its parents?"
23086 (interactive)
23087 (let ((re org-outline-regexp-bol)
23088 level l)
23089 (unless (org-at-heading-p t)
23090 (user-error "Not at a heading"))
23091 (setq level (funcall outline-level))
23092 (save-excursion
23093 (if (not (re-search-backward re nil t))
23095 (setq l (funcall outline-level))
23096 (< l level)))))
23098 (defun org-goto-sibling (&optional previous)
23099 "Goto the next sibling, even if it is invisible.
23100 When PREVIOUS is set, go to the previous sibling instead. Returns t
23101 when a sibling was found. When none is found, return nil and don't
23102 move point."
23103 (let ((fun (if previous 're-search-backward 're-search-forward))
23104 (pos (point))
23105 (re org-outline-regexp-bol)
23106 level l)
23107 (when (condition-case nil (org-back-to-heading t) (error nil))
23108 (setq level (funcall outline-level))
23109 (catch 'exit
23110 (or previous (forward-char 1))
23111 (while (funcall fun re nil t)
23112 (setq l (funcall outline-level))
23113 (when (< l level) (goto-char pos) (throw 'exit nil))
23114 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23115 (goto-char pos)
23116 nil))))
23118 (defun org-show-siblings ()
23119 "Show all siblings of the current headline."
23120 (save-excursion
23121 (while (org-goto-sibling) (org-flag-heading nil)))
23122 (save-excursion
23123 (while (org-goto-sibling 'previous)
23124 (org-flag-heading nil))))
23126 (defun org-goto-first-child ()
23127 "Goto the first child, even if it is invisible.
23128 Return t when a child was found. Otherwise don't move point and
23129 return nil."
23130 (let (level (pos (point)) (re org-outline-regexp-bol))
23131 (when (condition-case nil (org-back-to-heading t) (error nil))
23132 (setq level (outline-level))
23133 (forward-char 1)
23134 (if (and (re-search-forward re nil t) (> (outline-level) level))
23135 (progn (goto-char (match-beginning 0)) t)
23136 (goto-char pos) nil))))
23138 (defun org-show-hidden-entry ()
23139 "Show an entry where even the heading is hidden."
23140 (save-excursion
23141 (org-show-entry)))
23143 (defun org-flag-heading (flag &optional entry)
23144 "Flag the current heading. FLAG non-nil means make invisible.
23145 When ENTRY is non-nil, show the entire entry."
23146 (save-excursion
23147 (org-back-to-heading t)
23148 ;; Check if we should show the entire entry
23149 (if entry
23150 (progn
23151 (org-show-entry)
23152 (save-excursion
23153 (and (outline-next-heading)
23154 (org-flag-heading nil))))
23155 (outline-flag-region (max (point-min) (1- (point)))
23156 (save-excursion (outline-end-of-heading) (point))
23157 flag))))
23159 (defun org-get-next-sibling ()
23160 "Move to next heading of the same level, and return point.
23161 If there is no such heading, return nil.
23162 This is like outline-next-sibling, but invisible headings are ok."
23163 (let ((level (funcall outline-level)))
23164 (outline-next-heading)
23165 (while (and (not (eobp)) (> (funcall outline-level) level))
23166 (outline-next-heading))
23167 (if (or (eobp) (< (funcall outline-level) level))
23169 (point))))
23171 (defun org-get-last-sibling ()
23172 "Move to previous heading of the same level, and return point.
23173 If there is no such heading, return nil."
23174 (let ((opoint (point))
23175 (level (funcall outline-level)))
23176 (outline-previous-heading)
23177 (when (and (/= (point) opoint) (outline-on-heading-p t))
23178 (while (and (> (funcall outline-level) level)
23179 (not (bobp)))
23180 (outline-previous-heading))
23181 (if (< (funcall outline-level) level)
23183 (point)))))
23185 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23186 "Goto to the end of a subtree."
23187 ;; This contains an exact copy of the original function, but it uses
23188 ;; `org-back-to-heading', to make it work also in invisible
23189 ;; trees. And is uses an invisible-ok argument.
23190 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23191 ;; Furthermore, when used inside Org, finding the end of a large subtree
23192 ;; with many children and grandchildren etc, this can be much faster
23193 ;; than the outline version.
23194 (org-back-to-heading invisible-ok)
23195 (let ((first t)
23196 (level (funcall outline-level)))
23197 (if (and (derived-mode-p 'org-mode) (< level 1000))
23198 ;; A true heading (not a plain list item), in Org-mode
23199 ;; This means we can easily find the end by looking
23200 ;; only for the right number of stars. Using a regexp to do
23201 ;; this is so much faster than using a Lisp loop.
23202 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23203 (forward-char 1)
23204 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23205 ;; something else, do it the slow way
23206 (while (and (not (eobp))
23207 (or first (> (funcall outline-level) level)))
23208 (setq first nil)
23209 (outline-next-heading)))
23210 (unless to-heading
23211 (if (memq (preceding-char) '(?\n ?\^M))
23212 (progn
23213 ;; Go to end of line before heading
23214 (forward-char -1)
23215 (if (memq (preceding-char) '(?\n ?\^M))
23216 ;; leave blank line before heading
23217 (forward-char -1))))))
23218 (point))
23220 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23221 "Use Org version in org-mode, for dramatic speed-up."
23222 (if (derived-mode-p 'org-mode)
23223 (progn
23224 (org-end-of-subtree nil t)
23225 (unless (eobp) (backward-char 1)))
23226 ad-do-it))
23228 (defun org-end-of-meta-data-and-drawers ()
23229 "Jump to the first text after meta data and drawers in the current entry.
23230 This will move over empty lines, lines with planning time stamps,
23231 clocking lines, and drawers."
23232 (org-back-to-heading t)
23233 (let ((end (save-excursion (outline-next-heading) (point)))
23234 (re (concat "\\(" org-drawer-regexp "\\)"
23235 "\\|" "[ \t]*" org-keyword-time-regexp)))
23236 (forward-line 1)
23237 (while (re-search-forward re end t)
23238 (if (not (match-end 1))
23239 ;; empty or planning line
23240 (forward-line 1)
23241 ;; a drawer, find the end
23242 (re-search-forward "^[ \t]*:END:" end 'move)
23243 (forward-line 1)))
23244 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23245 (point)))
23247 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23248 "Move forward to the ARG'th subheading at same level as this one.
23249 Stop at the first and last subheadings of a superior heading.
23250 Normally this only looks at visible headings, but when INVISIBLE-OK is
23251 non-nil it will also look at invisible ones."
23252 (interactive "p")
23253 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23254 (if (and arg (< arg 0))
23255 (goto-char (point-min))
23256 (outline-next-heading))
23257 (org-at-heading-p)
23258 (let ((level (- (match-end 0) (match-beginning 0) 1))
23259 (f (if (and arg (< arg 0))
23260 're-search-backward
23261 're-search-forward))
23262 (count (if arg (abs arg) 1))
23263 (result (point)))
23264 (while (and (prog1 (> count 0)
23265 (forward-char (if (and arg (< arg 0)) -1 1)))
23266 (funcall f org-outline-regexp-bol nil 'move))
23267 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23268 (cond ((< l level) (setq count 0))
23269 ((and (= l level)
23270 (or invisible-ok
23271 (progn
23272 (goto-char (line-beginning-position))
23273 (not (outline-invisible-p)))))
23274 (setq count (1- count))
23275 (when (eq l level)
23276 (setq result (point)))))))
23277 (goto-char result))
23278 (beginning-of-line 1)))
23280 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23281 "Move backward to the ARG'th subheading at same level as this one.
23282 Stop at the first and last subheadings of a superior heading."
23283 (interactive "p")
23284 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23286 (defun org-next-block (arg &optional backward block-regexp)
23287 "Jump to the next block.
23288 With a prefix argument ARG, jump forward ARG many source blocks.
23289 When BACKWARD is non-nil, jump to the previous block.
23290 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23291 (interactive "p")
23292 (let ((re (or block-regexp org-block-regexp))
23293 (re-search-fn (or (and backward 're-search-backward)
23294 're-search-forward)))
23295 (if (looking-at re) (forward-char 1))
23296 (condition-case nil
23297 (funcall re-search-fn re nil nil arg)
23298 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23299 (goto-char (match-beginning 0)) (org-show-context)))
23301 (defun org-previous-block (arg &optional block-regexp)
23302 "Jump to the previous block.
23303 With a prefix argument ARG, jump backward ARG many source blocks.
23304 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23305 (interactive "p")
23306 (org-next-block arg t block-regexp))
23308 (defun org-forward-paragraph ()
23309 "Move forward to beginning of next paragraph or equivalent.
23311 The function moves point to the beginning of the next visible
23312 structural element, which can be a paragraph, a table, a list
23313 item, etc. It also provides some special moves for convenience:
23315 - On an affiliated keyword, jump to the beginning of the
23316 relative element.
23317 - On an item or a footnote definition, move to the second
23318 element inside, if any.
23319 - On a table or a property drawer, jump after it.
23320 - On a verse or source block, stop after blank lines."
23321 (interactive)
23322 (when (eobp) (user-error "Cannot move further down"))
23323 (let* ((deactivate-mark nil)
23324 (element (org-element-at-point))
23325 (type (org-element-type element))
23326 (post-affiliated (org-element-property :post-affiliated element))
23327 (contents-begin (org-element-property :contents-begin element))
23328 (contents-end (org-element-property :contents-end element))
23329 (end (let ((end (org-element-property :end element)) (parent element))
23330 (while (and (setq parent (org-element-property :parent parent))
23331 (= (org-element-property :contents-end parent) end))
23332 (setq end (org-element-property :end parent)))
23333 end)))
23334 (cond ((not element)
23335 (skip-chars-forward " \r\t\n")
23336 (or (eobp) (beginning-of-line)))
23337 ;; On affiliated keywords, move to element's beginning.
23338 ((and post-affiliated (< (point) post-affiliated))
23339 (goto-char post-affiliated))
23340 ;; At a table row, move to the end of the table. Similarly,
23341 ;; at a node property, move to the end of the property
23342 ;; drawer.
23343 ((memq type '(node-property table-row))
23344 (goto-char (org-element-property
23345 :end (org-element-property :parent element))))
23346 ((memq type '(property-drawer table)) (goto-char end))
23347 ;; Consider blank lines as separators in verse and source
23348 ;; blocks to ease editing.
23349 ((memq type '(src-block verse-block))
23350 (when (eq type 'src-block)
23351 (setq contents-end
23352 (save-excursion (goto-char end)
23353 (skip-chars-backward " \r\t\n")
23354 (line-beginning-position))))
23355 (beginning-of-line)
23356 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23357 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23358 (goto-char end)
23359 (skip-chars-forward " \r\t\n")
23360 (if (= (point) contents-end) (goto-char end)
23361 (beginning-of-line))))
23362 ;; With no contents, just skip element.
23363 ((not contents-begin) (goto-char end))
23364 ;; If contents are invisible, skip the element altogether.
23365 ((outline-invisible-p (line-end-position))
23366 (case type
23367 (headline
23368 (org-with-limited-levels (outline-next-visible-heading 1)))
23369 ;; At a plain list, make sure we move to the next item
23370 ;; instead of skipping the whole list.
23371 (plain-list (forward-char)
23372 (org-forward-paragraph))
23373 (otherwise (goto-char end))))
23374 ((>= (point) contents-end) (goto-char end))
23375 ((>= (point) contents-begin)
23376 ;; This can only happen on paragraphs and plain lists.
23377 (case type
23378 (paragraph (goto-char end))
23379 ;; At a plain list, try to move to second element in
23380 ;; first item, if possible.
23381 (plain-list (end-of-line)
23382 (org-forward-paragraph))))
23383 ;; When contents start on the middle of a line (e.g. in
23384 ;; items and footnote definitions), try to reach first
23385 ;; element starting after current line.
23386 ((> (line-end-position) contents-begin)
23387 (end-of-line)
23388 (org-forward-paragraph))
23389 (t (goto-char contents-begin)))))
23391 (defun org-backward-paragraph ()
23392 "Move backward to start of previous paragraph or equivalent.
23394 The function moves point to the beginning of the current
23395 structural element, which can be a paragraph, a table, a list
23396 item, etc., or to the beginning of the previous visible one if
23397 point is already there. It also provides some special moves for
23398 convenience:
23400 - On an affiliated keyword, jump to the first one.
23401 - On a table or a property drawer, move to its beginning.
23402 - On a verse or source block, stop before blank lines."
23403 (interactive)
23404 (when (bobp) (user-error "Cannot move further up"))
23405 (let* ((deactivate-mark nil)
23406 (element (org-element-at-point))
23407 (type (org-element-type element))
23408 (contents-begin (org-element-property :contents-begin element))
23409 (contents-end (org-element-property :contents-end element))
23410 (post-affiliated (org-element-property :post-affiliated element))
23411 (begin (org-element-property :begin element)))
23412 (cond
23413 ((not element) (goto-char (point-min)))
23414 ((= (point) begin)
23415 (backward-char)
23416 (org-backward-paragraph))
23417 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23418 ((memq type '(node-property table-row))
23419 (goto-char (org-element-property
23420 :post-affiliated (org-element-property :parent element))))
23421 ((memq type '(property-drawer table)) (goto-char begin))
23422 ((memq type '(src-block verse-block))
23423 (when (eq type 'src-block)
23424 (setq contents-begin
23425 (save-excursion (goto-char begin) (forward-line) (point))))
23426 (if (= (point) contents-begin) (goto-char post-affiliated)
23427 ;; Inside a verse block, see blank lines as paragraph
23428 ;; separators.
23429 (let ((origin (point)))
23430 (skip-chars-backward " \r\t\n" contents-begin)
23431 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23432 (skip-chars-forward " \r\t\n" origin)
23433 (if (= (point) origin) (goto-char contents-begin)
23434 (beginning-of-line))))))
23435 ((not contents-begin) (goto-char (or post-affiliated begin)))
23436 ((eq type 'paragraph)
23437 (goto-char contents-begin)
23438 ;; When at first paragraph in an item or a footnote definition,
23439 ;; move directly to beginning of line.
23440 (let ((parent-contents
23441 (org-element-property
23442 :contents-begin (org-element-property :parent element))))
23443 (when (and parent-contents (= parent-contents contents-begin))
23444 (beginning-of-line))))
23445 ;; At the end of a greater element, move to the beginning of the
23446 ;; last element within.
23447 ((>= (point) contents-end)
23448 (goto-char (1- contents-end))
23449 (org-backward-paragraph))
23450 (t (goto-char (or post-affiliated begin))))
23451 ;; Ensure we never leave point invisible.
23452 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23454 (defun org-forward-element ()
23455 "Move forward by one element.
23456 Move to the next element at the same level, when possible."
23457 (interactive)
23458 (cond ((eobp) (user-error "Cannot move further down"))
23459 ((org-with-limited-levels (org-at-heading-p))
23460 (let ((origin (point)))
23461 (goto-char (org-end-of-subtree nil t))
23462 (unless (org-with-limited-levels (org-at-heading-p))
23463 (goto-char origin)
23464 (user-error "Cannot move further down"))))
23466 (let* ((elem (org-element-at-point))
23467 (end (org-element-property :end elem))
23468 (parent (org-element-property :parent elem)))
23469 (cond ((and parent (= (org-element-property :contents-end parent) end))
23470 (goto-char (org-element-property :end parent)))
23471 ((integer-or-marker-p end) (goto-char end))
23472 (t (message "No element at point")))))))
23474 (defun org-backward-element ()
23475 "Move backward by one element.
23476 Move to the previous element at the same level, when possible."
23477 (interactive)
23478 (cond ((bobp) (user-error "Cannot move further up"))
23479 ((org-with-limited-levels (org-at-heading-p))
23480 ;; At a headline, move to the previous one, if any, or stay
23481 ;; here.
23482 (let ((origin (point)))
23483 (org-with-limited-levels (org-backward-heading-same-level 1))
23484 ;; When current headline has no sibling above, move to its
23485 ;; parent.
23486 (when (= (point) origin)
23487 (or (org-with-limited-levels (org-up-heading-safe))
23488 (progn (goto-char origin)
23489 (user-error "Cannot move further up"))))))
23491 (let* ((trail (org-element-at-point 'keep-trail))
23492 (elem (car trail))
23493 (prev-elem (nth 1 trail))
23494 (beg (org-element-property :begin elem)))
23495 (cond
23496 ;; Move to beginning of current element if point isn't
23497 ;; there already.
23498 ((null beg) (message "No element at point"))
23499 ((/= (point) beg) (goto-char beg))
23500 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23501 ((org-before-first-heading-p) (goto-char (point-min)))
23502 (t (org-back-to-heading)))))))
23504 (defun org-up-element ()
23505 "Move to upper element."
23506 (interactive)
23507 (if (org-with-limited-levels (org-at-heading-p))
23508 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23509 (let* ((elem (org-element-at-point))
23510 (parent (org-element-property :parent elem)))
23511 (if parent (goto-char (org-element-property :begin parent))
23512 (if (org-with-limited-levels (org-before-first-heading-p))
23513 (user-error "No surrounding element")
23514 (org-with-limited-levels (org-back-to-heading)))))))
23516 (defvar org-element-greater-elements)
23517 (defun org-down-element ()
23518 "Move to inner element."
23519 (interactive)
23520 (let ((element (org-element-at-point)))
23521 (cond
23522 ((memq (org-element-type element) '(plain-list table))
23523 (goto-char (org-element-property :contents-begin element))
23524 (forward-char))
23525 ((memq (org-element-type element) org-element-greater-elements)
23526 ;; If contents are hidden, first disclose them.
23527 (when (org-element-property :hiddenp element) (org-cycle))
23528 (goto-char (or (org-element-property :contents-begin element)
23529 (user-error "No content for this element"))))
23530 (t (user-error "No inner element")))))
23532 (defun org-drag-element-backward ()
23533 "Move backward element at point."
23534 (interactive)
23535 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23536 (let* ((trail (org-element-at-point 'keep-trail))
23537 (elem (car trail))
23538 (prev-elem (nth 1 trail)))
23539 ;; Error out if no previous element or previous element is
23540 ;; a parent of the current one.
23541 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23542 (user-error "Cannot drag element backward")
23543 (let ((pos (point)))
23544 (org-element-swap-A-B prev-elem elem)
23545 (goto-char (+ (org-element-property :begin prev-elem)
23546 (- pos (org-element-property :begin elem)))))))))
23548 (defun org-drag-element-forward ()
23549 "Move forward element at point."
23550 (interactive)
23551 (let* ((pos (point))
23552 (elem (org-element-at-point)))
23553 (when (= (point-max) (org-element-property :end elem))
23554 (user-error "Cannot drag element forward"))
23555 (goto-char (org-element-property :end elem))
23556 (let ((next-elem (org-element-at-point)))
23557 (when (or (org-element-nested-p elem next-elem)
23558 (and (eq (org-element-type next-elem) 'headline)
23559 (not (eq (org-element-type elem) 'headline))))
23560 (goto-char pos)
23561 (user-error "Cannot drag element forward"))
23562 ;; Compute new position of point: it's shifted by NEXT-ELEM
23563 ;; body's length (without final blanks) and by the length of
23564 ;; blanks between ELEM and NEXT-ELEM.
23565 (let ((size-next (- (save-excursion
23566 (goto-char (org-element-property :end next-elem))
23567 (skip-chars-backward " \r\t\n")
23568 (forward-line)
23569 ;; Small correction if buffer doesn't end
23570 ;; with a newline character.
23571 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23572 (org-element-property :begin next-elem)))
23573 (size-blank (- (org-element-property :end elem)
23574 (save-excursion
23575 (goto-char (org-element-property :end elem))
23576 (skip-chars-backward " \r\t\n")
23577 (forward-line)
23578 (point)))))
23579 (org-element-swap-A-B elem next-elem)
23580 (goto-char (+ pos size-next size-blank))))))
23582 (defun org-drag-line-forward (arg)
23583 "Drag the line at point ARG lines forward."
23584 (interactive "p")
23585 (dotimes (n (abs arg))
23586 (let ((c (current-column)))
23587 (if (< 0 arg)
23588 (progn
23589 (beginning-of-line 2)
23590 (transpose-lines 1)
23591 (beginning-of-line 0))
23592 (transpose-lines 1)
23593 (beginning-of-line -1))
23594 (org-move-to-column c))))
23596 (defun org-drag-line-backward (arg)
23597 "Drag the line at point ARG lines backward."
23598 (interactive "p")
23599 (org-drag-line-forward (- arg)))
23601 (defun org-mark-element ()
23602 "Put point at beginning of this element, mark at end.
23604 Interactively, if this command is repeated or (in Transient Mark
23605 mode) if the mark is active, it marks the next element after the
23606 ones already marked."
23607 (interactive)
23608 (let (deactivate-mark)
23609 (if (and (org-called-interactively-p 'any)
23610 (or (and (eq last-command this-command) (mark t))
23611 (and transient-mark-mode mark-active)))
23612 (set-mark
23613 (save-excursion
23614 (goto-char (mark))
23615 (goto-char (org-element-property :end (org-element-at-point)))))
23616 (let ((element (org-element-at-point)))
23617 (end-of-line)
23618 (push-mark (org-element-property :end element) t t)
23619 (goto-char (org-element-property :begin element))))))
23621 (defun org-narrow-to-element ()
23622 "Narrow buffer to current element."
23623 (interactive)
23624 (let ((elem (org-element-at-point)))
23625 (cond
23626 ((eq (car elem) 'headline)
23627 (narrow-to-region
23628 (org-element-property :begin elem)
23629 (org-element-property :end elem)))
23630 ((memq (car elem) org-element-greater-elements)
23631 (narrow-to-region
23632 (org-element-property :contents-begin elem)
23633 (org-element-property :contents-end elem)))
23635 (narrow-to-region
23636 (org-element-property :begin elem)
23637 (org-element-property :end elem))))))
23639 (defun org-transpose-element ()
23640 "Transpose current and previous elements, keeping blank lines between.
23641 Point is moved after both elements."
23642 (interactive)
23643 (org-skip-whitespace)
23644 (let ((end (org-element-property :end (org-element-at-point))))
23645 (org-drag-element-backward)
23646 (goto-char end)))
23648 (defun org-unindent-buffer ()
23649 "Un-indent the visible part of the buffer.
23650 Relative indentation (between items, inside blocks, etc.) isn't
23651 modified."
23652 (interactive)
23653 (unless (eq major-mode 'org-mode)
23654 (user-error "Cannot un-indent a buffer not in Org mode"))
23655 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23656 unindent-tree ; For byte-compiler.
23657 (unindent-tree
23658 (function
23659 (lambda (contents)
23660 (mapc
23661 (lambda (element)
23662 (if (memq (org-element-type element) '(headline section))
23663 (funcall unindent-tree (org-element-contents element))
23664 (save-excursion
23665 (save-restriction
23666 (narrow-to-region
23667 (org-element-property :begin element)
23668 (org-element-property :end element))
23669 (org-do-remove-indentation)))))
23670 (reverse contents))))))
23671 (funcall unindent-tree (org-element-contents parse-tree))))
23673 (defun org-show-subtree ()
23674 "Show everything after this heading at deeper levels."
23675 (interactive)
23676 (outline-flag-region
23677 (point)
23678 (save-excursion
23679 (org-end-of-subtree t t))
23680 nil))
23682 (defun org-show-entry ()
23683 "Show the body directly following this heading.
23684 Show the heading too, if it is currently invisible."
23685 (interactive)
23686 (save-excursion
23687 (condition-case nil
23688 (progn
23689 (org-back-to-heading t)
23690 (outline-flag-region
23691 (max (point-min) (1- (point)))
23692 (save-excursion
23693 (if (re-search-forward
23694 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23695 (match-beginning 1)
23696 (point-max)))
23697 nil)
23698 (org-cycle-hide-drawers 'children))
23699 (error nil))))
23701 (defun org-make-options-regexp (kwds &optional extra)
23702 "Make a regular expression for keyword lines."
23703 (concat
23704 "^#\\+\\("
23705 (mapconcat 'regexp-quote kwds "\\|")
23706 (if extra (concat "\\|" extra))
23707 "\\):[ \t]*\\(.*\\)"))
23709 ;; Make isearch reveal the necessary context
23710 (defun org-isearch-end ()
23711 "Reveal context after isearch exits."
23712 (when isearch-success ; only if search was successful
23713 (if (featurep 'xemacs)
23714 ;; Under XEmacs, the hook is run in the correct place,
23715 ;; we directly show the context.
23716 (org-show-context 'isearch)
23717 ;; In Emacs the hook runs *before* restoring the overlays.
23718 ;; So we have to use a one-time post-command-hook to do this.
23719 ;; (Emacs 22 has a special variable, see function `org-mode')
23720 (unless (and (boundp 'isearch-mode-end-hook-quit)
23721 isearch-mode-end-hook-quit)
23722 ;; Only when the isearch was not quitted.
23723 (org-add-hook 'post-command-hook 'org-isearch-post-command
23724 'append 'local)))
23725 (org-fix-ellipsis-at-bol)))
23727 (defun org-isearch-post-command ()
23728 "Remove self from hook, and show context."
23729 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23730 (org-show-context 'isearch))
23733 ;;;; Integration with and fixes for other packages
23735 ;;; Imenu support
23737 (defvar org-imenu-markers nil
23738 "All markers currently used by Imenu.")
23739 (make-variable-buffer-local 'org-imenu-markers)
23741 (defun org-imenu-new-marker (&optional pos)
23742 "Return a new marker for use by Imenu, and remember the marker."
23743 (let ((m (make-marker)))
23744 (move-marker m (or pos (point)))
23745 (push m org-imenu-markers)
23748 (defun org-imenu-get-tree ()
23749 "Produce the index for Imenu."
23750 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23751 (setq org-imenu-markers nil)
23752 (let* ((n org-imenu-depth)
23753 (re (concat "^" (org-get-limited-outline-regexp)))
23754 (subs (make-vector (1+ n) nil))
23755 (last-level 0)
23756 m level head0 head)
23757 (save-excursion
23758 (save-restriction
23759 (widen)
23760 (goto-char (point-max))
23761 (while (re-search-backward re nil t)
23762 (setq level (org-reduced-level (funcall outline-level)))
23763 (when (and (<= level n)
23764 (looking-at org-complex-heading-regexp)
23765 (setq head0 (org-match-string-no-properties 4)))
23766 (setq head (org-link-display-format head0)
23767 m (org-imenu-new-marker))
23768 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23769 (if (>= level last-level)
23770 (push (cons head m) (aref subs level))
23771 (push (cons head (aref subs (1+ level))) (aref subs level))
23772 (loop for i from (1+ level) to n do (aset subs i nil)))
23773 (setq last-level level)))))
23774 (aref subs 1)))
23776 (eval-after-load "imenu"
23777 '(progn
23778 (add-hook 'imenu-after-jump-hook
23779 (lambda ()
23780 (if (derived-mode-p 'org-mode)
23781 (org-show-context 'org-goto))))))
23783 (defun org-link-display-format (link)
23784 "Replace a link with its the description.
23785 If there is no description, use the link target."
23786 (save-match-data
23787 (if (string-match org-bracket-link-analytic-regexp link)
23788 (replace-match (if (match-end 5)
23789 (match-string 5 link)
23790 (concat (match-string 1 link)
23791 (match-string 3 link)))
23792 nil t link)
23793 link)))
23795 (defun org-toggle-link-display ()
23796 "Toggle the literal or descriptive display of links."
23797 (interactive)
23798 (if org-descriptive-links
23799 (progn (org-remove-from-invisibility-spec '(org-link))
23800 (org-restart-font-lock)
23801 (setq org-descriptive-links nil))
23802 (progn (add-to-invisibility-spec '(org-link))
23803 (org-restart-font-lock)
23804 (setq org-descriptive-links t))))
23806 ;; Speedbar support
23808 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23809 "Overlay marking the agenda restriction line in speedbar.")
23810 (overlay-put org-speedbar-restriction-lock-overlay
23811 'face 'org-agenda-restriction-lock)
23812 (overlay-put org-speedbar-restriction-lock-overlay
23813 'help-echo "Agendas are currently limited to this item.")
23814 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23816 (defun org-speedbar-set-agenda-restriction ()
23817 "Restrict future agenda commands to the location at point in speedbar.
23818 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23819 (interactive)
23820 (require 'org-agenda)
23821 (let (p m tp np dir txt)
23822 (cond
23823 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23824 'org-imenu t))
23825 (setq m (get-text-property p 'org-imenu-marker))
23826 (with-current-buffer (marker-buffer m)
23827 (goto-char m)
23828 (org-agenda-set-restriction-lock 'subtree)))
23829 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23830 'speedbar-function 'speedbar-find-file))
23831 (setq tp (previous-single-property-change
23832 (1+ p) 'speedbar-function)
23833 np (next-single-property-change
23834 tp 'speedbar-function)
23835 dir (speedbar-line-directory)
23836 txt (buffer-substring-no-properties (or tp (point-min))
23837 (or np (point-max))))
23838 (with-current-buffer (find-file-noselect
23839 (let ((default-directory dir))
23840 (expand-file-name txt)))
23841 (unless (derived-mode-p 'org-mode)
23842 (user-error "Cannot restrict to non-Org-mode file"))
23843 (org-agenda-set-restriction-lock 'file)))
23844 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23845 (move-overlay org-speedbar-restriction-lock-overlay
23846 (point-at-bol) (point-at-eol))
23847 (setq current-prefix-arg nil)
23848 (org-agenda-maybe-redo)))
23850 (defvar speedbar-file-key-map)
23851 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23852 (eval-after-load "speedbar"
23853 '(progn
23854 (speedbar-add-supported-extension ".org")
23855 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23856 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23857 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23858 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23859 (add-hook 'speedbar-visiting-tag-hook
23860 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23862 ;;; Fixes and Hacks for problems with other packages
23864 ;; Make flyspell not check words in links, to not mess up our keymap
23865 (defvar org-element-affiliated-keywords) ; From org-element.el
23866 (defvar org-element-block-name-alist) ; From org-element.el
23867 (defun org-mode-flyspell-verify ()
23868 "Don't let flyspell put overlays at active buttons, or on
23869 {todo,all-time,additional-option-like}-keywords."
23870 (require 'org-element) ; For `org-element-affiliated-keywords'
23871 (let ((pos (max (1- (point)) (point-min)))
23872 (word (thing-at-point 'word)))
23873 (and (not (get-text-property pos 'keymap))
23874 (not (get-text-property pos 'org-no-flyspell))
23875 (not (member word org-todo-keywords-1))
23876 (not (member word org-all-time-keywords))
23877 (not (member word org-options-keywords))
23878 (not (member word (mapcar 'car org-startup-options)))
23879 (not (member-ignore-case word org-element-affiliated-keywords))
23880 (not (member-ignore-case word (org-get-export-keywords)))
23881 (not (member-ignore-case
23882 word (mapcar 'car org-element-block-name-alist)))
23883 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23884 (not (org-in-src-block-p)))))
23886 (defun org-remove-flyspell-overlays-in (beg end)
23887 "Remove flyspell overlays in region."
23888 (and (org-bound-and-true-p flyspell-mode)
23889 (fboundp 'flyspell-delete-region-overlays)
23890 (flyspell-delete-region-overlays beg end))
23891 (add-text-properties beg end '(org-no-flyspell t)))
23893 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23894 (eval-after-load "bookmark"
23895 '(if (boundp 'bookmark-after-jump-hook)
23896 ;; We can use the hook
23897 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23898 ;; Hook not available, use advice
23899 (defadvice bookmark-jump (after org-make-visible activate)
23900 "Make the position visible."
23901 (org-bookmark-jump-unhide))))
23903 ;; Make sure saveplace shows the location if it was hidden
23904 (eval-after-load "saveplace"
23905 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23906 "Make the position visible."
23907 (org-bookmark-jump-unhide)))
23909 ;; Make sure ecb shows the location if it was hidden
23910 (eval-after-load "ecb"
23911 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23912 "Make hierarchy visible when jumping into location from ECB tree buffer."
23913 (if (derived-mode-p 'org-mode)
23914 (org-show-context))))
23916 (defun org-bookmark-jump-unhide ()
23917 "Unhide the current position, to show the bookmark location."
23918 (and (derived-mode-p 'org-mode)
23919 (or (outline-invisible-p)
23920 (save-excursion (goto-char (max (point-min) (1- (point))))
23921 (outline-invisible-p)))
23922 (org-show-context 'bookmark-jump)))
23924 ;; Make session.el ignore our circular variable
23925 (defvar session-globals-exclude)
23926 (eval-after-load "session"
23927 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23929 ;;;; Finish up
23931 (provide 'org)
23933 (run-hooks 'org-load-hook)
23935 ;;; org.el ends here